Skip to content

Commit 26f7074

Browse files
Корректировка работы методов
1 parent c5994be commit 26f7074

File tree

4 files changed

+83
-32
lines changed

4 files changed

+83
-32
lines changed

README.md

+57-4
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,59 @@
2020
Компонент самостоятельно проверяет и создает необходимые (указанные) схемы, таблицы и папки при наличии заранее
2121
определенных разрешений (прав). Для корректной работы с базой данных необходимо заранее установить соединение с ней.
2222

23+
Для использования компонента достаточно создать экземпляр класса и вызвать нужный метод:
24+
25+
```php
26+
$sqlMigration = new SqlMigration($database, [
27+
'schema' => 'migrations',
28+
'table' => 'migration',
29+
'path' => 'migrations'
30+
]);
31+
32+
$sqlMigration->up();
33+
```
34+
35+
Для работы с консолью достаточно создать файл управления миграциями и вызвать его через `php FILE ACTION PARAMS`:
36+
37+
1. `php migrate up`
38+
2. `php migrate down 2`
39+
40+
Файл автоматической обработки таких запросов может выглядеть следующим образом:
41+
42+
```php
43+
#!/usr/bin/env php
44+
<?php
45+
declare(strict_types = 1);
46+
47+
use mepihindeveloper\components\{Console, ConsoleSqlMigration, Database};
48+
49+
require_once 'vendor/autoload.php';
50+
51+
$database = new Database([
52+
'dbms' => 'pgsql',
53+
'host' => 'localhost',
54+
'dbname' => 'php',
55+
'user' => 'www-data',
56+
'password' => 'pass'
57+
]);
58+
$database->connect();
59+
$sqlMigration = new ConsoleSqlMigration($database, [
60+
'schema' => 'migrations',
61+
'table' => 'migration',
62+
'path' => 'migrations'
63+
]);
64+
65+
$method = $argv[1];
66+
$params = $argv[2] ?? null;
67+
68+
if (!method_exists($sqlMigration, $method)) {
69+
Console::writeLine("Неопознанная команда '{$method}'", Console::FG_RED);
70+
exit;
71+
}
72+
73+
return is_null($params) ? $sqlMigration->$method() : $sqlMigration->$method($params);
74+
```
75+
2376
# Структура
2477

2578
```
@@ -41,15 +94,15 @@ src/
4194

4295
| Метод | Аргументы | Возвращаемые данные | Исключения | Описание |
4396
|-------------------------------------------------------------------|------------------------------------------------------------------------------------------------|---------------------|-----------------------------------------|-----------------------------------------------------------------------------|
44-
| public function up(int $count = 0) | $count Количество миграция (0 - относительно всех) | array | SqlMigrationException | Применяет указанное количество миграций |
45-
| public function down(int $count = 0) | $count Количество миграция (0 - относительно всех) | array | SqlMigrationException | Отменяет указанное количество миграций |
97+
| public function up(int $count = 0) | $count Количество миграций (0 - относительно всех) | array | SqlMigrationException | Применяет указанное количество миграций |
98+
| public function down(int $count = 0) | $count Количество миграций (0 - относительно всех) | array | SqlMigrationException | Отменяет указанное количество миграций |
4699
| public function history(int $limit = 0) | $limit Ограничение длины списка (null - полный список) | array | | Возвращает список сообщений о примененных миграций |
47-
| public function create(string $name) | $name Название миграции | bool | RuntimeException\|SqlMigrationException | Создает новую миграцию и возвращает сообщение об успешном создании миграции |
100+
| public function create(string $name) | $name Название миграции | void | RuntimeException\|SqlMigrationException | Создает новую миграцию и возвращает сообщение об успешном создании миграции |
48101
| __construct(DatabaseInterface $database, array $settings) | $database Компонент работы с базой данных; array $settings Массив настроек | | SqlMigrationException | Конструктор класса |
49102
| public function initSchemaAndTable() | | bool | SqlMigrationException | Создает схему и таблицу в случае их отсутствия |
50103
| public function __destruct() | | | | Деструктор класса |
51104
| protected function getNotAppliedList() | | array | | Возвращает список не примененных миграций |
52-
| protected function getHistoryList(int $limit = 0) | $limit Ограничение длины списка (null - полный список) | array | | Возвращает список примененных миграций |
105+
| protected function getHistoryList(int $limit = 0) | $limit Ограничение длины списка (0 - полный список) | array | | Возвращает список примененных миграций |
53106
| protected function execute(array $list, int $count, string $type) | $list Массив миграций; $count Количество миграций для применения; $type Тип миграции (up/down) | array | RuntimeException | Выполняет миграции |
54107
| protected function addHistory(string $name) | $name Наименование миграции | bool | SqlMigrationException | Добавляет запись в таблицу миграций |
55108
| protected function removeHistory(string $name) | $name Наименование миграции | bool | SqlMigrationException | Удаляет миграцию из таблицы миграций |

src/ConsoleSqlMigration.php

+10-9
Original file line numberDiff line numberDiff line change
@@ -40,16 +40,17 @@ public function up(int $count = 0): array {
4040
exit;
4141
}
4242

43-
foreach ($migrations['success'] as $successMigration) {
44-
Console::writeLine("Миграция {$successMigration['name']} успешно применена", Console::FG_GREEN);
43+
if (array_key_exists('success', $migrations)) {
44+
foreach ($migrations['success'] as $successMigration) {
45+
Console::writeLine("Миграция {$successMigration['name']} успешно применена", Console::FG_GREEN);
46+
}
4547
}
4648

4749
if (array_key_exists('error', $migrations)) {
4850
foreach ($migrations['error'] as $errorMigration) {
4951
Console::writeLine("Ошибка применения миграции {$errorMigration['name']}", Console::FG_RED);
52+
Console::writeLine($errorMigration['errorMessage'], Console::FG_WHITE);
5053
}
51-
52-
exit;
5354
}
5455

5556
return $migrations;
@@ -82,23 +83,23 @@ public function down(int $count = 0): array {
8283
return $migrations;
8384
}
8485

85-
public function create(string $name): bool {
86+
public function create(string $name): void {
8687
try {
8788
parent::create($name);
8889

8990
Console::writeLine("Миграция {$name} успешно создана");
9091
} catch (RuntimeException | SqlMigrationException $exception) {
9192
Console::writeLine($exception->getMessage(), Console::FG_RED);
92-
93-
return false;
9493
}
95-
96-
return true;
9794
}
9895

9996
public function history(int $limit = 0): array {
10097
$historyList = parent::history($limit);
10198

99+
if (empty($historyList)) {
100+
Console::writeLine('История миграций пуста');
101+
}
102+
102103
foreach ($historyList as $historyRow) {
103104
Console::writeLine($historyRow);
104105
}

src/SqlMigration.php

+10-13
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,9 @@ class SqlMigration implements SqlMigrationInterface {
2929
*/
3030
protected array $settings;
3131
/**
32-
* @var null|DatabaseInterface Компонент работы с базой данных
32+
* @var DatabaseInterface Компонент работы с базой данных
3333
*/
34-
protected ?DatabaseInterface $database;
34+
protected DatabaseInterface $database;
3535

3636
/**
3737
* SqlMigration constructor.
@@ -86,7 +86,6 @@ public function initSchemaAndTable(): bool {
8686

8787
public function __destruct() {
8888
$this->database->closeConnection();
89-
$this->database = null;
9089
}
9190

9291
/**
@@ -99,10 +98,7 @@ public function up(int $count = 0): array {
9998
return [];
10099
}
101100

102-
$executeListCount = count($executeList);
103-
$executeCount = $count === 0 ? $executeListCount : min($count, $executeListCount);
104-
105-
return $this->execute($executeList, $executeCount, self::UP);
101+
return $this->execute($executeList, $count, self::UP);
106102
}
107103

108104
/**
@@ -175,9 +171,12 @@ protected function getHistoryList(int $limit = 0): array {
175171
* @throws RuntimeException
176172
*/
177173
protected function execute(array $list, int $count, string $type): array {
174+
$executeListCount = count($list);
175+
$executeCount = $count === 0 ? $executeListCount : min($count, $executeListCount);
176+
178177
$migrationInfo = [];
179178

180-
for ($index = 0; $index < $count; $index++) {
179+
for ($index = 0; $index < $executeCount; $index++) {
181180
$migration = $list[$index];
182181
$migration['path'] = array_key_exists('path', $migration) ? $migration['path'] :
183182
"{$this->settings['path']}/{$migration['name']}";
@@ -227,7 +226,7 @@ protected function addHistory(string $name): bool {
227226
SQL;
228227

229228
if (!$this->database->execute($sql, ['name' => $name, 'apply_time' => time()])) {
230-
throw new SqlMigrationException("Ошибка применения миграция {$name}");
229+
throw new SqlMigrationException("Ошибка применения миграции {$name}");
231230
}
232231

233232
return true;
@@ -278,7 +277,7 @@ public function history(int $limit = 0): array {
278277
$historyList = $this->getHistoryList($limit);
279278

280279
if (empty($historyList)) {
281-
return ['История миграций пуста'];
280+
return [];
282281
}
283282

284283
$messages = [];
@@ -295,7 +294,7 @@ public function history(int $limit = 0): array {
295294
*
296295
* @throws RuntimeException|SqlMigrationException
297296
*/
298-
public function create(string $name): bool {
297+
public function create(string $name): void {
299298
$this->validateName($name);
300299

301300
$migrationMame = $this->generateName($name);
@@ -312,8 +311,6 @@ public function create(string $name): bool {
312311
if (!file_put_contents($path . '/down.sql', '') === false) {
313312
throw new RuntimeException("Ошибка создания файла миграции {$path}/down.sql");
314313
}
315-
316-
return true;
317314
}
318315

319316
/**

src/interfaces/SqlMigrationInterface.php

+6-6
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ interface SqlMigrationInterface {
1919
/**
2020
* Применяет указанное количество миграций
2121
*
22-
* @param int $count Количество миграция (0 - относительно всех)
22+
* @param int $count Количество миграций (0 - относительно всех)
2323
*
24-
* @return array Возвращает список применения и ошибочных миграций. Список может иметь вид:
24+
* @return array Возвращает список примененных и ошибочных миграций. Список может иметь вид:
2525
* 1. Случай, когда отсутствуют миграции для выполнения, то возвращается пустой массив
2626
* 2. Когда присутствуют миграции для выполнения:
2727
* [
@@ -37,7 +37,7 @@ public function up(int $count = 0): array;
3737
/**
3838
* Отменяет указанное количество миграций
3939
*
40-
* @param int $count Количество миграция (0 - относительно всех)
40+
* @param int $count Количество миграций (0 - относительно всех)
4141
*
4242
* @return array Возвращает список отменных и ошибочных миграций. Список может иметь вид:
4343
* 1. Случай, когда отсутствуют миграции для выполнения, то возвращается пустой массив
@@ -55,7 +55,7 @@ public function down(int $count = 0): array;
5555
/**
5656
* Возвращает список сообщений о примененных миграций
5757
*
58-
* @param int $limit Ограничение длины списка (null - полный список)
58+
* @param int $limit Ограничение длины списка (0 - полный список)
5959
*
6060
* @return array
6161
*/
@@ -66,9 +66,9 @@ public function history(int $limit = 0): array;
6666
*
6767
* @param string $name Название миграции
6868
*
69-
* @return bool Возвращает true, если миграция была успешно создана. В остальных случаях выкидывает исключение
69+
* @return void
7070
*
7171
* @throws RuntimeException|SqlMigrationException
7272
*/
73-
public function create(string $name): bool;
73+
public function create(string $name): void;
7474
}

0 commit comments

Comments
 (0)