JsonEquals   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 21.74%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 20
c 1
b 0
f 0
dl 0
loc 47
ccs 5
cts 23
cp 0.2174
rs 10
wmc 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A getName() 0 3 1
A getParsedValue() 0 9 2
A decodeJson() 0 8 3
A matches() 0 14 3
1
<?php
2
/**
3
 * This file is part of Phiremock.
4
 *
5
 * Phiremock is free software: you can redistribute it and/or modify
6
 * it under the terms of the GNU Lesser General Public License as published by
7
 * the Free Software Foundation, either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * Phiremock is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with Phiremock.  If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
namespace Mcustiel\Phiremock\Domain\Condition\Matchers;
20
21
use Mcustiel\Phiremock\Common\Utils\ArraysHelper;
22
use Mcustiel\Phiremock\Domain\Condition\Json;
23
use Mcustiel\Phiremock\Domain\Condition\MatchersEnum;
24
25
class JsonEquals extends Matcher
26
{
27 6
    public function __construct(Json $string)
28
    {
29 6
        parent::__construct($string);
30 6
    }
31
32
    public function matches($value): bool
33
    {
34
        if (\is_string($value)) {
35
            $requestValue = $this->getParsedValue($value);
36
        } else {
37
            $requestValue = $value;
38
        }
39
        $configValue = $this->getCheckValue()->get();
40
41
        if (!\is_array($requestValue)) {
42
            return false;
43
        }
44
45
        return ArraysHelper::areRecursivelyEquals($requestValue, $configValue);
46
    }
47
48 6
    public function getName(): string
49
    {
50 6
        return MatchersEnum::SAME_JSON;
51
    }
52
53
    private function decodeJson(string $value): array
54
    {
55
        $decodedValue = json_decode($value, true);
56
        if (\JSON_ERROR_NONE !== json_last_error() || $decodedValue === null) {
57
            throw new \InvalidArgumentException('JSON parsing error: ' . json_last_error_msg());
58
        }
59
60
        return $decodedValue;
61
    }
62
63
    private function getParsedValue(string $value)
64
    {
65
        try {
66
            $requestValue = $this->decodeJson($value);
67
        } catch (\Throwable $e) {
68
            $requestValue = $value;
69
        }
70
71
        return $requestValue;
72
    }
73
}
74