]> git.andy128k.dev Git - missing-tools.git/commitdiff
implement MapLike for ArrayAccess 0.3.1
authorAndrey Kutejko <andy128k@gmail.com>
Tue, 30 Apr 2019 08:57:25 +0000 (10:57 +0200)
committerAndrey Kutejko <andy128k@gmail.com>
Tue, 30 Apr 2019 08:57:25 +0000 (10:57 +0200)
src/maplike.php
t/MapLikeTest.php

index c092a00ccf552ab678b1529b2c7f356dea04eef5..2612e205671e7de4cb757cebfc8ef31f1c9ed78e 100644 (file)
@@ -12,6 +12,12 @@ final class MapLike
             } else {
                 return $default;
             }
+        } elseif ($mapLike instanceof \ArrayAccess) {
+            if ($mapLike->offsetExists($key)) {
+                return $mapLike->offsetGet($key);
+            } else {
+                return $default;
+            }
         } elseif (is_object($mapLike)) {
             try {
                 return $mapLike->$key;
index 1320d35b332b78feb56aa4448039c31ad58f1880..feac82227b271e456ffda216573b753964d6b7dd 100644 (file)
@@ -1,21 +1,61 @@
 <?php
 
+class TestArrayAccess implements ArrayAccess
+{
+    private $container = array();
+
+    public function __construct($data) {
+        $this->container = $data;
+    }
+
+    public function offsetSet($offset, $value) {
+        if (is_null($offset)) {
+            $this->container[] = $value;
+        } else {
+            $this->container[$offset] = $value;
+        }
+    }
+
+    public function offsetExists($offset) {
+        return array_key_exists($offset, $this->container);
+    }
+
+    public function offsetUnset($offset) {
+        unset($this->container[$offset]);
+    }
+
+    public function offsetGet($offset) {
+        return $this->container[$offset];
+    }
+}
+
 class MapLikeTest extends PHPUnit_Framework_TestCase
 {
     function testGetArray()
     {
-        $map = ['a' => '1', 'b' => 2];
+        $map = ['a' => '1', 'b' => 2, 'n' => null];
+
+        $this->assertEquals('1', \PFF\MapLike::get($map, 'a'));
+        $this->assertEquals(33, \PFF\MapLike::get($map, 'c', 33));
+        $this->assertEquals(null, \PFF\MapLike::get($map, 'n', 'not null'));
+    }
+
+    function testGetArrayAccess()
+    {
+        $map = new TestArrayAccess(['a' => '1', 'b' => 2, 'n' => null]);
 
         $this->assertEquals('1', \PFF\MapLike::get($map, 'a'));
         $this->assertEquals(33, \PFF\MapLike::get($map, 'c', 33));
+        $this->assertEquals(null, \PFF\MapLike::get($map, 'n', 'not null'));
     }
 
     function testGetObject()
     {
-        $map = (object)['a' => '1', 'b' => 2];
+        $map = (object)['a' => '1', 'b' => 2, 'n' => null];
 
         $this->assertEquals('1', \PFF\MapLike::get($map, 'a'));
         $this->assertEquals(33, \PFF\MapLike::get($map, 'c', 33));
+        $this->assertEquals(null, \PFF\MapLike::get($map, 'n', 'not null'));
     }
 
     function testGetUnsupported()