Skip to content

Commit

Permalink
Fix string handling of Hash::remove() and Hash::_simpleOp('remove')
Browse files Browse the repository at this point in the history
Hash::remove() mishandles '0' in path strings.
Hash::_simpleOp('remove') causes a fatal error when data is a string.
  • Loading branch information
chinpei215 committed Aug 19, 2017
1 parent 727a0e4 commit ea5f05b
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/Utility/Hash.php
Expand Up @@ -365,7 +365,9 @@ protected static function _simpleOp($op, $data, $path, $values = null)
}
} elseif ($op === 'remove') {
if ($i === $last) {
unset($_list[$key]);
if (!is_string($_list)) {
unset($_list[$key]);
}

return $data;
}
Expand Down Expand Up @@ -414,7 +416,7 @@ public static function remove(array $data, $path)
if ($match && is_array($v)) {
if ($conditions) {
if (static::_matches($v, $conditions)) {
if ($nextPath) {
if ($nextPath !== '') {
$data[$k] = static::remove($v, $nextPath);
} else {
unset($data[$k]);
Expand All @@ -426,7 +428,7 @@ public static function remove(array $data, $path)
if (empty($data[$k])) {
unset($data[$k]);
}
} elseif ($match && empty($nextPath)) {
} elseif ($match && $nextPath === '') {
unset($data[$k]);
}
}
Expand Down
37 changes: 37 additions & 0 deletions tests/TestCase/Utility/HashTest.php
Expand Up @@ -2127,6 +2127,43 @@ public function testRemove()
$this->assertEquals($expected, $result);
$result = Hash::remove($array, '{n}.{n}.part');
$this->assertEquals($expected, $result);

$array = [
'foo' => 'string',
];
$expected = $array;
$result = Hash::remove($array, 'foo.bar');
$this->assertEquals($expected, $result);

$array = [
'foo' => 'string',
'bar' => [
0 => 'a',
1 => 'b',
],
];
$expected = [
'foo' => 'string',
'bar' => [
1 => 'b',
],
];
$result = Hash::remove($array, '{s}.0');
$this->assertEquals($expected, $result);

$array = [
'foo' => [
0 => 'a',
1 => 'b',
],
];
$expected = [
'foo' => [
1 => 'b',
],
];
$result = Hash::remove($array, 'foo[1=b].0');
$this->assertEquals($expected, $result);
}

/**
Expand Down

0 comments on commit ea5f05b

Please sign in to comment.