function YamlTest::testEnums
Same name and namespace in other branches
- main core/tests/Drupal/Tests/Component/Serialization/YamlTest.php \Drupal\Tests\Component\Serialization\YamlTest::testEnums()
Tests that enums can be encoded and parsed.
File
-
core/
tests/ Drupal/ Tests/ Component/ Serialization/ YamlTest.php, line 120
Class
- YamlTest
- Tests the Yaml serialization implementation.
Namespace
Drupal\Tests\Component\SerializationCode
public function testEnums() : void {
$data = [
'foo' => EnumValue::Yes,
'bar' => BackedEnumValue::Maybe,
];
$yaml = Yaml::encode($data);
$this->assertSame($yaml, <<<YAML
foo: !php/enum Drupal\\Tests\\Component\\Serialization\\EnumValue::Yes
bar: !php/enum Drupal\\Tests\\Component\\Serialization\\BackedEnumValue::Maybe
YAML);
// Test decoding of `!php/enum`-encoded enums.
$decoded = Yaml::decode($yaml);
$this->assertSame(EnumValue::Yes, $decoded['foo']);
$this->assertSame(BackedEnumValue::Maybe, $decoded['bar']);
// Test decoding of `!php/const`-encoded enums.
$yaml_alternative = <<<YAML
foo: !php/const Drupal\\Tests\\Component\\Serialization\\EnumValue::Yes
bar: !php/const Drupal\\Tests\\Component\\Serialization\\BackedEnumValue::Maybe
YAML;
$decoded = Yaml::decode($yaml_alternative);
$this->assertSame(EnumValue::Yes, $decoded['foo']);
$this->assertSame(BackedEnumValue::Maybe, $decoded['bar']);
// Test decoding of `!php/enum`-encoded arrow values.
$yaml_alternative = <<<YAML
bar: !php/enum Drupal\\Tests\\Component\\Serialization\\BackedEnumValue::Maybe->value
YAML;
$decoded = Yaml::decode($yaml_alternative);
$this->assertSame(BackedEnumValue::Maybe->value, $decoded['bar']);
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.