Completed
Pull Request — master (#76)
by Luke
02:26
created

IsContainer::fold()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
nc 1
dl 0
loc 1
ccs 0
cts 0
cp 0
c 0
b 0
f 0
1
<?php
2
/**
3
 * Nozavroni/Collections
4
 * Just another collections library for PHP5.6+.
5
 * @version   {version}
6
 * @copyright Copyright (c) 2017 Luke Visinoni <[email protected]>
7
 * @author    Luke Visinoni <[email protected]>
8
 * @license   https://github.com/deni-zen/csvelte/blob/master/LICENSE The MIT License (MIT)
9
 */
10
11
namespace Noz\Traits;
12
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
}