Completed
Push — master ( a3ba2f...57d762 )
by Erin
02:00
created

InclusionMatcher::matchTraversable()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 10
rs 9.4285
1
<?php
2
3
namespace Peridot\Leo\Matcher;
4
5
use InvalidArgumentException;
6
use Peridot\Leo\Matcher\Template\ArrayTemplate;
7
use Peridot\Leo\Matcher\Template\TemplateInterface;
8
use Traversable;
9
10
/**
11
 * InclusionMatcher determines if an array or string includes the expected value.
12
 *
13
 * @package Peridot\Leo\Matcher
14
 */
15
class InclusionMatcher extends AbstractMatcher
16
{
17
    /**
18
     * Matches if an array or string contains the expected value.
19
     *
20
     * @param $actual
21
     * @return mixed
22
     * @throws InvalidArgumentException
23
     */
24
    protected function doMatch($actual)
25
    {
26
        if ($actual instanceof Traversable) {
27
            return $this->matchTraversable($actual);
28
        }
29
30
        if (is_array($actual)) {
31
            return array_search($this->expected, $actual, true) !== false;
32
        }
33
34
        if (is_string($actual)) {
35
            return strpos($actual, $this->expected) !== false;
36
        }
37
38
        throw new InvalidArgumentException('Inclusion matcher requires a string or array');
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     *
44
     * @return TemplateInterface
45
     */
46
    public function getDefaultTemplate()
47
    {
48
        return new ArrayTemplate([
49
            'default' => 'Expected {{actual}} to include {{expected}}',
50
            'negated' => 'Expected {{actual}} to not include {{expected}}',
51
        ]);
52
    }
53
54
    private function matchTraversable(Traversable $actual)
55
    {
56
        foreach ($actual as $value) {
57
            if ($value === $this->expected) {
58
                return true;
59
            }
60
        }
61
62
        return false;
63
    }
64
}
65