Completed
Push — master ( 49a1e7...c69450 )
by TJ
03:04
created

SchemaAssertion::isFileFromConfigPath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
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 5
    public function __construct($schema)
18
    {
19 5
        if (is_array($schema)) {
20 1
            $schema = json_encode($schema);
21
        }
22
23 5
        if ($this->isJson($schema)) {
24 3
            $schema = json_decode($schema);
25
        }
26
27 5
        if ($this->isFileFromConfigPath($schema)) {
28 1
            $schema = $this->mergeConfigPath($schema);
29
        }
30
31 5
        $this->schema = Schema::import($schema);
32 5
    }
33
34
    /**
35
     * Assert JSON against the loaded schema.
36
     *
37
     * @param  string  $data
38
     *
39
     * @return void
40
     */
41 5
    public function assert(string $data)
42
    {
43
        try {
44 5
            $this->schema->in(json_decode($data));
45 1
        } catch (InvalidValue $e) {
46 1
            PHPUnit::fail($e->getMessage());
47
        }
48
49 4
        PHPUnit::assertTrue(true);
50 4
    }
51
52
    /**
53
     * Test if the schema is a JSON string.
54
     *
55
     * @param  mixed  $schema
56
     *
57
     * @return bool
58
     */
59 5
    private function isJson($schema)
60
    {
61 5
        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 5
    private function isFileFromConfigPath($schema)
72
    {
73 5
        return is_string($schema)
74 5
            && 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 2
    private function mergeConfigPath($schema)
85
    {
86 2
        return vsprintf('%s/%s.json', [
87 2
            config('json-schema-assertions.schema_base_path'),
88 2
            $schema,
89
        ]);
90
    }
91
}
92