From 2414fc516ed5c5305beab7b246534371b093d184 Mon Sep 17 00:00:00 2001 From: Kevin Pfeifer Date: Tue, 13 Jun 2023 20:10:36 +0200 Subject: [PATCH 01/13] cakephp 5 update --- .github/workflows/phpstan.yml | 2 +- .github/workflows/tests_composer2.yml | 2 +- .gitignore | 2 +- composer.json | 23 ++- phpunit.xml.dist | 36 ++-- src/Command/BakeFixtureFactoryCommand.php | 15 +- src/Command/SetupCommand.php | 135 ------------- src/Factory/BaseFactory.php | 28 +-- src/Factory/FactoryAwareTrait.php | 1 + src/Plugin.php | 6 +- tests/Fixture/ArticlesFixture.php | 12 -- .../TestPlugin/src/Model/Entity/Bill.php | 2 +- .../src/Model/Behavior/SluggableBehavior.php | 2 +- tests/TestApp/src/Model/Entity/Address.php | 2 +- tests/TestApp/src/Model/Entity/Article.php | 4 +- tests/TestApp/src/Model/Entity/Author.php | 2 +- tests/TestApp/src/Model/Entity/City.php | 2 +- tests/TestApp/src/Model/Entity/Country.php | 2 +- .../TestApp/src/Model/Table/ArticlesTable.php | 4 +- .../Command/BakeFixtureFactoryCommandTest.php | 4 +- tests/TestCase/Command/PersistCommandTest.php | 4 +- tests/TestCase/Command/SetupCommandTest.php | 181 ------------------ .../Factory/BaseFactoryAssociationsTest.php | 4 +- .../Factory/BaseFactoryDefaultValuesTest.php | 2 +- ...BaseFactoryDisablePrimaryKeyOffsetTest.php | 2 +- .../BaseFactoryHiddenPropertiesTest.php | 2 +- ...actoryLoadAssociationsInInitializeTest.php | 2 +- .../BaseFactoryPrimaryKeyOffsetTest.php | 2 +- .../Factory/BaseFactoryStaticFinderTest.php | 4 +- tests/TestCase/Factory/BaseFactoryTest.php | 10 +- .../Factory/BaseFactoryUniqueEntitiesTest.php | 1 - tests/TestCase/Factory/DataCompilerTest.php | 4 +- tests/TestCase/Factory/EventCollectorTest.php | 4 +- .../FactoryAwareTraitIntegrationTest.php | 4 +- .../Factory/FactoryAwareTraitUnitTest.php | 8 +- .../TestCase/Factory/FixtureInjectorTest.php | 4 +- .../Factory/UniquenessJanitorTest.php | 4 +- .../TestCase/ORM/FactoryTableRegistryTest.php | 2 +- .../TestCase/Scenario/FixtureScenarioTest.php | 6 +- tests/TestCase/StaticFixturesTest.php | 2 +- tests/Util/TestCaseWithFixtureBaking.php | 3 +- tests/bootstrap.php | 13 +- 42 files changed, 113 insertions(+), 441 deletions(-) delete mode 100644 src/Command/SetupCommand.php delete mode 100644 tests/TestCase/Command/SetupCommandTest.php diff --git a/.github/workflows/phpstan.yml b/.github/workflows/phpstan.yml index f69ae263..a6bbbc43 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 }} diff --git a/.github/workflows/tests_composer2.yml b/.github/workflows/tests_composer2.yml index db8fc271..c7ca3f88 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] 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..7679e491 100644 --- a/composer.json +++ b/composer.json @@ -14,22 +14,19 @@ } ], "license": "MIT", - "minimum-stability": "dev", "require": { - "php": ">=7.2", - "cakephp/orm": "^4.2", - "fakerphp/faker": "^1.15", - "vierge-noire/cakephp-test-suite-light": "^2.1" + "php": ">=8.1", + "cakephp/orm": "5.x-dev", + "fakerphp/faker": "^1.15" }, "require-dev": { - "cakephp/bake": "^2.0", - "cakephp/cakephp-codesniffer": "^4.0", - "cakephp/migrations": "^3.7", + "cakephp/bake": "3.x-dev as 3.0.0", + "cakephp/cakephp-codesniffer": "^5.1", + "cakephp/migrations": "4.x-dev as 4.0.0", "josegonzalez/dotenv": "dev-master", "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": { @@ -60,5 +57,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/src/Command/BakeFixtureFactoryCommand.php b/src/Command/BakeFixtureFactoryCommand.php index d217c56f..f9084106 100644 --- a/src/Command/BakeFixtureFactoryCommand.php +++ b/src/Command/BakeFixtureFactoryCommand.php @@ -19,7 +19,6 @@ 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\Inflector; @@ -140,21 +139,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,7 +167,7 @@ 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 { 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/Factory/BaseFactory.php b/src/Factory/BaseFactory.php index feaa6793..8daf36c5 100644 --- a/src/Factory/BaseFactory.php +++ b/src/Factory/BaseFactory.php @@ -15,7 +15,7 @@ use Cake\Datasource\EntityInterface; 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; @@ -605,30 +605,30 @@ public function skipSetterFor($skippedSetters, bool $merge = false) return $this; } - /** - * 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() - */ - public static function find(string $type = 'all', array $options = []): Query + /** + * Query the factory's related table without before find. + * + * @param string $type the type of query to perform + * @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', 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 mixed ...$options options accepted by `Table::get()` * @return \Cake\Datasource\EntityInterface * @see Table::get() */ - public static function get($primaryKey, array $options = []): EntityInterface + public static function get(mixed $primaryKey, mixed ...$options): EntityInterface { - return (new static())->getTable()->get($primaryKey, $options); + return (new static())->getTable()->get($primaryKey, 'all', null, null, ...$options); } /** diff --git a/src/Factory/FactoryAwareTrait.php b/src/Factory/FactoryAwareTrait.php index 03d4bb92..f7793428 100644 --- a/src/Factory/FactoryAwareTrait.php +++ b/src/Factory/FactoryAwareTrait.php @@ -17,6 +17,7 @@ use Cake\Core\Configure; use Cake\Utility\Inflector; use CakephpFixtureFactories\Error\FactoryNotFoundException; +use function Cake\Core\namespaceSplit; trait FactoryAwareTrait { 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/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/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..80038612 100644 --- a/tests/TestCase/Command/BakeFixtureFactoryCommandTest.php +++ b/tests/TestCase/Command/BakeFixtureFactoryCommandTest.php @@ -274,11 +274,11 @@ public function testRunBakeAllInTestPlugin() $this->assertInstanceOf(Customer::class, $customer); } - public function dataForTestThisTableShouldBeBaked() + public static function dataForTestThisTableShouldBeBaked() { return [ ['Cities', null, true], - ['Cities', true, false], + ['Cities', null, 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..141e6fc8 100644 --- a/tests/TestCase/Command/PersistCommandTest.php +++ b/tests/TestCase/Command/PersistCommandTest.php @@ -60,7 +60,7 @@ public function tearDown(): void unset($this->io); } - public function dataProviderForStringFactories(): array + public static function dataProviderForStringFactories(): array { return [ ['Articles'], @@ -82,7 +82,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/BaseFactoryAssociationsTest.php b/tests/TestCase/Factory/BaseFactoryAssociationsTest.php index 5b8accc5..e47ac331 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; @@ -501,7 +501,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..0c5ca505 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->equalTo(5); } /** diff --git a/tests/TestCase/Factory/BaseFactoryDisablePrimaryKeyOffsetTest.php b/tests/TestCase/Factory/BaseFactoryDisablePrimaryKeyOffsetTest.php index da29a186..ded8921b 100644 --- a/tests/TestCase/Factory/BaseFactoryDisablePrimaryKeyOffsetTest.php +++ b/tests/TestCase/Factory/BaseFactoryDisablePrimaryKeyOffsetTest.php @@ -22,7 +22,7 @@ class BaseFactoryDisablePrimaryKeyOffsetTest extends TestCase { - public function dataForTestDisablePrimaryKeyOffset() + 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..af0f1265 100644 --- a/tests/TestCase/Factory/BaseFactoryLoadAssociationsInInitializeTest.php +++ b/tests/TestCase/Factory/BaseFactoryLoadAssociationsInInitializeTest.php @@ -118,7 +118,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/BaseFactoryPrimaryKeyOffsetTest.php b/tests/TestCase/Factory/BaseFactoryPrimaryKeyOffsetTest.php index dc58899d..2f02b182 100644 --- a/tests/TestCase/Factory/BaseFactoryPrimaryKeyOffsetTest.php +++ b/tests/TestCase/Factory/BaseFactoryPrimaryKeyOffsetTest.php @@ -23,7 +23,7 @@ class BaseFactoryPrimaryKeyOffsetTest extends TestCase { - public function dataForTestSetPrimaryKeyOffset() + public static function dataForTestSetPrimaryKeyOffset() { return [ [rand(1, 1000000)], diff --git a/tests/TestCase/Factory/BaseFactoryStaticFinderTest.php b/tests/TestCase/Factory/BaseFactoryStaticFinderTest.php index 073c8550..46143d88 100644 --- a/tests/TestCase/Factory/BaseFactoryStaticFinderTest.php +++ b/tests/TestCase/Factory/BaseFactoryStaticFinderTest.php @@ -15,7 +15,7 @@ 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; @@ -29,7 +29,7 @@ public function setUp(): void $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..bb7c010c 100644 --- a/tests/TestCase/Factory/BaseFactoryTest.php +++ b/tests/TestCase/Factory/BaseFactoryTest.php @@ -40,7 +40,7 @@ class BaseFactoryTest extends TestCase { - public function dataForTestConnectionInDataProvider() + public static function dataForTestConnectionInDataProvider() { return [ [AuthorFactory::make()], @@ -641,7 +641,7 @@ public function testPersistingWithAssociationWithDefaultAssociationWrong() ->persist(); $this->assertSame(true, is_int($article->id)); - $this->equalTo($n, count($article->bills)); + $this->equalTo($n); $this->assertEquals($title, $article->title); foreach ($article->bills as $bill) { $this->assertEquals($bill->article_id, $article->id); @@ -668,7 +668,7 @@ public function testPersistingWithAssociationWithDefaultAssociationUnstopped() ->persist(); $this->assertSame(true, is_int($article->id)); - $this->equalTo($n, count($article->bills)); + $this->equalTo($n); $this->assertEquals($title, $article->title); foreach ($article->bills as $bill) { $this->assertSame($bill->article_id, $article->id); @@ -704,7 +704,7 @@ public function testPersistingWithAssociationWithinPlugin() ->persist(); $this->assertSame(true, is_int($customer->id)); - $this->equalTo($n, count($customer->bills)); + $this->equalTo($n); $this->assertEquals($name, $customer->name); foreach ($customer->bills as $bill) { $this->assertEquals($bill->customer_id, $customer->id); @@ -820,7 +820,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..7a221c43 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; 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..ba7bc9ea 100644 --- a/tests/TestCase/Factory/EventCollectorTest.php +++ b/tests/TestCase/Factory/EventCollectorTest.php @@ -99,7 +99,7 @@ public function testSetBehaviorEmpty() ); } - public function provideFactories() + public static function provideFactories() { return [ [ArticleFactory::make()], @@ -122,7 +122,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..b35fa99e 100644 --- a/tests/TestCase/Factory/FixtureInjectorTest.php +++ b/tests/TestCase/Factory/FixtureInjectorTest.php @@ -25,7 +25,7 @@ class FixtureInjectorTest extends TestCase * * @return array */ - public function createWithOneFactoryInTheDataProvider() + public static function createWithOneFactoryInTheDataProvider() { $Factory = ArticleFactory::make(); @@ -42,7 +42,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..7d32abca 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; @@ -39,7 +39,7 @@ public static function tearDownAfterClass(): void Configure::delete('FixtureFactories.testFixtureNamespace'); } - public function scenarioNames(): array + public static function scenarioNames(): array { return [ ['NAustralianAuthors', 3], @@ -80,7 +80,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 From 2bc2af5d7e79455bd82305568fa2734041423bd6 Mon Sep 17 00:00:00 2001 From: Kevin Pfeifer Date: Thu, 15 Jun 2023 20:32:54 +0200 Subject: [PATCH 02/13] add use TruncateDirtyTables --- composer.json | 9 ++++++++- tests/TestCase/Command/BakeFixtureFactoryCommandTest.php | 3 +++ tests/TestCase/Command/PersistCommandTest.php | 3 +++ tests/TestCase/Factory/AssociationBuilderTest.php | 3 +++ tests/TestCase/Factory/BaseFactoryArrayNotationTest.php | 3 +++ tests/TestCase/Factory/BaseFactoryAssociationsTest.php | 3 +++ .../Factory/BaseFactoryDisablePrimaryKeyOffsetTest.php | 3 +++ .../BaseFactoryLoadAssociationsInInitializeTest.php | 3 +++ tests/TestCase/Factory/BaseFactoryMakeWithEntityTest.php | 3 +++ .../TestCase/Factory/BaseFactoryPrimaryKeyOffsetTest.php | 3 +++ tests/TestCase/Factory/BaseFactoryStaticFinderTest.php | 3 +++ tests/TestCase/Factory/BaseFactoryTest.php | 3 +++ tests/TestCase/Factory/BaseFactoryUniqueEntitiesTest.php | 3 +++ tests/TestCase/Factory/EventCollectorTest.php | 3 +++ tests/TestCase/Factory/FixtureInjectorTest.php | 3 +++ tests/TestCase/Scenario/FixtureScenarioTest.php | 2 ++ 16 files changed, 52 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 7679e491..b92b9d22 100644 --- a/composer.json +++ b/composer.json @@ -13,11 +13,18 @@ "email": "pabloelcolombiano@gmail.com" } ], + "repositories": [ + { + "type": "vcs", + "url": "https://github.com/lordsimal/cakephp-test-suite-light" + } + ], "license": "MIT", "require": { "php": ">=8.1", "cakephp/orm": "5.x-dev", - "fakerphp/faker": "^1.15" + "fakerphp/faker": "^1.15", + "vierge-noire/cakephp-test-suite-light": "dev-main" }, "require-dev": { "cakephp/bake": "3.x-dev as 3.0.0", diff --git a/tests/TestCase/Command/BakeFixtureFactoryCommandTest.php b/tests/TestCase/Command/BakeFixtureFactoryCommandTest.php index 80038612..91d9c18d 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 */ diff --git a/tests/TestCase/Command/PersistCommandTest.php b/tests/TestCase/Command/PersistCommandTest.php index 141e6fc8..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 */ 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 46d86ff9..8de56aac 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 e47ac331..0468e6e1 100644 --- a/tests/TestCase/Factory/BaseFactoryAssociationsTest.php +++ b/tests/TestCase/Factory/BaseFactoryAssociationsTest.php @@ -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'); diff --git a/tests/TestCase/Factory/BaseFactoryDisablePrimaryKeyOffsetTest.php b/tests/TestCase/Factory/BaseFactoryDisablePrimaryKeyOffsetTest.php index ded8921b..8bc36c2e 100644 --- a/tests/TestCase/Factory/BaseFactoryDisablePrimaryKeyOffsetTest.php +++ b/tests/TestCase/Factory/BaseFactoryDisablePrimaryKeyOffsetTest.php @@ -18,10 +18,13 @@ 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 { + use TruncateDirtyTables; + public static function dataForTestDisablePrimaryKeyOffset() { return [ diff --git a/tests/TestCase/Factory/BaseFactoryLoadAssociationsInInitializeTest.php b/tests/TestCase/Factory/BaseFactoryLoadAssociationsInInitializeTest.php index af0f1265..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'); diff --git a/tests/TestCase/Factory/BaseFactoryMakeWithEntityTest.php b/tests/TestCase/Factory/BaseFactoryMakeWithEntityTest.php index 735c04ba..2e1ff4af 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 2f02b182..99724f06 100644 --- a/tests/TestCase/Factory/BaseFactoryPrimaryKeyOffsetTest.php +++ b/tests/TestCase/Factory/BaseFactoryPrimaryKeyOffsetTest.php @@ -19,10 +19,13 @@ 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 { + use TruncateDirtyTables; + public static function dataForTestSetPrimaryKeyOffset() { return [ diff --git a/tests/TestCase/Factory/BaseFactoryStaticFinderTest.php b/tests/TestCase/Factory/BaseFactoryStaticFinderTest.php index 46143d88..67c91355 100644 --- a/tests/TestCase/Factory/BaseFactoryStaticFinderTest.php +++ b/tests/TestCase/Factory/BaseFactoryStaticFinderTest.php @@ -19,9 +19,12 @@ 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 diff --git a/tests/TestCase/Factory/BaseFactoryTest.php b/tests/TestCase/Factory/BaseFactoryTest.php index bb7c010c..4923308a 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,6 +41,8 @@ class BaseFactoryTest extends TestCase { + use TruncateDirtyTables; + public static function dataForTestConnectionInDataProvider() { return [ diff --git a/tests/TestCase/Factory/BaseFactoryUniqueEntitiesTest.php b/tests/TestCase/Factory/BaseFactoryUniqueEntitiesTest.php index 7a221c43..f4310ad6 100644 --- a/tests/TestCase/Factory/BaseFactoryUniqueEntitiesTest.php +++ b/tests/TestCase/Factory/BaseFactoryUniqueEntitiesTest.php @@ -23,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/EventCollectorTest.php b/tests/TestCase/Factory/EventCollectorTest.php index ba7bc9ea..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 */ diff --git a/tests/TestCase/Factory/FixtureInjectorTest.php b/tests/TestCase/Factory/FixtureInjectorTest.php index b35fa99e..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 diff --git a/tests/TestCase/Scenario/FixtureScenarioTest.php b/tests/TestCase/Scenario/FixtureScenarioTest.php index 7d32abca..2d5619f0 100644 --- a/tests/TestCase/Scenario/FixtureScenarioTest.php +++ b/tests/TestCase/Scenario/FixtureScenarioTest.php @@ -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 From 3ef53a8a0cc0caf196791e6c1ea98ebb2f9461a1 Mon Sep 17 00:00:00 2001 From: Kevin Pfeifer Date: Thu, 15 Jun 2023 21:18:13 +0200 Subject: [PATCH 03/13] fix tests --- src/Event/ModelEventsHandler.php | 10 +++++++--- .../TestCase/Command/BakeFixtureFactoryCommandTest.php | 1 - tests/TestCase/Factory/BaseFactoryStaticFinderTest.php | 1 + 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Event/ModelEventsHandler.php b/src/Event/ModelEventsHandler.php index c6cba888..ce2731c6 100644 --- a/src/Event/ModelEventsHandler.php +++ b/src/Event/ModelEventsHandler.php @@ -89,9 +89,13 @@ 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)) { + try { + $reflection = new \ReflectionFunction($listeners['callable']); + $obj = $reflection->getClosureThis(); + $this->processListener($table, $obj, $ormEvent); + } catch (\ReflectionException $e) { + // Do something? } } } diff --git a/tests/TestCase/Command/BakeFixtureFactoryCommandTest.php b/tests/TestCase/Command/BakeFixtureFactoryCommandTest.php index 91d9c18d..4888e73b 100644 --- a/tests/TestCase/Command/BakeFixtureFactoryCommandTest.php +++ b/tests/TestCase/Command/BakeFixtureFactoryCommandTest.php @@ -281,7 +281,6 @@ public static function dataForTestThisTableShouldBeBaked() { return [ ['Cities', null, true], - ['Cities', null, false], ['Cities', 'TestPlugin', false], ['Bills', null, false], ['Bills', 'TestPlugin', true], diff --git a/tests/TestCase/Factory/BaseFactoryStaticFinderTest.php b/tests/TestCase/Factory/BaseFactoryStaticFinderTest.php index 67c91355..a6043112 100644 --- a/tests/TestCase/Factory/BaseFactoryStaticFinderTest.php +++ b/tests/TestCase/Factory/BaseFactoryStaticFinderTest.php @@ -29,6 +29,7 @@ class BaseFactoryStaticFinderTest extends TestCase public function setUp(): void { + parent::setUp(); $this->Articles = TableRegistry::getTableLocator()->get('Articles'); $this->Articles->getEventManager()->on( 'Model.beforeFind', From dc9e934f9fb7be357f7da009dae4199590df7f65 Mon Sep 17 00:00:00 2001 From: Kevin Pfeifer Date: Thu, 15 Jun 2023 21:20:57 +0200 Subject: [PATCH 04/13] fix cs --- src/Command/BakeFixtureFactoryCommand.php | 26 +++--- src/Command/PersistCommand.php | 3 +- src/Event/ModelEventsHandler.php | 21 ++--- src/Factory/AssociationBuilder.php | 23 +++--- src/Factory/BaseFactory.php | 97 ++++++++++++----------- src/Factory/DataCompiler.php | 61 +++++++------- src/Factory/EventCollector.php | 13 +-- src/Factory/FactoryAwareTrait.php | 10 +-- src/Factory/UniquenessJanitor.php | 4 +- src/ORM/FactoryTableBeforeSave.php | 16 ++-- src/ORM/FactoryTableLocator.php | 2 +- src/ORM/FactoryTableRegistry.php | 4 +- src/Scenario/FixtureScenarioInterface.php | 2 +- src/Scenario/ScenarioAwareTrait.php | 8 +- 14 files changed, 156 insertions(+), 134 deletions(-) diff --git a/src/Command/BakeFixtureFactoryCommand.php b/src/Command/BakeFixtureFactoryCommand.php index f9084106..875a8f04 100644 --- a/src/Command/BakeFixtureFactoryCommand.php +++ b/src/Command/BakeFixtureFactoryCommand.php @@ -23,7 +23,9 @@ use Cake\ORM\TableRegistry; use Cake\Utility\Inflector; use CakephpFixtureFactories\Factory\FactoryAwareTrait; +use Exception; use ReflectionClass; +use ReflectionException; class BakeFixtureFactoryCommand extends BakeCommand { @@ -32,17 +34,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 @@ -89,7 +91,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()); } @@ -118,9 +120,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; @@ -151,7 +153,7 @@ public function getTableList(ConsoleIo $io): array if (!$this->thisTableShouldBeBaked($table, $io)) { $io->warning("{$table} ignored"); } else { - $return[] = $table; + $return[] = $table; } } @@ -172,7 +174,7 @@ public function thisTableShouldBeBaked(string $table, ConsoleIo $io): bool try { $class = new ReflectionClass($tableClassName); - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { $io->error($e->getMessage()); return false; @@ -190,7 +192,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)) { @@ -256,9 +258,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; @@ -304,7 +306,7 @@ public function templateData(Arguments $arg): array $data['manyToMany'] = $associations['manyToMany']; $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; 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/Event/ModelEventsHandler.php b/src/Event/ModelEventsHandler.php index ce2731c6..864a1e7d 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', @@ -91,10 +94,10 @@ private function ignoreModelEvents(Table $table): void foreach ($table->getEventManager()->listeners($ormEvent) as $listeners) { if (array_key_exists('callable', $listeners)) { try { - $reflection = new \ReflectionFunction($listeners['callable']); + $reflection = new ReflectionFunction($listeners['callable']); $obj = $reflection->getClosureThis(); $this->processListener($table, $obj, $ormEvent); - } catch (\ReflectionException $e) { + } catch (ReflectionException $e) { // Do something? } } @@ -108,7 +111,7 @@ 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); @@ -125,7 +128,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( @@ -143,7 +146,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..0cec3e28 100644 --- a/src/Factory/AssociationBuilder.php +++ b/src/Factory/AssociationBuilder.php @@ -14,6 +14,7 @@ namespace CakephpFixtureFactories\Factory; +use Cake\Datasource\EntityInterface; use Cake\ORM\Association; use Cake\ORM\Association\BelongsTo; use Cake\ORM\Association\BelongsToMany; @@ -23,6 +24,8 @@ use Cake\Utility\Hash; use Cake\Utility\Inflector; use CakephpFixtureFactories\Error\AssociationBuilderException; +use Exception; +use Throwable; /** * Class AssociationBuilder @@ -35,12 +38,12 @@ class AssociationBuilder getFactory as getFactoryInstance; } - private $associated = []; + private array $associated = []; /** * @var \CakephpFixtureFactories\Factory\BaseFactory */ - private $factory; + private BaseFactory $factory; /** * AssociationBuilder constructor. @@ -65,7 +68,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 +149,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 \CakephpFixtureFactories\Factory\BaseFactory|\Cake\Datasource\EntityInterface|array|array<\Cake\Datasource\EntityInterface> $data Injected data * @return \CakephpFixtureFactories\Factory\BaseFactory */ - public function getAssociatedFactory(string $associationName, $data = []): BaseFactory - { + public function getAssociatedFactory( + string $associationName, + array|BaseFactory|EntityInterface $data = [] + ): BaseFactory { $associations = explode('.', $associationName); $firstAssociation = array_shift($associations); @@ -179,11 +184,11 @@ public function getAssociatedFactory(string $associationName, $data = []): BaseF * @param array $data Injected data * @return \CakephpFixtureFactories\Factory\BaseFactory */ - public function getFactoryFromTableName(string $modelName, $data = []): BaseFactory + public function getFactoryFromTableName(string $modelName, array $data = []): BaseFactory { try { return $this->getFactoryInstance($modelName, $data); - } catch (\Throwable $e) { + } catch (Throwable $e) { throw new AssociationBuilderException($e->getMessage()); } } @@ -205,7 +210,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 8daf36c5..45d96d86 100644 --- a/src/Factory/BaseFactory.php +++ b/src/Factory/BaseFactory.php @@ -13,15 +13,19 @@ */ namespace CakephpFixtureFactories\Factory; +use Cake\Database\ExpressionInterface; use Cake\Datasource\EntityInterface; +use Cake\Datasource\ResultSetInterface; use Cake\I18n\I18n; 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 Throwable; use function array_merge; use function is_array; use function is_callable; @@ -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 \Cake\Datasource\EntityInterface|callable|array|string|int|null $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( + array|callable|int|EntityInterface|string|null $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> $data Injected data * @return static */ - private static function makeFromNonCallable($data = []): BaseFactory + private static function makeFromNonCallable(EntityInterface|array $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( @@ -605,14 +611,14 @@ public function skipSetterFor($skippedSetters, bool $merge = false) return $this; } - /** - * Query the factory's related table without before find. - * - * @param string $type the type of query to perform - * @param mixed ...$options Options passed to the finder - * @return \Cake\ORM\Query\SelectQuery The query builder - * @see \Cake\ORM\Query\SelectQuery::find() - */ + /** + * Query the factory's related table without before find. + * + * @param string $type the type of query to perform + * @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', mixed ...$options): SelectQuery { return (new static())->getTable()->find($type, ...$options); @@ -649,8 +655,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 d2928c49..c9dc57e6 100644 --- a/src/Factory/DataCompiler.php +++ b/src/Factory/DataCompiler.php @@ -16,6 +16,7 @@ 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; @@ -34,29 +35,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 $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 +72,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 +157,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 +185,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); } @@ -271,7 +274,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 @@ -333,10 +336,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( @@ -442,7 +445,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 { @@ -492,9 +495,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)); @@ -562,9 +565,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': @@ -598,10 +601,10 @@ public function getFactory(): BaseFactory } /** - * @param int|string|array $primaryKeyOffset Name of the primary key + * @param array|string|int $primaryKeyOffset Name of the primary key * @return void */ - public function setPrimaryKeyOffset($primaryKeyOffset): void + public function setPrimaryKeyOffset(int|string|array $primaryKeyOffset): void { if (is_int($primaryKeyOffset) || is_string($primaryKeyOffset)) { $primaryKey = $this->getFactory()->getTable()->getPrimaryKey(); @@ -712,7 +715,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 f7793428..0200db55 100644 --- a/src/Factory/FactoryAwareTrait.php +++ b/src/Factory/FactoryAwareTrait.php @@ -26,13 +26,13 @@ trait FactoryAwareTrait * * Additionnal arguments are passed *as is* to `BaseFactory::make` * - * @param string $name Factory or model name - * @param string|array[] ...$arguments Additional arguments for `BaseFactory::make` + * @param string $name Factory or model name + * @param array|string ...$arguments Additional arguments for `BaseFactory::make` * @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, ...$arguments): BaseFactory + public function getFactory(string $name, string|array ...$arguments): BaseFactory { $factoryClassName = $this->getFactoryClassName($name); @@ -46,7 +46,7 @@ public function getFactory(string $name, ...$arguments): BaseFactory /** * 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 @@ -61,7 +61,7 @@ public function getFactoryClassName(string $name): string /** * 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 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 8eeed301..79f90889 100644 --- a/src/ORM/FactoryTableRegistry.php +++ b/src/ORM/FactoryTableRegistry.php @@ -40,12 +40,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/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()); } } From 68499c99b9c71366c99302c2905edb8ccab98f58 Mon Sep 17 00:00:00 2001 From: Kevin Pfeifer Date: Thu, 15 Jun 2023 21:33:44 +0200 Subject: [PATCH 05/13] fix stan and cs --- psalm.xml | 6 ++++-- src/Factory/AssociationBuilder.php | 9 ++++----- src/Factory/BaseFactory.php | 12 +++--------- src/Factory/DataCompiler.php | 11 ++++------- src/Factory/FactoryAwareTrait.php | 16 ++++++++-------- tests/Factory/AuthorFactory.php | 2 +- tests/Factory/CityFactory.php | 2 +- tests/Factory/CountryFactory.php | 2 +- tests/Scenario/NAustralianAuthorsScenario.php | 2 +- tests/Scenario/SubFolder/SubFolderScenario.php | 3 ++- tests/Scenario/TenAustralianAuthorsScenario.php | 2 +- 11 files changed, 30 insertions(+), 37 deletions(-) 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/Factory/AssociationBuilder.php b/src/Factory/AssociationBuilder.php index 0cec3e28..030e4a3a 100644 --- a/src/Factory/AssociationBuilder.php +++ b/src/Factory/AssociationBuilder.php @@ -14,7 +14,6 @@ namespace CakephpFixtureFactories\Factory; -use Cake\Datasource\EntityInterface; use Cake\ORM\Association; use Cake\ORM\Association\BelongsTo; use Cake\ORM\Association\BelongsToMany; @@ -149,12 +148,12 @@ public function removeAssociationForToOneFactory(string $associationName, BaseFa * Get the factory for the association * * @param string $associationName Association name - * @param \CakephpFixtureFactories\Factory\BaseFactory|\Cake\Datasource\EntityInterface|array|array<\Cake\Datasource\EntityInterface> $data Injected data + * @param mixed $data Injected data * @return \CakephpFixtureFactories\Factory\BaseFactory */ public function getAssociatedFactory( string $associationName, - array|BaseFactory|EntityInterface $data = [] + mixed $data = [] ): BaseFactory { $associations = explode('.', $associationName); $firstAssociation = array_shift($associations); @@ -181,10 +180,10 @@ public function getAssociatedFactory( * 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, array $data = []): BaseFactory + public function getFactoryFromTableName(string $modelName, mixed $data = []): BaseFactory { try { return $this->getFactoryInstance($modelName, $data); diff --git a/src/Factory/BaseFactory.php b/src/Factory/BaseFactory.php index 45d96d86..9fc14bf7 100644 --- a/src/Factory/BaseFactory.php +++ b/src/Factory/BaseFactory.php @@ -24,11 +24,9 @@ use Closure; use Faker\Factory; use Faker\Generator; -use InvalidArgumentException; use Throwable; use function array_merge; use function is_array; -use function is_callable; /** * Class BaseFactory @@ -137,12 +135,8 @@ public static function make( $factory = self::makeFromNonCallable(); } elseif (is_array($makeParameter) || $makeParameter instanceof EntityInterface || is_string($makeParameter)) { $factory = self::makeFromNonCallable($makeParameter); - } elseif (is_callable($makeParameter)) { - $factory = self::makeFromCallable($makeParameter); } else { - throw new InvalidArgumentException(' - ::make only accepts an array, an integer, an EntityInterface, a string or a callable as first parameter. - '); + $factory = self::makeFromCallable($makeParameter); } $factory->setUp($factory, $times); @@ -178,10 +172,10 @@ protected function initialize(): void } /** - * @param \Cake\Datasource\EntityInterface|array|array<\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(EntityInterface|array $data = []): BaseFactory + private static function makeFromNonCallable(EntityInterface|array|string $data = []): BaseFactory { $factory = new static(); $factory->getDataCompiler()->collectFromInstantiation($data); diff --git a/src/Factory/DataCompiler.php b/src/Factory/DataCompiler.php index c9dc57e6..a45ce614 100644 --- a/src/Factory/DataCompiler.php +++ b/src/Factory/DataCompiler.php @@ -23,6 +23,7 @@ use Cake\Utility\Inflector; use CakephpFixtureFactories\Error\FixtureFactoryException; use CakephpFixtureFactories\Error\PersistenceException; +use Closure; use InvalidArgumentException; /** @@ -35,7 +36,7 @@ class DataCompiler public const MODIFIED_UNIQUE_PROPERTIES = '___data_compiler__modified_unique_properties'; public const IS_ASSOCIATED = '___data_compiler__is_associated'; - private array $dataFromDefaultTemplate = []; + private array|Closure $dataFromDefaultTemplate = []; /** * @var \Cake\Datasource\EntityInterface|callable|array|array<\Cake\Datasource\EntityInterface> */ @@ -43,7 +44,7 @@ class DataCompiler private array $dataFromPatch = []; private array $dataFromAssociations = []; private array $dataFromDefaultAssociations = []; - private array $primaryKeyOffset = []; + private ?array $primaryKeyOffset = []; private array $enforcedFields = []; private array $skippedSetters = []; @@ -616,12 +617,8 @@ public function setPrimaryKeyOffset(int|string|array $primaryKeyOffset): void $this->primaryKeyOffset = [ $primaryKey => $primaryKeyOffset, ]; - } elseif (is_array($primaryKeyOffset)) { - $this->primaryKeyOffset = $primaryKeyOffset; } else { - throw new FixtureFactoryException( - "$primaryKeyOffset must be an integer, a string or an array of format ['primaryKey1' => value, ...]" - ); + $this->primaryKeyOffset = $primaryKeyOffset; } } diff --git a/src/Factory/FactoryAwareTrait.php b/src/Factory/FactoryAwareTrait.php index 0200db55..c3bc4679 100644 --- a/src/Factory/FactoryAwareTrait.php +++ b/src/Factory/FactoryAwareTrait.php @@ -26,13 +26,13 @@ trait FactoryAwareTrait * * Additionnal arguments are passed *as is* to `BaseFactory::make` * - * @param string $name Factory or model name - * @param array|string ...$arguments Additional arguments for `BaseFactory::make` + * @param string $name Factory or model name + * @param mixed ...$arguments Additional arguments for `BaseFactory::make` * @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, string|array ...$arguments): BaseFactory + public function getFactory(string $name, mixed ...$arguments): BaseFactory { $factoryClassName = $this->getFactoryClassName($name); @@ -53,6 +53,7 @@ public function getFactoryClassName(string $name): string { // phpcs:disable @[$modelName, $plugin] = array_reverse(explode('.', $name)); + // phpcs:enable return $this->getFactoryNamespace($plugin) . '\\' . $this->getFactoryNameFromModelName($modelName); @@ -96,11 +97,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/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/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); } From 6763bebecfe9397125b1273e0423a2b2381546cb Mon Sep 17 00:00:00 2001 From: Kevin Pfeifer Date: Thu, 15 Jun 2023 21:35:18 +0200 Subject: [PATCH 06/13] fix CI config --- .github/workflows/phpstan.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/phpstan.yml b/.github/workflows/phpstan.yml index a6bbbc43..9bf04afb 100644 --- a/.github/workflows/phpstan.yml +++ b/.github/workflows/phpstan.yml @@ -41,7 +41,7 @@ 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 From f4e0ad248d50770020997231f0406be676d5c2cf Mon Sep 17 00:00:00 2001 From: Kevin Pfeifer Date: Sun, 18 Jun 2023 12:24:20 +0200 Subject: [PATCH 07/13] fix ModelEventsHandler --- src/Event/ModelEventsHandler.php | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/src/Event/ModelEventsHandler.php b/src/Event/ModelEventsHandler.php index 864a1e7d..6d05c04d 100644 --- a/src/Event/ModelEventsHandler.php +++ b/src/Event/ModelEventsHandler.php @@ -93,13 +93,7 @@ private function ignoreModelEvents(Table $table): void foreach (self::$ormEvents as $ormEvent) { foreach ($table->getEventManager()->listeners($ormEvent) as $listeners) { if (array_key_exists('callable', $listeners)) { - try { - $reflection = new ReflectionFunction($listeners['callable']); - $obj = $reflection->getClosureThis(); - $this->processListener($table, $obj, $ormEvent); - } catch (ReflectionException $e) { - // Do something? - } + $this->processListener($table, $listeners['callable'], $ormEvent); } } } @@ -113,10 +107,19 @@ private function ignoreModelEvents(Table $table): 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); } From 16718895c39b69da950212c5770f66923dc27287 Mon Sep 17 00:00:00 2001 From: Kevin Pfeifer Date: Tue, 20 Jun 2023 13:15:56 +0200 Subject: [PATCH 08/13] refactor equalTo to assertSame --- tests/TestCase/Factory/BaseFactoryDefaultValuesTest.php | 2 +- tests/TestCase/Factory/BaseFactoryTest.php | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/TestCase/Factory/BaseFactoryDefaultValuesTest.php b/tests/TestCase/Factory/BaseFactoryDefaultValuesTest.php index 0c5ca505..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); + $this->assertSame(5, count($article->bills)); } /** diff --git a/tests/TestCase/Factory/BaseFactoryTest.php b/tests/TestCase/Factory/BaseFactoryTest.php index 4923308a..27785e6e 100644 --- a/tests/TestCase/Factory/BaseFactoryTest.php +++ b/tests/TestCase/Factory/BaseFactoryTest.php @@ -644,7 +644,7 @@ public function testPersistingWithAssociationWithDefaultAssociationWrong() ->persist(); $this->assertSame(true, is_int($article->id)); - $this->equalTo($n); + $this->assertSame($n, count($article->bills)); $this->assertEquals($title, $article->title); foreach ($article->bills as $bill) { $this->assertEquals($bill->article_id, $article->id); @@ -671,7 +671,7 @@ public function testPersistingWithAssociationWithDefaultAssociationUnstopped() ->persist(); $this->assertSame(true, is_int($article->id)); - $this->equalTo($n); + $this->assertSame($n, count($article->bills)); $this->assertEquals($title, $article->title); foreach ($article->bills as $bill) { $this->assertSame($bill->article_id, $article->id); @@ -707,7 +707,7 @@ public function testPersistingWithAssociationWithinPlugin() ->persist(); $this->assertSame(true, is_int($customer->id)); - $this->equalTo($n); + $this->assertSame($n, count($customer->bills)); $this->assertEquals($name, $customer->name); foreach ($customer->bills as $bill) { $this->assertEquals($bill->customer_id, $customer->id); From d8dd1c8da03df1b8f3100d4071102f565a483c88 Mon Sep 17 00:00:00 2001 From: Kevin Pfeifer Date: Tue, 20 Jun 2023 13:20:55 +0200 Subject: [PATCH 09/13] re-add manually thrown exceptions --- composer.json | 8 +------- src/Factory/BaseFactory.php | 13 +++++++++---- src/Factory/DataCompiler.php | 10 +++++++--- 3 files changed, 17 insertions(+), 14 deletions(-) diff --git a/composer.json b/composer.json index b92b9d22..81b00234 100644 --- a/composer.json +++ b/composer.json @@ -13,18 +13,12 @@ "email": "pabloelcolombiano@gmail.com" } ], - "repositories": [ - { - "type": "vcs", - "url": "https://github.com/lordsimal/cakephp-test-suite-light" - } - ], "license": "MIT", "require": { "php": ">=8.1", "cakephp/orm": "5.x-dev", "fakerphp/faker": "^1.15", - "vierge-noire/cakephp-test-suite-light": "dev-main" + "vierge-noire/cakephp-test-suite-light": "dev-next" }, "require-dev": { "cakephp/bake": "3.x-dev as 3.0.0", diff --git a/src/Factory/BaseFactory.php b/src/Factory/BaseFactory.php index 9fc14bf7..a86c5317 100644 --- a/src/Factory/BaseFactory.php +++ b/src/Factory/BaseFactory.php @@ -24,6 +24,7 @@ use Closure; use Faker\Factory; use Faker\Generator; +use InvalidArgumentException; use Throwable; use function array_merge; use function is_array; @@ -120,12 +121,12 @@ abstract protected function getRootTableRegistryName(): string; abstract protected function setDefaultTemplate(): void; /** - * @param \Cake\Datasource\EntityInterface|callable|array|string|int|null $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( - array|callable|int|EntityInterface|string|null $makeParameter = [], + mixed $makeParameter = [], int $times = 1 ): BaseFactory { if (is_numeric($makeParameter)) { @@ -135,8 +136,12 @@ public static function make( $factory = self::makeFromNonCallable(); } elseif (is_array($makeParameter) || $makeParameter instanceof EntityInterface || is_string($makeParameter)) { $factory = self::makeFromNonCallable($makeParameter); - } else { + } elseif (is_callable($makeParameter)) { $factory = self::makeFromCallable($makeParameter); + } else { + throw new InvalidArgumentException(' + ::make only accepts an array, an integer, an EntityInterface, a string or a callable as first parameter. + '); } $factory->setUp($factory, $times); diff --git a/src/Factory/DataCompiler.php b/src/Factory/DataCompiler.php index a45ce614..954490db 100644 --- a/src/Factory/DataCompiler.php +++ b/src/Factory/DataCompiler.php @@ -602,10 +602,10 @@ public function getFactory(): BaseFactory } /** - * @param array|string|int $primaryKeyOffset Name of the primary key + * @param mixed $primaryKeyOffset Name of the primary key * @return void */ - public function setPrimaryKeyOffset(int|string|array $primaryKeyOffset): void + public function setPrimaryKeyOffset(mixed $primaryKeyOffset): void { if (is_int($primaryKeyOffset) || is_string($primaryKeyOffset)) { $primaryKey = $this->getFactory()->getTable()->getPrimaryKey(); @@ -617,8 +617,12 @@ public function setPrimaryKeyOffset(int|string|array $primaryKeyOffset): void $this->primaryKeyOffset = [ $primaryKey => $primaryKeyOffset, ]; - } else { + } elseif (is_array($primaryKeyOffset)) { $this->primaryKeyOffset = $primaryKeyOffset; + } else { + throw new FixtureFactoryException( + "$primaryKeyOffset must be an integer, a string or an array of format ['primaryKey1' => value, ...]" + ); } } From b290d7eee597632c5f5223ab10f098b2c9337682 Mon Sep 17 00:00:00 2001 From: Kevin Pfeifer Date: Tue, 20 Jun 2023 13:32:55 +0200 Subject: [PATCH 10/13] update BaseFactory::get to cake5 signature --- src/Factory/BaseFactory.php | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/Factory/BaseFactory.php b/src/Factory/BaseFactory.php index a86c5317..db0ef638 100644 --- a/src/Factory/BaseFactory.php +++ b/src/Factory/BaseFactory.php @@ -25,6 +25,7 @@ use Faker\Factory; use Faker\Generator; use InvalidArgumentException; +use Psr\SimpleCache\CacheInterface; use Throwable; use function array_merge; use function is_array; @@ -627,13 +628,23 @@ public static function find(string $type = 'all', mixed ...$options): SelectQuer * Get from primary key the factory's related table entries, without before find. * * @param mixed $primaryKey primary key value to find - * @param mixed ...$options options accepted by `Table::get()` + * @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(mixed $primaryKey, mixed ...$options): EntityInterface - { - return (new static())->getTable()->get($primaryKey, 'all', null, null, ...$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); } /** From 8cf3804b177a8fe81be3591e774f4afa62174324 Mon Sep 17 00:00:00 2001 From: Kevin Pfeifer Date: Fri, 23 Jun 2023 23:23:43 +0200 Subject: [PATCH 11/13] fix generated factories not being CS conform --- src/Command/BakeFixtureFactoryCommand.php | 49 ++++++++++++--- src/Factory/FactoryAwareTrait.php | 13 ++++ templates/bake/fixture_factory.twig | 17 +++-- .../Command/BakeFixtureFactoryCommandTest.php | 62 ++++++++++++++++--- 4 files changed, 116 insertions(+), 25 deletions(-) diff --git a/src/Command/BakeFixtureFactoryCommand.php b/src/Command/BakeFixtureFactoryCommand.php index 875a8f04..f61d36bd 100644 --- a/src/Command/BakeFixtureFactoryCommand.php +++ b/src/Command/BakeFixtureFactoryCommand.php @@ -21,6 +21,7 @@ use Cake\Core\Configure; use Cake\ORM\Table; use Cake\ORM\TableRegistry; +use Cake\Utility\Hash; use Cake\Utility\Inflector; use CakephpFixtureFactories\Factory\FactoryAwareTrait; use Exception; @@ -294,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): 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; @@ -331,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/Factory/FactoryAwareTrait.php b/src/Factory/FactoryAwareTrait.php index c3bc4679..ca399181 100644 --- a/src/Factory/FactoryAwareTrait.php +++ b/src/Factory/FactoryAwareTrait.php @@ -59,6 +59,19 @@ public function getFactoryClassName(string $name): string 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 * diff --git a/templates/bake/fixture_factory.twig b/templates/bake/fixture_factory.twig index 5cf8856d..797d60fa 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 $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 $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 $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/TestCase/Command/BakeFixtureFactoryCommandTest.php b/tests/TestCase/Command/BakeFixtureFactoryCommandTest.php index 4888e73b..09a900e7 100644 --- a/tests/TestCase/Command/BakeFixtureFactoryCommandTest.php +++ b/tests/TestCase/Command/BakeFixtureFactoryCommandTest.php @@ -97,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); @@ -113,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); } @@ -126,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); @@ -150,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' => [], ]; From 74f2f639730d23a1e5bf4d9d66a18705e8a01a35 Mon Sep 17 00:00:00 2001 From: Kevin Pfeifer Date: Wed, 20 Sep 2023 13:51:16 +0200 Subject: [PATCH 12/13] use stable versions --- composer.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/composer.json b/composer.json index 81b00234..973b2e21 100644 --- a/composer.json +++ b/composer.json @@ -16,15 +16,15 @@ "license": "MIT", "require": { "php": ">=8.1", - "cakephp/orm": "5.x-dev", + "cakephp/orm": "^5.0", "fakerphp/faker": "^1.15", "vierge-noire/cakephp-test-suite-light": "dev-next" }, "require-dev": { - "cakephp/bake": "3.x-dev as 3.0.0", + "cakephp/bake": "^3.0.0", "cakephp/cakephp-codesniffer": "^5.1", - "cakephp/migrations": "4.x-dev as 4.0.0", - "josegonzalez/dotenv": "dev-master", + "cakephp/migrations": "^4.0.0", + "josegonzalez/dotenv": "^4.0.0", "phpstan/phpstan": "^1.0", "phpunit/phpunit": "^10.1", "vimeo/psalm": "^5.0" From f52dde63dbcd831c061cb8f7ed1e6eaf547a836d Mon Sep 17 00:00:00 2001 From: Juan Pablo Ramirez Date: Mon, 9 Oct 2023 20:27:02 +0200 Subject: [PATCH 13/13] Fix Cake5 branch --- .github/workflows/phpstan.yml | 2 +- .github/workflows/tests_composer2.yml | 2 +- composer.json | 4 +-- src/Factory/DataCompiler.php | 17 +++++++---- src/Factory/FactoryAwareTrait.php | 15 ++++++---- templates/bake/fixture_factory.twig | 6 ++-- .../20200208100000_initial_migration.php | 29 ++++++++----------- ...22100000_table_without_model_migration.php | 4 +-- .../20200513155719_CreateCustomers.php | 4 +-- .../Migrations/20200513155720_CreateBills.php | 4 +-- .../Factory/BaseFactoryMakeWithEntityTest.php | 8 +++++ 11 files changed, 52 insertions(+), 43 deletions(-) diff --git a/.github/workflows/phpstan.yml b/.github/workflows/phpstan.yml index 9bf04afb..cae8fcc7 100644 --- a/.github/workflows/phpstan.yml +++ b/.github/workflows/phpstan.yml @@ -44,7 +44,7 @@ jobs: 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 c7ca3f88..d89baba8 100644 --- a/.github/workflows/tests_composer2.yml +++ b/.github/workflows/tests_composer2.yml @@ -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/composer.json b/composer.json index 973b2e21..444d302c 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,7 @@ "php": ">=8.1", "cakephp/orm": "^5.0", "fakerphp/faker": "^1.15", - "vierge-noire/cakephp-test-suite-light": "dev-next" + "vierge-noire/cakephp-test-suite-light": "^3.0" }, "require-dev": { "cakephp/bake": "^3.0.0", @@ -48,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" diff --git a/src/Factory/DataCompiler.php b/src/Factory/DataCompiler.php index f046562c..4a8e6c14 100644 --- a/src/Factory/DataCompiler.php +++ b/src/Factory/DataCompiler.php @@ -197,14 +197,16 @@ public function compileEntity( if (is_string($injectedData)) { $injectedData = $this->setDisplayFieldToInjectedString($injectedData); } - if ($injectedData instanceof EntityInterface) { + $isEntityInjected = $injectedData instanceof EntityInterface; + if ($isEntityInjected) { + /** @var \Cake\Datasource\EntityInterface $entity */ $entity = $injectedData; } else { $entity = $this->getEntityFromDefaultTemplate(); $this->mergeWithInjectedData($entity, $injectedData); } - $this->mergeWithPatchedData($entity)->mergeWithAssociatedData($entity); + $this->mergeWithPatchedData($entity)->mergeWithAssociatedData($entity, $isEntityInjected); if ($this->isInPersistMode() && !empty($this->getModifiedUniqueFields())) { $entity->set(self::MODIFIED_UNIQUE_PROPERTIES, $this->getModifiedUniqueFields()); @@ -380,12 +382,17 @@ private function mergeWithPatchedData(EntityInterface $entity): self * Merge with the data from the associations * * @param \Cake\Datasource\EntityInterface $entity Entity produced by the factory. + * @param bool $isEntityInjected Whether \Cake\Datasource\EntityInterface is injected or not. * @return self */ - private function mergeWithAssociatedData(EntityInterface $entity): self + private function mergeWithAssociatedData(EntityInterface $entity, bool $isEntityInjected): self { - // Overwrite the default associations if these are found in the associations - $associatedData = array_merge($this->dataFromDefaultAssociations, $this->dataFromAssociations); + if ($isEntityInjected) { + $associatedData = $this->dataFromAssociations; + } else { + // Overwrite the default associations if these are found in the associations + $associatedData = array_merge($this->dataFromDefaultAssociations, $this->dataFromAssociations); + } foreach ($associatedData as $propertyName => $data) { $association = $this->getAssociationByPropertyName($propertyName); diff --git a/src/Factory/FactoryAwareTrait.php b/src/Factory/FactoryAwareTrait.php index ca399181..681d280c 100644 --- a/src/Factory/FactoryAwareTrait.php +++ b/src/Factory/FactoryAwareTrait.php @@ -15,6 +15,7 @@ namespace CakephpFixtureFactories\Factory; use Cake\Core\Configure; +use Cake\Datasource\EntityInterface; use Cake\Utility\Inflector; use CakephpFixtureFactories\Error\FactoryNotFoundException; use function Cake\Core\namespaceSplit; @@ -26,18 +27,22 @@ trait FactoryAwareTrait * * Additionnal arguments are passed *as is* to `BaseFactory::make` * - * @param string $name Factory or model name - * @param mixed ...$arguments Additional arguments for `BaseFactory::make` + * @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, mixed ...$arguments): 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)) { - return $factoryClassName::make(...$arguments); + return $factoryClassName::make($makeParameter, $times); } throw new FactoryNotFoundException("Unable to locate factory class $factoryClassName"); diff --git a/templates/bake/fixture_factory.twig b/templates/bake/fixture_factory.twig index 797d60fa..38e2b7f9 100644 --- a/templates/bake/fixture_factory.twig +++ b/templates/bake/fixture_factory.twig @@ -50,7 +50,7 @@ class {{ factory }} extends CakephpBaseFactory {% for association, associationData in toOne %} /** - * @param array|callable|null|int $parameter + * @param array|callable|null|int|\Cake\Datasource\EntityInterface|string $parameter * @return {{ factory }} */ public function with{{ association }}($parameter = null): {{ factory }} @@ -64,7 +64,7 @@ class {{ factory }} extends CakephpBaseFactory {% for association, associationData in oneToMany %} /** - * @param array|callable|null|int $parameter + * @param array|callable|null|int|\Cake\Datasource\EntityInterface|string $parameter * @param int $n * @return {{ factory }} */ @@ -79,7 +79,7 @@ class {{ factory }} extends CakephpBaseFactory {% for association, associationData in manyToMany %} /** - * @param array|callable|null|int $parameter + * @param array|callable|null|int|\Cake\Datasource\EntityInterface|string $parameter * @param int $n * @return {{ factory }} */ 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/TestCase/Factory/BaseFactoryMakeWithEntityTest.php b/tests/TestCase/Factory/BaseFactoryMakeWithEntityTest.php index 2e1ff4af..ffc2ec2b 100644 --- a/tests/TestCase/Factory/BaseFactoryMakeWithEntityTest.php +++ b/tests/TestCase/Factory/BaseFactoryMakeWithEntityTest.php @@ -134,4 +134,12 @@ public function testWithEntitiesAndTimes() $this->assertSame($n * $m, count($authors)); $this->assertSame($n, AuthorFactory::count()); } + + public function testMakeEntityWithoutDefaultAssociations() + { + $article1 = ArticleFactory::make()->persist(); + $this->assertSame(ArticleFactory::DEFAULT_NUMBER_OF_AUTHORS, count($article1->authors)); + $article2 = ArticleFactory::make($article1)->persist(); + $this->assertSame(ArticleFactory::DEFAULT_NUMBER_OF_AUTHORS, count($article1->authors)); + } }