-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIsJSON.php
61 lines (49 loc) · 1.14 KB
/
IsJSON.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
declare(strict_types=1);
namespace PHPUnitExtraConstraints\Constraint;
use PHPUnit\Framework\Constraint\Constraint;
use function is_string;
use function json_decode;
use function json_last_error;
use function json_last_error_msg;
use const JSON_ERROR_NONE;
/**
* Constraint that asserts that the value is a decodable JSON string.
*/
final class IsJSON extends Constraint
{
/**
* @inheritDoc
*/
protected function matches($other): bool
{
return is_string($other) && $this->isValidJson($other);
}
/**
* @psalm-suppress UnusedFunctionCall
*/
private function isValidJson(string $value): bool
{
json_decode($value);
return json_last_error() === JSON_ERROR_NONE;
}
/**
* @inheritDoc
* @psalm-suppress UnusedFunctionCall
*/
protected function additionalFailureDescription($other): string
{
if (!is_string($other)) {
return '';
}
json_decode($other);
return json_last_error_msg();
}
/**
* @inheritDoc
*/
public function toString(): string
{
return 'is a JSON string';
}
}