Skip to content

Commit

Permalink
Реализация метода фильтрации масива
Browse files Browse the repository at this point in the history
  • Loading branch information
petrgrishin committed Jun 1, 2014
1 parent 9c7ef83 commit f1171ac
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/ArrayAccess.php
Expand Up @@ -8,6 +8,7 @@

use PetrGrishin\ArrayAccess\Exception\ArrayAccessException;
use PetrGrishin\ArrayMap\ArrayMap;
use PetrGrishin\ArrayMap\Exception\ArrayMapException;

class ArrayAccess {
/** @var array */
Expand Down Expand Up @@ -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;
Expand All @@ -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;
}
}
18 changes: 18 additions & 0 deletions tests/unit/ArrayAccessTest.php
Expand Up @@ -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());
}
}

0 comments on commit f1171ac

Please sign in to comment.