LengthMatcher   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 58
rs 10
c 1
b 0
f 1
wmc 7
lcom 1
cbo 2

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getDefaultTemplate() 0 9 1
A doMatch() 0 16 4
A isCountable() 0 4 2
1
<?php
2
3
namespace Peridot\Leo\Matcher;
4
5
use Countable;
6
use InvalidArgumentException;
7
use Peridot\Leo\Matcher\Template\ArrayTemplate;
8
use Peridot\Leo\Matcher\Template\TemplateInterface;
9
10
/**
11
 * LengthMatcher determines if an actual array, string, or Countable has a length equivalent
12
 * to the expected value.
13
 *
14
 * @package Peridot\Leo\Matcher
15
 */
16
class LengthMatcher extends AbstractMatcher
17
{
18
    /**
19
     * @var int
20
     */
21
    protected $count;
22
23
    /**
24
     * {@inheritdoc}
25
     *
26
     * @return TemplateInterface
27
     */
28
    public function getDefaultTemplate()
29
    {
30
        $template = new ArrayTemplate([
31
            'default' => 'Expected {{actual}} to have a length of {{expected}} but got {{count}}',
32
            'negated' => 'Expected {{actual}} to not have a length of {{expected}}',
33
        ]);
34
35
        return $template->setTemplateVars(['count' => $this->count]);
36
    }
37
38
    /**
39
     * Match the length of the countable interface or string against
40
     * the expected value.
41
     *
42
     * @param  string|array|Countable $actual
43
     * @return mixed
44
     */
45
    protected function doMatch($actual)
46
    {
47
        if ($this->isCountable($actual)) {
48
            $this->count = count($actual);
49
        }
50
51
        if (is_string($actual)) {
52
            $this->count = strlen($actual);
53
        }
54
55
        if (isset($this->count)) {
56
            return $this->expected === $this->count;
57
        }
58
59
        throw new InvalidArgumentException('Length matcher requires a string, array, or Countable');
60
    }
61
62
    /**
63
     * Determine if the native count() function can return a valid result
64
     * on the actual value.
65
     *
66
     * @param  mixed $actual
67
     * @return bool
68
     */
69
    protected function isCountable($actual)
70
    {
71
        return is_array($actual) || $actual instanceof Countable;
72
    }
73
}
74