Migrator::getBlendMigrationCollection()   B
last analyzed

Complexity

Conditions 7
Paths 5

Size

Total Lines 38
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 7
eloc 21
c 2
b 0
f 1
nc 5
nop 1
dl 0
loc 38
rs 8.6506
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.
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
195
        try {
196
            /** @var \DirectoryIterator $file */
197
            $directoryIterator = new \DirectoryIterator($this->blender->getMigrationPath());
198
        } catch (\UnexpectedValueException $exception) {
199
200
            $this->outError($exception->getMessage());
201
            return $loaded_migrations;
202
        }
203
204
        foreach ($directoryIterator as $file) {
205
            if ($file->isFile() && $file->getExtension() == 'php') {
206
207
                $name = $file->getBasename('.php');
208
                //exit();
209
                if (!isset($blendMigrations[$name])) {
210
                    $new_migrations[] = $name;
211
                    /** @var Migrations $migrationProcessClass */
212
                    $migrationProcessClass = $this->loadMigrationClass($name, $this->blender);
213
214
                    $log_data = [
215
                        'project' => $this->project,
216
                        'name' => $name,
217
                        'status' => 'ready',
218
                    ];
219
                    if ($migrationProcessClass instanceof Migrations) {
220
                        $log_data['author'] = $migrationProcessClass->getAuthor();
221
                        $log_data['description'] = $migrationProcessClass->getDescription();
222
                        $log_data['type'] = $migrationProcessClass->getType();
223
                        $log_data['version'] = $migrationProcessClass->getVersion();
224
225
                        $loaded_migrations[$name] = $migrationProcessClass;
226
                    }
227
228
                    $this->logMigration($log_data);
229
230
                    $reload = true;
231
                }
232
            }
233
        }
234
235
        ksort($loaded_migrations);
236
237
        foreach ($loaded_migrations as $name => $migration) {
238
            $this->out('Found new Migration class '.$name);
239
        }
240
241
        if ($reload) {
242
            $this->getBlendMigrationCollection(true);
243
        }
244
245
        return $loaded_migrations;
246
    }
247
248
    /**
249
     * @throws MigratorException
250
     */
251
    protected function runExistingDBMigrations()
252
    {
253
        $this->out(__METHOD__ . ' Start', Blender::VERBOSITY_DEBUG);
254
        /** @var \BlendMigrations $migrationLog */
255
        foreach ($this->blendMigrations as $name => $migrationLog) {
256
            if (!$this->canRunMigrationVerifyLog($migrationLog)) {
257
                continue;
258
            }
259
            /** @var string $name */
260
            $name = $migrationLog->get('name');
261
262
            // new blender for each instance
263
            $blender = new Blender($this->modx, $this->blender->getUserInteractionHandler(), $this->blender->getConfig());
264
265
            /** @var Migrations $migration */
266
            $migration = $this->loadMigrationClass($name, $blender);
267
268
            if ($migration instanceof Migrations) {
269
                $this->out('Load Class: '.$name.' and call method: '.$this->migration_method, OutputInterface::VERBOSITY_VERBOSE);
270
271
                $migration->{$this->migration_method}();
272
273
                $migrationLog->set('ran_sequence', $this->getRanSequence((int)$migrationLog->get('ran_sequence')));
274
                $migrationLog->set('status', $this->migration_method . '_complete');
275
                $migrationLog->set('processed_at', date('Y-m-d H:i:s'));
276
277
                if ($this->delay_logging) {
278
                    $this->out(__METHOD__.' Delay logging', OutputInterface::VERBOSITY_DEBUG);
279
                    $this->delayed_logs[$migrationLog->get('project').$migrationLog->get('name')] = $migrationLog;
280
281
                } else {
282
                    $migrationLog->save();
283
                }
284
285
            } else {
286
                // error
287
                throw new MigratorException('Class: ' . $name .' is not an instance of LCI\BLend\Migrations');
288
            }
289
        }
290
    }
291
292
    /**
293
     * @param $loaded_migrations
294
     */
295
    protected function runLoadedFileMigrations($loaded_migrations)
296
    {
297
        $this->out(__METHOD__ . ' Start', Blender::VERBOSITY_DEBUG);
298
        $logged_migrations = $this->getBlendMigrationCollection();
299
300
        $count = 0;
301
        /** @var Migrations $migration */
302
        foreach ($loaded_migrations as $name => $migration) {
303
            if (
304
                !$this->canRunMigrationVerifyMigration($name, $migration) ||
305
                (isset($logged_migrations[$name]) && !$this->canRunMigrationVerifyLog($logged_migrations[$name]))
306
            ) {
307
                continue;
308
            }
309
310
            $this->out('Load Class: '.$name.' and call method: '.$this->migration_method, OutputInterface::VERBOSITY_VERBOSE);
311
312
            $migration->{$this->migration_method}();
313
314
            if (isset($logged_migrations[$name])) {
315
                /** @var \BlendMigrations $migrationLog */
316
                $migrationLog = $logged_migrations[$name];
317
                $migrationLog->set('ran_sequence', $this->getRanSequence($migrationLog->get('ran_sequence')));
318
                $migrationLog->set('status', $this->migration_method . '_complete');
319
                $migrationLog->set('processed_at', date('Y-m-d H:i:s'));
320
321
                if ($this->delay_logging) {
322
                    $this->delayed_logs[$this->project . $name] = $migrationLog;
323
324
                } else {
325
                    $migrationLog->save();
326
                }
327
328
            } else {
329
                $this->logMigration([
330
                    'project' => $this->project,
331
                    'name' => $name,
332
                    'author' => $migration->getAuthor(),
333
                    'description' => $migration->getDescription(),
334
                    'type' => $migration->getType(),
335
                    'version' => $migration->getVersion(),
336
                    'status' => $this->migration_method . '_complete',
337
                    'ran_sequence' => $this->getRanSequence($count++),
338
                    'processed_at' => date('Y-m-d H:i:s')
339
                    ]);
340
341
            }
342
        }
343
    }
344
345
    /**
346
     * @param string $name
347
     * @param Migrations $migration
348
     * @return bool
349
     */
350
    protected function canRunMigrationVerifyMigration($name, Migrations $migration)
351
    {
352
        $can = true;
353
354
        if (!empty($this->migration_name) && $this->migration_name !== $name) {
355
            $can = false;
356
        }
357
358
        if ($migration->getType() !== $this->migration_type) {
359
            $can = false;
360
        }
361
362
        return $can;
363
    }
364
365
    /**
366
     * @param \BlendMigrations $migration
367
     * @return bool
368
     */
369
    protected function canRunMigrationVerifyLog($migration)
370
    {
371
        $can = true;
372
373
        if ($this->migration_id > 0 && $migration->get('id') != $this->migration_id) {
374
            $can = false;
375
        }
376
377
        /** @var string $name */
378
        $name = $migration->get('name');
379
380
        if (!empty($this->migration_name) && $this->migration_name !== $name) {
381
            $can = false;
382
        }
383
384
        /** @var string $status ~ ready|up_complete|down_complete*/
385
        $status = $migration->get('status');
386
387
        /** @var string $server_type */
388
        $server_type = $migration->get('type');
389
390
        if (($this->migration_type != $server_type) ||
391
            $status == 'seed export' ||
392
            ($this->migration_method == 'up' && $status == 'up_complete') ||
393
            ($this->migration_method == 'down' && $status != 'up_complete')
394
        ) {
395
            $this->out('canRunMigrationVerifyLog() Failed' . __LINE__, OutputInterface::VERBOSITY_DEBUG);
396
            $can = false;
397
        }
398
399
        return $can;
400
    }
401
402
    /**
403
     * @param bool $reload
404
     *
405
     * @return array ~ array of \BlendMigrations
406
     */
407
    protected function getBlendMigrationCollection($reload = false)
408
    {
409
        if (
410
            $this->blender->isBlendInstalledInModx($this->check_install_log) &&
411
            (!$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...
412
        ) {
413
            $blendMigrations = [];
414
415
            $dir = 'ASC';
416
            if ($this->migration_method == 'down') {
417
                $dir = 'DESC';
418
            }
419
420
            /** @var \xPDOQuery $query */
421
            $query = $this->modx->newQuery($this->blender->getBlendClassObject());
422
            $query->where(['project' => $this->project]);
423
424
            $query
425
                ->sortby('ran_sequence', $dir)
426
                ->sortBy('name', $dir);
427
428
            if ($this->migration_count > 0) {
429
                $query->limit($this->migration_count);
430
            }
431
            $query->prepare();
432
433
            $this->out(__METHOD__ .':: sql: ' . $query->toSQL(), OutputInterface::VERBOSITY_DEBUG);
434
435
            $migrationCollection = $this->modx->getCollection($this->blender->getBlendClassObject(), $query);
436
437
            /** @var \BlendMigrations $migration */
438
            foreach ($migrationCollection as $migration) {
439
                $blendMigrations[$migration->get('name')] = $migration;
440
            }
441
            $this->blendMigrations = $blendMigrations;
442
        }
443
444
        return $this->blendMigrations;
445
    }
446
447
    /**
448
     * @param int $ran_sequence
449
     * @return int|mixed
450
     */
451
    protected function getRanSequence(int $ran_sequence=0)
452
    {
453
        if ($this->migration_method == 'up') {
454
            /** @var \xPDOQuery $query */
455
            $query = $this->modx->newQuery($this->blender->getBlendClassObject());
456
            $query
457
                ->where([
458
                    'project' => $this->project,
459
                    'status' => 'up_complete'
460
                ])
461
                ->sortby('ran_sequence', 'DESC')
462
                ->limit(1);
463
464
            /** @var \BlendMigrations $lastMigrationLog */
465
            $lastMigrationLog = $this->modx->getObject($this->blender->getBlendClassObject(), $query);
466
467
            if (is_object($lastMigrationLog)) {
468
                $ran_sequence = $lastMigrationLog->get('ran_sequence');
469
            }
470
471
            // Advance
472
            ++$ran_sequence;
473
        }
474
475
        return $ran_sequence;
476
    }
477
478
    /**
479
     * @param string $name
480
     * @param Blender $blender
481
     *
482
     * @return bool|Migrations
483
     */
484
    protected function loadMigrationClass($name, Blender $blender)
485
    {
486
        $migrationProcessClass = false;
487
488
        $file = $blender->getMigrationPath().$name.'.php';
489
        if (file_exists($file)) {
490
            require_once $file;
491
492
            if (class_exists($name)) {
493
                /** @var Migrations $migrationProcessClass */
494
                $migrationProcessClass = new $name($this->modx, $blender);
495
            }
496
        }
497
498
        return $migrationProcessClass;
499
    }
500
501
    /**
502
     * @param string $message
503
     * @param int $verbose
504
     */
505
    protected function outError($message, $verbose=OutputInterface::VERBOSITY_NORMAL)
506
    {
507
        $this->blender->outError($message, $verbose);
508
    }
509
510
    /**
511
     * @param string $message
512
     * @param int $verbose
513
     */
514
    protected function out($message, $verbose=OutputInterface::VERBOSITY_NORMAL)
515
    {
516
        $this->blender->out($message, $verbose);
517
    }
518
}