ValidateSchema::performAction()   A
last analyzed

Complexity

Conditions 5
Paths 8

Size

Total Lines 27
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 11.7741

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 5
eloc 21
c 2
b 0
f 0
nc 8
nop 0
dl 0
loc 27
ccs 6
cts 17
cp 0.3529
crap 11.7741
rs 9.2728
1
<?php
2
3
namespace Swaggest\JsonCli;
4
5
use Swaggest\JsonSchema\InvalidValue;
6
use Swaggest\JsonSchema\Schema;
7
use Yaoi\Command;
8
9
class ValidateSchema extends Base
10
{
11
    public $schema;
12
    public $data;
13
14
    /**
15
     * @param Command\Definition $definition
16
     * @param \stdClass|static $options
17
     */
18 1
    static function setUpDefinition(Command\Definition $definition, $options)
19
    {
20 1
        $options->data = Command\Option::create()->setIsUnnamed()->setIsRequired()
21 1
            ->setDescription('Path to data (JSON/YAML)');
22 1
        $options->schema = Command\Option::create()->setIsUnnamed()
23 1
            ->setDescription('Path to schema, default JSON Schema');
24 1
    }
25
26
27 1
    /**
28
     * @throws ExitCode
29 1
     * @throws \Swaggest\JsonSchema\Exception
30 1
     */
31
    public function performAction()
32 1
    {
33
        if ($this->schema) {
34
            $schemaData = $this->readData($this->schema);
35
            try {
36
                $schema = Schema::import($schemaData);
37
            } catch (InvalidValue $e) {
38
                $this->response->error('Invalid schema');
39 1
                $this->response->addContent($e->getMessage());
40
                throw new ExitCode('', 1);
41
            } catch (\Exception $e) {
42
                $this->response->error('Failed to import schema:' . $e->getMessage());
43
                throw new ExitCode('', 1);
44
            }
45 1
        } else {
46
            $schema = Schema::schema();
47
        }
48 1
49 1
        $data = $this->readData($this->data);
50
51
        try {
52
            $schema->in($data);
53
            $this->response->success('Data is valid');
54
        } catch (InvalidValue $exception) {
55 1
            $this->response->error('Data is invalid');
56
            $this->response->addContent($exception->getMessage());
57
            throw new ExitCode('', 1);
58
        }
59
    }
60
}