Completed
Push — master ( ed1c4a...aa1cbe )
by TJ
05:33
created

SchemaAssertion::__construct()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 0
cts 13
cp 0
rs 9.7333
c 0
b 0
f 0
cc 4
nc 8
nop 1
crap 20
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
    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