Completed
Push — master ( 814431...bcdc84 )
by Viacheslav
10:46 queued 15s
created

LoadFile::loadFile()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 15
nc 4
nop 0
dl 0
loc 24
rs 9.2222
c 1
b 0
f 0
1
<?php
2
3
namespace Swaggest\JsonCli\Json;
4
5
use Swaggest\JsonCli\Base;
6
use Swaggest\JsonCli\ExitCode;
7
use Swaggest\JsonDiff\Exception;
8
use Swaggest\JsonDiff\JsonMergePatch;
9
use Swaggest\JsonDiff\JsonPatch;
10
use Yaoi\Command\Option;
11
12
trait LoadFile
13
{
14
    /** @var string[] */
15
    public $patches = [];
16
17
    /**
18
     * @param \stdClass|static $options
19
     */
20
    public static function setupLoadFileOptions($options)
21
    {
22
        $options->patches = Option::create()->setType()->setIsVariadic()
0 ignored issues
show
Documentation Bug introduced by
It seems like Yaoi\Command\Option::cre...es are also supported') of type Yaoi\Command\Option is incompatible with the declared type string[] of property $patches.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
23
            ->setDescription('JSON patches to apply to schema file before processing, merge patches are also supported');
24
25
    }
26
27
    protected function loadFile()
28
    {
29
        $dataValue = Base::readJsonOrYaml($this->schema, $this->response);
30
        if (!$dataValue) {
31
            throw new ExitCode('Unable to find schema in ' . $this->schema, 1);
32
        }
33
34
        if (!empty($this->patches)) {
35
            foreach ($this->patches as $patchPath) {
36
                $patch = Base::readJsonOrYaml($patchPath, $this->response);
37
                if (is_array($patch)) {
38
                    $jp = JsonPatch::import($patch);
39
                    try {
40
                        $jp->apply($dataValue);
41
                    } catch (Exception $e) {
42
                        throw new ExitCode($e->getMessage(), 1);
43
                    }
44
                } else {
45
                    JsonMergePatch::apply($dataValue, $patch);
46
                }
47
            }
48
        }
49
50
        return $dataValue;
51
    }
52
}