Completed
Push — master ( 3ff958...7b3273 )
by Joao
04:38
created

Scripts::extractArguments()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 6
nop 1
dl 0
loc 15
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
namespace Builder;
4
5
use ByJG\DbMigration\Database\MySqlDatabase;
6
use ByJG\DbMigration\Migration;
7
use ByJG\Util\Uri;
8
use Composer\Script\Event;
9
10
class Scripts extends _Lib
11
{
12
    public function __construct()
13
    {
14
        parent::__construct();
15
    }
16
17
    /**
18
     * @throws \ByJG\Config\Exception\ConfigNotFoundException
19
     * @throws \ByJG\Config\Exception\EnvironmentException
20
     * @throws \ByJG\Config\Exception\KeyNotFoundException
21
     * @throws \Psr\SimpleCache\InvalidArgumentException
22
     */
23
    public static function build()
24
    {
25
        $build = new Scripts();
26
        $build->runBuild();
27
    }
28
29
    /**
30
     * @param \Composer\Script\Event $event
0 ignored issues
show
Bug introduced by
The type Composer\Script\Event was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
31
     * @throws \ByJG\Config\Exception\ConfigNotFoundException
32
     * @throws \ByJG\Config\Exception\EnvironmentException
33
     * @throws \ByJG\Config\Exception\KeyNotFoundException
34
     * @throws \ByJG\DbMigration\Exception\InvalidMigrationFile
35
     * @throws \Psr\SimpleCache\InvalidArgumentException
36
     */
37
    public static function migrate(Event $event)
38
    {
39
        $migrate = new Scripts();
40
        $migrate->runMigrate($event->getArguments());
41
    }
42
43
    /**
44
     * @throws \ByJG\Config\Exception\ConfigNotFoundException
45
     * @throws \ByJG\Config\Exception\EnvironmentException
46
     * @throws \ByJG\Config\Exception\KeyNotFoundException
47
     * @throws \Psr\SimpleCache\InvalidArgumentException
48
     */
49
    public static function genRestDocs()
50
    {
51
        $build = new Scripts();
52
        $build->runGenRestDocs();
53
    }
54
55
56
    /**
57
     * @throws \ByJG\Config\Exception\ConfigNotFoundException
58
     * @throws \ByJG\Config\Exception\EnvironmentException
59
     * @throws \ByJG\Config\Exception\KeyNotFoundException
60
     * @throws \Psr\SimpleCache\InvalidArgumentException
61
     */
62
    public function runBuild()
63
    {
64
        $dockerExtra = Psr11::container()->get('BUILDER_DOCKERFILE');
65
        if (!empty($dockerExtra)) {
66
            $dockerExtra = array_merge(
67
                [
68
                    '############################################################',
69
                    '##-- START CUSTOM',
70
                    'ENV APPLICATION_ENV=' . Psr11::environment()->getCurrentEnv()
71
                ],
72
                (array)$dockerExtra,
73
                [
74
                    '##-- END CUSTOM',
75
                    '############################################################',
76
                ]
77
            );
78
79
            $dockerFile = file_get_contents($this->workdir . '/docker/Dockerfile');
80
81
            file_put_contents(
82
                $this->workdir . '/Dockerfile',
83
                str_replace('##---ENV-SPECIFICS-HERE', implode("\n", $dockerExtra), $dockerFile)
84
            );
85
        }
86
87
        $beforeBuild = Psr11::container()->get('BUILDER_BEFORE_BUILD');
88
        $build = Psr11::container()->get('BUILDER_BUILD');
89
        $deployCommand = Psr11::container()->get('BUILDER_DEPLOY_COMMAND');
90
        $afterDeploy = Psr11::container()->get('BUILDER_AFTER_DEPLOY');
91
92
        // Before Build
93
        if (!empty($beforeBuild)) {
94
            $this->liveExecuteCommand($beforeBuild);
95
        }
96
97
        // Build
98
        if (!empty($build)) {
99
            $this->liveExecuteCommand($build);
100
        }
101
        // Deploy
102
        if (!empty($deployCommand)) {
103
            $this->liveExecuteCommand($deployCommand);
104
        }
105
        // After Deploy
106
        if (!empty($afterDeploy)) {
107
            $this->liveExecuteCommand($afterDeploy);
108
        }
109
    }
110
111
112
    /**
113
     * @param $arguments
114
     * @throws \ByJG\Config\Exception\ConfigNotFoundException
115
     * @throws \ByJG\Config\Exception\EnvironmentException
116
     * @throws \ByJG\Config\Exception\KeyNotFoundException
117
     * @throws \ByJG\DbMigration\Exception\InvalidMigrationFile
118
     * @throws \Psr\SimpleCache\InvalidArgumentException
119
     */
120
    public function runMigrate($arguments)
121
    {
122
        $dbConnection = Psr11::container()->get('DBDRIVER_CONNECTION');
123
124
        $migration = new Migration(new Uri($dbConnection), $this->workdir . "/db");
125
        $migration->registerDatabase("mysql", MySqlDatabase::class);
126
        $migration->addCallbackProgress(function ($cmd, $version) {
127
            echo "Doing $cmd, $version\n";
128
        });
129
130
        $argumentList = $this->extractArguments($arguments);
131
132
        $exec['reset'] = function () use ($migration, $argumentList) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
$exec was never initialized. Although not strictly required by PHP, it is generally a good practice to add $exec = array(); before regardless.
Loading history...
133
            if (!$argumentList["--yes"]) {
134
                throw new \Exception("Reset require the argument --yes");
135
            }
136
            $migration->reset();
137
        };
138
139
140
        $exec["update"] = function () use ($migration, $argumentList) {
141
            $migration->update($argumentList["--up-to"], $argumentList["--force"]);
142
        };
143
144
        if (isset($exec[$argumentList['command']])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $exec seems to never exist and therefore isset should always be false.
Loading history...
145
            $exec[$argumentList['command']]();
146
        }
147
    }
148
149
    /**
150
     * @param $arguments
151
     * @return array
152
     */
153
    protected function extractArguments($arguments) {
154
        $ret = [
155
            '--up-to' => null,
156
            '--yes' => null,
157
            '--force' => false,
158
        ];
159
160
        $ret['command'] = isset($arguments[0]) ? $arguments[0] : null;
161
162
        for ($i=1; $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...
163
            $args = explode("=", $arguments[$i]);
164
            $ret[$args[0]] = isset($args[1]) ? $args[1] : true;
165
        }
166
167
        return $ret;
168
    }
169
170
    /**
171
     * @throws \ByJG\Config\Exception\ConfigNotFoundException
172
     * @throws \ByJG\Config\Exception\EnvironmentException
173
     * @throws \ByJG\Config\Exception\KeyNotFoundException
174
     * @throws \Psr\SimpleCache\InvalidArgumentException
175
     */
176
    public function runGenRestDocs()
177
    {
178
        $docPath = $this->workdir . '/web/docs/';
179
        chdir($this->workdir);
180
        $this->liveExecuteCommand(
181
            $this->fixDir("vendor/bin/swagger")
182
            . " --output \"$docPath\" "
183
            . "--exclude vendor "
184
            . "--exclude docker "
185
            . "--exclude fw "
186
            . "--processor OperationId"
187
        );
188
189
        $docs = file_get_contents("$docPath/swagger.json");
190
        $docs = str_replace('__HOSTNAME__', Psr11::container()->get('API_SERVER'), $docs);
191
        file_put_contents("$docPath/swagger.json", $docs);
192
    }
193
}
194