Skip to content

Commit

Permalink
Merge pull request #10614 from cakephp/3.next-hash-extract
Browse files Browse the repository at this point in the history
Fix Hash::extract() to not array cast objects unnecessarily.
  • Loading branch information
dereuromark committed May 14, 2017
2 parents 9c78e0b + 1c3de4a commit 0c5c24c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/Utility/Hash.php
Expand Up @@ -135,7 +135,12 @@ public static function extract($data, $path)

// Simple paths.
if (!preg_match('/[{\[]/', $path)) {
return (array)static::get($data, $path);
$data = static::get($data, $path);
if ($data !== null && !(is_array($data) || $data instanceof ArrayAccess)) {
return [$data];
}

return $data !== null ? (array)$data : [];
}

if (strpos($path, '[') === false) {
Expand Down
27 changes: 27 additions & 0 deletions tests/TestCase/Utility/HashTest.php
Expand Up @@ -15,6 +15,7 @@
namespace Cake\Test\TestCase\Utility;

use ArrayObject;
use Cake\I18n\Time;
use Cake\ORM\Entity;
use Cake\TestSuite\TestCase;
use Cake\Utility\Hash;
Expand Down Expand Up @@ -1488,6 +1489,32 @@ public function testExtractUnevenKeys()
$this->assertEquals($expected, Hash::extract($data, 'Level1.Level2bis'));
}

/**
* Tests that objects as values handled correctly.
*
* @return void
*/
public function testExtractObjects()
{
$data = [
'root' => [
'array' => new ArrayObject([
'foo' => 'bar',
]),
'created' => new Time('2010-01-05'),
],
];

$result = Hash::extract($data, 'root.created');
$this->assertSame([$data['root']['created']], $result);

$result = Hash::extract($data, 'root.array');
$this->assertSame(['foo' => 'bar'], $result);

$result = Hash::extract($data, 'root.array.foo');
$this->assertSame(['bar'], $result);
}

/**
* testSort method
*
Expand Down

0 comments on commit 0c5c24c

Please sign in to comment.