4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Serializer\Encoder;
14 use Symfony\Component\Serializer\Exception\RuntimeException;
15 use Symfony\Component\Yaml\Dumper;
16 use Symfony\Component\Yaml\Parser;
21 * @author Kévin Dunglas <dunglas@gmail.com>
23 class YamlEncoder implements EncoderInterface, DecoderInterface
25 const FORMAT = 'yaml';
29 private $defaultContext = array('yaml_inline' => 0, 'yaml_indent' => 0, 'yaml_flags' => 0);
31 public function __construct(Dumper $dumper = null, Parser $parser = null, array $defaultContext = array())
33 if (!class_exists(Dumper::class)) {
34 throw new RuntimeException('The YamlEncoder class requires the "Yaml" component. Install "symfony/yaml" to use it.');
37 $this->dumper = $dumper ?: new Dumper();
38 $this->parser = $parser ?: new Parser();
39 $this->defaultContext = array_merge($this->defaultContext, $defaultContext);
45 public function encode($data, $format, array $context = array())
47 $context = array_merge($this->defaultContext, $context);
49 return $this->dumper->dump($data, $context['yaml_inline'], $context['yaml_indent'], $context['yaml_flags']);
55 public function supportsEncoding($format)
57 return self::FORMAT === $format;
63 public function decode($data, $format, array $context = array())
65 $context = array_merge($this->defaultContext, $context);
67 return $this->parser->parse($data, $context['yaml_flags']);
73 public function supportsDecoding($format)
75 return self::FORMAT === $format;