YamlSymfony.php 1.29 KB
Newer Older
1 2 3 4 5 6 7
<?php

namespace Drupal\Component\Serialization;

use Drupal\Component\Serialization\Exception\InvalidDataTypeException;
use Symfony\Component\Yaml\Parser;
use Symfony\Component\Yaml\Dumper;
8
use Symfony\Component\Yaml\Yaml as SymfonyYaml;
9 10 11 12 13 14 15 16 17 18 19

/**
 * Default serialization for YAML using the Symfony component.
 */
class YamlSymfony implements SerializationInterface {

  /**
   * {@inheritdoc}
   */
  public static function encode($data) {
    try {
20 21
      // Set the indentation to 2 to match Drupal's coding standards.
      $yaml = new Dumper(2);
22
      return $yaml->dump($data, PHP_INT_MAX, 0, SymfonyYaml::DUMP_EXCEPTION_ON_INVALID_TYPE);
23 24 25 26 27 28 29 30 31 32 33 34 35 36
    }
    catch (\Exception $e) {
      throw new InvalidDataTypeException($e->getMessage(), $e->getCode(), $e);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function decode($raw) {
    try {
      $yaml = new Parser();
      // Make sure we have a single trailing newline. A very simple config like
      // 'foo: bar' with no newline will fail to parse otherwise.
37
      return $yaml->parse($raw, SymfonyYaml::PARSE_EXCEPTION_ON_INVALID_TYPE);
38 39 40 41 42 43 44 45 46 47 48 49 50 51
    }
    catch (\Exception $e) {
      throw new InvalidDataTypeException($e->getMessage(), $e->getCode(), $e);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getFileExtension() {
    return 'yml';
  }

}