diff --git a/.github/workflows/build-mysql5.yml b/.github/workflows/build-mysql5.yml index b39bc09..a4bd766 100644 --- a/.github/workflows/build-mysql5.yml +++ b/.github/workflows/build-mysql5.yml @@ -30,7 +30,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Install PHP uses: shivammathur/setup-php@v2 diff --git a/.github/workflows/build-mysql8.yml b/.github/workflows/build-mysql8.yml index 1f26be3..2ee874f 100644 --- a/.github/workflows/build-mysql8.yml +++ b/.github/workflows/build-mysql8.yml @@ -30,7 +30,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Install PHP uses: shivammathur/setup-php@v2 diff --git a/.github/workflows/build-pgsql.yml b/.github/workflows/build-pgsql.yml index 3d869a2..c328e21 100644 --- a/.github/workflows/build-pgsql.yml +++ b/.github/workflows/build-pgsql.yml @@ -28,7 +28,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Install PHP uses: shivammathur/setup-php@v2 diff --git a/.github/workflows/build-sqlite.yml b/.github/workflows/build-sqlite.yml index a5b8de8..76f35d1 100644 --- a/.github/workflows/build-sqlite.yml +++ b/.github/workflows/build-sqlite.yml @@ -17,7 +17,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Install PHP uses: shivammathur/setup-php@v2 diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml index f48ed35..4a7ae2b 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -38,7 +38,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Install PHP uses: shivammathur/setup-php@v2 diff --git a/.github/workflows/static-anal.yml b/.github/workflows/static-anal.yml index 9f87758..d9293ea 100644 --- a/.github/workflows/static-anal.yml +++ b/.github/workflows/static-anal.yml @@ -16,7 +16,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Install PHP uses: shivammathur/setup-php@v2 diff --git a/composer.json b/composer.json index b22584c..3eb9cef 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,7 @@ "require-dev": { "infection/infection": "*", "phpstan/phpstan": "*", - "phpunit/phpunit": "*", + "phpunit/phpunit": "<10.0", "roave/security-advisories": "dev-latest" }, "autoload": { diff --git a/phpunit-no-yii-autoload.xml.dist b/phpunit-no-yii-autoload.xml.dist index f9b0141..fc361d3 100644 --- a/phpunit-no-yii-autoload.xml.dist +++ b/phpunit-no-yii-autoload.xml.dist @@ -1,14 +1,17 @@ - - - - ./tests - - + + + + ./src + + + ./src/dummy + ./src/views + + + + + ./tests + + diff --git a/phpunit.xml.dist b/phpunit.xml.dist index cf5ac75..363d57d 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,23 +1,17 @@ - - - - ./tests - - - - - ./src - - ./src/dummy - ./src/views - - - + + + + ./src + + + ./src/dummy + ./src/views + + + + + ./tests + + diff --git a/src/Arranger.php b/src/Arranger.php index ed2caf7..34b922c 100644 --- a/src/Arranger.php +++ b/src/Arranger.php @@ -6,12 +6,6 @@ use yii\base\NotSupportedException; -use function array_diff; -use function array_key_exists; -use function array_merge_recursive; -use function array_unique; -use function count; - final class Arranger implements ArrangerInterface { /** @var TableMapperInterface */ @@ -49,12 +43,10 @@ public function arrangeTables(array $inputTables): void /** * Adds dependency of the table. - * @param string $table - * @param string|null $dependsOnTable */ private function addDependency(string $table, string $dependsOnTable = null): void { - if (!array_key_exists($table, $this->dependencies)) { + if (!\array_key_exists($table, $this->dependencies)) { $this->dependencies[$table] = []; } @@ -92,7 +84,7 @@ public function getReferencesToPostpone(): array } } - return array_unique($flattenedReferencesToPostpone); + return \array_unique($flattenedReferencesToPostpone); } /** @@ -104,21 +96,21 @@ private function arrangeDependencies(array $input): void $order = []; $checkList = []; - $inputCount = count($input); + $inputCount = \count($input); - while ($inputCount > count($order)) { + while ($inputCount > \count($order)) { $done = false; $lastCheckedName = $lastCheckedDependency = null; foreach ($input as $name => $dependencies) { - if (array_key_exists($name, $checkList)) { + if (\array_key_exists($name, $checkList)) { continue; } $resolved = true; foreach ($dependencies as $dependency) { - if (!array_key_exists($dependency, $checkList)) { + if (!\array_key_exists($dependency, $checkList)) { $resolved = false; $lastCheckedName = $name; $lastCheckedDependency = $dependency; @@ -135,7 +127,7 @@ private function arrangeDependencies(array $input): void } if ($done === false) { - $input[$lastCheckedName] = array_diff($input[$lastCheckedName], [$lastCheckedDependency]); + $input[$lastCheckedName] = \array_diff($input[$lastCheckedName], [$lastCheckedDependency]); $this->arrangeDependencies($input); $order = $this->getTablesInOrder(); diff --git a/src/Comparator.php b/src/Comparator.php index 2e827c8..ce8d0a6 100644 --- a/src/Comparator.php +++ b/src/Comparator.php @@ -13,13 +13,6 @@ use yii\base\NotSupportedException; use yii\helpers\Json; -use function count; -use function in_array; -use function is_string; -use function preg_match; -use function strpos; -use function substr; - final class Comparator implements ComparatorInterface { /** @var bool */ @@ -32,12 +25,7 @@ public function __construct(bool $generalSchema) /** * Compares migration virtual structure with database structure and gathers required modifications. - * @param StructureInterface $newStructure - * @param StructureInterface $oldStructure - * @param BlueprintInterface $blueprint * @param bool $onlyShow whether changes should be only displayed - * @param string|null $schema - * @param string|null $engineVersion * @throws NotSupportedException */ public function compare( @@ -62,12 +50,6 @@ public function compare( /** * Compares the columns between new and old structure. - * @param StructureInterface $newStructure - * @param StructureInterface $oldStructure - * @param BlueprintInterface $blueprint - * @param bool $onlyShow - * @param string|null $schema - * @param string|null $engineVersion * @throws NotSupportedException */ private function compareColumns( @@ -86,7 +68,7 @@ private function compareColumns( /** @var ColumnInterface $column */ /** @var string $name */ foreach ($newColumns as $name => $column) { - if (!array_key_exists($name, $oldColumns)) { + if (!\array_key_exists($name, $oldColumns)) { $blueprint->addDescription("missing column '$name'"); if ($previousColumn) { $column->setAfter($previousColumn); @@ -131,10 +113,10 @@ private function compareColumns( $oldProperty = $oldColumn->$propertyFetch(); $newProperty = $column->$propertyFetch(); } - if (!is_bool($oldProperty) && $oldProperty !== null && !is_array($oldProperty)) { + if (!\is_bool($oldProperty) && $oldProperty !== null && !\is_array($oldProperty)) { $oldProperty = (string)$oldProperty; } - if (!is_bool($newProperty) && $newProperty !== null && !is_array($newProperty)) { + if (!\is_bool($newProperty) && $newProperty !== null && !\is_array($newProperty)) { $newProperty = (string)$newProperty; } if ($oldProperty !== $newProperty) { @@ -184,7 +166,7 @@ private function compareColumns( } foreach ($oldColumns as $name => $column) { - if (!array_key_exists($name, $newColumns)) { + if (!\array_key_exists($name, $newColumns)) { $blueprint->addDescription("excessive column '$name'"); if ($schema === Schema::SQLITE) { $blueprint->addDescription( @@ -202,11 +184,6 @@ private function compareColumns( /** * Compares the foreign keys between new and old structure. - * @param StructureInterface $newStructure - * @param StructureInterface $oldStructure - * @param BlueprintInterface $blueprint - * @param bool $onlyShow - * @param string|null $schema * @throws NotSupportedException */ private function compareForeignKeys( @@ -219,7 +196,7 @@ private function compareForeignKeys( $newForeignKeys = $newStructure->getForeignKeys(); $oldForeignKeys = $oldStructure->getForeignKeys(); foreach ($newForeignKeys as $name => $foreignKey) { - if (!array_key_exists($name, $oldForeignKeys)) { + if (!\array_key_exists($name, $oldForeignKeys)) { $blueprint->addDescription("missing foreign key '$name'"); if ($schema === Schema::SQLITE) { @@ -242,8 +219,8 @@ private function compareForeignKeys( $oldForeignKeyColumns = $oldForeignKey->getColumns(); if ( - array_diff($newForeignKeyColumns, $oldForeignKeyColumns) - !== array_diff($oldForeignKeyColumns, $newForeignKeyColumns) + \array_diff($newForeignKeyColumns, $oldForeignKeyColumns) + !== \array_diff($oldForeignKeyColumns, $newForeignKeyColumns) ) { $blueprint->addDescription( "different foreign key '$name' columns (" @@ -270,8 +247,8 @@ private function compareForeignKeys( $oldForeignKeyReferredColumns = $oldForeignKey->getReferredColumns(); if ( - array_diff($newForeignKeyReferredColumns, $oldForeignKeyReferredColumns) - !== array_diff($oldForeignKeyReferredColumns, $newForeignKeyReferredColumns) + \array_diff($newForeignKeyReferredColumns, $oldForeignKeyReferredColumns) + !== \array_diff($oldForeignKeyReferredColumns, $newForeignKeyReferredColumns) ) { $blueprint->addDescription( "different foreign key '$name' referred columns (" @@ -360,7 +337,7 @@ private function compareForeignKeys( } foreach ($oldForeignKeys as $name => $foreignKey) { - if (!array_key_exists($name, $newForeignKeys)) { + if (!\array_key_exists($name, $newForeignKeys)) { $blueprint->addDescription("excessive foreign key '$name'"); if ($schema === Schema::SQLITE) { @@ -379,11 +356,6 @@ private function compareForeignKeys( /** * Compares the primary keys between new and old structure. - * @param PrimaryKeyInterface|null $newPrimaryKey - * @param PrimaryKeyInterface|null $oldPrimaryKey - * @param BlueprintInterface $blueprint - * @param bool $onlyShow - * @param string|null $schema * @throws NotSupportedException */ private function comparePrimaryKeys( @@ -398,13 +370,13 @@ private function comparePrimaryKeys( $newPrimaryKeyColumns = $newPrimaryKey ? $newPrimaryKey->getColumns() : []; $oldPrimaryKeyColumns = $oldPrimaryKey ? $oldPrimaryKey->getColumns() : []; - $differentColumns = array_diff($newPrimaryKeyColumns, $oldPrimaryKeyColumns); + $differentColumns = \array_diff($newPrimaryKeyColumns, $oldPrimaryKeyColumns); - if ($differentColumns !== array_diff($oldPrimaryKeyColumns, $newPrimaryKeyColumns)) { + if ($differentColumns !== \array_diff($oldPrimaryKeyColumns, $newPrimaryKeyColumns)) { $blueprint->addDescription('different primary key definition'); $alreadyDropped = false; - if (count($oldPrimaryKeyColumns)) { + if (!empty($oldPrimaryKeyColumns)) { if ($schema === Schema::SQLITE) { $blueprint->addDescription( '(!) DROP PRIMARY KEY is not supported by SQLite: Migration must be created manually' @@ -419,7 +391,7 @@ private function comparePrimaryKeys( $blueprint->dropPrimaryKey($oldPrimaryKey); } - $newPrimaryKeyColumnsCount = count($newPrimaryKeyColumns); + $newPrimaryKeyColumnsCount = \count($newPrimaryKeyColumns); if ($this->shouldPrimaryKeyBeAdded($blueprint, $differentColumns, $newPrimaryKeyColumnsCount, $schema)) { if ($schema === Schema::SQLITE) { if ($alreadyDropped === false) { @@ -442,8 +414,6 @@ private function comparePrimaryKeys( /** * Removes excessive primary key statements from the column in case the primary key will be added separately anyway. - * @param BlueprintInterface $blueprint - * @param string|null $schema */ private function removeExcessivePrimaryKeyStatements(BlueprintInterface $blueprint, ?string $schema): void { @@ -458,11 +428,7 @@ private function removeExcessivePrimaryKeyStatements(BlueprintInterface $bluepri /** * Checks whether the separate primary key needs to be added. - * @param BlueprintInterface $blueprint * @param array $differentColumns - * @param int $newColumnsCount - * @param string|null $schema - * @return bool */ private function shouldPrimaryKeyBeAdded( BlueprintInterface $blueprint, @@ -473,7 +439,7 @@ private function shouldPrimaryKeyBeAdded( if ($newColumnsCount === 0) { return false; } - if ($newColumnsCount === 1 && count($differentColumns) === 1) { + if ($newColumnsCount === 1 && \count($differentColumns) === 1) { foreach ($blueprint->getAddedColumns() as $name => $column) { if ($name === $differentColumns[0] && $column->isPrimaryKeyInfoAppended($schema)) { return false; @@ -494,9 +460,6 @@ private function shouldPrimaryKeyBeAdded( /** * Compares the indexes between new and old structure. - * @param StructureInterface $newStructure - * @param StructureInterface $oldStructure - * @param BlueprintInterface $blueprint */ private function compareIndexes( StructureInterface $newStructure, @@ -507,11 +470,11 @@ private function compareIndexes( $oldIndexes = $oldStructure->getIndexes(); foreach ($newIndexes as $name => $index) { - if (!array_key_exists($name, $oldIndexes)) { + if (!\array_key_exists($name, $oldIndexes)) { $indexColumns = $index->getColumns(); if ( $index->isUnique() - && count($indexColumns) === 1 + && \count($indexColumns) === 1 && ($newIndexColumn = $newStructure->getColumn($indexColumns[0])) && $newIndexColumn->isUnique() && ($oldIndexColumn = $oldStructure->getColumn($indexColumns[0])) @@ -551,7 +514,7 @@ private function compareIndexes( $newIndexColumns = $index->getColumns(); $oldIndexColumns = $oldIndex->getColumns(); - if (array_diff($newIndexColumns, $oldIndexColumns) !== array_diff($oldIndexColumns, $newIndexColumns)) { + if (\array_diff($newIndexColumns, $oldIndexColumns) !== \array_diff($oldIndexColumns, $newIndexColumns)) { $blueprint->addDescription( "different index '$name' columns (DB: " . $this->stringifyValue($newIndexColumns) . ') != MIG: (' @@ -563,7 +526,7 @@ private function compareIndexes( } foreach ($oldIndexes as $name => $index) { - if (!array_key_exists($name, $newIndexes)) { + if (!\array_key_exists($name, $newIndexes)) { $blueprint->addDescription("excessive index '$name'"); $blueprint->dropIndex($index); } @@ -573,9 +536,6 @@ private function compareIndexes( /** * Checks if append statements are the same in new and old structure. * Compares the actual statements and potential ones. - * @param ColumnInterface $newColumn - * @param ColumnInterface $oldColumn - * @return bool */ private function isAppendSame(ColumnInterface $newColumn, ColumnInterface $oldColumn): bool { @@ -602,7 +562,6 @@ private function isAppendSame(ColumnInterface $newColumn, ColumnInterface $oldCo /** * Strips append string from primary key and autoincrement constraints. - * @param string|null $append * @return array */ private function stripAppend(?string $append): array @@ -611,27 +570,27 @@ private function stripAppend(?string $append): array $primaryKey = false; if ($append !== null) { - if (strpos($append, 'AUTO_INCREMENT') !== false) { + if (\strpos($append, 'AUTO_INCREMENT') !== false) { $autoIncrement = true; - $append = str_replace('AUTO_INCREMENT', '', $append); + $append = \str_replace('AUTO_INCREMENT', '', $append); } - if (strpos($append, 'AUTOINCREMENT') !== false) { + if (\strpos($append, 'AUTOINCREMENT') !== false) { $autoIncrement = true; - $append = str_replace('AUTOINCREMENT', '', $append); + $append = \str_replace('AUTOINCREMENT', '', $append); } - if (strpos($append, 'IDENTITY PRIMARY KEY') !== false) { + if (\strpos($append, 'IDENTITY PRIMARY KEY') !== false) { $primaryKey = true; - $append = str_replace('IDENTITY PRIMARY KEY', '', $append); + $append = \str_replace('IDENTITY PRIMARY KEY', '', $append); } - if (strpos($append, 'PRIMARY KEY') !== false) { + if (\strpos($append, 'PRIMARY KEY') !== false) { $primaryKey = true; - $append = str_replace('PRIMARY KEY', '', $append); + $append = \str_replace('PRIMARY KEY', '', $append); } - $append = trim($append); + $append = \trim($append); if ($append === '') { $append = null; } @@ -642,17 +601,13 @@ private function stripAppend(?string $append): array /** * Checks if columns' uniqueness is the same because of the unique index. - * @param StructureInterface $structure - * @param string $columnName - * @param bool $unique - * @return bool */ private function getRealUniqueness(StructureInterface $structure, string $columnName, bool $unique): bool { if ($unique) { foreach ($structure->getIndexes() as $index) { $indexColumns = $index->getColumns(); - if ($index->isUnique() && count($indexColumns) === 1 && in_array($columnName, $indexColumns, true)) { + if ($index->isUnique() && \count($indexColumns) === 1 && \in_array($columnName, $indexColumns, true)) { return false; } } @@ -665,24 +620,23 @@ private function getRealUniqueness(StructureInterface $structure, string $column * Checks if length has the same value but written differently. * @param mixed $newLength * @param mixed $oldLength - * @return bool */ private function isLengthSame($newLength, $oldLength): bool { $normalizedNew = $newLength; if ( - is_string($newLength) - && ($commaPosition = strpos($newLength, ',')) !== false - && preg_match('/,\s?0$/', $newLength) + \is_string($newLength) + && ($commaPosition = \strpos($newLength, ',')) !== false + && \preg_match('/,\s?0$/', $newLength) ) { $normalizedNew = substr($newLength, 0, $commaPosition); } $normalizedOld = $oldLength; if ( - is_string($oldLength) - && ($commaPosition = strpos($oldLength, ',')) !== false - && preg_match('/,\s?0$/', $oldLength)) { - $normalizedOld = substr($oldLength, 0, $commaPosition); + \is_string($oldLength) + && ($commaPosition = \strpos($oldLength, ',')) !== false + && \preg_match('/,\s?0$/', $oldLength)) { + $normalizedOld = \substr($oldLength, 0, $commaPosition); } return $normalizedNew === $normalizedOld; } @@ -690,7 +644,6 @@ private function isLengthSame($newLength, $oldLength): bool /** * Returns values as strings. * @param mixed $value - * @return string */ private function stringifyValue($value): string { @@ -706,10 +659,10 @@ private function stringifyValue($value): string return 'FALSE'; } - if (is_array($value)) { + if (\is_array($value)) { return Json::encode($value); } - return '"' . str_replace('"', '\"', $value) . '"'; + return '"' . \str_replace('"', '\"', $value) . '"'; } } diff --git a/src/ComparatorInterface.php b/src/ComparatorInterface.php index f8f7ffc..06f2a42 100644 --- a/src/ComparatorInterface.php +++ b/src/ComparatorInterface.php @@ -12,12 +12,7 @@ interface ComparatorInterface { /** * Compares migration virtual structure with database structure and gathers required modifications. - * @param StructureInterface $newStructure - * @param StructureInterface $oldStructure - * @param BlueprintInterface $blueprint * @param bool $onlyShow whether changes should be only displayed - * @param string|null $schema - * @param string|null $engineVersion * @throws NotSupportedException */ public function compare( diff --git a/src/Extractor.php b/src/Extractor.php index 5d0f56c..31ce878 100644 --- a/src/Extractor.php +++ b/src/Extractor.php @@ -12,9 +12,6 @@ use yii\base\InvalidArgumentException; use yii\db\Connection; -use function file_exists; -use function strpos; - final class Extractor implements SqlExtractorInterface { /** @var Connection */ @@ -37,7 +34,6 @@ public function __construct(Connection $db, bool $experimental = false) /** * Extracts migration data structures. - * @param string $migration * @param string[] $migrationPaths * @throws ErrorException */ @@ -47,7 +43,7 @@ public function extract(string $migration, array $migrationPaths): void $this->loadFile($migration, $migrationPaths); $subject = new $migration(['db' => $this->db, 'experimental' => $this->experimental]); - if ($subject instanceof MigrationChangesInterface === false) { + if (!$subject instanceof MigrationChangesInterface) { throw new ErrorException( "Class '{$migration}' must implement bizley\migration\dummy\MigrationChangesInterface." ); @@ -59,13 +55,12 @@ public function extract(string $migration, array $migrationPaths): void /** * Loads a non-namespaced file. - * @param string $migration * @param string[] $migrationPaths * @throws ErrorException */ private function loadFile(string $migration, array $migrationPaths): void { - if (strpos($migration, '\\') !== false) { + if (\strpos($migration, '\\') !== false) { // migration with `\` character is most likely namespaced, so it doesn't require loading return; } @@ -73,7 +68,7 @@ private function loadFile(string $migration, array $migrationPaths): void foreach ($migrationPaths as $path) { /** @var string $file */ $file = Yii::getAlias($path . DIRECTORY_SEPARATOR . $migration . '.php'); - if (file_exists($file)) { + if (\file_exists($file)) { require_once $file; return; @@ -93,7 +88,7 @@ private function setDummyMigrationClass(bool $sqlDummy = false): void // attempt to register Yii's autoloader in case it's not been done already // registering it second time should be skipped anyway /** @infection-ignore-all */ - spl_autoload_register(['Yii', 'autoload'], true, true); + \spl_autoload_register(['Yii', 'autoload'], true, true); Yii::$classMap['yii\db\Migration'] = Yii::getAlias( $sqlDummy ? '@bizley/migration/dummy/MigrationSql.php' : '@bizley/migration/dummy/MigrationChanges.php' diff --git a/src/ExtractorInterface.php b/src/ExtractorInterface.php index 1a1d3e0..df4a1ee 100644 --- a/src/ExtractorInterface.php +++ b/src/ExtractorInterface.php @@ -11,7 +11,6 @@ interface ExtractorInterface { /** * Extracts migration data structures. - * @param string $migration * @param array $migrationPaths * @throws ErrorException */ diff --git a/src/Generator.php b/src/Generator.php index 7306dcc..fa14078 100644 --- a/src/Generator.php +++ b/src/Generator.php @@ -11,8 +11,6 @@ use yii\base\View; use yii\helpers\FileHelper; -use function array_reverse; - final class Generator implements GeneratorInterface { /** @var TableMapperInterface */ @@ -36,7 +34,6 @@ public function __construct( /** * Returns the translated alias of create table migration template. - * @return string */ public function getCreateTableMigrationTemplate(): string { @@ -47,7 +44,6 @@ public function getCreateTableMigrationTemplate(): string /** * Returns the translated alias of create foreign keys migration template. - * @return string */ public function getCreateForeignKeysMigrationTemplate(): string { @@ -58,8 +54,6 @@ public function getCreateForeignKeysMigrationTemplate(): string /** * Returns the normalized namespace (in case it uses incorrect slashes). - * @param string|null $namespace - * @return string|null */ private function getNormalizedNamespace(?string $namespace): ?string { @@ -68,13 +62,7 @@ private function getNormalizedNamespace(?string $namespace): ?string /** * Generates migration for the table. - * @param string $tableName - * @param string $migrationName * @param array $referencesToPostpone - * @param bool $usePrefix - * @param string $dbPrefix - * @param string|null $namespace - * @return string * @throws TableMissingException * @throws NotSupportedException */ @@ -122,11 +110,6 @@ public function getSuppressedForeignKeys(): array /** * Generates the migration for the foreign keys. * @param array $foreignKeys - * @param string $migrationName - * @param bool $usePrefix - * @param string $dbPrefix - * @param string|null $namespace - * @return string */ public function generateForForeignKeys( array $foreignKeys, @@ -147,7 +130,7 @@ public function generateForForeignKeys( $dbPrefix ), 'bodyDown' => $this->structureRenderer->renderForeignKeysDown( - array_reverse($foreignKeys), + \array_reverse($foreignKeys), 8, $usePrefix, $dbPrefix diff --git a/src/GeneratorInterface.php b/src/GeneratorInterface.php index 8545c82..0d11a14 100644 --- a/src/GeneratorInterface.php +++ b/src/GeneratorInterface.php @@ -11,13 +11,7 @@ interface GeneratorInterface { /** * Generates migration for the table. - * @param string $tableName - * @param string $migrationName * @param array $referencesToPostpone - * @param bool $usePrefix - * @param string $dbPrefix - * @param string|null $namespace - * @return string * @throws TableMissingException * @throws NotSupportedException */ @@ -33,11 +27,6 @@ public function generateForTable( /** * Generates the migration for the foreign keys. * @param array $foreignKeys - * @param string $migrationName - * @param bool $usePrefix - * @param string $dbPrefix - * @param string|null $namespace - * @return string */ public function generateForForeignKeys( array $foreignKeys, diff --git a/src/HistoryManager.php b/src/HistoryManager.php index cc0a31c..2c2f8be 100644 --- a/src/HistoryManager.php +++ b/src/HistoryManager.php @@ -5,18 +5,13 @@ namespace bizley\migration; use yii\base\NotSupportedException; +use yii\console\controllers\BaseMigrateController; use yii\console\controllers\MigrateController; use yii\db\Connection; use yii\db\Exception; use yii\db\Query; use yii\helpers\ArrayHelper; -use function preg_match; -use function str_replace; -use function strcasecmp; -use function time; -use function usort; - final class HistoryManager implements HistoryManagerInterface { /** @var Connection */ @@ -65,8 +60,6 @@ private function createTable(): void /** * Adds migration history entry. - * @param string $migrationName - * @param string|null $namespace * @throws Exception * @throws NotSupportedException */ @@ -82,7 +75,7 @@ public function addHistory(string $migrationName, string $namespace = null): voi $this->historyTable, [ 'version' => ($namespace ? $namespace . '\\' : '') . $migrationName, - 'apply_time' => time(), + 'apply_time' => \time(), ] ) ->execute(); @@ -109,12 +102,12 @@ public function fetchHistory(): array $history = []; foreach ($rows as $row) { - if ($row['version'] === MigrateController::BASE_MIGRATION) { + if ($row['version'] === BaseMigrateController::BASE_MIGRATION) { continue; } - if (preg_match('/m?(\d{6}_?\d{6})(\D.*)?/i', $row['version'], $matches)) { - $row['canonicalVersion'] = str_replace('_', '', $matches[1]); + if (\preg_match('/m?(\d{6}_?\d{6})(\D.*)?/i', $row['version'], $matches)) { + $row['canonicalVersion'] = \str_replace('_', '', $matches[1]); } else { $row['canonicalVersion'] = $row['version']; } @@ -124,15 +117,15 @@ public function fetchHistory(): array $history[] = $row; } - usort( + \usort( $history, static function ($a, $b) { if ($a['apply_time'] === $b['apply_time']) { - if (($compareResult = strcasecmp($b['canonicalVersion'], $a['canonicalVersion'])) !== 0) { + if (($compareResult = \strcasecmp($b['canonicalVersion'], $a['canonicalVersion'])) !== 0) { return $compareResult; } - return strcasecmp($b['version'], $a['version']); + return \strcasecmp($b['version'], $a['version']); } return $b['apply_time'] <=> $a['apply_time']; diff --git a/src/HistoryManagerInterface.php b/src/HistoryManagerInterface.php index 668512e..53108b9 100644 --- a/src/HistoryManagerInterface.php +++ b/src/HistoryManagerInterface.php @@ -11,8 +11,6 @@ interface HistoryManagerInterface { /** * Adds migration history entry. - * @param string $migrationName - * @param string|null $namespace * @throws Exception * @throws NotSupportedException */ diff --git a/src/Inspector.php b/src/Inspector.php index 17f3506..0edddae 100644 --- a/src/Inspector.php +++ b/src/Inspector.php @@ -13,12 +13,6 @@ use yii\base\InvalidConfigException; use yii\base\NotSupportedException; -use function array_key_exists; -use function array_reverse; -use function count; -use function in_array; -use function trim; - final class Inspector implements InspectorInterface { /** @var HistoryManagerInterface */ @@ -53,13 +47,8 @@ public function __construct( /** * Prepares a blueprint for the upcoming update. - * @param StructureInterface $newStructure - * @param bool $onlyShow * @param array $migrationsToSkip * @param array $migrationPaths - * @param string|null $schema - * @param string|null $engineVersion - * @return BlueprintInterface * @throws InvalidConfigException * @throws ErrorException * @throws NotSupportedException @@ -79,10 +68,10 @@ public function prepareBlueprint( $blueprint = new Blueprint(); $blueprint->setTableName($this->currentTable); - if (count($history)) { + if (!empty($history)) { foreach ($history as $migration => $time) { - $migration = trim($migration, '\\'); - if (in_array($migration, $migrationsToSkip, true)) { + $migration = \trim($migration, '\\'); + if (\in_array($migration, $migrationsToSkip, true)) { continue; } @@ -93,11 +82,10 @@ public function prepareBlueprint( } } - /* @phpstan-ignore-next-line */ - if (count($this->appliedChanges)) { + if (!empty($this->appliedChanges)) { $this->comparator->compare( $newStructure, - $this->structureBuilder->build(array_reverse($this->appliedChanges), $schema, $engineVersion), + $this->structureBuilder->build(\array_reverse($this->appliedChanges), $schema, $engineVersion), $blueprint, $onlyShow, $schema, @@ -121,12 +109,12 @@ public function prepareBlueprint( */ private function gatherChanges(?array $changes): bool { - if ($changes === null || !array_key_exists($this->currentTable, $changes)) { + if ($changes === null || !\array_key_exists($this->currentTable, $changes)) { return true; } /** @var StructureChangeInterface $change */ - foreach (array_reverse($changes[$this->currentTable]) as $change) { + foreach (\array_reverse($changes[$this->currentTable]) as $change) { $method = $change->getMethod(); if ($method === 'dropTable') { diff --git a/src/InspectorInterface.php b/src/InspectorInterface.php index f2d3706..30be980 100644 --- a/src/InspectorInterface.php +++ b/src/InspectorInterface.php @@ -14,13 +14,8 @@ interface InspectorInterface { /** * Prepares a blueprint for the upcoming update. - * @param StructureInterface $newStructure - * @param bool $onlyShow * @param array $migrationsToSkip * @param array $migrationPaths - * @param string|null $schema - * @param string|null $engineVersion - * @return BlueprintInterface * @throws InvalidConfigException * @throws ErrorException * @throws NotSupportedException diff --git a/src/Schema.php b/src/Schema.php index 6ce09df..5032abf 100644 --- a/src/Schema.php +++ b/src/Schema.php @@ -131,7 +131,6 @@ final class Schema /** * Returns schema code based on its class name. * @param mixed $schema - * @return string */ public static function identifySchema($schema): string { @@ -165,7 +164,6 @@ public static function identifySchema($schema): string /** * Checks whether the schema is SQLite. * @param mixed $schema - * @return bool */ public static function isSQLite($schema): bool { @@ -175,10 +173,6 @@ public static function isSQLite($schema): bool /** * Returns default length based on the schema and column type. * For MySQL >= 5.6.4 additional default sizes are available. - * @param string|null $schema - * @param string $type - * @param string|null $engineVersion - * @return string|null */ public static function getDefaultLength(?string $schema, string $type, string $engineVersion = null): ?string { @@ -186,7 +180,7 @@ public static function getDefaultLength(?string $schema, string $type, string $e return null; } - if ($engineVersion && $schema === self::MYSQL && version_compare($engineVersion, '5.6.4', '>=')) { + if ($engineVersion && $schema === self::MYSQL && \version_compare($engineVersion, '5.6.4', '>=')) { $schema = self::MYSQL . '+'; } @@ -195,10 +189,6 @@ public static function getDefaultLength(?string $schema, string $type, string $e /** * Returns alias definition based on the schema, column type, and length. - * @param string|null $schema - * @param string $type - * @param string $length - * @return string|null */ public static function getAlias(?string $schema, string $type, string $length): ?string { diff --git a/src/SqlColumnMapper.php b/src/SqlColumnMapper.php index 171e701..a4d167a 100644 --- a/src/SqlColumnMapper.php +++ b/src/SqlColumnMapper.php @@ -6,20 +6,6 @@ use yii\db\Expression; -use function array_slice; -use function count; -use function is_numeric; -use function preg_match; -use function preg_replace; -use function preg_split; -use function stripos; -use function strlen; -use function substr; -use function trim; -use function uksort; - -use const PREG_SPLIT_NO_EMPTY; - class SqlColumnMapper { /** @@ -38,21 +24,19 @@ class SqlColumnMapper private $schema = []; /** - * @param string $definition * @param array $typeMap */ private function __construct(string $definition, array $typeMap) { $this->definition = $definition; // make sure longer DB types are first to avoid mismatch in detectType() - uksort($typeMap, static function ($a, $b) { - return strlen($b) <=> strlen($a); + \uksort($typeMap, static function ($a, $b) { + return \strlen($b) <=> \strlen($a); }); $this->typeMap = $typeMap; } /** - * @param string $definition * @param array $typeMap * @return array */ @@ -86,16 +70,16 @@ private function getSchema(): array private function detectTypeAndLength(): void { foreach ($this->typeMap as $dbType => $yiiType) { - if (stripos($this->definition, $dbType) !== false) { + if (\stripos($this->definition, $dbType) !== false) { $this->schema['type'] = $yiiType; - if (preg_match("/$dbType\\s?(\\(([a-z0-9',\\s_-]+)\\))?/i", $this->definition, $matches)) { - if ($dbType !== 'enum' && count($matches) >= 3) { - $this->schema['length'] = preg_replace('/\s+/', '', $matches[2]); + if (\preg_match("/$dbType\\s?(\\(([a-z0-9',\\s_-]+)\\))?/i", $this->definition, $matches)) { + if ($dbType !== 'enum' && \count($matches) >= 3) { + $this->schema['length'] = \preg_replace('/\s+/', '', $matches[2]); } /** @infection-ignore-all */ - $this->definition = (string)preg_replace( + $this->definition = (string)\preg_replace( "/$dbType\\s?(\\(([a-z0-9',\\s_-]+)\\))?/i", '', $this->definition @@ -112,14 +96,14 @@ private function detectTypeAndLength(): void private function cutOutDefinition(int $from, int $to): void { /** @infection-ignore-all */ - $this->definition = substr($this->definition, 0, $from) . substr($this->definition, $to); + $this->definition = \substr($this->definition, 0, $from) . \substr($this->definition, $to); } private function detectComment(): void { - if (preg_match('/COMMENT\s?([\'\"])/i', $this->definition, $matches)) { + if (\preg_match('/COMMENT\s?([\'\"])/i', $this->definition, $matches)) { /** @infection-ignore-all */ - $cutFrom = (int)stripos($this->definition, 'COMMENT'); + $cutFrom = (int)\stripos($this->definition, 'COMMENT'); [$cutTo, $sentence] = $this->findPart($matches[1], $this->definition, $cutFrom); $this->schema['comment'] = $sentence; @@ -130,20 +114,20 @@ private function detectComment(): void private function detectDefault(): void { /** @infection-ignore-all */ - if (($cutFrom = stripos($this->definition, 'DEFAULT')) !== false) { - if (preg_match('/DEFAULT\s?([\'\"])/i', $this->definition, $matches)) { + if (($cutFrom = \stripos($this->definition, 'DEFAULT')) !== false) { + if (\preg_match('/DEFAULT\s?([\'\"])/i', $this->definition, $matches)) { [$cutTo, $sentence] = $this->findPart($matches[1], $this->definition, $cutFrom); $this->schema['default'] = $sentence; $this->cutOutDefinition($cutFrom, $cutTo); - } elseif (preg_match('/DEFAULT\s?\(/i', $this->definition)) { + } elseif (\preg_match('/DEFAULT\s?\(/i', $this->definition)) { [$cutTo, $sentence] = $this->findPart('(', $this->definition, $cutFrom); $this->schema['default'] = new Expression($sentence); $this->cutOutDefinition($cutFrom, $cutTo); - } elseif (preg_match('/DEFAULT\s?[0-9]/i', $this->definition)) { + } elseif (\preg_match('/DEFAULT\s?[0-9]/i', $this->definition)) { [$cutTo, $sentence] = $this->findPart('1', $this->definition, $cutFrom); $this->schema['default'] = $sentence; $this->cutOutDefinition($cutFrom, $cutTo); - } elseif (preg_match('/DEFAULT\s?[a-z]/i', $this->definition)) { + } elseif (\preg_match('/DEFAULT\s?[a-z]/i', $this->definition)) { [$cutTo, $sentence] = $this->findPart('', $this->definition, $cutFrom + 7); $this->schema['default'] = new Expression($sentence); $this->cutOutDefinition($cutFrom, $cutTo); @@ -153,33 +137,33 @@ private function detectDefault(): void private function detectNotNull(): void { - if (stripos($this->definition, 'NOT NULL') !== false) { + if (\stripos($this->definition, 'NOT NULL') !== false) { $this->schema['isNotNull'] = true; - $this->definition = str_ireplace('NOT NULL', '', $this->definition); + $this->definition = \str_ireplace('NOT NULL', '', $this->definition); } } private function detectNull(): void { - if (stripos($this->definition, 'NULL') !== false) { + if (\stripos($this->definition, 'NULL') !== false) { $this->schema['isNotNull'] = false; - $this->definition = str_ireplace('NULL', '', $this->definition); + $this->definition = \str_ireplace('NULL', '', $this->definition); } } private function detectFirst(): void { - if (stripos($this->definition, 'FIRST') !== false) { + if (\stripos($this->definition, 'FIRST') !== false) { $this->schema['isFirst'] = true; - $this->definition = str_ireplace('FIRST', '', $this->definition); + $this->definition = \str_ireplace('FIRST', '', $this->definition); } } private function detectAfter(): void { - if (preg_match('/AFTER\s?`/i', $this->definition)) { + if (\preg_match('/AFTER\s?`/i', $this->definition)) { /** @infection-ignore-all */ - $cutFrom = (int)stripos($this->definition, 'AFTER'); + $cutFrom = (int)\stripos($this->definition, 'AFTER'); /** @infection-ignore-all */ [$cutTo, $sentence] = $this->findPart('`', $this->definition, $cutFrom + 5); $this->schema['after'] = $sentence; @@ -191,53 +175,50 @@ private function detectAfter(): void private function detectAutoincrement(): void { if ( - stripos($this->definition, 'AUTO_INCREMENT') !== false - || stripos($this->definition, 'AUTOINCREMENT') !== false + \stripos($this->definition, 'AUTO_INCREMENT') !== false + || \stripos($this->definition, 'AUTOINCREMENT') !== false ) { $this->schema['autoIncrement'] = true; - $this->definition = str_ireplace(['AUTO_INCREMENT', 'AUTOINCREMENT'], '', $this->definition); + $this->definition = \str_ireplace(['AUTO_INCREMENT', 'AUTOINCREMENT'], '', $this->definition); } } private function detectPrimaryKey(): void { if ( - stripos($this->definition, 'IDENTITY PRIMARY KEY') !== false - || stripos($this->definition, 'PRIMARY KEY') !== false + \stripos($this->definition, 'IDENTITY PRIMARY KEY') !== false + || \stripos($this->definition, 'PRIMARY KEY') !== false ) { $this->schema['isPrimaryKey'] = true; - $this->definition = str_ireplace(['IDENTITY PRIMARY KEY', 'PRIMARY KEY'], '', $this->definition); + $this->definition = \str_ireplace(['IDENTITY PRIMARY KEY', 'PRIMARY KEY'], '', $this->definition); } } private function detectUnsigned(): void { - if (stripos($this->definition, 'UNSIGNED') !== false) { + if (\stripos($this->definition, 'UNSIGNED') !== false) { $this->schema['isUnsigned'] = true; - $this->definition = str_ireplace('UNSIGNED', '', $this->definition); + $this->definition = \str_ireplace('UNSIGNED', '', $this->definition); } } private function detectUnique(): void { - if (stripos($this->definition, 'UNIQUE') !== false) { + if (\stripos($this->definition, 'UNIQUE') !== false) { $this->schema['isUnique'] = true; - $this->definition = str_ireplace('UNIQUE', '', $this->definition); + $this->definition = \str_ireplace('UNIQUE', '', $this->definition); } } /** - * @param string $type - * @param string $sentence - * @param int $offset * @return array{0: int, 1: string} */ private function findPart(string $type, string $sentence, int $offset): array { - $sentence = substr($sentence, $offset); + $sentence = \substr($sentence, $offset); /** @var array $sentenceArray */ - $sentenceArray = preg_split('//u', $sentence, -1, PREG_SPLIT_NO_EMPTY); + $sentenceArray = \preg_split('//u', $sentence, -1, \PREG_SPLIT_NO_EMPTY); switch ($type) { case "'": @@ -295,7 +276,7 @@ private function findQuotedPart(array $sentenceArray, string $quote): array } } if ($consecutiveQuotes > 0 && $consecutiveQuotes % 2 !== 0) { - $part = substr($part, 0, -1); + $part = \substr($part, 0, -1); } return [(int)$end, $part]; @@ -321,7 +302,7 @@ private function findBacktickedPart(array $sentenceArray): array } if ($collect) { - if ($char === '`' || preg_match('/\s/', $char)) { + if ($char === '`' || \preg_match('/\s/', $char)) { break; } $part .= $char; @@ -378,11 +359,11 @@ private function findNumericPart(array $sentenceArray): array $end = 0; $collect = false; foreach ($sentenceArray as $index => $char) { - if (!$collect && !is_numeric($char) && $char !== '-') { + if (!$collect && !\is_numeric($char) && $char !== '-') { continue; } - if (!$collect && (is_numeric($char) || $char === '-')) { + if (!$collect && (\is_numeric($char) || $char === '-')) { $collect = true; $part .= $char; $end = $index + 1; @@ -390,7 +371,7 @@ private function findNumericPart(array $sentenceArray): array } if ($collect) { - if (!is_numeric($char) && !preg_match('/[a-fA-F0-9x.]/', $char)) { + if (!\is_numeric($char) && !\preg_match('/[a-fA-F0-9x.]/', $char)) { break; } $part .= $char; @@ -411,22 +392,22 @@ private function findExpressionPart(array $sentenceArray): array $end = 0; $collect = false; foreach ($sentenceArray as $index => $char) { - if (!$collect && !preg_match('/[a-z]/i', $char)) { + if (!$collect && !\preg_match('/[a-z]/i', $char)) { continue; } - if (!$collect && preg_match('/[a-z]/i', $char)) { + if (!$collect && \preg_match('/[a-z]/i', $char)) { $collect = true; } if ($collect) { - if (preg_match('/\s/', $char)) { + if (\preg_match('/\s/', $char)) { break; } if ($char === '(') { [$parenthesisPartEnd, $parenthesisPart] = $this->findParenthesizedPart( - array_slice($sentenceArray, $index) + \array_slice($sentenceArray, $index) ); $part .= $parenthesisPart; $end = $index + $parenthesisPartEnd; @@ -443,7 +424,7 @@ private function findExpressionPart(array $sentenceArray): array private function prepareAppend(): void { - $append = trim($this->definition); + $append = \trim($this->definition); if ($append !== '') { $this->schema['append'] = $append; diff --git a/src/SqlExtractorInterface.php b/src/SqlExtractorInterface.php index e50e61a..d0c3eb6 100644 --- a/src/SqlExtractorInterface.php +++ b/src/SqlExtractorInterface.php @@ -13,7 +13,6 @@ interface SqlExtractorInterface extends ExtractorInterface { /** * Extracts migration SQL statements. - * @param string $migration * @param array $migrationPaths * @throws ErrorException */ diff --git a/src/TableMapper.php b/src/TableMapper.php index 7537556..997062b 100644 --- a/src/TableMapper.php +++ b/src/TableMapper.php @@ -15,7 +15,6 @@ use bizley\migration\table\Structure; use bizley\migration\table\StructureInterface; use PDO; -use Throwable; use yii\base\NotSupportedException; use yii\db\ColumnSchema; use yii\db\Connection; @@ -28,9 +27,6 @@ use yii\db\sqlite\Schema as SqliteSchema; use yii\db\TableSchema; -use function count; -use function in_array; - final class TableMapper implements TableMapperInterface { /** @var Connection */ @@ -46,9 +42,7 @@ public function __construct(Connection $db) /** * Returns a structure of the table. - * @param string $table * @param array $referencesToPostpone - * @return StructureInterface * @throws NotSupportedException */ public function getStructureOf(string $table, array $referencesToPostpone = []): StructureInterface @@ -57,7 +51,7 @@ public function getStructureOf(string $table, array $referencesToPostpone = []): $foreignKeys = $this->getForeignKeys($table); foreach ($foreignKeys as $foreignKeyName => $foreignKey) { - if (in_array($foreignKey->getReferredTable(), $referencesToPostpone, true)) { + if (\in_array($foreignKey->getReferredTable(), $referencesToPostpone, true)) { $this->suppressedForeignKeys[] = $foreignKey; unset($foreignKeys[$foreignKeyName]); } @@ -77,7 +71,6 @@ public function getStructureOf(string $table, array $referencesToPostpone = []): /** * Returns the foreign keys of the table. - * @param string $table * @return array * @throws NotSupportedException */ @@ -105,7 +98,6 @@ private function getForeignKeys(string $table): array /** * Returns the indexes of the table. - * @param string $table * @return array * @throws NotSupportedException */ @@ -131,7 +123,6 @@ private function getIndexes(string $table): array /** * Returns a primary key of the table. - * @param string $table * @return PrimaryKeyInterface|null * @throws NotSupportedException */ @@ -154,7 +145,6 @@ private function getPrimaryKey(string $table): ?PrimaryKeyInterface /** * Returns the columns of the table. - * @param string $table * @param array $indexes * @return array * @throws NotSupportedException @@ -201,14 +191,12 @@ private function getColumns(string $table, array $indexes = []): array /** * @param array $indexes - * @param ColumnSchema $column - * @return bool */ private function isUnique(array $indexes, ColumnSchema $column): bool { foreach ($indexes as $index) { $indexColumns = $index->getColumns(); - if ($index->isUnique() && count($indexColumns) === 1 && $indexColumns[0] === $column->name) { + if ($index->isUnique() && \count($indexColumns) === 1 && $indexColumns[0] === $column->name) { return true; } } @@ -227,8 +215,6 @@ public function getSuppressedForeignKeys(): array /** * Returns a table schema of the table. - * @param string $table - * @return TableSchema|null */ public function getTableSchema(string $table): ?TableSchema { @@ -237,7 +223,6 @@ public function getTableSchema(string $table): ?TableSchema /** * Returns a schema type. - * @return string * @throws NotSupportedException */ public function getSchemaType(): string @@ -249,7 +234,6 @@ public function getSchemaType(): string /** * Returns a DB engine version. - * @return string|null */ public function getEngineVersion(): ?string { @@ -260,7 +244,7 @@ public function getEngineVersion(): ?string } return $slavePdo->getAttribute(PDO::ATTR_SERVER_VERSION); - } catch (Throwable $exception) { + } catch (\Throwable $exception) { return null; } } diff --git a/src/TableMapperInterface.php b/src/TableMapperInterface.php index bdeb105..947044a 100644 --- a/src/TableMapperInterface.php +++ b/src/TableMapperInterface.php @@ -13,30 +13,24 @@ interface TableMapperInterface { /** * Returns a structure of the table. - * @param string $table * @param array $referencesToPostpone - * @return StructureInterface * @throws NotSupportedException */ public function getStructureOf(string $table, array $referencesToPostpone = []): StructureInterface; /** * Returns a table schema of the table. - * @param string $table - * @return TableSchema|null */ public function getTableSchema(string $table): ?TableSchema; /** * Returns a schema type. - * @return string * @throws NotSupportedException */ public function getSchemaType(): string; /** * Returns a DB engine version. - * @return string|null */ public function getEngineVersion(): ?string; diff --git a/src/TableMissingException.php b/src/TableMissingException.php index acea1bb..3fd0c80 100644 --- a/src/TableMissingException.php +++ b/src/TableMissingException.php @@ -4,11 +4,9 @@ namespace bizley\migration; -use Exception; - /** * Exception to be thrown when requested DB table does not exist. */ -class TableMissingException extends Exception +class TableMissingException extends \Exception { } diff --git a/src/Updater.php b/src/Updater.php index e034792..150c544 100644 --- a/src/Updater.php +++ b/src/Updater.php @@ -41,7 +41,6 @@ public function __construct( /** * Returns the translated alias of update table migration template. - * @return string */ public function getUpdateTableMigrationTemplate(): string { @@ -52,11 +51,8 @@ public function getUpdateTableMigrationTemplate(): string /** * Prepares a blueprint for update. - * @param string $tableName - * @param bool $onlyShow * @param array $migrationsToSkip * @param array $migrationPaths - * @return BlueprintInterface * @throws TableMissingException * @throws ErrorException * @throws InvalidConfigException @@ -89,12 +85,6 @@ private function getNormalizedNamespace(?string $namespace): ?string /** * Generates migration based on the blueprint. - * @param BlueprintInterface $blueprint - * @param string $migrationName - * @param bool $usePrefix - * @param string $dbPrefix - * @param string|null $namespace - * @return string * @throws NotSupportedException */ public function generateFromBlueprint( diff --git a/src/UpdaterInterface.php b/src/UpdaterInterface.php index 4fe10fc..3cd37c6 100644 --- a/src/UpdaterInterface.php +++ b/src/UpdaterInterface.php @@ -13,11 +13,8 @@ interface UpdaterInterface { /** * Prepares a blueprint for update. - * @param string $tableName - * @param bool $onlyShow * @param array $migrationsToSkip * @param array $migrationPaths - * @return BlueprintInterface * @throws TableMissingException * @throws ErrorException * @throws InvalidConfigException @@ -32,12 +29,6 @@ public function prepareBlueprint( /** * Generates migration based on the blueprint. - * @param BlueprintInterface $blueprint - * @param string $migrationName - * @param bool $usePrefix - * @param string $dbPrefix - * @param string|null $namespace - * @return string * @throws NotSupportedException */ public function generateFromBlueprint( diff --git a/src/controllers/FallbackFileHelper.php b/src/controllers/FallbackFileHelper.php index fe1063d..431148c 100644 --- a/src/controllers/FallbackFileHelper.php +++ b/src/controllers/FallbackFileHelper.php @@ -4,29 +4,14 @@ namespace bizley\migration\controllers; -use Exception; -use RuntimeException; use yii\base\InvalidArgumentException; use yii\helpers\ArrayHelper; -use function chgrp; -use function chmod; -use function chown; -use function count; -use function decoct; -use function explode; -use function is_array; -use function is_int; -use function is_numeric; -use function is_string; - class FallbackFileHelper { /** - * @param string $path * @param int|string|array|null $ownership - * @param int|null $mode - * @throws Exception + * @throws \Exception */ public static function changeOwnership(string $path, $ownership, ?int $mode): void { @@ -36,15 +21,15 @@ public static function changeOwnership(string $path, $ownership, ?int $mode): vo $user = $group = null; if (!empty($ownership) || $ownership === 0 || $ownership === '0') { - if (is_int($ownership)) { + if (\is_int($ownership)) { $user = $ownership; - } elseif (is_string($ownership)) { - $ownerParts = explode(':', $ownership); + } elseif (\is_string($ownership)) { + $ownerParts = \explode(':', $ownership); $user = $ownerParts[0]; - if (count($ownerParts) > 1) { + if (\count($ownerParts) > 1) { $group = $ownerParts[1]; } - } elseif (is_array($ownership)) { + } elseif (\is_array($ownership)) { $ownershipIsIndexed = ArrayHelper::isIndexed($ownership); $user = ArrayHelper::getValue($ownership, $ownershipIsIndexed ? '0' : 'user'); $group = ArrayHelper::getValue($ownership, $ownershipIsIndexed ? '1' : 'group'); @@ -53,31 +38,31 @@ public static function changeOwnership(string $path, $ownership, ?int $mode): vo } } - if ($mode !== null && !chmod($path, $mode)) { - throw new RuntimeException('Unable to change mode of "' . $path . '" to "0' . decoct($mode) . '".'); + if ($mode !== null && !\chmod($path, $mode)) { + throw new \RuntimeException('Unable to change mode of "' . $path . '" to "0' . \decoct($mode) . '".'); } if ($user !== null && $user !== '') { - if (is_numeric($user)) { + if (\is_numeric($user)) { $user = (int)$user; - } elseif (!is_string($user)) { + } elseif (!\is_string($user)) { throw new InvalidArgumentException( 'The user part of fileOwnership option must be an integer, string, or null.' ); } - if (!chown($path, $user)) { - throw new RuntimeException('Unable to change user ownership of "' . $path . '" to "' . $user . '".'); + if (!\chown($path, $user)) { + throw new \RuntimeException('Unable to change user ownership of "' . $path . '" to "' . $user . '".'); } } if ($group !== null && $group !== '') { - if (is_numeric($group)) { + if (\is_numeric($group)) { $group = (int)$group; - } elseif (!is_string($group)) { + } elseif (!\is_string($group)) { throw new InvalidArgumentException( 'The group part of fileOwnership option must be an integer, string, or null.' ); } - if (!chgrp($path, $group)) { - throw new RuntimeException('Unable to change group ownership of "' . $path . '" to "' . $group . '".'); + if (!\chgrp($path, $group)) { + throw new \RuntimeException('Unable to change group ownership of "' . $path . '" to "' . $group . '".'); } } } diff --git a/src/controllers/MigrationController.php b/src/controllers/MigrationController.php index ba484db..3d86243 100644 --- a/src/controllers/MigrationController.php +++ b/src/controllers/MigrationController.php @@ -8,8 +8,6 @@ use bizley\migration\table\BlueprintInterface; use bizley\migration\table\ForeignKeyInterface; use bizley\migration\TableMissingException; -use RuntimeException; -use Throwable; use Yii; use yii\base\Action; use yii\base\Exception; @@ -19,51 +17,22 @@ use yii\db\Connection; use yii\db\Exception as DbException; use yii\di\Instance; -use yii\helpers\Console; +use yii\helpers\BaseConsole; use yii\helpers\FileHelper; -use function array_column; -use function array_merge; -use function array_unique; -use function closedir; -use function count; -use function date; -use function explode; -use function file_put_contents; -use function gmdate; -use function implode; -use function in_array; -use function is_array; -use function is_dir; -use function is_file; -use function is_numeric; -use function is_string; -use function method_exists; -use function octdec; -use function opendir; -use function preg_match; -use function readdir; -use function sort; -use function sprintf; -use function str_replace; -use function strpos; -use function strtolower; -use function time; -use function trim; - /** * Migration creator and updater. * Generates migration files based on the existing database table and previous migrations. * * @author Paweł Bizley Brzozowski - * @version 4.4.0 + * @version 4.4.1 * @license Apache 2.0 * https://github.com/bizley/yii2-migration */ class MigrationController extends BaseMigrationController { /** @var string */ - private $version = '4.4.0'; + private $version = '4.4.1'; /** * @var string|array Directory storing the migration classes. @@ -137,7 +106,7 @@ class MigrationController extends BaseMigrationController /** {@inheritdoc} */ public function options($actionID): array // BC declaration { - $defaultOptions = array_merge(parent::options($actionID), ['db', 'fileMode', 'fileOwnership']); + $defaultOptions = \array_merge(parent::options($actionID), ['db', 'fileMode', 'fileOwnership']); $createOptions = [ 'fixHistory', @@ -153,10 +122,10 @@ public function options($actionID): array // BC declaration switch ($actionID) { case 'create': - return array_merge($defaultOptions, $createOptions); + return \array_merge($defaultOptions, $createOptions); case 'update': - return array_merge($defaultOptions, $createOptions, $updateOptions); + return \array_merge($defaultOptions, $createOptions, $updateOptions); default: return $defaultOptions; @@ -166,7 +135,7 @@ public function options($actionID): array // BC declaration /** @return array */ public function optionAliases(): array { - return array_merge( + return \array_merge( parent::optionAliases(), [ 'ex' => 'experimental', @@ -203,10 +172,10 @@ public function beforeAction($action): bool // BC declaration return false; } - if (in_array($action->id, ['create', 'update', 'sql'], true)) { + if (\in_array($action->id, ['create', 'update', 'sql'], true)) { $createFolders = $action->id !== 'sql'; if ($this->migrationNamespace !== null) { - if (!is_array($this->migrationNamespace)) { + if (!\is_array($this->migrationNamespace)) { $this->migrationNamespace = [$this->migrationNamespace]; } foreach ($this->migrationNamespace as &$namespace) { @@ -222,7 +191,7 @@ public function beforeAction($action): bool // BC declaration } unset($namespace); } elseif ($this->migrationPath !== null) { - if (!is_array($this->migrationPath)) { + if (!\is_array($this->migrationPath)) { $this->migrationPath = [$this->migrationPath]; } foreach ($this->migrationPath as $path) { @@ -238,12 +207,12 @@ public function beforeAction($action): bool // BC declaration } foreach ($this->skipMigrations as $index => $migration) { - $this->skipMigrations[$index] = trim($migration, '\\'); + $this->skipMigrations[$index] = \trim($migration, '\\'); } } $this->db = Instance::ensure($this->db, Connection::class); - $this->stdout("Yii 2 Migration Generator Tool v{$this->version}\n", Console::FG_CYAN); + $this->stdout("Yii 2 Migration Generator Tool v{$this->version}\n", BaseConsole::FG_CYAN); return true; } @@ -259,11 +228,11 @@ public function actionList(): int $tables = $this->getAllTableNames($db); $migrationTable = $db->getSchema()->getRawTableName($this->migrationTable); - $tablesCount = count($tables); + $tablesCount = \count($tables); if ($tablesCount === 0) { $this->stdout(" > Your database does not contain any tables yet.\n"); } else { - sort($tables); + \sort($tables); $this->stdout(" > Your database contains {$tablesCount} table" . ($tablesCount > 1 ? 's' : '') . ":\n"); foreach ($tables as $table) { @@ -275,30 +244,30 @@ public function actionList(): int } } - $this->stdout("\n > Run\n", Console::FG_GREEN); + $this->stdout("\n > Run\n", BaseConsole::FG_GREEN); - $tab = $this->ansiFormat('', Console::FG_YELLOW); - $cmd = $this->ansiFormat('migration/create', Console::FG_CYAN); + $tab = $this->ansiFormat('
', BaseConsole::FG_YELLOW); + $cmd = $this->ansiFormat('migration/create', BaseConsole::FG_CYAN); $this->stdout(" $cmd $tab\n"); - $this->stdout(" to generate creating migration for the specific table.\n", Console::FG_GREEN); + $this->stdout(" to generate creating migration for the specific table.\n", BaseConsole::FG_GREEN); - $cmd = $this->ansiFormat('migration/update', Console::FG_CYAN); + $cmd = $this->ansiFormat('migration/update', BaseConsole::FG_CYAN); $this->stdout(" $cmd $tab\n"); - $this->stdout(" to generate updating migration for the specific table.\n", Console::FG_GREEN); + $this->stdout(" to generate updating migration for the specific table.\n", BaseConsole::FG_GREEN); - $name = $this->ansiFormat('', Console::FG_YELLOW); - $cmd = $this->ansiFormat('migration/sql', Console::FG_CYAN); + $name = $this->ansiFormat('', BaseConsole::FG_YELLOW); + $cmd = $this->ansiFormat('migration/sql', BaseConsole::FG_CYAN); $this->stdout(" $cmd $name\n"); - $this->stdout(" to extract SQL statements of the specific migration.\n", Console::FG_GREEN); + $this->stdout(" to extract SQL statements of the specific migration.\n", BaseConsole::FG_GREEN); $this->stdout("\n > $tab can be:\n"); - $variant = $this->ansiFormat('* (asterisk)', Console::FG_CYAN); + $variant = $this->ansiFormat('* (asterisk)', BaseConsole::FG_CYAN); $this->stdout(" - $variant - for all the tables in database (except excluded ones)\n"); - $variant = $this->ansiFormat('string with * (one or more)', Console::FG_CYAN); + $variant = $this->ansiFormat('string with * (one or more)', BaseConsole::FG_CYAN); $this->stdout(" - $variant - for all the tables in database matching the pattern (except excluded ones)\n"); - $variant = $this->ansiFormat('string without *', Console::FG_CYAN); + $variant = $this->ansiFormat('string without *', BaseConsole::FG_CYAN); $this->stdout(" - $variant - for the table of specified name\n"); - $variant = $this->ansiFormat('strings separated with comma', Console::FG_CYAN); + $variant = $this->ansiFormat('strings separated with comma', BaseConsole::FG_CYAN); $this->stdout(" - $variant - for multiple tables of specified names (with optional *)\n"); return ExitCode::OK; @@ -320,7 +289,7 @@ public function actionCreate(string $inputTable): int return ExitCode::OK; } - $countTables = count($inputTables); + $countTables = \count($inputTables); $referencesToPostpone = []; $tables = $inputTables; if ($countTables > 1) { @@ -331,10 +300,10 @@ public function actionCreate(string $inputTable): int /** @var Connection $db */ $db = $this->db; - if (count($referencesToPostpone) && Schema::isSQLite($db->getSchema())) { + if (!empty($referencesToPostpone) && Schema::isSQLite($db->getSchema())) { $this->stdout( "\nERROR!\n > Generating migrations for provided tables in batch is not possible because 'ADD FOREIGN KEY' is not supported by SQLite!\n", - Console::FG_RED + BaseConsole::FG_RED ); return ExitCode::DATAERR; @@ -347,33 +316,33 @@ public function actionCreate(string $inputTable): int ' > There are migration files detected that have timestamps colliding with the ones that will be generated. Are you sure you want to proceed?' ) ) { - $this->stdout("\n Operation cancelled by user.\n", Console::FG_YELLOW); + $this->stdout("\n Operation cancelled by user.\n", BaseConsole::FG_YELLOW); return ExitCode::UNSPECIFIED_ERROR; } $postponedForeignKeys = []; - $lastUsedTimestamp = time() + $this->leeway; + $lastUsedTimestamp = \time() + $this->leeway; $migrationsGenerated = 0; foreach ($tables as $tableName) { - $this->stdout("\n > Generating migration for creating table '{$tableName}' ...", Console::FG_YELLOW); + $this->stdout("\n > Generating migration for creating table '{$tableName}' ...", BaseConsole::FG_YELLOW); - $normalizedTableName = str_replace('.', '_', $tableName); - $timestamp = time(); + $normalizedTableName = \str_replace('.', '_', $tableName); + $timestamp = \time(); if ($timestamp <= $lastUsedTimestamp) { $timestamp = ++$lastUsedTimestamp; } else { $lastUsedTimestamp = $timestamp; } - $migrationClassName = sprintf( + $migrationClassName = \sprintf( 'm%s_create_table_%s', - gmdate('ymd_His', $timestamp), + \gmdate('ymd_His', $timestamp), $normalizedTableName ); try { $this->generateMigrationForTableCreation($tableName, $migrationClassName, $referencesToPostpone); - } catch (Throwable $exception) { - $this->stdout("ERROR!\n > {$exception->getMessage()}\n", Console::FG_RED); + } catch (\Throwable $exception) { + $this->stdout("ERROR!\n > {$exception->getMessage()}\n", BaseConsole::FG_RED); return ExitCode::UNSPECIFIED_ERROR; } @@ -386,8 +355,8 @@ public function actionCreate(string $inputTable): int } } - if (count($postponedForeignKeys)) { - $timestamp = time(); + if (!empty($postponedForeignKeys)) { + $timestamp = \time(); if ($timestamp <= $lastUsedTimestamp) { $timestamp = ++$lastUsedTimestamp; } @@ -395,10 +364,10 @@ public function actionCreate(string $inputTable): int try { $this->generateMigrationForForeignKeys( $postponedForeignKeys, - sprintf("m%s_create_foreign_keys", gmdate('ymd_His', $timestamp)) + \sprintf("m%s_create_foreign_keys", \gmdate('ymd_His', $timestamp)) ); - } catch (Throwable $exception) { - $this->stdout("ERROR!\n > {$exception->getMessage()}\n", Console::FG_RED); + } catch (\Throwable $exception) { + $this->stdout("ERROR!\n > {$exception->getMessage()}\n", BaseConsole::FG_RED); return ExitCode::UNSPECIFIED_ERROR; } @@ -407,9 +376,9 @@ public function actionCreate(string $inputTable): int $this->stdout( "\n Generated $migrationsGenerated file" . ($migrationsGenerated > 1 ? 's' : '') . "\n", - Console::FG_YELLOW + BaseConsole::FG_YELLOW ); - $this->stdout(" (!) Remember to verify files before applying migration.\n", Console::FG_YELLOW); + $this->stdout(" (!) Remember to verify files before applying migration.\n", BaseConsole::FG_YELLOW); return ExitCode::OK; } @@ -434,7 +403,7 @@ public function actionUpdate(string $inputTable): int /** @var array $migrationPaths */ $migrationPaths = $this->migrationNamespace ?? $this->migrationPath; foreach ($inputTables as $tableName) { - $this->stdout("\n > Comparing current table '{$tableName}' with its migrations ...", Console::FG_YELLOW); + $this->stdout("\n > Comparing current table '{$tableName}' with its migrations ...", BaseConsole::FG_YELLOW); try { $blueprint = $this->getUpdater()->prepareBlueprint( @@ -444,7 +413,7 @@ public function actionUpdate(string $inputTable): int $migrationPaths ); if (!$blueprint->isPending()) { - $this->stdout("TABLE IS UP-TO-DATE.\n", Console::FG_GREEN); + $this->stdout("TABLE IS UP-TO-DATE.\n", BaseConsole::FG_GREEN); continue; } @@ -457,39 +426,39 @@ public function actionUpdate(string $inputTable): int if ($this->onlyShow) { $this->stdout("Showing differences:\n"); if ($blueprint->needsStartFromScratch()) { - $this->stdout(" - table needs creating migration\n", Console::FG_YELLOW); + $this->stdout(" - table needs creating migration\n", BaseConsole::FG_YELLOW); } else { foreach ($blueprint->getDescriptions() as $difference) { $this->stdout( " - $difference\n", - strpos($difference, '(!)') !== false ? Console::FG_RED : Console::FG_YELLOW + \strpos($difference, '(!)') !== false ? BaseConsole::FG_RED : BaseConsole::FG_YELLOW ); } } $this->stdout("\n"); } else { - $this->stdout("DONE!\n", Console::FG_GREEN); + $this->stdout("DONE!\n", BaseConsole::FG_GREEN); } } catch (NotSupportedException $exception) { $this->stdout( "WARNING!\n > Updating table '{$tableName}' requires manual migration!\n", - Console::FG_RED + BaseConsole::FG_RED ); - $this->stdout(' > ' . $exception->getMessage() . "\n", Console::FG_RED); - } catch (Throwable $exception) { - $this->stdout("ERROR!\n > {$exception->getMessage()}\n", Console::FG_RED); + $this->stdout(' > ' . $exception->getMessage() . "\n", BaseConsole::FG_RED); + } catch (\Throwable $exception) { + $this->stdout("ERROR!\n > {$exception->getMessage()}\n", BaseConsole::FG_RED); return ExitCode::UNSPECIFIED_ERROR; } } if ($this->onlyShow) { - $this->stdout(" No files generated.\n", Console::FG_YELLOW); + $this->stdout(" No files generated.\n", BaseConsole::FG_YELLOW); return ExitCode::OK; } - $countTables = count($newTables); + $countTables = \count($newTables); $referencesToPostpone = []; if ($countTables > 1) { $arranger = $this->getArranger(); @@ -499,11 +468,11 @@ public function actionUpdate(string $inputTable): int /** @var Connection $db */ $db = $this->db; - if (count($referencesToPostpone) && Schema::isSQLite($db->getSchema())) { + if (!empty($referencesToPostpone) && Schema::isSQLite($db->getSchema())) { $this->stdout( "ERROR!\n > Generating migrations for provided tables in batch is not possible " . "because 'ADD FOREIGN KEY' is not supported by SQLite!\n", - Console::FG_RED + BaseConsole::FG_RED ); return ExitCode::DATAERR; @@ -511,20 +480,20 @@ public function actionUpdate(string $inputTable): int } if ( - $this->hasTimestampsCollision($countTables + count($blueprints)) + $this->hasTimestampsCollision($countTables + \count($blueprints)) && !$this->confirm( ' > There are migration files detected that have timestamps colliding with the ones that will be generated. Are you sure you want to proceed?' ) ) { - $this->stdout("\n Operation cancelled by user.\n", Console::FG_YELLOW); + $this->stdout("\n Operation cancelled by user.\n", BaseConsole::FG_YELLOW); return ExitCode::UNSPECIFIED_ERROR; } $postponedForeignKeys = []; - $lastUsedTimestamp = time() + $this->leeway; + $lastUsedTimestamp = \time() + $this->leeway; $migrationsGenerated = 0; foreach ($newTables as $tableName) { - $this->stdout("\n > Generating migration for creating table '{$tableName}' ...", Console::FG_YELLOW); + $this->stdout("\n > Generating migration for creating table '{$tableName}' ...", BaseConsole::FG_YELLOW); $timestamp = time(); if ($timestamp <= $lastUsedTimestamp) { @@ -535,15 +504,15 @@ public function actionUpdate(string $inputTable): int try { $this->generateMigrationForTableCreation( $tableName, - sprintf( + \sprintf( "m%s_create_table_%s", - gmdate('ymd_His', $timestamp), - str_replace('.', '_', $tableName) + \gmdate('ymd_His', $timestamp), + \str_replace('.', '_', $tableName) ), $referencesToPostpone ); - } catch (Throwable $exception) { - $this->stdout("ERROR!\n > {$exception->getMessage()}\n", Console::FG_RED); + } catch (\Throwable $exception) { + $this->stdout("ERROR!\n > {$exception->getMessage()}\n", BaseConsole::FG_RED); return ExitCode::UNSPECIFIED_ERROR; } @@ -557,7 +526,7 @@ public function actionUpdate(string $inputTable): int } if ($postponedForeignKeys) { - $timestamp = time(); + $timestamp = \time(); if ($timestamp <= $lastUsedTimestamp) { $timestamp = ++$lastUsedTimestamp; } else { @@ -566,13 +535,13 @@ public function actionUpdate(string $inputTable): int try { $this->generateMigrationForForeignKeys( $postponedForeignKeys, - sprintf( + \sprintf( "m%s_create_foreign_keys", - gmdate('ymd_His', $timestamp) + \gmdate('ymd_His', $timestamp) ) ); - } catch (Throwable $exception) { - $this->stdout("ERROR!\n > {$exception->getMessage()}\n", Console::FG_RED); + } catch (\Throwable $exception) { + $this->stdout("ERROR!\n > {$exception->getMessage()}\n", BaseConsole::FG_RED); return ExitCode::UNSPECIFIED_ERROR; } @@ -580,22 +549,22 @@ public function actionUpdate(string $inputTable): int } foreach ($blueprints as $tableName => $blueprint) { - $this->stdout("\n > Generating migration for updating table '{$tableName}' ...", Console::FG_YELLOW); + $this->stdout("\n > Generating migration for updating table '{$tableName}' ...", BaseConsole::FG_YELLOW); - $normalizedTableName = str_replace('.', '_', $tableName); - $timestamp = time(); + $normalizedTableName = \str_replace('.', '_', $tableName); + $timestamp = \time(); if ($timestamp <= $lastUsedTimestamp) { $timestamp = ++$lastUsedTimestamp; } else { $lastUsedTimestamp = $timestamp; } - $migrationClassName = 'm' . gmdate('ymd_His', $timestamp) . '_update_table_' . $normalizedTableName; + $migrationClassName = 'm' . \gmdate('ymd_His', $timestamp) . '_update_table_' . $normalizedTableName; try { $this->generateMigrationWithBlueprint($blueprint, $migrationClassName); - } catch (Throwable $exception) { - $this->stdout("ERROR!\n > {$exception->getMessage()}\n", Console::FG_RED); + } catch (\Throwable $exception) { + $this->stdout("ERROR!\n > {$exception->getMessage()}\n", BaseConsole::FG_RED); return ExitCode::UNSPECIFIED_ERROR; } @@ -607,11 +576,11 @@ public function actionUpdate(string $inputTable): int if ($migrationsGenerated) { $this->stdout( "\n Generated $migrationsGenerated file" . ($migrationsGenerated > 1 ? 's' : '') . "\n", - Console::FG_YELLOW + BaseConsole::FG_YELLOW ); - $this->stdout(" (!) Remember to verify files before applying migration.\n", Console::FG_YELLOW); + $this->stdout(" (!) Remember to verify files before applying migration.\n", BaseConsole::FG_YELLOW); } else { - $this->stdout("\n No files generated.\n", Console::FG_YELLOW); + $this->stdout("\n No files generated.\n", BaseConsole::FG_YELLOW); } return ExitCode::OK; @@ -620,8 +589,8 @@ public function actionUpdate(string $inputTable): int /** @since 4.4.0 */ public function actionSql(string $migrationName, string $method = 'up'): int { - $method = strtolower($method); - if (!in_array($method, ['up', 'down'], true)) { + $method = \strtolower($method); + if (!\in_array($method, ['up', 'down'], true)) { $method = 'up'; } @@ -631,23 +600,21 @@ public function actionSql(string $migrationName, string $method = 'up'): int $extractor = $this->getSqlExtractor(); $extractor->getSql($migrationName, $migrationPaths, $method); - $migration = $this->ansiFormat($migrationName, Console::FG_YELLOW); - $version = $this->ansiFormat(($method === 'up' ? 'UP' : 'DOWN') . ' method', Console::FG_CYAN); + $migration = $this->ansiFormat($migrationName, BaseConsole::FG_YELLOW); + $version = $this->ansiFormat(($method === 'up' ? 'UP' : 'DOWN') . ' method', BaseConsole::FG_CYAN); $this->stdout(" > SQL statements of the {$migration} file ({$version}):\n\n"); foreach ($extractor->getStatements() as $statement) { - $this->stdout("$statement;\n", Console::FG_YELLOW); + $this->stdout("$statement;\n", BaseConsole::FG_YELLOW); } - $this->stdout("\n (!) Note that the above statements were not executed.\n", Console::FG_RED); + $this->stdout("\n (!) Note that the above statements were not executed.\n", BaseConsole::FG_RED); return ExitCode::OK; } /** * Prepares path directory. If directory doesn't exist it's being created. - * @param string $path - * @return string * @throws Exception */ private function preparePathDirectory(string $path): string @@ -655,7 +622,7 @@ private function preparePathDirectory(string $path): string /** @var string $translatedPath */ $translatedPath = Yii::getAlias($path); - if (!is_dir($translatedPath)) { + if (!\is_dir($translatedPath)) { FileHelper::createDirectory($translatedPath); } @@ -664,15 +631,14 @@ private function preparePathDirectory(string $path): string /** * Stores the content in a file under the given path. - * @param string $path * @param mixed $content - * @throws Throwable + * @throws \Throwable */ public function storeFile(string $path, $content): void { /** @infection-ignore-all */ - if (file_put_contents($path, $content) === false) { - throw new RuntimeException('Migration file can not be saved!'); + if (\file_put_contents($path, $content) === false) { + throw new \RuntimeException('Migration file can not be saved!'); } $this->setFileModeAndOwnership($path); @@ -680,7 +646,6 @@ public function storeFile(string $path, $content): void /** * Fixes the migration history with a new entry. If migration history table doesn't exist it's being created first. - * @param string $migrationClassName * @throws DbException * @throws InvalidConfigException * @throws NotSupportedException @@ -688,23 +653,22 @@ public function storeFile(string $path, $content): void private function fixHistory(string $migrationClassName): void { if ($this->fixHistory) { - $this->stdout("\n > Fixing migration history ...", Console::FG_YELLOW); + $this->stdout("\n > Fixing migration history ...", BaseConsole::FG_YELLOW); $this->getHistoryManager()->addHistory($migrationClassName, $this->workingNamespace); - $this->stdout('DONE!', Console::FG_GREEN); + $this->stdout('DONE!', BaseConsole::FG_GREEN); } } /** * Generates migration for postponed foreign keys. * @param array $postponedForeignKeys - * @param string $migrationClassName * @throws DbException * @throws InvalidConfigException * @throws NotSupportedException */ private function generateMigrationForForeignKeys(array $postponedForeignKeys, string $migrationClassName): void { - $this->stdout("\n > Generating migration for creating foreign keys ...", Console::FG_YELLOW); + $this->stdout("\n > Generating migration for creating foreign keys ...", BaseConsole::FG_YELLOW); $file = $this->workingPath . DIRECTORY_SEPARATOR . $migrationClassName . '.php'; @@ -720,7 +684,7 @@ private function generateMigrationForForeignKeys(array $postponedForeignKeys, st $this->storeFile($file, $migration); - $this->stdout("DONE!\n", Console::FG_GREEN); + $this->stdout("DONE!\n", BaseConsole::FG_GREEN); $this->stdout(" > Saved as '{$file}'\n"); $this->fixHistory($migrationClassName); @@ -728,8 +692,6 @@ private function generateMigrationForForeignKeys(array $postponedForeignKeys, st /** * Generates updating migration based on a blueprint. - * @param BlueprintInterface $blueprint - * @param string $migrationClassName * @throws DbException * @throws InvalidConfigException * @throws NotSupportedException @@ -750,7 +712,7 @@ private function generateMigrationWithBlueprint(BlueprintInterface $blueprint, s $this->storeFile($file, $migration); - $this->stdout("DONE!\n", Console::FG_GREEN); + $this->stdout("DONE!\n", BaseConsole::FG_GREEN); $this->stdout(" > Saved as '{$file}'"); $this->fixHistory($migrationClassName); @@ -758,8 +720,6 @@ private function generateMigrationWithBlueprint(BlueprintInterface $blueprint, s /** * Generates creating migration based on a table structure. - * @param string $tableName - * @param string $migrationClassName * @param array $referencesToPostpone * @throws DbException * @throws InvalidConfigException @@ -786,7 +746,7 @@ private function generateMigrationForTableCreation( $this->storeFile($file, $migration); - $this->stdout("DONE!\n", Console::FG_GREEN); + $this->stdout("DONE!\n", BaseConsole::FG_GREEN); $this->stdout(" > Saved as '{$file}'"); $this->fixHistory($migrationClassName); @@ -795,14 +755,13 @@ private function generateMigrationForTableCreation( /** * Prepares table names based on an input. Resulting names must not be on an excluded list. Migration history table * is always on the excluded list by default. - * @param string $inputTables * @return array * @throws NotSupportedException */ private function prepareTableNames(string $inputTables): array { - if (strpos($inputTables, ',') !== false) { - $tablesList = explode(',', $inputTables); + if (\strpos($inputTables, ',') !== false) { + $tablesList = \explode(',', $inputTables); } else { $tablesList = [$inputTables]; } @@ -810,17 +769,17 @@ private function prepareTableNames(string $inputTables): array /** @var Connection $db */ $db = $this->db; $allTables = $this->getAllTableNames($db); - if (count($allTables) === 0) { + if (empty($allTables)) { return []; } - $excludedTables = array_merge( + $excludedTables = \array_merge( [$db->getSchema()->getRawTableName($this->migrationTable)], $this->excludeTables ); $tables = []; - if (in_array('*', $tablesList, true)) { + if (\in_array('*', $tablesList, true)) { $tables = $this->findMatchingTables(null, $allTables, $excludedTables); } else { foreach ($tablesList as $inputTable) { @@ -838,7 +797,6 @@ private function prepareTableNames(string $inputTables): array /** * Finds tables matching the pattern. - * @param string|null $pattern * @param array $allTables * @param array $excludedTables * @return array @@ -851,8 +809,8 @@ private function findMatchingTables( $filteredTables = []; foreach ($allTables as $table) { - if (!in_array($table, $excludedTables, true)) { - if ($pattern && preg_match('/^' . str_replace('*', '(.+)', $pattern) . '$/', $table) === 0) { + if (!\in_array($table, $excludedTables, true)) { + if ($pattern && \preg_match('/^' . \str_replace('*', '(.+)', $pattern) . '$/', $table) === 0) { continue; } $filteredTables[] = $table; @@ -866,40 +824,39 @@ private function findMatchingTables( /** * Prepares table names and adds confirmation for proceeding with generating for the user. - * @param string $inputTable * @return array|null * @throws NotSupportedException */ private function proceedWithOperation(string $inputTable): ?array { $inputTables = $this->prepareTableNames($inputTable); - $this->foundExcluded = array_unique($this->foundExcluded); - $foundExcludedCount = count($this->foundExcluded); + $this->foundExcluded = \array_unique($this->foundExcluded); + $foundExcludedCount = \count($this->foundExcluded); $excludedInfo = null; if ($foundExcludedCount) { $excludedInfo = " > $foundExcludedCount table" . ($foundExcludedCount > 1 ? 's' : '') . " excluded by the config.\n"; } - $countTables = count($inputTables); + $countTables = \count($inputTables); if ($countTables === 0) { - $this->stdout("\n > No matching tables in database.\n", Console::FG_YELLOW); + $this->stdout("\n > No matching tables in database.\n", BaseConsole::FG_YELLOW); if ($excludedInfo) { - $this->stdout($excludedInfo, Console::FG_YELLOW); + $this->stdout($excludedInfo, BaseConsole::FG_YELLOW); } return null; } if ($excludedInfo) { - $this->stdout($excludedInfo, Console::FG_YELLOW); + $this->stdout($excludedInfo, BaseConsole::FG_YELLOW); } if ( $countTables > 1 && !$this->confirm( " > Are you sure you want to generate migrations for the following tables?\n - " - . implode("\n - ", $inputTables) + . \implode("\n - ", $inputTables) ) ) { - $this->stdout("\n Operation cancelled by user.\n", Console::FG_YELLOW); + $this->stdout("\n Operation cancelled by user.\n", BaseConsole::FG_YELLOW); return null; } @@ -907,7 +864,6 @@ private function proceedWithOperation(string $inputTable): ?array } /** - * @param Connection $db * @return array * @throws NotSupportedException */ @@ -922,14 +878,14 @@ private function getAllTableNames(Connection $db): array } catch (NotSupportedException $ex) { } - if ($schemaNames === null || count($schemaNames) < 2) { + if ($schemaNames === null || \count($schemaNames) < 2) { $tables = $db->getSchema()->getTableNames(); } else { $schemaTables = []; foreach ($schemaNames as $schemaName) { - $schemaTables[] = array_column($db->getSchema()->getTableSchemas($schemaName), 'fullName'); + $schemaTables[] = \array_column($db->getSchema()->getTableSchemas($schemaName), 'fullName'); } - $tables = array_merge($tables, ...$schemaTables); + $tables = \array_merge($tables, ...$schemaTables); } return $tables; } @@ -947,10 +903,10 @@ private function setFileModeAndOwnership(string $path): void { $mode = $this->fileMode; if ($mode !== null) { - if (is_numeric($mode)) { - if (is_string($mode)) { - if (strpos($mode, '0') === 0) { - $mode = octdec($mode); + if (\is_numeric($mode)) { + if (\is_string($mode)) { + if (\strpos($mode, '0') === 0) { + $mode = \octdec($mode); } $mode = (int)$mode; } @@ -960,7 +916,7 @@ private function setFileModeAndOwnership(string $path): void } /** @infection-ignore-all */ - if (method_exists(FileHelper::class, 'changeOwnership')) { + if (\method_exists(FileHelper::class, 'changeOwnership')) { FileHelper::changeOwnership($path, $this->fileOwnership, $mode); return; } @@ -976,7 +932,7 @@ private function hasTimestampsCollision(int $tables): bool return false; } - $now = time() + 5 + $this->leeway; // 5 seconds for response + $now = \time() + 5 + $this->leeway; // 5 seconds for response $lastTimestamp = $now + $tables + 1; // +1 for potential foreign keys migration $folders = []; @@ -984,37 +940,37 @@ private function hasTimestampsCollision(int $tables): bool foreach ((array)$this->migrationNamespace as $namespacedMigration) { /** @var string $translatedPath */ $translatedPath = Yii::getAlias('@' . FileHelper::normalizePath($namespacedMigration, '/')); - if (is_dir($translatedPath)) { + if (\is_dir($translatedPath)) { $folders[] = $translatedPath; } } } else { foreach ((array)$this->migrationPath as $pathMigration) { - if (is_dir($pathMigration)) { + if (\is_dir($pathMigration)) { $folders[] = $pathMigration; } } } - $nowDate = date('ymdHis', $now); - $lastTimestampDate = date('ymdHis', $lastTimestamp); + $nowDate = \date('ymdHis', $now); + $lastTimestampDate = \date('ymdHis', $lastTimestamp); $foundCollision = false; foreach ($folders as $folder) { - if ($handle = opendir($folder)) { - while (($file = readdir($handle)) !== false) { + if ($handle = \opendir($folder)) { + while (($file = \readdir($handle)) !== false) { if ($file === '.' || $file === '..') { continue; } $path = $folder . DIRECTORY_SEPARATOR . $file; - if (is_file($path) && preg_match('/m(\d{6}_?\d{6})\D.*?/i', $file, $matches)) { - $time = str_replace('_', '', $matches[1]); + if (\is_file($path) && \preg_match('/m(\d{6}_?\d{6})\D.*?/i', $file, $matches)) { + $time = \str_replace('_', '', $matches[1]); if ($time >= $nowDate && $time <= $lastTimestampDate) { $foundCollision = true; break; } } } - closedir($handle); + \closedir($handle); if ($foundCollision) { break; } diff --git a/src/dummy/MigrationChanges.php b/src/dummy/MigrationChanges.php index ab11769..83dbec1 100644 --- a/src/dummy/MigrationChanges.php +++ b/src/dummy/MigrationChanges.php @@ -14,15 +14,6 @@ use yii\base\InvalidArgumentException; use yii\base\NotSupportedException; -use function array_key_exists; -use function is_array; -use function is_string; -use function preg_match; -use function preg_split; -use function str_replace; -use function strpos; -use function trim; - /** * Dummy Migration class. * This class is used to gather migration details instead of applying them. @@ -100,7 +91,6 @@ private function extractColumns(array $columns): array /** * Updates column properties based on schema type map. - * @param string $type * @param array $keyToDb * @param array $dbToKey * @return array @@ -109,46 +99,46 @@ private function fillTypeMapProperties(string $type, array $keyToDb, array $dbTo { $schema = []; - if (!array_key_exists($type, $keyToDb)) { + if (!\array_key_exists($type, $keyToDb)) { $schema['type'] = $type; return $schema; } $builder = $keyToDb[$type]; - if (strpos($builder, 'NOT NULL') !== false) { + if (\strpos($builder, 'NOT NULL') !== false) { $schema['isNotNull'] = true; - $builder = trim(str_replace('NOT NULL', '', $builder)); + $builder = \trim(\str_replace('NOT NULL', '', $builder)); } - if (strpos($builder, 'AUTO_INCREMENT') !== false) { + if (\strpos($builder, 'AUTO_INCREMENT') !== false) { $schema['autoIncrement'] = true; - $builder = trim(str_replace('AUTO_INCREMENT', '', $builder)); + $builder = \trim(\str_replace('AUTO_INCREMENT', '', $builder)); } - if (strpos($builder, 'AUTOINCREMENT') !== false) { + if (\strpos($builder, 'AUTOINCREMENT') !== false) { $schema['autoIncrement'] = true; - $builder = trim(str_replace('AUTOINCREMENT', '', $builder)); + $builder = \trim(\str_replace('AUTOINCREMENT', '', $builder)); } - if (strpos($builder, 'IDENTITY PRIMARY KEY') !== false) { + if (\strpos($builder, 'IDENTITY PRIMARY KEY') !== false) { $schema['isPrimaryKey'] = true; - $builder = trim(str_replace('IDENTITY PRIMARY KEY', '', $builder)); + $builder = \trim(\str_replace('IDENTITY PRIMARY KEY', '', $builder)); } - if (strpos($builder, 'PRIMARY KEY') !== false) { + if (\strpos($builder, 'PRIMARY KEY') !== false) { $schema['isPrimaryKey'] = true; - $builder = trim(str_replace('PRIMARY KEY', '', $builder)); + $builder = \trim(\str_replace('PRIMARY KEY', '', $builder)); } - if (strpos($builder, 'UNSIGNED') !== false) { + if (\strpos($builder, 'UNSIGNED') !== false) { $schema['isUnsigned'] = true; - $builder = trim(str_replace('UNSIGNED', '', $builder)); + $builder = \trim(\str_replace('UNSIGNED', '', $builder)); } - preg_match('/^([a-zA-Z ]+)(\(([0-9,]+)\))?$/', $builder, $matches); + \preg_match('/^([a-zA-Z ]+)(\(([0-9,]+)\))?$/', $builder, $matches); - if (array_key_exists($matches[1], $dbToKey)) { + if (\array_key_exists($matches[1], $dbToKey)) { if (!empty($matches[3])) { $schema['length'] = $matches[3]; } @@ -184,7 +174,7 @@ private function extractColumn($columnData): array $typeMap = $this->db->schema->typeMap; } - if ($this->experimental && is_string($columnData)) { + if ($this->experimental && \is_string($columnData)) { return SqlColumnMapper::map($columnData, $typeMap); } @@ -221,7 +211,7 @@ private function extractColumn($columnData): array $reflectionProperty->setAccessible(true); $value = $reflectionProperty->getValue($columnData); - if (($value !== null && $value !== []) || !array_key_exists($property, $schema)) { + if (($value !== null && $value !== []) || !\array_key_exists($property, $schema)) { $schema[$property] = $value; } } @@ -238,15 +228,13 @@ private function getRawTableName(string $table): string /** * Adds method of structure change and its data. - * @param string $table - * @param string $method * @param mixed $data */ private function addChange(string $table, string $method, $data): void { $table = $this->getRawTableName($table); - if (!array_key_exists($table, $this->changes)) { + if (!\array_key_exists($table, $this->changes)) { $this->changes[$table] = []; } @@ -395,7 +383,7 @@ public function addPrimaryKey(string $name, string $table, $columns): void 'addPrimaryKey', [ 'name' => $name, - 'columns' => is_array($columns) ? $columns : preg_split('/\s*,\s*/', $columns) + 'columns' => \is_array($columns) ? $columns : \preg_split('/\s*,\s*/', $columns) ] ); } @@ -406,8 +394,8 @@ public function dropPrimaryKey(string $name, string $table): void } /** - * @param string|string[]$columns - * @param string|string[]$refColumns + * @param string|string[] $columns + * @param string|string[] $refColumns */ public function addForeignKey( string $name, @@ -418,7 +406,7 @@ public function addForeignKey( string $delete = null, string $update = null ): void { - $columns = is_array($columns) ? $columns : preg_split('/\s*,\s*/', $columns); + $columns = \is_array($columns) ? $columns : \preg_split('/\s*,\s*/', $columns); $this->addChange( $table, 'addForeignKey', @@ -426,7 +414,7 @@ public function addForeignKey( 'name' => $name, 'columns' => $columns, 'referredTable' => $this->getRawTableName($refTable), - 'referredColumns' => is_array($refColumns) ? $refColumns : preg_split('/\s*,\s*/', $refColumns), + 'referredColumns' => \is_array($refColumns) ? $refColumns : \preg_split('/\s*,\s*/', $refColumns), 'onDelete' => $delete, 'onUpdate' => $update, 'tableName' => $this->getRawTableName($table) @@ -447,7 +435,7 @@ public function createIndex(string $name, string $table, $columns, bool $unique 'createIndex', [ 'name' => $name, - 'columns' => is_array($columns) ? $columns : preg_split('/\s*,\s*/', $columns), + 'columns' => \is_array($columns) ? $columns : \preg_split('/\s*,\s*/', $columns), 'unique' => $unique ] ); diff --git a/src/dummy/MigrationSql.php b/src/dummy/MigrationSql.php index f91c5cb..63a7a16 100644 --- a/src/dummy/MigrationSql.php +++ b/src/dummy/MigrationSql.php @@ -196,8 +196,8 @@ public function dropPrimaryKey(string $name, string $table): void } /** - * @param string|string[]$columns - * @param string|string[]$refColumns + * @param string|string[] $columns + * @param string|string[] $refColumns */ public function addForeignKey( string $name, diff --git a/src/renderers/BlueprintRenderer.php b/src/renderers/BlueprintRenderer.php index 93d054f..ce2b517 100644 --- a/src/renderers/BlueprintRenderer.php +++ b/src/renderers/BlueprintRenderer.php @@ -6,9 +6,6 @@ use bizley\migration\table\BlueprintInterface; -use function array_filter; -use function implode; - final class BlueprintRenderer implements BlueprintRendererInterface { /** @var ColumnRendererInterface */ @@ -38,13 +35,6 @@ public function __construct( /** * Renders the blueprint for up(). * @see https://www.yiiframework.com/doc/api/2.0/yii-db-migration#up()-detail - * @param BlueprintInterface $blueprint - * @param int $indent - * @param string|null $schema - * @param string|null $engineVersion - * @param bool $usePrefix - * @param string|null $dbPrefix - * @return string */ public function renderUp( BlueprintInterface $blueprint, @@ -56,7 +46,7 @@ public function renderUp( ): string { $tableName = $this->renderName($blueprint->getTableName(), $usePrefix, $dbPrefix); - $renderedBlueprint = array_filter( + $renderedBlueprint = \array_filter( [ $this->renderIndexesToDrop($blueprint, $tableName, $indent), $this->renderPrimaryKeyToDrop($blueprint, $tableName, $indent, $schema), @@ -70,19 +60,12 @@ public function renderUp( ] ); - return implode("\n\n", $renderedBlueprint); + return \implode("\n\n", $renderedBlueprint); } /** * Renders the blueprint for down(). * @see https://www.yiiframework.com/doc/api/2.0/yii-db-migration#down()-detail - * @param BlueprintInterface $blueprint - * @param int $indent - * @param string|null $schema - * @param string|null $engineVersion - * @param bool $usePrefix - * @param string|null $dbPrefix - * @return string */ public function renderDown( BlueprintInterface $blueprint, @@ -94,7 +77,7 @@ public function renderDown( ): string { $tableName = $this->renderName($blueprint->getTableName(), $usePrefix, $dbPrefix); - $renderedBlueprint = array_filter( + $renderedBlueprint = \array_filter( [ $this->renderIndexesToDrop($blueprint, $tableName, $indent, true), $this->renderPrimaryKeyToDrop($blueprint, $tableName, $indent, $schema, true), @@ -108,16 +91,13 @@ public function renderDown( ] ); - return implode("\n\n", $renderedBlueprint); + return \implode("\n\n", $renderedBlueprint); } /** * Renders table name. Name should be provided without the prefix. If name should be with prefix and it is being * detected, prefix is removed from the name and replaced by a prefix structure ({{%}}). - * @param string $tableName * @param bool $usePrefix whether to add prefix structure to the name - * @param string|null $dbPrefix - * @return string */ public function renderName(string $tableName, bool $usePrefix, string $dbPrefix = null): string { @@ -125,8 +105,8 @@ public function renderName(string $tableName, bool $usePrefix, string $dbPrefix return $tableName; } - if (!empty($dbPrefix) && strpos($tableName, $dbPrefix) === 0) { - $tableName = mb_substr($tableName, mb_strlen($dbPrefix, 'UTF-8'), null, 'UTF-8'); + if (!empty($dbPrefix) && \strpos($tableName, $dbPrefix) === 0) { + $tableName = \mb_substr($tableName, \mb_strlen($dbPrefix, 'UTF-8'), null, 'UTF-8'); } return "{{%$tableName}}"; @@ -134,11 +114,6 @@ public function renderName(string $tableName, bool $usePrefix, string $dbPrefix /** * Renders drop columns statements. - * @param BlueprintInterface $blueprint - * @param string $tableName - * @param int $indent - * @param bool $inverse - * @return string|null */ private function renderColumnsToDrop( BlueprintInterface $blueprint, @@ -158,18 +133,11 @@ private function renderColumnsToDrop( $renderedColumns[] = $this->columnRenderer->renderDrop($column, $tableName, $indent); } - return count($renderedColumns) ? implode("\n", $renderedColumns) : null; + return !empty($renderedColumns) ? \implode("\n", $renderedColumns) : null; } /** * Renders add columns statements. - * @param BlueprintInterface $blueprint - * @param string $tableName - * @param int $indent - * @param string|null $schema - * @param string|null $engineVersion - * @param bool $inverse - * @return string|null */ private function renderColumnsToAdd( BlueprintInterface $blueprint, @@ -200,18 +168,11 @@ private function renderColumnsToAdd( ); } - return count($renderedColumns) ? implode("\n", $renderedColumns) : null; + return !empty($renderedColumns) ? \implode("\n", $renderedColumns) : null; } /** * Renders alter columns statements. - * @param BlueprintInterface $blueprint - * @param string $tableName - * @param int $indent - * @param string|null $schema - * @param string|null $engineVersion - * @param bool $inverse - * @return string|null */ private function renderColumnsToAlter( BlueprintInterface $blueprint, @@ -242,17 +203,11 @@ private function renderColumnsToAlter( ); } - return count($renderedColumns) ? implode("\n", $renderedColumns) : null; + return !empty($renderedColumns) ? \implode("\n", $renderedColumns) : null; } /** * Renders drop foreign keys statements. - * @param BlueprintInterface $blueprint - * @param string $tableName - * @param int $indent - * @param string|null $schema - * @param bool $inverse - * @return string|null */ private function renderForeignKeysToDrop( BlueprintInterface $blueprint, @@ -273,19 +228,11 @@ private function renderForeignKeysToDrop( $renderedForeignKeys[] = $this->foreignKeyRenderer->renderDown($foreignKey, $tableName, $indent, $schema); } - return count($renderedForeignKeys) ? implode("\n", $renderedForeignKeys) : null; + return !empty($renderedForeignKeys) ? \implode("\n", $renderedForeignKeys) : null; } /** * Renders add foreign keys statements. - * @param BlueprintInterface $blueprint - * @param string $tableName - * @param int $indent - * @param string|null $schema - * @param bool $usePrefix - * @param string|null $dbPrefix - * @param bool $inverse - * @return string|null */ private function renderForeignKeysToAdd( BlueprintInterface $blueprint, @@ -314,16 +261,11 @@ private function renderForeignKeysToAdd( ); } - return count($renderedForeignKeys) ? implode("\n", $renderedForeignKeys) : null; + return !empty($renderedForeignKeys) ? \implode("\n", $renderedForeignKeys) : null; } /** * Renders drop indexes statements. - * @param BlueprintInterface $blueprint - * @param string $tableName - * @param int $indent - * @param bool $inverse - * @return string|null */ private function renderIndexesToDrop( BlueprintInterface $blueprint, @@ -343,16 +285,11 @@ private function renderIndexesToDrop( $renderedIndexes[] = $this->indexRenderer->renderDown($index, $tableName, $indent); } - return count($renderedIndexes) ? implode("\n", $renderedIndexes) : null; + return !empty($renderedIndexes) ? \implode("\n", $renderedIndexes) : null; } /** * Renders add indexes statements. - * @param BlueprintInterface $blueprint - * @param string $tableName - * @param int $indent - * @param bool $inverse - * @return string|null */ private function renderIndexesToAdd( BlueprintInterface $blueprint, @@ -372,17 +309,11 @@ private function renderIndexesToAdd( $renderedIndexes[] = $this->indexRenderer->renderUp($index, $tableName, $indent); } - return count($renderedIndexes) ? implode("\n", $renderedIndexes) : null; + return !empty($renderedIndexes) ? \implode("\n", $renderedIndexes) : null; } /** * Renders drop primary key statement. - * @param BlueprintInterface $blueprint - * @param string $tableName - * @param int $indent - * @param string|null $schema - * @param bool $inverse - * @return string|null */ private function renderPrimaryKeyToDrop( BlueprintInterface $blueprint, @@ -402,12 +333,6 @@ private function renderPrimaryKeyToDrop( /** * Renders add primary key statement. - * @param BlueprintInterface $blueprint - * @param string $tableName - * @param int $indent - * @param string|null $schema - * @param bool $inverse - * @return string|null */ private function renderPrimaryKeyToAdd( BlueprintInterface $blueprint, diff --git a/src/renderers/BlueprintRendererInterface.php b/src/renderers/BlueprintRendererInterface.php index cd14685..ab018fc 100644 --- a/src/renderers/BlueprintRendererInterface.php +++ b/src/renderers/BlueprintRendererInterface.php @@ -11,13 +11,6 @@ interface BlueprintRendererInterface /** * Renders the blueprint for up(). * @see https://www.yiiframework.com/doc/api/2.0/yii-db-migration#up()-detail - * @param BlueprintInterface $blueprint - * @param int $indent - * @param string|null $schema - * @param string|null $engineVersion - * @param bool $usePrefix - * @param string|null $dbPrefix - * @return string */ public function renderUp( BlueprintInterface $blueprint, @@ -31,13 +24,6 @@ public function renderUp( /** * Renders the blueprint for down(). * @see https://www.yiiframework.com/doc/api/2.0/yii-db-migration#down()-detail - * @param BlueprintInterface $blueprint - * @param int $indent - * @param string|null $schema - * @param string|null $engineVersion - * @param bool $usePrefix - * @param string|null $dbPrefix - * @return string */ public function renderDown( BlueprintInterface $blueprint, diff --git a/src/renderers/ColumnRenderer.php b/src/renderers/ColumnRenderer.php index 8f27e29..53cdf1c 100644 --- a/src/renderers/ColumnRenderer.php +++ b/src/renderers/ColumnRenderer.php @@ -12,12 +12,6 @@ use yii\db\Expression; use yii\helpers\Json; -use function array_unshift; -use function is_array; -use function str_repeat; -use function str_replace; -use function trim; - final class ColumnRenderer implements ColumnRendererInterface { /** @var array */ @@ -54,12 +48,6 @@ public function __construct(bool $generalSchema) /** * Renders the array part with column definition (name => definition). - * @param ColumnInterface $column - * @param PrimaryKeyInterface|null $primaryKey - * @param int $indent - * @param string|null $schema - * @param string|null $engineVersion - * @return string|null */ public function render( ColumnInterface $column, @@ -68,9 +56,9 @@ public function render( string $schema = null, string $engineVersion = null ): ?string { - $template = str_repeat(' ', $indent) . $this->definitionTemplate; + $template = \str_repeat(' ', $indent) . $this->definitionTemplate; - return str_replace( + return \str_replace( [ '{columnName}', '{columnDefinition}' @@ -85,13 +73,6 @@ public function render( /** * Renders the add column statement. - * @param ColumnInterface $column - * @param string $tableName - * @param PrimaryKeyInterface|null $primaryKey - * @param int $indent - * @param string|null $schema - * @param string|null $engineVersion - * @return string|null */ public function renderAdd( ColumnInterface $column, @@ -101,9 +82,9 @@ public function renderAdd( string $schema = null, string $engineVersion = null ): ?string { - $template = str_repeat(' ', $indent) . $this->addColumnTemplate; + $template = \str_repeat(' ', $indent) . $this->addColumnTemplate; - return str_replace( + return \str_replace( [ '{tableName}', '{columnName}', @@ -120,13 +101,6 @@ public function renderAdd( /** * Renders the alter column statement. - * @param ColumnInterface $column - * @param string $tableName - * @param PrimaryKeyInterface|null $primaryKey - * @param int $indent - * @param string|null $schema - * @param string|null $engineVersion - * @return string|null */ public function renderAlter( ColumnInterface $column, @@ -136,9 +110,9 @@ public function renderAlter( string $schema = null, string $engineVersion = null ): ?string { - $template = str_repeat(' ', $indent) . $this->alterColumnTemplate; + $template = \str_repeat(' ', $indent) . $this->alterColumnTemplate; - return str_replace( + return \str_replace( [ '{tableName}', '{columnName}', @@ -155,16 +129,12 @@ public function renderAlter( /** * Renders the drop column statement. - * @param ColumnInterface $column - * @param string $tableName - * @param int $indent - * @return string|null */ public function renderDrop(ColumnInterface $column, string $tableName, int $indent = 0): ?string { - $template = str_repeat(' ', $indent) . $this->dropColumnTemplate; + $template = \str_repeat(' ', $indent) . $this->dropColumnTemplate; - return str_replace( + return \str_replace( [ '{tableName}', '{columnName}' @@ -179,11 +149,6 @@ public function renderDrop(ColumnInterface $column, string $tableName, int $inde /** * Renders the column definition. - * @param ColumnInterface $column - * @param PrimaryKeyInterface|null $primaryKey - * @param string|null $schema - * @param string|null $engineVersion - * @return string|null */ public function renderDefinition( ColumnInterface $column, @@ -199,15 +164,11 @@ public function renderDefinition( $this->buildColumnDefinition($column, $primaryKey, $schema, $engineVersion); $this->buildGeneralDefinition($column, $primaryKey, $schema); - return implode('->', $this->definition); + return \implode('->', $this->definition); } /** * Builds the column definition. - * @param ColumnInterface $column - * @param PrimaryKeyInterface|null $primaryKey - * @param string|null $schema - * @param string|null $engineVersion */ private function buildColumnDefinition( ColumnInterface $column, @@ -238,12 +199,12 @@ private function buildColumnDefinition( if ($this->generalSchema) { $alias = Schema::getAlias($schema, $type, (string)$length); if ($alias !== null) { - $this->definition[] = str_replace('{renderLength}', '', $alias); + $this->definition[] = \str_replace('{renderLength}', '', $alias); return; } } - $this->definition[] = str_replace( + $this->definition[] = \str_replace( '{renderLength}', $this->getRenderedLength( (string)$length, @@ -255,9 +216,6 @@ private function buildColumnDefinition( /** * Renders the column length. - * @param string $length - * @param string $defaultLength - * @return string|null */ private function getRenderedLength( string $length, @@ -277,16 +235,13 @@ private function getRenderedLength( /** * Builds general methods chain for column definition. - * @param ColumnInterface $column - * @param PrimaryKeyInterface|null $primaryKey - * @param string|null $schema */ private function buildGeneralDefinition( ColumnInterface $column, ?PrimaryKeyInterface $primaryKey, string $schema = null ): void { - array_unshift($this->definition, '$this'); + \array_unshift($this->definition, '$this'); if ($this->isUnsignedPossible && $column->isUnsigned()) { $this->definition[] = 'unsigned()'; @@ -300,7 +255,7 @@ private function buildGeneralDefinition( if ($default !== null) { if ($default instanceof Expression) { $this->definition[] = "defaultExpression('{$this->escapeQuotes($default->expression)}')"; - } elseif (is_array($default)) { + } elseif (\is_array($default)) { $this->definition[] = "defaultValue('{$this->escapeQuotes(Json::encode($default))}')"; } else { $this->definition[] = "defaultValue('{$this->escapeQuotes((string)$default)}')"; @@ -318,13 +273,13 @@ private function buildGeneralDefinition( if ($schemaAppend !== null) { if (!empty($columnAppend)) { - $schemaAppend .= ' ' . trim(str_replace($schemaAppend, '', $columnAppend)); + $schemaAppend .= ' ' . \trim(\str_replace($schemaAppend, '', $columnAppend)); } - $schemaAppend = trim($schemaAppend); + $schemaAppend = \trim($schemaAppend); } $this->definition[] = "append('" . $this->escapeQuotes($schemaAppend) . "')"; } elseif (!empty($columnAppend)) { - $this->definition[] = "append('" . $this->escapeQuotes(trim($columnAppend)) . "')"; + $this->definition[] = "append('" . $this->escapeQuotes(\trim($columnAppend)) . "')"; } $comment = $column->getComment(); @@ -342,8 +297,6 @@ private function buildGeneralDefinition( /** * Escapes single quotes. - * @param string|null $value - * @return string|null */ public function escapeQuotes(?string $value): ?string { @@ -351,6 +304,6 @@ public function escapeQuotes(?string $value): ?string return null; } - return str_replace('\'', '\\\'', $value); + return \str_replace('\'', '\\\'', $value); } } diff --git a/src/renderers/ColumnRendererInterface.php b/src/renderers/ColumnRendererInterface.php index 0406b29..0b4ac7a 100644 --- a/src/renderers/ColumnRendererInterface.php +++ b/src/renderers/ColumnRendererInterface.php @@ -11,12 +11,6 @@ interface ColumnRendererInterface { /** * Renders the array part with column definition (name => definition). - * @param ColumnInterface $column - * @param PrimaryKeyInterface|null $primaryKey - * @param int $indent - * @param string|null $schema - * @param string|null $engineVersion - * @return string|null */ public function render( ColumnInterface $column, @@ -28,11 +22,6 @@ public function render( /** * Renders the column definition. - * @param ColumnInterface $column - * @param PrimaryKeyInterface|null $primaryKey - * @param string|null $schema - * @param string|null $engineVersion - * @return string|null */ public function renderDefinition( ColumnInterface $column, @@ -43,13 +32,6 @@ public function renderDefinition( /** * Renders the add column statement. - * @param ColumnInterface $column - * @param string $tableName - * @param PrimaryKeyInterface|null $primaryKey - * @param int $indent - * @param string|null $schema - * @param string|null $engineVersion - * @return string|null */ public function renderAdd( ColumnInterface $column, @@ -62,13 +44,6 @@ public function renderAdd( /** * Renders the alter column statement. - * @param ColumnInterface $column - * @param string $tableName - * @param PrimaryKeyInterface|null $primaryKey - * @param int $indent - * @param string|null $schema - * @param string|null $engineVersion - * @return string|null */ public function renderAlter( ColumnInterface $column, @@ -81,10 +56,6 @@ public function renderAlter( /** * Renders the drop column statement. - * @param ColumnInterface $column - * @param string $tableName - * @param int $indent - * @return string|null */ public function renderDrop(ColumnInterface $column, string $tableName, int $indent = 0): ?string; } diff --git a/src/renderers/ForeignKeyRenderer.php b/src/renderers/ForeignKeyRenderer.php index 45fcb66..114afec 100644 --- a/src/renderers/ForeignKeyRenderer.php +++ b/src/renderers/ForeignKeyRenderer.php @@ -8,11 +8,6 @@ use bizley\migration\table\ForeignKeyInterface; use yii\base\NotSupportedException; -use function explode; -use function implode; -use function str_repeat; -use function str_replace; - final class ForeignKeyRenderer implements ForeignKeyRendererInterface { /** @var string */ @@ -41,12 +36,6 @@ public function __construct(bool $generalSchema) /** * Renders the add foreign key statement. - * @param ForeignKeyInterface $foreignKey - * @param string $tableName - * @param string $referencedTableName - * @param int $indent - * @param string|null $schema - * @return string * @throws NotSupportedException */ public function renderUp( @@ -77,7 +66,7 @@ public function renderUp( $onDelete = $foreignKey->getOnDelete(); $onUpdate = $foreignKey->getOnUpdate(); - return str_replace( + return \str_replace( [ '{keyName}', '{tableName}', @@ -90,9 +79,9 @@ public function renderUp( [ $foreignKey->getName(), $tableName, - implode(', ', $renderedKeyColumns), + \implode(', ', $renderedKeyColumns), $referencedTableName, - implode(', ', $renderedReferencedColumns), + \implode(', ', $renderedReferencedColumns), $onDelete ? "'$onDelete'" : 'null', $onUpdate ? "'$onUpdate'" : 'null' ], @@ -102,11 +91,6 @@ public function renderUp( /** * Renders the drop foreign key statement. - * @param ForeignKeyInterface $foreignKey - * @param string $tableName - * @param int $indent - * @param string|null $schema - * @return string * @throws NotSupportedException */ public function renderDown( @@ -121,7 +105,7 @@ public function renderDown( $template = $this->applyIndent($indent, $this->dropKeyTemplate); - return str_replace( + return \str_replace( [ '{keyName}', '{tableName}' @@ -136,9 +120,6 @@ public function renderDown( /** * Applies the indent to every row in the template. - * @param int $indent - * @param string $template - * @return string */ private function applyIndent(int $indent, string $template): string { @@ -146,13 +127,13 @@ private function applyIndent(int $indent, string $template): string return $template; } - $rows = explode("\n", $template); + $rows = \explode("\n", $template); foreach ($rows as &$row) { if ($row !== '') { - $row = str_repeat(' ', $indent) . $row; + $row = \str_repeat(' ', $indent) . $row; } } - return implode("\n", $rows); + return \implode("\n", $rows); } } diff --git a/src/renderers/ForeignKeyRendererInterface.php b/src/renderers/ForeignKeyRendererInterface.php index 8a37f0d..79cad6e 100644 --- a/src/renderers/ForeignKeyRendererInterface.php +++ b/src/renderers/ForeignKeyRendererInterface.php @@ -10,12 +10,6 @@ interface ForeignKeyRendererInterface { /** * Renders the add foreign key statement. - * @param ForeignKeyInterface $foreignKey - * @param string $tableName - * @param string $referencedTableName - * @param int $indent - * @param string|null $schema - * @return string */ public function renderUp( ForeignKeyInterface $foreignKey, @@ -27,11 +21,6 @@ public function renderUp( /** * Renders the drop foreign key statement. - * @param ForeignKeyInterface $foreignKey - * @param string $tableName - * @param int $indent - * @param string|null $schema - * @return string */ public function renderDown( ForeignKeyInterface $foreignKey, diff --git a/src/renderers/IndexRenderer.php b/src/renderers/IndexRenderer.php index 71cfaf2..f6b871c 100644 --- a/src/renderers/IndexRenderer.php +++ b/src/renderers/IndexRenderer.php @@ -6,10 +6,6 @@ use bizley\migration\table\IndexInterface; -use function implode; -use function str_repeat; -use function str_replace; - final class IndexRenderer implements IndexRendererInterface { /** @var string */ @@ -20,14 +16,10 @@ final class IndexRenderer implements IndexRendererInterface /** * Renders the add index statement. - * @param IndexInterface $index - * @param string $tableName - * @param int $indent - * @return string|null */ public function renderUp(IndexInterface $index, string $tableName, int $indent = 0): ?string { - $template = str_repeat(' ', $indent) . $this->createIndexTemplate; + $template = \str_repeat(' ', $indent) . $this->createIndexTemplate; $indexColumns = $index->getColumns(); $renderedColumns = []; @@ -35,7 +27,7 @@ public function renderUp(IndexInterface $index, string $tableName, int $indent = $renderedColumns[] = "'$indexColumn'"; } - return str_replace( + return \str_replace( [ '{indexName}', '{tableName}', @@ -45,7 +37,7 @@ public function renderUp(IndexInterface $index, string $tableName, int $indent = [ $index->getName(), $tableName, - implode(', ', $renderedColumns), + \implode(', ', $renderedColumns), $index->isUnique() ? ', true' : '', ], $template @@ -54,16 +46,12 @@ public function renderUp(IndexInterface $index, string $tableName, int $indent = /** * Renders the drop index statement. - * @param IndexInterface $index - * @param string $tableName - * @param int $indent - * @return string|null */ public function renderDown(IndexInterface $index, string $tableName, int $indent = 0): ?string { - $template = str_repeat(' ', $indent) . $this->dropIndexTemplate; + $template = \str_repeat(' ', $indent) . $this->dropIndexTemplate; - return str_replace( + return \str_replace( [ '{indexName}', '{tableName}' diff --git a/src/renderers/IndexRendererInterface.php b/src/renderers/IndexRendererInterface.php index 8b752c5..14c3758 100644 --- a/src/renderers/IndexRendererInterface.php +++ b/src/renderers/IndexRendererInterface.php @@ -10,19 +10,11 @@ interface IndexRendererInterface { /** * Renders the add index statement. - * @param IndexInterface $index - * @param string $tableName - * @param int $indent - * @return string|null */ public function renderUp(IndexInterface $index, string $tableName, int $indent = 0): ?string; /** * Renders the drop index statement. - * @param IndexInterface $index - * @param string $tableName - * @param int $indent - * @return string|null */ public function renderDown(IndexInterface $index, string $tableName, int $indent = 0): ?string; } diff --git a/src/renderers/PrimaryKeyRenderer.php b/src/renderers/PrimaryKeyRenderer.php index d58df1c..a645e56 100644 --- a/src/renderers/PrimaryKeyRenderer.php +++ b/src/renderers/PrimaryKeyRenderer.php @@ -8,10 +8,6 @@ use bizley\migration\table\PrimaryKeyInterface; use yii\base\NotSupportedException; -use function implode; -use function str_repeat; -use function str_replace; - final class PrimaryKeyRenderer implements PrimaryKeyRendererInterface { /** @var string */ @@ -30,11 +26,6 @@ public function __construct(bool $generalSchema) /** * Renders the add primary key statement. - * @param PrimaryKeyInterface|null $primaryKey - * @param string $tableName - * @param int $indent - * @param string|null $schema - * @return string|null * @throws NotSupportedException */ public function renderUp( @@ -51,7 +42,7 @@ public function renderUp( throw new NotSupportedException('ADD PRIMARY KEY is not supported by SQLite.'); } - $template = str_repeat(' ', $indent) . $this->addKeyTemplate; + $template = \str_repeat(' ', $indent) . $this->addKeyTemplate; $keyColumns = $primaryKey->getColumns(); $renderedColumns = []; @@ -59,7 +50,7 @@ public function renderUp( $renderedColumns[] = "'$keyColumn'"; } - return str_replace( + return \str_replace( [ '{keyName}', '{tableName}', @@ -68,7 +59,7 @@ public function renderUp( [ $primaryKey->getName(), $tableName, - implode(', ', $renderedColumns), + \implode(', ', $renderedColumns), ], $template ); @@ -76,11 +67,6 @@ public function renderUp( /** * Renders the drop primary key statement. - * @param PrimaryKeyInterface|null $primaryKey - * @param string $tableName - * @param int $indent - * @param string|null $schema - * @return string|null * @throws NotSupportedException */ public function renderDown( @@ -97,9 +83,9 @@ public function renderDown( throw new NotSupportedException('DROP PRIMARY KEY is not supported by SQLite.'); } - $template = str_repeat(' ', $indent) . $this->dropKeyTemplate; + $template = \str_repeat(' ', $indent) . $this->dropKeyTemplate; - return str_replace( + return \str_replace( [ '{keyName}', '{tableName}' diff --git a/src/renderers/PrimaryKeyRendererInterface.php b/src/renderers/PrimaryKeyRendererInterface.php index 3dd151f..9d37915 100644 --- a/src/renderers/PrimaryKeyRendererInterface.php +++ b/src/renderers/PrimaryKeyRendererInterface.php @@ -10,11 +10,6 @@ interface PrimaryKeyRendererInterface { /** * Renders the add primary key statement. - * @param PrimaryKeyInterface|null $primaryKey - * @param string $tableName - * @param int $indent - * @param string|null $schema - * @return string|null */ public function renderUp( ?PrimaryKeyInterface $primaryKey, @@ -25,11 +20,6 @@ public function renderUp( /** * Renders the drop primary key statement. - * @param PrimaryKeyInterface|null $primaryKey - * @param string $tableName - * @param int $indent - * @param string|null $schema - * @return string|null */ public function renderDown( ?PrimaryKeyInterface $primaryKey, diff --git a/src/renderers/StructureRenderer.php b/src/renderers/StructureRenderer.php index 748c663..ee07407 100644 --- a/src/renderers/StructureRenderer.php +++ b/src/renderers/StructureRenderer.php @@ -7,16 +7,6 @@ use bizley\migration\table\ForeignKeyInterface; use bizley\migration\table\StructureInterface; -use function array_filter; -use function count; -use function explode; -use function implode; -use function mb_strlen; -use function mb_substr; -use function str_repeat; -use function str_replace; -use function strpos; - final class StructureRenderer implements StructureRendererInterface { /** @var string */ @@ -65,10 +55,6 @@ public function __construct( /** * Renders table name. Name should be provided without the prefix. If name should be with prefix and it is being * detected, prefix is removed from the name and replaced by a prefix structure ({{%}}). - * @param string $tableName - * @param bool $usePrefix - * @param string|null $dbPrefix - * @return string */ public function renderName(string $tableName, bool $usePrefix, string $dbPrefix = null): string { @@ -76,8 +62,8 @@ public function renderName(string $tableName, bool $usePrefix, string $dbPrefix return $tableName; } - if (!empty($dbPrefix) && strpos($tableName, $dbPrefix) === 0) { - $tableName = mb_substr($tableName, mb_strlen($dbPrefix, 'UTF-8'), null, 'UTF-8'); + if (!empty($dbPrefix) && \strpos($tableName, $dbPrefix) === 0) { + $tableName = \mb_substr($tableName, \mb_strlen($dbPrefix, 'UTF-8'), null, 'UTF-8'); } return "{{%$tableName}}"; @@ -86,13 +72,6 @@ public function renderName(string $tableName, bool $usePrefix, string $dbPrefix /** * Renders the migration structure for up(). * @see https://www.yiiframework.com/doc/api/2.0/yii-db-migration#up()-detail - * @param StructureInterface $structure - * @param int $indent - * @param string $schema - * @param string|null $engineVersion - * @param bool $usePrefix - * @param string|null $dbPrefix - * @return string */ public function renderStructureUp( StructureInterface $structure, @@ -104,7 +83,7 @@ public function renderStructureUp( ): string { $tableName = $this->renderName($structure->getName(), $usePrefix, $dbPrefix); - $renderedStructure = array_filter( + $renderedStructure = \array_filter( [ $this->renderStructureTableUp($structure, $tableName, $indent, $schema, $engineVersion), $this->renderStructurePrimaryKeyUp($structure, $tableName, $indent, $schema), @@ -113,17 +92,12 @@ public function renderStructureUp( ] ); - return implode("\n\n", $renderedStructure); + return \implode("\n\n", $renderedStructure); } /** * Renders the migration structure for down(). * @see https://www.yiiframework.com/doc/api/2.0/yii-db-migration#down()-detail - * @param StructureInterface $structure - * @param int $indent - * @param bool $usePrefix - * @param string|null $dbPrefix - * @return string */ public function renderStructureDown( StructureInterface $structure, @@ -139,9 +113,6 @@ public function renderStructureDown( /** * Applies the indent to every row in the template. - * @param int $indent - * @param string $template - * @return string */ private function applyIndent(int $indent, string $template): string { @@ -149,24 +120,18 @@ private function applyIndent(int $indent, string $template): string return $template; } - $rows = explode("\n", $template); + $rows = \explode("\n", $template); foreach ($rows as &$row) { if ($row !== '') { - $row = str_repeat(' ', $indent) . $row; + $row = \str_repeat(' ', $indent) . $row; } } - return implode("\n", $rows); + return \implode("\n", $rows); } /** * Renders the create-table statement. - * @param StructureInterface $structure - * @param string $tableName - * @param int $indent - * @param string|null $schema - * @param string|null $engineVersion - * @return string */ private function renderStructureTableUp( StructureInterface $structure, @@ -189,14 +154,14 @@ private function renderStructureTableUp( return $this->applyIndent( $indent, - str_replace( + \str_replace( [ '{tableName}', '{columns}', ], [ $tableName, - implode("\n", $renderedColumns), + \implode("\n", $renderedColumns), ], $this->createTableTemplate ) @@ -205,9 +170,6 @@ private function renderStructureTableUp( /** * Renders the drop-table statement. - * @param string $tableName - * @param int $indent - * @return string */ private function renderStructureTableDown( string $tableName, @@ -215,16 +177,11 @@ private function renderStructureTableDown( ): string { $template = $this->applyIndent($indent, $this->dropTableTemplate); - return str_replace('{tableName}', $tableName, $template); + return \str_replace('{tableName}', $tableName, $template); } /** * Renders the add-primary-key statement. - * @param StructureInterface $structure - * @param string $tableName - * @param int $indent - * @param string|null $schema - * @return string|null */ private function renderStructurePrimaryKeyUp( StructureInterface $structure, @@ -237,10 +194,6 @@ private function renderStructurePrimaryKeyUp( /** * Renders the add indexes statements. - * @param StructureInterface $structure - * @param string $tableName - * @param int $indent - * @return string|null */ private function renderStructureIndexesUp( StructureInterface $structure, @@ -266,17 +219,11 @@ private function renderStructureIndexesUp( ); } - return count($renderedIndexes) ? implode("\n", $renderedIndexes) : null; + return !empty($renderedIndexes) ? \implode("\n", $renderedIndexes) : null; } /** * Renders the add foreign keys statements (through the structure). - * @param StructureInterface $structure - * @param int $indent - * @param bool $usePrefix - * @param string|null $dbPrefix - * @param string|null $schema - * @return string|null */ private function renderStructureForeignKeysUp( StructureInterface $structure, @@ -297,11 +244,6 @@ private function renderStructureForeignKeysUp( /** * Renders the add foreign keys statements (direct). * @param array $foreignKeys - * @param int $indent - * @param bool $usePrefix - * @param string|null $dbPrefix - * @param string|null $schema - * @return string|null */ public function renderForeignKeysUp( array $foreignKeys, @@ -321,17 +263,12 @@ public function renderForeignKeysUp( ); } - return count($renderedForeignKeys) ? implode("\n", $renderedForeignKeys) : null; + return !empty($renderedForeignKeys) ? \implode("\n", $renderedForeignKeys) : null; } /** * Renders the drop foreign keys statements. * @param array $foreignKeys - * @param int $indent - * @param bool $usePrefix - * @param string|null $dbPrefix - * @param string|null $schema - * @return string|null */ public function renderForeignKeysDown( array $foreignKeys, @@ -350,6 +287,6 @@ public function renderForeignKeysDown( ); } - return count($renderedForeignKeys) ? implode("\n", $renderedForeignKeys) : null; + return !empty($renderedForeignKeys) ? \implode("\n", $renderedForeignKeys) : null; } } diff --git a/src/renderers/StructureRendererInterface.php b/src/renderers/StructureRendererInterface.php index 82d5e15..414b871 100644 --- a/src/renderers/StructureRendererInterface.php +++ b/src/renderers/StructureRendererInterface.php @@ -12,13 +12,6 @@ interface StructureRendererInterface /** * Renders the migration structure for up(). * @see https://www.yiiframework.com/doc/api/2.0/yii-db-migration#up()-detail - * @param StructureInterface $structure - * @param int $indent - * @param string|null $schema - * @param string|null $engineVersion - * @param bool $usePrefix - * @param string|null $dbPrefix - * @return string */ public function renderStructureUp( StructureInterface $structure, @@ -32,11 +25,6 @@ public function renderStructureUp( /** * Renders the migration structure for down(). * @see https://www.yiiframework.com/doc/api/2.0/yii-db-migration#down()-detail - * @param StructureInterface $structure - * @param int $indent - * @param bool $usePrefix - * @param string|null $dbPrefix - * @return string */ public function renderStructureDown( StructureInterface $structure, @@ -48,21 +36,12 @@ public function renderStructureDown( /** * Renders table name. Name should be provided without the prefix. If name should be with prefix and it is being * detected, prefix is removed from the name and replaced by a prefix structure ({{%}}). - * @param string $tableName - * @param bool $usePrefix - * @param string|null $dbPrefix - * @return string */ public function renderName(string $tableName, bool $usePrefix, string $dbPrefix = null): string; /** * Renders the add foreign keys statements (direct). * @param array $foreignKeys - * @param int $indent - * @param bool $usePrefix - * @param string|null $dbPrefix - * @param string|null $schema - * @return string|null */ public function renderForeignKeysUp( array $foreignKeys, @@ -75,10 +54,6 @@ public function renderForeignKeysUp( /** * Renders the drop foreign keys statements. * @param array $foreignKeys - * @param int $indent - * @param bool $usePrefix - * @param string|null $dbPrefix - * @return string|null */ public function renderForeignKeysDown( array $foreignKeys, diff --git a/src/table/BigIntegerColumn.php b/src/table/BigIntegerColumn.php index a0c0617..0071782 100644 --- a/src/table/BigIntegerColumn.php +++ b/src/table/BigIntegerColumn.php @@ -6,9 +6,6 @@ use bizley\migration\Schema; -use function in_array; -use function version_compare; - final class BigIntegerColumn extends Column implements PrimaryKeyVariantColumnInterface { /** @var array Schemas using length for this column */ @@ -17,23 +14,18 @@ final class BigIntegerColumn extends Column implements PrimaryKeyVariantColumnIn /** * Checks if schema supports length for this column. * In case of MySQL the engine version must be lower than 8.0.17. - * @param string|null $schema - * @param string|null $engineVersion - * @return bool */ private function isSchemaLengthSupporting(?string $schema, ?string $engineVersion): bool { - if ($engineVersion && $schema === Schema::MYSQL && version_compare($engineVersion, '8.0.17', '<')) { + if ($engineVersion && $schema === Schema::MYSQL && \version_compare($engineVersion, '8.0.17', '<')) { return true; } - return in_array($schema, $this->lengthSchemas, true); + return \in_array($schema, $this->lengthSchemas, true); } /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) @@ -44,8 +36,6 @@ public function getLength(string $schema = null, string $engineVersion = null) /** * Sets length of the column. * @param string|int|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { diff --git a/src/table/BigPrimaryKeyColumn.php b/src/table/BigPrimaryKeyColumn.php index 05f40ab..3fc3dc1 100644 --- a/src/table/BigPrimaryKeyColumn.php +++ b/src/table/BigPrimaryKeyColumn.php @@ -6,9 +6,6 @@ use bizley\migration\Schema; -use function in_array; -use function version_compare; - class BigPrimaryKeyColumn extends Column implements PrimaryKeyColumnInterface { /** @var array Schemas using length for this column */ @@ -17,23 +14,18 @@ class BigPrimaryKeyColumn extends Column implements PrimaryKeyColumnInterface /** * Checks if schema supports length for this column. * In case of MySQL the engine version must be lower than 8.0.17. - * @param string|null $schema - * @param string|null $engineVersion - * @return bool */ private function isSchemaLengthSupporting(?string $schema, ?string $engineVersion): bool { - if ($engineVersion && $schema === Schema::MYSQL && version_compare($engineVersion, '8.0.17', '<')) { + if ($engineVersion && $schema === Schema::MYSQL && \version_compare($engineVersion, '8.0.17', '<')) { return true; } - return in_array($schema, $this->lengthSchemas, true); + return \in_array($schema, $this->lengthSchemas, true); } /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) @@ -44,8 +36,6 @@ public function getLength(string $schema = null, string $engineVersion = null) /** * Sets length of the column. * @param string|int|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { @@ -57,7 +47,6 @@ public function setLength($value, string $schema = null, string $engineVersion = /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/src/table/BinaryColumn.php b/src/table/BinaryColumn.php index b9925ee..f65759f 100644 --- a/src/table/BinaryColumn.php +++ b/src/table/BinaryColumn.php @@ -6,8 +6,6 @@ use bizley\migration\Schema; -use function in_array; - final class BinaryColumn extends Column implements ColumnInterface { /** @var array Schemas using length for this column */ @@ -15,24 +13,20 @@ final class BinaryColumn extends Column implements ColumnInterface /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) { - return in_array($schema, $this->lengthSchemas, true) ? $this->getSize() : null; + return \in_array($schema, $this->lengthSchemas, true) ? $this->getSize() : null; } /** * Sets length of the column. * @param string|int|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { - if (in_array($schema, $this->lengthSchemas, true)) { + if (\in_array($schema, $this->lengthSchemas, true)) { $this->setSize($value); $this->setPrecision($value); } @@ -40,7 +34,6 @@ public function setLength($value, string $schema = null, string $engineVersion = /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/src/table/Blueprint.php b/src/table/Blueprint.php index 655a748..bb42d1a 100644 --- a/src/table/Blueprint.php +++ b/src/table/Blueprint.php @@ -4,8 +4,6 @@ namespace bizley\migration\table; -use function count; - final class Blueprint implements BlueprintInterface { /** @var string */ @@ -55,7 +53,6 @@ final class Blueprint implements BlueprintInterface /** * Returns table name of the structure. - * @return string */ public function getTableName(): string { @@ -64,7 +61,6 @@ public function getTableName(): string /** * Sets table name for the structure. - * @param string $tableName */ public function setTableName(string $tableName): void { @@ -81,7 +77,6 @@ public function startFromScratch(): void /** * Checks if blueprint contains no changes because table requires creation migration. - * @return bool */ public function needsStartFromScratch(): bool { @@ -90,7 +85,6 @@ public function needsStartFromScratch(): bool /** * Adds single description of the change. - * @param string $description */ public function addDescription(string $description): void { @@ -108,16 +102,14 @@ public function getDescriptions(): array /** * Checks if blueprint is ready to proceed with the update of table. - * @return bool */ public function isPending(): bool { - return $this->startFromScratch === true || count($this->description) > 0; + return $this->startFromScratch === true || !empty($this->description); } /** * Adds added column. - * @param ColumnInterface $column */ public function addColumn(ColumnInterface $column): void { @@ -126,7 +118,6 @@ public function addColumn(ColumnInterface $column): void /** * Adds altered column. - * @param ColumnInterface $column */ public function alterColumn(ColumnInterface $column): void { @@ -135,7 +126,6 @@ public function alterColumn(ColumnInterface $column): void /** * Adds unaltered column. - * @param ColumnInterface $column */ public function reverseColumn(ColumnInterface $column): void { @@ -144,7 +134,6 @@ public function reverseColumn(ColumnInterface $column): void /** * Adds dropped column. - * @param ColumnInterface $column */ public function dropColumn(ColumnInterface $column): void { @@ -153,7 +142,6 @@ public function dropColumn(ColumnInterface $column): void /** * Adds added foreign key. - * @param ForeignKeyInterface $foreignKey */ public function addForeignKey(ForeignKeyInterface $foreignKey): void { @@ -162,7 +150,6 @@ public function addForeignKey(ForeignKeyInterface $foreignKey): void /** * Adds dropped foreign key. - * @param ForeignKeyInterface $foreignKey */ public function dropForeignKey(ForeignKeyInterface $foreignKey): void { @@ -171,7 +158,6 @@ public function dropForeignKey(ForeignKeyInterface $foreignKey): void /** * Adds dropped primary key. - * @param PrimaryKeyInterface $primaryKey */ public function dropPrimaryKey(PrimaryKeyInterface $primaryKey): void { @@ -180,7 +166,6 @@ public function dropPrimaryKey(PrimaryKeyInterface $primaryKey): void /** * Adds added primary key. - * @param PrimaryKeyInterface $primaryKey */ public function addPrimaryKey(PrimaryKeyInterface $primaryKey): void { @@ -189,7 +174,6 @@ public function addPrimaryKey(PrimaryKeyInterface $primaryKey): void /** * Adds added index. - * @param IndexInterface $index */ public function addIndex(IndexInterface $index): void { @@ -198,7 +182,6 @@ public function addIndex(IndexInterface $index): void /** * Adds dropped index. - * @param IndexInterface $index */ public function dropIndex(IndexInterface $index): void { @@ -261,7 +244,6 @@ public function getAddedForeignKeys(): array /** * Returns dropped primary key. - * @return PrimaryKeyInterface|null */ public function getDroppedPrimaryKey(): ?PrimaryKeyInterface { @@ -270,7 +252,6 @@ public function getDroppedPrimaryKey(): ?PrimaryKeyInterface /** * Returns added primary key. - * @return PrimaryKeyInterface|null */ public function getAddedPrimaryKey(): ?PrimaryKeyInterface { @@ -297,7 +278,6 @@ public function getAddedIndexes(): array /** * Returns old table's primary key. - * @return PrimaryKeyInterface|null */ public function getTableOldPrimaryKey(): ?PrimaryKeyInterface { @@ -306,7 +286,6 @@ public function getTableOldPrimaryKey(): ?PrimaryKeyInterface /** * Sets old table's primary key. - * @param PrimaryKeyInterface|null $tableOldPrimaryKey */ public function setTableOldPrimaryKey(?PrimaryKeyInterface $tableOldPrimaryKey): void { @@ -315,7 +294,6 @@ public function setTableOldPrimaryKey(?PrimaryKeyInterface $tableOldPrimaryKey): /** * Returns new table's primary key. - * @return PrimaryKeyInterface|null */ public function getTableNewPrimaryKey(): ?PrimaryKeyInterface { @@ -324,7 +302,6 @@ public function getTableNewPrimaryKey(): ?PrimaryKeyInterface /** * Sets new table's primary key. - * @param PrimaryKeyInterface|null $tableNewPrimaryKey */ public function setTableNewPrimaryKey(?PrimaryKeyInterface $tableNewPrimaryKey): void { diff --git a/src/table/BlueprintInterface.php b/src/table/BlueprintInterface.php index cb9366f..0175cda 100644 --- a/src/table/BlueprintInterface.php +++ b/src/table/BlueprintInterface.php @@ -8,13 +8,11 @@ interface BlueprintInterface { /** * Returns table name of the structure. - * @return string */ public function getTableName(): string; /** * Sets table name for the structure. - * @param string $tableName */ public function setTableName(string $tableName): void; @@ -25,13 +23,11 @@ public function startFromScratch(): void; /** * Checks if blueprint contains no changes because table requires creation migration. - * @return bool */ public function needsStartFromScratch(): bool; /** * Adds single description of the change. - * @param string $description */ public function addDescription(string $description): void; @@ -43,67 +39,56 @@ public function getDescriptions(): array; /** * Checks if blueprint is ready to proceed with the update of table. - * @return bool */ public function isPending(): bool; /** * Adds added column. - * @param ColumnInterface $column */ public function addColumn(ColumnInterface $column): void; /** * Adds altered column. - * @param ColumnInterface $column */ public function alterColumn(ColumnInterface $column): void; /** * Adds unaltered column. - * @param ColumnInterface $column */ public function reverseColumn(ColumnInterface $column): void; /** * Adds dropped column. - * @param ColumnInterface $column */ public function dropColumn(ColumnInterface $column): void; /** * Adds added foreign key. - * @param ForeignKeyInterface $foreignKey */ public function addForeignKey(ForeignKeyInterface $foreignKey): void; /** * Adds dropped foreign key. - * @param ForeignKeyInterface $foreignKey */ public function dropForeignKey(ForeignKeyInterface $foreignKey): void; /** * Adds dropped primary key. - * @param PrimaryKeyInterface $primaryKey */ public function dropPrimaryKey(PrimaryKeyInterface $primaryKey): void; /** * Adds added primary key. - * @param PrimaryKeyInterface $primaryKey */ public function addPrimaryKey(PrimaryKeyInterface $primaryKey): void; /** * Adds added index. - * @param IndexInterface $index */ public function addIndex(IndexInterface $index): void; /** * Adds dropped index. - * @param IndexInterface $index */ public function dropIndex(IndexInterface $index): void; @@ -145,13 +130,11 @@ public function getAddedForeignKeys(): array; /** * Returns dropped primary key. - * @return PrimaryKeyInterface|null */ public function getDroppedPrimaryKey(): ?PrimaryKeyInterface; /** * Returns added primary key. - * @return PrimaryKeyInterface|null */ public function getAddedPrimaryKey(): ?PrimaryKeyInterface; @@ -169,25 +152,21 @@ public function getAddedIndexes(): array; /** * Returns old table's primary key. - * @return PrimaryKeyInterface|null */ public function getTableOldPrimaryKey(): ?PrimaryKeyInterface; /** * Sets old table's primary key. - * @param PrimaryKeyInterface|null $tableOldPrimaryKey */ public function setTableOldPrimaryKey(?PrimaryKeyInterface $tableOldPrimaryKey): void; /** * Returns new table's primary key. - * @return PrimaryKeyInterface|null */ public function getTableNewPrimaryKey(): ?PrimaryKeyInterface; /** * Sets new table's primary key. - * @param PrimaryKeyInterface|null $tableNewPrimaryKey */ public function setTableNewPrimaryKey(?PrimaryKeyInterface $tableNewPrimaryKey): void; } diff --git a/src/table/BooleanColumn.php b/src/table/BooleanColumn.php index 79916a2..8179807 100644 --- a/src/table/BooleanColumn.php +++ b/src/table/BooleanColumn.php @@ -6,8 +6,6 @@ use bizley\migration\Schema; -use function in_array; - final class BooleanColumn extends Column implements ColumnInterface { /** @var array Schemas using length for this column */ @@ -18,24 +16,20 @@ final class BooleanColumn extends Column implements ColumnInterface /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) { - return in_array($schema, $this->lengthSchemas, true) ? $this->getSize() : null; + return \in_array($schema, $this->lengthSchemas, true) ? $this->getSize() : null; } /** * Sets length of the column. * @param string|int|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { - if (in_array($schema, $this->lengthSchemas, true)) { + if (\in_array($schema, $this->lengthSchemas, true)) { $this->setSize($value); $this->setPrecision($value); } @@ -43,7 +37,6 @@ public function setLength($value, string $schema = null, string $engineVersion = /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/src/table/CharacterColumn.php b/src/table/CharacterColumn.php index 7831324..cd52418 100644 --- a/src/table/CharacterColumn.php +++ b/src/table/CharacterColumn.php @@ -8,8 +8,6 @@ final class CharacterColumn extends Column implements ColumnInterface { /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) @@ -20,8 +18,6 @@ public function getLength(string $schema = null, string $engineVersion = null) /** * Sets length of the column. * @param string|int|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { @@ -31,7 +27,6 @@ public function setLength($value, string $schema = null, string $engineVersion = /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/src/table/Column.php b/src/table/Column.php index 98650b0..703f973 100644 --- a/src/table/Column.php +++ b/src/table/Column.php @@ -6,13 +6,6 @@ use bizley\migration\Schema; -use function in_array; -use function preg_replace; -use function str_ireplace; -use function str_replace; -use function stripos; -use function trim; - abstract class Column { /** @var string */ @@ -62,7 +55,6 @@ abstract class Column /** * Returns name of the column. - * @return string */ public function getName(): string { @@ -71,7 +63,6 @@ public function getName(): string /** * Sets name for the column. - * @param string $name */ public function setName(string $name): void { @@ -80,7 +71,6 @@ public function setName(string $name): void /** * Returns type of the column. - * @return string */ public function getType(): string { @@ -89,7 +79,6 @@ public function getType(): string /** * Sets type for the column. - * @param string $type */ public function setType(string $type): void { @@ -98,7 +87,6 @@ public function setType(string $type): void /** * Checks whether the column can not be null. - * @return bool|null */ public function isNotNull(): ?bool { @@ -107,7 +95,6 @@ public function isNotNull(): ?bool /** * Sets the column to not be null. - * @param bool|null $notNull */ public function setNotNull(?bool $notNull): void { @@ -171,7 +158,6 @@ public function setScale($scale): void /** * Checks whether the column is unique. - * @return bool */ public function isUnique(): bool { @@ -180,7 +166,6 @@ public function isUnique(): bool /** * Sets the uniqueness of the column. - * @param bool $unique */ public function setUnique(bool $unique): void { @@ -189,7 +174,6 @@ public function setUnique(bool $unique): void /** * Checks whether the column is unsigned. - * @return bool */ public function isUnsigned(): bool { @@ -198,7 +182,6 @@ public function isUnsigned(): bool /** * Sets the unsigned flag for the column. - * @param bool $unsigned */ public function setUnsigned(bool $unsigned): void { @@ -225,7 +208,6 @@ public function setDefault($default): void /** * Checks whether the column is a primary key. - * @return bool */ public function isPrimaryKey(): bool { @@ -234,7 +216,6 @@ public function isPrimaryKey(): bool /** * Sets the primary key flag for the column. - * @param bool|null $primaryKey */ public function setPrimaryKey(?bool $primaryKey): void { @@ -243,7 +224,6 @@ public function setPrimaryKey(?bool $primaryKey): void /** * Checks whether the column has autoincrement flag. - * @return bool */ public function isAutoIncrement(): bool { @@ -252,7 +232,6 @@ public function isAutoIncrement(): bool /** * Sets the autoincrement flag for the column. - * @param bool $autoIncrement */ public function setAutoIncrement(bool $autoIncrement): void { @@ -261,7 +240,6 @@ public function setAutoIncrement(bool $autoIncrement): void /** * Returns the value of append statement of the column. - * @return string|null */ public function getAppend(): ?string { @@ -270,7 +248,6 @@ public function getAppend(): ?string /** * Sets the value for append statement for the column. - * @param string|null $append */ public function setAppend(?string $append): void { @@ -279,7 +256,6 @@ public function setAppend(?string $append): void /** * Returns the value for comment statement for the column. - * @return string|null */ public function getComment(): ?string { @@ -288,7 +264,6 @@ public function getComment(): ?string /** * Sets the value for comment statement for the column. - * @param string|null $comment */ public function setComment(?string $comment): void { @@ -297,7 +272,6 @@ public function setComment(?string $comment): void /** * Returns the value for after statement for the column. - * @return string|null */ public function getAfter(): ?string { @@ -306,7 +280,6 @@ public function getAfter(): ?string /** * Sets the value for after statement for the column. - * @param string|null $after */ public function setAfter(?string $after): void { @@ -315,7 +288,6 @@ public function setAfter(?string $after): void /** * Checks whether the column has first statement. - * @return bool */ public function isFirst(): bool { @@ -324,7 +296,6 @@ public function isFirst(): bool /** * Sets the column for the first statement. - * @param bool $first */ public function setFirst(bool $first): void { @@ -333,18 +304,14 @@ public function setFirst(bool $first): void /** * Checks if column is a part of the primary key. - * @param PrimaryKeyInterface $primaryKey - * @return bool */ public function isColumnInPrimaryKey(PrimaryKeyInterface $primaryKey): bool { - return in_array($this->name, $primaryKey->getColumns(), true); + return \in_array($this->name, $primaryKey->getColumns(), true); } /** * Checks if information of primary key is set in append statement. - * @param string|null $schema - * @return bool */ public function isPrimaryKeyInfoAppended(?string $schema): bool { @@ -353,8 +320,8 @@ public function isPrimaryKeyInfoAppended(?string $schema): bool return false; } - if (stripos($append, 'PRIMARY KEY') !== false) { - return !($schema === Schema::MSSQL && stripos($append, 'IDENTITY') === false); + if (\stripos($append, 'PRIMARY KEY') !== false) { + return !($schema === Schema::MSSQL && \stripos($append, 'IDENTITY') === false); } return false; @@ -364,8 +331,6 @@ public function isPrimaryKeyInfoAppended(?string $schema): bool * Prepares append statement based on the schema. * @param bool $primaryKey whether the column is primary key * @param bool $autoIncrement whether the column has autoincrement flag - * @param string|null $schema - * @return string|null */ public function prepareSchemaAppend(bool $primaryKey, bool $autoIncrement, string $schema = null): ?string { @@ -380,13 +345,13 @@ public function prepareSchemaAppend(bool $primaryKey, bool $autoIncrement, strin break; case Schema::SQLITE: - $append = trim(($primaryKey ? 'PRIMARY KEY ' : '') . ($autoIncrement ? 'AUTOINCREMENT' : '')); + $append = \trim(($primaryKey ? 'PRIMARY KEY ' : '') . ($autoIncrement ? 'AUTOINCREMENT' : '')); break; case Schema::CUBRID: case Schema::MYSQL: default: - $append = trim(($autoIncrement ? 'AUTO_INCREMENT ' : '') . ($primaryKey ? 'PRIMARY KEY' : '')); + $append = \trim(($autoIncrement ? 'AUTO_INCREMENT ' : '') . ($primaryKey ? 'PRIMARY KEY' : '')); } return empty($append) ? null : $append; @@ -394,18 +359,14 @@ public function prepareSchemaAppend(bool $primaryKey, bool $autoIncrement, strin /** * Escapes single quotes. - * @param string $value - * @return string */ public function escapeQuotes(string $value): string { - return str_replace('\'', '\\\'', $value); + return \str_replace('\'', '\\\'', $value); } /** * Removes information of primary key in append statement and returns what is left. - * @param string|null $schema - * @return null|string */ public function removeAppendedPrimaryKeyInfo(?string $schema): ?string { @@ -415,27 +376,27 @@ public function removeAppendedPrimaryKeyInfo(?string $schema): ?string switch ($schema) { case Schema::MSSQL: - $cleanedAppend = str_ireplace(['PRIMARY KEY', 'IDENTITY'], '', $this->append); + $cleanedAppend = \str_ireplace(['PRIMARY KEY', 'IDENTITY'], '', $this->append); break; case Schema::OCI: case Schema::PGSQL: - $cleanedAppend = str_ireplace('PRIMARY KEY', '', $this->append); + $cleanedAppend = \str_ireplace('PRIMARY KEY', '', $this->append); break; case Schema::SQLITE: - $cleanedAppend = str_ireplace(['PRIMARY KEY', 'AUTOINCREMENT'], '', $this->append); + $cleanedAppend = \str_ireplace(['PRIMARY KEY', 'AUTOINCREMENT'], '', $this->append); break; case Schema::CUBRID: case Schema::MYSQL: default: - $cleanedAppend = str_ireplace(['PRIMARY KEY', 'AUTO_INCREMENT'], '', $this->append); + $cleanedAppend = \str_ireplace(['PRIMARY KEY', 'AUTO_INCREMENT'], '', $this->append); } - $cleanedAppend = preg_replace('/\s+/', ' ', $cleanedAppend); + $cleanedAppend = \preg_replace('/\s+/', ' ', $cleanedAppend); if ($cleanedAppend !== null) { - $cleanedAppend = trim($cleanedAppend); + $cleanedAppend = \trim($cleanedAppend); } return !empty($cleanedAppend) ? $cleanedAppend : null; @@ -443,8 +404,6 @@ public function removeAppendedPrimaryKeyInfo(?string $schema): ?string /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return string|int|null */ abstract public function getLength(string $schema = null, string $engineVersion = null); @@ -452,8 +411,6 @@ abstract public function getLength(string $schema = null, string $engineVersion /** * Sets length for the column. * @param string|int|array|null $value - * @param string|null $schema - * @param string|null $engineVersion */ abstract public function setLength($value, string $schema = null, string $engineVersion = null): void; } diff --git a/src/table/ColumnFactory.php b/src/table/ColumnFactory.php index 750e8d3..21f75e6 100644 --- a/src/table/ColumnFactory.php +++ b/src/table/ColumnFactory.php @@ -11,8 +11,6 @@ final class ColumnFactory { /** * Builds table column object based on the type. - * @param string $type - * @return ColumnInterface */ public static function build(string $type): ColumnInterface { diff --git a/src/table/ColumnInterface.php b/src/table/ColumnInterface.php index eb5a359..83b6461 100644 --- a/src/table/ColumnInterface.php +++ b/src/table/ColumnInterface.php @@ -8,51 +8,41 @@ interface ColumnInterface { /** * Returns name of the column. - * @return string */ public function getName(): string; /** * Sets name for the column. - * @param string $name */ public function setName(string $name): void; /** * Checks whether the column is a primary key. - * @return bool */ public function isPrimaryKey(): bool; /** * Sets the primary key flag for the column. - * @param bool|null $primaryKey */ public function setPrimaryKey(?bool $primaryKey): void; /** * Checks if column is a part of the primary key. - * @param PrimaryKeyInterface $primaryKey - * @return bool */ public function isColumnInPrimaryKey(PrimaryKeyInterface $primaryKey): bool; /** * Checks if information of primary key is set in append statement. - * @param string|null $schema - * @return bool */ public function isPrimaryKeyInfoAppended(?string $schema): bool; /** * Returns the value of append statement of the column. - * @return string|null */ public function getAppend(): ?string; /** * Sets the value for append statement for the column. - * @param string|null $append */ public function setAppend(?string $append): void; @@ -60,27 +50,21 @@ public function setAppend(?string $append): void; * Prepares append statement based on the schema. * @param bool $primaryKey whether the column is primary key * @param bool $autoIncrement whether the column has autoincrement flag - * @param string|null $schema - * @return string|null */ public function prepareSchemaAppend(bool $primaryKey, bool $autoIncrement, string $schema = null): ?string; /** * Removes information of primary key in append statement and returns what is left. - * @param string|null $schema - * @return null|string */ public function removeAppendedPrimaryKeyInfo(?string $schema): ?string; /** * Sets the value for comment statement for the column. - * @param string|null $comment */ public function setComment(?string $comment): void; /** * Returns the value for comment statement for the column. - * @return string|null */ public function getComment(): ?string; @@ -122,13 +106,11 @@ public function setScale($scale): void; /** * Checks whether the column can not be null. - * @return bool|null */ public function isNotNull(): ?bool; /** * Sets the column to not be null. - * @param bool|null $notNull */ public function setNotNull(?bool $notNull): void; @@ -146,32 +128,26 @@ public function setDefault($default): void; /** * Checks whether the column is unsigned. - * @return bool */ public function isUnsigned(): bool; /** * Sets the unsigned flag for the column. - * @param bool $unsigned */ public function setUnsigned(bool $unsigned): void; /** * Checks whether the column is unique. - * @return bool */ public function isUnique(): bool; /** * Sets the uniqueness of the column. - * @param bool $unique */ public function setUnique(bool $unique): void; /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return string|int|null */ public function getLength(string $schema = null, string $engineVersion = null); @@ -179,56 +155,46 @@ public function getLength(string $schema = null, string $engineVersion = null); /** * Sets length for the column. * @param string|int|array|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void; /** * Returns default column definition. - * @return string */ public function getDefinition(): string; /** * Returns the value for after statement for the column. - * @return string|null */ public function getAfter(): ?string; /** * Sets the value for after statement for the column. - * @param string|null $after */ public function setAfter(?string $after): void; /** * Checks whether the column has first statement. - * @return bool */ public function isFirst(): bool; /** * Sets the column for the first statement. - * @param bool $first */ public function setFirst(bool $first): void; /** * Checks whether the column has autoincrement flag. - * @return bool */ public function isAutoIncrement(): bool; /** * Sets the autoincrement flag for the column. - * @param bool $autoIncrement */ public function setAutoIncrement(bool $autoIncrement): void; /** * Returns type of the column. - * @return string */ public function getType(): string; } diff --git a/src/table/DateColumn.php b/src/table/DateColumn.php index a874e50..ae82377 100644 --- a/src/table/DateColumn.php +++ b/src/table/DateColumn.php @@ -9,8 +9,6 @@ final class DateColumn extends Column implements ColumnInterface /** * Sets length of the column. * @param mixed $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { @@ -18,9 +16,6 @@ public function setLength($value, string $schema = null, string $engineVersion = /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion - * @return int|null */ public function getLength(string $schema = null, string $engineVersion = null): ?int { @@ -29,7 +24,6 @@ public function getLength(string $schema = null, string $engineVersion = null): /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/src/table/DateTimeColumn.php b/src/table/DateTimeColumn.php index b6f94db..ee10a65 100644 --- a/src/table/DateTimeColumn.php +++ b/src/table/DateTimeColumn.php @@ -7,11 +7,6 @@ use bizley\migration\Schema; use yii\db\Expression; -use function in_array; -use function is_string; -use function preg_match; -use function version_compare; - final class DateTimeColumn extends Column implements ColumnInterface { /** @var array Schemas using length for this column */ @@ -24,7 +19,7 @@ final class DateTimeColumn extends Column implements ColumnInterface */ public function setDefault($default): void { - if (is_string($default) && preg_match('/^current_timestamp\([0-9]*\)$/i', $default)) { + if (\is_string($default) && \preg_match('/^current_timestamp\([0-9]*\)$/i', $default)) { // https://github.com/yiisoft/yii2/issues/17744 $default = new Expression($default); } @@ -33,8 +28,6 @@ public function setDefault($default): void /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) @@ -45,8 +38,6 @@ public function getLength(string $schema = null, string $engineVersion = null) /** * Sets length of the column. * @param string|int|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { @@ -58,22 +49,18 @@ public function setLength($value, string $schema = null, string $engineVersion = /** * Checks if schema supports length for this column. * In case of MySQL the engine version must be 5.6.4 or newer. - * @param string|null $schema - * @param string|null $engineVersion - * @return bool */ private function isSchemaLengthSupporting(?string $schema, ?string $engineVersion): bool { - if ($engineVersion && $schema === Schema::MYSQL && version_compare($engineVersion, '5.6.4', '>=')) { + if ($engineVersion && $schema === Schema::MYSQL && \version_compare($engineVersion, '5.6.4', '>=')) { return true; } - return in_array($schema, $this->lengthSchemas, true); + return \in_array($schema, $this->lengthSchemas, true); } /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/src/table/DecimalColumn.php b/src/table/DecimalColumn.php index 827c17c..a3d7b6b 100644 --- a/src/table/DecimalColumn.php +++ b/src/table/DecimalColumn.php @@ -6,10 +6,6 @@ use bizley\migration\Schema; -use function in_array; -use function is_array; -use function preg_split; - final class DecimalColumn extends Column implements ColumnInterface { /** @var array Schemas using length for this column */ @@ -23,13 +19,11 @@ final class DecimalColumn extends Column implements ColumnInterface /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) { - if (!in_array($schema, $this->lengthSchemas, true)) { + if (!\in_array($schema, $this->lengthSchemas, true)) { return null; } @@ -40,17 +34,15 @@ public function getLength(string $schema = null, string $engineVersion = null) /** * Sets length of the column. * @param string|int|array|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { - if (in_array($schema, $this->lengthSchemas, true)) { - if (is_array($value)) { + if (\in_array($schema, $this->lengthSchemas, true)) { + if (\is_array($value)) { $length = $value; } else { /** @var array $length */ - $length = preg_split('/\s*,\s*/', (string)$value); + $length = \preg_split('/\s*,\s*/', (string)$value); } if (!empty($length[0])) { @@ -69,7 +61,6 @@ public function setLength($value, string $schema = null, string $engineVersion = /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/src/table/DoubleColumn.php b/src/table/DoubleColumn.php index 8a4bfc1..0e4ee58 100644 --- a/src/table/DoubleColumn.php +++ b/src/table/DoubleColumn.php @@ -6,8 +6,6 @@ use bizley\migration\Schema; -use function in_array; - final class DoubleColumn extends Column implements ColumnInterface { /** @var array Schemas using length for this column */ @@ -15,31 +13,26 @@ final class DoubleColumn extends Column implements ColumnInterface /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) { - return in_array($schema, $this->lengthSchemas, true) ? $this->getPrecision() : null; + return \in_array($schema, $this->lengthSchemas, true) ? $this->getPrecision() : null; } /** * Sets length of the column. * @param string|int|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { - if (in_array($schema, $this->lengthSchemas, true)) { + if (\in_array($schema, $this->lengthSchemas, true)) { $this->setPrecision($value); } } /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/src/table/FloatColumn.php b/src/table/FloatColumn.php index 7631c04..748618c 100644 --- a/src/table/FloatColumn.php +++ b/src/table/FloatColumn.php @@ -6,8 +6,6 @@ use bizley\migration\Schema; -use function in_array; - final class FloatColumn extends Column implements ColumnInterface { /** @var array Schemas using length for this column */ @@ -15,31 +13,26 @@ final class FloatColumn extends Column implements ColumnInterface /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) { - return in_array($schema, $this->lengthSchemas, true) ? $this->getPrecision() : null; + return \in_array($schema, $this->lengthSchemas, true) ? $this->getPrecision() : null; } /** * Sets length of the column. * @param string|int|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { - if (in_array($schema, $this->lengthSchemas, true)) { + if (\in_array($schema, $this->lengthSchemas, true)) { $this->setPrecision($value); } } /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/src/table/ForeignKey.php b/src/table/ForeignKey.php index 8272647..2113b28 100644 --- a/src/table/ForeignKey.php +++ b/src/table/ForeignKey.php @@ -4,9 +4,6 @@ namespace bizley\migration\table; -use function implode; -use function is_numeric; - final class ForeignKey implements ForeignKeyInterface { /** @var string|null */ @@ -32,19 +29,17 @@ final class ForeignKey implements ForeignKeyInterface /** * Returns name of the foreign key. - * @return string */ public function getName(): string { - if (empty($this->name) || is_numeric($this->name)) { - return "fk-{$this->tableName}-" . implode('-', $this->columns); + if (empty($this->name) || \is_numeric($this->name)) { + return "fk-{$this->tableName}-" . \implode('-', $this->columns); } return $this->name; } /** * Sets name for the foreign key. - * @param string|null $name */ public function setName(?string $name): void { @@ -73,7 +68,6 @@ public function setColumns(?array $columns): void /** * Returns referred table name of the foreign key. - * @return string */ public function getReferredTable(): string { @@ -82,7 +76,6 @@ public function getReferredTable(): string /** * Sets referred table name for the foreign key. - * @param string $referredTable */ public function setReferredTable(string $referredTable): void { @@ -109,7 +102,6 @@ public function setReferredColumns(array $referredColumns): void /** * Returns ON DELETE statement of the foreign key. - * @return string|null */ public function getOnDelete(): ?string { @@ -118,7 +110,6 @@ public function getOnDelete(): ?string /** * Sets ON DELETE statement for the foreign key. - * @param string|null $onDelete */ public function setOnDelete(?string $onDelete): void { @@ -127,7 +118,6 @@ public function setOnDelete(?string $onDelete): void /** * Returns ON UPDATE statement of the foreign key. - * @return string|null */ public function getOnUpdate(): ?string { @@ -136,7 +126,6 @@ public function getOnUpdate(): ?string /** * Sets ON UPDATE statement for the foreign key. - * @param string|null $onUpdate */ public function setOnUpdate(?string $onUpdate): void { @@ -145,7 +134,6 @@ public function setOnUpdate(?string $onUpdate): void /** * Returns table name of the foreign key. - * @return string */ public function getTableName(): string { @@ -154,7 +142,6 @@ public function getTableName(): string /** * Sets table name for the foreign key. - * @param string $tableName */ public function setTableName(string $tableName): void { diff --git a/src/table/ForeignKeyInterface.php b/src/table/ForeignKeyInterface.php index ed30b81..3f971f8 100644 --- a/src/table/ForeignKeyInterface.php +++ b/src/table/ForeignKeyInterface.php @@ -8,13 +8,11 @@ interface ForeignKeyInterface { /** * Returns name of the foreign key. - * @return string */ public function getName(): string; /** * Returns table name of the foreign key. - * @return string */ public function getTableName(): string; @@ -26,7 +24,6 @@ public function getColumns(): array; /** * Returns referred table name of the foreign key. - * @return string */ public function getReferredTable(): string; @@ -38,13 +35,11 @@ public function getReferredColumns(): array; /** * Returns ON DELETE statement of the foreign key. - * @return string|null */ public function getOnDelete(): ?string; /** * Returns ON UPDATE statement of the foreign key. - * @return string|null */ public function getOnUpdate(): ?string; } diff --git a/src/table/Index.php b/src/table/Index.php index 02f47ec..fe040a8 100644 --- a/src/table/Index.php +++ b/src/table/Index.php @@ -17,7 +17,6 @@ final class Index implements IndexInterface /** * Return name of the index. - * @return string|null */ public function getName(): ?string { @@ -26,7 +25,6 @@ public function getName(): ?string /** * Sets name for the index. - * @param string|null $name */ public function setName(?string $name): void { @@ -35,7 +33,6 @@ public function setName(?string $name): void /** * Checks whether the index is unique. - * @return bool */ public function isUnique(): bool { @@ -44,7 +41,6 @@ public function isUnique(): bool /** * Sets unique flag for the index. - * @param bool $unique */ public function setUnique(bool $unique): void { diff --git a/src/table/IndexInterface.php b/src/table/IndexInterface.php index f1ba4c9..71167c4 100644 --- a/src/table/IndexInterface.php +++ b/src/table/IndexInterface.php @@ -8,7 +8,6 @@ interface IndexInterface { /** * Return name of the index. - * @return string|null */ public function getName(): ?string; @@ -20,7 +19,6 @@ public function getColumns(): array; /** * Checks whether the index is unique. - * @return bool */ public function isUnique(): bool; } diff --git a/src/table/IntegerColumn.php b/src/table/IntegerColumn.php index 71d9ad7..10bfc8a 100644 --- a/src/table/IntegerColumn.php +++ b/src/table/IntegerColumn.php @@ -6,9 +6,6 @@ use bizley\migration\Schema; -use function in_array; -use function version_compare; - final class IntegerColumn extends Column implements PrimaryKeyVariantColumnInterface { /** @var array Schemas using length for this column */ @@ -17,23 +14,18 @@ final class IntegerColumn extends Column implements PrimaryKeyVariantColumnInter /** * Checks if schema supports length for this column. * In case of MySQL the engine version must be lower than 8.0.17. - * @param string|null $schema - * @param string|null $engineVersion - * @return bool */ private function isSchemaLengthSupporting(?string $schema, ?string $engineVersion): bool { - if ($engineVersion && $schema === Schema::MYSQL && version_compare($engineVersion, '8.0.17', '<')) { + if ($engineVersion && $schema === Schema::MYSQL && \version_compare($engineVersion, '8.0.17', '<')) { return true; } - return in_array($schema, $this->lengthSchemas, true); + return \in_array($schema, $this->lengthSchemas, true); } /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) @@ -44,8 +36,6 @@ public function getLength(string $schema = null, string $engineVersion = null) /** * Sets length of the column. * @param string|int|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { @@ -57,7 +47,6 @@ public function setLength($value, string $schema = null, string $engineVersion = /** * Returns default column definition. - * @return string */ public function getDefinition(): string { @@ -66,7 +55,6 @@ public function getDefinition(): string /** * Returns primary key variant column definition. - * @return string */ public function getPrimaryKeyDefinition(): string { diff --git a/src/table/JsonColumn.php b/src/table/JsonColumn.php index 3cd2163..89d50cc 100644 --- a/src/table/JsonColumn.php +++ b/src/table/JsonColumn.php @@ -6,8 +6,6 @@ use yii\helpers\Json; -use function is_array; - final class JsonColumn extends Column implements ColumnInterface { /** @@ -17,7 +15,7 @@ final class JsonColumn extends Column implements ColumnInterface */ public function setDefault($default): void { - if (is_array($default)) { + if (\is_array($default)) { $default = Json::encode($default); } parent::setDefault($default); @@ -25,9 +23,6 @@ public function setDefault($default): void /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion - * @return int|null */ public function getLength(string $schema = null, string $engineVersion = null): ?int { @@ -37,8 +32,6 @@ public function getLength(string $schema = null, string $engineVersion = null): /** * Sets length of the column. * @param mixed $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { @@ -46,7 +39,6 @@ public function setLength($value, string $schema = null, string $engineVersion = /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/src/table/MoneyColumn.php b/src/table/MoneyColumn.php index 96a5495..71c340a 100644 --- a/src/table/MoneyColumn.php +++ b/src/table/MoneyColumn.php @@ -4,15 +4,10 @@ namespace bizley\migration\table; -use function is_array; -use function preg_split; - final class MoneyColumn extends Column implements ColumnInterface { /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) @@ -24,16 +19,14 @@ public function getLength(string $schema = null, string $engineVersion = null) /** * Sets length of the column. * @param string|int|array|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { - if (is_array($value)) { + if (\is_array($value)) { $length = $value; } else { /** @var array $length */ - $length = preg_split('/\s*,\s*/', (string)$value); + $length = \preg_split('/\s*,\s*/', (string)$value); } if (!empty($length[0])) { @@ -51,7 +44,6 @@ public function setLength($value, string $schema = null, string $engineVersion = /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/src/table/PrimaryKey.php b/src/table/PrimaryKey.php index 6001e1e..689437b 100644 --- a/src/table/PrimaryKey.php +++ b/src/table/PrimaryKey.php @@ -4,9 +4,6 @@ namespace bizley\migration\table; -use function count; -use function in_array; - final class PrimaryKey implements PrimaryKeyInterface { public const GENERIC_PRIMARY_KEY = 'PRIMARYKEY'; @@ -19,16 +16,14 @@ final class PrimaryKey implements PrimaryKeyInterface /** * Checks whether the primary key is composite. - * @return bool */ public function isComposite(): bool { - return count($this->columns) > 1; + return \count($this->columns) > 1; } /** * Returns name of the primary key. - * @return string */ public function getName(): string { @@ -37,7 +32,6 @@ public function getName(): string /** * Sets name for the primary key. - * @param string|null $name */ public function setName(?string $name): void { @@ -66,11 +60,10 @@ public function setColumns(?array $columns): void /** * Adds column to the primary key. - * @param string $name */ public function addColumn(string $name): void { - if (!in_array($name, $this->columns, true)) { + if (!\in_array($name, $this->columns, true)) { $this->columns[] = $name; } } diff --git a/src/table/PrimaryKeyColumn.php b/src/table/PrimaryKeyColumn.php index 19e3863..6f167d0 100644 --- a/src/table/PrimaryKeyColumn.php +++ b/src/table/PrimaryKeyColumn.php @@ -6,9 +6,6 @@ use bizley\migration\Schema; -use function in_array; -use function version_compare; - class PrimaryKeyColumn extends Column implements PrimaryKeyColumnInterface { /** @var array Schemas using length for this column */ @@ -17,23 +14,18 @@ class PrimaryKeyColumn extends Column implements PrimaryKeyColumnInterface /** * Checks if schema supports length for this column. * In case of MySQL the engine version must be lower than 8.0.17. - * @param string|null $schema - * @param string|null $engineVersion - * @return bool */ private function isSchemaLengthSupporting(?string $schema, ?string $engineVersion): bool { - if ($engineVersion && $schema === Schema::MYSQL && version_compare($engineVersion, '8.0.17', '<')) { + if ($engineVersion && $schema === Schema::MYSQL && \version_compare($engineVersion, '8.0.17', '<')) { return true; } - return in_array($schema, $this->lengthSchemas, true); + return \in_array($schema, $this->lengthSchemas, true); } /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) @@ -44,8 +36,6 @@ public function getLength(string $schema = null, string $engineVersion = null) /** * Sets length of the column. * @param string|int|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { @@ -57,7 +47,6 @@ public function setLength($value, string $schema = null, string $engineVersion = /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/src/table/PrimaryKeyInterface.php b/src/table/PrimaryKeyInterface.php index 64af88f..8f39642 100644 --- a/src/table/PrimaryKeyInterface.php +++ b/src/table/PrimaryKeyInterface.php @@ -8,7 +8,6 @@ interface PrimaryKeyInterface { /** * Returns name of the primary key. - * @return string */ public function getName(): string; @@ -20,13 +19,11 @@ public function getColumns(): array; /** * Checks whether the primary key is composite. - * @return bool */ public function isComposite(): bool; /** * Adds column to the primary key. - * @param string $name */ public function addColumn(string $name): void; } diff --git a/src/table/PrimaryKeyVariantColumnInterface.php b/src/table/PrimaryKeyVariantColumnInterface.php index 07bd239..5252953 100644 --- a/src/table/PrimaryKeyVariantColumnInterface.php +++ b/src/table/PrimaryKeyVariantColumnInterface.php @@ -8,7 +8,6 @@ interface PrimaryKeyVariantColumnInterface extends ColumnInterface { /** * Returns primary key variant column definition. - * @return string */ public function getPrimaryKeyDefinition(): string; } diff --git a/src/table/SmallIntegerColumn.php b/src/table/SmallIntegerColumn.php index 7dc1c5c..2c16a12 100644 --- a/src/table/SmallIntegerColumn.php +++ b/src/table/SmallIntegerColumn.php @@ -6,9 +6,6 @@ use bizley\migration\Schema; -use function in_array; -use function version_compare; - final class SmallIntegerColumn extends Column implements ColumnInterface { /** @var array Schemas using length for this column */ @@ -17,23 +14,18 @@ final class SmallIntegerColumn extends Column implements ColumnInterface /** * Checks if schema supports length for this column. * In case of MySQL the engine version must be lower than 8.0.17. - * @param string|null $schema - * @param string|null $engineVersion - * @return bool */ private function isSchemaLengthSupporting(?string $schema, ?string $engineVersion): bool { - if ($engineVersion && $schema === Schema::MYSQL && version_compare($engineVersion, '8.0.17', '<')) { + if ($engineVersion && $schema === Schema::MYSQL && \version_compare($engineVersion, '8.0.17', '<')) { return true; } - return in_array($schema, $this->lengthSchemas, true); + return \in_array($schema, $this->lengthSchemas, true); } /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) @@ -44,8 +36,6 @@ public function getLength(string $schema = null, string $engineVersion = null) /** * Sets length of the column. * @param string|int|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { @@ -57,7 +47,6 @@ public function setLength($value, string $schema = null, string $engineVersion = /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/src/table/StringColumn.php b/src/table/StringColumn.php index e22adf3..dfb1471 100644 --- a/src/table/StringColumn.php +++ b/src/table/StringColumn.php @@ -8,8 +8,6 @@ final class StringColumn extends Column implements ColumnInterface { /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) @@ -20,8 +18,6 @@ public function getLength(string $schema = null, string $engineVersion = null) /** * Sets length of the column. * @param string|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { @@ -31,7 +27,6 @@ public function setLength($value, string $schema = null, string $engineVersion = /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/src/table/Structure.php b/src/table/Structure.php index 03b6ce0..2d0e18e 100644 --- a/src/table/Structure.php +++ b/src/table/Structure.php @@ -23,7 +23,6 @@ final class Structure implements StructureInterface /** * Returns name of the structure. - * @return string */ public function getName(): string { @@ -32,7 +31,6 @@ public function getName(): string /** * Sets name of the structure. - * @param string $name */ public function setName(string $name): void { @@ -41,7 +39,6 @@ public function setName(string $name): void /** * Returns primary key of the structure. - * @return PrimaryKeyInterface|null */ public function getPrimaryKey(): ?PrimaryKeyInterface { @@ -50,7 +47,6 @@ public function getPrimaryKey(): ?PrimaryKeyInterface /** * Sets primary key of the structure. - * @param PrimaryKeyInterface|null $primaryKey */ public function setPrimaryKey(?PrimaryKeyInterface $primaryKey): void { @@ -77,7 +73,6 @@ public function setColumns(array $columns): void /** * Adds column to the structure. - * @param ColumnInterface $column */ public function addColumn(ColumnInterface $column): void { @@ -86,7 +81,6 @@ public function addColumn(ColumnInterface $column): void /** * Removes column from the structure. - * @param string $name */ public function removeColumn(string $name): void { @@ -95,8 +89,6 @@ public function removeColumn(string $name): void /** * Returns column of given name of the structure. - * @param string $name - * @return ColumnInterface|null */ public function getColumn(string $name): ?ColumnInterface { @@ -114,8 +106,6 @@ public function getIndexes(): array /** * Returns index of given name of the structure. - * @param string $name - * @return IndexInterface|null */ public function getIndex(string $name): ?IndexInterface { @@ -133,7 +123,6 @@ public function setIndexes(array $indexes): void /** * Adds index to the structure. - * @param IndexInterface $index */ public function addIndex(IndexInterface $index): void { @@ -142,7 +131,6 @@ public function addIndex(IndexInterface $index): void /** * Removes index from the structure. - * @param string $name */ public function removeIndex(string $name): void { @@ -160,8 +148,6 @@ public function getForeignKeys(): array /** * Returns foreign key of given name of the structure. - * @param string $name - * @return ForeignKeyInterface|null */ public function getForeignKey(string $name): ?ForeignKeyInterface { @@ -179,7 +165,6 @@ public function setForeignKeys(array $foreignKeys): void /** * Adds foreign key to the structure. - * @param ForeignKeyInterface $foreignKey */ public function addForeignKey(ForeignKeyInterface $foreignKey): void { @@ -188,7 +173,6 @@ public function addForeignKey(ForeignKeyInterface $foreignKey): void /** * Removes foreign key from the structure. - * @param string $name */ public function removeForeignKey(string $name): void { diff --git a/src/table/StructureBuilder.php b/src/table/StructureBuilder.php index e07489f..0405387 100644 --- a/src/table/StructureBuilder.php +++ b/src/table/StructureBuilder.php @@ -7,18 +7,11 @@ use bizley\migration\Schema; use yii\base\InvalidArgumentException; -use function array_intersect_assoc; -use function array_key_exists; -use function count; - final class StructureBuilder implements StructureBuilderInterface { /** * Builds table structure based on the list of changes from the Inspector. * @param array $changes - * @param string|null $schema - * @param string|null $engineVersion - * @return StructureInterface */ public function build(array $changes, ?string $schema, ?string $engineVersion): StructureInterface { @@ -99,10 +92,7 @@ public function build(array $changes, ?string $schema, ?string $engineVersion): /** * Applies create table value. - * @param StructureInterface $structure * @param array $columns - * @param string|null $schema - * @param string|null $engineVersion */ private function applyCreateTableValue( StructureInterface $structure, @@ -117,10 +107,6 @@ private function applyCreateTableValue( /** * Applies add column value. - * @param StructureInterface $structure - * @param ColumnInterface $column - * @param string|null $schema - * @param string|null $engineVersion */ private function applyAddColumnValue( StructureInterface $structure, @@ -152,8 +138,6 @@ private function applyAddColumnValue( /** * Applies drop column value. - * @param StructureInterface $structure - * @param string $columnName */ private function applyDropColumnValue(StructureInterface $structure, string $columnName): void { @@ -162,7 +146,6 @@ private function applyDropColumnValue(StructureInterface $structure, string $col /** * Applies rename column value. - * @param StructureInterface $structure * @param array $data */ private function applyRenameColumnValue(StructureInterface $structure, array $data): void @@ -178,9 +161,6 @@ private function applyRenameColumnValue(StructureInterface $structure, array $da /** * Applies add primary key value. - * @param StructureInterface $structure - * @param PrimaryKeyInterface $primaryKey - * @param string|null $schema */ private function applyAddPrimaryKeyValue( StructureInterface $structure, @@ -192,7 +172,7 @@ private function applyAddPrimaryKeyValue( $columns = $structure->getColumns(); foreach ($primaryKey->getColumns() as $columnName) { - if (array_key_exists($columnName, $columns)) { + if (\array_key_exists($columnName, $columns)) { $column = $columns[$columnName]; $columnAppend = $column->getAppend(); if (empty($columnAppend)) { @@ -206,8 +186,6 @@ private function applyAddPrimaryKeyValue( /** * Applies drop primary key value. - * @param StructureInterface $structure - * @param string|null $schema */ private function applyDropPrimaryKeyValue(StructureInterface $structure, ?string $schema): void { @@ -218,7 +196,7 @@ private function applyDropPrimaryKeyValue(StructureInterface $structure, ?string foreach ($primaryKey->getColumns() as $columnName) { $column = $columns[$columnName]; $columnAppend = $column->getAppend(); - if (array_key_exists($columnName, $columns) && !empty($columnAppend)) { + if (\array_key_exists($columnName, $columns) && !empty($columnAppend)) { $column->setAppend($column->removeAppendedPrimaryKeyInfo($schema)); } } @@ -229,8 +207,6 @@ private function applyDropPrimaryKeyValue(StructureInterface $structure, ?string /** * Applies add foreign key value. - * @param StructureInterface $structure - * @param ForeignKeyInterface $foreignKey */ private function applyAddForeignKeyValue(StructureInterface $structure, ForeignKeyInterface $foreignKey): void { @@ -239,8 +215,6 @@ private function applyAddForeignKeyValue(StructureInterface $structure, ForeignK /** * Applies drop foreign key value. - * @param StructureInterface $structure - * @param string $name */ private function applyDropForeignKeyValue(StructureInterface $structure, string $name): void { @@ -249,8 +223,6 @@ private function applyDropForeignKeyValue(StructureInterface $structure, string /** * Applies create index value. - * @param StructureInterface $structure - * @param IndexInterface $index */ private function applyCreateIndexValue(StructureInterface $structure, IndexInterface $index): void { @@ -259,8 +231,8 @@ private function applyCreateIndexValue(StructureInterface $structure, IndexInter $indexColumns = $index->getColumns(); if ( $index->isUnique() - && count($indexColumns) === 1 - && array_key_exists($indexColumns[0], $structure->getColumns()) + && \count($indexColumns) === 1 + && \array_key_exists($indexColumns[0], $structure->getColumns()) ) { /** @var ColumnInterface $column */ $column = $structure->getColumn($indexColumns[0]); @@ -270,8 +242,6 @@ private function applyCreateIndexValue(StructureInterface $structure, IndexInter /** * Applies drop index value. - * @param StructureInterface $structure - * @param string $name */ private function applyDropIndexValue(StructureInterface $structure, string $name): void { @@ -280,8 +250,8 @@ private function applyDropIndexValue(StructureInterface $structure, string $name $indexColumns = $index->getColumns(); if ( $index->isUnique() - && count($indexColumns) === 1 - && array_key_exists($indexColumns[0], $structure->getColumns()) + && \count($indexColumns) === 1 + && \array_key_exists($indexColumns[0], $structure->getColumns()) && ($column = $structure->getColumn($indexColumns[0])) !== null && $column->isUnique() ) { @@ -294,7 +264,6 @@ private function applyDropIndexValue(StructureInterface $structure, string $name /** * Applies add comment on column value. - * @param StructureInterface $structure * @param array $data */ private function applyAddCommentOnColumnValue(StructureInterface $structure, array $data): void @@ -307,8 +276,6 @@ private function applyAddCommentOnColumnValue(StructureInterface $structure, arr /** * Applies drop comment from column value. - * @param StructureInterface $structure - * @param string $columnName */ private function applyDropCommentFromColumnValue(StructureInterface $structure, string $columnName): void { @@ -320,8 +287,6 @@ private function applyDropCommentFromColumnValue(StructureInterface $structure, /** * Adds automatic indexes made by DB engine. - * @param StructureInterface $structure - * @param string|null $schema */ private function addHiddenIndexes(StructureInterface $structure, ?string $schema): void { @@ -340,7 +305,7 @@ private function addHiddenIndexes(StructureInterface $structure, ?string $schema $foreignKeyColumnsCount = count($foreignKeyColumns); foreach ($indexes as $index) { $indexColumns = $index->getColumns(); - if ($foreignKeyColumnsCount === count(array_intersect_assoc($foreignKeyColumns, $indexColumns))) { + if ($foreignKeyColumnsCount === \count(\array_intersect_assoc($foreignKeyColumns, $indexColumns))) { // any index matching the FK columns as the first columns will do continue 2; } diff --git a/src/table/StructureBuilderInterface.php b/src/table/StructureBuilderInterface.php index 958355b..5bcff41 100644 --- a/src/table/StructureBuilderInterface.php +++ b/src/table/StructureBuilderInterface.php @@ -9,9 +9,6 @@ interface StructureBuilderInterface /** * Builds table structure based on the list of changes from the Inspector. * @param array $changes - * @param string|null $schema - * @param string|null $engineVersion - * @return StructureInterface */ public function build(array $changes, ?string $schema, ?string $engineVersion): StructureInterface; } diff --git a/src/table/StructureChange.php b/src/table/StructureChange.php index eebf0f0..2e0b09a 100644 --- a/src/table/StructureChange.php +++ b/src/table/StructureChange.php @@ -6,9 +6,6 @@ use InvalidArgumentException; -use function array_key_exists; -use function is_array; - final class StructureChange implements StructureChangeInterface { /** @var string */ @@ -22,7 +19,6 @@ final class StructureChange implements StructureChangeInterface /** * Returns table name of the change. - * @return string */ public function getTable(): string { @@ -31,7 +27,6 @@ public function getTable(): string /** * Sets table name for the change. - * @param string $table */ public function setTable(string $table): void { @@ -40,7 +35,6 @@ public function setTable(string $table): void /** * Returns method of the change. - * @return string */ public function getMethod(): string { @@ -49,7 +43,6 @@ public function getMethod(): string /** * Sets method for the change. - * @param string $method */ public function setMethod(string $method): void { @@ -76,8 +69,6 @@ public function setData($data): void /** * Returns value of the change based on the method. - * @param string|null $schema - * @param string|null $engineVersion * @return mixed Change value */ public function getValue(string $schema = null, string $engineVersion = null) @@ -119,8 +110,6 @@ public function getValue(string $schema = null, string $engineVersion = null) /** * Returns create table value of the change. - * @param string|null $engineName - * @param string|null $engineVersion * @return array */ private function getValueForCreateTable(string $engineName = null, string $engineVersion = null): array @@ -128,7 +117,7 @@ private function getValueForCreateTable(string $engineName = null, string $engin $columns = []; $data = $this->getData(); - if (!is_array($data)) { + if (!\is_array($data)) { throw new InvalidArgumentException('Wrong data for createTable method.'); } @@ -144,7 +133,7 @@ private function getValueForCreateTable(string $engineName = null, string $engin $column->setAppend($schema['append'] ?? null); $column->setUnsigned($schema['isUnsigned'] ?? false); $column->setComment( - (array_key_exists('comment', $schema) && !empty($schema['comment'])) ? $schema['comment'] : null + (\array_key_exists('comment', $schema) && !empty($schema['comment'])) ? $schema['comment'] : null ); $column->setAfter($schema['after'] ?? null); $column->setFirst($schema['isFirst'] ?? false); @@ -164,11 +153,11 @@ private function getValueForRenameColumn(): array /** @var array $data */ $data = $this->getData(); if ( - !is_array($data) - || !array_key_exists('new', $data) - || !array_key_exists('old', $data) - || !is_string($data['new']) - || !is_string($data['old']) + !\is_array($data) + || !\array_key_exists('new', $data) + || !\array_key_exists('old', $data) + || !\is_string($data['new']) + || !\is_string($data['old']) ) { throw new InvalidArgumentException('Wrong data for renameColumn method.'); } @@ -178,19 +167,16 @@ private function getValueForRenameColumn(): array /** * Returns add column value of the change. - * @param string|null $engineName - * @param string|null $engineVersion - * @return ColumnInterface */ private function getValueForAddColumn(string $engineName = null, string $engineVersion = null): ColumnInterface { $data = $this->getData(); if ( - !is_array($data) - || !array_key_exists('name', $data) - || !array_key_exists('schema', $data) - || !is_string($data['name']) - || !is_array($data['schema']) + !\is_array($data) + || !\array_key_exists('name', $data) + || !\array_key_exists('schema', $data) + || !\is_string($data['name']) + || !\is_array($data['schema']) ) { throw new InvalidArgumentException('Wrong data for addColumn method.'); } @@ -214,17 +200,16 @@ private function getValueForAddColumn(string $engineName = null, string $engineV /** * Returns add primary key value of the change. - * @return PrimaryKeyInterface */ private function getValueForAddPrimaryKey(): PrimaryKeyInterface { $data = $this->getData(); if ( - !is_array($data) - || !array_key_exists('name', $data) - || !array_key_exists('columns', $data) - || !is_string($data['name']) - || !is_array($data['columns']) + !\is_array($data) + || !\array_key_exists('name', $data) + || !\array_key_exists('columns', $data) + || !\is_string($data['name']) + || !\is_array($data['columns']) ) { throw new InvalidArgumentException('Wrong data for addPrimaryKey method.'); } @@ -238,27 +223,26 @@ private function getValueForAddPrimaryKey(): PrimaryKeyInterface /** * Returns add foreign key value of the change. - * @return ForeignKeyInterface */ private function getValueForAddForeignKey(): ForeignKeyInterface { $data = $this->getData(); if ( - !is_array($data) - || !array_key_exists('name', $data) - || !array_key_exists('columns', $data) - || !array_key_exists('referredTable', $data) - || !array_key_exists('referredColumns', $data) - || !array_key_exists('onDelete', $data) - || !array_key_exists('onUpdate', $data) - || !array_key_exists('tableName', $data) - || !is_string($data['name']) - || !is_array($data['columns']) - || !is_string($data['referredTable']) - || !is_array($data['referredColumns']) - || ($data['onDelete'] !== null && !is_string($data['onDelete'])) - || ($data['onUpdate'] !== null && !is_string($data['onUpdate'])) - || !is_string($data['tableName']) + !\is_array($data) + || !\array_key_exists('name', $data) + || !\array_key_exists('columns', $data) + || !\array_key_exists('referredTable', $data) + || !\array_key_exists('referredColumns', $data) + || !\array_key_exists('onDelete', $data) + || !\array_key_exists('onUpdate', $data) + || !\array_key_exists('tableName', $data) + || !\is_string($data['name']) + || !\is_array($data['columns']) + || !\is_string($data['referredTable']) + || !\is_array($data['referredColumns']) + || ($data['onDelete'] !== null && !\is_string($data['onDelete'])) + || ($data['onUpdate'] !== null && !\is_string($data['onUpdate'])) + || !\is_string($data['tableName']) ) { throw new InvalidArgumentException('Wrong data for addForeignKey method.'); } @@ -277,19 +261,18 @@ private function getValueForAddForeignKey(): ForeignKeyInterface /** * Returns create index value of the change. - * @return IndexInterface */ private function getValueForCreateIndex(): IndexInterface { $data = $this->getData(); if ( - !is_array($data) - || !array_key_exists('name', $data) - || !array_key_exists('columns', $data) - || !array_key_exists('unique', $data) - || !is_string($data['name']) - || !is_array($data['columns']) - || !is_bool($data['unique']) + !\is_array($data) + || !\array_key_exists('name', $data) + || !\array_key_exists('columns', $data) + || !\array_key_exists('unique', $data) + || !\is_string($data['name']) + || !\is_array($data['columns']) + || !\is_bool($data['unique']) ) { throw new InvalidArgumentException('Wrong data for createIndex method.'); } @@ -311,11 +294,11 @@ private function getValueForAddCommentOnColumn(): array /** @var array $data */ $data = $this->getData(); if ( - !is_array($data) - || !array_key_exists('column', $data) - || !array_key_exists('comment', $data) - || !is_string($data['column']) - || !is_string($data['comment']) + !\is_array($data) + || !\array_key_exists('column', $data) + || !\array_key_exists('comment', $data) + || !\is_string($data['column']) + || !\is_string($data['comment']) ) { throw new InvalidArgumentException('Wrong data for addCommentOnColumn.'); } diff --git a/src/table/StructureChangeInterface.php b/src/table/StructureChangeInterface.php index c47aeee..b563ee9 100644 --- a/src/table/StructureChangeInterface.php +++ b/src/table/StructureChangeInterface.php @@ -8,20 +8,16 @@ interface StructureChangeInterface { /** * Returns table name of the change. - * @return string */ public function getTable(): string; /** * Returns method of the change. - * @return string */ public function getMethod(): string; /** * Returns value of the change based on the method. - * @param string|null $schema - * @param string|null $engineVersion * @return mixed Change value */ public function getValue(string $schema = null, string $engineVersion = null); diff --git a/src/table/StructureInterface.php b/src/table/StructureInterface.php index db020cc..5919a95 100644 --- a/src/table/StructureInterface.php +++ b/src/table/StructureInterface.php @@ -8,31 +8,26 @@ interface StructureInterface { /** * Returns name of the structure. - * @return string */ public function getName(): string; /** * Returns primary key of the structure. - * @return PrimaryKeyInterface|null */ public function getPrimaryKey(): ?PrimaryKeyInterface; /** * Sets primary key of the structure. - * @param PrimaryKeyInterface|null $primaryKey */ public function setPrimaryKey(?PrimaryKeyInterface $primaryKey): void; /** * Adds column to the structure. - * @param ColumnInterface $column */ public function addColumn(ColumnInterface $column): void; /** * Removes column from the structure. - * @param string $name */ public function removeColumn(string $name): void; @@ -44,8 +39,6 @@ public function getColumns(): array; /** * Returns column of given name of the structure. - * @param string $name - * @return ColumnInterface|null */ public function getColumn(string $name): ?ColumnInterface; @@ -57,26 +50,21 @@ public function getForeignKeys(): array; /** * Returns foreign key of given name of the structure. - * @param string $name - * @return ForeignKeyInterface|null */ public function getForeignKey(string $name): ?ForeignKeyInterface; /** * Adds foreign key to the structure. - * @param ForeignKeyInterface $foreignKey */ public function addForeignKey(ForeignKeyInterface $foreignKey): void; /** * Removes foreign key from the structure. - * @param string $name */ public function removeForeignKey(string $name): void; /** * Adds index to the structure. - * @param IndexInterface $index */ public function addIndex(IndexInterface $index): void; @@ -88,14 +76,11 @@ public function getIndexes(): array; /** * Returns index of given name of the structure. - * @param string $name - * @return IndexInterface|null */ public function getIndex(string $name): ?IndexInterface; /** * Removes index from the structure. - * @param string $name */ public function removeIndex(string $name): void; } diff --git a/src/table/TextColumn.php b/src/table/TextColumn.php index e43770b..b5aa4f8 100644 --- a/src/table/TextColumn.php +++ b/src/table/TextColumn.php @@ -6,8 +6,6 @@ use bizley\migration\Schema; -use function in_array; - final class TextColumn extends Column implements ColumnInterface { /** @var array Schemas using length for this column */ @@ -15,24 +13,20 @@ final class TextColumn extends Column implements ColumnInterface /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) { - return in_array($schema, $this->lengthSchemas, true) ? $this->getSize() : null; + return \in_array($schema, $this->lengthSchemas, true) ? $this->getSize() : null; } /** * Sets length of the column. * @param string|int|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { - if (in_array($schema, $this->lengthSchemas, true)) { + if (\in_array($schema, $this->lengthSchemas, true)) { $this->setSize($value); $this->setPrecision($value); } @@ -40,7 +34,6 @@ public function setLength($value, string $schema = null, string $engineVersion = /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/src/table/TimeColumn.php b/src/table/TimeColumn.php index 15af937..5ab6843 100644 --- a/src/table/TimeColumn.php +++ b/src/table/TimeColumn.php @@ -6,9 +6,6 @@ use bizley\migration\Schema; -use function in_array; -use function version_compare; - final class TimeColumn extends Column implements ColumnInterface { /** @var array Schemas using length for this column */ @@ -17,23 +14,18 @@ final class TimeColumn extends Column implements ColumnInterface /** * Checks if schema supports length for this column. * In case of MySQL the engine version must be 5.6.4 or newer. - * @param string|null $schema - * @param string|null $engineVersion - * @return bool */ private function isSchemaLengthSupporting(?string $schema, ?string $engineVersion): bool { - if ($engineVersion && $schema === Schema::MYSQL && version_compare($engineVersion, '5.6.4', '>=')) { + if ($engineVersion && $schema === Schema::MYSQL && \version_compare($engineVersion, '5.6.4', '>=')) { return true; } - return in_array($schema, $this->lengthSchemas, true); + return \in_array($schema, $this->lengthSchemas, true); } /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) @@ -44,8 +36,6 @@ public function getLength(string $schema = null, string $engineVersion = null) /** * Sets length of the column. * @param string|int $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { @@ -56,7 +46,6 @@ public function setLength($value, string $schema = null, string $engineVersion = /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/src/table/TimestampColumn.php b/src/table/TimestampColumn.php index b5934fb..11ffd92 100644 --- a/src/table/TimestampColumn.php +++ b/src/table/TimestampColumn.php @@ -7,11 +7,6 @@ use bizley\migration\Schema; use yii\db\Expression; -use function in_array; -use function is_string; -use function preg_match; -use function version_compare; - final class TimestampColumn extends Column implements ColumnInterface { /** @var array Schemas using length for this column */ @@ -24,7 +19,7 @@ final class TimestampColumn extends Column implements ColumnInterface */ public function setDefault($default): void { - if (is_string($default) && preg_match('/^current_timestamp\([0-9]*\)$/i', $default)) { + if (\is_string($default) && \preg_match('/^current_timestamp\([0-9]*\)$/i', $default)) { // https://github.com/yiisoft/yii2/issues/17744 $default = new Expression($default); } @@ -34,23 +29,19 @@ public function setDefault($default): void /** * Checks if schema supports length for this column. * In case of MySQL the engine version must be 5.6.4 or newer. - * @param string|null $schema - * @param string|null $engineVersion * @return bool */ private function isSchemaLengthSupporting(?string $schema, ?string $engineVersion): bool { - if ($engineVersion && $schema === Schema::MYSQL && version_compare($engineVersion, '5.6.4', '>=')) { + if ($engineVersion && $schema === Schema::MYSQL && \version_compare($engineVersion, '5.6.4', '>=')) { return true; } - return in_array($schema, $this->lengthSchemas, true); + return \in_array($schema, $this->lengthSchemas, true); } /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) @@ -61,8 +52,6 @@ public function getLength(string $schema = null, string $engineVersion = null) /** * Sets length of the column. * @param string|int|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { @@ -73,7 +62,6 @@ public function setLength($value, string $schema = null, string $engineVersion = /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/src/table/TinyIntegerColumn.php b/src/table/TinyIntegerColumn.php index 47e0ca0..490294b 100644 --- a/src/table/TinyIntegerColumn.php +++ b/src/table/TinyIntegerColumn.php @@ -6,9 +6,6 @@ use bizley\migration\Schema; -use function in_array; -use function version_compare; - final class TinyIntegerColumn extends Column implements ColumnInterface { /** @var array Schemas using length for this column */ @@ -17,23 +14,18 @@ final class TinyIntegerColumn extends Column implements ColumnInterface /** * Checks if schema supports length for this column. * In case of MySQL the engine version must be lower than 8.0.17. - * @param string|null $schema - * @param string|null $engineVersion - * @return bool */ private function isSchemaLengthSupporting(?string $schema, ?string $engineVersion): bool { - if ($engineVersion && $schema === Schema::MYSQL && version_compare($engineVersion, '8.0.17', '<')) { + if ($engineVersion && $schema === Schema::MYSQL && \version_compare($engineVersion, '8.0.17', '<')) { return true; } - return in_array($schema, $this->lengthSchemas, true); + return \in_array($schema, $this->lengthSchemas, true); } /** * Returns length of the column. - * @param string|null $schema - * @param string|null $engineVersion * @return int|string|null */ public function getLength(string $schema = null, string $engineVersion = null) @@ -53,8 +45,6 @@ public function getLength(string $schema = null, string $engineVersion = null) /** * Sets length of the column. * @param string|int|null $value - * @param string|null $schema - * @param string|null $engineVersion */ public function setLength($value, string $schema = null, string $engineVersion = null): void { @@ -69,7 +59,6 @@ public function setLength($value, string $schema = null, string $engineVersion = /** * Returns default column definition. - * @return string */ public function getDefinition(): string { diff --git a/tests/config.php b/tests/config.php index 541137b..689f751 100644 --- a/tests/config.php +++ b/tests/config.php @@ -6,13 +6,13 @@ $config = [ 'mysql' => [ - 'dsn' => 'mysql:host=127.0.0.1;dbname=migration', + 'dsn' => 'mysql:host=127.0.0.1:3406;dbname=migration', 'username' => 'migration', 'password' => 'password', 'charset' => 'utf8mb4', ], 'pgsql' => [ - 'dsn' => 'pgsql:host=127.0.0.1;dbname=migration', + 'dsn' => 'pgsql:host=127.0.0.1:5532;dbname=migration', 'username' => 'migration', 'password' => 'password', ], diff --git a/tests/docker/docker-compose.yml b/tests/docker/docker-compose.yml index d947ed7..3b3fbdd 100644 --- a/tests/docker/docker-compose.yml +++ b/tests/docker/docker-compose.yml @@ -4,7 +4,7 @@ services: restart: "no" image: mysql:8.0 ports: - - 3306:3306 + - "3406:3306" environment: - MYSQL_ROOT_PASSWORD=password - MYSQL_DATABASE=migration @@ -17,7 +17,7 @@ services: restart: "no" image: postgres:12.5 ports: - - 5432:5432 + - "5532:5432" environment: - POSTGRES_DB=migration - POSTGRES_USER=migration diff --git a/tests/functional/DbLoaderTestCase.php b/tests/functional/DbLoaderTestCase.php index 707b0a9..803ca03 100644 --- a/tests/functional/DbLoaderTestCase.php +++ b/tests/functional/DbLoaderTestCase.php @@ -11,9 +11,6 @@ use yii\db\Exception; use yii\db\SchemaBuilderTrait; -use function array_reverse; -use function time; - abstract class DbLoaderTestCase extends DbTestCase { use SchemaBuilderTrait; @@ -36,7 +33,7 @@ protected function getDb(): Connection */ protected function createTables(array $tables): void { - foreach (array_reverse($tables) as $table => $columns) { + foreach (\array_reverse($tables) as $table => $columns) { $this->dropTable($table); } diff --git a/tests/functional/DbTestCase.php b/tests/functional/DbTestCase.php index f481206..a7b3678 100644 --- a/tests/functional/DbTestCase.php +++ b/tests/functional/DbTestCase.php @@ -12,8 +12,6 @@ use yii\db\Connection; use yii\db\Exception; -use function array_key_exists; - abstract class DbTestCase extends TestCase { /** @var string */ @@ -70,7 +68,7 @@ public static function getConnection(): Connection $params = require __DIR__ . '/../config.php'; - if (!array_key_exists(static::$schema, $params)) { + if (!\array_key_exists(static::$schema, $params)) { throw new InvalidConfigException('There is no configuration for requested DBMS'); } diff --git a/tests/functional/mysql/GeneratorTest.php b/tests/functional/mysql/GeneratorTest.php index be261e1..8f0a168 100644 --- a/tests/functional/mysql/GeneratorTest.php +++ b/tests/functional/mysql/GeneratorTest.php @@ -5,17 +5,12 @@ namespace bizley\tests\functional\mysql; use bizley\tests\stubs\MigrationControllerStub; -use PDO; -use Throwable; use yii\base\InvalidRouteException; use yii\base\NotSupportedException; use yii\console\Exception as ConsoleException; use yii\console\ExitCode; use yii\db\Exception; -use function preg_match_all; -use function version_compare; - /** @group mysql */ final class GeneratorTest extends \bizley\tests\functional\GeneratorTest { @@ -30,8 +25,8 @@ final class GeneratorTest extends \bizley\tests\functional\GeneratorTest public function isV8(): bool { if ($this->v8 === null) { - $this->v8 = version_compare( - $this->getDb()->getSlavePdo()->getAttribute(PDO::ATTR_SERVER_VERSION), + $this->v8 = \version_compare( + $this->getDb()->getSlavePdo()->getAttribute(\PDO::ATTR_SERVER_VERSION), '8.0.17', '>=' ); @@ -514,7 +509,7 @@ public function shouldGenerateGeneralSchemaTableWithForeignKey(): void { try { $this->getDb()->createCommand()->dropForeignKey('fk-table12', 'table12')->execute(); - } catch (Throwable $exception) { + } catch (\Throwable $exception) { } $this->createTables( [ @@ -581,7 +576,7 @@ public function shouldGenerateGeneralSchemaCrossReferredTables(): void try { $this->getDb()->createCommand()->dropForeignKey('fk-table21', 'table21')->execute(); $this->getDb()->createCommand()->dropForeignKey('fk-table22', 'table22')->execute(); - } catch (Throwable $exception) { + } catch (\Throwable $exception) { } $this->createTables( @@ -711,7 +706,7 @@ public function shouldGenerateGeneralSchemaTablesInProperOrder(): void try { $this->getDb()->createCommand()->dropForeignKey('fk-table31', 'table31')->execute(); $this->getDb()->createCommand()->dropForeignKey('fk-table32', 'table32')->execute(); - } catch (Throwable $exception) { + } catch (\Throwable $exception) { } $this->createTables( @@ -747,7 +742,7 @@ public function shouldGenerateGeneralSchemaTablesInProperOrder(): void )->execute(); self::assertEquals(ExitCode::OK, $this->controller->runAction('create', ['table31,table32,table33'])); - preg_match_all('/create_table_table(\d{2})/', MigrationControllerStub::$content, $matches); + \preg_match_all('/create_table_table(\d{2})/', MigrationControllerStub::$content, $matches); self::assertSame(['33', '32', '31'], $matches[1]); } diff --git a/tests/functional/mysql/UpdaterShowTest.php b/tests/functional/mysql/UpdaterShowTest.php index e35b1bd..f653c94 100644 --- a/tests/functional/mysql/UpdaterShowTest.php +++ b/tests/functional/mysql/UpdaterShowTest.php @@ -11,8 +11,6 @@ use yii\console\Exception as ConsoleException; use yii\console\ExitCode; -use function version_compare; - /** @group mysql */ final class UpdaterShowTest extends \bizley\tests\functional\UpdaterShowTest { @@ -27,7 +25,7 @@ final class UpdaterShowTest extends \bizley\tests\functional\UpdaterShowTest public function isV8(): bool { if ($this->v8 === null) { - $this->v8 = version_compare( + $this->v8 = \version_compare( $this->getDb()->getSlavePdo()->getAttribute(PDO::ATTR_SERVER_VERSION), '8.0.17', '>=' diff --git a/tests/functional/pgsql/GeneratorTest.php b/tests/functional/pgsql/GeneratorTest.php index b87f34f..7541bc2 100644 --- a/tests/functional/pgsql/GeneratorTest.php +++ b/tests/functional/pgsql/GeneratorTest.php @@ -5,7 +5,6 @@ namespace bizley\tests\functional\pgsql; use bizley\tests\stubs\MigrationControllerStub; -use Throwable; use yii\base\InvalidRouteException; use yii\base\NotSupportedException; use yii\console\Exception as ConsoleException; @@ -389,7 +388,7 @@ public function shouldGenerateGeneralSchemaTableWithForeignKey(): void { try { $this->getDb()->createCommand()->dropForeignKey('fk-table12', 'table12')->execute(); - } catch (Throwable $exception) { + } catch (\Throwable $exception) { } $this->createTables( [ @@ -437,7 +436,7 @@ public function shouldGenerateGeneralSchemaCrossReferredTables(): void try { $this->getDb()->createCommand()->dropForeignKey('fk-table21', 'table21')->execute(); $this->getDb()->createCommand()->dropForeignKey('fk-table22', 'table22')->execute(); - } catch (Throwable $exception) { + } catch (\Throwable $exception) { } $this->createTables( @@ -565,7 +564,7 @@ public function shouldGenerateGeneralSchemaTablesInProperOrder(): void try { $this->getDb()->createCommand()->dropForeignKey('fk-table31', 'table31')->execute(); $this->getDb()->createCommand()->dropForeignKey('fk-table32', 'table32')->execute(); - } catch (Throwable $exception) { + } catch (\Throwable $exception) { } $this->createTables( diff --git a/tests/stubs/GeneratorStub.php b/tests/stubs/GeneratorStub.php index db37127..7a86925 100644 --- a/tests/stubs/GeneratorStub.php +++ b/tests/stubs/GeneratorStub.php @@ -27,7 +27,7 @@ public function generateForTable( string $dbPrefix = '', string $namespace = null ): string { - if (static::$throwForTable) { + if (self::$throwForTable) { throw new Exception('Stub exception'); } return ''; @@ -40,7 +40,7 @@ public function generateForForeignKeys( string $dbPrefix = '', string $namespace = null ): string { - if (static::$throwForKeys) { + if (self::$throwForKeys) { throw new Exception('Stub exception'); } return ''; diff --git a/tests/stubs/MigrateControllerStub.php b/tests/stubs/MigrateControllerStub.php index b174685..d040c10 100644 --- a/tests/stubs/MigrateControllerStub.php +++ b/tests/stubs/MigrateControllerStub.php @@ -13,6 +13,6 @@ final class MigrateControllerStub extends MigrateController public function stdout($string) // BC declaration { - static::$stdout .= $string; + self::$stdout .= $string; } } diff --git a/tests/stubs/UpdaterStub.php b/tests/stubs/UpdaterStub.php index 72dc35a..86cac53 100644 --- a/tests/stubs/UpdaterStub.php +++ b/tests/stubs/UpdaterStub.php @@ -30,10 +30,10 @@ public function prepareBlueprint( array $migrationsToSkip, array $migrationPaths ): BlueprintInterface { - if (static::$throwForPrepare) { + if (self::$throwForPrepare) { throw new NotSupportedException('Stub Exception'); } - return static::$blueprint; + return self::$blueprint; } public function generateFromBlueprint( @@ -43,7 +43,7 @@ public function generateFromBlueprint( string $dbPrefix = '', string $namespace = null ): string { - if (static::$throwForGenerate) { + if (self::$throwForGenerate) { throw new NotSupportedException('Stub Exception'); } return ''; diff --git a/tests/unit/ArrangerTest.php b/tests/unit/ArrangerTest.php index d3217d8..25053e3 100644 --- a/tests/unit/ArrangerTest.php +++ b/tests/unit/ArrangerTest.php @@ -12,8 +12,6 @@ use PHPUnit\Framework\TestCase; use yii\base\NotSupportedException; -use function array_keys; - /** @group arranger */ final class ArrangerTest extends TestCase { @@ -61,7 +59,7 @@ public function shouldArrangeTables( $structure = $this->createMock(StructureInterface::class); $callbacks = []; - foreach ($inputData as $tableName => $referencedTables) { + foreach ($inputData as $referencedTables) { $mockedReferencedTables = []; foreach ($referencedTables as $referencedTable) { $foreignKey = $this->createMock(ForeignKeyInterface::class); @@ -72,12 +70,12 @@ public function shouldArrangeTables( } $structure->method('getForeignKeys')->willReturnOnConsecutiveCalls(...$callbacks); - /** @var TableMapperInterface|MockObject $tableMapper */ + /** @var TableMapperInterface&MockObject $tableMapper */ $tableMapper = $this->createMock(TableMapperInterface::class); $tableMapper->method('getStructureOf')->willReturn($structure); $arranger = new Arranger($tableMapper); - $arranger->arrangeTables(array_keys($inputData)); + $arranger->arrangeTables(\array_keys($inputData)); self::assertSame($tablesInOrder, $arranger->getTablesInOrder()); self::assertSame($referencesToPostpone, $arranger->getReferencesToPostpone()); diff --git a/tests/unit/ComparatorNonSqliteTest.php b/tests/unit/ComparatorNonSqliteTest.php index ebb3331..ebd8bac 100644 --- a/tests/unit/ComparatorNonSqliteTest.php +++ b/tests/unit/ComparatorNonSqliteTest.php @@ -14,15 +14,13 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use function array_keys; - /** @group comparator */ class ComparatorNonSqliteTest extends TestCase { - /** @var StructureInterface|MockObject */ + /** @var StructureInterface&MockObject */ public $newStructure; - /** @var StructureInterface|MockObject */ + /** @var StructureInterface&MockObject */ public $oldStructure; /** @var Blueprint */ @@ -108,7 +106,7 @@ public function shouldAddColumns(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['col1', 'col2'], array_keys($this->blueprint->getAddedColumns())); + self::assertSame(['col1', 'col2'], \array_keys($this->blueprint->getAddedColumns())); } /** @@ -124,7 +122,7 @@ public function shouldDropColumn(): void self::assertTrue($this->blueprint->isPending()); self::assertSame(["excessive column 'col1'"], $this->blueprint->getDescriptions()); - self::assertSame(['col1'], array_keys($this->blueprint->getDroppedColumns())); + self::assertSame(['col1'], \array_keys($this->blueprint->getDroppedColumns())); } /** @@ -148,8 +146,8 @@ public function shouldAlterColumnForGetType(): void ["different 'col' column property: type (DB: \"a\" != MIG: \"b\")"], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -173,8 +171,8 @@ public function shouldAlterColumnForIsNotNull(): void ["different 'col' column property: not null (DB: TRUE != MIG: FALSE)"], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -198,8 +196,8 @@ public function shouldAlterColumnForGetLength(): void ["different 'col' column property: length (DB: \"10\" != MIG: \"2\")"], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -223,8 +221,8 @@ public function shouldAlterColumnForGetLengthDecimal(): void ["different 'col' column property: length (DB: \"10, 2\" != MIG: \"9, 3\")"], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -286,8 +284,8 @@ public function shouldAlterColumnForIsUnique(): void ["different 'col' column property: unique (DB: FALSE != MIG: TRUE)"], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -363,8 +361,8 @@ public function shouldAlterColumnForIsUnsigned(): void ["different 'col' column property: unsigned (DB: FALSE != MIG: TRUE)"], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -388,8 +386,8 @@ public function shouldAlterColumnForGetDefault(): void ["different 'col' column property: default (DB: [\"a\"] != MIG: [\"b\"])"], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -413,8 +411,8 @@ public function shouldAlterColumnForGetDefaultNULL(): void ["different 'col' column property: default (DB: \"NULL\" != MIG: NULL)"], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -438,8 +436,8 @@ public function shouldAlterColumnForGetComment(): void ["different 'col' column property: comment (DB: \"abc\" != MIG: \"def\")"], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -463,8 +461,8 @@ public function shouldAlterColumnForGetAppendNonPK(): void ["different 'col' column property: append (DB: \"abc\" != MIG: \"def\")"], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -511,8 +509,8 @@ public function shouldAlterColumnForGetAppendWithPKAndNonGeneralSchema(): void ["different 'col' column property: append (DB: \"PRIMARY KEY\" != MIG: NULL)"], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -688,8 +686,8 @@ public function shouldAlterColumnForGetAppendWithNotPKAndEmptyOldAppend(): void ["different 'col' column property: append (DB: \"PRIMARY KEY\" != MIG: NULL)"], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -713,8 +711,8 @@ public function shouldAlterColumnForGetAppendWithNotAutoIncrementVariant1AndEmpt ["different 'col' column property: append (DB: \"AUTO_INCREMENT\" != MIG: NULL)"], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -738,8 +736,8 @@ public function shouldAlterColumnForGetAppendWithNotAutoIncrementVariant2AndEmpt ["different 'col' column property: append (DB: \"AUTOINCREMENT\" != MIG: NULL)"], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -763,8 +761,8 @@ public function shouldAlterColumnForGetAppendWithNoIdentityAndEmptyOldAppend(): ["different 'col' column property: append (DB: \"IDENTITY PRIMARY KEY\" != MIG: NULL)"], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -792,7 +790,7 @@ public function shouldAddForeignKeys(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['fk', 'fk2'], array_keys($this->blueprint->getAddedForeignKeys())); + self::assertSame(['fk', 'fk2'], \array_keys($this->blueprint->getAddedForeignKeys())); } /** @@ -811,7 +809,7 @@ public function shouldDropForeignKey(): void ["excessive foreign key 'fk'"], $this->blueprint->getDescriptions() ); - self::assertSame(['fk'], array_keys($this->blueprint->getDroppedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getDroppedForeignKeys())); } /** @@ -856,8 +854,8 @@ public function shouldReplaceForeignKeysWithDifferentColumns(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['fk', 'fk2'], array_keys($this->blueprint->getAddedForeignKeys())); - self::assertSame(['fk', 'fk2'], array_keys($this->blueprint->getDroppedForeignKeys())); + self::assertSame(['fk', 'fk2'], \array_keys($this->blueprint->getAddedForeignKeys())); + self::assertSame(['fk', 'fk2'], \array_keys($this->blueprint->getDroppedForeignKeys())); } /** @@ -881,8 +879,8 @@ public function shouldReplaceForeignKeyWithDifferentReferredColumns(): void ["different foreign key 'fk' referred columns (DB: [\"a\",\"b\"] != MIG: [\"c\",\"b\"])"], $this->blueprint->getDescriptions() ); - self::assertSame(['fk'], array_keys($this->blueprint->getAddedForeignKeys())); - self::assertSame(['fk'], array_keys($this->blueprint->getDroppedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getAddedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getDroppedForeignKeys())); } /** @@ -906,8 +904,8 @@ public function shouldReplaceForeignKeyWithDifferentReferredTable(): void ["different foreign key 'fk' referred table (DB: \"a\" != MIG: \"b\")"], $this->blueprint->getDescriptions() ); - self::assertSame(['fk'], array_keys($this->blueprint->getAddedForeignKeys())); - self::assertSame(['fk'], array_keys($this->blueprint->getDroppedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getAddedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getDroppedForeignKeys())); } /** @@ -931,8 +929,8 @@ public function shouldReplaceForeignKeyWithDifferentOnUpdateConstraint(): void ["different foreign key 'fk' ON UPDATE constraint (DB: \"CASCADE\" != MIG: \"RESTRICT\")"], $this->blueprint->getDescriptions() ); - self::assertSame(['fk'], array_keys($this->blueprint->getAddedForeignKeys())); - self::assertSame(['fk'], array_keys($this->blueprint->getDroppedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getAddedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getDroppedForeignKeys())); } /** @@ -956,8 +954,8 @@ public function shouldReplaceForeignKeyWithDifferentOnDeleteConstraint(): void ["different foreign key 'fk' ON DELETE constraint (DB: \"RESTRICT\" != MIG: \"CASCADE\")"], $this->blueprint->getDescriptions() ); - self::assertSame(['fk'], array_keys($this->blueprint->getAddedForeignKeys())); - self::assertSame(['fk'], array_keys($this->blueprint->getDroppedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getAddedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getDroppedForeignKeys())); } /** @@ -1196,7 +1194,7 @@ public function shouldAddIndex(): void ["missing index 'idx'"], $this->blueprint->getDescriptions() ); - self::assertSame(['idx'], array_keys($this->blueprint->getAddedIndexes())); + self::assertSame(['idx'], \array_keys($this->blueprint->getAddedIndexes())); } /** @@ -1238,7 +1236,7 @@ public function shouldDropIndex(): void ["excessive index 'idx'"], $this->blueprint->getDescriptions() ); - self::assertSame(['idx'], array_keys($this->blueprint->getDroppedIndexes())); + self::assertSame(['idx'], \array_keys($this->blueprint->getDroppedIndexes())); } /** @@ -1264,8 +1262,8 @@ public function shouldReplaceIndexWhenDifferentUnique(): void ["different index 'idx' definition (DB: unique FALSE != MIG: unique TRUE)"], $this->blueprint->getDescriptions() ); - self::assertSame(['idx'], array_keys($this->blueprint->getAddedIndexes())); - self::assertSame(['idx'], array_keys($this->blueprint->getDroppedIndexes())); + self::assertSame(['idx'], \array_keys($this->blueprint->getAddedIndexes())); + self::assertSame(['idx'], \array_keys($this->blueprint->getDroppedIndexes())); } /** @@ -1300,8 +1298,8 @@ public function shouldReplaceMoreThanOneIndex(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['idx', 'idx2'], array_keys($this->blueprint->getAddedIndexes())); - self::assertSame(['idx', 'idx2'], array_keys($this->blueprint->getDroppedIndexes())); + self::assertSame(['idx', 'idx2'], \array_keys($this->blueprint->getAddedIndexes())); + self::assertSame(['idx', 'idx2'], \array_keys($this->blueprint->getDroppedIndexes())); } /** @@ -1325,7 +1323,7 @@ public function shouldReplaceIndexWhenDifferentColumns(): void ["different index 'idx' columns (DB: [\"a\"]) != MIG: ([\"b\"]))"], $this->blueprint->getDescriptions() ); - self::assertSame(['idx'], array_keys($this->blueprint->getAddedIndexes())); - self::assertSame(['idx'], array_keys($this->blueprint->getDroppedIndexes())); + self::assertSame(['idx'], \array_keys($this->blueprint->getAddedIndexes())); + self::assertSame(['idx'], \array_keys($this->blueprint->getDroppedIndexes())); } } diff --git a/tests/unit/ComparatorSqliteShowTest.php b/tests/unit/ComparatorSqliteShowTest.php index 1a81bfa..2400e88 100644 --- a/tests/unit/ComparatorSqliteShowTest.php +++ b/tests/unit/ComparatorSqliteShowTest.php @@ -48,7 +48,7 @@ public function shouldDropColumn(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['col1'], array_keys($this->blueprint->getDroppedColumns())); + self::assertSame(['col1'], \array_keys($this->blueprint->getDroppedColumns())); } /** @@ -76,8 +76,8 @@ public function shouldAlterColumnForGetType(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -105,8 +105,8 @@ public function shouldAlterColumnForIsNotNull(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -134,8 +134,8 @@ public function shouldAlterColumnForGetLength(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -163,8 +163,8 @@ public function shouldAlterColumnForGetLengthDecimal(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -192,8 +192,8 @@ public function shouldAlterColumnForIsUnique(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -221,8 +221,8 @@ public function shouldAlterColumnForIsUnsigned(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -250,8 +250,8 @@ public function shouldAlterColumnForGetDefault(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -298,8 +298,8 @@ public function shouldAlterColumnForGetComment(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -327,8 +327,8 @@ public function shouldAlterColumnForGetAppendNonPK(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -358,8 +358,8 @@ public function shouldAlterColumnForGetAppendWithPKAndNonGeneralSchema(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -387,8 +387,8 @@ public function shouldAlterColumnForGetAppendWithNotPKAndEmptyOldAppend(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -416,8 +416,8 @@ public function shouldAlterColumnForGetAppendWithNotAutoIncrementVariant1AndEmpt ], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -445,8 +445,8 @@ public function shouldAlterColumnForGetAppendWithNotAutoIncrementVariant2AndEmpt ], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -474,8 +474,8 @@ public function shouldAlterColumnForGetAppendWithNoIdentityAndEmptyOldAppend(): ], $this->blueprint->getDescriptions() ); - self::assertSame(['col'], array_keys($this->blueprint->getAlteredColumns())); - self::assertSame(['col'], array_keys($this->blueprint->getUnalteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getAlteredColumns())); + self::assertSame(['col'], \array_keys($this->blueprint->getUnalteredColumns())); } /** @@ -506,7 +506,7 @@ public function shouldAddForeignKeys(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['fk', 'fk2'], array_keys($this->blueprint->getAddedForeignKeys())); + self::assertSame(['fk', 'fk2'], \array_keys($this->blueprint->getAddedForeignKeys())); } /** @@ -529,7 +529,7 @@ public function shouldDropForeignKey(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['fk'], array_keys($this->blueprint->getDroppedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getDroppedForeignKeys())); } /** @@ -577,8 +577,8 @@ public function shouldReplaceForeignKeysWithDifferentColumns(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['fk', 'fk2'], array_keys($this->blueprint->getAddedForeignKeys())); - self::assertSame(['fk', 'fk2'], array_keys($this->blueprint->getDroppedForeignKeys())); + self::assertSame(['fk', 'fk2'], \array_keys($this->blueprint->getAddedForeignKeys())); + self::assertSame(['fk', 'fk2'], \array_keys($this->blueprint->getDroppedForeignKeys())); } /** @@ -606,8 +606,8 @@ public function shouldReplaceForeignKeyWithDifferentReferredColumns(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['fk'], array_keys($this->blueprint->getAddedForeignKeys())); - self::assertSame(['fk'], array_keys($this->blueprint->getDroppedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getAddedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getDroppedForeignKeys())); } /** @@ -635,8 +635,8 @@ public function shouldReplaceForeignKeyWithDifferentReferredTable(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['fk'], array_keys($this->blueprint->getAddedForeignKeys())); - self::assertSame(['fk'], array_keys($this->blueprint->getDroppedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getAddedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getDroppedForeignKeys())); } /** @@ -664,8 +664,8 @@ public function shouldReplaceForeignKeyWithDifferentOnUpdateConstraint(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['fk'], array_keys($this->blueprint->getAddedForeignKeys())); - self::assertSame(['fk'], array_keys($this->blueprint->getDroppedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getAddedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getDroppedForeignKeys())); } /** @@ -693,8 +693,8 @@ public function shouldReplaceForeignKeyWithDifferentOnDeleteConstraint(): void ], $this->blueprint->getDescriptions() ); - self::assertSame(['fk'], array_keys($this->blueprint->getAddedForeignKeys())); - self::assertSame(['fk'], array_keys($this->blueprint->getDroppedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getAddedForeignKeys())); + self::assertSame(['fk'], \array_keys($this->blueprint->getDroppedForeignKeys())); } /** diff --git a/tests/unit/ExtractorTest.php b/tests/unit/ExtractorTest.php index 723227d..b6ba40d 100644 --- a/tests/unit/ExtractorTest.php +++ b/tests/unit/ExtractorTest.php @@ -75,8 +75,8 @@ public function shouldReturnChangesWhenSubjectIsNamespaced(): void { $this->extractor->extract(GoodMigration::class, []); $changes = $this->extractor->getChanges(); - self::assertSame(['table'], array_keys($changes)); - self::assertInstanceOf(StructureChangeInterface::class, array_values($changes)[0][0]); + self::assertSame(['table'], \array_keys($changes)); + self::assertInstanceOf(StructureChangeInterface::class, \array_values($changes)[0][0]); self::assertSame(Yii::getAlias('@bizley/migration/dummy/MigrationChanges.php'), Yii::$classMap['yii\db\Migration']); } @@ -89,8 +89,8 @@ public function shouldReturnChangesWhenSubjectIsNotNamespaced(): void { $this->extractor->extract('good_migration', ['tests/stubs']); $changes = $this->extractor->getChanges(); - self::assertSame(['table'], array_keys($changes)); - self::assertInstanceOf(StructureChangeInterface::class, array_values($changes)[0][0]); + self::assertSame(['table'], \array_keys($changes)); + self::assertInstanceOf(StructureChangeInterface::class, \array_values($changes)[0][0]); self::assertSame(Yii::getAlias('@bizley/migration/dummy/MigrationChanges.php'), Yii::$classMap['yii\db\Migration']); } diff --git a/tests/unit/GeneratorTest.php b/tests/unit/GeneratorTest.php index 3ea8454..a297df5 100644 --- a/tests/unit/GeneratorTest.php +++ b/tests/unit/GeneratorTest.php @@ -17,18 +17,16 @@ use yii\base\View; use yii\db\TableSchema; -use function is_string; - /** @group generator */ final class GeneratorTest extends TestCase { - /** @var TableMapperInterface|MockObject */ + /** @var TableMapperInterface&MockObject */ private $mapper; - /** @var MockObject|View */ + /** @var MockObject&View */ private $view; - /** @var StructureRendererInterface|MockObject */ + /** @var StructureRendererInterface&MockObject */ private $renderer; /** @var Generator */ @@ -144,8 +142,8 @@ public function shouldProperlyGenerateForTable(): void $this->view->expects(self::once())->method('renderFile')->with( self::callback( - static function (string $template) { - return is_string($template); + static function ($template) { + return \is_string($template); } ), self::callback( @@ -183,7 +181,7 @@ public function shouldProperlyGenerateForForeignKeys(): void $this->view->expects(self::once())->method('renderFile')->with( self::callback( - static function (string $template) { + static function ($template) { return is_string($template); } ), diff --git a/tests/unit/HistoryManagerTest.php b/tests/unit/HistoryManagerTest.php index e8eaaf5..b22ac7c 100644 --- a/tests/unit/HistoryManagerTest.php +++ b/tests/unit/HistoryManagerTest.php @@ -8,6 +8,7 @@ use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use yii\base\NotSupportedException; +use yii\console\controllers\BaseMigrateController; use yii\console\controllers\MigrateController; use yii\db\Command; use yii\db\Connection; @@ -16,21 +17,19 @@ use yii\db\Schema; use yii\db\TableSchema; -use function time; - /** @group historymanager */ final class HistoryManagerTest extends TestCase { - /** @var MockObject|Connection */ + /** @var MockObject&Connection */ private $db; /** @var HistoryManager */ private $manager; - /** @var MockObject|Schema */ + /** @var MockObject&Schema */ private $schema; - /** @var MockObject|Query */ + /** @var MockObject&Query */ private $query; protected function setUp(): void @@ -76,13 +75,13 @@ static function (array $structure): bool { } ) )->willReturn($command); - $time = time(); + $time = \time(); $command->expects(self::exactly(2))->method('insert')->withConsecutive( [ 'table', self::callback( static function (array $structure) use ($time): bool { - return $structure['version'] === MigrateController::BASE_MIGRATION + return $structure['version'] === BaseMigrateController::BASE_MIGRATION && $structure['apply_time'] >= $time - 1 && $structure['apply_time'] <= $time + 1; } @@ -113,7 +112,7 @@ public function shouldAddHistoryWithNamespace(): void { $this->schema->method('getTableSchema')->willReturn($this->createMock(TableSchema::class)); $command = $this->createMock(Command::class); - $time = time(); + $time = \time(); $command->expects(self::once())->method('insert')->with( 'table', self::callback( @@ -142,12 +141,12 @@ public function providerForHistory(): array { return [ 'only base' => [ - [['version' => MigrateController::BASE_MIGRATION, 'apply_time' => 1]], + [['version' => BaseMigrateController::BASE_MIGRATION, 'apply_time' => 1]], [] ], [ [ - ['version' => MigrateController::BASE_MIGRATION, 'apply_time' => 1], + ['version' => BaseMigrateController::BASE_MIGRATION, 'apply_time' => 1], ['version' => 'a', 'apply_time' => 1], ['version' => 'b', 'apply_time' => '2'], ['version' => 'c', 'apply_time' => 3], diff --git a/tests/unit/InspectorTest.php b/tests/unit/InspectorTest.php index 4f3e339..10945dd 100644 --- a/tests/unit/InspectorTest.php +++ b/tests/unit/InspectorTest.php @@ -20,16 +20,13 @@ /** @group inspector */ final class InspectorTest extends TestCase { - /** @var HistoryManagerInterface|MockObject */ + /** @var HistoryManagerInterface&MockObject */ private $historyManager; - /** @var ExtractorInterface|MockObject */ + /** @var ExtractorInterface&MockObject */ private $extractor; - /** @var StructureBuilderInterface|MockObject */ - private $builder; - - /** @var ComparatorInterface|MockObject */ + /** @var ComparatorInterface&MockObject */ private $comparator; /** @var Inspector */ @@ -39,12 +36,11 @@ protected function setUp(): void { $this->historyManager = $this->createMock(HistoryManagerInterface::class); $this->extractor = $this->createMock(ExtractorInterface::class); - $this->builder = $this->createMock(StructureBuilderInterface::class); $this->comparator = $this->createMock(ComparatorInterface::class); $this->inspector = new Inspector( $this->historyManager, $this->extractor, - $this->builder, + $this->createMock(StructureBuilderInterface::class), $this->comparator ); } diff --git a/tests/unit/SchemaTest.php b/tests/unit/SchemaTest.php index 01a1c56..62c3f4b 100644 --- a/tests/unit/SchemaTest.php +++ b/tests/unit/SchemaTest.php @@ -6,7 +6,6 @@ use bizley\migration\Schema; use PHPUnit\Framework\TestCase; -use stdClass; use Yii; use yii\base\InvalidConfigException; use yii\db\Connection; @@ -53,7 +52,7 @@ public function shouldReturnProperSchemaType(string $schemaClass, string $expect public function shouldCheckIfSchemaIsSqlite(): void { self::assertTrue(Schema::isSQLite(Yii::createObject(\yii\db\sqlite\Schema::class))); - self::assertFalse(Schema::isSQLite(new stdClass())); + self::assertFalse(Schema::isSQLite(new \stdClass())); } /** @test */ diff --git a/tests/unit/TableMapperTest.php b/tests/unit/TableMapperTest.php index 07a18eb..806d6b5 100644 --- a/tests/unit/TableMapperTest.php +++ b/tests/unit/TableMapperTest.php @@ -23,13 +23,13 @@ /** @group tablemapper */ final class TableMapperTest extends TestCase { - /** @var MockObject|Connection */ + /** @var MockObject&Connection */ private $db; /** @var TableMapper */ private $mapper; - /** @var MockObject|Schema */ + /** @var MockObject&Schema */ private $schema; protected function setUp(): void diff --git a/tests/unit/UpdaterTest.php b/tests/unit/UpdaterTest.php index 4b7b5d7..4ade13f 100644 --- a/tests/unit/UpdaterTest.php +++ b/tests/unit/UpdaterTest.php @@ -20,24 +20,22 @@ use yii\base\View; use yii\db\TableSchema; -use function is_string; - /** @group updater */ final class UpdaterTest extends TestCase { - /** @var TableMapperInterface|MockObject */ + /** @var TableMapperInterface&MockObject */ private $mapper; - /** @var MockObject|View */ + /** @var MockObject&View */ private $view; - /** @var BlueprintRendererInterface|MockObject */ + /** @var BlueprintRendererInterface&MockObject */ private $renderer; /** @var Updater */ private $updater; - /** @var InspectorInterface|MockObject */ + /** @var InspectorInterface&MockObject */ private $inspector; protected function setUp(): void @@ -84,8 +82,8 @@ public function shouldProperlyNormalizeNamespace(?string $namespace, ?string $ex { $this->view->expects(self::once())->method('renderFile')->with( self::callback( - static function (string $template) { - return is_string($template); + static function ($template) { + return \is_string($template); } ), self::callback( @@ -175,8 +173,8 @@ public function shouldProperlyGenerateFromBlueprint(): void $this->view->expects(self::once())->method('renderFile')->with( self::callback( - static function (string $template) { - return is_string($template); + static function ($template) { + return \is_string($template); } ), self::callback( diff --git a/tests/unit/controllers/FallbackFileHelperTest.php b/tests/unit/controllers/FallbackFileHelperTest.php index c3e2c72..70d4e72 100644 --- a/tests/unit/controllers/FallbackFileHelperTest.php +++ b/tests/unit/controllers/FallbackFileHelperTest.php @@ -6,25 +6,8 @@ use bizley\migration\controllers\FallbackFileHelper; use PHPUnit\Framework\TestCase; -use stdClass; use yii\base\InvalidArgumentException; -use function chmod; -use function clearstatcache; -use function decoct; -use function explode; -use function file_put_contents; -use function filegroup; -use function fileowner; -use function fileperms; -use function is_array; -use function mkdir; -use function posix_getgid; -use function posix_getgrgid; -use function posix_getpwuid; -use function posix_getuid; -use function substr; - /** @group controller */ final class FallbackFileHelperTest extends TestCase { @@ -37,33 +20,33 @@ protected function createFileStructure(array $items, $basePath = ''): void } foreach ($items as $name => $content) { $itemName = $basePath . DIRECTORY_SEPARATOR . $name; - if (is_array($content)) { - if (@mkdir($itemName, 0777, true) === false) { + if (\is_array($content)) { + if (@\mkdir($itemName, 0777, true) === false) { self::markTestSkipped("Permission denied to create folder $itemName"); } $this->createFileStructure($content, $itemName); } else { - file_put_contents($itemName, $content); + \file_put_contents($itemName, $content); } } } protected function removeDir($dirName): void { - if (!empty($dirName) && is_dir($dirName) && $handle = opendir($dirName)) { - while (false !== ($entry = readdir($handle))) { + if (!empty($dirName) && \is_dir($dirName) && $handle = \opendir($dirName)) { + while (false !== ($entry = \readdir($handle))) { if ($entry !== '.' && $entry !== '..') { $item = $dirName . DIRECTORY_SEPARATOR . $entry; - if (is_dir($item) === true && !is_link($item)) { + if (\is_dir($item) === true && !\is_link($item)) { $this->removeDir($item); } else { - unlink($item); + \unlink($item); } } } - closedir($handle); - if (substr($dirName, -7) !== 'runtime') { - rmdir($dirName); + \closedir($handle); + if (\substr($dirName, -7) !== 'runtime') { + \rmdir($dirName); } } } @@ -91,10 +74,10 @@ public function shouldChangeOwnership(): void $fileName = 'file_1.txt'; $testFile = $this->basePath . DIRECTORY_SEPARATOR . $dirName . DIRECTORY_SEPARATOR . $fileName; - $currentUserId = posix_getuid(); - $currentUserName = posix_getpwuid($currentUserId)['name']; - $currentGroupId = posix_getgid(); - $currentGroupName = posix_getgrgid($currentGroupId)['name']; + $currentUserId = \posix_getuid(); + $currentUserName = \posix_getpwuid($currentUserId)['name']; + $currentGroupId = \posix_getgid(); + $currentGroupName = \posix_getgrgid($currentGroupId)['name']; $this->createFileStructure( [ @@ -107,13 +90,13 @@ public function shouldChangeOwnership(): void // Ensure the test file is created as the current user/group and has a specific file mode self::assertFileExists($testFile); $fileMode = 0770; - chmod($testFile, $fileMode); - clearstatcache(true, $testFile); - self::assertEquals($currentUserId, fileowner($testFile), 'Expected created test file owner to be current user.'); - self::assertEquals($currentGroupId, filegroup($testFile), 'Expected created test file group to be current group.'); + \chmod($testFile, $fileMode); + \clearstatcache(true, $testFile); + self::assertEquals($currentUserId, \fileowner($testFile), 'Expected created test file owner to be current user.'); + self::assertEquals($currentGroupId, \filegroup($testFile), 'Expected created test file group to be current group.'); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be changed.' ); @@ -121,16 +104,16 @@ public function shouldChangeOwnership(): void // Test file mode $fileMode = 0777; FallbackFileHelper::changeOwnership($testFile, null, $fileMode); - clearstatcache(true, $testFile); - self::assertEquals($currentUserId, fileowner($testFile), 'Expected file owner to be unchanged.'); - self::assertEquals($currentGroupId, filegroup($testFile), 'Expected file group to be unchanged.'); + \clearstatcache(true, $testFile); + self::assertEquals($currentUserId, \fileowner($testFile), 'Expected file owner to be unchanged.'); + self::assertEquals($currentGroupId, \filegroup($testFile), 'Expected file group to be unchanged.'); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be changed.' ); - chmod($this->basePath, 0777); + \chmod($this->basePath, 0777); if ($currentUserId !== 0) { self::markTestInComplete( @@ -143,268 +126,268 @@ public function shouldChangeOwnership(): void // Test user ownership as integer $ownership = 10001; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); - self::assertEquals($ownership, fileowner($testFile), 'Expected file owner to be changed.'); - self::assertEquals($currentGroupId, filegroup($testFile), 'Expected file group to be unchanged.'); + \clearstatcache(true, $testFile); + self::assertEquals($ownership, \fileowner($testFile), 'Expected file owner to be changed.'); + self::assertEquals($currentGroupId, \filegroup($testFile), 'Expected file group to be unchanged.'); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test user ownership as numeric string (should be treated as integer) $ownership = '10002'; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); - self::assertEquals((int)$ownership, fileowner($testFile), 'Expected created test file owner to be changed.'); - self::assertEquals($currentGroupId, filegroup($testFile), 'Expected file group to be unchanged.'); + \clearstatcache(true, $testFile); + self::assertEquals((int)$ownership, \fileowner($testFile), 'Expected created test file owner to be changed.'); + self::assertEquals($currentGroupId, \filegroup($testFile), 'Expected file group to be unchanged.'); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test user ownership as string $ownership = $currentUserName; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); + \clearstatcache(true, $testFile); self::assertEquals( $ownership, - posix_getpwuid(fileowner($testFile))['name'], + \posix_getpwuid(\fileowner($testFile))['name'], 'Expected created test file owner to be changed.' ); - self::assertEquals($currentGroupId, filegroup($testFile), 'Expected file group to be unchanged.'); + self::assertEquals($currentGroupId, \filegroup($testFile), 'Expected file group to be unchanged.'); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test user ownership as numeric string with trailing colon (should be treated as integer) $ownership = '10003:'; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); - self::assertEquals((int)$ownership, fileowner($testFile), 'Expected created test file owner to be changed.'); - self::assertEquals($currentGroupId, filegroup($testFile), 'Expected file group to be unchanged.'); + \clearstatcache(true, $testFile); + self::assertEquals((int)$ownership, \fileowner($testFile), 'Expected created test file owner to be changed.'); + self::assertEquals($currentGroupId, \filegroup($testFile), 'Expected file group to be unchanged.'); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test user ownership as string with trailing colon $ownership = $currentUserName . ':'; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); + \clearstatcache(true, $testFile); self::assertEquals( - substr($ownership, 0, -1), - posix_getpwuid(fileowner($testFile))['name'], + \substr($ownership, 0, -1), + \posix_getpwuid(\fileowner($testFile))['name'], 'Expected created test file owner to be changed.' ); - self::assertEquals($currentGroupId, filegroup($testFile), 'Expected file group to be unchanged.'); + self::assertEquals($currentGroupId, \filegroup($testFile), 'Expected file group to be unchanged.'); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test user ownership as indexed array (integer value) $ownership = [10004]; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); - self::assertEquals($ownership[0], fileowner($testFile), 'Expected created test file owner to be changed.'); - self::assertEquals($currentGroupId, filegroup($testFile), 'Expected file group to be unchanged.'); + \clearstatcache(true, $testFile); + self::assertEquals($ownership[0], \fileowner($testFile), 'Expected created test file owner to be changed.'); + self::assertEquals($currentGroupId, \filegroup($testFile), 'Expected file group to be unchanged.'); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test user ownership as indexed array (numeric string value) $ownership = ['10005']; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); - self::assertEquals((int)$ownership[0], fileowner($testFile), 'Expected created test file owner to be changed.'); - self::assertEquals($currentGroupId, filegroup($testFile), 'Expected file group to be unchanged.'); + \clearstatcache(true, $testFile); + self::assertEquals((int)$ownership[0], \fileowner($testFile), 'Expected created test file owner to be changed.'); + self::assertEquals($currentGroupId, \filegroup($testFile), 'Expected file group to be unchanged.'); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test user ownership as associative array (string value) $ownership = ['user' => $currentUserName]; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); + \clearstatcache(true, $testFile); self::assertEquals( $ownership['user'], - posix_getpwuid(fileowner($testFile))['name'], + \posix_getpwuid(\fileowner($testFile))['name'], 'Expected created test file owner to be changed.' ); - self::assertEquals($currentGroupId, filegroup($testFile), 'Expected file group to be unchanged.'); + self::assertEquals($currentGroupId, \filegroup($testFile), 'Expected file group to be unchanged.'); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test group ownership as numeric string $ownership = ':10006'; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); - self::assertEquals($currentUserId, fileowner($testFile), 'Expected file owner to be unchanged.'); + \clearstatcache(true, $testFile); + self::assertEquals($currentUserId, \fileowner($testFile), 'Expected file owner to be unchanged.'); self::assertEquals( - (int)substr($ownership, 1), - filegroup($testFile), + (int)\substr($ownership, 1), + \filegroup($testFile), 'Expected created test file group to be changed.' ); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test group ownership as string $ownership = ':' . $currentGroupName; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); - self::assertEquals($currentUserId, fileowner($testFile), 'Expected file owner to be unchanged.'); + \clearstatcache(true, $testFile); + self::assertEquals($currentUserId, \fileowner($testFile), 'Expected file owner to be unchanged.'); self::assertEquals( - substr($ownership, 1), - posix_getgrgid(filegroup($testFile))['name'], + \substr($ownership, 1), + \posix_getgrgid(\filegroup($testFile))['name'], 'Expected created test file group to be changed.' ); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test group ownership as associative array (integer value) $ownership = ['group' => 10007]; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); - self::assertEquals($currentUserId, fileowner($testFile), 'Expected file owner to be unchanged.'); - self::assertEquals($ownership['group'], filegroup($testFile), 'Expected created test file group to be changed.'); + \clearstatcache(true, $testFile); + self::assertEquals($currentUserId, \fileowner($testFile), 'Expected file owner to be unchanged.'); + self::assertEquals($ownership['group'], \filegroup($testFile), 'Expected created test file group to be changed.'); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test group ownership as associative array (numeric string value) $ownership = ['group' => '10008']; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); - self::assertEquals($currentUserId, fileowner($testFile), 'Expected file owner to be unchanged.'); + \clearstatcache(true, $testFile); + self::assertEquals($currentUserId, \fileowner($testFile), 'Expected file owner to be unchanged.'); self::assertEquals( (int)$ownership['group'], - filegroup($testFile), + \filegroup($testFile), 'Expected created test file group to be changed.' ); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test group ownership as associative array (string value) $ownership = ['group' => $currentGroupName]; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); - self::assertEquals($currentUserId, fileowner($testFile), 'Expected file owner to be unchanged.'); + \clearstatcache(true, $testFile); + self::assertEquals($currentUserId, \fileowner($testFile), 'Expected file owner to be unchanged.'); self::assertEquals( $ownership['group'], - posix_getgrgid(filegroup($testFile))['name'], + \posix_getgrgid(\filegroup($testFile))['name'], 'Expected created test file group to be changed.' ); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test user and group ownership as numeric string $ownership = '10009:10010'; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); + \clearstatcache(true, $testFile); self::assertEquals( - (int)explode(':', $ownership)[0], - fileowner($testFile), + (int)\explode(':', $ownership)[0], + \fileowner($testFile), 'Expected file owner to be changed.' ); self::assertEquals( - (int)explode(':', $ownership)[1], - filegroup($testFile), + (int)\explode(':', $ownership)[1], + \filegroup($testFile), 'Expected created test file group to be changed.' ); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test user and group ownership as string $ownership = $currentUserName . ':' . $currentGroupName; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); + \clearstatcache(true, $testFile); self::assertEquals( - explode(':', $ownership)[0], - posix_getpwuid(fileowner($testFile))['name'], + \explode(':', $ownership)[0], + \posix_getpwuid(\fileowner($testFile))['name'], 'Expected file owner to be changed.' ); self::assertEquals( - explode(':', $ownership)[1], - posix_getgrgid(filegroup($testFile))['name'], + \explode(':', $ownership)[1], + \posix_getgrgid(\filegroup($testFile))['name'], 'Expected created test file group to be changed.' ); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test user and group ownership as indexed array (integer values) $ownership = [10011, 10012]; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); - self::assertEquals($ownership[0], fileowner($testFile), 'Expected file owner to be changed.'); - self::assertEquals($ownership[1], filegroup($testFile), 'Expected created test file group to be changed.'); + \clearstatcache(true, $testFile); + self::assertEquals($ownership[0], \fileowner($testFile), 'Expected file owner to be changed.'); + self::assertEquals($ownership[1], \filegroup($testFile), 'Expected created test file group to be changed.'); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test user and group ownership as indexed array (numeric string values) $ownership = ['10013', '10014']; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); - self::assertEquals((int)$ownership[0], fileowner($testFile), 'Expected file owner to be changed.'); - self::assertEquals((int)$ownership[1], filegroup($testFile), 'Expected created test file group to be changed.'); + \clearstatcache(true, $testFile); + self::assertEquals((int)$ownership[0], \fileowner($testFile), 'Expected file owner to be changed.'); + self::assertEquals((int)$ownership[1], \filegroup($testFile), 'Expected created test file group to be changed.'); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test user and group ownership as indexed array (string values) $ownership = [$currentUserName, $currentGroupName]; FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); + \clearstatcache(true, $testFile); self::assertEquals( $ownership[0], - posix_getpwuid(fileowner($testFile))['name'], + \posix_getpwuid(\fileowner($testFile))['name'], 'Expected file owner to be changed.' ); self::assertEquals( $ownership[1], - posix_getgrgid(filegroup($testFile))['name'], + \posix_getgrgid(\filegroup($testFile))['name'], 'Expected created test file group to be changed.' ); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); @@ -412,47 +395,47 @@ public function shouldChangeOwnership(): void $ownership = ['group' => 10015, 'user' => 10016]; // user/group reversed on purpose FallbackFileHelper::changeOwnership($testFile, $ownership, null); clearstatcache(true, $testFile); - self::assertEquals($ownership['user'], fileowner($testFile), 'Expected file owner to be changed.'); - self::assertEquals($ownership['group'], filegroup($testFile), 'Expected created test file group to be changed.'); + self::assertEquals($ownership['user'], \fileowner($testFile), 'Expected file owner to be changed.'); + self::assertEquals($ownership['group'], \filegroup($testFile), 'Expected created test file group to be changed.'); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test user and group ownership as associative array (numeric string values) $ownership = ['group' => '10017', 'user' => '10018']; // user/group reversed on purpose FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); - self::assertEquals((int)$ownership['user'], fileowner($testFile), 'Expected file owner to be changed.'); + \clearstatcache(true, $testFile); + self::assertEquals((int)$ownership['user'], \fileowner($testFile), 'Expected file owner to be changed.'); self::assertEquals( (int)$ownership['group'], - filegroup($testFile), + \filegroup($testFile), 'Expected created test file group to be changed.' ); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); // Test user and group ownership as associative array (string values) $ownership = ['group' => $currentGroupName, 'user' => $currentUserName]; // user/group reversed on purpose FallbackFileHelper::changeOwnership($testFile, $ownership, null); - clearstatcache(true, $testFile); + \clearstatcache(true, $testFile); self::assertEquals( $ownership['user'], - posix_getpwuid(fileowner($testFile))['name'], + \posix_getpwuid(\fileowner($testFile))['name'], 'Expected file owner to be changed.' ); self::assertEquals( $ownership['group'], - posix_getgrgid(filegroup($testFile))['name'], + \posix_getgrgid(\filegroup($testFile))['name'], 'Expected created test file group to be changed.' ); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected file mode to be unchanged.' ); @@ -460,24 +443,24 @@ public function shouldChangeOwnership(): void $ownership = '10019:10020'; $fileMode = 0774; FallbackFileHelper::changeOwnership($testFile, $ownership, $fileMode); - clearstatcache(true, $testFile); + \clearstatcache(true, $testFile); self::assertEquals( - explode(':', $ownership)[0], - fileowner($testFile), + \explode(':', $ownership)[0], + \fileowner($testFile), 'Expected created test file owner to be changed.' ); self::assertEquals( - explode(':', $ownership)[1], - filegroup($testFile), + \explode(':', $ownership)[1], + \filegroup($testFile), 'Expected file group to be unchanged.' ); self::assertEquals( - '0' . decoct($fileMode), - substr(decoct(fileperms($testFile)), -4), + '0' . \decoct($fileMode), + \substr(\decoct(\fileperms($testFile)), -4), 'Expected created test file mode to be changed.' ); - chmod($this->basePath, 0777); + \chmod($this->basePath, 0777); } /** @@ -510,9 +493,9 @@ public function shouldNotChangeOwnershipToNonExistingUser(): void public function providerForInvalidArguments(): array { return [ - [new stdClass()], - [['user' => new stdClass()]], - [['group' => new stdClass()]], + [new \stdClass()], + [['user' => new \stdClass()]], + [['group' => new \stdClass()]], ]; } diff --git a/tests/unit/controllers/MigrationControllerTest.php b/tests/unit/controllers/MigrationControllerTest.php index 9e46356..4a2e6fd 100644 --- a/tests/unit/controllers/MigrationControllerTest.php +++ b/tests/unit/controllers/MigrationControllerTest.php @@ -14,7 +14,6 @@ use bizley\tests\stubs\UpdaterStub; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use stdClass; use Yii; use yii\base\Action; use yii\base\Controller; @@ -33,16 +32,6 @@ use yii\db\TableSchema; use yii\helpers\FileHelper; -use function chmod; -use function fileperms; -use function glob; -use function mktime; -use function preg_match_all; -use function substr; -use function time; -use function ucfirst; -use function unlink; - /** * @group controller */ @@ -51,10 +40,10 @@ final class MigrationControllerTest extends TestCase /** @var MigrationControllerStub */ private $controller; - /** @var MockObject|Connection */ + /** @var MockObject&Connection */ private $db; - /** @var MockObject|View */ + /** @var MockObject&View */ private $view; protected function setUp(): void @@ -64,7 +53,7 @@ protected function setUp(): void public function __construct() { - $this->errorHandler = new stdClass(); + $this->errorHandler = new \stdClass(); } public function has(): bool @@ -708,11 +697,11 @@ public function shouldCreateManyMigrations(): void MigrationControllerStub::$stdout ); - preg_match_all('/m\d{6}_(\d{6})_create_table/m', MigrationControllerStub::$stdout, $matches); + \preg_match_all('/m\d{6}_(\d{6})_create_table/m', MigrationControllerStub::$stdout, $matches); $time = $matches[1][0]; self::assertEqualsWithDelta( - time(), - mktime((int)substr($time, 0, 2), (int)substr($time, 2, 2), (int)substr($time, -2)), + \time(), + \mktime((int)\substr($time, 0, 2), (int)\substr($time, 2, 2), (int)\substr($time, -2)), 2 ); self::assertTrue($matches[1][1] - $matches[1][0] >= 1); @@ -758,10 +747,10 @@ public function shouldCreateManyMigrationsWithLeeway(): void MigrationControllerStub::$stdout ); - preg_match_all('/m\d{6}_(\d{6})_create_table/m', MigrationControllerStub::$stdout, $matches); + \preg_match_all('/m\d{6}_(\d{6})_create_table/m', MigrationControllerStub::$stdout, $matches); self::assertEqualsWithDelta( - time() + 100, - mktime((int)substr($matches[1][0], 0, 2), (int)substr($matches[1][0], 2, 2), (int)substr($matches[1][0], -2)), + \time() + 100, + \mktime((int)\substr($matches[1][0], 0, 2), (int)\substr($matches[1][0], 2, 2), (int)\substr($matches[1][0], -2)), 5 ); self::assertTrue($matches[1][1] - $matches[1][0] >= 1); @@ -827,10 +816,10 @@ public function shouldCreateManyMigrationsWithPostponedForeignKeys(): void MigrationControllerStub::$stdout ); - preg_match_all('/m\d{6}_(\d{6})_create_/m', MigrationControllerStub::$stdout, $matches); - $t1 = mktime((int)substr($matches[1][2], 0, 2), (int)substr($matches[1][2], 2, 2), (int)substr($matches[1][2], -2)); - $t2 = mktime((int)substr($matches[1][1], 0, 2), (int)substr($matches[1][1], 2, 2), (int)substr($matches[1][1], -2)); - $t3 = mktime((int)substr($matches[1][0], 0, 2), (int)substr($matches[1][0], 2, 2), (int)substr($matches[1][0], -2)); + \preg_match_all('/m\d{6}_(\d{6})_create_/m', MigrationControllerStub::$stdout, $matches); + $t1 = \mktime((int)\substr($matches[1][2], 0, 2), (int)\substr($matches[1][2], 2, 2), (int)\substr($matches[1][2], -2)); + $t2 = \mktime((int)\substr($matches[1][1], 0, 2), (int)\substr($matches[1][1], 2, 2), (int)\substr($matches[1][1], -2)); + $t3 = \mktime((int)\substr($matches[1][0], 0, 2), (int)\substr($matches[1][0], 2, 2), (int)\substr($matches[1][0], -2)); self::assertTrue($t1 - $t2 >= 1); self::assertTrue($t2 - $t3 >= 1); } @@ -1525,7 +1514,7 @@ public function shouldStopUpdateWhenUpdateDataIsAvailableButThereIsException(): */ public function shouldCreateDirectoryForPath(): void { - chmod(__DIR__ . '/../../runtime', 0777); + \chmod(__DIR__ . '/../../runtime', 0777); FileHelper::removeDirectory(__DIR__ . '/../../runtime/test'); @@ -1545,7 +1534,7 @@ public function shouldCreateDirectoryForPath(): void */ public function shouldCreateDirectoryForPathByNamespace(): void { - chmod(__DIR__ . '/../../runtime', 0777); + \chmod(__DIR__ . '/../../runtime', 0777); FileHelper::removeDirectory(__DIR__ . '/../../runtime/test'); @@ -1565,11 +1554,11 @@ public function shouldCreateDirectoryForPathByNamespace(): void */ public function shouldStoreOneMigration(): void { - chmod(__DIR__ . '/../../runtime', 0777); + \chmod(__DIR__ . '/../../runtime', 0777); - $potentialFiles = glob(__DIR__ . '/../../runtime/m??????_??????_create_table_test.php'); + $potentialFiles = \glob(__DIR__ . '/../../runtime/m??????_??????_create_table_test.php'); foreach ($potentialFiles as $potentialFile) { - unlink($potentialFile); + \unlink($potentialFile); } $controller = new MigrationControllerStoringStub('id', $this->createMock(Module::class)); @@ -1599,7 +1588,7 @@ public function shouldStoreOneMigration(): void */ public function shouldNotStoreOneMigration(): void { - chmod(__DIR__ . '/../../runtime', 0644); + \chmod(__DIR__ . '/../../runtime', 0644); MigrationControllerStoringStub::$stdout = ''; $controller = new MigrationControllerStoringStub('id', $this->createMock(Module::class)); @@ -1628,10 +1617,10 @@ public function shouldNotStoreOneMigration(): void ); self::assertStringContainsString( '_create_table_test.php): failed to open stream: permission denied', - strtolower(MigrationControllerStoringStub::$stdout) // PHP 8 changed case in message + \strtolower(MigrationControllerStoringStub::$stdout) // PHP 8 changed case in message ); - chmod(__DIR__ . '/../../runtime', 0777); + \chmod(__DIR__ . '/../../runtime', 0777); } public function providerForFileMode(): array @@ -1651,11 +1640,11 @@ public function providerForFileMode(): array */ public function shouldChangeMigrationPermissions($mode): void { - chmod(__DIR__ . '/../../runtime', 0777); + \chmod(__DIR__ . '/../../runtime', 0777); $potentialFiles = glob(__DIR__ . '/../../runtime/m??????_??????_create_table_testFileMode.php'); foreach ($potentialFiles as $potentialFile) { - unlink($potentialFile); + \unlink($potentialFile); } $controller = new MigrationController( @@ -1686,10 +1675,10 @@ public function shouldChangeMigrationPermissions($mode): void self::assertSame(ExitCode::OK, $controller->actionCreate('testFileMode')); - $generatedFiles = glob(__DIR__ . '/../../runtime/m??????_??????_create_table_testFileMode.php'); + $generatedFiles = \glob(__DIR__ . '/../../runtime/m??????_??????_create_table_testFileMode.php'); self::assertNotEmpty($generatedFiles); foreach ($generatedFiles as $generatedFile) { - self::assertSame('0777', substr(sprintf('%o', fileperms($generatedFile)), -4)); + self::assertSame('0777', \substr(\sprintf('%o', \fileperms($generatedFile)), -4)); } } diff --git a/tests/unit/controllers/TimestampMigrationControllerTest.php b/tests/unit/controllers/TimestampMigrationControllerTest.php index dccc056..d30ebc7 100644 --- a/tests/unit/controllers/TimestampMigrationControllerTest.php +++ b/tests/unit/controllers/TimestampMigrationControllerTest.php @@ -9,7 +9,6 @@ use bizley\tests\stubs\UpdaterStub; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use stdClass; use Yii; use yii\base\Module; use yii\base\View; @@ -19,11 +18,6 @@ use yii\db\TableSchema; use yii\helpers\FileHelper; -use function file_put_contents; -use function gmdate; -use function sprintf; -use function time; - /** * @group controller */ @@ -32,13 +26,13 @@ final class TimestampMigrationControllerTest extends TestCase /** @var MigrationControllerStub */ private $controller; - /** @var MockObject|Connection */ + /** @var MockObject&Connection */ private $db; - /** @var MockObject|View */ + /** @var MockObject&View */ private $view; - /** @var MockObject|MysqlSchema */ + /** @var MockObject&MysqlSchema */ private $schema; protected function setUp(): void @@ -48,7 +42,7 @@ protected function setUp(): void public function __construct() { - $this->errorHandler = new stdClass(); + $this->errorHandler = new \stdClass(); } public function has(): bool @@ -93,13 +87,13 @@ public function shouldDetectCollisionOnCreateWithMigrationPath(): void { $this->controller->migrationPath = [__DIR__ . '/../../runtime/test']; - $now = time(); + $now = \time(); $count = 0; while ($count < 10) { - file_put_contents( - __DIR__ . '/../../runtime/test/' . sprintf( + \file_put_contents( + __DIR__ . '/../../runtime/test/' . \sprintf( 'm%s_create_table_tab', - gmdate('ymd_His', $now + $count++) + \gmdate('ymd_His', $now + $count++) ), '' ); @@ -122,13 +116,13 @@ public function shouldDetectCollisionOnUpdateWithMigrationPath(): void { $this->controller->migrationPath = [__DIR__ . '/../../runtime/test']; - $now = time(); + $now = \time(); $count = 0; while ($count < 10) { - file_put_contents( - __DIR__ . '/../../runtime/test/' . sprintf( + \file_put_contents( + __DIR__ . '/../../runtime/test/' . \sprintf( 'm%s_create_table_tab', - gmdate('ymd_His', $now + $count++) + \gmdate('ymd_His', $now + $count++) ), '' ); @@ -155,13 +149,13 @@ public function shouldDetectCollisionOnCreateWithMigrationNamespace(): void { $this->controller->migrationNamespace = ['bizley\\tests\\runtime\\test']; - $now = time(); + $now = \time(); $count = 0; while ($count < 10) { - file_put_contents( - __DIR__ . '/../../runtime/test/' . sprintf( + \file_put_contents( + __DIR__ . '/../../runtime/test/' . \sprintf( 'M%sCreateTableTab', - gmdate('ymdHis', $now + $count++) + \gmdate('ymdHis', $now + $count++) ), '' ); @@ -184,13 +178,13 @@ public function shouldDetectCollisionOnUpdateWithMigrationNamespace(): void { $this->controller->migrationNamespace = ['bizley\\tests\\runtime\\test']; - $now = time(); + $now = \time(); $count = 0; while ($count < 10) { - file_put_contents( - __DIR__ . '/../../runtime/test/' . sprintf( + \file_put_contents( + __DIR__ . '/../../runtime/test/' . \sprintf( 'M%sCreateTableTab', - gmdate('ymd_His', $now + $count++) + \gmdate('ymd_His', $now + $count++) ), '' ); diff --git a/tests/unit/renderers/BlueprintRendererTest.php b/tests/unit/renderers/BlueprintRendererTest.php index 45b2cb9..d1e0c52 100644 --- a/tests/unit/renderers/BlueprintRendererTest.php +++ b/tests/unit/renderers/BlueprintRendererTest.php @@ -26,19 +26,19 @@ final class BlueprintRendererTest extends TestCase /** @var BlueprintRenderer */ private $renderer; - /** @var ColumnRendererInterface|MockObject */ + /** @var ColumnRendererInterface&MockObject */ private $columnRenderer; - /** @var PrimaryKeyRendererInterface|MockObject */ + /** @var PrimaryKeyRendererInterface&MockObject */ private $primaryKeyRenderer; - /** @var IndexRendererInterface|MockObject */ + /** @var IndexRendererInterface&MockObject */ private $indexRenderer; - /** @var ForeignKeyRendererInterface|MockObject */ + /** @var ForeignKeyRendererInterface&MockObject */ private $foreignKeyRenderer; - /** @var BlueprintInterface|MockObject */ + /** @var BlueprintInterface&MockObject */ private $blueprint; protected function setUp(): void diff --git a/tests/unit/renderers/StructureRendererTest.php b/tests/unit/renderers/StructureRendererTest.php index 9d4eb84..1ceea48 100644 --- a/tests/unit/renderers/StructureRendererTest.php +++ b/tests/unit/renderers/StructureRendererTest.php @@ -24,13 +24,13 @@ final class StructureRendererTest extends TestCase { /** @var StructureRenderer */ private $structureRenderer; - /** @var ColumnRendererInterface|MockObject */ + /** @var ColumnRendererInterface&MockObject */ private $columnRenderer; - /** @var PrimaryKeyRendererInterface|MockObject */ + /** @var PrimaryKeyRendererInterface&MockObject */ private $primaryKeyRenderer; - /** @var IndexRendererInterface|MockObject */ + /** @var IndexRendererInterface&MockObject */ private $indexRenderer; - /** @var ForeignKeyRendererInterface|MockObject */ + /** @var ForeignKeyRendererInterface&MockObject */ private $foreignKeyRenderer; protected function setUp(): void diff --git a/tests/unit/table/StructureBuilderTest.php b/tests/unit/table/StructureBuilderTest.php index 646f969..73865aa 100644 --- a/tests/unit/table/StructureBuilderTest.php +++ b/tests/unit/table/StructureBuilderTest.php @@ -13,7 +13,6 @@ use bizley\migration\table\StructureChangeInterface; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; -use stdClass; use yii\base\InvalidArgumentException; /** @@ -25,7 +24,7 @@ final class StructureBuilderTest extends TestCase /** @var StructureBuilder */ private $builder; - /** @var StructureChangeInterface|MockObject */ + /** @var StructureChangeInterface&MockObject */ private $change; protected function setUp(): void @@ -38,7 +37,7 @@ protected function setUp(): void public function shouldThrowExceptionWhenNoStructureChange(): void { $this->expectException(InvalidArgumentException::class); - $this->builder->build([new stdClass()], null, null); + $this->builder->build([new \stdClass()], null, null); } /** @test */