Skip to content

Commit

Permalink
Fix flattening in arrays starting with null
Browse files Browse the repository at this point in the history
Co-Authored-By: Albert Boada <albert.boada.flaquer@gmail.com>
  • Loading branch information
GrahamCampbell and Albert Boada committed Aug 25, 2023
1 parent f3734e2 commit bbb69a9
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,7 @@

## 2.7.0 - UPCOMING

* Fixed flattening in arrays starting with null
* Drop support for HHVM and PHP earlier than 7.2.5.
* Add support for PHP 8.1, 8.2, and 8.3.

Expand Down
2 changes: 1 addition & 1 deletion src/TreeCompiler.php
Expand Up @@ -305,7 +305,7 @@ private function visit_flatten(array $node)
->write('%s = [];', $merged)
->write('foreach ($value as %s) {', $val)
->indent()
->write('if (is_array(%s) && isset(%s[0])) {', $val, $val)
->write('if (is_array(%s) && array_key_exists(0, %s)) {', $val, $val)
->indent()
->write('%s = array_merge(%s, %s);', $merged, $merged, $val)
->outdent()
Expand Down
2 changes: 1 addition & 1 deletion src/TreeInterpreter.php
Expand Up @@ -107,7 +107,7 @@ private function dispatch(array $node, $value)
$merged = [];
foreach ($value as $values) {
// Only merge up arrays lists and not hashes
if (is_array($values) && isset($values[0])) {
if (is_array($values) && array_key_exists(0, $values)) {
$merged = array_merge($merged, $values);
} elseif ($values !== $skipElement) {
$merged[] = $values;
Expand Down
23 changes: 23 additions & 0 deletions tests/compliance/indices.json
Expand Up @@ -297,6 +297,29 @@
}
]
},
{
"given":
{
"foo": [
{"bar": [null, null, 3, 5, 6, null]},
{"bar": [1, 3, null, 5]}
]
},
"cases": [
{
"expression": "foo[*].bar",
"result": [[null, null, 3, 5, 6, null], [1, 3, null, 5]]
},
{
"expression": "foo[*].bar[*]",
"result": [[3, 5, 6], [1, 3, 5]]
},
{
"expression": "foo[*].bar[]",
"result": [3, 5, 6, 1, 3, 5]
}
]
},
{
"given": {
"string": "string",
Expand Down
11 changes: 11 additions & 0 deletions tests/compliance/wildcard.json
Expand Up @@ -456,5 +456,16 @@
"result": [0, 0]
}
]
},
{
"given": {
"foo": [null, 1, null, 2, null]
},
"cases": [
{
"expression": "foo[*]",
"result": [1, 2]
}
]
}
]

0 comments on commit bbb69a9

Please sign in to comment.