Skip to content

Commit 71ef86e

Browse files
committed
bug symfony#15770 [Yaml] Fix the parsing of float keys (jmgq)
This PR was merged into the 2.3 branch. Discussion ---------- [Yaml] Fix the parsing of float keys | Q | A | ------------- | --- | Bug fix? | yes | New feature? | no | BC breaks? | no | Deprecations? | no | Tests pass? | yes | Fixed tickets | symfony#15667 | License | MIT | Doc PR | Before this fix, the parser was trying to set a float as an array key, and according to the [PHP documentation](http://php.net/manual/en/language.types.array.php) *"The key can either be an integer or a string"*. Therefore, PHP was internally casting the key to an integer. My first approach was to always cast to string, by changing this line: $key = Inline::parseScalar($values['key']); to $key = (string) Inline::parseScalar($values['key']); But that broke some tests, for instance, the parser is expected to transform the key `false` to `0`, but casting `false` to string results in an empty string, rather than `0`. Commits ------- 520bd26 [Yaml] Fix the parsing of float keys
2 parents e2156d7 + 520bd26 commit 71ef86e

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/Symfony/Component/Yaml/Parser.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,11 @@ public function parse($value, $exceptionOnInvalidType = false, $objectSupport =
133133
throw $e;
134134
}
135135

136+
// Convert float keys to strings, to avoid being converted to integers by PHP
137+
if (is_float($key)) {
138+
$key = (string) $key;
139+
}
140+
136141
if ('<<' === $key) {
137142
if (isset($values['value']) && 0 === strpos($values['value'], '*')) {
138143
$isInPlace = substr($values['value'], 1);

src/Symfony/Component/Yaml/Tests/ParserTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -685,6 +685,24 @@ public function testYamlDirective()
685685
EOF;
686686
$this->assertEquals(array('foo' => 1, 'bar' => 2), $this->parser->parse($yaml));
687687
}
688+
689+
public function testFloatKeys()
690+
{
691+
$yaml = <<<EOF
692+
foo:
693+
1.2: "bar"
694+
1.3: "baz"
695+
EOF;
696+
697+
$expected = array(
698+
'foo' => array(
699+
'1.2' => 'bar',
700+
'1.3' => 'baz',
701+
),
702+
);
703+
704+
$this->assertEquals($expected, $this->parser->parse($yaml));
705+
}
688706
}
689707

690708
class B

0 commit comments

Comments
 (0)