Skip to content

Commit

Permalink
Simplify exists() method with tests and docs
Browse files Browse the repository at this point in the history
  • Loading branch information
bocharsky-bw committed Oct 13, 2015
1 parent d5d7252 commit 7b3a0b6
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 18 deletions.
11 changes: 4 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -405,17 +405,14 @@ $a->each(); // [0 => 0, 'key' => 0, 1 => 'a', 'value' => 'a']

### exists

A custom contains function where you can supply your own contains function as a closure.
The closure must take two parameters, a needle and an element it will be comparing.
A custom contains method where you can supply your own custom logic in any callable function.

``` php
$a = A::create(['a', 'b', 'c']);

$closure = function($needle, $element) {
return $needle === $element;
};

$a->exists($closure, 'a'); // true
$a->exists(function($key, $value) {
return 1 === $key and 'b' === $value;
}); // true
```

### export
Expand Down
9 changes: 4 additions & 5 deletions src/AbstractArray.php
Original file line number Diff line number Diff line change
Expand Up @@ -431,15 +431,14 @@ public function containsKey($key)
/**
* Find the given value in the array using a closure
*
* @param callable $callable
* @param mixed $needle
* @param callable $func
*
* @return bool Returns true if the given value is found, false otherwise
*/
public function exists(callable $callable, $needle)
public function exists(callable $func)
{
foreach ($this->elements as $el) {
if ($callable($needle, $el)) {
foreach ($this->elements as $key => $value) {
if ($func($key, $value)) {
return true;
}
}
Expand Down
10 changes: 4 additions & 6 deletions tests/AbstractArrayTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -203,16 +203,14 @@ public function testEach(array $array)
*/
public function testExists(array $array)
{
$key = 2;

$closure = function($needle, $element){
return $needle === $element;
$callable = function($key, $value) {
return 2 === $key and 'two' === $value;
};

$arrayzy = $this->createArrayzy($array);
$isContains = in_array($key, $array);
$isExists = isset($array[2]) && 'two' === $array[2];

$this->assertSame($isContains, $arrayzy->exists($closure, $key));
$this->assertSame($isExists, $arrayzy->exists($callable));
}

/**
Expand Down

0 comments on commit 7b3a0b6

Please sign in to comment.