diff --git a/.github/workflows/phpstan.yml b/.github/workflows/phpstan.yml index f69ae263..cae8fcc7 100644 --- a/.github/workflows/phpstan.yml +++ b/.github/workflows/phpstan.yml @@ -17,7 +17,7 @@ jobs: strategy: fail-fast: false matrix: - php-version: ['7.4'] + php-version: ['8.1'] name: PHP ${{ matrix.php-version }} @@ -41,10 +41,10 @@ jobs: run: composer update --prefer-dist --no-progress --no-suggest --prefer-stable - name: Bake factories to perform analysis in the following steps - run : vendor/bin/phpunit vendor/bin/phpunit tests/TestCase/Command/BakeFixtureFactoryCommandTest.php + run : vendor/bin/phpunit tests/TestCase/Command/BakeFixtureFactoryCommandTest.php - name: Run phpstan - run: composer phpstan + run: composer stan - name: Run phpcs run: composer cs-check diff --git a/.github/workflows/tests_composer2.yml b/.github/workflows/tests_composer2.yml index db8fc271..d89baba8 100644 --- a/.github/workflows/tests_composer2.yml +++ b/.github/workflows/tests_composer2.yml @@ -17,7 +17,7 @@ jobs: strategy: fail-fast: false matrix: - php-version: ['7.4', '8.0', '8.2'] + php-version: ['8.1', '8.2'] db-type: [sqlite, mysql, pgsql] composer-type: [lowest, stable, dev] @@ -54,7 +54,7 @@ jobs: - name: Install dependencies run: | if [[ ${{ matrix.composer-type }} == 'lowest' ]]; then - composer self-update --1 && composer update --prefer-dist --no-progress --no-suggest --prefer-stable --prefer-lowest + composer update --prefer-dist --no-progress --no-suggest --prefer-stable --prefer-lowest elif [[ ${{ matrix.composer-type }} == 'stable' ]]; then composer update --prefer-dist --no-progress --no-suggest --prefer-stable else diff --git a/.gitignore b/.gitignore index 561c3025..d8798fd7 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,7 @@ tmp/ .idea composer.lock **/test_fixture_factories -.phpunit.result.cache +.phpunit.cache tests/.env # These factories are baked by TestFixtureFactoryTaskTest diff --git a/composer.json b/composer.json index 743c4e9d..444d302c 100644 --- a/composer.json +++ b/composer.json @@ -14,22 +14,20 @@ } ], "license": "MIT", - "minimum-stability": "dev", "require": { - "php": ">=7.2", - "cakephp/orm": "^4.2", + "php": ">=8.1", + "cakephp/orm": "^5.0", "fakerphp/faker": "^1.15", - "vierge-noire/cakephp-test-suite-light": "^2.1" + "vierge-noire/cakephp-test-suite-light": "^3.0" }, "require-dev": { - "cakephp/bake": "^2.0", - "cakephp/cakephp-codesniffer": "^4.0", - "cakephp/migrations": "^3.7", - "josegonzalez/dotenv": "dev-master", + "cakephp/bake": "^3.0.0", + "cakephp/cakephp-codesniffer": "^5.1", + "cakephp/migrations": "^4.0.0", + "josegonzalez/dotenv": "^4.0.0", "phpstan/phpstan": "^1.0", - "phpunit/phpunit": "^8.5.31", - "vierge-noire/cakephp-test-migrator": "^2.1", - "vimeo/psalm": "^4.0" + "phpunit/phpunit": "^10.1", + "vimeo/psalm": "^5.0" }, "autoload": { "psr-4": { @@ -50,7 +48,7 @@ "mysql": "bash run_tests.sh Mysql", "pgsql": "bash run_tests.sh Postgres", "sqlite": "bash run_tests.sh Sqlite", - "phpstan": "vendor/bin/phpstan analyse --memory-limit=-1", + "stan": "vendor/bin/phpstan analyse --memory-limit=-1", "psalm": "vendor/bin/psalm", "cs-check": "vendor/bin/phpcs --colors -p -s --extensions=php src/ tests/TestApp/tests/Factory tests/TestApp/plugins/TestPlugin/tests/Factory", "cs-fix": "vendor/bin/phpcbf --colors -p -s --extensions=php src/ tests/TestApp/tests/Factory" @@ -60,5 +58,7 @@ "allow-plugins": { "dealerdirect/phpcodesniffer-composer-installer": true } - } + }, + "minimum-stability": "dev", + "prefer-stable": true } diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 88b2f1ea..9b850d8a 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,15 +1,22 @@ - + + + + + + + @@ -17,19 +24,10 @@ - - - - - - - - - - - + + ./src/ - - + + diff --git a/psalm.xml b/psalm.xml index 90a62c88..f2292cc1 100644 --- a/psalm.xml +++ b/psalm.xml @@ -1,7 +1,10 @@ - diff --git a/src/Command/BakeFixtureFactoryCommand.php b/src/Command/BakeFixtureFactoryCommand.php index d217c56f..f61d36bd 100644 --- a/src/Command/BakeFixtureFactoryCommand.php +++ b/src/Command/BakeFixtureFactoryCommand.php @@ -19,12 +19,14 @@ use Cake\Console\ConsoleIo; use Cake\Console\ConsoleOptionParser; use Cake\Core\Configure; -use Cake\Filesystem\Folder; use Cake\ORM\Table; use Cake\ORM\TableRegistry; +use Cake\Utility\Hash; use Cake\Utility\Inflector; use CakephpFixtureFactories\Factory\FactoryAwareTrait; +use Exception; use ReflectionClass; +use ReflectionException; class BakeFixtureFactoryCommand extends BakeCommand { @@ -33,17 +35,17 @@ class BakeFixtureFactoryCommand extends BakeCommand /** * @var string path to the Table dir */ - public $pathToTableDir = 'Model' . DS . 'Table' . DS; + public string $pathToTableDir = 'Model' . DS . 'Table' . DS; /** * @var string */ - private $modelName; + private string $modelName; /** * @var \Cake\ORM\Table */ - private $table; + private Table $table; /** * @return string Name of the command @@ -90,7 +92,7 @@ public function setTable(string $tableName, ConsoleIo $io) $this->table = TableRegistry::getTableLocator()->get($tableName); try { $this->table->getSchema(); - } catch (\Exception $e) { + } catch (Exception $e) { $io->warning("The table $tableName could not be found... in " . $this->getModelPath()); $io->abort($e->getMessage()); } @@ -119,9 +121,9 @@ public function getPath(Arguments $args): string /** * Locate tables * - * @return string|string[] + * @return array|string */ - public function getModelPath() + public function getModelPath(): string|array { if (!empty($this->plugin)) { $path = $this->_pluginPath($this->plugin) . APP_DIR . DS . $this->pathToTableDir; @@ -140,21 +142,23 @@ public function getModelPath() */ public function getTableList(ConsoleIo $io): array { - $dir = new Folder($this->getModelPath()); - $tables = $dir->find('.*Table.php', true); + $tables = glob($this->getModelPath() . '*Table.php') ?: []; $tables = array_map(function ($a) { return preg_replace('/Table.php$/', '', $a); }, $tables); - foreach ($tables as $i => $table) { + $return = []; + foreach ($tables as $table) { + $table = str_replace($this->getModelPath(), '', $table); if (!$this->thisTableShouldBeBaked($table, $io)) { - unset($tables[$i]); $io->warning("{$table} ignored"); + } else { + $return[] = $table; } } - return $tables; + return $return; } /** @@ -166,12 +170,12 @@ public function getTableList(ConsoleIo $io): array */ public function thisTableShouldBeBaked(string $table, ConsoleIo $io): bool { - $tableClassName = $this->plugin ? $this->plugin : Configure::read('App.namespace'); + $tableClassName = $this->plugin ?: Configure::read('App.namespace'); $tableClassName .= "\Model\Table\\{$table}Table"; try { $class = new ReflectionClass($tableClassName); - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { $io->error($e->getMessage()); return false; @@ -189,7 +193,7 @@ public function thisTableShouldBeBaked(string $table, ConsoleIo $io): bool * @param \Cake\Console\ConsoleIo $io Console * @return string */ - private function bakeAllModels(Arguments $args, ConsoleIo $io) + private function bakeAllModels(Arguments $args, ConsoleIo $io): string { $tables = $this->getTableList($io); if (empty($tables)) { @@ -255,9 +259,9 @@ public function execute(Arguments $args, ConsoleIo $io): ?int * @param string $modelName Name of the model * @param \Cake\Console\Arguments $args Arguments * @param \Cake\Console\ConsoleIo $io Console - * @return bool|int + * @return int|bool */ - public function bakeFixtureFactory(string $modelName, Arguments $args, ConsoleIo $io) + public function bakeFixtureFactory(string $modelName, Arguments $args, ConsoleIo $io): bool|int { $this->modelName = $modelName; @@ -291,22 +295,42 @@ public function templateData(Arguments $arg): array 'factory' => Inflector::singularize($this->modelName) . 'Factory', 'namespace' => $this->getFactoryNamespace($this->plugin), ]; + $useStatements = $methods = []; if ($arg->getOption('methods')) { $associations = $this->getAssociations(); - $data['toOne'] = $associations['toOne']; - $methods = array_keys($associations['toOne']); + if ($associations['toOne']) { + $data['toOne'] = $associations['toOne']; + $useStatements[] = Hash::extract($associations['toOne'], '{s}.fqcn'); + $methods = array_keys($associations['toOne']); + } - $data['oneToMany'] = $associations['oneToMany']; - $methods = array_merge(array_keys($associations['oneToMany']), $methods); + if ($associations['oneToMany']) { + $data['oneToMany'] = $associations['oneToMany']; + $useStatements[] = Hash::extract($associations['oneToMany'], '{s}.fqcn'); + $methods = array_merge(array_keys($associations['oneToMany']), $methods); + } - $data['manyToMany'] = $associations['manyToMany']; - $methods = array_merge(array_keys($associations['manyToMany']), $methods); + if ($associations['manyToMany']) { + $data['manyToMany'] = $associations['manyToMany']; + $useStatements[] = Hash::extract($associations['manyToMany'], '{s}.fqcn'); + $methods = array_merge(array_keys($associations['manyToMany']), $methods); + } - array_walk($methods, function (&$value) { + array_walk($methods, function (&$value): void { $value = "with$value"; }); $data['methods'] = $methods; + $data['useStatements'] = array_unique(array_values(Hash::flatten($useStatements))); + } + + if ($data['useStatements']) { + foreach ($data['useStatements'] as $index => $useStatement) { + $nameSpaceCheck = str_replace($data['namespace'] . '\\', '', $useStatement); + if (!str_contains($nameSpaceCheck, '\\')) { + unset($data['useStatements'][$index]); + } + } } return $data; @@ -328,16 +352,26 @@ public function getAssociations(): array foreach ($this->getTable()->associations() as $association) { $modelName = $association->getClassName(); $factory = $this->getFactoryClassName($modelName); + $factoryClassName = $this->getFactorySimpleClassName($modelName); switch ($association->type()) { case 'oneToOne': case 'manyToOne': - $associations['toOne'][$association->getName()] = $factory; + $associations['toOne'][$association->getName()] = [ + 'fqcn' => $factory, + 'className' => $factoryClassName, + ]; break; case 'oneToMany': - $associations['oneToMany'][$association->getName()] = $factory; + $associations['oneToMany'][$association->getName()] = [ + 'fqcn' => $factory, + 'className' => $factoryClassName, + ]; break; case 'manyToMany': - $associations['manyToMany'][$association->getName()] = $factory; + $associations['manyToMany'][$association->getName()] = [ + 'fqcn' => $factory, + 'className' => $factoryClassName, + ]; break; } } diff --git a/src/Command/PersistCommand.php b/src/Command/PersistCommand.php index 635d9f14..058b901f 100644 --- a/src/Command/PersistCommand.php +++ b/src/Command/PersistCommand.php @@ -170,7 +170,7 @@ public function attachMethod(Arguments $args, BaseFactory $factory, ConsoleIo $i * @param \CakephpFixtureFactories\Factory\BaseFactory $factory Factory * @return \CakephpFixtureFactories\Factory\BaseFactory */ - public function with(Arguments $args, BaseFactory $factory) + public function with(Arguments $args, BaseFactory $factory): BaseFactory { $with = $args->getOption('with'); @@ -233,7 +233,6 @@ public function dryRun(BaseFactory $factory, ConsoleIo $io): void $factory = get_class($factory); $io->success("{$times} {$factory} generated on dry run."); - $eol = PHP_EOL; foreach ($entities as $i => $entity) { $io->hr(); $io->info("[$i]"); diff --git a/src/Command/SetupCommand.php b/src/Command/SetupCommand.php deleted file mode 100644 index 7bb1f7c8..00000000 --- a/src/Command/SetupCommand.php +++ /dev/null @@ -1,135 +0,0 @@ -setDescription('Helper to setup your phpunit xml file') - ->addOption('plugin', [ - 'help' => 'Set configs in a plugin', - 'short' => 'p', - ]) - ->addOption('file', [ - 'help' => 'Name of the phpunit config file (per default phpunit.xml.dist)', - 'short' => 'f', - ]); - - return $parser; - } - - /** - * @inheritDoc - */ - public function execute(Arguments $args, ConsoleIo $io) - { - $filePath = $this->getPhpunitFilePath($args, $io); - $this->replaceListenersInPhpunitXmlFile($filePath, $io); - $io->success("The listener was successfully replaced in $filePath."); - } - - /** - * @param \Cake\Console\Arguments $args Arguments - * @param \Cake\Console\ConsoleIo $io ConsoleIo - * @return string - */ - public function getPhpunitFilePath(Arguments $args, ConsoleIo $io): string - { - $fileName = $args->getOption('file') ?? 'phpunit.xml.dist'; - - $plugin = $args->getOption('plugin'); - if ($plugin) { - $path = ROOT . DS . 'plugins' . DS . $plugin . DS . $fileName; - } else { - $path = ROOT . DS . $fileName; - } - - if (!file_exists($path)) { - $io->abort("The phpunit config file $path could not be found."); - } - - return $path; - } - - /** - * Replaces the listeners and injectors in $filePath - * - * @param string $filePath Path to the phpunit file - * @param \Cake\Console\ConsoleIo $io ConsoleIo - * @return void - */ - public function replaceListenersInPhpunitXmlFile(string $filePath, ConsoleIo $io): void - { - try { - $this->replaceListenerInString( - $filePath, - file_get_contents($filePath) - ); - } catch (\Exception $exception) { - $io->abort($exception->getMessage()); - } - } - - /** - * @param string $filePath Path to the phpunit file - * @param string $string Content of the file - * @return void - */ - protected function replaceListenerInString(string $filePath, string $string): void - { - $this->existsInString(\Cake\TestSuite\Fixture\FixtureInjector::class, $string, $filePath); - $this->existsInString(\Cake\TestSuite\Fixture\FixtureManager::class, $string, $filePath); - - $string = str_replace(\Cake\TestSuite\Fixture\FixtureInjector::class, FixtureInjector::class, $string); - $string = str_replace(\Cake\TestSuite\Fixture\FixtureManager::class, FixtureManager::class, $string); - - file_put_contents($filePath, $string); - } - - /** - * Ensure that a string is well found in a file - * - * @param string $search Needle - * @param string $subject Stack - * @param string $filePath Path to the file - * @return void - */ - protected function existsInString(string $search, string $subject, string $filePath): void - { - if (strpos($subject, $search) === false) { - throw new FixtureFactoryException("$search could not be found in $filePath."); - } - } -} diff --git a/src/Event/ModelEventsHandler.php b/src/Event/ModelEventsHandler.php index c6cba888..6d05c04d 100644 --- a/src/Event/ModelEventsHandler.php +++ b/src/Event/ModelEventsHandler.php @@ -16,6 +16,9 @@ use Cake\ORM\Behavior; use Cake\ORM\Table; +use CakephpFixtureFactories\Factory\EventCollector; +use ReflectionException; +use ReflectionFunction; /** * Class ModelEventsHandler @@ -27,19 +30,19 @@ class ModelEventsHandler /** * @var array */ - private $listeningBehaviors = []; + private array $listeningBehaviors = []; /** * @var array */ - private $listeningModelEvents = []; + private array $listeningModelEvents = []; /** * @var \CakephpFixtureFactories\Factory\EventCollector */ - protected $eventCompiler; + protected EventCollector $eventCompiler; - public static $ormEvents = [ + public static array $ormEvents = [ 'Model.initialize', 'Model.beforeMarshal', 'Model.afterMarshal', @@ -89,10 +92,8 @@ private function ignoreModelEvents(Table $table): void { foreach (self::$ormEvents as $ormEvent) { foreach ($table->getEventManager()->listeners($ormEvent) as $listeners) { - if (array_key_exists('callable', $listeners) && is_array($listeners['callable'])) { - foreach ($listeners['callable'] as $listener) { - $this->processListener($table, $listener, $ormEvent); - } + if (array_key_exists('callable', $listeners)) { + $this->processListener($table, $listeners['callable'], $ormEvent); } } } @@ -104,12 +105,21 @@ private function ignoreModelEvents(Table $table): void * @param string $ormEvent Event name * @return void */ - private function processListener(Table $table, $listener, string $ormEvent): void + private function processListener(Table $table, mixed $listener, string $ormEvent): void { - if ($listener instanceof Table) { - $this->processModelListener($table, $listener, $ormEvent); - } elseif ($listener instanceof Behavior) { - $this->processBehaviorListener($table, $listener, $ormEvent); + try { + $reflection = new ReflectionFunction($listener); + $obj = $reflection->getClosureThis(); + } catch (ReflectionException $e) { + // Do something? + } + + if (isset($obj)) { + if ($obj instanceof Table) { + $this->processModelListener($table, $obj, $ormEvent); + } elseif ($obj instanceof Behavior) { + $this->processBehaviorListener($table, $obj, $ormEvent); + } } else { $table->getEventManager()->off($ormEvent, $listener); } @@ -121,7 +131,7 @@ private function processListener(Table $table, $listener, string $ormEvent): voi * @param string $ormEvent Event Name * @return void */ - private function processModelListener(Table $table, $listener, string $ormEvent): void + private function processModelListener(Table $table, mixed $listener, string $ormEvent): void { if ( !in_array( @@ -139,7 +149,7 @@ private function processModelListener(Table $table, $listener, string $ormEvent) * @param string $ormEvent Event name * @return void */ - private function processBehaviorListener(Table $table, $listener, string $ormEvent): void + private function processBehaviorListener(Table $table, mixed $listener, string $ormEvent): void { foreach ($this->getListeningBehaviors() as $behavior) { if ($this->skipBehavior($table, $behavior)) { diff --git a/src/Factory/AssociationBuilder.php b/src/Factory/AssociationBuilder.php index 2979b52a..030e4a3a 100644 --- a/src/Factory/AssociationBuilder.php +++ b/src/Factory/AssociationBuilder.php @@ -23,6 +23,8 @@ use Cake\Utility\Hash; use Cake\Utility\Inflector; use CakephpFixtureFactories\Error\AssociationBuilderException; +use Exception; +use Throwable; /** * Class AssociationBuilder @@ -35,12 +37,12 @@ class AssociationBuilder getFactory as getFactoryInstance; } - private $associated = []; + private array $associated = []; /** * @var \CakephpFixtureFactories\Factory\BaseFactory */ - private $factory; + private BaseFactory $factory; /** * AssociationBuilder constructor. @@ -65,7 +67,7 @@ public function getAssociation(string $associationName): Association try { $association = $this->getTable()->getAssociation($associationName); - } catch (\Exception $e) { + } catch (Exception $e) { throw new AssociationBuilderException($e->getMessage()); } if ($this->associationIsToOne($association) || $this->associationIsToMany($association)) { @@ -146,11 +148,13 @@ public function removeAssociationForToOneFactory(string $associationName, BaseFa * Get the factory for the association * * @param string $associationName Association name - * @param scalar[]|\CakephpFixtureFactories\Factory\BaseFactory|\Cake\Datasource\EntityInterface|\Cake\Datasource\EntityInterface[] $data Injected data + * @param mixed $data Injected data * @return \CakephpFixtureFactories\Factory\BaseFactory */ - public function getAssociatedFactory(string $associationName, $data = []): BaseFactory - { + public function getAssociatedFactory( + string $associationName, + mixed $data = [] + ): BaseFactory { $associations = explode('.', $associationName); $firstAssociation = array_shift($associations); @@ -176,14 +180,14 @@ public function getAssociatedFactory(string $associationName, $data = []): BaseF * Get a factory from a table name * * @param string $modelName Model Name - * @param array $data Injected data + * @param mixed $data Injected data * @return \CakephpFixtureFactories\Factory\BaseFactory */ - public function getFactoryFromTableName(string $modelName, $data = []): BaseFactory + public function getFactoryFromTableName(string $modelName, mixed $data = []): BaseFactory { try { return $this->getFactoryInstance($modelName, $data); - } catch (\Throwable $e) { + } catch (Throwable $e) { throw new AssociationBuilderException($e->getMessage()); } } @@ -205,7 +209,7 @@ public function removeBrackets(string &$string): string * @param string $string String * @return int|null */ - public function getTimeBetweenBrackets(string $string) + public function getTimeBetweenBrackets(string $string): ?int { preg_match_all("/\[([^\]]*)\]/", $string, $matches); $res = $matches[1]; diff --git a/src/Factory/BaseFactory.php b/src/Factory/BaseFactory.php index feaa6793..db0ef638 100644 --- a/src/Factory/BaseFactory.php +++ b/src/Factory/BaseFactory.php @@ -13,18 +13,22 @@ */ namespace CakephpFixtureFactories\Factory; +use Cake\Database\ExpressionInterface; use Cake\Datasource\EntityInterface; +use Cake\Datasource\ResultSetInterface; use Cake\I18n\I18n; -use Cake\ORM\Query; +use Cake\ORM\Query\SelectQuery; use Cake\ORM\Table; use CakephpFixtureFactories\Error\FixtureFactoryException; use CakephpFixtureFactories\Error\PersistenceException; +use Closure; use Faker\Factory; use Faker\Generator; use InvalidArgumentException; +use Psr\SimpleCache\CacheInterface; +use Throwable; use function array_merge; use function is_array; -use function is_callable; /** * Class BaseFactory @@ -36,16 +40,16 @@ abstract class BaseFactory /** * @var \Faker\Generator|null */ - private static $faker; + private static ?Generator $faker = null; /** * @deprecated * @var bool */ - protected static $applyListenersAndBehaviors = false; + protected static bool $applyListenersAndBehaviors = false; /** * @var array */ - protected $marshallerOptions = [ + protected array $marshallerOptions = [ 'validate' => false, 'forceNew' => true, 'accessibleFields' => ['*' => true], @@ -53,7 +57,7 @@ abstract class BaseFactory /** * @var array */ - protected $saveOptions = [ + protected array $saveOptions = [ 'checkRules' => false, 'atomic' => false, 'checkExisting' => false, @@ -61,17 +65,17 @@ abstract class BaseFactory /** * @var array Unique fields. Uniqueness applies only to persisted entities. */ - protected $uniqueProperties = []; + protected array $uniqueProperties = []; /** * @var array Fields on which the setters should be skipped. */ - protected $skippedSetters = []; + protected array $skippedSetters = []; /** * The number of records the factory should create * * @var int */ - private $times = 1; + private int $times = 1; /** * The data compiler gathers the data from the * default template, the injection and patched data @@ -80,20 +84,20 @@ abstract class BaseFactory * * @var \CakephpFixtureFactories\Factory\DataCompiler */ - private $dataCompiler; + private DataCompiler $dataCompiler; /** * Helper to check and build data in associations * * @var \CakephpFixtureFactories\Factory\AssociationBuilder */ - private $associationBuilder; + private AssociationBuilder $associationBuilder; /** * Handles the events at the model and behavior level * for the table on which the factories will be built * * @var \CakephpFixtureFactories\Factory\EventCollector */ - private $eventCompiler; + private EventCollector $eventCompiler; /** * BaseFactory constructor. @@ -118,12 +122,14 @@ abstract protected function getRootTableRegistryName(): string; abstract protected function setDefaultTemplate(): void; /** - * @param array|callable|null|int|\Cake\Datasource\EntityInterface|string $makeParameter Injected data - * @param int $times Number of entities created + * @param mixed $makeParameter Injected data + * @param int $times Number of entities created * @return static */ - public static function make($makeParameter = [], int $times = 1): BaseFactory - { + public static function make( + mixed $makeParameter = [], + int $times = 1 + ): BaseFactory { if (is_numeric($makeParameter)) { $factory = self::makeFromNonCallable(); $times = $makeParameter; @@ -172,10 +178,10 @@ protected function initialize(): void } /** - * @param array|\Cake\Datasource\EntityInterface|\Cake\Datasource\EntityInterface[] $data Injected data + * @param \Cake\Datasource\EntityInterface|array|array<\Cake\Datasource\EntityInterface>|string $data Injected data * @return static */ - private static function makeFromNonCallable($data = []): BaseFactory + private static function makeFromNonCallable(EntityInterface|array|string $data = []): BaseFactory { $factory = new static(); $factory->getDataCompiler()->collectFromInstantiation($data); @@ -207,7 +213,7 @@ public function getFaker(): Generator try { $fakerLocale = I18n::getLocale(); $faker = Factory::create($fakerLocale); - } catch (\Throwable $e) { + } catch (Throwable $e) { $fakerLocale = Factory::DEFAULT_LOCALE; $faker = Factory::create($fakerLocale); } @@ -231,7 +237,7 @@ public function getEntity(): EntityInterface /** * Produce a set of entities from the present factory * - * @return \Cake\Datasource\EntityInterface[] + * @return array<\Cake\Datasource\EntityInterface> */ public function getEntities(): array { @@ -264,7 +270,7 @@ public function getAssociated(): array /** * Fetch entities from the data compiler. * - * @return \Cake\Datasource\EntityInterface[] + * @return array<\Cake\Datasource\EntityInterface> */ protected function toArray(): array { @@ -297,10 +303,10 @@ public function getTable(): Table } /** - * @return \Cake\Datasource\EntityInterface|iterable<\Cake\Datasource\EntityInterface>|\Cake\Datasource\ResultSetInterface + * @return \Cake\Datasource\EntityInterface|\Cake\Datasource\ResultSetInterface|iterable<\Cake\Datasource\EntityInterface> * @throws \CakephpFixtureFactories\Error\PersistenceException if the entity/entities could not be saved. */ - public function persist() + public function persist(): EntityInterface|iterable|ResultSetInterface { $this->getDataCompiler()->startPersistMode(); $entities = $this->toArray(); @@ -312,7 +318,7 @@ public function persist() } else { return $this->getTable()->saveManyOrFail($entities, $this->getSaveOptions()); } - } catch (\Throwable $exception) { + } catch (Throwable $exception) { $factory = static::class; $message = $exception->getMessage(); throw new PersistenceException("Error in Factory $factory.\n Message: $message \n"); @@ -332,10 +338,10 @@ private function getSaveOptions(): array /** * Assigns the values of $data to the $keys of the entities generated * - * @param array|\Cake\Datasource\EntityInterface $data Data to inject + * @param \Cake\Datasource\EntityInterface|array $data Data to inject * @return $this */ - public function patchData($data) + public function patchData(array|EntityInterface $data) { if ($data instanceof EntityInterface) { $data = $data->toArray(); @@ -352,7 +358,7 @@ public function patchData($data) * @param mixed $value to assign * @return $this */ - public function setField(string $field, $value) + public function setField(string $field, mixed $value) { return $this->patchData([$field => $value]); } @@ -411,11 +417,11 @@ public function setTimes(int $times): self } /** - * @param string[]|string $activeBehaviors Behaviors listened to by the factory + * @param array|string $activeBehaviors Behaviors listened to by the factory * @return self * @throws \CakephpFixtureFactories\Error\FixtureFactoryException on argument passed error */ - public function listeningToBehaviors($activeBehaviors): self + public function listeningToBehaviors(array|string $activeBehaviors): self { $activeBehaviors = (array)$activeBehaviors; if (empty($activeBehaviors)) { @@ -427,11 +433,11 @@ public function listeningToBehaviors($activeBehaviors): self } /** - * @param string[]|string $activeModelEvents Model events listened to by the factory + * @param array|string $activeModelEvents Model events listened to by the factory * @return self * @throws \CakephpFixtureFactories\Error\FixtureFactoryException on argument passed error */ - public function listeningToModelEvents($activeModelEvents): self + public function listeningToModelEvents(array|string $activeModelEvents): self { $activeModelEvents = (array)$activeModelEvents; if (empty($activeModelEvents)) { @@ -452,10 +458,10 @@ public function listeningToModelEvents($activeModelEvents): self * ] * If not set, the offset is set randomly * - * @param int|string|array $primaryKeyOffset Offset + * @param array|string|int $primaryKeyOffset Offset * @return self */ - public function setPrimaryKeyOffset($primaryKeyOffset): self + public function setPrimaryKeyOffset(int|string|array $primaryKeyOffset): self { $this->getDataCompiler()->setPrimaryKeyOffset($primaryKeyOffset); @@ -496,7 +502,7 @@ public function getUniqueProperties(): array * @param array|string|null $fields Unique fields set on the fly. * @return $this */ - public function setUniqueProperties($fields) + public function setUniqueProperties(array|string|null $fields) { $this->uniqueProperties = (array)$fields; @@ -522,10 +528,10 @@ protected function setDefaultData(callable $fn) * The data can be an array, an integer, an entity interface, a callable or a factory * * @param string $associationName Association name - * @param array|int|callable|\CakephpFixtureFactories\Factory\BaseFactory|\Cake\Datasource\EntityInterface|string $data Injected data + * @param \CakephpFixtureFactories\Factory\BaseFactory|\Cake\Datasource\EntityInterface|callable|array|string|int $data Injected data * @return $this */ - public function with(string $associationName, $data = []) + public function with(string $associationName, array|int|callable|BaseFactory|EntityInterface|string $data = []) { $this->getAssociationBuilder()->getAssociation($associationName); @@ -584,12 +590,12 @@ public function mergeAssociated(array $data) * Per default setters defined in entities are applied. * Here the user may define a list of fields for which setters should be ignored * - * @param string|string[]|mixed $skippedSetters Field or list of fields for which setters ought to be skipped + * @param mixed|array|string $skippedSetters Field or list of fields for which setters ought to be skipped * @param bool $merge Merge the first argument with the setters already skipped. False by default. * @return $this * @throws \CakephpFixtureFactories\Error\FixtureFactoryException is no string or array is passed */ - public function skipSetterFor($skippedSetters, bool $merge = false) + public function skipSetterFor(mixed $skippedSetters, bool $merge = false) { if (!is_string($skippedSetters) && !is_array($skippedSetters)) { throw new FixtureFactoryException( @@ -609,26 +615,36 @@ public function skipSetterFor($skippedSetters, bool $merge = false) * Query the factory's related table without before find. * * @param string $type the type of query to perform - * @param array $options An array that will be passed to Query::applyOptions() - * @return \Cake\ORM\Query The query builder - * @see Query::find() + * @param mixed ...$options Options passed to the finder + * @return \Cake\ORM\Query\SelectQuery The query builder + * @see \Cake\ORM\Query\SelectQuery::find() */ - public static function find(string $type = 'all', array $options = []): Query + public static function find(string $type = 'all', mixed ...$options): SelectQuery { - return (new static())->getTable()->find($type, $options); + return (new static())->getTable()->find($type, ...$options); } /** * Get from primary key the factory's related table entries, without before find. * * @param mixed $primaryKey primary key value to find - * @param array $options options accepted by `Table::find()` + * @param array|string $finder The finder to use. Passing an options array is deprecated. + * @param \Psr\SimpleCache\CacheInterface|string|null $cache The cache config to use. + * Defaults to `null`, i.e. no caching. + * @param \Closure|string|null $cacheKey The cache key to use. If not provided + * one will be autogenerated if `$cache` is not null. + * @param mixed ...$args Arguments that query options or finder specific parameters. * @return \Cake\Datasource\EntityInterface * @see Table::get() */ - public static function get($primaryKey, array $options = []): EntityInterface - { - return (new static())->getTable()->get($primaryKey, $options); + public static function get( + mixed $primaryKey, + array|string $finder = 'all', + CacheInterface|string|null $cache = null, + Closure|string|null $cacheKey = null, + mixed ...$args + ): EntityInterface { + return (new static())->getTable()->get($primaryKey, $finder, $cache, $cacheKey, ...$args); } /** @@ -649,8 +665,9 @@ public static function count(): int * @return \Cake\Datasource\EntityInterface|array The first result from the ResultSet. * @throws \Cake\Datasource\Exception\RecordNotFoundException When there is no first record. */ - public static function firstOrFail($conditions = null) - { + public static function firstOrFail( + ExpressionInterface|Closure|array|string|null $conditions = null + ): EntityInterface|array { return self::find()->where($conditions)->firstOrFail(); } } diff --git a/src/Factory/DataCompiler.php b/src/Factory/DataCompiler.php index aa24b07c..4a8e6c14 100644 --- a/src/Factory/DataCompiler.php +++ b/src/Factory/DataCompiler.php @@ -16,12 +16,14 @@ use Cake\Database\Driver\Postgres; use Cake\Datasource\EntityInterface; +use Cake\ORM\Association; use Cake\ORM\Association\BelongsTo; use Cake\ORM\Association\HasOne; use Cake\Utility\Hash; use Cake\Utility\Inflector; use CakephpFixtureFactories\Error\FixtureFactoryException; use CakephpFixtureFactories\Error\PersistenceException; +use Closure; use InvalidArgumentException; /** @@ -34,29 +36,29 @@ class DataCompiler public const MODIFIED_UNIQUE_PROPERTIES = '___data_compiler__modified_unique_properties'; public const IS_ASSOCIATED = '___data_compiler__is_associated'; - private $dataFromDefaultTemplate = []; + private array|Closure $dataFromDefaultTemplate = []; /** - * @var array|\Cake\Datasource\EntityInterface|\Cake\Datasource\EntityInterface[]|callable + * @var \Cake\Datasource\EntityInterface|callable|array|array<\Cake\Datasource\EntityInterface> */ private $dataFromInstantiation = []; - private $dataFromPatch = []; - private $dataFromAssociations = []; - private $dataFromDefaultAssociations = []; - private $primaryKeyOffset = []; - private $enforcedFields = []; - private $skippedSetters = []; + private array $dataFromPatch = []; + private array $dataFromAssociations = []; + private array $dataFromDefaultAssociations = []; + private ?array $primaryKeyOffset = []; + private array $enforcedFields = []; + private array $skippedSetters = []; - private static $inPersistMode = false; + private static bool $inPersistMode = false; /** * @var \CakephpFixtureFactories\Factory\BaseFactory */ - private $factory; + private BaseFactory $factory; /** * @var bool */ - private $setPrimaryKey = true; + private bool $setPrimaryKey = true; /** * DataCompiler constructor. @@ -71,10 +73,10 @@ public function __construct(BaseFactory $factory) /** * Data passed in the instantiation by array * - * @param array|\Cake\Datasource\EntityInterface|\Cake\Datasource\EntityInterface[]|string $data Injected data. + * @param \Cake\Datasource\EntityInterface|array|array<\Cake\Datasource\EntityInterface>|string $data Injected data. * @return void */ - public function collectFromInstantiation($data): void + public function collectFromInstantiation(EntityInterface|array|string $data): void { $this->dataFromInstantiation = $data; } @@ -156,9 +158,9 @@ public function dropAssociation(string $associationName): void /** * Populate the factored entity * - * @return \Cake\Datasource\EntityInterface|\Cake\Datasource\EntityInterface[] + * @return \Cake\Datasource\EntityInterface|array<\Cake\Datasource\EntityInterface> */ - public function getCompiledTemplateData() + public function getCompiledTemplateData(): EntityInterface|array { $setPrimaryKey = $this->isInPersistMode(); @@ -184,12 +186,14 @@ public function getCompiledTemplateData() } /** - * @param array|callable|\Cake\Datasource\EntityInterface|string $injectedData Data from the injection. + * @param \Cake\Datasource\EntityInterface|callable|array|string $injectedData Data from the injection. * @param bool $setPrimaryKey Set the primary key if this entity is alone or the first of an array. * @return \Cake\Datasource\EntityInterface */ - public function compileEntity($injectedData = [], bool $setPrimaryKey = false): EntityInterface - { + public function compileEntity( + array|callable|EntityInterface|string $injectedData = [], + bool $setPrimaryKey = false + ): EntityInterface { if (is_string($injectedData)) { $injectedData = $this->setDisplayFieldToInjectedString($injectedData); } @@ -273,7 +277,7 @@ private function castArrayNotation(EntityInterface $entity, array $data): array * should be assigned to the display field of the table. * * @param string $data data injected - * @return string[] + * @return array * @throws \CakephpFixtureFactories\Error\FixtureFactoryException if the display field of the factory's table is not a string */ private function setDisplayFieldToInjectedString(string $data): array @@ -335,10 +339,10 @@ private function getEntityFromDefaultTemplate(): EntityInterface * Merge with the data injected during the instantiation of the Factory * * @param \Cake\Datasource\EntityInterface $entity Entity to manipulate. - * @param array|callable|\Cake\Datasource\EntityInterface $data Data from the instantiation. + * @param \Cake\Datasource\EntityInterface|callable|array $data Data from the instantiation. * @return self */ - private function mergeWithInjectedData(EntityInterface $entity, $data): self + private function mergeWithInjectedData(EntityInterface $entity, array|callable|EntityInterface $data): self { if (is_callable($data)) { $data = $data( @@ -449,7 +453,7 @@ private function mergeWithToMany(EntityInterface $entity, string $associationNam /** * @param \CakephpFixtureFactories\Factory\BaseFactory $factory Factory - * @return \Cake\Datasource\EntityInterface[] + * @return array<\Cake\Datasource\EntityInterface> */ private function getManyEntities(BaseFactory $factory): array { @@ -499,9 +503,9 @@ public function getMarshallerAssociationName(string $associationName): string /** * @param string $propertyName Property - * @return bool|\Cake\ORM\Association + * @return \Cake\ORM\Association|bool */ - public function getAssociationByPropertyName(string $propertyName) + public function getAssociationByPropertyName(string $propertyName): bool|Association { try { return $this->getFactory()->getTable()->getAssociation(Inflector::camelize($propertyName)); @@ -569,9 +573,9 @@ public function generateArrayOfRandomPrimaryKeys(): array * https://github.com/fzaninotto/Faker/blob/master/src/Faker/ORM/CakePHP/ColumnTypeGuesser.php * * @param string $columnType Column type - * @return int|string + * @return string|int */ - public function generateRandomPrimaryKey(string $columnType) + public function generateRandomPrimaryKey(string $columnType): int|string { switch ($columnType) { case 'uuid': @@ -605,10 +609,10 @@ public function getFactory(): BaseFactory } /** - * @param int|string|array $primaryKeyOffset Name of the primary key + * @param mixed $primaryKeyOffset Name of the primary key * @return void */ - public function setPrimaryKeyOffset($primaryKeyOffset): void + public function setPrimaryKeyOffset(mixed $primaryKeyOffset): void { if (is_int($primaryKeyOffset) || is_string($primaryKeyOffset)) { $primaryKey = $this->getFactory()->getTable()->getPrimaryKey(); @@ -719,7 +723,7 @@ public function getEnforcedFields(): array * @param array $fields Fields to be marked as enforced. * @return void */ - public function addEnforcedFields(array $fields) + public function addEnforcedFields(array $fields): void { $this->enforcedFields = array_merge( array_keys($fields), diff --git a/src/Factory/EventCollector.php b/src/Factory/EventCollector.php index 79fc529a..3af2e34e 100644 --- a/src/Factory/EventCollector.php +++ b/src/Factory/EventCollector.php @@ -17,6 +17,7 @@ use Cake\Core\Configure; use Cake\ORM\Table; use CakephpFixtureFactories\ORM\FactoryTableRegistry; +use RuntimeException; /** * Class EventCollector @@ -31,27 +32,27 @@ class EventCollector /** * @var \Cake\ORM\Table|null */ - private $table; + private ?Table $table = null; /** * @var array */ - private $listeningBehaviors = []; + private array $listeningBehaviors = []; /** * @var array */ - private $listeningModelEvents = []; + private array $listeningModelEvents = []; /** * @var array */ - private $defaultListeningBehaviors = []; + private array $defaultListeningBehaviors = []; /** * @var string */ - private $rootTableRegistryName; + private string $rootTableRegistryName; /** * EventCollector constructor. @@ -83,7 +84,7 @@ public function getTable(): Table try { $table = FactoryTableRegistry::getTableLocator()->get($this->rootTableRegistryName, $options); - } catch (\RuntimeException $exception) { + } catch (RuntimeException $exception) { FactoryTableRegistry::getTableLocator()->remove($this->rootTableRegistryName); $table = FactoryTableRegistry::getTableLocator()->get($this->rootTableRegistryName, $options); } diff --git a/src/Factory/FactoryAwareTrait.php b/src/Factory/FactoryAwareTrait.php index cdcf9096..681d280c 100644 --- a/src/Factory/FactoryAwareTrait.php +++ b/src/Factory/FactoryAwareTrait.php @@ -15,8 +15,10 @@ namespace CakephpFixtureFactories\Factory; use Cake\Core\Configure; +use Cake\Datasource\EntityInterface; use Cake\Utility\Inflector; use CakephpFixtureFactories\Error\FactoryNotFoundException; +use function Cake\Core\namespaceSplit; trait FactoryAwareTrait { @@ -25,15 +27,18 @@ trait FactoryAwareTrait * * Additionnal arguments are passed *as is* to `BaseFactory::make` * - * @param string $name Factory or model name - * @param array|callable|null|int|\Cake\Datasource\EntityInterface|string $makeParameter Injected data + * @param string $name Factory or model name + * @param \Cake\Datasource\EntityInterface|callable|array|string|int|null $makeParameter Injected data * @param int $times Number of entities created * @return \CakephpFixtureFactories\Factory\BaseFactory * @throws \CakephpFixtureFactories\Error\FactoryNotFoundException if the factory could not be found * @see \CakephpFixtureFactories\Factory\BaseFactory::make */ - public function getFactory(string $name, $makeParameter = [], int $times = 1): BaseFactory - { + public function getFactory( + string $name, + array|callable|int|EntityInterface|string|null $makeParameter = [], + int $times = 1 + ): BaseFactory { $factoryClassName = $this->getFactoryClassName($name); if (class_exists($factoryClassName)) { @@ -46,22 +51,36 @@ public function getFactory(string $name, $makeParameter = [], int $times = 1): B /** * Converts factory or model name to a fully qualified factory class name * - * @param string $name Factory or model name + * @param string $name Factory or model name * @return string Fully qualified class name */ public function getFactoryClassName(string $name): string { // phpcs:disable @[$modelName, $plugin] = array_reverse(explode('.', $name)); + // phpcs:enable return $this->getFactoryNamespace($plugin) . '\\' . $this->getFactoryNameFromModelName($modelName); } + /** + * Converts factory or model name to a simple factory class name + * + * @param string $name Factory or model name + * @return string Fully qualified class name + */ + public function getFactorySimpleClassName(string $name): string + { + [$modelName] = array_reverse(explode('.', $name)); + + return $this->getFactoryNameFromModelName($modelName); + } + /** * Returns the factory file name * - * @param string $name Name of the model or table + * @param string $name Name of the model or table * @return string [description] */ public function getFactoryFileName(string $name): string @@ -96,11 +115,10 @@ public function getFactoryNamespace(?string $plugin = null): string if (Configure::check('FixtureFactories.testFixtureNamespace')) { return Configure::read('FixtureFactories.testFixtureNamespace'); } else { - return ( - $plugin ? - str_replace('/', '\\', $plugin) : - Configure::read('App.namespace', 'App') - ) . '\Test\Factory'; + return ($plugin ? str_replace('/', '\\', $plugin) : Configure::read( + 'App.namespace', + 'App' + )) . '\Test\Factory'; } } } diff --git a/src/Factory/UniquenessJanitor.php b/src/Factory/UniquenessJanitor.php index f5d0916b..e09831bd 100644 --- a/src/Factory/UniquenessJanitor.php +++ b/src/Factory/UniquenessJanitor.php @@ -29,9 +29,9 @@ class UniquenessJanitor * in order to warn the user that she is about to create duplicates. * * @param \CakephpFixtureFactories\Factory\BaseFactory $factory Factory on which the entity will be built. - * @param \Cake\Datasource\EntityInterface[] $entities Array of data meant to be patched into entities. + * @param array<\Cake\Datasource\EntityInterface> $entities Array of data meant to be patched into entities. * @param bool $isStrict Throw an exception if unique fields in $entities collide. - * @return \Cake\Datasource\EntityInterface[] + * @return array<\Cake\Datasource\EntityInterface> * @throws \CakephpFixtureFactories\Error\UniquenessException */ public static function sanitizeEntityArray(BaseFactory $factory, array $entities, bool $isStrict = true): array diff --git a/src/ORM/FactoryTableBeforeSave.php b/src/ORM/FactoryTableBeforeSave.php index 66b1e16a..e05eb607 100644 --- a/src/ORM/FactoryTableBeforeSave.php +++ b/src/ORM/FactoryTableBeforeSave.php @@ -28,16 +28,16 @@ final class FactoryTableBeforeSave /** * @var \Cake\ORM\Table */ - protected $table; + protected Table $table; /** * @var \Cake\Datasource\EntityInterface */ - protected $entity; + protected EntityInterface $entity; /** - * @param \Cake\ORM\Table $table Table on which the beforeFind actions are taken. - * @param \Cake\Datasource\EntityInterface $entity Entity concerned by the saving. + * @param \Cake\ORM\Table $table Table on which the beforeFind actions are taken. + * @param \Cake\Datasource\EntityInterface $entity Entity concerned by the saving. */ public function __construct(Table $table, EntityInterface $entity) { @@ -46,8 +46,8 @@ public function __construct(Table $table, EntityInterface $entity) } /** - * @param \Cake\ORM\Table $table Table on which the beforeFind actions are taken. - * @param \Cake\Datasource\EntityInterface $entity Entity concerned by the saving. + * @param \Cake\ORM\Table $table Table on which the beforeFind actions are taken. + * @param \Cake\Datasource\EntityInterface $entity Entity concerned by the saving. * @return void */ public static function handle(Table $table, EntityInterface $entity): void @@ -102,7 +102,7 @@ public function getIsAssociated(): bool /** * @return void */ - public function unsetEntityTemporaryProperties() + public function unsetEntityTemporaryProperties(): void { $this->getEntity()->unset(DataCompiler::MODIFIED_UNIQUE_PROPERTIES); $this->getEntity()->unset(DataCompiler::IS_ASSOCIATED); @@ -112,7 +112,7 @@ public function unsetEntityTemporaryProperties() * @param array $conditions Conditions that a duplicate should meet * @return array|null */ - public function findDuplicate(array $conditions) + public function findDuplicate(array $conditions): ?array { /** @var array|null $duplicate */ $duplicate = $this->getTable() diff --git a/src/ORM/FactoryTableLocator.php b/src/ORM/FactoryTableLocator.php index 0e5d8912..0b92b381 100644 --- a/src/ORM/FactoryTableLocator.php +++ b/src/ORM/FactoryTableLocator.php @@ -44,7 +44,7 @@ protected function _create(array $options): Table $behaviors ); - $table->getEventManager()->on('Model.beforeSave', function ($event, $entity, $options) use ($table) { + $table->getEventManager()->on('Model.beforeSave', function ($event, $entity, $options) use ($table): void { FactoryTableBeforeSave::handle($table, $entity); }); diff --git a/src/ORM/FactoryTableRegistry.php b/src/ORM/FactoryTableRegistry.php index e93d4491..cb549ccb 100644 --- a/src/ORM/FactoryTableRegistry.php +++ b/src/ORM/FactoryTableRegistry.php @@ -38,12 +38,12 @@ class FactoryTableRegistry extends TableRegistry * * @var string */ - protected static $_defaultLocatorClass = FactoryTableLocator::class; + protected static string $_defaultLocatorClass = FactoryTableLocator::class; /** * @var \CakephpFixtureFactories\ORM\FactoryTableLocator|null */ - protected static $_locator; + protected static ?FactoryTableLocator $_locator = null; /** * Returns a singleton instance of LocatorInterface implementation. diff --git a/src/Plugin.php b/src/Plugin.php index 009c1c16..4a8683d0 100644 --- a/src/Plugin.php +++ b/src/Plugin.php @@ -23,14 +23,14 @@ class Plugin extends BasePlugin /** * Plugin name. * - * @var string + * @var string|null */ - protected $name = 'CakephpFixtureFactories'; + protected ?string $name = 'CakephpFixtureFactories'; /** * Don't try to load routes. * * @var bool */ - protected $routesEnabled = false; + protected bool $routesEnabled = false; } diff --git a/src/Scenario/FixtureScenarioInterface.php b/src/Scenario/FixtureScenarioInterface.php index 1fcf5dc3..b1cbfffc 100644 --- a/src/Scenario/FixtureScenarioInterface.php +++ b/src/Scenario/FixtureScenarioInterface.php @@ -22,5 +22,5 @@ interface FixtureScenarioInterface * @param mixed ...$args Arguments passed to the scenario. * @return mixed|void */ - public function load(...$args); + public function load(mixed ...$args): mixed; } diff --git a/src/Scenario/ScenarioAwareTrait.php b/src/Scenario/ScenarioAwareTrait.php index cef61fbb..ed728354 100644 --- a/src/Scenario/ScenarioAwareTrait.php +++ b/src/Scenario/ScenarioAwareTrait.php @@ -16,6 +16,8 @@ use CakephpFixtureFactories\Error\FixtureScenarioException; use CakephpFixtureFactories\Factory\FactoryAwareTrait; +use Exception; +use Throwable; trait ScenarioAwareTrait { @@ -29,7 +31,7 @@ trait ScenarioAwareTrait * @return mixed * @throws \CakephpFixtureFactories\Error\FixtureScenarioException if the scenario could not be found. */ - public function loadFixtureScenario(string $scenario, ...$args) + public function loadFixtureScenario(string $scenario, mixed ...$args): mixed { if (!class_exists($scenario)) { // phpcs:disable @@ -45,9 +47,9 @@ public function loadFixtureScenario(string $scenario, ...$args) if ($scenarioClass instanceof FixtureScenarioInterface) { return $scenarioClass->load(...$args); } else { - throw new \Exception("{$scenario} must implement " . FixtureScenarioInterface::class); + throw new Exception("{$scenario} must implement " . FixtureScenarioInterface::class); } - } catch (\Throwable $e) { + } catch (Throwable $e) { throw new FixtureScenarioException($e->getMessage()); } } diff --git a/templates/bake/fixture_factory.twig b/templates/bake/fixture_factory.twig index 62c5f724..38e2b7f9 100644 --- a/templates/bake/fixture_factory.twig +++ b/templates/bake/fixture_factory.twig @@ -5,6 +5,11 @@ namespace {{ namespace }}; use CakephpFixtureFactories\Factory\BaseFactory as CakephpBaseFactory; use Faker\Generator; +{% if useStatements %} +{% for useStatement in useStatements %} +use {{ useStatement }}; +{% endfor %} +{% endif %} /** * {{ factory }} @@ -42,7 +47,7 @@ class {{ factory }} extends CakephpBaseFactory ]; }); } -{% for association, associationFactory in toOne %} +{% for association, associationData in toOne %} /** * @param array|callable|null|int|\Cake\Datasource\EntityInterface|string $parameter @@ -52,11 +57,11 @@ class {{ factory }} extends CakephpBaseFactory { return $this->with( '{{ association }}', - \{{ associationFactory }}::make($parameter) + {{ associationData.className }}::make($parameter) ); } {% endfor %} -{% for association, associationFactory in oneToMany %} +{% for association, associationData in oneToMany %} /** * @param array|callable|null|int|\Cake\Datasource\EntityInterface|string $parameter @@ -67,11 +72,11 @@ class {{ factory }} extends CakephpBaseFactory { return $this->with( '{{ association }}', - \{{ associationFactory }}::make($parameter, $n) + {{ associationData.className }}::make($parameter, $n) ); } {% endfor %} -{% for association, associationFactory in manyToMany %} +{% for association, associationData in manyToMany %} /** * @param array|callable|null|int|\Cake\Datasource\EntityInterface|string $parameter @@ -82,7 +87,7 @@ class {{ factory }} extends CakephpBaseFactory { return $this->with( '{{ association }}', - \{{ associationFactory }}::make($parameter, $n)->without('{{ modelName }}') + {{ associationData.className }}::make($parameter, $n)->without('{{ modelName }}') ); } {% endfor %} diff --git a/tests/Factory/AuthorFactory.php b/tests/Factory/AuthorFactory.php index 491d9e76..803ed395 100644 --- a/tests/Factory/AuthorFactory.php +++ b/tests/Factory/AuthorFactory.php @@ -31,7 +31,7 @@ class AuthorFactory extends BaseFactory 'subField2' => 'subFieldValue2', ]; - protected $skippedSetters = [ + protected array $skippedSetters = [ 'field_with_setter_1', ]; diff --git a/tests/Factory/CityFactory.php b/tests/Factory/CityFactory.php index 43865f32..be6cc15e 100644 --- a/tests/Factory/CityFactory.php +++ b/tests/Factory/CityFactory.php @@ -26,7 +26,7 @@ */ class CityFactory extends BaseFactory { - protected $uniqueProperties = [ + protected array $uniqueProperties = [ 'virtual_unique_stamp', ]; diff --git a/tests/Factory/CountryFactory.php b/tests/Factory/CountryFactory.php index fbfadb12..42e9c84e 100644 --- a/tests/Factory/CountryFactory.php +++ b/tests/Factory/CountryFactory.php @@ -26,7 +26,7 @@ */ class CountryFactory extends BaseFactory { - protected $uniqueProperties = [ + protected array $uniqueProperties = [ 'unique_stamp', ]; diff --git a/tests/Fixture/ArticlesFixture.php b/tests/Fixture/ArticlesFixture.php index d16e1f23..c5b9144f 100644 --- a/tests/Fixture/ArticlesFixture.php +++ b/tests/Fixture/ArticlesFixture.php @@ -17,18 +17,6 @@ class ArticlesFixture extends TestFixture { - public $fields = [ - 'id' => ['type' => 'integer'], - 'title' => ['type' => 'string', 'length' => 255, 'null' => false], - 'body' => 'text', - 'published' => ['type' => 'integer', 'default' => '0', 'null' => false], - 'created' => 'datetime', - 'modified' => 'datetime', - '_constraints' => [ - 'primary' => ['type' => 'primary', 'columns' => ['id']], - ], - ]; - public function init(): void { $this->records = [ diff --git a/tests/Scenario/NAustralianAuthorsScenario.php b/tests/Scenario/NAustralianAuthorsScenario.php index 622ab878..6592b836 100644 --- a/tests/Scenario/NAustralianAuthorsScenario.php +++ b/tests/Scenario/NAustralianAuthorsScenario.php @@ -26,7 +26,7 @@ class NAustralianAuthorsScenario implements FixtureScenarioInterface * @param mixed $args the number of authors * @return Author|Author[] */ - public function load(...$args) + public function load(...$args): mixed { $n = $args[0]; return AuthorFactory::make($n)->fromCountry(self::COUNTRY_NAME)->persist(); diff --git a/tests/Scenario/SubFolder/SubFolderScenario.php b/tests/Scenario/SubFolder/SubFolderScenario.php index 97dc9387..d3804095 100644 --- a/tests/Scenario/SubFolder/SubFolderScenario.php +++ b/tests/Scenario/SubFolder/SubFolderScenario.php @@ -23,7 +23,8 @@ class SubFolderScenario implements FixtureScenarioInterface * * @inheritDoc */ - public function load(...$args) + public function load(...$args): mixed { + return null; } } diff --git a/tests/Scenario/TenAustralianAuthorsScenario.php b/tests/Scenario/TenAustralianAuthorsScenario.php index e92bab4b..8575afe5 100644 --- a/tests/Scenario/TenAustralianAuthorsScenario.php +++ b/tests/Scenario/TenAustralianAuthorsScenario.php @@ -20,7 +20,7 @@ class TenAustralianAuthorsScenario implements FixtureScenarioInterface { use ScenarioAwareTrait; - public function load(...$args) + public function load(...$args): mixed { return $this->loadFixtureScenario(NAustralianAuthorsScenario::class, 10); } diff --git a/tests/TestApp/config/Migrations/20200208100000_initial_migration.php b/tests/TestApp/config/Migrations/20200208100000_initial_migration.php index 5f76db43..5f887774 100644 --- a/tests/TestApp/config/Migrations/20200208100000_initial_migration.php +++ b/tests/TestApp/config/Migrations/20200208100000_initial_migration.php @@ -16,13 +16,12 @@ class InitialMigration extends AbstractMigration { - public $autoId = false; - public function up() { - $this->table('authors') + $this->table('authors', ['id' => false]) ->addColumn('id', 'integer', [ 'autoIncrement' => true, + 'identity' => true, 'limit' => 11, 'generated' => \Phinx\Db\Adapter\PostgresAdapter::GENERATED_BY_DEFAULT, ]) @@ -60,14 +59,13 @@ public function up() 'default' => null, 'null' => true, ]) - ->addIndex('address_id') - ->addIndex('business_address_id') ->addTimestamps('created', 'modified') ->create(); - $this->table('articles') + $this->table('articles', ['id' => false]) ->addColumn('id', 'integer', [ 'autoIncrement' => true, + 'identity' => true, 'limit' => 11, 'generated' => \Phinx\Db\Adapter\PostgresAdapter::GENERATED_BY_DEFAULT, ]) @@ -92,9 +90,10 @@ public function up() ->addTimestamps('created', 'modified') ->create(); - $this->table('articles_authors') + $this->table('articles_authors', ['id' => false]) ->addColumn('id', 'integer', [ 'autoIncrement' => true, + 'identity' => true, 'limit' => 11, 'generated' => \Phinx\Db\Adapter\PostgresAdapter::GENERATED_BY_DEFAULT, ]) @@ -107,17 +106,12 @@ public function up() 'limit' => 11, 'null' => false, ]) - ->addIndex([ - 'author_id', - ]) - ->addIndex([ - 'article_id', - ]) ->create(); - $this->table('addresses') + $this->table('addresses', ['id' => false]) ->addColumn('id', 'integer', [ 'autoIncrement' => true, + 'identity' => true, 'limit' => 11, 'generated' => \Phinx\Db\Adapter\PostgresAdapter::GENERATED_BY_DEFAULT, ]) @@ -134,9 +128,10 @@ public function up() ->addTimestamps('created', 'modified') ->create(); - $this->table('cities') + $this->table('cities', ['id' => false]) ->addColumn('id', 'integer', [ 'autoIncrement' => true, + 'identity' => true, 'limit' => 11, 'generated' => \Phinx\Db\Adapter\PostgresAdapter::GENERATED_BY_DEFAULT, ]) @@ -153,7 +148,6 @@ public function up() 'limit' => 11, 'null' => false, ]) - ->addIndex('country_id') // These fields should not be set by the DB by default // They are used to test that the TimeStampBehavior is // correctly applied by default. @@ -161,9 +155,10 @@ public function up() ->addColumn('modified', 'timestamp', ['null' => true]) ->create(); - $this->table('countries') + $this->table('countries', ['id' => false]) ->addColumn('id', 'integer', [ 'autoIncrement' => true, + 'identity' => true, 'limit' => 11, 'generated' => \Phinx\Db\Adapter\PostgresAdapter::GENERATED_BY_DEFAULT, ]) diff --git a/tests/TestApp/config/Migrations/20211022100000_table_without_model_migration.php b/tests/TestApp/config/Migrations/20211022100000_table_without_model_migration.php index 776ba0db..99c02e83 100644 --- a/tests/TestApp/config/Migrations/20211022100000_table_without_model_migration.php +++ b/tests/TestApp/config/Migrations/20211022100000_table_without_model_migration.php @@ -16,11 +16,9 @@ class TableWithoutModelMigration extends AbstractMigration { - public $autoId = false; - public function up() { - $this->table('table_without_model') + $this->table('table_without_model', ['id' => false]) ->addColumn('id', 'integer', [ 'autoIncrement' => true, 'limit' => 11, diff --git a/tests/TestApp/plugins/TestPlugin/config/Migrations/20200513155719_CreateCustomers.php b/tests/TestApp/plugins/TestPlugin/config/Migrations/20200513155719_CreateCustomers.php index 83a80605..bea670cf 100644 --- a/tests/TestApp/plugins/TestPlugin/config/Migrations/20200513155719_CreateCustomers.php +++ b/tests/TestApp/plugins/TestPlugin/config/Migrations/20200513155719_CreateCustomers.php @@ -16,8 +16,6 @@ class CreateCustomers extends AbstractMigration { - public $autoId = false; - /** * Change Method. * @@ -28,7 +26,7 @@ class CreateCustomers extends AbstractMigration */ public function up() { - $this->table('customers') + $this->table('customers', ['id' => false]) ->addColumn('id', 'integer', [ 'autoIncrement' => true, 'limit' => 11, diff --git a/tests/TestApp/plugins/TestPlugin/config/Migrations/20200513155720_CreateBills.php b/tests/TestApp/plugins/TestPlugin/config/Migrations/20200513155720_CreateBills.php index d5de30f9..825688ea 100644 --- a/tests/TestApp/plugins/TestPlugin/config/Migrations/20200513155720_CreateBills.php +++ b/tests/TestApp/plugins/TestPlugin/config/Migrations/20200513155720_CreateBills.php @@ -16,8 +16,6 @@ class CreateBills extends AbstractMigration { - public $autoId = false; - /** * Change Method. * @@ -28,7 +26,7 @@ class CreateBills extends AbstractMigration */ public function up() { - $this->table('bills') + $this->table('bills', ['id' => false]) ->addColumn('id', 'integer', [ 'autoIncrement' => true, 'limit' => 11, diff --git a/tests/TestApp/plugins/TestPlugin/src/Model/Entity/Bill.php b/tests/TestApp/plugins/TestPlugin/src/Model/Entity/Bill.php index 8162bf10..e2387157 100644 --- a/tests/TestApp/plugins/TestPlugin/src/Model/Entity/Bill.php +++ b/tests/TestApp/plugins/TestPlugin/src/Model/Entity/Bill.php @@ -31,7 +31,7 @@ */ class Bill extends BaseEntity { - protected $_accessible = [ + protected array $_accessible = [ 'customer_id' => true, 'article_id' => true, 'amount' => true, diff --git a/tests/TestApp/src/Model/Behavior/SluggableBehavior.php b/tests/TestApp/src/Model/Behavior/SluggableBehavior.php index 45024761..2285968e 100644 --- a/tests/TestApp/src/Model/Behavior/SluggableBehavior.php +++ b/tests/TestApp/src/Model/Behavior/SluggableBehavior.php @@ -21,7 +21,7 @@ class SluggableBehavior extends Behavior { - protected $_defaultConfig = [ + protected array $_defaultConfig = [ 'field' => 'title', 'slug' => 'slug', 'replacement' => '-', diff --git a/tests/TestApp/src/Model/Entity/Address.php b/tests/TestApp/src/Model/Entity/Address.php index 9e139693..573fa01b 100644 --- a/tests/TestApp/src/Model/Entity/Address.php +++ b/tests/TestApp/src/Model/Entity/Address.php @@ -22,7 +22,7 @@ class Address extends Entity /** * @inheritdoc */ - protected $_accessible = [ + protected array $_accessible = [ 'street' => true, 'city_id' => true, 'created' => true, diff --git a/tests/TestApp/src/Model/Entity/Article.php b/tests/TestApp/src/Model/Entity/Article.php index e2b028cf..2bbf739e 100644 --- a/tests/TestApp/src/Model/Entity/Article.php +++ b/tests/TestApp/src/Model/Entity/Article.php @@ -26,7 +26,7 @@ class Article extends Entity /** * @inheritdoc */ - protected $_accessible = [ + protected array $_accessible = [ 'title' => true, 'body' => true, 'published' => true, @@ -36,7 +36,7 @@ class Article extends Entity 'authors' => true, ]; - protected $_hidden = [ + protected array $_hidden = [ self::HIDDEN_PARAGRAPH_PROPERTY_NAME, ]; } diff --git a/tests/TestApp/src/Model/Entity/Author.php b/tests/TestApp/src/Model/Entity/Author.php index 13a0effe..15748300 100644 --- a/tests/TestApp/src/Model/Entity/Author.php +++ b/tests/TestApp/src/Model/Entity/Author.php @@ -28,7 +28,7 @@ class Author extends Entity /** * @inheritdoc */ - protected $_accessible = ['*' => false]; + protected array $_accessible = ['*' => false]; protected function _setFieldWithSetter_1(string $value): string { diff --git a/tests/TestApp/src/Model/Entity/City.php b/tests/TestApp/src/Model/Entity/City.php index bfe8cb69..9073050d 100644 --- a/tests/TestApp/src/Model/Entity/City.php +++ b/tests/TestApp/src/Model/Entity/City.php @@ -23,7 +23,7 @@ class City extends Entity /** * @inheritdoc */ - protected $_accessible = [ + protected array $_accessible = [ 'name' => true, 'country_id' => true, 'created' => true, diff --git a/tests/TestApp/src/Model/Entity/Country.php b/tests/TestApp/src/Model/Entity/Country.php index f09e5302..837edfe8 100644 --- a/tests/TestApp/src/Model/Entity/Country.php +++ b/tests/TestApp/src/Model/Entity/Country.php @@ -23,7 +23,7 @@ class Country extends Entity /** * @inheritdoc */ - protected $_accessible = [ + protected array $_accessible = [ 'name' => true, 'created' => true, 'modified' => true, diff --git a/tests/TestApp/src/Model/Table/ArticlesTable.php b/tests/TestApp/src/Model/Table/ArticlesTable.php index 07cd93d7..1701c3b9 100644 --- a/tests/TestApp/src/Model/Table/ArticlesTable.php +++ b/tests/TestApp/src/Model/Table/ArticlesTable.php @@ -13,7 +13,7 @@ */ namespace TestApp\Model\Table; -use Cake\ORM\Query; +use Cake\ORM\Query\SelectQuery; use Cake\ORM\Table; class ArticlesTable extends Table @@ -42,7 +42,7 @@ public function initialize(array $config): void parent::initialize($config); } - public function findPublished(Query $query, array $options): Query + public function findPublished(SelectQuery $query): SelectQuery { $query->where([ $this->aliasField('published') => 1 diff --git a/tests/TestCase/Command/BakeFixtureFactoryCommandTest.php b/tests/TestCase/Command/BakeFixtureFactoryCommandTest.php index 207c093d..09a900e7 100644 --- a/tests/TestCase/Command/BakeFixtureFactoryCommandTest.php +++ b/tests/TestCase/Command/BakeFixtureFactoryCommandTest.php @@ -15,6 +15,7 @@ use Cake\Core\Configure; use Cake\Console\Arguments; +use CakephpTestSuiteLight\Fixture\TruncateDirtyTables; use TestApp\Model\Entity\City; use TestApp\Model\Entity\Author; use TestApp\Model\Entity\Address; @@ -39,6 +40,8 @@ */ class BakeFixtureFactoryCommandTest extends TestCaseWithFixtureBaking { + use TruncateDirtyTables; + /** * @var string */ @@ -94,12 +97,24 @@ public function testHandleAssociationsWithArticles() $expected = [ 'toOne' => [], 'oneToMany' => [ - 'Bills' => 'TestPlugin\Test\Factory\BillFactory', - 'ArticlesAuthors' => 'TestApp\Test\Factory\ArticlesAuthorFactory' + 'Bills' => [ + 'fqcn' => 'TestPlugin\Test\Factory\BillFactory', + 'className' => 'BillFactory' + ], + 'ArticlesAuthors' => [ + 'fqcn' => 'TestApp\Test\Factory\ArticlesAuthorFactory', + 'className' => 'ArticlesAuthorFactory' + ], ], 'manyToMany' => [ - 'Authors' => 'TestApp\Test\Factory\AuthorFactory', - 'ExclusivePremiumAuthors' => 'TestApp\Test\Factory\PremiumAuthorFactory', + 'Authors' => [ + 'fqcn' => 'TestApp\Test\Factory\AuthorFactory', + 'className' => 'AuthorFactory' + ], + 'ExclusivePremiumAuthors' => [ + 'fqcn' => 'TestApp\Test\Factory\PremiumAuthorFactory', + 'className' => 'PremiumAuthorFactory' + ], ], ]; $this->assertEquals($expected, $associations); @@ -110,11 +125,22 @@ public function testHandleAssociationsWithAuthors() $associations = $this->FactoryCommand->setTable('Authors', $this->io)->getAssociations(); $expected = [ 'toOne' => [ - 'Address' => 'TestApp\Test\Factory\AddressFactory', - 'BusinessAddress' => 'TestApp\Test\Factory\AddressFactory', + 'Address' => [ + 'fqcn' => 'TestApp\Test\Factory\AddressFactory', + 'className' => 'AddressFactory' + ], + 'BusinessAddress' => [ + 'fqcn' => 'TestApp\Test\Factory\AddressFactory', + 'className' => 'AddressFactory' + ], ], 'oneToMany' => [], - 'manyToMany' => ['Articles' => 'TestApp\Test\Factory\ArticleFactory'], + 'manyToMany' => [ + 'Articles' => [ + 'fqcn' => 'TestApp\Test\Factory\ArticleFactory', + 'className' => 'ArticleFactory' + ] + ], ]; $this->assertEquals($expected, $associations); } @@ -123,8 +149,18 @@ public function testHandleAssociationsWithAddresses() { $associations = $this->FactoryCommand->setTable('Addresses', $this->io)->getAssociations(); $expected = [ - 'toOne' => ['City' => 'TestApp\Test\Factory\CityFactory'], - 'oneToMany' => ['Authors' => 'TestApp\Test\Factory\AuthorFactory',], + 'toOne' => [ + 'City' => [ + 'fqcn' => 'TestApp\Test\Factory\CityFactory', + 'className' => 'CityFactory' + ], + ], + 'oneToMany' => [ + 'Authors' => [ + 'fqcn' => 'TestApp\Test\Factory\AuthorFactory', + 'className' => 'AuthorFactory' + ], + ], 'manyToMany' => [], ]; $this->assertEquals($expected, $associations); @@ -147,7 +183,16 @@ public function testHandleAssociationsWithBills() $associations = $this->FactoryCommand->setTable('Bills', $this->io)->getAssociations(); $expected = [ - 'toOne' => ['Article' => 'TestApp\Test\Factory\ArticleFactory', 'Customer' => 'TestPlugin\Test\Factory\CustomerFactory'], + 'toOne' => [ + 'Article' => [ + 'fqcn' => 'TestApp\Test\Factory\ArticleFactory', + 'className' => 'ArticleFactory' + ], + 'Customer' => [ + 'fqcn' => 'TestPlugin\Test\Factory\CustomerFactory', + 'className' => 'CustomerFactory' + ] + ], 'oneToMany' => [], 'manyToMany' => [], ]; @@ -274,11 +319,10 @@ public function testRunBakeAllInTestPlugin() $this->assertInstanceOf(Customer::class, $customer); } - public function dataForTestThisTableShouldBeBaked() + public static function dataForTestThisTableShouldBeBaked() { return [ ['Cities', null, true], - ['Cities', true, false], ['Cities', 'TestPlugin', false], ['Bills', null, false], ['Bills', 'TestPlugin', true], diff --git a/tests/TestCase/Command/PersistCommandTest.php b/tests/TestCase/Command/PersistCommandTest.php index fa67271f..21ca4197 100644 --- a/tests/TestCase/Command/PersistCommandTest.php +++ b/tests/TestCase/Command/PersistCommandTest.php @@ -26,9 +26,12 @@ use CakephpFixtureFactories\Test\Factory\BillFactory; use CakephpFixtureFactories\Test\Factory\CityFactory; use CakephpFixtureFactories\Test\Factory\CountryFactory; +use CakephpTestSuiteLight\Fixture\TruncateDirtyTables; class PersistCommandTest extends TestCase { + use TruncateDirtyTables; + /** * @var PersistCommand */ @@ -60,7 +63,7 @@ public function tearDown(): void unset($this->io); } - public function dataProviderForStringFactories(): array + public static function dataProviderForStringFactories(): array { return [ ['Articles'], @@ -82,7 +85,7 @@ public function testPersistOnOneFactory(string $factoryString) $this->assertSame(1, ArticleFactory::count()); } - public function dataProviderForStringPluginFactories(): array + public static function dataProviderForStringPluginFactories(): array { return [ ['TestPlugin.Bills'], diff --git a/tests/TestCase/Command/SetupCommandTest.php b/tests/TestCase/Command/SetupCommandTest.php deleted file mode 100644 index 8f086393..00000000 --- a/tests/TestCase/Command/SetupCommandTest.php +++ /dev/null @@ -1,181 +0,0 @@ -setupCommand = new SetupCommand(); - $this->io = new ConsoleIo(); - } - - public function tearDown(): void - { - unset($this->setupCommand); - unset($this->io); - parent::tearDown(); - } - - private function createTmpPhpunitFile(string $source, string $target) - { - copy( - $this->testFixturePath . $source, - $this->testFixturePath . $target - ); - } - - private function createPhpunitFile(string $source, string $target) - { - copy( - $this->testFixturePath . $source, - ROOT . DS . $target - ); - } - - private function removeTmpPhpunitFile(string $tmpFileName) - { - unlink($this->testFixturePath . $tmpFileName); - } - - private function removePhpunitFile(string $tmpFileName) - { - unlink(ROOT . DS . $tmpFileName); - } - - protected function exec(array $args = [], array $options = [], array $argNames = []) - { - $args = new Arguments($args, $options, $argNames); - $this->assertEquals(0, $this->setupCommand->execute($args, $this->io)); - } - - public function dataProviderReplaceListenersInPhpunitXmlFile() - { - return [ - ['phpunit_default.xml.dist'], - ['phpunit_minimalist.xml.dist'], - ]; - } - - /** - * @dataProvider dataProviderReplaceListenersInPhpunitXmlFile - * @param string $phpunitFile - */ - public function testReplaceListenersInPhpunitXmlFile(string $phpunitFile) - { - $cmd = new SetupCommand(); - $tmpFileName = 'foo'; - $this->createTmpPhpunitFile($phpunitFile, $tmpFileName); - $filePath = $this->testFixturePath . $tmpFileName; - $cmd->replaceListenersInPhpunitXmlFile($filePath, $this->io); - - $content = file_get_contents($filePath); - - $expected = [ - '', - '', - '', - '', - '', - '', - '', - ]; - foreach ($expected as $ex) { - $this->assertStringContainsString($ex, $content); - } - - $this->removeTmpPhpunitFile($tmpFileName); - } - - public function testReplaceListenersInPhpunitXmlFileWrongFile() - { - $this->expectException(StopException::class); - $cmd = new SetupCommand(); - $cmd->replaceListenersInPhpunitXmlFile('abc', $this->io); - } - - /** - * @dataProvider dataProviderReplaceListenersInPhpunitXmlFile - * @param string $phpunitFile - */ - public function testExecute(string $phpunitFile) - { - $tmpFileName = 'foo'; - $this->createPhpunitFile($phpunitFile, $tmpFileName); - $this->exec([], ['file' => $tmpFileName]); - $this->removePhpunitFile($tmpFileName); - } - - public function testExecuteWithWrongFile() - { - $this->expectException(StopException::class); - $this->exec([], ['file' => 'foo']); - } - - public function testExecuteWithPlugin() - { - $pluginName = 'Foo'; - $this->expectException(StopException::class); - $this->expectExceptionMessage("plugins/$pluginName/phpunit.xml.dist could not be found."); - $this->exec([], ['plugin' => $pluginName]); - } - - public function testExecuteWithFile() - { - $fileName = 'Foo'; - $fullPath = ROOT . DS . $fileName; - $this->expectException(StopException::class); - $this->expectExceptionMessage("$fullPath could not be found."); - $this->exec([], ['file' => $fileName]); - } - - public function testExecuteWithFileAndPlugin() - { - $fileName = 'Foo'; - $pluginName = 'Bar'; - $fullPath = ROOT . DS . 'plugins' . DS . $pluginName . DS . $fileName; - $this->expectException(StopException::class); - $this->expectExceptionMessage("$fullPath could not be found."); - $this->exec([], ['file' => $fileName, 'plugin' => $pluginName]); - } -} diff --git a/tests/TestCase/Factory/AssociationBuilderTest.php b/tests/TestCase/Factory/AssociationBuilderTest.php index 8b9804c3..31b91091 100644 --- a/tests/TestCase/Factory/AssociationBuilderTest.php +++ b/tests/TestCase/Factory/AssociationBuilderTest.php @@ -25,9 +25,12 @@ use CakephpFixtureFactories\Test\Factory\BillFactory; use CakephpFixtureFactories\Test\Factory\CityFactory; use CakephpFixtureFactories\Test\Factory\CountryFactory; +use CakephpTestSuiteLight\Fixture\TruncateDirtyTables; class AssociationBuilderTest extends TestCase { + use TruncateDirtyTables; + public static function setUpBeforeClass(): void { Configure::write('FixtureFactories.testFixtureNamespace', 'CakephpFixtureFactories\Test\Factory'); diff --git a/tests/TestCase/Factory/BaseFactoryArrayNotationTest.php b/tests/TestCase/Factory/BaseFactoryArrayNotationTest.php index 08857681..e6d2b064 100644 --- a/tests/TestCase/Factory/BaseFactoryArrayNotationTest.php +++ b/tests/TestCase/Factory/BaseFactoryArrayNotationTest.php @@ -19,9 +19,12 @@ use CakephpFixtureFactories\Error\FixtureFactoryException; use CakephpFixtureFactories\Test\Factory\ArticleFactory; use CakephpFixtureFactories\Test\Factory\AuthorFactory; +use CakephpTestSuiteLight\Fixture\TruncateDirtyTables; class BaseFactoryArrayNotationTest extends TestCase { + use TruncateDirtyTables; + public static function setUpBeforeClass(): void { Configure::write('FixtureFactories.testFixtureNamespace', 'CakephpFixtureFactories\Test\Factory'); diff --git a/tests/TestCase/Factory/BaseFactoryAssociationsTest.php b/tests/TestCase/Factory/BaseFactoryAssociationsTest.php index af3f35e6..c48681cf 100644 --- a/tests/TestCase/Factory/BaseFactoryAssociationsTest.php +++ b/tests/TestCase/Factory/BaseFactoryAssociationsTest.php @@ -15,7 +15,7 @@ use Cake\Core\Configure; use Cake\Database\Driver\Postgres; -use Cake\ORM\Query; +use Cake\ORM\Query\SelectQuery; use Cake\TestSuite\TestCase; use Cake\Utility\Hash; use CakephpFixtureFactories\Error\AssociationBuilderException; @@ -28,6 +28,7 @@ use CakephpFixtureFactories\Test\Factory\CountryFactory; use CakephpFixtureFactories\Test\Factory\CustomerFactory; use CakephpFixtureFactories\Test\Factory\SubDirectory\SubCityFactory; +use CakephpTestSuiteLight\Fixture\TruncateDirtyTables; use Exception; use TestApp\Model\Entity\Address; use TestApp\Model\Entity\Article; @@ -40,6 +41,8 @@ class BaseFactoryAssociationsTest extends TestCase { + use TruncateDirtyTables; + public static function setUpBeforeClass(): void { Configure::write('FixtureFactories.testFixtureNamespace', 'CakephpFixtureFactories\Test\Factory'); @@ -501,7 +504,7 @@ public function testCountryWith2CitiesEachOfThemWithADifferentSpecifiedAddressTh // Make sure that all was correctly persisted $addresses = AddressFactory::find() - ->innerJoinWith('City.Country', function (Query $q) use ($country) { + ->innerJoinWith('City.Country', function (SelectQuery $q) use ($country) { return $q->where(['Country.id' => $country->id]); }) ->orderAsc('street') diff --git a/tests/TestCase/Factory/BaseFactoryDefaultValuesTest.php b/tests/TestCase/Factory/BaseFactoryDefaultValuesTest.php index a23e5398..934e21d0 100644 --- a/tests/TestCase/Factory/BaseFactoryDefaultValuesTest.php +++ b/tests/TestCase/Factory/BaseFactoryDefaultValuesTest.php @@ -59,7 +59,7 @@ public function testChildAssociation() $article = ArticleWithFiveBillsFactory::make()->getEntity(); $this->assertInstanceOf(Author::class, $article->authors[0]); - $this->equalTo(5, count($article->bills)); + $this->assertSame(5, count($article->bills)); } /** diff --git a/tests/TestCase/Factory/BaseFactoryDisablePrimaryKeyOffsetTest.php b/tests/TestCase/Factory/BaseFactoryDisablePrimaryKeyOffsetTest.php index da29a186..8bc36c2e 100644 --- a/tests/TestCase/Factory/BaseFactoryDisablePrimaryKeyOffsetTest.php +++ b/tests/TestCase/Factory/BaseFactoryDisablePrimaryKeyOffsetTest.php @@ -18,11 +18,14 @@ use CakephpFixtureFactories\Test\Factory\BillFactory; use CakephpFixtureFactories\Test\Factory\CityFactory; use CakephpFixtureFactories\Test\Factory\CountryFactory; +use CakephpTestSuiteLight\Fixture\TruncateDirtyTables; use TestApp\Model\Entity\Country; class BaseFactoryDisablePrimaryKeyOffsetTest extends TestCase { - public function dataForTestDisablePrimaryKeyOffset() + use TruncateDirtyTables; + + public static function dataForTestDisablePrimaryKeyOffset() { return [ [rand(1, 1000000)], diff --git a/tests/TestCase/Factory/BaseFactoryHiddenPropertiesTest.php b/tests/TestCase/Factory/BaseFactoryHiddenPropertiesTest.php index 8b29e1f3..1bdbf9bc 100644 --- a/tests/TestCase/Factory/BaseFactoryHiddenPropertiesTest.php +++ b/tests/TestCase/Factory/BaseFactoryHiddenPropertiesTest.php @@ -48,7 +48,7 @@ private function assertHiddenParagraphIsVisible($articles, bool $persisted) } } - public function iterate() + public static function iterate() { return [ [1, false], diff --git a/tests/TestCase/Factory/BaseFactoryLoadAssociationsInInitializeTest.php b/tests/TestCase/Factory/BaseFactoryLoadAssociationsInInitializeTest.php index ec1b5312..6db6586a 100644 --- a/tests/TestCase/Factory/BaseFactoryLoadAssociationsInInitializeTest.php +++ b/tests/TestCase/Factory/BaseFactoryLoadAssociationsInInitializeTest.php @@ -23,12 +23,15 @@ use CakephpFixtureFactories\Test\Factory\CityFactory; use CakephpFixtureFactories\Test\Factory\CountryFactory; use CakephpFixtureFactories\Test\Factory\TableWithoutModelFactory; +use CakephpTestSuiteLight\Fixture\TruncateDirtyTables; use TestApp\Model\Entity\Address; use TestApp\Model\Entity\Country; use function count; class BaseFactoryLoadAssociationsInInitializeTest extends TestCase { + use TruncateDirtyTables; + public static function setUpBeforeClass(): void { Configure::write('FixtureFactories.testFixtureNamespace', 'CakephpFixtureFactories\Test\Factory'); @@ -118,7 +121,7 @@ public function testLoadAssociationOnTheFly_Has_One_Persist() $this->assertSame(1, CountryFactory::count()); } - public function dataForClassName(): array + public static function dataForClassName(): array { return [['TableWithoutModel'], ['table_without_model']]; } diff --git a/tests/TestCase/Factory/BaseFactoryMakeWithEntityTest.php b/tests/TestCase/Factory/BaseFactoryMakeWithEntityTest.php index 66742930..ffc2ec2b 100644 --- a/tests/TestCase/Factory/BaseFactoryMakeWithEntityTest.php +++ b/tests/TestCase/Factory/BaseFactoryMakeWithEntityTest.php @@ -20,10 +20,13 @@ use CakephpFixtureFactories\Test\Factory\AddressFactory; use CakephpFixtureFactories\Test\Factory\ArticleFactory; use CakephpFixtureFactories\Test\Factory\AuthorFactory; +use CakephpTestSuiteLight\Fixture\TruncateDirtyTables; class BaseFactoryMakeWithEntityTest extends TestCase { + use TruncateDirtyTables; + public static function setUpBeforeClass(): void { Configure::write('FixtureFactories.testFixtureNamespace', 'CakephpFixtureFactories\Test\Factory'); diff --git a/tests/TestCase/Factory/BaseFactoryPrimaryKeyOffsetTest.php b/tests/TestCase/Factory/BaseFactoryPrimaryKeyOffsetTest.php index dc58899d..99724f06 100644 --- a/tests/TestCase/Factory/BaseFactoryPrimaryKeyOffsetTest.php +++ b/tests/TestCase/Factory/BaseFactoryPrimaryKeyOffsetTest.php @@ -19,11 +19,14 @@ use CakephpFixtureFactories\Test\Factory\BillFactory; use CakephpFixtureFactories\Test\Factory\CityFactory; use CakephpFixtureFactories\Test\Factory\CountryFactory; +use CakephpTestSuiteLight\Fixture\TruncateDirtyTables; use TestApp\Model\Entity\Country; class BaseFactoryPrimaryKeyOffsetTest extends TestCase { - public function dataForTestSetPrimaryKeyOffset() + use TruncateDirtyTables; + + public static function dataForTestSetPrimaryKeyOffset() { return [ [rand(1, 1000000)], diff --git a/tests/TestCase/Factory/BaseFactoryStaticFinderTest.php b/tests/TestCase/Factory/BaseFactoryStaticFinderTest.php index 073c8550..a6043112 100644 --- a/tests/TestCase/Factory/BaseFactoryStaticFinderTest.php +++ b/tests/TestCase/Factory/BaseFactoryStaticFinderTest.php @@ -15,21 +15,25 @@ use Cake\Datasource\Exception\RecordNotFoundException; use Cake\Event\EventInterface; -use Cake\ORM\Query; +use Cake\ORM\Query\SelectQuery; use Cake\ORM\TableRegistry; use Cake\TestSuite\TestCase; use CakephpFixtureFactories\Test\Factory\ArticleFactory; +use CakephpTestSuiteLight\Fixture\TruncateDirtyTables; class BaseFactoryStaticFinderTest extends TestCase { + use TruncateDirtyTables; + public $Articles; public function setUp(): void { + parent::setUp(); $this->Articles = TableRegistry::getTableLocator()->get('Articles'); $this->Articles->getEventManager()->on( 'Model.beforeFind', - function(EventInterface $event, Query $query) { + function(EventInterface $event, SelectQuery $query) { return $query->where(['title' => 'Cannot be found.']); } ); diff --git a/tests/TestCase/Factory/BaseFactoryTest.php b/tests/TestCase/Factory/BaseFactoryTest.php index 8b2ed457..27785e6e 100644 --- a/tests/TestCase/Factory/BaseFactoryTest.php +++ b/tests/TestCase/Factory/BaseFactoryTest.php @@ -25,6 +25,7 @@ use CakephpFixtureFactories\Test\Factory\CityFactory; use CakephpFixtureFactories\Test\Factory\CountryFactory; use CakephpFixtureFactories\Test\Factory\CustomerFactory; +use CakephpTestSuiteLight\Fixture\TruncateDirtyTables; use Faker\Generator; use TestApp\Model\Entity\Address; use TestApp\Model\Entity\Article; @@ -40,7 +41,9 @@ class BaseFactoryTest extends TestCase { - public function dataForTestConnectionInDataProvider() + use TruncateDirtyTables; + + public static function dataForTestConnectionInDataProvider() { return [ [AuthorFactory::make()], @@ -641,7 +644,7 @@ public function testPersistingWithAssociationWithDefaultAssociationWrong() ->persist(); $this->assertSame(true, is_int($article->id)); - $this->equalTo($n, count($article->bills)); + $this->assertSame($n, count($article->bills)); $this->assertEquals($title, $article->title); foreach ($article->bills as $bill) { $this->assertEquals($bill->article_id, $article->id); @@ -668,7 +671,7 @@ public function testPersistingWithAssociationWithDefaultAssociationUnstopped() ->persist(); $this->assertSame(true, is_int($article->id)); - $this->equalTo($n, count($article->bills)); + $this->assertSame($n, count($article->bills)); $this->assertEquals($title, $article->title); foreach ($article->bills as $bill) { $this->assertSame($bill->article_id, $article->id); @@ -704,7 +707,7 @@ public function testPersistingWithAssociationWithinPlugin() ->persist(); $this->assertSame(true, is_int($customer->id)); - $this->equalTo($n, count($customer->bills)); + $this->assertSame($n, count($customer->bills)); $this->assertEquals($name, $customer->name); foreach ($customer->bills as $bill) { $this->assertEquals($bill->customer_id, $customer->id); @@ -820,7 +823,7 @@ public function testSaveMultipleHasManyAssociationAndTimes() /** * @return array */ - public function feedTestSetTimes() + public static function feedTestSetTimes() { return [[rand(1, 10)], [rand(1, 10)], [rand(1, 10)], ]; } diff --git a/tests/TestCase/Factory/BaseFactoryUniqueEntitiesTest.php b/tests/TestCase/Factory/BaseFactoryUniqueEntitiesTest.php index 557636c9..f4310ad6 100644 --- a/tests/TestCase/Factory/BaseFactoryUniqueEntitiesTest.php +++ b/tests/TestCase/Factory/BaseFactoryUniqueEntitiesTest.php @@ -14,7 +14,6 @@ namespace CakephpFixtureFactories\Test\TestCase\Factory; - use Cake\Core\Configure; use Cake\TestSuite\TestCase; use CakephpFixtureFactories\Error\PersistenceException; @@ -24,10 +23,13 @@ use CakephpFixtureFactories\Test\Factory\AuthorFactory; use CakephpFixtureFactories\Test\Factory\CityFactory; use CakephpFixtureFactories\Test\Factory\CountryFactory; +use CakephpTestSuiteLight\Fixture\TruncateDirtyTables; use TestApp\Model\Entity\Country; class BaseFactoryUniqueEntitiesTest extends TestCase { + use TruncateDirtyTables; + public static function setUpBeforeClass(): void { Configure::write('FixtureFactories.testFixtureNamespace', 'CakephpFixtureFactories\Test\Factory'); diff --git a/tests/TestCase/Factory/DataCompilerTest.php b/tests/TestCase/Factory/DataCompilerTest.php index fcf57405..c4579c8d 100644 --- a/tests/TestCase/Factory/DataCompilerTest.php +++ b/tests/TestCase/Factory/DataCompilerTest.php @@ -21,12 +21,10 @@ use CakephpFixtureFactories\Test\Factory\ArticleFactory; use CakephpFixtureFactories\Test\Factory\AuthorFactory; use CakephpFixtureFactories\Test\Factory\CountryFactory; -use CakephpTestSuiteLight\SkipTablesTruncation; use TestApp\Model\Table\PremiumAuthorsTable; class DataCompilerTest extends TestCase { - use SkipTablesTruncation; /** * @var DataCompiler @@ -146,7 +144,7 @@ public function testSetPrimaryKeyOnEntity() $this->articleDataCompiler->endPersistMode(); } - public function dataForGetModifiedUniqueFields(): array + public static function dataForGetModifiedUniqueFields(): array { return [ [[], []], diff --git a/tests/TestCase/Factory/EventCollectorTest.php b/tests/TestCase/Factory/EventCollectorTest.php index cd5cb575..c7244fb0 100644 --- a/tests/TestCase/Factory/EventCollectorTest.php +++ b/tests/TestCase/Factory/EventCollectorTest.php @@ -28,6 +28,7 @@ use CakephpFixtureFactories\Test\Factory\CityFactory; use CakephpFixtureFactories\Test\Factory\CountryFactory; use CakephpFixtureFactories\Test\Factory\CustomerFactory; +use CakephpTestSuiteLight\Fixture\TruncateDirtyTables; use TestApp\Model\Entity\Address; use TestApp\Model\Entity\Article; use TestApp\Model\Entity\City; @@ -36,6 +37,8 @@ class EventCollectorTest extends TestCase { + use TruncateDirtyTables; + /** * @var CountriesTable */ @@ -99,7 +102,7 @@ public function testSetBehaviorEmpty() ); } - public function provideFactories() + public static function provideFactories() { return [ [ArticleFactory::make()], @@ -122,7 +125,7 @@ public function testTimestamp(BaseFactory $factory) $this->assertNotNull($entity->get('created')); } - public function runSeveralTimesWithOrWithoutEvents() + public static function runSeveralTimesWithOrWithoutEvents() { return [ [true], [false], [true], [false], diff --git a/tests/TestCase/Factory/FactoryAwareTraitIntegrationTest.php b/tests/TestCase/Factory/FactoryAwareTraitIntegrationTest.php index b8422ba5..bc4d6c8d 100644 --- a/tests/TestCase/Factory/FactoryAwareTraitIntegrationTest.php +++ b/tests/TestCase/Factory/FactoryAwareTraitIntegrationTest.php @@ -9,11 +9,9 @@ use CakephpFixtureFactories\Factory\FactoryAwareTrait; use CakephpFixtureFactories\Test\Factory\CountryFactory; use CakephpFixtureFactories\Test\Factory\PremiumAuthorFactory; -use CakephpTestSuiteLight\SkipTablesTruncation; class FactoryAwareTraitIntegrationTest extends TestCase { - use SkipTablesTruncation; public static function setUpBeforeClass(): void { @@ -25,7 +23,7 @@ public static function tearDownAfterClass(): void Configure::delete('FixtureFactories.testFixtureNamespace'); } - public function factoryFoundData(): array + public static function factoryFoundData(): array { return [ ['country', CountryFactory::class], diff --git a/tests/TestCase/Factory/FactoryAwareTraitUnitTest.php b/tests/TestCase/Factory/FactoryAwareTraitUnitTest.php index 29b6b711..404a9777 100644 --- a/tests/TestCase/Factory/FactoryAwareTraitUnitTest.php +++ b/tests/TestCase/Factory/FactoryAwareTraitUnitTest.php @@ -5,14 +5,12 @@ use Cake\TestSuite\TestCase; use CakephpFixtureFactories\Factory\FactoryAwareTrait; -use CakephpTestSuiteLight\SkipTablesTruncation; class FactoryAwareTraitUnitTest extends TestCase { use FactoryAwareTrait; - use SkipTablesTruncation; - public function getFactoryNamespaceData(): array + public static function getFactoryNamespaceData(): array { return [ [null, 'TestApp\Test\Factory'], @@ -28,7 +26,7 @@ public function testGetFactoryNamespace(?string $plugin, string $expected): void $this->assertEquals($expected, $trait->getFactoryNamespace($plugin)); } - public function getFactoryClassNameData(): array + public static function getFactoryClassNameData(): array { return [ ['Apples', 'TestApp\Test\Factory\AppleFactory'], @@ -43,7 +41,7 @@ public function testGetFactoryClassName(string $name, string $expected): void $this->assertEquals($expected, $trait->getFactoryClassName($name)); } - public function getFactoryNameData(): array + public static function getFactoryNameData(): array { return [ ['Apples', 'AppleFactory', 'AppleFactory.php'], diff --git a/tests/TestCase/Factory/FixtureInjectorTest.php b/tests/TestCase/Factory/FixtureInjectorTest.php index 273a9d76..4859de4b 100644 --- a/tests/TestCase/Factory/FixtureInjectorTest.php +++ b/tests/TestCase/Factory/FixtureInjectorTest.php @@ -15,9 +15,12 @@ use Cake\TestSuite\TestCase; use CakephpFixtureFactories\Test\Factory\ArticleFactory; +use CakephpTestSuiteLight\Fixture\TruncateDirtyTables; class FixtureInjectorTest extends TestCase { + use TruncateDirtyTables; + /** * For each of the data provided, their should be * 10 Articles found, which is the last value given to times @@ -25,7 +28,7 @@ class FixtureInjectorTest extends TestCase * * @return array */ - public function createWithOneFactoryInTheDataProvider() + public static function createWithOneFactoryInTheDataProvider() { $Factory = ArticleFactory::make(); @@ -42,7 +45,7 @@ public function createWithOneFactoryInTheDataProvider() * * @return array[] */ - public function createWithDifferentFactoriesInTheDataProvider() + public static function createWithDifferentFactoriesInTheDataProvider() { return [ [1, ArticleFactory::make()], diff --git a/tests/TestCase/Factory/UniquenessJanitorTest.php b/tests/TestCase/Factory/UniquenessJanitorTest.php index 41e266f4..9dc8af3a 100644 --- a/tests/TestCase/Factory/UniquenessJanitorTest.php +++ b/tests/TestCase/Factory/UniquenessJanitorTest.php @@ -24,7 +24,7 @@ class UniquenessJanitorTest extends TestCase { - public function dataForSanitizeEntityArrayOnPrimary() + public static function dataForSanitizeEntityArrayOnPrimary() { return [ [[], false], @@ -67,7 +67,7 @@ public function testSanitizeEntityArrayOnPrimary(array $uniqueProperties, bool $ UniquenessJanitor::sanitizeEntityArray($factoryStub, $entities, true); } - public function dataForSanitizeEntityArrayOnAssociation() + public static function dataForSanitizeEntityArrayOnAssociation() { $associatedData = [ ['property_1' => 'foo', 'property_2' => 'foo'], diff --git a/tests/TestCase/ORM/FactoryTableRegistryTest.php b/tests/TestCase/ORM/FactoryTableRegistryTest.php index b2685d80..71b935ef 100644 --- a/tests/TestCase/ORM/FactoryTableRegistryTest.php +++ b/tests/TestCase/ORM/FactoryTableRegistryTest.php @@ -33,7 +33,7 @@ public function setUp(): void TableRegistry::getTableLocator()->clear(); } - public function tables() + public static function tables() { return [ ['Articles', ArticlesTable::class], diff --git a/tests/TestCase/Scenario/FixtureScenarioTest.php b/tests/TestCase/Scenario/FixtureScenarioTest.php index 5a5ce498..2d5619f0 100644 --- a/tests/TestCase/Scenario/FixtureScenarioTest.php +++ b/tests/TestCase/Scenario/FixtureScenarioTest.php @@ -15,7 +15,7 @@ namespace CakephpFixtureFactories\Test\TestCase\Scenario; use Cake\Core\Configure; -use Cake\ORM\Query; +use Cake\ORM\Query\SelectQuery; use Cake\TestSuite\TestCase; use CakephpFixtureFactories\Error\FixtureScenarioException; use CakephpFixtureFactories\Scenario\ScenarioAwareTrait; @@ -23,10 +23,12 @@ use CakephpFixtureFactories\Test\Scenario\NAustralianAuthorsScenario; use CakephpFixtureFactories\Test\Scenario\SubFolder\SubFolderScenario; use CakephpFixtureFactories\Test\Scenario\TenAustralianAuthorsScenario; +use CakephpTestSuiteLight\Fixture\TruncateDirtyTables; use TestApp\Model\Entity\Author; class FixtureScenarioTest extends TestCase { + use TruncateDirtyTables; use ScenarioAwareTrait; public static function setUpBeforeClass(): void @@ -39,7 +41,7 @@ public static function tearDownAfterClass(): void Configure::delete('FixtureFactories.testFixtureNamespace'); } - public function scenarioNames(): array + public static function scenarioNames(): array { return [ ['NAustralianAuthors', 3], @@ -80,7 +82,7 @@ public function testLoadScenarioException() private function countAustralianAuthors(): int { return AuthorFactory::find() - ->innerJoinWith('Address.City.Country', function (Query $q) { + ->innerJoinWith('Address.City.Country', function (SelectQuery $q) { return $q->where(['Country.name' => NAustralianAuthorsScenario::COUNTRY_NAME]); }) ->count(); diff --git a/tests/TestCase/StaticFixturesTest.php b/tests/TestCase/StaticFixturesTest.php index 2c82e658..c8ffac3a 100644 --- a/tests/TestCase/StaticFixturesTest.php +++ b/tests/TestCase/StaticFixturesTest.php @@ -20,7 +20,7 @@ class StaticFixturesTest extends TestCase { - protected $fixtures = [ + protected array $fixtures = [ ArticlesFixture::class, ]; diff --git a/tests/Util/TestCaseWithFixtureBaking.php b/tests/Util/TestCaseWithFixtureBaking.php index 8b46ca73..7004e02f 100644 --- a/tests/Util/TestCaseWithFixtureBaking.php +++ b/tests/Util/TestCaseWithFixtureBaking.php @@ -78,7 +78,7 @@ public function tearDown(): void public static function tearDownAfterClass(): void { /** @psalm-suppress InternalMethod */ - $test = new self(); + $test = new self('SomeTest'); $test->setUp(); $test->bake([], ['methods' => true, 'all' => true]); $test->bake([], ['plugin' => 'TestPlugin', 'all' => true, 'methods' => true,]); @@ -88,6 +88,7 @@ protected function bake(array $args = [], array $options = [], array $argNames = { $options['force'] = $options['force'] ?? true; $options['quiet'] = $options['quiet'] ?? true; + $options['connection'] = $options['connection'] ?? 'default'; $args = new Arguments($args, $options, $argNames); $this->assertEquals(0, $this->FactoryCommand->execute($args, $this->io)); } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 1b22e0de..21a3be49 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -16,7 +16,7 @@ use Cake\Core\Configure; use Cake\Datasource\ConnectionManager; use Cake\Utility\Inflector; -use CakephpTestMigrator\Migrator; +use function Cake\Core\env; if (!defined('DS')) { define('DS', DIRECTORY_SEPARATOR); @@ -59,6 +59,7 @@ Configure::write('debug', true); Configure::write('App', [ 'namespace' => 'TestApp', + 'encoding' => 'UTF-8', 'paths' => [ 'plugins' => [TEST_APP . 'plugins' . DS], 'templates' => [ @@ -96,7 +97,7 @@ if (!getenv('DB_DRIVER')) { putenv('DB_DRIVER=Sqlite'); } -$driver = getenv('DB_DRIVER'); +$driver = getenv('DB_DRIVER'); $testDir = ROOT . DS . 'tests' . DS; if (!file_exists("$testDir.env")) { @@ -136,7 +137,13 @@ ConnectionManager::setConfig('test', $dbConnection); $dbConnection['dummy_key'] = 'DummyKeyValue'; ConnectionManager::setConfig('dummy', $dbConnection); +ConnectionManager::alias('test', 'default'); Inflector::rules('singular', ['/(ss)$/i' => '\1']); -Migrator::migrate(); +(new \Migrations\TestSuite\Migrator())->runMany([ + // TestApp Migrations + [], + + ['plugin' => 'TestPlugin'], +]); \ No newline at end of file