Passed
Pull Request — master (#32)
by Viacheslav
10:49
created

GenJson   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 33
c 1
b 0
f 0
dl 0
loc 53
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A performAction() 0 27 4
A setUpDefinition() 0 12 1
1
<?php
2
3
namespace Swaggest\JsonCli;
4
5
use Swaggest\JsonCli\GenPhp\BuilderOptions;
6
use Swaggest\JsonSchema\Schema;
7
use Swaggest\JsonSchemaMaker\InstanceFaker;
8
use Swaggest\JsonSchemaMaker\Options;
9
use Yaoi\Command;
10
11
class GenJson extends Base
12
{
13
    public $maxNesting = 10;
14
    public $defaultAdditionalProperties;
15
    public $randSeed;
16
17
    use BuilderOptions;
18
19
    /**
20
     * @param Command\Definition $definition
21
     * @param \stdClass|static $options
22
     */
23
    public static function setUpDefinition(Command\Definition $definition, $options)
24
    {
25
        $definition->description = 'Generate JSON sample from JSON schema';
26
        Base::setupGenOptions($definition, $options);
27
        $options->maxNesting = Command\Option::create()->setType()
28
            ->setDescription('Max nesting level, default 10');
29
        $options->defaultAdditionalProperties = Command\Option::create()
30
            ->setDescription('Treat non-existent `additionalProperties` as `additionalProperties: true`');
31
        $options->randSeed = Command\Option::create()->setType()
32
            ->setDescription('Integer random seed for deterministic output');
33
        Base::setUpDefinition($definition, $options);
34
        Base::setupLoadFileOptions($options);
35
    }
36
37
    public function performAction()
38
    {
39
        if ($this->randSeed !== null) {
40
            mt_srand((int)$this->randSeed);
41
        }
42
43
        try {
44
            $skipRoot = false;
45
            $baseName = null;
46
            $schema = $this->loadSchema($skipRoot, $baseName);
47
48
            if (!$schema instanceof Schema) {
49
                $this->response->error('failed to assert Schema type, ' . get_class($schema) . ' received');
50
                throw new ExitCode('', 1);
51
            }
52
53
            $options = new Options;
54
            $options->maxNesting = $this->maxNesting;
55
            $options->defaultAdditionalProperties = $this->defaultAdditionalProperties;
56
            $instanceFaker = new InstanceFaker($schema, $options);
57
58
            $this->out = $instanceFaker->makeValue();
59
60
            $this->postPerform();
61
        } catch (\Exception $e) {
62
            $this->response->error($e->getMessage());
63
            throw new ExitCode('', 1);
64
        }
65
    }
66
}