From: Andrey Kutejko Date: Tue, 30 Apr 2019 08:57:25 +0000 (+0200) Subject: implement MapLike for ArrayAccess X-Git-Tag: 0.3.1 X-Git-Url: https://git.andy128k.dev/?a=commitdiff_plain;h=3a57b9cc3b43ac2485700dbc29859a128fee7e25;p=missing-tools.git implement MapLike for ArrayAccess --- diff --git a/src/maplike.php b/src/maplike.php index c092a00..2612e20 100644 --- a/src/maplike.php +++ b/src/maplike.php @@ -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; diff --git a/t/MapLikeTest.php b/t/MapLikeTest.php index 1320d35..feac822 100644 --- a/t/MapLikeTest.php +++ b/t/MapLikeTest.php @@ -1,21 +1,61 @@ 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()