Passed
Push — master ( 361368...f78f12 )
by Josh
02:46
created

Migrator::runMigration()   B

Complexity

Conditions 9
Paths 24

Size

Total Lines 33
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 33
rs 8.0555
c 0
b 0
f 0
cc 9
nc 24
nop 5
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
    /** @var bool */
50
    protected $delay_logging = false;
51
52
    /** @var array  */
53
    protected $delayed_logs = [];
54
55
    /** @var bool  */
56
    protected $check_install_log = true;
57
58
    /**
59
     * Migrator constructor.
60
     * @param Blender $blender
61
     * @param modX $modx
62
     * @param string $project
63
     */
64
    public function __construct(Blender $blender, modX $modx, string $project)
65
    {
66
        $this->blender = $blender;
67
        $this->modx = $modx;
68
        $this->project = $project;
69
    }
70
71
    /**
72
     * @return int
73
     */
74
    public function getVerbose(): int
75
    {
76
        return $this->verbose;
77
    }
78
79
    /**
80
     * @param int $verbose
81
     * @see https://symfony.com/doc/current/console/verbosity.html
82
     * @return Migrator
83
     */
84
    public function setVerbose(int $verbose): Migrator
85
    {
86
        $this->verbose = $verbose;
87
        return $this;
88
    }
89
90
    /**
91
     * @param bool $delay_logging ~ if true will log after all Migrations are complete, only for new migrations
92
     * @return $this
93
     */
94
    public function setDelayLogging(bool $delay_logging): Migrator
95
    {
96
        $this->delay_logging = $delay_logging;
97
        return $this;
98
    }
99
100
    /**
101
     * @param bool $check_install_log
102
     * @return Migrator
103
     */
104
    public function setCheckInstallLog(bool $check_install_log): Migrator
105
    {
106
        $this->check_install_log = $check_install_log;
107
        return $this;
108
    }
109
110
    /**
111
     * @param array $data
112
     * @param bool $force_save_attempt
113
     */
114
    public function logMigration($data, $force_save_attempt=false)
115
    {
116
        if ($this->delay_logging && !$force_save_attempt) {// attempt
117
            $key = $data['project'] . $data['name'];
118
            $this->delayed_logs[$key] = $data;
119
120
        } else {
121
            if ($this->blender->isBlendInstalledInModx($this->check_install_log)) {
122
                try {
123
                    /** @var \BlendMigrations $migration */
124
                    $migration = $this->modx->newObject($this->blender->getBlendClassObject());
125
                    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:123
Loading history...
126
                        $migration->fromArray($data);
127
                        $migration->save();
128
                    }
129
                } catch (\Exception $exception) {
130
                    $this->outError($exception->getMessage());
131
                }
132
            }
133
        }
134
    }
135
136
    /**
137
     * @param string $method
138
     * @param string $type
139
     * @param int $count
140
     * @param int $id
141
     * @param null|string $name
142
     * @throws MigratorException
143
     */
144
    public function runMigration($method = 'up', $type = 'master', $count = 0, $id = 0, $name = null)
145
    {
146
        $this->migration_method = $method;
147
        $this->migration_type = $type;
148
        $this->migration_count = $count;
149
        $this->migration_id = $id;
150
        $this->migration_name = $name;
151
152
        $run_existing = true;
153
        // 1. Get all migrations currently in DB:
154
        $this->getBlendMigrationCollection(false);
155
156
        // 2. Load migration files:
157
        if ($this->migration_method == 'up') {
158
            $loaded_migrations = $this->retrieveMigrationFiles();
159
160
            if (!$this->blender->isBlendInstalledInModx($this->check_install_log) || ($this->delay_logging && count($loaded_migrations) > 0)) {
161
                $this->runLoadedFileMigrations($loaded_migrations);
162
163
                $run_existing = false;
164
            }
165
        }
166
167
        if ($run_existing) {
168
            $this->runExistingDBMigrations();
169
        }
170
171
        if ($this->delay_logging) {
172
            foreach ($this->delayed_logs as $key => $log) {
173
                if (is_object($log)) {
174
                    $log->save();
175
                } else {
176
                    $this->logMigration($log, true);
177
                }
178
            }
179
        }
180
    }
181
182
    /**
183
     * @return array ~ ['MigrationName' => MigrationObject, ...]
184
     */
185
    protected function retrieveMigrationFiles()
186
    {
187
        // 1. Get all migrations currently in DB:
188
        $blendMigrations = $this->getBlendMigrationCollection();
189
190
        $this->out('Searching directory for Migration classes ' . $this->blender->getMigrationPath());
191
192
        $loaded_migrations = [];
193
        $reload = false;
194
        /** @var \DirectoryIterator $file */
195
        foreach (new \DirectoryIterator($this->blender->getMigrationPath()) as $file) {
196
            if ($file->isFile() && $file->getExtension() == 'php') {
197
198
                $name = $file->getBasename('.php');
199
                //exit();
200
                if (!isset($blendMigrations[$name])) {
201
                    $new_migrations[] = $name;
202
                    /** @var Migrations $migrationProcessClass */
203
                    $migrationProcessClass = $this->loadMigrationClass($name, $this->blender);
204
205
                    $log_data = [
206
                        'project' => $this->project,
207
                        'name' => $name,
208
                        'status' => 'ready',
209
                    ];
210
                    if ($migrationProcessClass instanceof Migrations) {
211
                        $log_data['author'] = $migrationProcessClass->getAuthor();
212
                        $log_data['description'] = $migrationProcessClass->getDescription();
213
                        $log_data['type'] = $migrationProcessClass->getType();
214
                        $log_data['version'] = $migrationProcessClass->getVersion();
215
216
                        $loaded_migrations[$name] = $migrationProcessClass;
217
                    }
218
219
                    $this->logMigration($log_data);
220
221
                    $reload = true;
222
                }
223
            }
224
        }
225
226
        ksort($loaded_migrations);
227
228
        foreach ($loaded_migrations as $name => $migration) {
229
            $this->out('Found new Migration class '.$name);
230
        }
231
232
        if ($reload) {
233
            $this->getBlendMigrationCollection(true);
234
        }
235
236
        return $loaded_migrations;
237
    }
238
239
    /**
240
     * @throws MigratorException
241
     */
242
    protected function runExistingDBMigrations()
243
    {
244
        $this->out(__METHOD__ . ' Start', Blender::VERBOSITY_DEBUG);
245
        /** @var \BlendMigrations $migrationLog */
246
        foreach ($this->blendMigrations as $name => $migrationLog) {
247
            if (!$this->canRunMigrationVerifyLog($migrationLog)) {
248
                continue;
249
            }
250
            /** @var string $name */
251
            $name = $migrationLog->get('name');
252
253
            // new blender for each instance
254
            $blender = new Blender($this->modx, $this->blender->getUserInteractionHandler(), $this->blender->getConfig());
255
256
            /** @var Migrations $migration */
257
            $migration = $this->loadMigrationClass($name, $blender);
258
259
            if ($migration instanceof Migrations) {
260
                $this->out('Load Class: '.$name.' and call method: '.$this->migration_method, OutputInterface::VERBOSITY_VERBOSE);
261
262
                $migration->{$this->migration_method}();
263
264
                $migrationLog->set('ran_sequence', $this->getRanSequence((int)$migrationLog->get('ran_sequence')));
265
                $migrationLog->set('status', $this->migration_method . '_complete');
266
                $migrationLog->set('processed_at', date('Y-m-d H:i:s'));
267
268
                if ($this->delay_logging) {
269
                    $this->out(__METHOD__.' Delay logging', OutputInterface::VERBOSITY_DEBUG);
270
                    $this->delayed_logs[$migrationLog->get('project').$migrationLog->get('name')] = $migrationLog;
271
272
                } else {
273
                    $migrationLog->save();
274
                }
275
276
            } else {
277
                // error
278
                throw new MigratorException('Class: ' . $name .' is not an instance of LCI\BLend\Migrations');
279
            }
280
        }
281
    }
282
283
    /**
284
     * @param $loaded_migrations
285
     */
286
    protected function runLoadedFileMigrations($loaded_migrations)
287
    {
288
        $this->out(__METHOD__ . ' Start', Blender::VERBOSITY_DEBUG);
289
        $logged_migrations = $this->getBlendMigrationCollection();
290
291
        $count = 0;
292
        /** @var Migrations $migration */
293
        foreach ($loaded_migrations as $name => $migration) {
294
            if (
295
                !$this->canRunMigrationVerifyMigration($name, $migration) ||
296
                (isset($logged_migrations[$name]) && !$this->canRunMigrationVerifyLog($logged_migrations[$name]))
297
            ) {
298
                continue;
299
            }
300
301
            $this->out('Load Class: '.$name.' and call method: '.$this->migration_method, OutputInterface::VERBOSITY_VERBOSE);
302
303
            $migration->{$this->migration_method}();
304
305
            if (isset($logged_migrations[$name])) {
306
                /** @var \BlendMigrations $migrationLog */
307
                $migrationLog = $logged_migrations[$name];
308
                $migrationLog->set('ran_sequence', $this->getRanSequence($migrationLog->get('ran_sequence')));
309
                $migrationLog->set('status', $this->migration_method . '_complete');
310
                $migrationLog->set('processed_at', date('Y-m-d H:i:s'));
311
312
                if ($this->delay_logging) {
313
                    $this->delayed_logs[$this->project . $name] = $migrationLog;
314
315
                } else {
316
                    $migrationLog->save();
317
                }
318
319
            } else {
320
                $this->logMigration([
321
                    'project' => $this->project,
322
                    'name' => $name,
323
                    'author' => $migration->getAuthor(),
324
                    'description' => $migration->getDescription(),
325
                    'type' => $migration->getType(),
326
                    'version' => $migration->getVersion(),
327
                    'status' => $this->migration_method . '_complete',
328
                    'ran_sequence' => $this->getRanSequence($count++),
329
                    'processed_at' => date('Y-m-d H:i:s')
330
                    ]);
331
332
            }
333
        }
334
    }
335
336
    /**
337
     * @param string $name
338
     * @param Migrations $migration
339
     * @return bool
340
     */
341
    protected function canRunMigrationVerifyMigration($name, Migrations $migration)
342
    {
343
        $can = true;
344
345
        if (!empty($this->migration_name) && $this->migration_name !== $name) {
346
            $can = false;
347
        }
348
349
        if ($migration->getType() !== $this->migration_type) {
350
            $can = false;
351
        }
352
353
        return $can;
354
    }
355
356
    /**
357
     * @param \BlendMigrations $migration
358
     * @return bool
359
     */
360
    protected function canRunMigrationVerifyLog($migration)
361
    {
362
        $can = true;
363
364
        if ($this->migration_id > 0 && $migration->get('id') != $this->migration_id) {
365
            $can = false;
366
        }
367
368
        /** @var string $name */
369
        $name = $migration->get('name');
370
371
        if (!empty($this->migration_name) && $this->migration_name !== $name) {
372
            $can = false;
373
        }
374
375
        /** @var string $status ~ ready|up_complete|down_complete*/
376
        $status = $migration->get('status');
377
378
        /** @var string $server_type */
379
        $server_type = $migration->get('type');
380
381
        if (($this->migration_type != $server_type) ||
382
            $status == 'seed export' ||
383
            ($this->migration_method == 'up' && $status == 'up_complete') ||
384
            ($this->migration_method == 'down' && $status != 'up_complete')
385
        ) {
386
            $this->out('canRunMigrationVerifyLog() Failed' . __LINE__, OutputInterface::VERBOSITY_DEBUG);
387
            $can = false;
388
        }
389
390
        return $can;
391
    }
392
393
    /**
394
     * @param bool $reload
395
     *
396
     * @return array ~ array of \BlendMigrations
397
     */
398
    protected function getBlendMigrationCollection($reload = false)
399
    {
400
        if (
401
            $this->blender->isBlendInstalledInModx($this->check_install_log) &&
402
            (!$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...
403
        ) {
404
            $blendMigrations = [];
405
406
            $dir = 'ASC';
407
            if ($this->migration_method == 'down') {
408
                $dir = 'DESC';
409
            }
410
411
            /** @var \xPDOQuery $query */
412
            $query = $this->modx->newQuery($this->blender->getBlendClassObject());
413
            $query->where(['project' => $this->project]);
414
415
            if ($this->migration_id > 0) {
416
                $query->where(['id' => $this->migration_id]);
417
418
            } elseif (!empty($this->migration_name)) {
419
                $query->where(['name' => $this->migration_name]);
420
421
            }
422
423
            $query
424
                ->sortby('ran_sequence', $dir)
425
                ->sortBy('name', $dir);
426
427
            if ($this->migration_count > 0) {
428
                $query->limit($this->migration_count);
429
            }
430
            $query->prepare();
431
432
            $this->out(__METHOD__ .':: sql: ' . $query->toSQL(), OutputInterface::VERBOSITY_DEBUG);
433
434
            $migrationCollection = $this->modx->getCollection($this->blender->getBlendClassObject(), $query);
435
436
            /** @var \BlendMigrations $migration */
437
            foreach ($migrationCollection as $migration) {
438
                $blendMigrations[$migration->get('name')] = $migration;
439
            }
440
            $this->blendMigrations = $blendMigrations;
441
        }
442
443
        return $this->blendMigrations;
444
    }
445
446
    /**
447
     * @param int $ran_sequence
448
     * @return int|mixed
449
     */
450
    protected function getRanSequence(int $ran_sequence=0)
451
    {
452
        if ($this->migration_method == 'up') {
453
            /** @var \xPDOQuery $query */
454
            $query = $this->modx->newQuery($this->blender->getBlendClassObject());
455
            $query
456
                ->where([
457
                    'project' => $this->project,
458
                    'status' => 'up_complete'
459
                ])
460
                ->sortby('ran_sequence', 'DESC')
461
                ->limit(1);
462
463
            /** @var \BlendMigrations $lastMigrationLog */
464
            $lastMigrationLog = $this->modx->getObject($this->blender->getBlendClassObject(), $query);
465
466
            if (is_object($lastMigrationLog)) {
467
                $ran_sequence = $lastMigrationLog->get('ran_sequence');
468
            }
469
470
            // Advance
471
            ++$ran_sequence;
472
        }
473
474
        return $ran_sequence;
475
    }
476
477
    /**
478
     * @param string $name
479
     * @param Blender $blender
480
     *
481
     * @return bool|Migrations
482
     */
483
    protected function loadMigrationClass($name, Blender $blender)
484
    {
485
        $migrationProcessClass = false;
486
487
        $file = $blender->getMigrationPath().$name.'.php';
488
        if (file_exists($file)) {
489
            require_once $file;
490
491
            if (class_exists($name)) {
492
                /** @var Migrations $migrationProcessClass */
493
                $migrationProcessClass = new $name($this->modx, $blender);
494
            }
495
        }
496
497
        return $migrationProcessClass;
498
    }
499
500
    /**
501
     * @param string $message
502
     * @param int $verbose
503
     */
504
    protected function outError($message, $verbose=OutputInterface::VERBOSITY_NORMAL)
505
    {
506
        $this->blender->outError($message, $verbose);
507
    }
508
509
    /**
510
     * @param string $message
511
     * @param int $verbose
512
     */
513
    protected function out($message, $verbose=OutputInterface::VERBOSITY_NORMAL)
514
    {
515
        $this->blender->out($message, $verbose);
516
    }
517
}