Skip to content

Commit f1171ac

Browse files
committed
Реализация метода фильтрации масива
1 parent 9c7ef83 commit f1171ac

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/ArrayAccess.php

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
use PetrGrishin\ArrayAccess\Exception\ArrayAccessException;
1010
use PetrGrishin\ArrayMap\ArrayMap;
11+
use PetrGrishin\ArrayMap\Exception\ArrayMapException;
1112

1213
class ArrayAccess {
1314
/** @var array */
@@ -150,7 +151,7 @@ public function map($callback) {
150151
$this->data = ArrayMap::create($this->data)
151152
->map($callback)
152153
->getArray();
153-
} catch (\PetrGrishin\ArrayMap\Exception\ArrayMapException $e) {
154+
} catch (ArrayMapException $e) {
154155
throw new ArrayAccessException(sprintf('Error when mapping: %s', $e->getMessage()), null, $e);
155156
}
156157
return $this;
@@ -161,9 +162,20 @@ public function mergeWith(array $data, $recursive = true) {
161162
$this->data = ArrayMap::create($this->data)
162163
->mergeWith($data, $recursive)
163164
->getArray();
164-
} catch (\PetrGrishin\ArrayMap\Exception\ArrayMapException $e) {
165+
} catch (ArrayMapException $e) {
165166
throw new ArrayAccessException(sprintf('Error when merge: %s', $e->getMessage()), null, $e);
166167
}
167168
return $this;
168169
}
170+
171+
public function filter($callback) {
172+
try {
173+
$this->data = ArrayMap::create($this->data)
174+
->filter($callback)
175+
->getArray();
176+
} catch (ArrayMapException $e) {
177+
throw new ArrayAccessException(sprintf('Error when filter: %s', $e->getMessage()), null, $e);
178+
}
179+
return $this;
180+
}
169181
}

tests/unit/ArrayAccessTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,4 +189,22 @@ public function testRecursiveMergeWith() {
189189
$instance->mergeWith(array('a' => array(2), 'd', 'e'));
190190
$this->assertEquals(array('a' => array(1, 2), 'b', 'c', 'd', 'e'), $instance->getArray());
191191
}
192+
193+
public function testFiltering() {
194+
$original = array('a' => 1, 'b' => 2, 'c' => 3);
195+
$instance = ArrayAccess::create($original);
196+
$instance->filter(function ($value) {
197+
return $value > 2;
198+
});
199+
$this->assertEquals(array('c' => 3), $instance->getArray());
200+
}
201+
202+
public function testFilteringUseKeys() {
203+
$original = array('a' => 1, 'b' => 2, 'c' => 3);
204+
$instance = ArrayAccess::create($original);
205+
$instance->filter(function ($value, $key) {
206+
return $key === 'c';
207+
});
208+
$this->assertEquals(array('c' => 3), $instance->getArray());
209+
}
192210
}

0 commit comments

Comments
 (0)