Test Failed
Push — develop ( 815500...0204ba )
by nguereza
02:34
created

AbstractCommand::getExecuted()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 9
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 15
rs 9.9666
1
<?php
2
3
/**
4
 * Platine Framework
5
 *
6
 * Platine Framework is a lightweight, high-performance, simple and elegant
7
 * PHP Web framework
8
 *
9
 * This content is released under the MIT License (MIT)
10
 *
11
 * Copyright (c) 2020 Platine Framework
12
 *
13
 * Permission is hereby granted, free of charge, to any person obtaining a copy
14
 * of this software and associated documentation files (the "Software"), to deal
15
 * in the Software without restriction, including without limitation the rights
16
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
 * copies of the Software, and to permit persons to whom the Software is
18
 * furnished to do so, subject to the following conditions:
19
 *
20
 * The above copyright notice and this permission notice shall be included in all
21
 * copies or substantial portions of the Software.
22
 *
23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
 * SOFTWARE.
30
 */
31
32
/**
33
 *  @file AbstractCommand.php
34
 *
35
 *  The Base migration command class
36
 *
37
 *  @package    Platine\Framework\Migration\Command
38
 *  @author Platine Developers team
39
 *  @copyright  Copyright (c) 2020
40
 *  @license    http://opensource.org/licenses/MIT  MIT License
41
 *  @link   http://www.iacademy.cf
42
 *  @version 1.0.0
43
 *  @filesource
44
 */
45
46
declare(strict_types=1);
47
48
namespace Platine\Framework\Migration\Command;
49
50
use Platine\Config\Config;
51
use Platine\Console\Command\Command;
52
use Platine\Database\Connection;
53
use Platine\Database\Exception\QueryPrepareException;
54
use Platine\Database\Schema;
55
use Platine\Database\Schema\CreateTable;
56
use Platine\Filesystem\DirectoryInterface;
57
use Platine\Filesystem\FileInterface;
58
use Platine\Filesystem\Filesystem;
59
use Platine\Framework\App\Application;
60
use Platine\Framework\Migration\AbstractMigration;
61
use Platine\Framework\Migration\MigrationRepository;
62
use Platine\Stdlib\Helper\Path;
63
use Platine\Stdlib\Helper\Str;
64
use RuntimeException;
65
66
/**
67
 * class AbstractCommand
68
 * @package Platine\Framework\Migration\Command
69
 */
70
abstract class AbstractCommand extends Command
71
{
72
73
    /**
74
     * The migration repository
75
     * @var MigrationRepository
76
     */
77
    protected MigrationRepository $repository;
78
79
    /**
80
     * The schema to use
81
     * @var Schema
82
     */
83
    protected Schema $schema;
84
85
    /**
86
     * The configuration to use
87
     * @var Config
88
     */
89
    protected Config $config;
90
91
    /**
92
     * The file system to use
93
     * @var Filesystem
94
     */
95
    protected Filesystem $filesystem;
96
97
    /**
98
     * The Platine Application
99
     * @var Application
100
     */
101
    protected Application $application;
102
103
    /**
104
     * The migration files path
105
     * @var string
106
     */
107
    protected string $migrationPath = '';
108
109
    /**
110
     * Migration table name
111
     * @var string
112
     */
113
    protected string $table = 'migrations';
114
115
    /**
116
     * Create new instance
117
     * @param Application $app
118
     * @param MigrationRepository $repository
119
     * @param Schema $schema
120
     * @param Config $config
121
     * @param Filesystem $filesystem
122
     */
123
    public function __construct(
124
        Application $app,
125
        MigrationRepository $repository,
126
        Schema $schema,
127
        Config $config,
128
        Filesystem $filesystem
129
    ) {
130
        parent::__construct('migration', 'Command to manage database migration');
131
        $this->application = $app;
132
        $this->repository = $repository;
133
        $this->schema = $schema;
134
        $this->config = $config;
135
        $this->filesystem = $filesystem;
136
        $path = Path::convert2Absolute($config->get('migration.path', 'migrations'));
137
        $this->migrationPath = Path::normalizePathDS($path, true);
138
        $this->table = $config->get('migration.table', 'migrations');
139
    }
140
141
    /**
142
     * Check the migration directory
143
     * @return void
144
     */
145
    protected function checkMigrationPath(): void
146
    {
147
        $directory = $this->filesystem->directory($this->migrationPath);
148
149
        if (!$directory->exists() || !$directory->isWritable()) {
150
            throw new RuntimeException(sprintf(
151
                'Migration directory [%s] does not exist or is writable',
152
                $this->migrationPath
153
            ));
154
        }
155
    }
156
157
    /**
158
     * Check if migration table does not exist and create it
159
     * @return void
160
     */
161
    protected function checkMigrationTable(): void
162
    {
163
        try {
164
            $this->repository->find('xx');
165
        } catch (QueryPrepareException $ex) {
166
            $this->createMigrationTable();
167
        }
168
    }
169
170
    /**
171
     * Create migration table
172
     * @return void
173
     */
174
    protected function createMigrationTable(): void
175
    {
176
        $tableName = $this->config->get('migration.table', 'migrations');
177
        $this->schema->create($tableName, function (CreateTable $table) {
178
            $table->string('version', 20)
179
                   ->description('The migration version')
180
                   ->primary();
181
            $table->string('description')
182
                   ->description('The migration description');
183
            $table->datetime('created_at')
184
                    ->description('Migration run time');
185
186
            $table->engine('INNODB');
187
        });
188
    }
189
190
    /**
191
     * Create migration class for the given version
192
     * @param string $description
193
     * @param string $version
194
     * @return AbstractMigration
195
     */
196
    protected function createMigrationClass(
197
        string $description,
198
        string $version
199
    ): AbstractMigration {
200
        $this->checkMigrationPath();
201
202
        $className = $this->getMigrationClassName($description, $version);
203
        $filename = sprintf(
204
            '%s_%s.php',
205
            $version,
206
            str_replace($version, '', Str::snake($className))
207
        );
208
        $fullPath = $this->migrationPath . $filename;
209
210
        $file = $this->filesystem->file($fullPath);
211
        $fullClasName = 'Platine\\Framework\\Migration\\' . $className;
212
213
        if (!$file->exists()) {
214
            throw new RuntimeException(sprintf(
215
                'Migration file [%s] does not exist',
216
                $fullPath
217
            ));
218
        }
219
220
        require_once $fullPath;
221
222
        if (!class_exists($fullClasName)) {
223
            throw new RuntimeException(sprintf(
224
                'Migration class [%s] does not exist',
225
                $fullClasName
226
            ));
227
        }
228
229
        $connection = $this->application->get(Connection::class);
230
231
        return new $fullClasName($connection);
232
    }
233
234
    /**
235
     * Return all migrations files available
236
     * @return array<string, string>
237
     */
238
    protected function getMigrations(): array
239
    {
240
        $this->checkMigrationPath();
241
242
        $directory = $this->filesystem->directory($this->migrationPath);
243
        $result = [];
244
        /** @var FileInterface[] $files */
245
        $files = $directory->read(DirectoryInterface::FILE);
246
        foreach ($files as $file) {
247
            $matches = [];
248
            if (preg_match('/^([0-9]+)_([a-z_]+)\.php$/i', $file->getName(), $matches)) {
249
                $result[$matches[1]] = $matches[2];
250
            }
251
        }
252
253
        ksort($result);
254
255
        return $result;
256
    }
257
258
    /**
259
     * Return the executed migration
260
     * @return array<string, Entity>
261
     */
262
    protected function getExecuted(): array
263
    {
264
        $this->checkMigrationTable();
265
266
        $migrations = $this->repository
267
                           ->query()
268
                           ->orderBy('version')
269
                           ->all();
270
        $result = [];
271
272
        foreach ($migrations as $entity) {
273
            $result[$entity->version] = $entity;
274
        }
275
276
        return $result;
277
    }
278
279
    /**
280
     * Return the migration class name for the given name
281
     * @param string $description
282
     * @param string $version
283
     * @return string
284
     */
285
    protected function getMigrationClassName(string $description, string $version): string
286
    {
287
        return Str::camel($description, false) . $version;
288
    }
289
}
290