Passed
Branch master (ecaff5)
by Joao
02:24
created

Scripts::migrate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Builder;
4
5
use ByJG\Config\Exception\ConfigNotFoundException;
6
use ByJG\Config\Exception\EnvironmentException;
7
use ByJG\Config\Exception\KeyNotFoundException;
8
use ByJG\DbMigration\Database\MySqlDatabase;
9
use ByJG\DbMigration\Exception\InvalidMigrationFile;
10
use ByJG\DbMigration\Migration;
11
use ByJG\Util\Uri;
12
use Composer\Script\Event;
13
use Exception;
14
use Psr\SimpleCache\InvalidArgumentException;
15
use ReflectionException;
16
17
class Scripts extends _Lib
18
{
19
    public function __construct()
20
    {
21
        parent::__construct();
22
    }
23
24
    /**
25
     * @param Event $event
26
     * @throws ConfigNotFoundException
27
     * @throws EnvironmentException
28
     * @throws InvalidArgumentException
29
     * @throws InvalidMigrationFile
30
     * @throws KeyNotFoundException
31
     * @throws ReflectionException
32
     */
33
    public static function migrate(Event $event)
34
    {
35
        $migrate = new Scripts();
36
        $migrate->runMigrate($event->getArguments());
37
    }
38
39
    /**
40
     * @param Event $event
41
     * @throws ConfigNotFoundException
42
     * @throws EnvironmentException
43
     * @throws InvalidArgumentException
44
     * @throws KeyNotFoundException
45
     * @throws ReflectionException
46
     */
47
    public static function genRestDocs(Event $event)
48
    {
49
        $build = new Scripts();
50
        $build->runGenRestDocs($event->getArguments());
51
    }
52
53
    /**
54
     * @param $arguments
55
     * @throws ConfigNotFoundException
56
     * @throws EnvironmentException
57
     * @throws InvalidArgumentException
58
     * @throws InvalidMigrationFile
59
     * @throws KeyNotFoundException
60
     * @throws ReflectionException
61
     */
62
    public function runMigrate($arguments)
63
    {
64
        $argumentList = $this->extractArguments($arguments);
65
        if (isset($argumentList["command"])) {
66
            echo "> Command: ${argumentList["command"]} \n";
67
        }
68
69
        $dbConnection = Psr11::container($argumentList["--env"])->get('DBDRIVER_CONNECTION');
70
71
        $migration = new Migration(new Uri($dbConnection), $this->workdir . "/db");
72
        $migration->registerDatabase("mysql", MySqlDatabase::class);
73
        $migration->addCallbackProgress(function ($cmd, $version) {
74
            echo "Doing $cmd, $version\n";
75
        });
76
77
        $exec['reset'] = function () use ($migration, $argumentList) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
$exec was never initialized. Although not strictly required by PHP, it is generally a good practice to add $exec = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
78
            if (!$argumentList["--yes"]) {
79
                throw new Exception("Reset require the argument --yes");
80
            }
81
            $migration->prepareEnvironment();
82
            $migration->reset();
83
        };
84
85
86
        $exec["update"] = function () use ($migration, $argumentList) {
87
            $migration->update($argumentList["--up-to"], $argumentList["--force"]);
88
        };
89
90
        $exec["version"] = function () use ($migration, $argumentList) {
91
            foreach ($migration->getCurrentVersion() as $key => $value) {
92
                echo "$key: $value\n";
93
            }
94
        };
95
96
        $exec[$argumentList['command']]();
97
    }
98
99
    /**
100
     * @param $arguments
101
     * @param bool $hasCmd
102
     * @return array
103
     */
104
    protected function extractArguments($arguments, $hasCmd = true) {
105
        $ret = [
106
            '--up-to' => null,
107
            '--yes' => null,
108
            '--force' => false,
109
            '--env' => null
110
        ];
111
112
        $start = 0;
113
        if ($hasCmd) {
114
            $ret['command'] = isset($arguments[0]) ? $arguments[0] : null;
115
            $start = 1;
116
        }
117
118
        for ($i=$start; $i < count($arguments); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
119
            $args = explode("=", $arguments[$i]);
120
            $ret[$args[0]] = isset($args[1]) ? $args[1] : true;
121
        }
122
123
        return $ret;
124
    }
125
126
    /**
127
     * @param $arguments
128
     * @throws ConfigNotFoundException
129
     * @throws EnvironmentException
130
     * @throws InvalidArgumentException
131
     * @throws KeyNotFoundException
132
     * @throws ReflectionException
133
     */
134
    public function runGenRestDocs($arguments)
135
    {
136
        $docPath = $this->workdir . '/web/docs/';
137
        chdir($this->workdir);
138
        $this->liveExecuteCommand(
139
            $this->fixDir("vendor/bin/swagger")
140
            . " --output \"$docPath\" "
141
            . "--exclude vendor "
142
            . "--exclude docker "
143
            . "--exclude fw "
144
            . "--processor OperationId"
145
        );
146
147
        $argumentList = $this->extractArguments($arguments, false);
148
149
        $docs = file_get_contents("$docPath/swagger.json");
150
        $docs = str_replace('__HOSTNAME__', Psr11::container($argumentList["--env"])->get('API_SERVER'), $docs);
151
        file_put_contents("$docPath/swagger.json", $docs);
152
    }
153
}
154