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