|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace sixlive\Laravel\JsonSchemaAssertions; |
|
4
|
|
|
|
|
5
|
|
|
use PHPUnit\Framework\Assert as PHPUnit; |
|
6
|
|
|
use sixlive\Laravel\JsonSchemaAssertions\Support\Str; |
|
7
|
|
|
use Swaggest\JsonSchema\InvalidValue; |
|
8
|
|
|
use Swaggest\JsonSchema\Schema; |
|
9
|
|
|
|
|
10
|
|
|
class SchemaAssertion |
|
11
|
|
|
{ |
|
12
|
|
|
protected $schema; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* @param array|string $schema |
|
16
|
|
|
*/ |
|
17
|
|
|
public function __construct($schema) |
|
18
|
|
|
{ |
|
19
|
|
|
if (is_array($schema)) { |
|
20
|
|
|
$schema = json_encode($schema); |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
if ($this->isJson($schema)) { |
|
24
|
|
|
$schema = json_decode($schema); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
if ($this->isFileFromConfigPath($schema)) { |
|
28
|
|
|
$schema = $this->mergeConfigPath($schema); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
$this->schema = Schema::import($schema); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* Assert JSON against the loaded schema. |
|
36
|
|
|
* |
|
37
|
|
|
* @param string $data |
|
38
|
|
|
* |
|
39
|
|
|
* @return void |
|
40
|
|
|
*/ |
|
41
|
|
|
public function assert(string $data) |
|
42
|
|
|
{ |
|
43
|
|
|
try { |
|
44
|
|
|
$this->schema->in(json_decode($data)); |
|
45
|
|
|
} catch (InvalidValue $e) { |
|
46
|
|
|
PHPUnit::fail($e->getMessage()); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
PHPUnit::assertTrue(true); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* Test if the schema is a JSON string. |
|
54
|
|
|
* |
|
55
|
|
|
* @param mixed $schema |
|
56
|
|
|
* |
|
57
|
|
|
* @return bool |
|
58
|
|
|
*/ |
|
59
|
|
|
private function isJson($schema) |
|
60
|
|
|
{ |
|
61
|
|
|
return is_string($schema) && Str::isJson($schema); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
/** |
|
65
|
|
|
* Test if the schema is being loaded from the config path. |
|
66
|
|
|
* |
|
67
|
|
|
* @param mixed $schema |
|
68
|
|
|
* |
|
69
|
|
|
* @return bool |
|
70
|
|
|
*/ |
|
71
|
|
|
private function isFileFromConfigPath($schema) |
|
72
|
|
|
{ |
|
73
|
|
|
return is_string($schema) |
|
74
|
|
|
&& file_exists($this->mergeConfigPath($schema)); |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
/** |
|
78
|
|
|
* Merge the provided path with the config path and file extension. |
|
79
|
|
|
* |
|
80
|
|
|
* @param string $schema |
|
81
|
|
|
* |
|
82
|
|
|
* @return string |
|
83
|
|
|
*/ |
|
84
|
|
|
private function mergeConfigPath($schema) |
|
85
|
|
|
{ |
|
86
|
|
|
return vsprintf('%s/%s.json', [ |
|
87
|
|
|
config('json-schema-assertions.schema_base_path'), |
|
88
|
|
|
$schema, |
|
89
|
|
|
]); |
|
90
|
|
|
} |
|
91
|
|
|
} |
|
92
|
|
|
|