Browse Source

Allow using Hash::get() with objects implementing ArrayAccess

ADmad 10 years ago
parent
commit
514f2d239d
2 changed files with 24 additions and 2 deletions
  1. 2 2
      src/Utility/Hash.php
  2. 22 0
      tests/TestCase/Utility/HashTest.php

+ 2 - 2
src/Utility/Hash.php

@@ -35,7 +35,7 @@ class Hash
      * Does not support the full dot notation feature set,
      * but is faster for simple read operations.
      *
-     * @param array $data Array of data to operate on.
+     * @param array|\ArrayAccess $data Array of data to operate on.
      * @param string|array $path The path being searched for. Either a dot
      *   separated string, or an array of path segments.
      * @param mixed $default The return value when the path does not exist
@@ -43,7 +43,7 @@ class Hash
      * @return mixed The value fetched from the array, or null.
      * @link http://book.cakephp.org/3.0/en/core-libraries/hash.html#Hash::get
      */
-    public static function get(array $data, $path, $default = null)
+    public static function get($data, $path, $default = null)
     {
         if (empty($data) || $path === null || $path === '') {
             return $default;

+ 22 - 0
tests/TestCase/Utility/HashTest.php

@@ -14,6 +14,7 @@
  */
 namespace Cake\Test\TestCase\Utility;
 
+use ArrayObject;
 use Cake\TestSuite\TestCase;
 use Cake\Utility\Hash;
 
@@ -234,6 +235,27 @@ class HashTest extends TestCase
 
         $result = Hash::get($data, ['1', 'Article']);
         $this->assertEquals($data[1]['Article'], $result);
+
+        // Object which implements ArrayAccess
+        $nested = new ArrayObject([
+            'user' => 'bar'
+        ]);
+        $data = new ArrayObject([
+            'name' => 'foo',
+            'associated' => $nested
+        ]);
+
+        $return = Hash::get($data, 'name');
+        $this->assertEquals('foo', $return);
+
+        $return = Hash::get($data, 'associated');
+        $this->assertEquals($nested, $return);
+
+        $return = Hash::get($data, 'associated.user');
+        $this->assertEquals('bar', $return);
+
+        $return = Hash::get($data, 'non-existent');
+        $this->assertNull($return);
     }
 
     /**