Passed
Push — master ( 530886...6bdffc )
by Josh
02:33
created

Migrator::out()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: joshgulledge
5
 * Date: 10/2/18
6
 * Time: 2:35 PM
7
 */
8
9
namespace LCI\Blend\Migrations;
10
11
use LCI\Blend\Blender;
12
use LCI\Blend\Exception\MigratorException;
13
use LCI\Blend\Migrations;
14
use modX;
0 ignored issues
show
Bug introduced by
The type modX 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...
15
use Symfony\Component\Console\Output\OutputInterface;
16
17
class Migrator
18
{
19
    /** @var Blender */
20
    protected $blender;
21
22
    /** @var \modX */
23
    protected $modx;
24
25
    /** @var string  */
26
    protected $project = 'local';
27
28
    /** @var int @see https://symfony.com/doc/current/console/verbosity.html */
29
    protected $verbose = OutputInterface::VERBOSITY_NORMAL;
30
31
    /** @var array  */
32
    protected $blendMigrations = [];
33
34
    /** @var string ~ up|down */
35
    protected $migration_method = 'up';
36
37
    /** @var string  */
38
    protected $migration_type = 'master';
39
40
    /** @var int  */
41
    protected $migration_count = 0;
42
43
    /** @var int  */
44
    protected $migration_id = 0;
45
46
    /** @var string  */
47
    protected $migration_name = '';
48
49
    /**
50
     * Migrator constructor.
51
     * @param Blender $blender
52
     * @param modX $modx
53
     * @param string $project
54
     */
55
    public function __construct(Blender $blender, modX $modx, string $project)
56
    {
57
        $this->blender = $blender;
58
        $this->modx = $modx;
59
        $this->project = $project;
60
    }
61
62
    /**
63
     * @return int
64
     */
65
    public function getVerbose(): int
66
    {
67
        return $this->verbose;
68
    }
69
70
    /**
71
     * @param int $verbose
72
     * @see https://symfony.com/doc/current/console/verbosity.html
73
     * @return Migrator
74
     */
75
    public function setVerbose(int $verbose): Migrator
76
    {
77
        $this->verbose = $verbose;
78
        return $this;
79
    }
80
81
    /**
82
     * @param $data
83
     */
84
    public function logMigration($data)
85
    {
86
        if ($this->blender->isBlendInstalledInModx()) {
87
            try {
88
                /** @var \BlendMigrations $migration */
89
                $migration = $this->modx->newObject($this->blender->getBlendClassObject());
90
                if ($migration) {
0 ignored issues
show
introduced by
$migration is of type BlendMigrations, thus it always evaluated to true. If $migration can have other possible types, add them to src/Migrations/Migrator.php:88
Loading history...
91
                    $migration->fromArray($data);
92
                    $migration->save();
93
                }
94
            } catch (MigratorException $exception) {
95
                $this->outError($exception->getMessage());
96
            }
97
        }
98
    }
99
100
    /**
101
     * @param string $method
102
     * @param string $type
103
     * @param int $count
104
     * @param int $id
105
     * @param null|string $name
106
     * @throws MigratorException
107
     */
108
    public function runMigration($method = 'up', $type = 'master', $count = 0, $id = 0, $name = null)
109
    {
110
        $this->migration_method = $method;
111
        $this->migration_type = $type;
112
        $this->migration_count = $count;
113
        $this->migration_id = $id;
114
        $this->migration_name = $name;
115
116
        // 1. Get all migrations currently in DB:
117
        $this->getBlendMigrationCollection(false);
118
119
        // 2. Load migration files:
120
        if ($this->migration_method == 'up') {
121
            $loaded_migrations = $this->retrieveMigrationFiles();
122
123
            if (!$this->blender->isBlendInstalledInModx()) {
124
                $this->runLoadedFileMigrations($loaded_migrations);
125
                return;
126
            }
127
        }
128
129
        $this->runExistingDBMigrations();
130
    }
131
132
    /**
133
     * @return array ~ ['MigrationName' => MigrationObject, ...]
134
     */
135
    protected function retrieveMigrationFiles()
136
    {
137
        // 1. Get all migrations currently in DB:
138
        $blendMigrations = $this->getBlendMigrationCollection();
139
140
        $this->out('Searching directory for Migration classes ' . $this->blender->getMigrationPath());
141
142
        $loaded_migrations = [];
143
        $reload = false;
144
        /** @var \DirectoryIterator $file */
145
        foreach (new \DirectoryIterator($this->blender->getMigrationPath()) as $file) {
146
            if ($file->isFile() && $file->getExtension() == 'php') {
147
148
                $name = $file->getBasename('.php');
149
                //exit();
150
                if (!isset($blendMigrations[$name])) {
151
                    $new_migrations[] = $name;
152
                    /** @var Migrations $migrationProcessClass */
153
                    $migrationProcessClass = $this->loadMigrationClass($name, $this->blender);
154
155
                    $log_data = [
156
                        'project' => $this->project,
157
                        'name' => $name,
158
                        'status' => 'ready',
159
                    ];
160
                    if ($migrationProcessClass instanceof Migrations) {
161
                        $log_data['author'] = $migrationProcessClass->getAuthor();
162
                        $log_data['description'] = $migrationProcessClass->getDescription();
163
                        $log_data['type'] = $migrationProcessClass->getType();
164
                        $log_data['version'] = $migrationProcessClass->getVersion();
165
166
                        $loaded_migrations[$name] = $migrationProcessClass;
167
                    }
168
169
                    $this->logMigration($log_data);
170
171
                    $reload = true;
172
                }
173
            }
174
        }
175
176
        ksort($loaded_migrations);
177
178
        foreach ($loaded_migrations as $name => $migration) {
179
            $this->out('Found new Migration class '.$name);
180
        }
181
182
        if ($reload) {
183
            $this->getBlendMigrationCollection(true);
184
        }
185
186
        return $loaded_migrations;
187
    }
188
189
    /**
190
     * @throws MigratorException
191
     */
192
    protected function runExistingDBMigrations()
193
    {
194
        /** @var \BlendMigrations $migrationLog */
195
        foreach ($this->blendMigrations as $name => $migrationLog) {
196
            if (!$this->canRunMigrationVerifyLog($migrationLog)) {
197
                continue;
198
            }
199
            /** @var string $name */
200
            $name = $migrationLog->get('name');
201
202
            // new blender for each instance
203
            $blender = new Blender($this->modx, $this->blender->getUserInteractionHandler(), $this->blender->getConfig());
204
205
            /** @var Migrations $migration */
206
            $migration = $this->loadMigrationClass($name, $blender);
207
208
            if ($migration instanceof Migrations) {
209
                $this->out('Load Class: '.$name.' M: '.$this->migration_method, OutputInterface::VERBOSITY_DEBUG);
210
211
                $migration->{$this->migration_method}();
212
213
                $migrationLog->set('ran_sequence', $this->getRanSequence((int)$migrationLog->get('ran_sequence')));
214
                $migrationLog->set('status', $this->migration_method . '_complete');
215
                $migrationLog->set('processed_at', date('Y-m-d H:i:s'));
216
                $migrationLog->save();
217
218
            } else {
219
                // error
220
                throw new MigratorException('Class: ' . $name .' is not an instance of LCI\BLend\Migrations');
221
            }
222
        }
223
    }
224
225
    /**
226
     * @param $loaded_migrations
227
     */
228
    protected function runLoadedFileMigrations($loaded_migrations)
229
    {
230
        $logged_migrations = $this->getBlendMigrationCollection();
231
232
        /** @var Migrations $migration */
233
        foreach ($loaded_migrations as $name => $migration) {
234
            if (
235
                !$this->canRunMigrationVerifyMigration($name, $migration) ||
236
                (isset($logged_migrations[$name]) && !$this->canRunMigrationVerifyLog($logged_migrations[$name]))
237
            ) {
238
                continue;
239
            }
240
241
            $migration->{$this->migration_method}();
242
243
            if (isset($logged_migrations[$name])) {
244
                /** @var \BlendMigrations $migrationLog */
245
                $migrationLog = $logged_migrations[$name];
246
                $migrationLog->set('ran_sequence', $this->getRanSequence($migrationLog->get('ran_sequence')));
247
                $migrationLog->set('status', $this->migration_method . '_complete');
248
                $migrationLog->set('processed_at', date('Y-m-d H:i:s'));
249
                $migrationLog->save();
250
251
            } else {
252
                $this->logMigration([
253
                    'project' => $this->project,
254
                    'name' => $name,
255
                    'author' => $migration->getAuthor(),
256
                    'description' => $migration->getDescription(),
257
                    'type' => $migration->getType(),
258
                    'version' => $migration->getVersion(),
259
                    'status' => $this->migration_method . '_complete',
260
                    'ran_sequence' => $this->getRanSequence(),
261
                    'processed_at' => date('Y-m-d H:i:s')
262
                    ]);
263
264
            }
265
        }
266
    }
267
268
    /**
269
     * @param string $name
270
     * @param Migrations $migration
271
     * @return bool
272
     */
273
    protected function canRunMigrationVerifyMigration($name, Migrations $migration)
274
    {
275
        $can = true;
276
277
        if (!empty($this->migration_name) && $this->migration_name !== $name) {
278
            $can = false;
279
        }
280
281
        if ($migration->getType() !== $this->migration_type) {
282
            $can = false;
283
        }
284
285
        return $can;
286
    }
287
288
    /**
289
     * @param \BlendMigrations $migration
290
     * @return bool
291
     */
292
    protected function canRunMigrationVerifyLog($migration)
293
    {
294
        $can = true;
295
296
        if ($this->migration_id > 0 && $migration->get('id') != $this->migration_id) {
297
            $can = false;
298
        }
299
300
        /** @var string $name */
301
        $name = $migration->get('name');
302
303
        if (!empty($this->migration_name) && $this->migration_name !== $name) {
304
            $can = false;
305
        }
306
307
        /** @var string $status ~ ready|up_complete|down_complete*/
308
        $status = $migration->get('status');
309
310
        /** @var string $server_type */
311
        $server_type = $migration->get('type');
312
313
        if (($this->migration_type != $server_type) ||
314
            $status == 'seed export' ||
315
            ($this->migration_method == 'up' && $status == 'up_complete') ||
316
            ($this->migration_method == 'down' && $status != 'up_complete')
317
        ) {
318
            $this->out('canRunMigrationVerifyLog() Failed' . __LINE__, OutputInterface::VERBOSITY_DEBUG);
319
            $can = false;
320
        }
321
322
        return $can;
323
    }
324
325
    /**
326
     * @param bool $reload
327
     *
328
     * @return array ~ array of \BlendMigrations
329
     */
330
    protected function getBlendMigrationCollection($reload = false)
331
    {
332
        if (
333
            $this->blender->isBlendInstalledInModx() &&
334
            (!$this->blendMigrations || $reload)
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->blendMigrations of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
335
        ) {
336
            $blendMigrations = [];
337
338
            $dir = 'ASC';
339
            if ($this->migration_method == 'down') {
340
                $dir = 'DESC';
341
            }
342
343
            /** @var \xPDOQuery $query */
344
            $query = $this->modx->newQuery($this->blender->getBlendClassObject());
345
            $query->where(['project' => $this->project]);
346
347
            if ($this->migration_id > 0) {
348
                $query->where(['id' => $this->migration_id]);
349
350
            } elseif (!empty($this->migration_name)) {
351
                $query->where(['name' => $this->migration_name]);
352
353
            }
354
355
            $query
356
                ->sortby('ran_sequence', $dir)
357
                ->sortBy('name', $dir);
358
359
            if ($this->migration_count > 0) {
360
                $query->limit($this->migration_count);
361
            }
362
            $query->prepare();
363
364
            $this->out(__METHOD__ .':: sql: ' . $query->toSQL(), OutputInterface::VERBOSITY_DEBUG);
365
366
            $migrationCollection = $this->modx->getCollection($this->blender->getBlendClassObject(), $query);
367
368
            /** @var \BlendMigrations $migration */
369
            foreach ($migrationCollection as $migration) {
370
                $blendMigrations[$migration->get('name')] = $migration;
371
            }
372
            $this->blendMigrations = $blendMigrations;
373
        }
374
375
        return $this->blendMigrations;
376
    }
377
378
    /**
379
     * @param int $ran_sequence
380
     * @return int|mixed
381
     */
382
    protected function getRanSequence(int $ran_sequence=0)
383
    {
384
        if ($this->migration_method == 'up') {
385
            /** @var \xPDOQuery $query */
386
            $query = $this->modx->newQuery($this->blender->getBlendClassObject());
387
            $query
388
                ->where([
389
                    'project' => $this->project,
390
                    'status' => 'up_complete'
391
                ])
392
                ->sortby('ran_sequence', 'DESC')
393
                ->limit(1);
394
395
            /** @var \BlendMigrations $lastMigrationLog */
396
            $lastMigrationLog = $this->modx->getObject($this->blender->getBlendClassObject(), $query);
397
398
            if (is_object($lastMigrationLog)) {
399
                $ran_sequence = $lastMigrationLog->get('ran_sequence');
400
            }
401
402
            // Advance
403
            ++$ran_sequence;
404
        }
405
406
        return $ran_sequence;
407
    }
408
409
    /**
410
     * @param string $name
411
     * @param Blender $blender
412
     *
413
     * @return bool|Migrations
414
     */
415
    protected function loadMigrationClass($name, Blender $blender)
416
    {
417
        $migrationProcessClass = false;
418
419
        $file = $blender->getMigrationPath().$name.'.php';
420
        if (file_exists($file)) {
421
            require_once $file;
422
423
            if (class_exists($name)) {
424
                /** @var Migrations $migrationProcessClass */
425
                $migrationProcessClass = new $name($this->modx, $blender);
426
            }
427
        }
428
429
        return $migrationProcessClass;
430
    }
431
432
    /**
433
     * @param string $message
434
     * @param int $verbose
435
     */
436
    protected function outError($message)
437
    {
438
        $this->blender->out($message, true);
0 ignored issues
show
Bug introduced by
true of type true is incompatible with the type integer expected by parameter $verbose of LCI\Blend\Blender::out(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

438
        $this->blender->out($message, /** @scrutinizer ignore-type */ true);
Loading history...
439
    }
440
441
    /**
442
     * @param string $message
443
     * @param int $verbose
444
     */
445
    protected function out($message, $verbose=OutputInterface::VERBOSITY_NORMAL)
446
    {
447
        if ($this->verbose >= $verbose) {
448
            $this->blender->out($message);
449
        }
450
    }
451
}