3ac1af679a4a1a43f97a5ea0136ad681cc96fd7a
[yaffs-website] / vendor / symfony / serializer / Encoder / YamlEncoder.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\Serializer\Encoder;
13
14 use Symfony\Component\Serializer\Exception\RuntimeException;
15 use Symfony\Component\Yaml\Dumper;
16 use Symfony\Component\Yaml\Parser;
17
18 /**
19  * Encodes YAML data.
20  *
21  * @author Kévin Dunglas <dunglas@gmail.com>
22  */
23 class YamlEncoder implements EncoderInterface, DecoderInterface
24 {
25     const FORMAT = 'yaml';
26
27     private $dumper;
28     private $parser;
29     private $defaultContext = array('yaml_inline' => 0, 'yaml_indent' => 0, 'yaml_flags' => 0);
30
31     public function __construct(Dumper $dumper = null, Parser $parser = null, array $defaultContext = array())
32     {
33         if (!class_exists(Dumper::class)) {
34             throw new RuntimeException('The YamlEncoder class requires the "Yaml" component. Install "symfony/yaml" to use it.');
35         }
36
37         $this->dumper = $dumper ?: new Dumper();
38         $this->parser = $parser ?: new Parser();
39         $this->defaultContext = array_merge($this->defaultContext, $defaultContext);
40     }
41
42     /**
43      * {@inheritdoc}
44      */
45     public function encode($data, $format, array $context = array())
46     {
47         $context = array_merge($this->defaultContext, $context);
48
49         return $this->dumper->dump($data, $context['yaml_inline'], $context['yaml_indent'], $context['yaml_flags']);
50     }
51
52     /**
53      * {@inheritdoc}
54      */
55     public function supportsEncoding($format)
56     {
57         return self::FORMAT === $format;
58     }
59
60     /**
61      * {@inheritdoc}
62      */
63     public function decode($data, $format, array $context = array())
64     {
65         $context = array_merge($this->defaultContext, $context);
66
67         return $this->parser->parse($data, $context['yaml_flags']);
68     }
69
70     /**
71      * {@inheritdoc}
72      */
73     public function supportsDecoding($format)
74     {
75         return self::FORMAT === $format;
76     }
77 }