Skip to content

Commit

Permalink
Refactoring (#216)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tigrov committed Oct 17, 2023
1 parent 940d988 commit 176070a
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 30 deletions.
2 changes: 2 additions & 0 deletions src/Migrator.php
Expand Up @@ -78,6 +78,7 @@ public function getMigrationNameLimit(): ?int
return $this->migrationNameLimit = $limit;
}

/** @psalm-return array<string, int|string> */
public function getHistory(?int $limit = null): array
{
$this->checkMigrationHistoryTable();
Expand All @@ -92,6 +93,7 @@ public function getHistory(?int $limit = null): array
$query->limit($limit);
}

/** @psalm-var array<string, int|string> */
return $query->column();
}

Expand Down
34 changes: 17 additions & 17 deletions src/Service/Generate/FieldsParser.php
Expand Up @@ -4,7 +4,14 @@

namespace Yiisoft\Db\Migration\Service\Generate;

use function array_shift;
use function array_unshift;
use function explode;
use function in_array;
use function preg_match;
use function preg_split;
use function str_replace;
use function str_starts_with;

/**
* @internal
Expand Down Expand Up @@ -33,30 +40,30 @@ public function parse(
/** @psalm-var string[] $fields */
foreach ($fields as $field) {
$chunks = $this->splitFieldIntoChunks($field);
$property = (string) array_shift($chunks);
$column = (string) array_shift($chunks);

/** @psalm-var string[] $chunks */
foreach ($chunks as $i => $chunk) {
if (str_starts_with($chunk, 'foreignKey')) {
preg_match('/foreignKey\((\w*)\s?(\w*)\)/', $chunk, $matches);
$foreignKeys[] = $this->foreignKeyFactory->create(
$table,
$property,
$matches[1] ?? preg_replace('/_id$/', '', $property),
$column,
$matches[1] ?? preg_replace('/_id$/', '', $column),
empty($matches[2]) ? null : $matches[2]
);

unset($chunks[$i]);
continue;
}

if (!preg_match('/^(.+?)\(([^(]+)\)$/', $chunk)) {
if (!preg_match('/\(([^(]+)\)$/', $chunk)) {
$chunks[$i] .= '()';
}
}

/** @psalm-var string[] $chunks */
$columns[] = new Column($property, $chunks);
$columns[] = new Column($column, $chunks);
}
}

Expand All @@ -71,21 +78,17 @@ private function splitFieldIntoChunks(string $field): array
{
$defaultValue = '';
$originalDefaultValue = '';
$hasDoubleQuotes = false;

preg_match_all('/defaultValue\(.*?:.*?\)/', $field, $matches);

if (isset($matches[0][0])) {
$hasDoubleQuotes = true;
$originalDefaultValue = $matches[0][0];
if (preg_match('/defaultValue\(.*?:.*?\)/', $field, $matches) === 1) {
$originalDefaultValue = $matches[0];
$defaultValue = str_replace(':', '{{colon}}', $originalDefaultValue);
$field = str_replace($originalDefaultValue, $defaultValue, $field);
}

/** @var string[] $chunks */
$chunks = preg_split('/\s?:\s?/', $field);
$chunks = preg_split('/\s?:\s?/', $field, -1, PREG_SPLIT_NO_EMPTY);

if ($hasDoubleQuotes) {
if ($defaultValue !== '') {
foreach ($chunks as $key => $chunk) {
$chunks[$key] = str_replace($defaultValue, $originalDefaultValue, $chunk);
}
Expand All @@ -107,9 +110,6 @@ private function addDefaultPrimaryKey(array &$columns): void
}
}

array_unshift(
$columns,
new Column('id', ['primaryKey()']),
);
array_unshift($columns, new Column('id', ['primaryKey()']));
}
}
3 changes: 1 addition & 2 deletions src/Service/Generate/ForeignKeyFactory.php
Expand Up @@ -37,8 +37,7 @@ public function create(
$tablePrimaryKeys = $this->db->getSchema()->getTablePrimaryKey($relatedTable);

if ($tablePrimaryKeys !== null) {
$columNames = $tablePrimaryKeys->getColumnNames() ?? [];
$primaryKeys = is_string($columNames) ? [$columNames] : $columNames;
$primaryKeys = (array) $tablePrimaryKeys->getColumnNames();

match (count($primaryKeys)) {

Check warning on line 42 in src/Service/Generate/ForeignKeyFactory.php

View workflow job for this annotation

GitHub Actions / PHP 8-ubuntu-latest

Escaped Mutant for Mutator "MatchArmRemoval": --- Original +++ New @@ @@ if ($tablePrimaryKeys !== null) { $primaryKeys = (array) $tablePrimaryKeys->getColumnNames(); match (count($primaryKeys)) { - 1 => $relatedColumn = (string) $primaryKeys[0], default => $this->io?->writeln("<fg=yellow> Related table for field \"{$column}\" exists, but primary key is composite. Default name \"id\" will be used for related field</>\n"), }; } else {
1 => $relatedColumn = (string) $primaryKeys[0],
Expand Down
28 changes: 18 additions & 10 deletions src/Service/Generate/PhpRenderer.php
Expand Up @@ -6,27 +6,27 @@

use Throwable;

use function extract;
use function ob_clean;
use function ob_end_clean;
use function ob_get_clean;
use function ob_get_level;
use function ob_implicit_flush;
use function ob_start;

/**
* @internal
*/
final class PhpRenderer
{
public function render(string $file, array $params = []): string
{
/** @psalm-suppress MissingClosureReturnType */
$renderer = function () {
/** @psalm-suppress MixedArgument */
extract(func_get_arg(1), EXTR_OVERWRITE);
/** @psalm-suppress UnresolvableInclude */
require func_get_arg(0);
};

$obInitialLevel = ob_get_level();
ob_start();
ob_implicit_flush(false);

try {
/** @psalm-suppress PossiblyInvalidFunctionCall,PossiblyNullFunctionCall */
$renderer->bindTo($this)($file, $params);
$this->renderer($file, $params);
return ob_get_clean();
} catch (Throwable $e) {
while (ob_get_level() > $obInitialLevel) {
Expand All @@ -37,4 +37,12 @@ public function render(string $file, array $params = []): string
throw $e;
}
}

private function renderer(): void
{
/** @psalm-suppress MixedArgument */
extract(func_get_arg(1));
/** @psalm-suppress UnresolvableInclude */
require func_get_arg(0);
}
}
2 changes: 1 addition & 1 deletion src/Service/MigrationService.php
Expand Up @@ -112,7 +112,7 @@ public function getNewMigrations(): array
$applied = [];

foreach ($this->migrator->getHistory() as $class => $time) {
$applied[trim((string) $class, '\\')] = true;
$applied[trim($class, '\\')] = true;
}

$migrationPaths = [];
Expand Down

0 comments on commit 176070a

Please sign in to comment.