3 namespace Drupal\Component\Serialization;
5 use Drupal\Component\Serialization\Exception\InvalidDataTypeException;
8 * Provides default serialization for YAML using the PECL extension.
10 class YamlPecl implements SerializationInterface {
15 public static function encode($data) {
18 ini_set('yaml.output_indent', 2);
19 // Do not break lines at 80 characters.
20 ini_set('yaml.output_width', -1);
23 return yaml_emit($data, YAML_UTF8_ENCODING, YAML_LN_BREAK);
29 public static function decode($raw) {
32 // Decode binary, since Symfony YAML parser encodes binary from 3.1
34 ini_set('yaml.decode_binary', 1);
35 // We never want to unserialize !php/object.
36 ini_set('yaml.decode_php', 0);
39 // yaml_parse() will error with an empty value.
43 // @todo Use ErrorExceptions when https://drupal.org/node/1247666 is in.
44 // yaml_parse() will throw errors instead of raising an exception. Until
45 // such time as Drupal supports native PHP ErrorExceptions as the error
46 // handler, we need to temporarily set the error handler as ::errorHandler()
47 // and then restore it after decoding has occurred. This allows us to turn
48 // parsing errors into a throwable exception.
49 // @see Drupal\Component\Serialization\Exception\InvalidDataTypeException
50 // @see http://php.net/manual/en/class.errorexception.php
51 set_error_handler([__CLASS__, 'errorHandler']);
53 $data = yaml_parse($raw, 0, $ndocs, [
54 YAML_BOOL_TAG => '\Drupal\Component\Serialization\YamlPecl::applyBooleanCallbacks',
56 restore_error_handler();
61 * Handles errors for \Drupal\Component\Serialization\YamlPecl::decode().
63 * @param int $severity
64 * The severity level of the error.
65 * @param string $message
66 * The error message to display.
68 * @see \Drupal\Component\Serialization\YamlPecl::decode()
70 public static function errorHandler($severity, $message) {
71 restore_error_handler();
72 throw new InvalidDataTypeException($message, $severity);
78 public static function getFileExtension() {
83 * Applies callbacks after parsing to ignore 1.1 style booleans.
86 * Value from YAML file.
88 * Tag that triggered the callback.
90 * Scalar entity style flags.
93 * FALSE, false, TRUE and true are returned as booleans, everything else is
94 * returned as a string.
96 public static function applyBooleanCallbacks($value, $tag, $flags) {
97 // YAML 1.1 spec dictates that 'Y', 'N', 'y' and 'n' are booleans. But, we
98 // want the 1.2 behavior, so we only consider 'false', 'FALSE', 'true' and
99 // 'TRUE' as booleans.
100 if (!in_array(strtolower($value), ['false', 'true'], TRUE)) {
107 return $map[strtolower($value)];