Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\Serializer\Encoder; Chris@0: Chris@14: use Symfony\Component\Serializer\Exception\RuntimeException; Chris@0: use Symfony\Component\Yaml\Dumper; Chris@0: use Symfony\Component\Yaml\Parser; Chris@0: Chris@0: /** Chris@0: * Encodes YAML data. Chris@0: * Chris@0: * @author Kévin Dunglas Chris@0: */ Chris@0: class YamlEncoder implements EncoderInterface, DecoderInterface Chris@0: { Chris@0: const FORMAT = 'yaml'; Chris@0: Chris@0: private $dumper; Chris@0: private $parser; Chris@17: private $defaultContext = ['yaml_inline' => 0, 'yaml_indent' => 0, 'yaml_flags' => 0]; Chris@0: Chris@17: public function __construct(Dumper $dumper = null, Parser $parser = null, array $defaultContext = []) Chris@0: { Chris@14: if (!class_exists(Dumper::class)) { Chris@14: throw new RuntimeException('The YamlEncoder class requires the "Yaml" component. Install "symfony/yaml" to use it.'); Chris@14: } Chris@14: Chris@0: $this->dumper = $dumper ?: new Dumper(); Chris@0: $this->parser = $parser ?: new Parser(); Chris@0: $this->defaultContext = array_merge($this->defaultContext, $defaultContext); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@17: public function encode($data, $format, array $context = []) Chris@0: { Chris@0: $context = array_merge($this->defaultContext, $context); Chris@0: Chris@0: return $this->dumper->dump($data, $context['yaml_inline'], $context['yaml_indent'], $context['yaml_flags']); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function supportsEncoding($format) Chris@0: { Chris@0: return self::FORMAT === $format; Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@17: public function decode($data, $format, array $context = []) Chris@0: { Chris@0: $context = array_merge($this->defaultContext, $context); Chris@0: Chris@0: return $this->parser->parse($data, $context['yaml_flags']); Chris@0: } Chris@0: Chris@0: /** Chris@0: * {@inheritdoc} Chris@0: */ Chris@0: public function supportsDecoding($format) Chris@0: { Chris@0: return self::FORMAT === $format; Chris@0: } Chris@0: }