From 3a57b9cc3b43ac2485700dbc29859a128fee7e25 Mon Sep 17 00:00:00 2001 From: Andrey Kutejko Date: Tue, 30 Apr 2019 10:57:25 +0200 Subject: [PATCH] implement MapLike for ArrayAccess --- src/maplike.php | 6 ++++++ t/MapLikeTest.php | 44 ++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 48 insertions(+), 2 deletions(-) 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() -- 2.49.0