diff --git a/src/Bridges/Dibi/Dibi3Adapter.php b/src/Bridges/Dibi/Dibi3Adapter.php index 684c296..05dd5c3 100644 --- a/src/Bridges/Dibi/Dibi3Adapter.php +++ b/src/Bridges/Dibi/Dibi3Adapter.php @@ -9,7 +9,7 @@ namespace Nextras\Migrations\Bridges\Dibi; -use DateTime; +use DateTimeInterface; use Dibi; use Nextras\Migrations\IDbal; @@ -26,7 +26,7 @@ public function __construct(Dibi\Connection $dibi) } - public function query($sql) + public function query(string $sql): array { $result = $this->conn->nativeQuery($sql); $result->setRowClass(null); @@ -34,37 +34,38 @@ public function query($sql) } - public function exec($sql) + public function exec(string $sql): int { - return $this->conn->nativeQuery($sql); + $this->conn->nativeQuery($sql); + return $this->conn->getAffectedRows(); } - public function escapeString($value) + public function escapeString(string $value): string { return $this->conn->getDriver()->escapeText($value); } - public function escapeInt($value) + public function escapeInt(int $value): string { - return (string) (int) $value; + return (string) $value; } - public function escapeBool($value) + public function escapeBool(bool $value): string { - return $this->conn->getDriver()->escapeBool($value); + return (string) $this->conn->getDriver()->escapeBool($value); } - public function escapeDateTime(DateTime $value) + public function escapeDateTime(DateTimeInterface $value): string { return $this->conn->getDriver()->escapeDateTime($value); } - public function escapeIdentifier($value) + public function escapeIdentifier(string $value): string { return $this->conn->getDriver()->escapeIdentifier($value); } diff --git a/src/Bridges/Dibi/DibiAdapter.php b/src/Bridges/Dibi/DibiAdapter.php index ea8f8aa..e8807e2 100644 --- a/src/Bridges/Dibi/DibiAdapter.php +++ b/src/Bridges/Dibi/DibiAdapter.php @@ -9,8 +9,9 @@ namespace Nextras\Migrations\Bridges\Dibi; -use DateTime; +use DateTimeInterface; use dibi; +use Dibi\Connection; use LogicException; use Nextras\Migrations\IDbal; @@ -21,7 +22,7 @@ class DibiAdapter implements IDbal private $innerAdapter; - public function __construct($conn) + public function __construct(Connection $conn) { if (version_compare(dibi::VERSION, '3.0.0', '>=')) { $this->innerAdapter = new Dibi3Adapter($conn); @@ -32,43 +33,43 @@ public function __construct($conn) } - public function query($sql) + public function query(string $sql): array { return $this->innerAdapter->query($sql); } - public function exec($sql) + public function exec(string $sql): int { return $this->innerAdapter->exec($sql); } - public function escapeString($value) + public function escapeString(string $value): string { return $this->innerAdapter->escapeString($value); } - public function escapeInt($value) + public function escapeInt(int $value): string { return $this->innerAdapter->escapeInt($value); } - public function escapeBool($value) + public function escapeBool(bool $value): string { return $this->innerAdapter->escapeBool($value); } - public function escapeDateTime(DateTime $value) + public function escapeDateTime(DateTimeInterface $value): string { return $this->innerAdapter->escapeDateTime($value); } - public function escapeIdentifier($value) + public function escapeIdentifier(string $value): string { return $this->innerAdapter->escapeIdentifier($value); } diff --git a/src/Bridges/DoctrineDbal/DoctrineAdapter.php b/src/Bridges/DoctrineDbal/DoctrineAdapter.php index 3896244..64d9da5 100644 --- a/src/Bridges/DoctrineDbal/DoctrineAdapter.php +++ b/src/Bridges/DoctrineDbal/DoctrineAdapter.php @@ -9,7 +9,7 @@ namespace Nextras\Migrations\Bridges\DoctrineDbal; -use DateTime; +use DateTimeInterface; use Doctrine; use Nextras\Migrations\IDbal; @@ -26,7 +26,7 @@ public function __construct(Doctrine\DBAL\Connection $conn) } - public function query($sql) + public function query(string $sql): array { return method_exists($this->conn, 'fetchAllAssociative') ? $this->conn->fetchAllAssociative($sql) @@ -34,7 +34,7 @@ public function query($sql) } - public function exec($sql) + public function exec(string $sql): int { return method_exists($this->conn, 'executeStatement') ? $this->conn->executeStatement($sql) @@ -42,31 +42,31 @@ public function exec($sql) } - public function escapeString($value) + public function escapeString(string $value): string { return $this->conn->quote($value, 'string'); } - public function escapeInt($value) + public function escapeInt(int $value): string { return $this->conn->quote($value, 'integer'); } - public function escapeBool($value) + public function escapeBool(bool $value): string { return $this->conn->quote($value, 'boolean'); } - public function escapeDateTime(DateTime $value) + public function escapeDateTime(DateTimeInterface $value): string { return $this->conn->quote($value, 'datetime'); } - public function escapeIdentifier($value) + public function escapeIdentifier(string $value): string { return $this->conn->quoteIdentifier($value); } diff --git a/src/Bridges/DoctrineOrm/StructureDiffGenerator.php b/src/Bridges/DoctrineOrm/StructureDiffGenerator.php index 80c7e5c..daf1f80 100644 --- a/src/Bridges/DoctrineOrm/StructureDiffGenerator.php +++ b/src/Bridges/DoctrineOrm/StructureDiffGenerator.php @@ -25,30 +25,20 @@ class StructureDiffGenerator implements IDiffGenerator private $ignoredQueriesFile; - /** - * @param EntityManagerInterface $entityManager - * @param string|NULL $ignoredQueriesFile - */ - public function __construct(EntityManagerInterface $entityManager, $ignoredQueriesFile = null) + public function __construct(EntityManagerInterface $entityManager, ?string $ignoredQueriesFile = null) { $this->entityManager = $entityManager; $this->ignoredQueriesFile = $ignoredQueriesFile; } - /** - * @return string - */ - public function getExtension() + public function getExtension(): string { return 'sql'; } - /** - * @return string - */ - public function generateContent() + public function generateContent(): string { $queries = array_diff($this->getUpdateQueries(), $this->getIgnoredQueries()); $content = $queries ? (implode(";\n", $queries) . ";\n") : ''; @@ -58,9 +48,9 @@ public function generateContent() /** - * @return string[] + * @return list */ - protected function getUpdateQueries() + protected function getUpdateQueries(): array { $cache = $this->entityManager->getConfiguration()->getMetadataCacheImpl(); if ($cache instanceof ClearableCache) { @@ -76,9 +66,9 @@ protected function getUpdateQueries() /** - * @return string[] + * @return list */ - protected function getIgnoredQueries() + protected function getIgnoredQueries(): array { if ($this->ignoredQueriesFile === null) { return []; diff --git a/src/Bridges/NetteDI/MigrationsExtension.php b/src/Bridges/NetteDI/MigrationsExtension.php index 931dad2..c837f07 100644 --- a/src/Bridges/NetteDI/MigrationsExtension.php +++ b/src/Bridges/NetteDI/MigrationsExtension.php @@ -13,6 +13,8 @@ use Dibi; use Nette; use Nette\DI\ContainerBuilder; +use Nette\DI\ServiceDefinition; +use Nette\DI\Statement; use Nette\Utils\Strings; use Nette\Utils\Validators; use Nextras; @@ -27,7 +29,7 @@ class MigrationsExtension extends Nette\DI\CompilerExtension /** attributes = ['for' => names of target migration extensions, 'extension' => name of handled file extension] */ const TAG_EXTENSION_HANDLER = 'nextras.migrations.extensionHandler'; - /** @var array */ + /** @var array */ public $defaults = [ 'dir' => null, 'phpParams' => [], @@ -40,7 +42,7 @@ class MigrationsExtension extends Nette\DI\CompilerExtension 'ignoredQueriesFile' => null, ]; - /** @var array */ + /** @var array */ protected $dbals = [ 'dibi' => Nextras\Migrations\Bridges\Dibi\DibiAdapter::class, 'dibi3' => Nextras\Migrations\Bridges\Dibi\Dibi3Adapter::class, @@ -50,20 +52,20 @@ class MigrationsExtension extends Nette\DI\CompilerExtension 'nextras' => Nextras\Migrations\Bridges\NextrasDbal\NextrasAdapter::class, ]; - /** @var array */ + /** @var array */ protected $drivers = [ 'mysql' => Nextras\Migrations\Drivers\MySqlDriver::class, 'pgsql' => Nextras\Migrations\Drivers\PgSqlDriver::class, ]; - /** @var array */ + /** @var array */ protected $printers = [ 'console' => Nextras\Migrations\Printers\Console::class, 'psrLog' => Nextras\Migrations\Bridges\PsrLog\PsrLogPrinter::class, ]; - public function loadConfiguration() + public function loadConfiguration(): void { $config = $this->validateConfig($this->defaults); @@ -109,7 +111,7 @@ public function loadConfiguration() } - public function beforeCompile() + public function beforeCompile(): void { $builder = $this->getContainerBuilder(); $config = $this->validateConfig($this->defaults); @@ -160,6 +162,10 @@ public function beforeCompile() } + /** + * @param null|string|Statement $dbal + * @return string|ServiceDefinition + */ private function getDbalDefinition($dbal) { $factory = $this->getDbalFactory($dbal); @@ -179,9 +185,13 @@ private function getDbalDefinition($dbal) } + /** + * @param null|string|Statement $dbal + * @return string|Statement|null + */ private function getDbalFactory($dbal) { - if ($dbal instanceof Nette\DI\Statement) { + if ($dbal instanceof Statement) { return $this->filterArguments([$dbal])[0]; } elseif (is_string($dbal) && isset($this->dbals[$dbal])) { @@ -196,6 +206,11 @@ private function getDbalFactory($dbal) } + /** + * @param null|string|Statement $driver + * @param string|ServiceDefinition $dbal + * @return string|ServiceDefinition + */ private function getDriverDefinition($driver, $dbal) { $factory = $this->getDriverFactory($driver, $dbal); @@ -215,13 +230,18 @@ private function getDriverDefinition($driver, $dbal) } + /** + * @param null|string|Statement $driver + * @param string|ServiceDefinition $dbal + * @return string|Statement|null + */ private function getDriverFactory($driver, $dbal) { - if ($driver instanceof Nette\DI\Statement) { + if ($driver instanceof Statement) { return $this->filterArguments([$driver])[0]; } elseif (is_string($driver) && isset($this->drivers[$driver])) { - return new Nette\DI\Statement($this->drivers[$driver], [$dbal]); + return new Statement($this->drivers[$driver], [$dbal]); } else { return null; @@ -229,6 +249,10 @@ private function getDriverFactory($driver, $dbal) } + /** + * @param null|string|Statement $printer + * @return string|ServiceDefinition + */ private function getPrinterDefinition($printer) { $factory = $this->getPrinterFactory($printer); @@ -248,9 +272,13 @@ private function getPrinterDefinition($printer) } + /** + * @param null|string|Statement $printer + * @return string|Statement|null + */ private function getPrinterFactory($printer) { - if ($printer instanceof Nette\DI\Statement) { + if ($printer instanceof Statement) { return $this->filterArguments([$printer])[0]; } elseif (is_string($printer) && isset($this->printers[$printer])) { @@ -265,15 +293,19 @@ private function getPrinterFactory($printer) } - private function createDefaultGroupConfiguration($dir, $withDummyData) + /** + * @param string|Nette\PhpGenerator\PhpLiteral $dir + * @return array, generator?: ServiceDefinition|null}> + */ + private function createDefaultGroupConfiguration($dir, bool $withDummyData): array { if ($dir instanceof Nette\PhpGenerator\PhpLiteral) { - $append = function ($path) use ($dir) { + $append = function (string $path) use ($dir): Nette\PhpGenerator\PhpLiteral { return ContainerBuilder::literal('? . ?', [$dir, $path]); }; } else { - $append = function ($path) use ($dir) { + $append = function (string $path) use ($dir): string { return $dir . $path; }; } @@ -305,7 +337,11 @@ private function createDefaultGroupConfiguration($dir, $withDummyData) } - private function createGroupDefinitions(array $groups) + /** + * @param array, generator?: ServiceDefinition}> $groups + * @return list + */ + private function createGroupDefinitions(array $groups): array { $builder = $this->getContainerBuilder(); $groupDefinitions = []; @@ -334,7 +370,12 @@ private function createGroupDefinitions(array $groups) } - private function createExtensionHandlerDefinitions($driver, $phpParams) + /** + * @param string|ServiceDefinition $driver + * @param array $phpParams + * @return list + */ + private function createExtensionHandlerDefinitions($driver, array $phpParams): array { $builder = $this->getContainerBuilder(); @@ -354,7 +395,7 @@ private function createExtensionHandlerDefinitions($driver, $phpParams) } - private function createConfigurationDefinition() + private function createConfigurationDefinition(): ServiceDefinition { return $this->getContainerBuilder() ->addDefinition($this->prefix('configuration')) @@ -363,7 +404,7 @@ private function createConfigurationDefinition() } - private function createDoctrineStructureDiffGeneratorDefinition($ignoredQueriesFile) + private function createDoctrineStructureDiffGeneratorDefinition(?string $ignoredQueriesFile): ServiceDefinition { $builder = $this->getContainerBuilder(); @@ -375,7 +416,12 @@ private function createDoctrineStructureDiffGeneratorDefinition($ignoredQueriesF } - private function createSymfonyCommandDefinitions($driver, $configuration, $printer) + /** + * @param string|ServiceDefinition $driver + * @param string|ServiceDefinition $configuration + * @param string|ServiceDefinition $printer + */ + private function createSymfonyCommandDefinitions($driver, $configuration, $printer): void { $builder = $this->getContainerBuilder(); $builder->addExcludedClasses([Nextras\Migrations\Bridges\SymfonyConsole\BaseCommand::class]); @@ -397,7 +443,7 @@ private function createSymfonyCommandDefinitions($driver, $configuration, $print } - private function filterArguments(array $arguments) + private function filterArguments(array $arguments): array { if (method_exists(Nette\DI\Helpers::class, 'filterArguments')) { return Nette\DI\Helpers::filterArguments($arguments); diff --git a/src/Bridges/NetteDatabase/NetteAdapter.php b/src/Bridges/NetteDatabase/NetteAdapter.php index 0d0073e..5327528 100644 --- a/src/Bridges/NetteDatabase/NetteAdapter.php +++ b/src/Bridges/NetteDatabase/NetteAdapter.php @@ -9,7 +9,7 @@ namespace Nextras\Migrations\Bridges\NetteDatabase; -use DateTime; +use DateTimeInterface; use Nette; use Nextras\Migrations\IDbal; use PDO; @@ -27,7 +27,7 @@ public function __construct(Nette\Database\Connection $ndb) } - public function query($sql) + public function query(string $sql): array { return array_map( function ($row) { return (array) $row; }, @@ -36,37 +36,37 @@ function ($row) { return (array) $row; }, } - public function exec($sql) + public function exec(string $sql): int { return $this->conn->query($sql)->getRowCount(); } - public function escapeString($value) + public function escapeString(string $value): string { return $this->conn->quote($value, PDO::PARAM_STR); } - public function escapeInt($value) + public function escapeInt(int $value): string { return $this->conn->quote((string) $value, PDO::PARAM_INT); } - public function escapeBool($value) + public function escapeBool(bool $value): string { return $this->escapeString((string) (int) $value); } - public function escapeDateTime(DateTime $value) + public function escapeDateTime(DateTimeInterface $value): string { return $this->conn->getSupplementalDriver()->formatDateTime($value); } - public function escapeIdentifier($value) + public function escapeIdentifier(string $value): string { return $this->conn->getSupplementalDriver()->delimite($value); } diff --git a/src/Bridges/NextrasDbal/NextrasAdapter.php b/src/Bridges/NextrasDbal/NextrasAdapter.php index ebb5912..1cacb0e 100644 --- a/src/Bridges/NextrasDbal/NextrasAdapter.php +++ b/src/Bridges/NextrasDbal/NextrasAdapter.php @@ -9,7 +9,7 @@ namespace Nextras\Migrations\Bridges\NextrasDbal; -use DateTime; +use DateTimeInterface; use Nextras\Dbal\Connection; use Nextras\Dbal\Drivers\IDriver; use Nextras\Dbal\Result\Row; @@ -42,7 +42,7 @@ public function __construct(Connection $connection) } - public function query($sql) + public function query(string $sql): array { return array_map( function (Row $row) { return $row->toArray(); }, @@ -51,14 +51,14 @@ function (Row $row) { return $row->toArray(); }, } - public function exec($sql) + public function exec(string $sql): int { $this->conn->query('%raw', $sql); return $this->conn->getAffectedRows(); } - public function escapeString($value) + public function escapeString(string $value): string { if ($this->version >= 2) { return $this->conn->getDriver()->convertStringToSql($value); @@ -68,13 +68,13 @@ public function escapeString($value) } - public function escapeInt($value) + public function escapeInt(int $value): string { return (string) (int) $value; } - public function escapeBool($value) + public function escapeBool(bool $value): string { if ($this->version >= 5) { return $this->conn->getPlatform()->formatBool($value); @@ -86,7 +86,7 @@ public function escapeBool($value) } - public function escapeDateTime(DateTime $value) + public function escapeDateTime(DateTimeInterface $value): string { if ($this->version >= 5) { return $this->conn->getPlatform()->formatDateTime($value); @@ -98,7 +98,7 @@ public function escapeDateTime(DateTime $value) } - public function escapeIdentifier($value) + public function escapeIdentifier(string $value): string { if ($this->version >= 5) { return $this->conn->getPlatform()->formatIdentifier($value); diff --git a/src/Bridges/PsrLog/PsrLogPrinter.php b/src/Bridges/PsrLog/PsrLogPrinter.php index f601c67..fc1539d 100644 --- a/src/Bridges/PsrLog/PsrLogPrinter.php +++ b/src/Bridges/PsrLog/PsrLogPrinter.php @@ -27,13 +27,13 @@ public function __construct(LoggerInterface $logger) } - public function printIntro($mode) + public function printIntro(string $mode): void { $this->logger->info("Nextras Migrations: started in $mode mode"); } - public function printToExecute(array $toExecute) + public function printToExecute(array $toExecute): void { $count = count($toExecute); @@ -46,7 +46,7 @@ public function printToExecute(array $toExecute) } - public function printExecute(File $file, $count, $time) + public function printExecute(File $file, int $count, float $time): void { $this->logger->info("Nextras Migrations: {$file->group->name}/{$file->name} successfully executed", [ 'queryCount' => $count, @@ -55,19 +55,19 @@ public function printExecute(File $file, $count, $time) } - public function printDone() + public function printDone(): void { $this->logger->info('Nextras Migrations: done'); } - public function printError(Exception $e) + public function printError(Exception $e): void { throw $e; } - public function printSource($code) + public function printSource(string $code): void { $this->logger->debug("Nextras Migrations: init source:\n\n$code"); } diff --git a/src/Bridges/SymfonyBundle/DependencyInjection/Configuration.php b/src/Bridges/SymfonyBundle/DependencyInjection/Configuration.php index df19575..d422257 100644 --- a/src/Bridges/SymfonyBundle/DependencyInjection/Configuration.php +++ b/src/Bridges/SymfonyBundle/DependencyInjection/Configuration.php @@ -15,7 +15,7 @@ class Configuration implements ConfigurationInterface { - public function getConfigTreeBuilder() + public function getConfigTreeBuilder(): TreeBuilder { if (!method_exists(TreeBuilder::class, '__construct')) { // Symfony < 4.2.0 $treeBuilder = new TreeBuilder(); diff --git a/src/Bridges/SymfonyBundle/DependencyInjection/NextrasMigrationsExtension.php b/src/Bridges/SymfonyBundle/DependencyInjection/NextrasMigrationsExtension.php index d8192c0..1e29673 100644 --- a/src/Bridges/SymfonyBundle/DependencyInjection/NextrasMigrationsExtension.php +++ b/src/Bridges/SymfonyBundle/DependencyInjection/NextrasMigrationsExtension.php @@ -17,7 +17,7 @@ class NextrasMigrationsExtension extends Extension { - /** @var array */ + /** @var array */ protected $dbals = [ 'dibi' => Nextras\Migrations\Bridges\Dibi\DibiAdapter::class, 'dibi3' => Nextras\Migrations\Bridges\Dibi\Dibi3Adapter::class, @@ -27,20 +27,20 @@ class NextrasMigrationsExtension extends Extension 'nextras' => Nextras\Migrations\Bridges\NextrasDbal\NextrasAdapter::class, ]; - /** @var array */ + /** @var array */ protected $drivers = [ 'mysql' => Nextras\Migrations\Drivers\MySqlDriver::class, 'pgsql' => Nextras\Migrations\Drivers\PgSqlDriver::class, ]; - /** @var array */ + /** @var array */ protected $printers = [ 'console' => Nextras\Migrations\Printers\Console::class, 'psrLog' => Nextras\Migrations\Bridges\PsrLog\PsrLogPrinter::class, ]; - public function load(array $configs, ContainerBuilder $container) + public function load(array $configs, ContainerBuilder $container): void { $config = $this->processConfiguration(new Configuration(), $configs); diff --git a/src/Bridges/SymfonyConsole/BaseCommand.php b/src/Bridges/SymfonyConsole/BaseCommand.php index c7a25c6..13a3f16 100644 --- a/src/Bridges/SymfonyConsole/BaseCommand.php +++ b/src/Bridges/SymfonyConsole/BaseCommand.php @@ -29,26 +29,19 @@ abstract class BaseCommand extends Command protected $printer; - /** - * @param IDriver $driver - * @param IConfiguration $config - * @param IPrinter|NULL $printer - */ - public function __construct(IDriver $driver, IConfiguration $config, IPrinter $printer = NULL) + public function __construct(IDriver $driver, IConfiguration $config, ?IPrinter $printer = null) { $this->driver = $driver; $this->config = $config; - $this->printer = $printer ?: new Console(); + $this->printer = $printer ?? new Console(); parent::__construct(); } /** - * @param string $mode Runner::MODE_* - * @param IConfiguration $config - * @return int + * @param Runner::MODE_* $mode */ - protected function runMigrations($mode, $config) + protected function runMigrations(string $mode, IConfiguration $config): int { $runner = new Runner($this->driver, $this->printer); $runner->run($mode, $config); diff --git a/src/Bridges/SymfonyConsole/ContinueCommand.php b/src/Bridges/SymfonyConsole/ContinueCommand.php index b329e5c..88821b1 100644 --- a/src/Bridges/SymfonyConsole/ContinueCommand.php +++ b/src/Bridges/SymfonyConsole/ContinueCommand.php @@ -22,7 +22,8 @@ class ContinueCommand extends BaseCommand /** @var string */ protected static $defaultDescription = 'Updates database schema by running all new migrations'; - protected function configure() + + protected function configure(): void { $this->setName(self::$defaultName); $this->setDescription(self::$defaultDescription); @@ -30,7 +31,7 @@ protected function configure() } - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { return $this->runMigrations(Runner::MODE_CONTINUE, $this->config); } diff --git a/src/Bridges/SymfonyConsole/CreateCommand.php b/src/Bridges/SymfonyConsole/CreateCommand.php index de1294d..8dfe188 100644 --- a/src/Bridges/SymfonyConsole/CreateCommand.php +++ b/src/Bridges/SymfonyConsole/CreateCommand.php @@ -37,20 +37,13 @@ class CreateCommand extends BaseCommand protected $defaultContentSource = self::CONTENT_SOURCE_DIFF; - /** - * @param string $defaultContentSource - * @return void - */ - public function setDefaultContentSource($defaultContentSource) + public function setDefaultContentSource(string $defaultContentSource): void { $this->defaultContentSource = $defaultContentSource; } - /** - * @return void - */ - protected function configure() + protected function configure(): void { $this->setName(self::$defaultName); $this->setDescription(self::$defaultDescription); @@ -65,12 +58,7 @@ protected function configure() } - /** - * @param InputInterface $input - * @param OutputInterface $output - * @return int - */ - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $group = $this->getGroup($input->getArgument('type')); $path = $this->getPath($group, $input->getArgument('label')); @@ -83,12 +71,7 @@ protected function execute(InputInterface $input, OutputInterface $output) } - /** - * @param Group $group - * @param string $label - * @return string - */ - protected function getPath(Group $group, $label) + protected function getPath(Group $group, string $label): string { $dir = $group->directory; $extension = $group->generator ? $group->generator->getExtension() : 'sql'; @@ -108,11 +91,7 @@ protected function getPath(Group $group, $label) } - /** - * @param string $type - * @return Group - */ - protected function getGroup($type) + protected function getGroup(string $type): Group { $groupNamePattern = preg_quote($type, '~'); $groupNamePattern = str_replace('\\-', '\\w*+\\-', $groupNamePattern); @@ -143,12 +122,7 @@ protected function getGroup($type) } - /** - * @param string $label - * @param string $extension - * @return string - */ - protected function getFileName($label, $extension) + protected function getFileName(string $label, string $extension): string { if (preg_match('#^[a-z0-9.-]++$#i', $label)) { $slug = strtolower($label); @@ -171,12 +145,7 @@ class_exists(AsciiSlugger::class) } - /** - * @param string $dir - * @param string|NULL $found - * @return bool - */ - protected function hasNumericSubdirectory($dir, &$found) + protected function hasNumericSubdirectory(string $dir, ?string &$found): bool { $items = @scandir($dir); // directory may not exist @@ -193,10 +162,7 @@ protected function hasNumericSubdirectory($dir, &$found) } - /** - * @return string - */ - protected function getTypeArgDescription() + protected function getTypeArgDescription(): string { $options = []; $groups = $this->config->getGroups(); @@ -222,11 +188,7 @@ protected function getTypeArgDescription() } - /** - * @param InputInterface $input - * @return string - */ - protected function getFileContentSource(InputInterface $input) + protected function getFileContentSource(InputInterface $input): string { if ($input->getOption('diff')) { return self::CONTENT_SOURCE_DIFF; @@ -243,12 +205,7 @@ protected function getFileContentSource(InputInterface $input) } - /** - * @param Group $group - * @param string $source - * @return string - */ - protected function getFileContent(Group $group, $source) + protected function getFileContent(Group $group, string $source): string { if ($source === self::CONTENT_SOURCE_DIFF && $group->generator !== null) { return $group->generator->generateContent(); @@ -262,13 +219,7 @@ protected function getFileContent(Group $group, $source) } - /** - * @param string $path - * @param string $content - * @param OutputInterface $output - * @return void - */ - protected function createFile($path, $content, OutputInterface $output) + protected function createFile(string $path, string $content, OutputInterface $output): void { @mkdir(dirname($path), 0777, true); // directory may already exist diff --git a/src/Bridges/SymfonyConsole/ResetCommand.php b/src/Bridges/SymfonyConsole/ResetCommand.php index 05d9aaa..405f800 100644 --- a/src/Bridges/SymfonyConsole/ResetCommand.php +++ b/src/Bridges/SymfonyConsole/ResetCommand.php @@ -23,7 +23,7 @@ class ResetCommand extends BaseCommand protected static $defaultDescription = 'Drops current database and recreates it from scratch'; - protected function configure() + protected function configure(): void { $this->setName(self::$defaultName); $this->setDescription(self::$defaultDescription); @@ -31,7 +31,7 @@ protected function configure() } - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { return $this->runMigrations(Runner::MODE_RESET, $this->config); } diff --git a/src/Configurations/Configuration.php b/src/Configurations/Configuration.php index 217ac42..567d2f7 100644 --- a/src/Configurations/Configuration.php +++ b/src/Configurations/Configuration.php @@ -19,16 +19,16 @@ */ class Configuration implements IConfiguration { - /** @var Group[] */ + /** @var list */ private $groups; - /** @var IExtensionHandler[] (extension => IExtensionHandler) */ + /** @var array (extension => IExtensionHandler) */ private $extensionHandlers; /** - * @param Group[] $groups - * @param IExtensionHandler[] $extensionHandlers (extension => IExtensionHandler) + * @param list $groups + * @param array $extensionHandlers (extension => IExtensionHandler) */ public function __construct(array $groups, array $extensionHandlers) { @@ -37,19 +37,13 @@ public function __construct(array $groups, array $extensionHandlers) } - /** - * @return Group[] - */ - public function getGroups() + public function getGroups(): array { return $this->groups; } - /** - * @return IExtensionHandler[] (extension => IExtensionHandler) - */ - public function getExtensionHandlers() + public function getExtensionHandlers(): array { return $this->extensionHandlers; } diff --git a/src/Configurations/DefaultConfiguration.php b/src/Configurations/DefaultConfiguration.php index 12fbacd..fc71bbb 100644 --- a/src/Configurations/DefaultConfiguration.php +++ b/src/Configurations/DefaultConfiguration.php @@ -33,29 +33,26 @@ class DefaultConfiguration implements IConfiguration /** @var bool */ protected $withDummyData; - /** @var array */ + /** @var array */ protected $phpParams; - /** @var Group[] */ + /** @var list */ protected $groups; - /** @var IExtensionHandler[] */ + /** @var array */ protected $handlers; - /** @var IDiffGenerator|NULL */ + /** @var ?IDiffGenerator */ protected $structureDiffGenerator; - /** @var IDiffGenerator|NULL */ + /** @var ?IDiffGenerator */ protected $dummyDataDiffGenerator; /** - * @param string $dir - * @param IDriver $driver - * @param bool $withDummyData - * @param array $phpParams + * @param array $phpParams */ - public function __construct($dir, IDriver $driver, $withDummyData = true, array $phpParams = []) + public function __construct(string $dir, IDriver $driver, bool $withDummyData = true, array $phpParams = []) { $this->dir = $dir; $this->driver = $driver; @@ -64,10 +61,7 @@ public function __construct($dir, IDriver $driver, $withDummyData = true, array } - /** - * @return Group[] - */ - public function getGroups() + public function getGroups(): array { if ($this->groups === null) { $structures = new Group(); @@ -97,10 +91,7 @@ public function getGroups() } - /** - * @return array|IExtensionHandler[] (extension => IExtensionHandler) - */ - public function getExtensionHandlers() + public function getExtensionHandlers(): array { if ($this->handlers === null) { $this->handlers = [ @@ -113,21 +104,13 @@ public function getExtensionHandlers() } - /** - * @param IDiffGenerator|NULL $generator - * @return void - */ - public function setStructureDiffGenerator(IDiffGenerator $generator = null) + public function setStructureDiffGenerator(?IDiffGenerator $generator = null): void { $this->structureDiffGenerator = $generator; } - /** - * @param IDiffGenerator|NULL $generator - * @return void - */ - public function setDummyDataDiffGenerator(IDiffGenerator $generator = null) + public function setDummyDataDiffGenerator(?IDiffGenerator $generator = null): void { $this->dummyDataDiffGenerator = $generator; } diff --git a/src/Controllers/BaseController.php b/src/Controllers/BaseController.php index 9fc20bf..2295c10 100644 --- a/src/Controllers/BaseController.php +++ b/src/Controllers/BaseController.php @@ -13,6 +13,7 @@ use Nextras\Migrations\Entities\Group; use Nextras\Migrations\IDriver; use Nextras\Migrations\IExtensionHandler; +use Nextras\Migrations\IPrinter; abstract class BaseController @@ -23,7 +24,7 @@ abstract class BaseController /** @var string */ protected $mode; - /** @var array (name => Group) */ + /** @var array (name => Group) */ protected $groups; @@ -36,10 +37,13 @@ public function __construct(IDriver $driver) } - abstract public function run(); + abstract public function run(): void; - public function addGroup($name, $dir, array $dependencies = []) + /** + * @param list $dependencies + */ + public function addGroup(string $name, string $dir, array $dependencies = []): self { $group = new Group; $group->name = $name; @@ -52,32 +56,38 @@ public function addGroup($name, $dir, array $dependencies = []) } - public function addExtension($extension, IExtensionHandler $handler) + public function addExtension(string $extension, IExtensionHandler $handler): self { $this->runner->addExtensionHandler($extension, $handler); return $this; } - protected function registerGroups() + /** + * @return list + */ + protected function registerGroups(): array { $enabled = []; + foreach ($this->groups as $group) { $this->runner->addGroup($group); + if ($group->enabled) { $enabled[] = $group->name; } } + return $enabled; } - protected function setupPhp() + protected function setupPhp(): void { @set_time_limit(0); @ini_set('memory_limit', '1G'); } - abstract protected function createPrinter(); + abstract protected function createPrinter(): IPrinter; } diff --git a/src/Controllers/ConsoleController.php b/src/Controllers/ConsoleController.php index 3f4dde7..08a8caf 100644 --- a/src/Controllers/ConsoleController.php +++ b/src/Controllers/ConsoleController.php @@ -10,12 +10,13 @@ namespace Nextras\Migrations\Controllers; use Nextras\Migrations\Engine; +use Nextras\Migrations\IPrinter; use Nextras\Migrations\Printers; class ConsoleController extends BaseController { - public function run() + public function run(): void { $this->processArguments(); $this->printHeader(); @@ -24,7 +25,7 @@ public function run() } - private function printHeader() + private function printHeader(): void { if ($this->mode === Engine\Runner::MODE_INIT) { printf("-- Migrations init\n"); @@ -35,7 +36,7 @@ private function printHeader() } - private function processArguments() + private function processArguments(): void { $arguments = array_slice($_SERVER['argv'], 1); $help = count($arguments) === 0; @@ -88,7 +89,7 @@ private function processArguments() } - protected function createPrinter() + protected function createPrinter(): IPrinter { return new Printers\Console(); } diff --git a/src/Controllers/HttpController.php b/src/Controllers/HttpController.php index 8176a55..8857f1e 100644 --- a/src/Controllers/HttpController.php +++ b/src/Controllers/HttpController.php @@ -10,6 +10,7 @@ namespace Nextras\Migrations\Controllers; use Nextras\Migrations\Engine; +use Nextras\Migrations\IPrinter; use Nextras\Migrations\Printers; @@ -22,14 +23,14 @@ class HttpController extends BaseController private $error; - public function run() + public function run(): void { $this->processArguments(); $this->executeAction(); } - private function processArguments() + private function processArguments(): void { if (isset($_GET['action'])) { if ($_GET['action'] === 'run' || $_GET['action'] === 'css') { @@ -87,14 +88,14 @@ private function processArguments() } - private function executeAction() + private function executeAction(): void { $method = 'action' . ucfirst($this->action); $this->$method(); } - private function actionIndex() + private function actionIndex(): void { $combinations = $this->getGroupsCombinations(); $this->printHeader(); @@ -122,7 +123,7 @@ private function actionIndex() } - private function actionRun() + private function actionRun(): void { $groups = $this->registerGroups(); $groups = implode(' + ', $groups); @@ -135,14 +136,14 @@ private function actionRun() } - private function actionCss() + private function actionCss(): void { header('Content-Type: text/css', true); readfile(__DIR__ . '/templates/main.css'); } - private function actionError() + private function actionError(): void { $this->printHeader(); echo "

Migrations – error

\n"; @@ -150,7 +151,10 @@ private function actionError() } - private function getGroupsCombinations() + /** + * @return list> + */ + private function getGroupsCombinations(): array { $groups = []; $index = 1; @@ -183,13 +187,13 @@ private function getGroupsCombinations() } - private function printHeader() + private function printHeader(): void { readfile(__DIR__ . '/templates/header.phtml'); } - protected function createPrinter() + protected function createPrinter(): IPrinter { return new Printers\HtmlDump(); } diff --git a/src/Drivers/BaseDriver.php b/src/Drivers/BaseDriver.php index 508edbe..6c942d7 100644 --- a/src/Drivers/BaseDriver.php +++ b/src/Drivers/BaseDriver.php @@ -31,18 +31,14 @@ abstract class BaseDriver implements IDriver protected $tableNameQuoted; - /** - * @param IDbal $dbal - * @param string $tableName - */ - public function __construct(IDbal $dbal, $tableName = 'migrations') + public function __construct(IDbal $dbal, string $tableName = 'migrations') { $this->dbal = $dbal; $this->tableName = $tableName; } - public function setupConnection() + public function setupConnection(): void { $this->tableNameQuoted = $this->dbal->escapeIdentifier($this->tableName); } @@ -56,11 +52,8 @@ public function setupConnection() * @author Michael Moravec * @author Jan Skrasek * @license Apache License - * - * @param string $path - * @return int number of executed queries */ - public function loadFile($path) + public function loadFile(string $path): int { $content = @file_get_contents($path); if ($content === false) { @@ -103,7 +96,7 @@ public function loadFile($path) break; } elseif ($found) { // find matching quote or comment end - $endRe = isset($endReTable[$found]) ? $endReTable[$found] : '(' . (preg_match('~^-- |^#~', $found) ? "\n" : preg_quote($found) . "|\\\\.") . '|\z)s'; + $endRe = $endReTable[$found] ?? '(' . (preg_match('~^-- |^#~', $found) ? "\n" : preg_quote($found) . "|\\\\.") . '|\z)s'; while (preg_match($endRe, $content, $match, PREG_OFFSET_CAPTURE, $parseOffset)) { //! respect sql_mode NO_BACKSLASH_ESCAPES $s = $match[0][0]; if (strlen($s) === 0) { diff --git a/src/Drivers/MySqlDriver.php b/src/Drivers/MySqlDriver.php index 8130539..0534380 100644 --- a/src/Drivers/MySqlDriver.php +++ b/src/Drivers/MySqlDriver.php @@ -22,7 +22,10 @@ */ class MySqlDriver extends BaseDriver implements IDriver { - public function setupConnection() + private const LOCK_NAME = 'Nextras.Migrations'; + + + public function setupConnection(): void { parent::setupConnection(); $this->dbal->exec('SET NAMES "utf8mb4"'); @@ -32,7 +35,7 @@ public function setupConnection() } - public function emptyDatabase() + public function emptyDatabase(): void { $rows = $this->dbal->query('SELECT DATABASE() AS `name`'); $dbName = $this->dbal->escapeIdentifier($rows[0]['name']); @@ -46,25 +49,25 @@ public function emptyDatabase() } - public function beginTransaction() + public function beginTransaction(): void { $this->dbal->exec('START TRANSACTION'); } - public function commitTransaction() + public function commitTransaction(): void { $this->dbal->exec('COMMIT'); } - public function rollbackTransaction() + public function rollbackTransaction(): void { $this->dbal->exec('ROLLBACK'); } - public function lock() + public function lock(): void { $lock = $this->dbal->escapeString(self::LOCK_NAME); $result = (int) $this->dbal->query("SELECT GET_LOCK(SHA1(CONCAT($lock, '-', DATABASE())), 3) AS `result`")[0]['result']; @@ -74,7 +77,7 @@ public function lock() } - public function unlock() + public function unlock(): void { $lock = $this->dbal->escapeString(self::LOCK_NAME); $result = (int) $this->dbal->query("SELECT RELEASE_LOCK(SHA1(CONCAT($lock, '-', DATABASE()))) AS `result`")[0]['result']; @@ -84,19 +87,19 @@ public function unlock() } - public function createTable() + public function createTable(): void { $this->dbal->exec($this->getInitTableSource()); } - public function dropTable() + public function dropTable(): void { $this->dbal->exec("DROP TABLE {$this->tableNameQuoted}"); } - public function insertMigration(Migration $migration) + public function insertMigration(Migration $migration): void { $this->dbal->exec(" INSERT INTO {$this->tableNameQuoted} @@ -113,7 +116,7 @@ public function insertMigration(Migration $migration) } - public function markMigrationAsReady(Migration $migration) + public function markMigrationAsReady(Migration $migration): void { $this->dbal->exec(" UPDATE {$this->tableNameQuoted} @@ -123,7 +126,7 @@ public function markMigrationAsReady(Migration $migration) } - public function getAllMigrations() + public function getAllMigrations(): array { $migrations = []; $result = $this->dbal->query("SELECT * FROM {$this->tableNameQuoted} ORDER BY `executed`"); @@ -153,7 +156,7 @@ public function getAllMigrations() } - public function getInitTableSource() + public function getInitTableSource(): string { return preg_replace('#^\t{3}#m', '', trim(" CREATE TABLE IF NOT EXISTS {$this->tableNameQuoted} ( @@ -170,7 +173,7 @@ public function getInitTableSource() } - public function getInitMigrationsSource(array $files) + public function getInitMigrationsSource(array $files): string { $out = ''; foreach ($files as $file) { diff --git a/src/Drivers/PgSqlDriver.php b/src/Drivers/PgSqlDriver.php index 398ba79..acb4905 100644 --- a/src/Drivers/PgSqlDriver.php +++ b/src/Drivers/PgSqlDriver.php @@ -30,51 +30,46 @@ class PgSqlDriver extends BaseDriver implements IDriver protected $schemaQuoted; - /** - * @param IDbal $dbal - * @param string $tableName - * @param string $schema - */ - public function __construct(IDbal $dbal, $tableName = 'migrations', $schema = 'public') + public function __construct(IDbal $dbal, string $tableName = 'migrations', string $schema = 'public') { parent::__construct($dbal, $tableName); $this->schema = $schema; } - public function setupConnection() + public function setupConnection(): void { parent::setupConnection(); $this->schemaQuoted = $this->dbal->escapeIdentifier($this->schema); } - public function emptyDatabase() + public function emptyDatabase(): void { $this->dbal->exec("DROP SCHEMA IF EXISTS {$this->schemaQuoted} CASCADE"); $this->dbal->exec("CREATE SCHEMA {$this->schemaQuoted}"); } - public function beginTransaction() + public function beginTransaction(): void { $this->dbal->exec('START TRANSACTION'); } - public function commitTransaction() + public function commitTransaction(): void { $this->dbal->exec('COMMIT'); } - public function rollbackTransaction() + public function rollbackTransaction(): void { $this->dbal->exec('ROLLBACK'); } - public function lock() + public function lock(): void { try { $this->dbal->exec('SELECT pg_advisory_lock(-2099128779216184107)'); @@ -85,7 +80,7 @@ public function lock() } - public function unlock() + public function unlock(): void { try { $this->dbal->exec('SELECT pg_advisory_unlock(-2099128779216184107)'); @@ -96,19 +91,19 @@ public function unlock() } - public function createTable() + public function createTable(): void { $this->dbal->exec($this->getInitTableSource()); } - public function dropTable() + public function dropTable(): void { $this->dbal->exec("DROP TABLE {$this->schemaQuoted}.{$this->tableNameQuoted}"); } - public function insertMigration(Migration $migration) + public function insertMigration(Migration $migration): void { $rows = $this->dbal->query(" INSERT INTO {$this->schemaQuoted}.{$this->tableNameQuoted}" . ' @@ -126,7 +121,7 @@ public function insertMigration(Migration $migration) } - public function markMigrationAsReady(Migration $migration) + public function markMigrationAsReady(Migration $migration): void { $this->dbal->exec(" UPDATE {$this->schemaQuoted}.{$this->tableNameQuoted}" . ' @@ -136,7 +131,7 @@ public function markMigrationAsReady(Migration $migration) } - public function getAllMigrations() + public function getAllMigrations(): array { $migrations = []; $result = $this->dbal->query("SELECT * FROM {$this->schemaQuoted}.{$this->tableNameQuoted} ORDER BY \"executed\""); @@ -166,7 +161,7 @@ public function getAllMigrations() } - public function getInitTableSource() + public function getInitTableSource(): string { return preg_replace('#^\t{3}#m', '', trim(" CREATE TABLE IF NOT EXISTS {$this->schemaQuoted}.{$this->tableNameQuoted} (" . ' @@ -183,7 +178,7 @@ public function getInitTableSource() } - public function getInitMigrationsSource(array $files) + public function getInitMigrationsSource(array $files): string { $out = ''; foreach ($files as $file) { diff --git a/src/Engine/Finder.php b/src/Engine/Finder.php index 9a1b552..0687864 100644 --- a/src/Engine/Finder.php +++ b/src/Engine/Finder.php @@ -21,12 +21,12 @@ class Finder /** * Finds files. * - * @param Group[] $groups - * @param string[] $extensions - * @return File[] + * @param list $groups + * @param list $extensions + * @return list * @throws Exception */ - public function find(array $groups, array $extensions) + public function find(array $groups, array $extensions): array { $files = []; foreach ($groups as $group) { @@ -53,9 +53,8 @@ public function find(array $groups, array $extensions) * Returns logical name of migration file. * * @param string $path relative path to group directory - * @return string */ - protected function getName($path) + protected function getName(string $path): string { $parts = explode('/', $path); $dirName = implode('-', array_slice($parts, 0, -1)); @@ -68,12 +67,10 @@ protected function getName($path) /** * Returns file extension. * - * @param File $file - * @param string[] $extensions - * @return string + * @param list $extensions * @throws Exception */ - protected function getExtension(File $file, array $extensions) + protected function getExtension(File $file, array $extensions): string { $fileExt = null; @@ -102,11 +99,7 @@ protected function getExtension(File $file, array $extensions) } - /** - * @param File $file - * @return string - */ - protected function getChecksum(File $file) + protected function getChecksum(File $file): string { $content = @file_get_contents($file->path); if ($content === false) { @@ -118,11 +111,10 @@ protected function getChecksum(File $file) /** - * @param string $dir - * @return string[] + * @return list * @throws IOException */ - protected function getFilesRecursive($dir) + protected function getFilesRecursive(string $dir): array { $items = $this->getItems($dir); foreach ($items as $i => $item) { @@ -144,10 +136,9 @@ protected function getFilesRecursive($dir) /** - * @param string $dir - * @return array + * @return list */ - protected function getItems($dir) + protected function getItems(string $dir): array { return @scandir($dir) ?: []; // directory may not exist } diff --git a/src/Engine/OrderResolver.php b/src/Engine/OrderResolver.php index 1a13768..0f77c18 100644 --- a/src/Engine/OrderResolver.php +++ b/src/Engine/OrderResolver.php @@ -18,14 +18,13 @@ class OrderResolver { /** - * @param Migration[] $migrations - * @param Group[] $groups - * @param File[] $files - * @param string $mode - * @return File[] + * @param list $migrations + * @param list $groups + * @param list $files + * @return list * @throws LogicException */ - public function resolve(array $migrations, array $groups, array $files, $mode) + public function resolve(array $migrations, array $groups, array $files, string $mode): array { $groups = $this->getAssocGroups($groups); $this->validateGroups($groups); @@ -107,13 +106,13 @@ public function resolve(array $migrations, array $groups, array $files, $mode) /** - * @param File[] $files - * @param array $groups (name => Group) - * @return File[] sorted + * @param list $files + * @param array $groups (name => Group) + * @return list sorted */ - protected function sortFiles(array $files, array $groups) + protected function sortFiles(array $files, array $groups): array { - usort($files, function (File $a, File $b) use ($groups) { + usort($files, function (File $a, File $b) use ($groups): int { $cmp = strcmp($a->name, $b->name); if ($cmp === 0 && $a !== $b) { $cmpA = $this->isGroupDependentOn($groups, $a->group, $b->group); @@ -144,16 +143,14 @@ protected function sortFiles(array $files, array $groups) /** * Returns true if groupA depends on groupB. * - * @param array $groups (name => Group) - * @param Group $groupA - * @param Group $groupB - * @return bool + * @param array $groups (name => Group) */ - protected function isGroupDependentOn(array $groups, Group $groupA, Group $groupB) + protected function isGroupDependentOn(array $groups, Group $groupA, Group $groupB): bool { $visited = []; $queue = $groupB->dependencies; $queue[] = $groupB->name; + while ($node = array_shift($queue)) { if (isset($visited[$node])) { continue; @@ -168,74 +165,100 @@ protected function isGroupDependentOn(array $groups, Group $groupA, Group $group $queue[] = $dep; } } + return false; } - protected function getAssocMigrations(array $migrations) + /** + * @param list $migrations + * @return array> (group => (filename => Migration)) + */ + protected function getAssocMigrations(array $migrations): array { $assoc = []; + foreach ($migrations as $migration) { $assoc[$migration->group][$migration->filename] = $migration; } + return $assoc; } - protected function getAssocGroups(array $groups) + /** + * @param list $groups + * @return array (name => Group) + */ + protected function getAssocGroups(array $groups): array { $assoc = []; + foreach ($groups as $group) { $assoc[$group->name] = $group; } + return $assoc; } - protected function getAssocFiles(array $files) + /** + * @param list $files + * @return array> (group => (filename => File)) + */ + protected function getAssocFiles(array $files): array { $assoc = []; + foreach ($files as $file) { $assoc[$file->group->name][$file->name] = $file; } + return $assoc; } - protected function getFlatFiles(array $files) + /** + * @param array> $files + * @return list + */ + protected function getFlatFiles(array $files): array { $flat = []; + foreach ($files as $tmp) { foreach ($tmp as $file) { $flat[] = $file; } } + return $flat; } /** - * @param File[] $files - * @return File[] first file for each group + * @param list $files + * @return array (group => File) */ - protected function getFirstFiles(array $files) + protected function getFirstFiles(array $files): array { $firstFiles = []; + foreach ($files as $file) { if (!isset($firstFiles[$file->group->name])) { $firstFiles[$file->group->name] = $file; } } + return $firstFiles; } /** - * @param Group[] $groups - * @return void + * @param array $groups * @throws LogicException */ - private function validateGroups(array $groups) + private function validateGroups(array $groups): void { foreach ($groups as $group) { foreach ($group->dependencies as $dependency) { diff --git a/src/Engine/Runner.php b/src/Engine/Runner.php index 1101870..5e49e31 100644 --- a/src/Engine/Runner.php +++ b/src/Engine/Runner.php @@ -33,10 +33,10 @@ class Runner /** @var IPrinter */ private $printer; - /** @var array (extension => IExtensionHandler) */ + /** @var array (extension => IExtensionHandler) */ private $extensionsHandlers = []; - /** @var Group[] */ + /** @var list */ private $groups = []; /** @var IDriver */ @@ -58,19 +58,14 @@ public function __construct(IDriver $driver, IPrinter $printer) } - public function addGroup(Group $group) + public function addGroup(Group $group): self { $this->groups[] = $group; return $this; } - /** - * @param string $extension - * @param IExtensionHandler $handler - * @return self - */ - public function addExtensionHandler($extension, IExtensionHandler $handler) + public function addExtensionHandler(string $extension, IExtensionHandler $handler): self { if (isset($this->extensionsHandlers[$extension])) { throw new LogicException("Extension '$extension' has already been defined."); @@ -82,11 +77,9 @@ public function addExtensionHandler($extension, IExtensionHandler $handler) /** - * @param string $mode self::MODE_CONTINUE|self::MODE_RESET|self::MODE_INIT - * @param IConfiguration $config - * @return void + * @param self::MODE_* $mode */ - public function run($mode = self::MODE_CONTINUE, IConfiguration $config = null) + public function run(string $mode = self::MODE_CONTINUE, ?IConfiguration $config = null): void { if ($config) { foreach ($config->getGroups() as $group) { @@ -142,24 +135,20 @@ public function run($mode = self::MODE_CONTINUE, IConfiguration $config = null) } - /** - * @param string $name - * @return IExtensionHandler - */ - public function getExtension($name) + public function getExtension(string $name): IExtensionHandler { if (!isset($this->extensionsHandlers[$name])) { throw new LogicException("Extension '$name' not found."); } + return $this->extensionsHandlers[$name]; } /** - * @param File $file * @return int number of executed queries */ - protected function execute(File $file) + protected function execute(File $file): int { $this->driver->beginTransaction(); @@ -173,6 +162,7 @@ protected function execute(File $file) try { $queriesCount = $this->getExtension($file->extension)->execute($file); + } catch (\Exception $e) { $this->driver->rollbackTransaction(); throw new ExecutionException(sprintf('Executing migration "%s" has failed.', $file->path), 0, $e); diff --git a/src/Entities/Group.php b/src/Entities/Group.php index 00fc2e4..146db30 100644 --- a/src/Entities/Group.php +++ b/src/Entities/Group.php @@ -26,7 +26,7 @@ class Group /** @var string absolute path do directory */ public $directory; - /** @var string[] */ + /** @var list */ public $dependencies; /** @var IDiffGenerator|null */ diff --git a/src/Extensions/PhpHandler.php b/src/Extensions/PhpHandler.php index 2f77a6c..08ab3a7 100644 --- a/src/Extensions/PhpHandler.php +++ b/src/Extensions/PhpHandler.php @@ -20,12 +20,12 @@ */ class PhpHandler implements IExtensionHandler { - /** @var array name => value */ + /** @var array name => value */ private $params; /** - * @param array $params name => value + * @param array $params (name => value) */ public function __construct(array $params = []) { @@ -34,11 +34,9 @@ public function __construct(array $params = []) /** - * @param string $name * @param mixed $value - * @return self */ - public function addParameter($name, $value) + public function addParameter(string $name, $value): self { $this->params[$name] = $value; return $this; @@ -46,25 +44,23 @@ public function addParameter($name, $value) /** - * @return array (name => value) + * @return array (name => value) */ - public function getParameters() + public function getParameters(): array { return $this->params; } - /** - * @param File $file - * @return int number of queries - */ - public function execute(File $file) + public function execute(File $file): int { extract($this->params, EXTR_SKIP); $count = @include $file->path; + if ($count === false) { throw new IOException("Cannot include file '{$file->path}'."); } + return $count; } } diff --git a/src/Extensions/SqlHandler.php b/src/Extensions/SqlHandler.php index 6996ea2..7eb61ab 100644 --- a/src/Extensions/SqlHandler.php +++ b/src/Extensions/SqlHandler.php @@ -24,25 +24,20 @@ class SqlHandler implements IExtensionHandler private $driver; - /** - * @param IDriver $driver - */ public function __construct(IDriver $driver) { $this->driver = $driver; } - /** - * @param File $file - * @return int number of queries - */ - public function execute(File $file) + public function execute(File $file): int { $count = $this->driver->loadFile($file->path); + if ($count === 0) { throw new LogicException("{$file->path} is empty"); } + return $count; } } diff --git a/src/IConfiguration.php b/src/IConfiguration.php index c354ea4..436367d 100644 --- a/src/IConfiguration.php +++ b/src/IConfiguration.php @@ -18,13 +18,13 @@ interface IConfiguration { /** - * @return Group[] + * @return list */ - public function getGroups(); + public function getGroups(): array; /** - * @return array (extension => IExtensionHandler) + * @return array (extension => IExtensionHandler) */ - public function getExtensionHandlers(); + public function getExtensionHandlers(): array; } diff --git a/src/IDbal.php b/src/IDbal.php index b020e53..2c5a4e4 100644 --- a/src/IDbal.php +++ b/src/IDbal.php @@ -9,7 +9,7 @@ namespace Nextras\Migrations; -use DateTime; +use DateTimeInterface; /** @@ -18,51 +18,28 @@ interface IDbal { /** - * @param string $sql - * @return array list of rows represented by assoc. arrays + * @return array> list of rows represented by assoc. arrays */ - function query($sql); + public function query(string $sql): array; /** - * @param string $sql * @return int number of affected rows */ - function exec($sql); + public function exec(string $sql): int; - /** - * @param string $value - * @return string escaped string wrapped in quotes - */ - function escapeString($value); + public function escapeString(string $value): string; - /** - * @param int $value - * @return string - */ - function escapeInt($value); + public function escapeInt(int $value): string; - /** - * @param bool $value - * @return string - */ - function escapeBool($value); + public function escapeBool(bool $value): string; - /** - * @param DateTime $value - * @return string - */ - function escapeDateTime(DateTime $value); - + public function escapeDateTime(DateTimeInterface $value): string; - /** - * @param string $value - * @return string - */ - function escapeIdentifier($value); + public function escapeIdentifier(string $value): string; } diff --git a/src/IDiffGenerator.php b/src/IDiffGenerator.php index 605a1d6..2ecb2f4 100644 --- a/src/IDiffGenerator.php +++ b/src/IDiffGenerator.php @@ -12,15 +12,14 @@ interface IDiffGenerator { - /** - * @return string + * @return string file extension */ - function getExtension(); + public function getExtension(): string; /** * @return string SQL (semicolon-separated queries) */ - function generateContent(); + public function generateContent(): string; } diff --git a/src/IDriver.php b/src/IDriver.php index 0c96b81..67740e0 100644 --- a/src/IDriver.php +++ b/src/IDriver.php @@ -18,112 +18,98 @@ */ interface IDriver { - /** @const shared lock identifier */ - const LOCK_NAME = 'Nextras.Migrations'; - - /** * Setups the connection, such as encoding, default schema, etc. */ - function setupConnection(); + public function setupConnection(): void; /** - * Drops the database / schema. Should removes all db objects (tables, views, procedures, sequences, ...) - * - * @return mixed + * Drops the database / schema. Should remove all db objects (tables, views, procedures, sequences, ...) */ - function emptyDatabase(); + public function emptyDatabase(): void; /** * Loads and executes SQL queries from given file. * - * @param string $path * @return int number of executed queries */ - function loadFile($path); + public function loadFile(string $path): int; /** * Starts transaction. */ - function beginTransaction(); + public function beginTransaction(): void; /** * Commit transaction. */ - function commitTransaction(); + public function commitTransaction(): void; /** * Rollback transaction. */ - function rollbackTransaction(); + public function rollbackTransaction(): void; /** * Locks database for running migrations. */ - function lock(); + public function lock(): void; /** * Unlocks database. */ - function unlock(); + public function unlock(): void; /** * Creates migration table. */ - function createTable(); + public function createTable(): void; /** * Drop migration table. */ - function dropTable(); + public function dropTable(): void; /** * Inserts migration info into migration table. - * - * @param Migration $migration */ - function insertMigration(Migration $migration); + public function insertMigration(Migration $migration): void; /** * Updated migration as executed. - * - * @param Migration $migration */ - function markMigrationAsReady(Migration $migration); + public function markMigrationAsReady(Migration $migration): void; /** * Returns all migrations stored in migration table sorted by time. * - * @return Migration[] + * @return list */ - function getAllMigrations(); + public function getAllMigrations(): array; /** * Returns source code for migration table initialization. - * - * @return string */ - function getInitTableSource(); + public function getInitTableSource(): string; /** * Returns source code for migration table data initialization. * - * @param File[] $files - * @return string + * @param list $files */ - function getInitMigrationsSource(array $files); + public function getInitMigrationsSource(array $files): string; } diff --git a/src/IExtensionHandler.php b/src/IExtensionHandler.php index ea631af..12c5551 100644 --- a/src/IExtensionHandler.php +++ b/src/IExtensionHandler.php @@ -19,8 +19,7 @@ interface IExtensionHandler { /** - * @param File $file * @return int number of queries */ - function execute(File $file); + public function execute(File $file): int; } diff --git a/src/IPrinter.php b/src/IPrinter.php index 1a83aae..71a11fe 100644 --- a/src/IPrinter.php +++ b/src/IPrinter.php @@ -18,51 +18,42 @@ interface IPrinter { /** - * Print general info about mode. - * - reset = Database has been wiped. - * - continue = Running new migrations. - * - * @param string $mode + * Prints general info about mode. */ - function printIntro($mode); + public function printIntro(string $mode): void; /** * List of migrations which should be executed has been completed. * - * @param File[] $toExecute + * @param list $toExecute */ - function printToExecute(array $toExecute); + public function printToExecute(array $toExecute): void; /** * A migration has been successfully executed. * - * @param File $file * @param int $count number of executed queries - * @param float $time elapsed time in milliseconds + * @param float $time elapsed time in seconds */ - function printExecute(File $file, $count, $time); + public function printExecute(File $file, int $count, float $time): void; /** * All migrations have been successfully executed. */ - function printDone(); + public function printDone(): void; /** * An error has occurred during execution of a migration. - * - * @param Exception $e */ - function printError(Exception $e); + public function printError(Exception $e): void; /** * Prints init source code. - * - * @param string $code */ - function printSource($code); + public function printSource(string $code): void; } diff --git a/src/Printers/Console.php b/src/Printers/Console.php index 4d42c72..6b52c3b 100644 --- a/src/Printers/Console.php +++ b/src/Printers/Console.php @@ -36,14 +36,14 @@ public function __construct() } - public function printIntro($mode) + public function printIntro(string $mode): void { $this->output('Nextras Migrations'); $this->output(strtoupper($mode), self::COLOR_INTRO); } - public function printToExecute(array $toExecute) + public function printToExecute(array $toExecute): void { if ($toExecute) { $count = count($toExecute); @@ -54,30 +54,30 @@ public function printToExecute(array $toExecute) } - public function printExecute(File $file, $count, $time) + public function printExecute(File $file, int $count, float $time): void { $this->output( '- ' . $file->group->name . '/' . $file->name . '; ' - . $this->color($count, self::COLOR_INFO) . ' queries; ' - . $this->color(sprintf('%0.3f', $time), self::COLOR_INFO) . ' s' + . $this->colorize((string) $count, self::COLOR_INFO) . ' queries; ' + . $this->colorize(sprintf('%0.3f', $time), self::COLOR_INFO) . ' s' ); } - public function printDone() + public function printDone(): void { $this->output('OK', self::COLOR_SUCCESS); } - public function printError(Exception $e) + public function printError(Exception $e): void { $this->output('ERROR: ' . $e->getMessage(), self::COLOR_ERROR); throw $e; } - public function printSource($code) + public function printSource(string $code): void { $this->output($code); } @@ -86,41 +86,27 @@ public function printSource($code) /** * Prints text to a console, optionally in a specific color. * - * @param string $s - * @param string|NULL $color self::COLOR_* + * @param string|null $color self::COLOR_* */ - protected function output($s, $color = null) + protected function output(string $s, ?string $color = null): void { - if ($color === null || !$this->useColors) { - echo "$s\n"; - } else { - echo $this->color($s, $color) . "\n"; - } + echo $this->colorize($s, $color) . "\n"; } - /** - * @param string $s - * @param string $color - * @return string - */ - protected function color($s, $color) + protected function colorize(string $s, ?string $color): string { - if (!$this->useColors) { - return $s; - } - return "\033[{$color}m$s\033[22;39m"; + return $this->useColors && $color !== null ? "\033[{$color}m$s\033[22;39m" : $s; } /** - * @return bool TRUE if terminal support colors, FALSE otherwise - * @license New BSD License - * @author David Grudl + * @return bool true if terminal support colors, false otherwise */ - protected function detectColorSupport() + protected function detectColorSupport(): bool { - return (getenv('ConEmuANSI') === 'ON' || getenv('ANSICON') !== false - || (defined('STDOUT') && function_exists('posix_isatty') && posix_isatty(STDOUT))); + return (function_exists('posix_isatty') && posix_isatty(STDOUT)) + || (function_exists('stream_isatty') && stream_isatty(STDOUT)) + || (function_exists('sapi_windows_vt100_support') && sapi_windows_vt100_support(STDOUT)); } } diff --git a/src/Printers/DevNull.php b/src/Printers/DevNull.php index 36a88c6..7479e97 100644 --- a/src/Printers/DevNull.php +++ b/src/Printers/DevNull.php @@ -21,32 +21,32 @@ */ class DevNull implements IPrinter { - public function printIntro($mode) + public function printIntro(string $mode): void { } - public function printToExecute(array $toExecute) + public function printToExecute(array $toExecute): void { } - public function printExecute(File $file, $count, $time) + public function printExecute(File $file, int $count, float $time): void { } - public function printDone() + public function printDone(): void { } - public function printError(Exception $e) + public function printError(Exception $e): void { } - public function printSource($code) + public function printSource(string $code): void { } } diff --git a/src/Printers/HtmlDump.php b/src/Printers/HtmlDump.php index 8c6b6f0..5d35d7e 100644 --- a/src/Printers/HtmlDump.php +++ b/src/Printers/HtmlDump.php @@ -27,7 +27,7 @@ class HtmlDump implements IPrinter private $index; - public function printIntro($mode) + public function printIntro(string $mode): void { if ($mode === Runner::MODE_RESET) { $this->output(' RESET: All tables, views and data has been destroyed!'); @@ -37,7 +37,7 @@ public function printIntro($mode) } - public function printToExecute(array $toExecute) + public function printToExecute(array $toExecute): void { if ($toExecute) { $this->output(' ' . count($toExecute) . ' migrations need to be executed.'); @@ -50,9 +50,9 @@ public function printToExecute(array $toExecute) } - public function printExecute(File $file, $count, $time) + public function printExecute(File $file, int $count, float $time): void { - $format = '%0' . strlen($this->count) . 'd'; + $format = '%0' . strlen((string) $this->count) . 'd'; $name = htmlspecialchars($file->group->name . '/' . $file->name); $this->output(sprintf( $format . '/' . $format . ': %s (%d %s, %0.3f s)', @@ -61,31 +61,26 @@ public function printExecute(File $file, $count, $time) } - public function printDone() + public function printDone(): void { $this->output('OK', 'success'); } - public function printError(Exception $e) + public function printError(Exception $e): void { $this->output('ERROR: ' . htmlspecialchars($e->getMessage()), 'error'); throw $e; } - public function printSource($code) + public function printSource(string $code): void { $this->output($code); } - /** - * @param string $s HTML string - * @param string $class - * @return void - */ - protected function output($s, $class = 'info') + protected function output(string $s, string $class = 'info'): void { echo "
$s
\n"; } diff --git a/src/exceptions.php b/src/exceptions.php index 903bbe7..3fa3034 100644 --- a/src/exceptions.php +++ b/src/exceptions.php @@ -9,11 +9,13 @@ namespace Nextras\Migrations; +use Throwable; + /** * Marker interface. */ -interface Exception +interface Exception extends Throwable { } diff --git a/tests/cases/integration/dbal/Runner.EmptyRun.phpt b/tests/cases/integration/dbal/Runner.EmptyRun.phpt index 5bc1c7e..255182c 100644 --- a/tests/cases/integration/dbal/Runner.EmptyRun.phpt +++ b/tests/cases/integration/dbal/Runner.EmptyRun.phpt @@ -15,7 +15,7 @@ require __DIR__ . '/../../../bootstrap.php'; class EmptyRunTest extends IntegrationTestCase { - public function testReset() + public function testReset(): void { $this->runner->run(Runner::MODE_RESET); Assert::same([ @@ -29,7 +29,7 @@ class EmptyRunTest extends IntegrationTestCase } - protected function getGroups($dir) + protected function getGroups(string $dir): array { return []; } diff --git a/tests/cases/integration/dbal/Runner.FirstRun.phpt b/tests/cases/integration/dbal/Runner.FirstRun.phpt index 2051f11..dc54197 100644 --- a/tests/cases/integration/dbal/Runner.FirstRun.phpt +++ b/tests/cases/integration/dbal/Runner.FirstRun.phpt @@ -16,7 +16,7 @@ require __DIR__ . '/../../../bootstrap.php'; class FirstRunTest extends IntegrationTestCase { - public function testReset() + public function testReset(): void { $this->runner->run(Runner::MODE_RESET); Assert::same([ @@ -54,7 +54,7 @@ class FirstRunTest extends IntegrationTestCase } - public function testContinue() + public function testContinue(): void { $this->runner->run(Runner::MODE_CONTINUE); Assert::same([ @@ -92,7 +92,7 @@ class FirstRunTest extends IntegrationTestCase } - public function testInit() + public function testInit(): void { $options = Tester\Environment::loadData(); $this->runner->run(Runner::MODE_INIT); diff --git a/tests/cases/integration/dbal/Runner.SecondRun.phpt b/tests/cases/integration/dbal/Runner.SecondRun.phpt index 0756b62..c0c5947 100644 --- a/tests/cases/integration/dbal/Runner.SecondRun.phpt +++ b/tests/cases/integration/dbal/Runner.SecondRun.phpt @@ -17,7 +17,7 @@ require __DIR__ . '/../../../bootstrap.php'; class SecondRunTest extends IntegrationTestCase { - public function testReset() + public function testReset(): void { $this->driver->loadFile($this->fixtureDir . '/3ok.sql'); Assert::count(3, $this->driver->getAllMigrations()); @@ -39,7 +39,7 @@ class SecondRunTest extends IntegrationTestCase } - public function testContinueOk() + public function testContinueOk(): void { $this->driver->loadFile($this->fixtureDir . '/3ok.sql'); Assert::count(3, $this->driver->getAllMigrations()); @@ -58,7 +58,7 @@ class SecondRunTest extends IntegrationTestCase } - public function testContinueError() + public function testContinueError(): void { $this->driver->loadFile($this->fixtureDir . '/2ok, 1ko.sql'); Assert::count(3, $this->driver->getAllMigrations()); @@ -77,7 +77,7 @@ class SecondRunTest extends IntegrationTestCase } - public function testInit() + public function testInit(): void { $options = Tester\Environment::loadData(); $this->driver->loadFile($this->fixtureDir . '/3ok.sql'); diff --git a/tests/cases/integration/nette-di/MigrationsExtension.phpt b/tests/cases/integration/nette-di/MigrationsExtension.phpt index 0167527..80cb5d1 100644 --- a/tests/cases/integration/nette-di/MigrationsExtension.phpt +++ b/tests/cases/integration/nette-di/MigrationsExtension.phpt @@ -21,7 +21,7 @@ class MigrationsExtensionTest extends TestCase /** * @dataProvider provideCommandsData */ - public function testCommands($config) + public function testCommands(string $config): void { $dic = $this->createContainer($config); @@ -31,7 +31,7 @@ class MigrationsExtensionTest extends TestCase } - public function provideCommandsData() + public function provideCommandsData(): array { return [ ['configA'], @@ -47,7 +47,7 @@ class MigrationsExtensionTest extends TestCase /** * @dataProvider provideDiffGeneratorData */ - public function testDoctrineDiffGenerator($config) + public function testDoctrineDiffGenerator(string $config): void { $dic = $this->createContainer($config); @@ -62,7 +62,7 @@ class MigrationsExtensionTest extends TestCase } - public function provideDiffGeneratorData() + public function provideDiffGeneratorData(): array { return [ ['diffGenerator.configA'], @@ -71,7 +71,7 @@ class MigrationsExtensionTest extends TestCase } - public function testDynamicContainerParameters() + public function testDynamicContainerParameters(): void { if (!method_exists(Nette\DI\Compiler::class, 'setDynamicParameterNames')) { Environment::skip('Required Nette >= 2.4.7'); @@ -89,7 +89,7 @@ class MigrationsExtensionTest extends TestCase } - public function testOptionsAsService() + public function testOptionsAsService(): void { $container = $this->createContainer('optionsAsService'); @@ -100,7 +100,7 @@ class MigrationsExtensionTest extends TestCase } - public function testMultipleRegistrations() + public function testMultipleRegistrations(): void { $container = $this->createContainer('multipleRegistrations'); @@ -113,11 +113,7 @@ class MigrationsExtensionTest extends TestCase } - /** - * @param string $config - * @return Nette\DI\Container - */ - protected function createContainer($config, array $dynamicParameters = null) + protected function createContainer(string $config, array $dynamicParameters = null): Nette\DI\Container { $options = parse_ini_file(__DIR__ . '/../../../drivers.ini', true)['mysql']; diff --git a/tests/cases/integration/symfony-bundle/SymfonyBundleTest.phpt b/tests/cases/integration/symfony-bundle/SymfonyBundleTest.phpt index 15621af..2af253b 100644 --- a/tests/cases/integration/symfony-bundle/SymfonyBundleTest.phpt +++ b/tests/cases/integration/symfony-bundle/SymfonyBundleTest.phpt @@ -24,7 +24,7 @@ class SymfonyBundleTest extends TestCase private $symfonyKernel; - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -48,7 +48,7 @@ class SymfonyBundleTest extends TestCase } - public function testMigrationsReset() + public function testMigrationsReset(): void { $application = new Application($this->symfonyKernel); @@ -58,7 +58,7 @@ class SymfonyBundleTest extends TestCase } - public function testMigrationsContinue() + public function testMigrationsContinue(): void { $application = new Application($this->symfonyKernel); diff --git a/tests/cases/unit/BaseDriverTest.phpt b/tests/cases/unit/BaseDriverTest.phpt index 3ebfa19..1623d5f 100644 --- a/tests/cases/unit/BaseDriverTest.phpt +++ b/tests/cases/unit/BaseDriverTest.phpt @@ -19,7 +19,7 @@ class BaseDriverTest extends Tester\TestCase /** * @dataProvider provideLoadFileData */ - public function testLoadFile($content, array $expectedQueries) + public function testLoadFile(string $content, array $expectedQueries): void { $dbal = Mockery::mock(Nextras\Migrations\IDbal::class); $dbal->shouldReceive('escapeIdentifier')->with('migrations')->andReturn('migrations'); @@ -38,7 +38,7 @@ class BaseDriverTest extends Tester\TestCase } - protected function provideLoadFileData() + protected function provideLoadFileData(): array { return [ [ diff --git a/tests/cases/unit/CreateCommandTest.phpt b/tests/cases/unit/CreateCommandTest.phpt index cb3da98..70065d3 100644 --- a/tests/cases/unit/CreateCommandTest.phpt +++ b/tests/cases/unit/CreateCommandTest.phpt @@ -18,7 +18,7 @@ require __DIR__ . '/../../bootstrap.php'; class CreateCommandTest extends Tester\TestCase { - public function testTypeArgDescription() + public function testTypeArgDescription(): void { $driver = Mockery::mock(Nextras\Migrations\IDriver::class); $config = new DefaultConfiguration('migrations', $driver); diff --git a/tests/cases/unit/Finder.logicalName.phpt b/tests/cases/unit/Finder.logicalName.phpt index fcf1c9d..7b125c6 100644 --- a/tests/cases/unit/Finder.logicalName.phpt +++ b/tests/cases/unit/Finder.logicalName.phpt @@ -22,11 +22,11 @@ class FinderLogicalNameTest extends Tester\TestCase /** @var Finder|Mockery\MockInterface */ private $finder; - /** @var Group[] */ + /** @var list */ private $groups; - protected function setUp() + protected function setUp(): void { parent::setUp(); $this->finder = Mockery::mock(Nextras\Migrations\Engine\Finder::class) @@ -44,7 +44,7 @@ class FinderLogicalNameTest extends Tester\TestCase } - public function testSimple() + public function testSimple(): void { $this->finder->shouldReceive('getItems') ->with('./baseDir/structures') @@ -62,7 +62,7 @@ class FinderLogicalNameTest extends Tester\TestCase } - public function testComplex() + public function testComplex(): void { $this->finder->shouldReceive('getItems') ->with('./baseDir/structures') diff --git a/tests/cases/unit/OrderResolverTest.phpt b/tests/cases/unit/OrderResolverTest.phpt index 619b6b4..44af898 100644 --- a/tests/cases/unit/OrderResolverTest.phpt +++ b/tests/cases/unit/OrderResolverTest.phpt @@ -21,7 +21,7 @@ require __DIR__ . '/../../bootstrap.php'; class OrderResolverTest extends Tester\TestCase { - public function testFirstRun() + public function testFirstRun(): void { $resolver = new OrderResolver; @@ -39,7 +39,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testFirstRunTwoGroups() + public function testFirstRunTwoGroups(): void { $resolver = new OrderResolver; @@ -59,7 +59,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testSecondRunContinue() + public function testSecondRunContinue(): void { $resolver = new OrderResolver; @@ -78,7 +78,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testSecondRunContinueNothingToDo() + public function testSecondRunContinueNothingToDo(): void { $resolver = new OrderResolver; @@ -98,7 +98,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testSecondRunContinueTwoGroups() + public function testSecondRunContinueTwoGroups(): void { $resolver = new OrderResolver; @@ -123,7 +123,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testSecondRunContinueDisabledGroup() + public function testSecondRunContinueDisabledGroup(): void { $resolver = new OrderResolver; @@ -146,7 +146,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testSecondRunReset() + public function testSecondRunReset(): void { $resolver = new OrderResolver; @@ -164,7 +164,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testRunWithDisabledGroups() + public function testRunWithDisabledGroups(): void { $groupA = $this->createGroup('structures'); $groupB = $this->createGroup('data', false, ['structures']); @@ -181,7 +181,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testTopologicalOrder() + public function testTopologicalOrder(): void { $resolver = new OrderResolver(); @@ -200,7 +200,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testIndependentGroupsOrder1() + public function testIndependentGroupsOrder1(): void { $resolver = new OrderResolver(); @@ -222,7 +222,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testIndependentGroupsOrder2() + public function testIndependentGroupsOrder2(): void { $resolver = new OrderResolver(); @@ -247,7 +247,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testErrorRemovedFile() + public function testErrorRemovedFile(): void { $resolver = new OrderResolver; @@ -267,7 +267,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testErrorChangedChecksum() + public function testErrorChangedChecksum(): void { $resolver = new OrderResolver; @@ -288,7 +288,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testErrorIncompleteMigration() + public function testErrorIncompleteMigration(): void { $resolver = new OrderResolver; @@ -309,7 +309,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testErrorNewMigrationInTheMiddleOfExistingOnes() + public function testErrorNewMigrationInTheMiddleOfExistingOnes(): void { $resolver = new OrderResolver; @@ -332,7 +332,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testErrorNewMigrationInTheMiddleOfExistingOnes2() + public function testErrorNewMigrationInTheMiddleOfExistingOnes2(): void { $resolver = new OrderResolver(); @@ -359,7 +359,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testErrorNewMigrationInTheMiddleOfExistingOnes3() + public function testErrorNewMigrationInTheMiddleOfExistingOnes3(): void { $resolver = new OrderResolver(); @@ -385,7 +385,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testErrorMigrationDependingOnUnknownGroup() + public function testErrorMigrationDependingOnUnknownGroup(): void { $resolver = new OrderResolver; @@ -402,7 +402,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testErrorGroupDependingOnUnknownGroup() + public function testErrorGroupDependingOnUnknownGroup(): void { $resolver = new OrderResolver; @@ -419,7 +419,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testErrorDisablingRequiredGroup() + public function testErrorDisablingRequiredGroup(): void { $resolver = new OrderResolver; @@ -437,7 +437,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testErrorAmbiguousLogicalName() + public function testErrorAmbiguousLogicalName(): void { $resolver = new OrderResolver(); @@ -458,7 +458,7 @@ class OrderResolverTest extends Tester\TestCase } - public function testErrorAmbiguousLogicalNameCyclic() + public function testErrorAmbiguousLogicalNameCyclic(): void { $resolver = new OrderResolver(); @@ -479,28 +479,31 @@ class OrderResolverTest extends Tester\TestCase } - private function createMigration($groupName, $fileName, $checksum = null, $completed = true) + private function createMigration(string $groupName, string $fileName, ?string $checksum = null, bool $completed = true): Migration { $migration = new Migration; $migration->group = $groupName; $migration->filename = $fileName; - $migration->checksum = $checksum ?: "$fileName.md5"; + $migration->checksum = $checksum ?? "$fileName.md5"; $migration->completed = $completed; return $migration; } - private function createFile($name, $group, $checksum = null) + private function createFile(string $name, Group $group, ?string $checksum = null): File { $file = new File; $file->name = $name; $file->group = $group; - $file->checksum = $checksum ?: "$name.md5"; + $file->checksum = $checksum ?? "$name.md5"; return $file; } - private function createGroup($name, $enabled = true, $deps = []) + /** + * @param list $deps + */ + private function createGroup(string $name, bool $enabled = true, array $deps = []): Group { $group = new Group; $group->name = $name; diff --git a/tests/inc/IntegrationTestCase.php b/tests/inc/IntegrationTestCase.php index 5d2e420..f68e152 100644 --- a/tests/inc/IntegrationTestCase.php +++ b/tests/inc/IntegrationTestCase.php @@ -40,7 +40,7 @@ abstract class IntegrationTestCase extends TestCase protected $fixtureDir; - protected function setUp() + protected function setUp(): void { parent::setUp(); @@ -72,7 +72,7 @@ protected function setUp() } - protected function tearDown() + protected function tearDown(): void { parent::tearDown(); $cleanupDb = require $this->fixtureDir . '/cleanup.php'; @@ -81,7 +81,10 @@ protected function tearDown() } - protected function getGroups($dir) + /** + * @return list + */ + protected function getGroups(string $dir): array { $structures = new Group(); $structures->enabled = true; @@ -106,9 +109,9 @@ protected function getGroups($dir) /** - * @return array (extension => IExtensionHandler) + * @return array (extension => IExtensionHandler) */ - protected function getExtensionHandlers() + protected function getExtensionHandlers(): array { return [ 'sql' => new Nextras\Migrations\Extensions\SqlHandler($this->driver), @@ -117,11 +120,9 @@ protected function getExtensionHandlers() /** - * @param array $options - * @return IDbal * @throws \Exception */ - protected function createDbal($options) + protected function createDbal(array $options): IDbal { switch ($options['dbal']) { case 'dibi': @@ -178,12 +179,7 @@ protected function createDbal($options) } - /** - * @param array $name - * @param IDbal $dbal - * @return IDriver - */ - protected function createDriver($name, IDbal $dbal) + protected function createDriver(string $name, IDbal $dbal): IDriver { switch ($name) { case 'mysql': @@ -191,14 +187,14 @@ protected function createDriver($name, IDbal $dbal) case 'pgsql': return new Nextras\Migrations\Drivers\PgSqlDriver($dbal, 'm', $this->dbName); + + default: + throw new \Exception("Unknown driver '$name'."); } } - /** - * @return IPrinter - */ - protected function createPrinter() + protected function createPrinter(): IPrinter { return new TestPrinter(); } diff --git a/tests/inc/TestPrinter.php b/tests/inc/TestPrinter.php index cdcf405..a1abf8e 100644 --- a/tests/inc/TestPrinter.php +++ b/tests/inc/TestPrinter.php @@ -7,7 +7,7 @@ class TestPrinter extends Console { - /** @var string[] output lines */ + /** @var list output lines */ public $lines = []; /** @var string whole output */ @@ -21,7 +21,7 @@ public function __construct() } - protected function output($s, $color = NULL) + protected function output(string $s, string $color = null): void { $this->lines[] = preg_replace('#; \d+\.\d+ s#', '; XX s', $s); $this->out .= "$s\n"; diff --git a/tests/inc/TestSymfonyKernel.php b/tests/inc/TestSymfonyKernel.php index 9d93629..7a92c11 100644 --- a/tests/inc/TestSymfonyKernel.php +++ b/tests/inc/TestSymfonyKernel.php @@ -20,11 +20,7 @@ class TestSymfonyKernel extends Kernel private $parameters; - /** - * @param string $configPath - * @param array $parameters - */ - public function __construct($configPath, array $parameters) + public function __construct(string $configPath, array $parameters) { parent::__construct('dev', true); @@ -33,13 +29,13 @@ public function __construct($configPath, array $parameters) } - public function getRootDir() + public function getRootDir(): string { return TEMP_DIR . '/symfony-bundle'; } - public function registerBundles() + public function registerBundles(): array { return [ new FrameworkBundle(), @@ -49,9 +45,9 @@ public function registerBundles() } - public function registerContainerConfiguration(LoaderInterface $loader) + public function registerContainerConfiguration(LoaderInterface $loader): void { - $loader->load(function (ContainerBuilder $container) { + $loader->load(function (ContainerBuilder $container): void { $container->addResource(new ContainerParametersResource($this->parameters)); foreach ($this->parameters as $key => $value) { $container->setParameter($key, $value); diff --git a/tests/inc/TestSymfonyKernel6.php b/tests/inc/TestSymfonyKernel6.php index 3e78f82..f95a6c3 100644 --- a/tests/inc/TestSymfonyKernel6.php +++ b/tests/inc/TestSymfonyKernel6.php @@ -21,10 +21,9 @@ class TestSymfonyKernel6 extends Kernel /** - * @param string $configPath * @param array $parameters */ - public function __construct($configPath, array $parameters) + public function __construct(string $configPath, array $parameters) { parent::__construct('dev', true); @@ -33,7 +32,7 @@ public function __construct($configPath, array $parameters) } - public function getRootDir() + public function getRootDir(): string { return TEMP_DIR . '/symfony-bundle'; } @@ -49,9 +48,9 @@ public function registerBundles(): iterable } - public function registerContainerConfiguration(LoaderInterface $loader) + public function registerContainerConfiguration(LoaderInterface $loader): void { - $loader->load(function (ContainerBuilder $container) { + $loader->load(function (ContainerBuilder $container): void { $container->addResource(new ContainerParametersResource($this->parameters)); foreach ($this->parameters as $key => $value) { $container->setParameter($key, $value);