From f1171acfb6d965ed2703e0ec2285f115b4d8e40f Mon Sep 17 00:00:00 2001 From: Petr Grishin Date: Sun, 1 Jun 2014 13:24:41 +0400 Subject: [PATCH] =?UTF-8?q?=D0=A0=D0=B5=D0=B0=D0=BB=D0=B8=D0=B7=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D1=8F=20=D0=BC=D0=B5=D1=82=D0=BE=D0=B4=D0=B0=20=20?= =?UTF-8?q?=D1=84=D0=B8=D0=BB=D1=8C=D1=82=D1=80=D0=B0=D1=86=D0=B8=D0=B8=20?= =?UTF-8?q?=D0=BC=D0=B0=D1=81=D0=B8=D0=B2=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ArrayAccess.php | 16 ++++++++++++++-- tests/unit/ArrayAccessTest.php | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/ArrayAccess.php b/src/ArrayAccess.php index 0d1f975..d856aab 100644 --- a/src/ArrayAccess.php +++ b/src/ArrayAccess.php @@ -8,6 +8,7 @@ use PetrGrishin\ArrayAccess\Exception\ArrayAccessException; use PetrGrishin\ArrayMap\ArrayMap; +use PetrGrishin\ArrayMap\Exception\ArrayMapException; class ArrayAccess { /** @var array */ @@ -150,7 +151,7 @@ public function map($callback) { $this->data = ArrayMap::create($this->data) ->map($callback) ->getArray(); - } catch (\PetrGrishin\ArrayMap\Exception\ArrayMapException $e) { + } catch (ArrayMapException $e) { throw new ArrayAccessException(sprintf('Error when mapping: %s', $e->getMessage()), null, $e); } return $this; @@ -161,9 +162,20 @@ public function mergeWith(array $data, $recursive = true) { $this->data = ArrayMap::create($this->data) ->mergeWith($data, $recursive) ->getArray(); - } catch (\PetrGrishin\ArrayMap\Exception\ArrayMapException $e) { + } catch (ArrayMapException $e) { throw new ArrayAccessException(sprintf('Error when merge: %s', $e->getMessage()), null, $e); } return $this; } + + public function filter($callback) { + try { + $this->data = ArrayMap::create($this->data) + ->filter($callback) + ->getArray(); + } catch (ArrayMapException $e) { + throw new ArrayAccessException(sprintf('Error when filter: %s', $e->getMessage()), null, $e); + } + return $this; + } } diff --git a/tests/unit/ArrayAccessTest.php b/tests/unit/ArrayAccessTest.php index 3abac04..d57fac8 100644 --- a/tests/unit/ArrayAccessTest.php +++ b/tests/unit/ArrayAccessTest.php @@ -189,4 +189,22 @@ public function testRecursiveMergeWith() { $instance->mergeWith(array('a' => array(2), 'd', 'e')); $this->assertEquals(array('a' => array(1, 2), 'b', 'c', 'd', 'e'), $instance->getArray()); } + + public function testFiltering() { + $original = array('a' => 1, 'b' => 2, 'c' => 3); + $instance = ArrayAccess::create($original); + $instance->filter(function ($value) { + return $value > 2; + }); + $this->assertEquals(array('c' => 3), $instance->getArray()); + } + + public function testFilteringUseKeys() { + $original = array('a' => 1, 'b' => 2, 'c' => 3); + $instance = ArrayAccess::create($original); + $instance->filter(function ($value, $key) { + return $key === 'c'; + }); + $this->assertEquals(array('c' => 3), $instance->getArray()); + } }