Completed
Push — master ( a787fa...dc9af5 )
by Vincent
05:35
created

LinkEqualsConstraint   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 81
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
eloc 25
c 1
b 0
f 0
dl 0
loc 81
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A toString() 0 5 1
A check() 0 3 1
B matches() 0 35 7
A __construct() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace VGirol\JsonApiAssert\Constraint;
6
7
use PHPUnit\Framework\Constraint\Constraint;
8
9
/**
10
 * A constraint class to assert that a link object equals an expected value.
11
 */
12
class LinkEqualsConstraint extends Constraint
13
{
14
    /**
15
     * @var string|null
16
     */
17
    private $expected;
18
19
    /**
20
     * Class constructor.
21
     *
22
     * @param string|null $expected
23
     */
24
    public function __construct($expected)
25
    {
26
        $this->expected = $expected;
27
    }
28
29
    /**
30
     * Returns a string representation of the constraint.
31
     */
32
    public function toString(): string
33
    {
34
        return \sprintf(
35
            'equals %s',
36
            $this->exporter()->export($this->expected)
37
        );
38
    }
39
40
    /**
41
     * Evaluates the constraint for parameter $other. Returns true if the
42
     * constraint is met, false otherwise.
43
     *
44
     * @param mixed $other value or object to evaluate
45
     */
46
    protected function matches($other): bool
47
    {
48
        if (is_null($this->expected)) {
49
            return \is_null($other);
50
        }
51
52
        if (is_null($other)) {
53
            return false;
54
        }
55
56
        $linkElms = explode('?', $other);
57
        $expectedElms = explode('?', $this->expected);
58
59
        if (count($expectedElms) != count($linkElms)) {
60
            return false;
61
        }
62
63
        if ($expectedElms[0] != $linkElms[0]) {
64
            return false;
65
        }
66
67
        if (count($linkElms) == 1) {
68
            return true;
69
        }
70
71
        $expectedQuery = explode('&', $expectedElms[1]);
72
        $linkQuery = explode('&', $linkElms[1]);
73
74
        if (count($expectedQuery) != count($linkQuery)) {
75
            return false;
76
        }
77
78
        $diff = array_diff($expectedQuery, $linkQuery);
79
80
        return count($diff) === 0;
81
    }
82
83
    /**
84
     * Evaluates the constraint for parameter $other. Returns true if the
85
     * constraint is met, false otherwise.
86
     *
87
     * @param mixed $other value or object to evaluate
88
     * @return boolean
89
     */
90
    public function check($other): bool
91
    {
92
        return $this->matches($other);
93
    }
94
}
95