JsonEquals::decodeJson()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 4
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 8
ccs 0
cts 5
cp 0
crap 12
rs 10
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