| 1 | <?php |
||
| 13 | trait IsContainer |
||
| 14 | { |
||
| 15 | |||
| 16 | /** |
||
| 17 | * Determine if this collection contains a value. |
||
| 18 | * |
||
| 19 | * Allows you to pass in a value or a callback function and optionally an index, |
||
| 20 | * and tells you whether or not this collection contains that value. |
||
| 21 | * If the $index param is specified, only that index will be looked under. |
||
| 22 | * |
||
| 23 | * @param mixed|callable $value The value to check for |
||
| 24 | * @param mixed $index The (optional) index to look under |
||
| 25 | * |
||
| 26 | * @return bool True if this collection contains $value |
||
| 27 | * |
||
| 28 | * @todo Maybe add $identical param for identical comparison (===) |
||
| 29 | * @todo Allow negative offset for second param |
||
| 30 | */ |
||
| 31 | public function contains($value, $index = null) |
||
| 32 | { |
||
| 33 | return (bool) $this->fold(function ($carry, $val, $key) use ($value, $index) { |
||
| 34 | if ($carry) { |
||
| 35 | return $carry; |
||
| 36 | } |
||
| 37 | if (is_callable($value)) { |
||
| 38 | $found = $value($val, $key); |
||
| 39 | } else { |
||
| 40 | $found = ($value == $val); |
||
| 41 | } |
||
| 42 | if ($found) { |
||
| 43 | if (is_null($index)) { |
||
| 44 | return true; |
||
| 45 | } |
||
| 46 | if (is_array($index)) { |
||
| 47 | return in_array($key, $index); |
||
| 48 | } |
||
| 49 | |||
| 50 | return $key == $index; |
||
| 51 | } |
||
| 52 | |||
| 53 | return false; |
||
| 54 | }); |
||
| 55 | } |
||
| 56 | |||
| 57 | abstract public function fold(callable $funk, $initial = null); |
||
| 58 | |||
| 59 | } |