diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml index c0fbc53..9652006 100644 --- a/.github/workflows/codecov.yml +++ b/.github/workflows/codecov.yml @@ -15,14 +15,14 @@ jobs: - ubuntu-latest php: - - "8.2" - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 @@ -36,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v3 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} @@ -50,6 +50,6 @@ jobs: run: vendor/bin/phpunit --colors=always --coverage-clover clover.xml - name: Send code coverage report to Codecov.io - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v7 with: token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/continuous-integration.yml b/.github/workflows/continuous-integration.yml index 72dde2f..26c5802 100644 --- a/.github/workflows/continuous-integration.yml +++ b/.github/workflows/continuous-integration.yml @@ -1,11 +1,11 @@ -name: "Continuous Integration" - -on: - pull_request: - push: - branches: - tags: - -jobs: - ci: - uses: laminas/workflow-continuous-integration/.github/workflows/continuous-integration.yml@1.x +name: "Continuous Integration" + +on: + pull_request: + push: + branches: + tags: + +jobs: + ci: + uses: laminas/workflow-continuous-integration/.github/workflows/continuous-integration.yml@1.x diff --git a/.github/workflows/docs-build.yml b/.github/workflows/docs-build.yml index a18edb1..1a7aa24 100644 --- a/.github/workflows/docs-build.yml +++ b/.github/workflows/docs-build.yml @@ -1,16 +1,16 @@ -name: docs-build - -on: - release: - types: [published] - workflow_dispatch: - -jobs: - build-deploy: - runs-on: ubuntu-latest - steps: - - name: Build Docs - uses: dotkernel/documentation-theme/github-actions/docs@main - env: - DEPLOY_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} +name: docs-build + +on: + release: + types: [published] + workflow_dispatch: + +jobs: + build-deploy: + runs-on: ubuntu-latest + steps: + - name: Build Docs + uses: dotkernel/documentation-theme/github-actions/docs@main + env: + DEPLOY_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 9976515..8baba0f 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -15,14 +15,14 @@ jobs: - ubuntu-latest php: - - "8.2" - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 @@ -36,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} @@ -47,4 +47,4 @@ jobs: run: composer install --prefer-dist --no-interaction --no-progress --optimize-autoloader --ansi - name: Run static analysis with PHPStan - run: vendor/bin/phpstan analyse + run: composer static-analysis diff --git a/.gitignore b/.gitignore index e0b1315..7cdbe68 100644 --- a/.gitignore +++ b/.gitignore @@ -3,5 +3,6 @@ composer.lock .idea/ .DS_Store /src/.DS_Store +/.phpunit.cache/ .phpunit.result.cache .phpcs-cache diff --git a/.laminas-ci.json b/.laminas-ci.json index 29216fa..e827682 100644 --- a/.laminas-ci.json +++ b/.laminas-ci.json @@ -1,3 +1,6 @@ { + "ignore_php_platform_requirements": { + "8.6": true + }, "backwardCompatibilityCheck": true } diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fa3e25..7ed27cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,85 +1,413 @@ +# Changelog + +## 2.0.0 - TBD + +### Changed + +- `ExecuteFixturesCommand` and `ListFixturesCommand` take their name and description from `#[AsCommand]`; `$defaultName` and `configure()` are kept and use the same values +- `--class` requires a value and takes a path relative to the fixtures directory, for example `--class=User/UserLoader` +- `fixtures:execute` prints an error and returns exit code `1` when a fixture cannot be loaded, instead of throwing +- `fixtures:execute` prints the "Executing" lines before running the fixtures +- `ExecuteFixturesCommandFactory` no longer creates an unused `ORMPurger` +- Minimum `symfony/console` raised to 7.0.3, and `symfony/string` below 6.4.3 and from 7.0.0 to 7.0.2 marked as conflicting. Those releases trigger "implicitly nullable" deprecations on PHP 8.4+ +- Bumped `phpunit/phpunit` to `^12`; strict `phpunit.xml` (fail on deprecations, notices, warnings and risky tests) +- PHPStan level raised from 5 to 8 +- Tests use real fixtures, a real `Loader` and an in-memory SQLite entity manager instead of mocks +- Documentation for v2 + +### Added + +- Support for PHP 8.6 +- Support for `symfony/console` 8 +- `NAME` and `DESCRIPTION` constants on `ExecuteFixturesCommand` and `ListFixturesCommand` +- `psr/container` declared as a direct requirement +- `ext-pdo_sqlite` as a development requirement, for the SQLite tests +- Upgrade guide from 1.x +- `.gitattributes` to keep line endings LF + +### Deprecated + +- Nothing + +### Removed + +- Support for PHP 8.2 + +### Fixed + +- `fixtures:list` printed an empty command name on `symfony/console` 7.3+ and failed on 8.x +- `fixtures:list` suggested a `--class` value that did not work for fixtures in subdirectories +- `fixtures:execute --class` without a value tried to load `.php` +- `fixtures:execute --class` could include PHP files outside the fixtures directory +- `ListFixturesCommand` did not handle `false` from `getFileName()` and `filemtime()` +- `ExecuteFixturesCommandFactory` failed with a `TypeError` inside Doctrine when the entity manager service had the wrong type + +## 1.5.0 - 2025-10-30 + +### Changed + +- Nothing + +### Added + +- Support for PHP 8.5 (#33) + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 1.4.0 - 2025-02-28 + +### Changed + +- Replaced Psalm with PHPStan (#31) + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- `vimeo/psalm` + +### Fixed + +- Nothing + +## 1.3.1 - 2025-01-27 + +### Changed + +- Bumped `vimeo/psalm` to `^6.0` (#29) + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 1.3.0 - 2025-01-27 + +### Changed + +- Bumped `doctrine/data-fixtures` from `^1.7` to `^2.0` and `doctrine/orm` from `*` to `^3.0` +- Bumped `laminas/laminas-coding-standard` to `^3.0` +- Updated README.md (#25) + +### Added + +- Support for PHP 8.4 (#27) + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 1.2.3 - 2024-07-01 + +### Changed + +- Marked the package as a wrapper of `doctrine/data-fixtures` (#24) + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 1.2.2 - 2024-06-14 + +### Changed + +- Bumped `doctrine/data-fixtures` to `^1.7` (#22) + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 1.2.1 - 2024-05-21 + +### Changed + +- Bumped `symfony/console` from `^5.1` to `^7.0` (#20) + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Support for PHP 8.1 (#20) + +### Fixed + +- Nothing + +## 1.2.0 - 2024-05-03 + +### Changed + +- Nothing + +### Added + +- Documentation for v1 (#17, #18) +- `symfony/console` `^5.1` as a direct requirement + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 1.1.3 - 2023-11-30 + +### Changed + +- Updated README.md + +### Added + +- Support for PHP 8.3 (#15) + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 1.1.2 - 2023-08-29 + +### Changed + +- Nothing + +### Added + +- Codecov workflow and badge (#10, #12) + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + +## 1.1.1 - 2023-08-11 + +### Changed + +- Nothing + +### Added + +- Nothing + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- `ORMPurger` not found (#8) + +## 1.1.0 - 2023-08-10 + +### Changed + +- Nothing + +### Added + +- PHPUnit tests, PHP_CodeSniffer and Psalm (#6) + +### Deprecated + +- Nothing + +### Removed + +- Nothing + +### Fixed + +- Nothing + ## 1.0.3 - 2022-08-26 ### Changed -* src/Factory/ListFixturesCommandFactory.php -* src/Factory/ExecuteFixturesCommandFactory.php -* CHANGELOG.md + +- src/Factory/ListFixturesCommandFactory.php +- src/Factory/ExecuteFixturesCommandFactory.php +- CHANGELOG.md ### Added -* Support for PHP 7.4 -* src/Command/ListFixturesCommandFactory.php -* src/Command/ExecuteFixturesCommandFactory.php -* CHANGELOG.md + +- Support for PHP 7.4 +- src/Command/ListFixturesCommandFactory.php +- src/Command/ExecuteFixturesCommandFactory.php +- CHANGELOG.md ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Added support for PHP 7.4 +- Added support for PHP 7.4 ## 1.0.2 - 2022-08-23 ### Changed -* README.md -* src/Command/ListFixturesCommand.php -* src/Command/ExecuteFixturesCommand.php -* CHANGELOG.md + +- README.md +- src/Command/ListFixturesCommand.php +- src/Command/ExecuteFixturesCommand.php +- CHANGELOG.md ### Added -* README.md -* src/Command/ListFixturesCommand.php -* src/Command/ExecuteFixturesCommand.php -* CHANGELOG.md + +- README.md +- src/Command/ListFixturesCommand.php +- src/Command/ExecuteFixturesCommand.php +- CHANGELOG.md ### Deprecated -* Nothing + +- Nothing ### Removed -* Removed the ``--append`` option from ``ExecuteFixturesCommand`` + +- Removed the `--append` option from `ExecuteFixturesCommand` ### Fixed -* Nothing +- Nothing ## 1.0.1 - 2022-08-23 ### Changed -* README.md -* src/Command/ListFixturesCommand.php -* CHANGELOG.md + +- README.md +- src/Command/ListFixturesCommand.php +- CHANGELOG.md ### Added -* README.md -* src/Command/ListFixturesCommand.php -* CHANGELOG.md + +- README.md +- src/Command/ListFixturesCommand.php +- CHANGELOG.md ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing +- Nothing ## 1.0.0 - 2022-08-23 ### Changed -* Nothing + +- Nothing ### Added -* Everything + +- Everything ### Deprecated -* Nothing + +- Nothing ### Removed -* Nothing + +- Nothing ### Fixed -* Nothing + +- Nothing diff --git a/README.md b/README.md index f9c241c..5e9c330 100644 --- a/README.md +++ b/README.md @@ -11,26 +11,36 @@ Documentation is available at: https://docs.dotkernel.org/dot-data-fixtures/. ## Badges ![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-data-fixtures) -![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-data-fixtures/1.5.0) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-data-fixtures/2.0.0) [![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-data-fixtures)](https://github.com/dotkernel/dot-data-fixtures/issues) [![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-data-fixtures)](https://github.com/dotkernel/dot-data-fixtures/network) [![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-data-fixtures)](https://github.com/dotkernel/dot-data-fixtures/stargazers) -[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-data-fixtures)](https://github.com/dotkernel/dot-data-fixtures/blob/1.0/LICENSE) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-data-fixtures)](https://github.com/dotkernel/dot-data-fixtures/blob/2.0/LICENSE) -[![Build Static](https://github.com/dotkernel/dot-data-fixtures/actions/workflows/continuous-integration.yml/badge.svg?branch=1.0)](https://github.com/dotkernel/dot-data-fixtures/actions/workflows/continuous-integration.yml) +[![Build Static](https://github.com/dotkernel/dot-data-fixtures/actions/workflows/continuous-integration.yml/badge.svg?branch=2.0)](https://github.com/dotkernel/dot-data-fixtures/actions/workflows/continuous-integration.yml) [![codecov](https://codecov.io/gh/dotkernel/dot-data-fixtures/graph/badge.svg?token=PGOXZOZAB0)](https://codecov.io/gh/dotkernel/dot-data-fixtures) -[![PHPStan](https://github.com/dotkernel/dot-data-fixtures/actions/workflows/static-analysis.yml/badge.svg?branch=1.0)](https://github.com/dotkernel/dot-data-fixtures/actions/workflows/static-analysis.yml) +[![PHPStan](https://github.com/dotkernel/dot-data-fixtures/actions/workflows/static-analysis.yml/badge.svg?branch=2.0)](https://github.com/dotkernel/dot-data-fixtures/actions/workflows/static-analysis.yml) This package provides a CLI interface for interacting with doctrine/data-fixtures. -**Executing fixtures will **append** data to the tables.** +**Executing fixtures will append data to the tables.** + +## Versions + +| Version | Branch | Status | PHP | +| --- | --- | --- | --- | +| 2.x | `2.0` | Active | 8.3, 8.4, 8.5, 8.6 | +| 1.x | `1.0` | Security fixes only | 8.2, 8.3, 8.4, 8.5 | + +Upgrading from 1.x? See the [upgrade guide](https://docs.dotkernel.org/dot-data-fixtures/v2/upgrading/). ## Requirements -- **PHP**: 8.2, 8.3 or 8.4 -- **doctrine/orm**: => 3.0 -- **doctrine/data-fixtures**: => 2.0 +- **PHP**: 8.3, 8.4, 8.5 or 8.6 +- **doctrine/orm**: >= 3.0 +- **doctrine/data-fixtures**: >= 2.0 +- **symfony/console**: 7.0.3 or later, or 8.x ## Installation @@ -47,6 +57,7 @@ Next, register the package's ConfigProvider into your application config. ``` In `doctrine.global.php` (or your custom doctrine config file) add a new key `fixtures`, in the `doctrine` array, the value should be a valid path to a folder where your fixtures can be found. +The folder is scanned recursively, so fixtures can be grouped in subfolders. **Make sure the path is valid before proceeding to the next step.** @@ -54,9 +65,11 @@ In `doctrine.global.php` (or your custom doctrine config file) add a new key `fi ```php return [ - 'dependencies' => [ ... ], - 'doctrine' => [ - ..., + 'dependencies' => [ + // ... + ], + 'doctrine' => [ + // ... 'fixtures' => getcwd() . '/data/doctrine/fixtures', ], ]; @@ -69,12 +82,14 @@ Create a new php file `bin/doctrine` (if you don't already have this file feel f ```php get(\Doctrine\ORM\EntityManager::class); @@ -91,11 +106,11 @@ ConsoleRunner::run( ## Usage -**List fixtures command**: will list all the available fixtures, by order of execution. +**List fixtures command**: will list all the available fixtures, by order of execution, with the command that executes each one and when its file was last changed (in UTC). -````shell +```shell php ./bin/doctrine fixtures:list -```` +``` **Execute fixtures command**: this command will execute one or all fixtures. @@ -105,19 +120,23 @@ To execute all the fixtures, run: php ./bin/doctrine fixtures:execute ``` -To execute a specific fixture, run: +To execute a specific fixture, pass its path relative to the fixtures folder, without `.php`: ```shell php ./bin/doctrine fixtures:execute --class=RoleLoader +php ./bin/doctrine fixtures:execute --class=User/UserLoader ``` +`--class` must have a value. A missing fixture, or a path outside the fixtures folder, prints an error and exits with code `1`. + ## Creating fixtures When creating a new fixture, we have two requirements: -- Fixtures should be created in the folder we configured earlier: `data/doctrine/fixtures` +- Fixtures should be created in the folder we configured earlier, `data/doctrine/fixtures`, or in a subfolder of it. - Fixtures should implement `FixtureInterface` and have a `load` method. -- Create a new PHP file and copy the below code-block. + +Create a new PHP file and copy the below code-block. ### Example @@ -132,7 +151,6 @@ use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Persistence\ObjectManager; use Frontend\User\Entity\UserRole; - class RoleLoader implements FixtureInterface { public function load(ObjectManager $manager): void @@ -142,10 +160,10 @@ class RoleLoader implements FixtureInterface $userRole = new UserRole(); $userRole->setName('user'); - + $guestRole = new UserRole(); $guestRole->setName('guest'); - + $manager->persist($adminRole); $manager->persist($userRole); $manager->persist($guestRole); diff --git a/SECURITY.md b/SECURITY.md index 5ad5da5..ca95cad 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,38 +1,36 @@ -# Security Policy - -## Supported Versions - - -| Version | Supported | PHP Version | -|---------|--------------------|-------------------------------------------------------------------------------------------------------------------| -| 1.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-data-fixtures/1.5.0) | - - -## Reporting Potential Security Issues - -If you have encountered a potential security vulnerability in this project, -please report it to us at . We will work with you to -verify the vulnerability and patch it. - -When reporting issues, please provide the following information: - -- Component(s) affected -- A description indicating how to reproduce the issue -- A summary of the security vulnerability and impact - -We request that you contact us via the email address above and give the -project contributors a chance to resolve the vulnerability and issue a new -release prior to any public exposure; this helps protect the project's -users, and provides them with a chance to upgrade and/or update in order to -protect their applications. - - -## Policy - -If we verify a reported security vulnerability, our policy is: - -- We will patch the current release branch, as well as the immediate prior minor - release branch. - -- After patching the release branches, we will immediately issue new security - fix releases for each patched release branch. \ No newline at end of file +# Security Policy + +## Supported Versions + +| Version | Supported | PHP Version | +|---------|------------------------|-------------------------------------------------------------------------------------------------------------------| +| 2.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-data-fixtures/2.0.0) | +| 1.x | Security fixes only | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-data-fixtures/1.5.0) | + +## Reporting Potential Security Issues + +If you have encountered a potential security vulnerability in this project, +please report it to us at . We will work with you to +verify the vulnerability and patch it. + +When reporting issues, please provide the following information: + +- Component(s) affected +- A description indicating how to reproduce the issue +- A summary of the security vulnerability and impact + +We request that you contact us via the email address above and give the +project contributors a chance to resolve the vulnerability and issue a new +release prior to any public exposure; this helps protect the project's +users, and provides them with a chance to upgrade and/or update in order to +protect their applications. + +## Policy + +If we verify a reported security vulnerability, our policy is: + +- We will patch the current release branch, as well as the immediate prior minor + release branch. + +- After patching the release branches, we will immediately issue new security + fix releases for each patched release branch. diff --git a/composer.json b/composer.json index e723369..cccf74c 100644 --- a/composer.json +++ b/composer.json @@ -19,16 +19,18 @@ "laminas" ], "require": { - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", "doctrine/data-fixtures": "^2.0", "doctrine/orm": "^3.0", - "symfony/console": "^7.0" + "psr/container": "^1.1 || ^2.0", + "symfony/console": "^7.0.3 || ^8.0" }, "require-dev": { + "ext-pdo_sqlite": "*", "laminas/laminas-coding-standard": "^3.0", "phpstan/phpstan": "^2.1", "phpstan/phpstan-phpunit": "^2.0", - "phpunit/phpunit": "^10.2" + "phpunit/phpunit": "^12.5" }, "autoload": { "psr-4": { @@ -56,5 +58,11 @@ "allow-plugins": { "dealerdirect/phpcodesniffer-composer-installer": true } + }, + "conflict": { + "doctrine/dbal": "<3.10.2", + "doctrine/event-manager": "<2.1.0", + "doctrine/persistence": "<3.4.1 || >=4.0,<4.0.1", + "symfony/string": "<6.4.3 || >=7.0,<7.0.3" } } diff --git a/docs/book/v1/configuration.md b/docs/book/v1/configuration.md index b165ddc..00279bd 100644 --- a/docs/book/v1/configuration.md +++ b/docs/book/v1/configuration.md @@ -1,52 +1,52 @@ -# Configuration - -## Register ConfigProvider - -After installation, register the package's ConfigProvider by adding the below line into your application config: - -`\Dot\DataFixtures\ConfigProvider::class,` - -In `doctrine.global.php` (or your custom doctrine config file) add a new key `fixtures`, in the `doctrine` array, the value should be a valid path to a folder where your fixtures can be found. - -Make sure the path is valid before proceeding to the next step. - -### Example - -```php -return [ - 'dependencies' => [ ... ], - 'doctrine' => [ - ..., - 'fixtures' => getcwd() . '/data/doctrine/fixtures', - ], -]; -``` - -## Registering commands - -The last step is to register the commands. We can register the commands to work with the default CLI that doctrine provides us. Create a new php file `bin/doctrine` (if you don't already have this file feel free to copy it from the below example) - -```php -get(\Doctrine\ORM\EntityManager::class); - -$commands = [ - $container->get(Dot\DataFixtures\Command\ExecuteFixturesCommand::class), - $container->get(Dot\DataFixtures\Command\ListFixturesCommand::class), -]; - -ConsoleRunner::run( - new SingleManagerProvider($entityManager), - $commands -); -``` +# Configuration + +## Register ConfigProvider + +After installation, register the package's ConfigProvider by adding the below line into your application config: + +`\Dot\DataFixtures\ConfigProvider::class,` + +In `doctrine.global.php` (or your custom doctrine config file) add a new key `fixtures`, in the `doctrine` array, the value should be a valid path to a folder where your fixtures can be found. + +Make sure the path is valid before proceeding to the next step. + +### Example + +```php +return [ + 'dependencies' => [ ... ], + 'doctrine' => [ + ..., + 'fixtures' => getcwd() . '/data/doctrine/fixtures', + ], +]; +``` + +## Registering commands + +The last step is to register the commands. We can register the commands to work with the default CLI that doctrine provides us. Create a new php file `bin/doctrine` (if you don't already have this file feel free to copy it from the below example) + +```php +get(\Doctrine\ORM\EntityManager::class); + +$commands = [ + $container->get(Dot\DataFixtures\Command\ExecuteFixturesCommand::class), + $container->get(Dot\DataFixtures\Command\ListFixturesCommand::class), +]; + +ConsoleRunner::run( + new SingleManagerProvider($entityManager), + $commands +); +``` diff --git a/docs/book/v1/installation.md b/docs/book/v1/installation.md index 914e886..a4bc5ec 100644 --- a/docs/book/v1/installation.md +++ b/docs/book/v1/installation.md @@ -1,7 +1,7 @@ -# Installation - -Install dotkernel/dot-data-fixtures by executing the following Composer command in your project directory: - -```shell -composer require dotkernel/dot-data-fixtures -``` +# Installation + +Install dotkernel/dot-data-fixtures by executing the following Composer command in your project directory: + +```shell +composer require dotkernel/dot-data-fixtures +``` diff --git a/docs/book/v1/usage.md b/docs/book/v1/usage.md index b31de21..44bc1eb 100644 --- a/docs/book/v1/usage.md +++ b/docs/book/v1/usage.md @@ -1,80 +1,80 @@ -# Usage - -## Commands - -### List fixtures command - -This command will list all the available fixtures, by order of execution. - -```shell -php ./bin/doctrine fixtures:list -``` - -### Execute fixtures command - -This command will execute one or all fixtures. - -To execute all the fixtures, run: - -```shell -php ./bin/doctrine fixtures:execute -``` - -To execute a specific fixture, run: - -```shell -php ./bin/doctrine fixtures:execute --class=RoleLoader -``` - -## Creating fixtures - -When creating a new fixture, we have two requirements: - -- Fixtures should be created in the folder we configured earlier, `data/doctrine/fixtures` -- Fixtures should implement `FixtureInterface` and have a `load` method. -- Create a new PHP file and copy the below code-block. - -### Example - -```php -setName('admin'); - - $userRole = new UserRole(); - $userRole->setName('user'); - - $guestRole = new UserRole(); - $guestRole->setName('guest'); - - $manager->persist($adminRole); - $manager->persist($userRole); - $manager->persist($guestRole); - - $manager->flush(); - } -} -``` - -## Ordering fixtures - -Fixtures can be ordered: - -- by order -- by dependencies - -Please refer to this link for further details on ordering fixtures : - -https://www.doctrine-project.org/projects/doctrine-data-fixtures/en/latest/how-to/fixture-ordering.html#fixture-ordering +# Usage + +## Commands + +### List fixtures command + +This command will list all the available fixtures, by order of execution. + +```shell +php ./bin/doctrine fixtures:list +``` + +### Execute fixtures command + +This command will execute one or all fixtures. + +To execute all the fixtures, run: + +```shell +php ./bin/doctrine fixtures:execute +``` + +To execute a specific fixture, run: + +```shell +php ./bin/doctrine fixtures:execute --class=RoleLoader +``` + +## Creating fixtures + +When creating a new fixture, we have two requirements: + +- Fixtures should be created in the folder we configured earlier, `data/doctrine/fixtures` +- Fixtures should implement `FixtureInterface` and have a `load` method. +- Create a new PHP file and copy the below code-block. + +### Example + +```php +setName('admin'); + + $userRole = new UserRole(); + $userRole->setName('user'); + + $guestRole = new UserRole(); + $guestRole->setName('guest'); + + $manager->persist($adminRole); + $manager->persist($userRole); + $manager->persist($guestRole); + + $manager->flush(); + } +} +``` + +## Ordering fixtures + +Fixtures can be ordered: + +- by order +- by dependencies + +Please refer to this link for further details on ordering fixtures : + +https://www.doctrine-project.org/projects/doctrine-data-fixtures/en/latest/how-to/fixture-ordering.html#fixture-ordering diff --git a/docs/book/v2/configuration.md b/docs/book/v2/configuration.md new file mode 100644 index 0000000..0a42e77 --- /dev/null +++ b/docs/book/v2/configuration.md @@ -0,0 +1,62 @@ +# Configuration + +## Register ConfigProvider + +After installation, register the package's ConfigProvider by adding the below line into your application config: + +```php +\Dot\DataFixtures\ConfigProvider::class, +``` + +In `doctrine.global.php` (or your custom doctrine config file) add a new key `fixtures` in the `doctrine` array. +The value must be the path to the folder where your fixtures can be found. +The folder is scanned recursively, so fixtures can be grouped in subfolders. + +Make sure the path is valid before proceeding to the next step. + +### Example + +The `// ...` comments stand for the rest of your existing configuration. + +```php +return [ + 'dependencies' => [ + // ... + ], + 'doctrine' => [ + // ... + 'fixtures' => getcwd() . '/data/doctrine/fixtures', + ], +]; +``` + +## Registering commands + +The last step is to register the commands. We can register the commands to work with the default CLI that doctrine provides us. Create a new php file `bin/doctrine` (if you don't already have this file feel free to copy it from the below example) + +```php +get(\Doctrine\ORM\EntityManager::class); + +$commands = [ + $container->get(Dot\DataFixtures\Command\ExecuteFixturesCommand::class), + $container->get(Dot\DataFixtures\Command\ListFixturesCommand::class), +]; + +ConsoleRunner::run( + new SingleManagerProvider($entityManager), + $commands +); +``` + +The factories only use `Psr\Container\ContainerInterface`, so they work with any PSR-11 container that accepts a factory per service, such as `laminas/laminas-servicemanager`. diff --git a/docs/book/v2/installation.md b/docs/book/v2/installation.md new file mode 100644 index 0000000..f5800f4 --- /dev/null +++ b/docs/book/v2/installation.md @@ -0,0 +1,20 @@ +# Installation + +## Requirements + +- **PHP**: 8.3, 8.4, 8.5 or 8.6 +- **doctrine/orm**: 3.x +- **doctrine/data-fixtures**: 2.x +- **symfony/console**: 7.0.3 or later, or 8.x (8.x requires PHP 8.4 or later) +- **symfony/string** (installed with `symfony/console`): 6.4.3 or later, or 7.0.3 or later +- a PSR-11 container that provides the `config` service and the `Doctrine\ORM\EntityManager` service + +## Install the package + +Install dotkernel/dot-data-fixtures by executing the following Composer command in your project directory: + +```shell +composer require dotkernel/dot-data-fixtures +``` + +Upgrading from 1.x? Read [Upgrading](upgrading.md) first. diff --git a/docs/book/v2/overview.md b/docs/book/v2/overview.md new file mode 100644 index 0000000..a4a468e --- /dev/null +++ b/docs/book/v2/overview.md @@ -0,0 +1,21 @@ +# Overview + +`dot-data-fixtures` provides a CLI interface for interacting with doctrine/data-fixtures. + +> dot-data-fixtures is a wrapper on top of [data-fixtures](https://github.com/doctrine/data-fixtures) + +Executing fixtures will append data to the tables. + +## Badges + +![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-data-fixtures) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-data-fixtures/2.0.0) + +[![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-data-fixtures)](https://github.com/dotkernel/dot-data-fixtures/issues) +[![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-data-fixtures)](https://github.com/dotkernel/dot-data-fixtures/network) +[![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-data-fixtures)](https://github.com/dotkernel/dot-data-fixtures/stargazers) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-data-fixtures)](https://github.com/dotkernel/dot-data-fixtures/blob/2.0/LICENSE) + +[![Build Static](https://github.com/dotkernel/dot-data-fixtures/actions/workflows/continuous-integration.yml/badge.svg?branch=2.0)](https://github.com/dotkernel/dot-data-fixtures/actions/workflows/continuous-integration.yml) +[![codecov](https://codecov.io/gh/dotkernel/dot-data-fixtures/graph/badge.svg?token=PGOXZOZAB0)](https://codecov.io/gh/dotkernel/dot-data-fixtures) +[![PHPStan](https://github.com/dotkernel/dot-data-fixtures/actions/workflows/static-analysis.yml/badge.svg?branch=2.0)](https://github.com/dotkernel/dot-data-fixtures/actions/workflows/static-analysis.yml) diff --git a/docs/book/v2/upgrading.md b/docs/book/v2/upgrading.md new file mode 100644 index 0000000..fa64e1d --- /dev/null +++ b/docs/book/v2/upgrading.md @@ -0,0 +1,52 @@ +# Upgrading from 1.x to 2.0 + +Version 2.0 fixes the `fixtures:list` output, makes the package work with Symfony Console 8, and hardens the `--class` option. Most applications only need to update the version constraint: + +```shell +composer require dotkernel/dot-data-fixtures:^2.0 +``` + +## Changes that can break your code + +| Change | Symptom | Fix | +| --- | --- | --- | +| PHP 8.2 is no longer supported | Composer refuses to install 2.0 on PHP 8.2 | Upgrade to PHP 8.3 or later, or stay on 1.x | +| `symfony/console` 7.0.0 to 7.0.2 and `symfony/string` 6.4.0 to 6.4.2 and 7.0.0 to 7.0.2 are no longer allowed | Composer refuses to install 2.0 while one of them is pinned | Update them (`composer update symfony/console symfony/string`) | +| Command names and descriptions come from `#[AsCommand]` | Code that calls `Command::getDefaultName()` fails on Symfony Console 8, where that method was removed | Use the `NAME` and `DESCRIPTION` constants | +| `--class` requires a value | `fixtures:execute --class` without a value prints `The "--class" option requires a value.` | Pass a fixture name, or omit the option to run all fixtures | +| `--class` is a path relative to the fixtures folder | Fixtures in subfolders need the subfolder, for example `--class=User/UserLoader` | Use the command that `fixtures:list` prints | +| `--class` cannot point outside the fixtures folder | `--class=../Other/File` used to load that file; it is now refused | Move the fixture into the fixtures folder | +| A missing fixture returns exit code `1` | No exception and stack trace; an error line is printed instead | Check the exit code | +| The `--class` default is `null` instead of `false` | Only code that inspects the command's input definition sees it | Compare with `null` | + +## Before and after + +Reading the command name in a subclass or a script: + +```php +// 1.x +$name = ExecuteFixturesCommand::getDefaultName(); // null on Symfony Console 7.3+, fatal error on 8.x +``` + +```php +// 2.0 +$name = ExecuteFixturesCommand::NAME; // 'fixtures:execute' +``` + +Executing a fixture from a subfolder: + +```shell +# 1.x: fixtures:list suggested this, and it failed +php ./bin/doctrine fixtures:execute --class=UserLoader + +# 2.0 +php ./bin/doctrine fixtures:execute --class=User/UserLoader +``` + +## Unchanged + +- The configuration key (`doctrine.fixtures`) and the `ConfigProvider` +- The service keys `ExecuteFixturesCommand::class` and `ListFixturesCommand::class`, and the container key `Doctrine\ORM\EntityManager` +- The command names `fixtures:execute` and `fixtures:list` +- The protected static `$defaultName` property on both commands, with the same name and visibility as in 1.x, so subclasses that read or redeclare it keep working. Symfony Console 7 and 8 no longer read it; prefer the `NAME` constants in new code +- Fixtures are appended; nothing is purged diff --git a/docs/book/v2/usage.md b/docs/book/v2/usage.md new file mode 100644 index 0000000..9ca0f10 --- /dev/null +++ b/docs/book/v2/usage.md @@ -0,0 +1,95 @@ +# Usage + +## Commands + +### List fixtures command + +This command will list all the available fixtures, by order of execution. + +```shell +php ./bin/doctrine fixtures:list +``` + +For each fixture it shows the class name, the command that executes only that fixture, and when its file was last changed (in UTC). + +### Execute fixtures command + +This command will execute one or all fixtures. +Executing fixtures will **append** data to the tables: nothing is purged first. + +To execute all the fixtures, run: + +```shell +php ./bin/doctrine fixtures:execute +``` + +To execute a specific fixture, pass its path relative to the fixtures folder, without `.php`: + +```shell +php ./bin/doctrine fixtures:execute --class=RoleLoader +``` + +A fixture in a subfolder, for example `data/doctrine/fixtures/User/UserLoader.php`, is executed with: + +```shell +php ./bin/doctrine fixtures:execute --class=User/UserLoader +``` + +`fixtures:list` prints this exact command for every fixture. + +`--class` must have a value. If the fixture does not exist, or the path points outside the fixtures folder, the command prints an error and exits with code `1`. + +## Creating fixtures + +When creating a new fixture, we have two requirements: + +- Fixtures should be created in the folder we configured earlier, `data/doctrine/fixtures`, or in a subfolder of it. +- Fixtures should implement `FixtureInterface` and have a `load` method. + +Create a new PHP file and copy the below code-block. + +### Example + +```php +setName('admin'); + + $userRole = new UserRole(); + $userRole->setName('user'); + + $guestRole = new UserRole(); + $guestRole->setName('guest'); + + $manager->persist($adminRole); + $manager->persist($userRole); + $manager->persist($guestRole); + + $manager->flush(); + } +} +``` + +## Ordering fixtures + +Fixtures can be ordered: + +- by order +- by dependencies + +Please refer to this link for further details on ordering fixtures: + +https://www.doctrine-project.org/projects/doctrine-data-fixtures/en/latest/how-to/fixture-ordering.html#fixture-ordering diff --git a/mkdocs.yml b/mkdocs.yml index 8a9c1ee..220783b 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -2,11 +2,18 @@ docs_dir: docs/book site_dir: docs/html extra: project: Packages - current_version: v1 + current_version: v2 versions: + - v2 - v1 nav: - Home: index.md + - v2: + - Overview: v2/overview.md + - Installation: v2/installation.md + - Configuration: v2/configuration.md + - Usage: v2/usage.md + - Upgrading: v2/upgrading.md - v1: - Overview: v1/overview.md - Installation: v1/installation.md diff --git a/phpstan.neon b/phpstan.neon index 349be25..08d6acd 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,7 +1,7 @@ includes: - vendor/phpstan/phpstan-phpunit/extension.neon parameters: - level: 5 + level: 8 paths: - src - test diff --git a/phpunit.xml b/phpunit.xml index 054b7b8..4694f45 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,14 +1,30 @@ - + - ./test + test - - + - ./src + src diff --git a/src/Command/ExecuteFixturesCommand.php b/src/Command/ExecuteFixturesCommand.php index 39ead36..d861ed0 100644 --- a/src/Command/ExecuteFixturesCommand.php +++ b/src/Command/ExecuteFixturesCommand.php @@ -6,19 +6,31 @@ use Doctrine\Common\DataFixtures\Executor\ORMExecutor; use Doctrine\Common\DataFixtures\Loader; +use InvalidArgumentException; +use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; +use function is_string; +use function realpath; use function sprintf; +use function str_starts_with; use const DIRECTORY_SEPARATOR; +#[AsCommand(name: self::NAME, description: self::DESCRIPTION)] class ExecuteFixturesCommand extends Command { - /** @var string */ - protected static $defaultName = 'fixtures:execute'; + public const NAME = 'fixtures:execute'; + public const DESCRIPTION = 'Executes one or multiple fixtures.'; + + /** + * Kept from 1.x for subclasses that read it. Symfony Console 7 and 8 no longer read it; + * the name comes from #[AsCommand] and the constructor. + */ + protected static string $defaultName = self::NAME; public function __construct( private readonly Loader $loader, @@ -30,33 +42,40 @@ public function __construct( protected function configure(): void { - $this->setName(self::$defaultName) - ->setDescription('Executes one or multiple fixtures.') + $this + ->setName(self::$defaultName) + ->setDescription(self::DESCRIPTION) ->addOption( 'class', null, - InputOption::VALUE_OPTIONAL, - 'Execute a specific fixture.', - false + InputOption::VALUE_REQUIRED, + 'Execute a specific fixture, given by its path relative to the fixtures directory, without ".php".' ); } protected function execute(InputInterface $input, OutputInterface $output): int { - if ($input->getOption('class') === false) { - $this->loader->loadFromDirectory($this->path); - } else { - $this->loader->loadFromFile($this->path . DIRECTORY_SEPARATOR . $input->getOption('class') . '.php'); - } + $class = $input->getOption('class'); - $fixtures = $this->loader->getFixtures(); + try { + if (is_string($class)) { + $this->loader->loadFromFile($this->resolveFixtureFile($class)); + } else { + $this->loader->loadFromDirectory($this->path); + } + } catch (InvalidArgumentException $exception) { + $output->writeln(sprintf('%s', $exception->getMessage())); - $this->executor->execute($fixtures, true); + return Command::FAILURE; + } + $fixtures = $this->loader->getFixtures(); foreach ($fixtures as $fixture) { - $output->writeln(sprintf('Executing %s ', $fixture::class)); + $output->writeln(sprintf('Executing %s', $fixture::class)); } + $this->executor->execute($fixtures, true); + $output->writeln("Fixtures have been loaded."); $output->write(" .'' ._.-.___.' (`\ @@ -65,6 +84,29 @@ protected function execute(InputInterface $input, OutputInterface $output): int ' <' `\ ._/'\ ` \ \ "); + return Command::SUCCESS; } + + /** + * Resolves a fixture name relative to the fixtures directory and refuses any file outside it. + * + * @throws InvalidArgumentException + */ + private function resolveFixtureFile(string $class): string + { + $directory = realpath($this->path); + $file = realpath($this->path . DIRECTORY_SEPARATOR . $class . '.php'); + if ( + ! is_string($directory) + || ! is_string($file) + || ! str_starts_with($file, $directory . DIRECTORY_SEPARATOR) + ) { + throw new InvalidArgumentException( + sprintf('Fixture "%s" was not found in "%s".', $class, $this->path) + ); + } + + return $file; + } } diff --git a/src/Command/ListFixturesCommand.php b/src/Command/ListFixturesCommand.php index 123e142..c9ee589 100644 --- a/src/Command/ListFixturesCommand.php +++ b/src/Command/ListFixturesCommand.php @@ -7,17 +7,33 @@ use DateTimeImmutable; use Doctrine\Common\DataFixtures\Loader; use ReflectionClass; +use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use function filemtime; +use function is_string; +use function realpath; +use function str_replace; +use function str_starts_with; +use function strlen; +use function substr; +use const DIRECTORY_SEPARATOR; + +#[AsCommand(name: self::NAME, description: self::DESCRIPTION)] class ListFixturesCommand extends Command { - /** @var string */ - protected static $defaultName = 'fixtures:list'; + public const NAME = 'fixtures:list'; + public const DESCRIPTION = 'List all available fixtures.'; + + /** + * Kept from 1.x for subclasses that read it. Symfony Console 7 and 8 no longer read it; + * the name comes from #[AsCommand] and the constructor. + */ + protected static string $defaultName = self::NAME; public function __construct( private readonly Loader $loader, @@ -28,32 +44,39 @@ public function __construct( protected function configure(): void { - $this->setName(self::$defaultName)->setDescription('List all available fixtures.'); + $this + ->setName(self::$defaultName) + ->setDescription(self::DESCRIPTION); } protected function execute(InputInterface $input, OutputInterface $output): int { $this->loader->loadFromDirectory($this->path); - $rows = []; - $commandName = ExecuteFixturesCommand::getDefaultName(); - + $directory = (string) realpath($this->path) . DIRECTORY_SEPARATOR; + $rows = []; foreach ($this->loader->getFixtures() as $fixture) { $reflectionClass = new ReflectionClass($fixture); - $lastUpdatedAt = DateTimeImmutable::createFromFormat( - 'U', - (string) filemtime($reflectionClass->getFileName()) - ); - - $rows[] = [ - 'namespace' => $reflectionClass->getName(), - 'command' => $commandName . ' --class=' . $reflectionClass->getShortName(), - 'last_updated_at' => $lastUpdatedAt->format('Y-m-d H:i:s'), - ]; + $fileName = $reflectionClass->getFileName(); + $command = ''; + $lastUpdatedAt = ''; + if (is_string($fileName)) { + if (str_starts_with($fileName, $directory)) { + $relative = substr($fileName, strlen($directory), -strlen('.php')); + $relative = str_replace(DIRECTORY_SEPARATOR, '/', $relative); + $command = ExecuteFixturesCommand::NAME . ' --class=' . $relative; + } + + $modified = filemtime($fileName); + if ($modified !== false) { + $lastUpdatedAt = (new DateTimeImmutable('@' . $modified))->format('Y-m-d H:i:s'); + } + } + + $rows[] = [$reflectionClass->getName(), $command, $lastUpdatedAt]; } - $table = new Table($output); - $table + (new Table($output)) ->setHeaders(['Namespace', 'Run fixture command', 'Last updated at']) ->setRows($rows) ->render(); diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index b38332a..35f298d 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -11,6 +11,9 @@ class ConfigProvider { + /** + * @return array{dependencies: array{factories: array}} + */ public function __invoke(): array { return [ @@ -18,6 +21,9 @@ public function __invoke(): array ]; } + /** + * @return array{factories: array} + */ public function getDependencies(): array { return [ diff --git a/src/Factory/ExecuteFixturesCommandFactory.php b/src/Factory/ExecuteFixturesCommandFactory.php index 58117c2..f2dddd4 100644 --- a/src/Factory/ExecuteFixturesCommandFactory.php +++ b/src/Factory/ExecuteFixturesCommandFactory.php @@ -6,15 +6,17 @@ use Doctrine\Common\DataFixtures\Executor\ORMExecutor; use Doctrine\Common\DataFixtures\Loader; -use Doctrine\Common\DataFixtures\Purger\ORMPurger; use Doctrine\ORM\EntityManager; +use Doctrine\ORM\EntityManagerInterface; use Dot\DataFixtures\Command\ExecuteFixturesCommand; use Dot\DataFixtures\Exception\NotFoundException; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use function is_array; use function is_string; +use function sprintf; class ExecuteFixturesCommandFactory { @@ -29,17 +31,21 @@ public function __invoke(ContainerInterface $container): ExecuteFixturesCommand throw new NotFoundException('EntityManager not found.'); } - $path = $container->get('config')['doctrine']['fixtures'] ?? null; + $config = $container->get('config'); + $path = is_array($config) && is_array($config['doctrine'] ?? null) + ? $config['doctrine']['fixtures'] ?? null + : null; if (! is_string($path)) { throw new NotFoundException('Key `fixtures` not found in doctrine configuration.'); } $entityManager = $container->get(EntityManager::class); + if (! $entityManager instanceof EntityManagerInterface) { + throw new NotFoundException( + sprintf('Service `%s` is not an instance of `%s`.', EntityManager::class, EntityManagerInterface::class) + ); + } - return new ExecuteFixturesCommand( - new Loader(), - new ORMExecutor($entityManager, new ORMPurger($entityManager)), - $path - ); + return new ExecuteFixturesCommand(new Loader(), new ORMExecutor($entityManager), $path); } } diff --git a/src/Factory/ListFixturesCommandFactory.php b/src/Factory/ListFixturesCommandFactory.php index b3ecf96..8489832 100644 --- a/src/Factory/ListFixturesCommandFactory.php +++ b/src/Factory/ListFixturesCommandFactory.php @@ -11,6 +11,7 @@ use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use function is_array; use function is_string; class ListFixturesCommandFactory @@ -22,14 +23,14 @@ class ListFixturesCommandFactory */ public function __invoke(ContainerInterface $container): ListFixturesCommand { - $path = $container->get('config')['doctrine']['fixtures'] ?? null; + $config = $container->get('config'); + $path = is_array($config) && is_array($config['doctrine'] ?? null) + ? $config['doctrine']['fixtures'] ?? null + : null; if (! is_string($path)) { throw new NotFoundException('Key `fixtures` not found in doctrine configuration.'); } - return new ListFixturesCommand( - new Loader(), - $path - ); + return new ListFixturesCommand(new Loader(), $path); } } diff --git a/test/Command/ExecuteFixturesCommandTest.php b/test/Command/ExecuteFixturesCommandTest.php index 9828b6a..95ac932 100644 --- a/test/Command/ExecuteFixturesCommandTest.php +++ b/test/Command/ExecuteFixturesCommandTest.php @@ -6,91 +6,153 @@ use Doctrine\Common\DataFixtures\Executor\ORMExecutor; use Doctrine\Common\DataFixtures\Loader; -use Doctrine\Common\EventManager; -use Doctrine\DBAL\Configuration; -use Doctrine\DBAL\Connection; use Doctrine\ORM\EntityManager; use Dot\DataFixtures\Command\ExecuteFixturesCommand; -use PHPUnit\Framework\MockObject\Exception; +use DotTest\DataFixtures\Fixtures\Data\RoleFixture; +use DotTest\DataFixtures\Fixtures\Data\Sub\NestedFixture; +use DotTest\DataFixtures\Fixtures\EntityManagerFactory; +use DotTest\DataFixtures\Fixtures\Legacy\LegacyExecuteFixturesCommand; +use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; use ReflectionClass; -use ReflectionException; -use ReflectionMethod; +use ReflectionProperty; +use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Exception\RuntimeException; use Symfony\Component\Console\Input\ArgvInput; use Symfony\Component\Console\Output\BufferedOutput; +use Symfony\Component\Console\Tester\CommandTester; -use function getcwd; +use function get_included_files; +use function realpath; +#[CoversClass(ExecuteFixturesCommand::class)] class ExecuteFixturesCommandTest extends TestCase { - /** - * @throws Exception - * @throws ReflectionException - */ - public function testWillCreateCommand(): void + private EntityManager $entityManager; + private ExecuteFixturesCommand $command; + + protected function setUp(): void + { + $this->entityManager = EntityManagerFactory::create(); + $this->command = new ExecuteFixturesCommand( + new Loader(), + new ORMExecutor($this->entityManager), + EntityManagerFactory::FIXTURES_PATH + ); + } + + public function testNameAndDescriptionComeFromAttribute(): void + { + $attributes = (new ReflectionClass(ExecuteFixturesCommand::class))->getAttributes(AsCommand::class); + + $this->assertCount(1, $attributes); + $this->assertSame(ExecuteFixturesCommand::NAME, $attributes[0]->newInstance()->name); + $this->assertSame('fixtures:execute', $this->command->getName()); + $this->assertSame('Executes one or multiple fixtures.', $this->command->getDescription()); + } + + public function testDefaultNamePropertyKeepsItsVersion1Shape(): void + { + $property = new ReflectionProperty(ExecuteFixturesCommand::class, 'defaultName'); + + $this->assertTrue($property->isProtected()); + $this->assertTrue($property->isStatic()); + $this->assertFalse($property->hasType()); + $this->assertSame(ExecuteFixturesCommand::NAME, $property->getValue()); + $this->assertSame(ExecuteFixturesCommand::DESCRIPTION, $this->command->getDescription()); + } + + public function testVersion1SubclassRedeclaringDefaultNameStillWorks(): void + { + $command = new LegacyExecuteFixturesCommand( + new Loader(), + new ORMExecutor($this->entityManager), + EntityManagerFactory::FIXTURES_PATH + ); + + $this->assertSame( + 'app:fixtures:execute', + (new ReflectionProperty(LegacyExecuteFixturesCommand::class, 'defaultName'))->getValue() + ); + // As in 1.x, the parent uses self::$defaultName, so the command keeps its name. + $this->assertSame(ExecuteFixturesCommand::NAME, $command->getName()); + $this->assertSame(Command::SUCCESS, (new CommandTester($command))->execute(['--class' => 'RoleFixture'])); + } + + public function testClassOptionRequiresValueAndHasNoDefault(): void { - $entityManager = $this->createMock(EntityManager::class); - $loader = $this->createMock(Loader::class); - $path = getcwd() . '/data/doctrine/fixtures'; - $executor = new ReflectionClass(ORMExecutor::class); - $executor = $executor->newInstance($entityManager); - - $command = new ExecuteFixturesCommand($loader, $executor, $path); - $this->assertContainsOnlyInstancesOf(ExecuteFixturesCommand::class, [$command]); + $option = $this->command->getDefinition()->getOption('class'); + + $this->assertTrue($option->isValueRequired()); + $this->assertNull($option->getShortcut()); + $this->assertNull($option->getDefault()); } - /** - * @throws Exception - * @throws ReflectionException - */ - public function testWillExecuteCommand(): void + public function testExecuteAllInsertsEveryFixture(): void { - $configuration = $this->createMock(Configuration::class); - $connection = $this->createMock(Connection::class); - $entityManager = $this->createMock(EntityManager::class); - $eventManager = $this->createMock(EventManager::class); - $loader = $this->createMock(Loader::class); - $executor = new ReflectionClass(ORMExecutor::class); - $executor = $executor->newInstance($entityManager); - $connection->method('getConfiguration')->willReturn($configuration); - $entityManager->method('getConnection')->willReturn($connection); - $entityManager->method('getEventManager')->willReturn($eventManager); - $loader->method('getFixtures')->willReturnMap([ - [ - [], - ], - ]); - $path = getcwd() . '/data/doctrine/fixtures'; - - $command = new ExecuteFixturesCommand($loader, $executor, $path); - $reflection = new ReflectionMethod(ExecuteFixturesCommand::class, 'execute'); - $result = $reflection->invoke($command, new ArgvInput([], $command->getDefinition()), new BufferedOutput()); - $this->assertSame($result, Command::SUCCESS); + $tester = new CommandTester($this->command); + + $this->assertSame(Command::SUCCESS, $tester->execute([])); + $this->assertEqualsCanonicalizing( + ['admin', 'nested'], + EntityManagerFactory::roleNames($this->entityManager) + ); + $this->assertStringContainsString('Executing ' . RoleFixture::class, $tester->getDisplay()); + $this->assertStringContainsString('Executing ' . NestedFixture::class, $tester->getDisplay()); + $this->assertStringContainsString('Fixtures have been loaded.', $tester->getDisplay()); } - /** - * @throws Exception - * @throws ReflectionException - */ - public function testConfigure(): void + public function testExecuteOneInsertsOnlyThatFixture(): void { - $entityManager = $this->createMock(EntityManager::class); - $loader = $this->createMock(Loader::class); - $executor = new ReflectionClass(ORMExecutor::class); - $executor = $executor->newInstance($entityManager); - - $path = getcwd() . '/data/doctrine/fixtures'; - $command = new ExecuteFixturesCommand($loader, $executor, $path); - $defaultName = $command->getName(); - $description = $command->getDescription(); - $options = $command->getDefinition()->getOption('class'); - - $this->assertSame('fixtures:execute', $defaultName); - $this->assertSame('Executes one or multiple fixtures.', $description); - $this->assertSame('class', $options->getName()); - $this->assertEmpty($options->getShortcut()); - $this->assertFalse($options->getDefault()); - $this->assertSame('Execute a specific fixture.', $options->getDescription()); + $tester = new CommandTester($this->command); + + $this->assertSame(Command::SUCCESS, $tester->execute(['--class' => 'RoleFixture'])); + $this->assertSame(['admin'], EntityManagerFactory::roleNames($this->entityManager)); + } + + public function testExecuteNestedFixtureByRelativePath(): void + { + $tester = new CommandTester($this->command); + + $this->assertSame(Command::SUCCESS, $tester->execute(['--class' => 'Sub/NestedFixture'])); + $this->assertSame(['nested'], EntityManagerFactory::roleNames($this->entityManager)); + } + + public function testExecuteAppendsOnRepeatedRuns(): void + { + $tester = new CommandTester($this->command); + $tester->execute(['--class' => 'RoleFixture']); + $tester->execute(['--class' => 'RoleFixture']); + + $this->assertSame(['admin', 'admin'], EntityManagerFactory::roleNames($this->entityManager)); + } + + public function testClassOptionWithoutValueIsRejected(): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('The "--class" option requires a value.'); + + $this->command->run(new ArgvInput(['bin/doctrine', '--class']), new BufferedOutput()); + } + + public function testMissingFixtureReturnsFailure(): void + { + $tester = new CommandTester($this->command); + + $this->assertSame(Command::FAILURE, $tester->execute(['--class' => 'MissingFixture'])); + $this->assertStringContainsString('Fixture "MissingFixture" was not found', $tester->getDisplay()); + $this->assertSame([], EntityManagerFactory::roleNames($this->entityManager)); + } + + public function testFixtureOutsideFixturesDirectoryIsRefused(): void + { + $outside = realpath(__DIR__ . '/../Fixtures/Outside/OutsideFixture.php'); + $tester = new CommandTester($this->command); + + $this->assertSame(Command::FAILURE, $tester->execute(['--class' => '../Outside/OutsideFixture'])); + $this->assertStringContainsString('was not found', $tester->getDisplay()); + $this->assertSame([], EntityManagerFactory::roleNames($this->entityManager)); + $this->assertNotContains($outside, get_included_files()); } } diff --git a/test/Command/ListFixturesCommandTest.php b/test/Command/ListFixturesCommandTest.php index 4527ea9..9e70507 100644 --- a/test/Command/ListFixturesCommandTest.php +++ b/test/Command/ListFixturesCommandTest.php @@ -6,65 +6,76 @@ use Doctrine\Common\DataFixtures\Loader; use Dot\DataFixtures\Command\ListFixturesCommand; -use PHPUnit\Framework\MockObject\Exception; +use DotTest\DataFixtures\Fixtures\Data\RoleFixture; +use DotTest\DataFixtures\Fixtures\Data\Sub\NestedFixture; +use DotTest\DataFixtures\Fixtures\EntityManagerFactory; +use DotTest\DataFixtures\Fixtures\Legacy\LegacyListFixturesCommand; +use InvalidArgumentException; +use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; -use ReflectionException; -use ReflectionMethod; +use ReflectionClass; +use ReflectionProperty; +use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Input\ArgvInput; -use Symfony\Component\Console\Output\BufferedOutput; - -use function getcwd; +use Symfony\Component\Console\Tester\CommandTester; +#[CoversClass(ListFixturesCommand::class)] class ListFixturesCommandTest extends TestCase { - /** - * @throws Exception - */ - public function testWillCreateCommand(): void + public function testNameAndDescriptionComeFromAttribute(): void { - $loader = $this->createMock(Loader::class); - $path = getcwd() . '/data/doctrine/fixtures'; - $command = new ListFixturesCommand($loader, $path); - $this->assertContainsOnlyInstancesOf(ListFixturesCommand::class, [$command]); + $command = new ListFixturesCommand(new Loader(), EntityManagerFactory::FIXTURES_PATH); + $attributes = (new ReflectionClass(ListFixturesCommand::class))->getAttributes(AsCommand::class); + + $this->assertCount(1, $attributes); + $this->assertSame(ListFixturesCommand::NAME, $attributes[0]->newInstance()->name); + $this->assertSame('fixtures:list', $command->getName()); + $this->assertSame('List all available fixtures.', $command->getDescription()); } - /** - * @throws Exception - * @throws ReflectionException - */ - public function testWillExecuteCommand(): void + public function testDefaultNamePropertyKeepsItsVersion1Shape(): void { - $loader = $this->createMock(Loader::class); - $loader->method('getFixtures')->willReturnMap([ - [ - [], - ], - ]); - $path = getcwd() . '/data/doctrine/fixtures'; + $property = new ReflectionProperty(ListFixturesCommand::class, 'defaultName'); + + $this->assertTrue($property->isProtected()); + $this->assertTrue($property->isStatic()); + $this->assertFalse($property->hasType()); + $this->assertSame(ListFixturesCommand::NAME, $property->getValue()); + } - $command = new ListFixturesCommand($loader, $path); - $reflection = new ReflectionMethod(ListFixturesCommand::class, 'execute'); + public function testVersion1SubclassRedeclaringDefaultNameStillWorks(): void + { + $command = new LegacyListFixturesCommand(new Loader(), EntityManagerFactory::FIXTURES_PATH); - $result = $reflection->invoke( - $command, - new ArgvInput(), - new BufferedOutput() + $this->assertSame( + 'app:fixtures:list', + (new ReflectionProperty(LegacyListFixturesCommand::class, 'defaultName'))->getValue() ); - $this->assertSame($result, Command::SUCCESS); + // As in 1.x, the parent uses self::$defaultName, so the command keeps its name. + $this->assertSame(ListFixturesCommand::NAME, $command->getName()); + $this->assertSame(ListFixturesCommand::DESCRIPTION, $command->getDescription()); + $this->assertSame(Command::SUCCESS, (new CommandTester($command))->execute([])); } - /** - * @throws Exception - */ - public function testFunctions(): void + public function testListsEveryFixtureWithARunnableCommand(): void { - $loader = $this->createMock(Loader::class); - $path = getcwd() . '/data/doctrine/fixtures'; - $command = new ListFixturesCommand($loader, $path); - $defaultName = $command->getName(); - $description = $command->getDescription(); - $this->assertSame('fixtures:list', $defaultName); - $this->assertSame('List all available fixtures.', $description); + $tester = new CommandTester(new ListFixturesCommand(new Loader(), EntityManagerFactory::FIXTURES_PATH)); + + $this->assertSame(Command::SUCCESS, $tester->execute([])); + + $display = $tester->getDisplay(); + $this->assertStringContainsString(RoleFixture::class, $display); + $this->assertStringContainsString(NestedFixture::class, $display); + $this->assertStringContainsString('fixtures:execute --class=RoleFixture ', $display); + $this->assertStringContainsString('fixtures:execute --class=Sub/NestedFixture ', $display); + $this->assertMatchesRegularExpression('/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/', $display); + } + + public function testMissingFixturesDirectoryThrows(): void + { + $tester = new CommandTester(new ListFixturesCommand(new Loader(), __DIR__ . '/does-not-exist')); + + $this->expectException(InvalidArgumentException::class); + $tester->execute([]); } } diff --git a/test/ConfigProviderTest.php b/test/ConfigProviderTest.php index a9d7c23..b1ab7c6 100644 --- a/test/ConfigProviderTest.php +++ b/test/ConfigProviderTest.php @@ -9,30 +9,29 @@ use Dot\DataFixtures\ConfigProvider; use Dot\DataFixtures\Factory\ExecuteFixturesCommandFactory; use Dot\DataFixtures\Factory\ListFixturesCommandFactory; +use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; +#[CoversClass(ConfigProvider::class)] class ConfigProviderTest extends TestCase { - protected array $config; - - protected function setup(): void + public function testInvokeReturnsDependencies(): void { - $this->config = (new ConfigProvider())(); - } + $provider = new ConfigProvider(); - public function testHasDependencies(): void - { - $this->assertArrayHasKey('dependencies', $this->config); + $this->assertSame(['dependencies' => $provider->getDependencies()], $provider()); } - public function testDependenciesHasFactories(): void + public function testRegistersFactoryForEachCommand(): void { - $this->assertArrayHasKey('factories', $this->config['dependencies']); - - $factories = $this->config['dependencies']['factories']; - $this->assertArrayHasKey(ExecuteFixturesCommand::class, $factories); - $this->assertSame(ExecuteFixturesCommandFactory::class, $factories[ExecuteFixturesCommand::class]); - $this->assertArrayHasKey(ListFixturesCommand::class, $factories); - $this->assertSame(ListFixturesCommandFactory::class, $factories[ListFixturesCommand::class]); + $this->assertSame( + [ + 'factories' => [ + ExecuteFixturesCommand::class => ExecuteFixturesCommandFactory::class, + ListFixturesCommand::class => ListFixturesCommandFactory::class, + ], + ], + (new ConfigProvider())->getDependencies() + ); } } diff --git a/test/Exception/NotFoundExceptionTest.php b/test/Exception/NotFoundExceptionTest.php index bcc778c..7e2778b 100644 --- a/test/Exception/NotFoundExceptionTest.php +++ b/test/Exception/NotFoundExceptionTest.php @@ -5,15 +5,16 @@ namespace DotTest\DataFixtures\Exception; use Dot\DataFixtures\Exception\NotFoundException; -use Exception; +use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; +#[CoversClass(NotFoundException::class)] class NotFoundExceptionTest extends TestCase { - public function testCreate(): void + public function testKeepsMessage(): void { - $exception = new NotFoundException(); - $this->assertContainsOnlyInstancesOf(NotFoundException::class, [$exception]); - $this->assertContainsOnlyInstancesOf(Exception::class, [$exception]); + $exception = new NotFoundException('message'); + + $this->assertSame('message', $exception->getMessage()); } } diff --git a/test/Factory/ExecuteFixturesCommandFactoryTest.php b/test/Factory/ExecuteFixturesCommandFactoryTest.php index 50648cc..6a4a26f 100644 --- a/test/Factory/ExecuteFixturesCommandFactoryTest.php +++ b/test/Factory/ExecuteFixturesCommandFactoryTest.php @@ -4,99 +4,90 @@ namespace DotTest\DataFixtures\Factory; -use Doctrine\Common\EventManager; -use Doctrine\DBAL\Configuration; -use Doctrine\DBAL\Connection; use Doctrine\ORM\EntityManager; -use Dot\DataFixtures\Command\ExecuteFixturesCommand; use Dot\DataFixtures\Exception\NotFoundException; use Dot\DataFixtures\Factory\ExecuteFixturesCommandFactory; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\MockObject\MockObject; +use DotTest\DataFixtures\Fixtures\Container; +use DotTest\DataFixtures\Fixtures\EntityManagerFactory; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use stdClass; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Tester\CommandTester; -use function getcwd; - +#[CoversClass(ExecuteFixturesCommandFactory::class)] class ExecuteFixturesCommandFactoryTest extends TestCase { - protected ContainerInterface|MockObject $container; - - /** - * @throws Exception - */ - public function setUp(): void - { - $this->container = $this->createMock(ContainerInterface::class); - } - - /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundException - * @throws NotFoundExceptionInterface - */ public function testWillNotCreateServiceWithoutEntityManager(): void { - $this->container->expects($this->once()) - ->method('has') - ->with(EntityManager::class) - ->willReturn(false); + $container = new Container([ + 'config' => ['doctrine' => ['fixtures' => EntityManagerFactory::FIXTURES_PATH]], + ]); + $this->expectException(NotFoundException::class); $this->expectExceptionMessage('EntityManager not found.'); - (new ExecuteFixturesCommandFactory())($this->container); + (new ExecuteFixturesCommandFactory())($container); } - /** - * @throws ContainerExceptionInterface - * @throws NotFoundException - * @throws NotFoundExceptionInterface - */ - public function testWillNotCreateServiceWithoutPath(): void + public function testWillNotCreateServiceWithoutConfigService(): void { - $this->container->method('has')->willReturnMap([ - [EntityManager::class, true], - ['config', true], + $container = new Container([EntityManager::class => EntityManagerFactory::create()]); + + $this->expectException(NotFoundExceptionInterface::class); + (new ExecuteFixturesCommandFactory())($container); + } + + #[DataProvider('invalidConfigProvider')] + public function testWillNotCreateServiceWithoutFixturesPath(mixed $config): void + { + $container = new Container([ + EntityManager::class => EntityManagerFactory::create(), + 'config' => $config, ]); - $this->container->method('get') - ->with('config') - ->willReturn(null); + $this->expectException(NotFoundException::class); $this->expectExceptionMessage('Key `fixtures` not found in doctrine configuration.'); - (new ExecuteFixturesCommandFactory())($this->container); + (new ExecuteFixturesCommandFactory())($container); } /** - * @throws ContainerExceptionInterface - * @throws Exception - * @throws NotFoundException - * @throws NotFoundExceptionInterface + * @return iterable */ - public function testPath(): void + public static function invalidConfigProvider(): iterable { - $configuration = $this->createMock(Configuration::class); - $connection = $this->createMock(Connection::class); - $entityManager = $this->createMock(EntityManager::class); - $eventManager = $this->createMock(EventManager::class); - $connection->method('getConfiguration')->willReturn($configuration); - $entityManager->method('getConnection')->willReturn($connection); - $entityManager->method('getEventManager')->willReturn($eventManager); + yield 'config is null' => [null]; + yield 'config is a string' => ['config']; + yield 'no doctrine key' => [[]]; + yield 'doctrine is a string' => [['doctrine' => 'doctrine']]; + yield 'no fixtures key' => [['doctrine' => []]]; + yield 'fixtures is not a string' => [['doctrine' => ['fixtures' => 123]]]; + } - $this->container->method('has')->willReturnMap([ - [EntityManager::class, true], - ['config', true], + public function testWillNotCreateServiceWithWrongEntityManagerType(): void + { + $container = new Container([ + EntityManager::class => new stdClass(), + 'config' => ['doctrine' => ['fixtures' => EntityManagerFactory::FIXTURES_PATH]], ]); - $this->container->method('get')->willReturnMap([ - [EntityManager::class, $entityManager], - ['config', ['doctrine' => ['fixtures' => getcwd() . '/data/doctrine/fixtures']]], + $this->expectException(NotFoundException::class); + $this->expectExceptionMessage('is not an instance of `Doctrine\ORM\EntityManagerInterface`'); + (new ExecuteFixturesCommandFactory())($container); + } + + public function testCreatesCommandThatExecutesConfiguredFixtures(): void + { + $entityManager = EntityManagerFactory::create(); + $container = new Container([ + EntityManager::class => $entityManager, + 'config' => ['doctrine' => ['fixtures' => EntityManagerFactory::FIXTURES_PATH]], ]); - $factory = (new ExecuteFixturesCommandFactory())($this->container); - $this->assertContainsOnlyInstancesOf(ExecuteFixturesCommand::class, [$factory]); - $path = $this->container->get('config')['doctrine']['fixtures']; - $this->assertSame(getcwd() . '/data/doctrine/fixtures', $path); + $tester = new CommandTester((new ExecuteFixturesCommandFactory())($container)); + + $this->assertSame(Command::SUCCESS, $tester->execute(['--class' => 'RoleFixture'])); + $this->assertSame(['admin'], EntityManagerFactory::roleNames($entityManager)); } } diff --git a/test/Factory/ListFixturesCommandFactoryTest.php b/test/Factory/ListFixturesCommandFactoryTest.php index 7a076c5..fc7eadd 100644 --- a/test/Factory/ListFixturesCommandFactoryTest.php +++ b/test/Factory/ListFixturesCommandFactoryTest.php @@ -4,60 +4,57 @@ namespace DotTest\DataFixtures\Factory; -use Dot\DataFixtures\Command\ListFixturesCommand; use Dot\DataFixtures\Exception\NotFoundException; use Dot\DataFixtures\Factory\ListFixturesCommandFactory; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\MockObject\MockObject; +use DotTest\DataFixtures\Fixtures\Container; +use DotTest\DataFixtures\Fixtures\Data\RoleFixture; +use DotTest\DataFixtures\Fixtures\EntityManagerFactory; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use Symfony\Component\Console\Command\Command; +use Symfony\Component\Console\Tester\CommandTester; -use function getcwd; - +#[CoversClass(ListFixturesCommandFactory::class)] class ListFixturesCommandFactoryTest extends TestCase { - private ContainerInterface|MockObject $container; - - /** - * @throws Exception - */ - protected function setUp(): void + public function testWillNotCreateServiceWithoutConfigService(): void { - $this->container = $this->createMock(ContainerInterface::class); + $this->expectException(NotFoundExceptionInterface::class); + (new ListFixturesCommandFactory())(new Container()); } - /** - * @throws ContainerExceptionInterface - * @throws NotFoundException - * @throws NotFoundExceptionInterface - */ - public function testWithoutConfig(): void + #[DataProvider('invalidConfigProvider')] + public function testWillNotCreateServiceWithoutFixturesPath(mixed $config): void { - $this->container->expects($this->once()) - ->method('get') - ->with('config') - ->willReturn(null); $this->expectException(NotFoundException::class); $this->expectExceptionMessage('Key `fixtures` not found in doctrine configuration.'); - $factory = (new ListFixturesCommandFactory())($this->container); - $this->assertContainsOnlyInstancesOf(ListFixturesCommand::class, [$factory]); + (new ListFixturesCommandFactory())(new Container(['config' => $config])); } /** - * @throws ContainerExceptionInterface - * @throws NotFoundException - * @throws NotFoundExceptionInterface + * @return iterable */ - public function testPathWithConfig(): void + public static function invalidConfigProvider(): iterable { - $this->container->method('get')->willReturnMap([ - ['config', ['doctrine' => ['fixtures' => getcwd() . '/data/doctrine/fixtures']]], + yield 'config is null' => [null]; + yield 'config is a string' => ['config']; + yield 'no doctrine key' => [[]]; + yield 'doctrine is a string' => [['doctrine' => 'doctrine']]; + yield 'no fixtures key' => [['doctrine' => []]]; + yield 'fixtures is not a string' => [['doctrine' => ['fixtures' => 123]]]; + } + + public function testCreatesCommandThatListsConfiguredFixtures(): void + { + $container = new Container([ + 'config' => ['doctrine' => ['fixtures' => EntityManagerFactory::FIXTURES_PATH]], ]); - $factory = (new ListFixturesCommandFactory())($this->container); - $this->assertContainsOnlyInstancesOf(ListFixturesCommand::class, [$factory]); - $path = $this->container->get('config')['doctrine']['fixtures']; - $this->assertSame(getcwd() . '/data/doctrine/fixtures', $path); + + $tester = new CommandTester((new ListFixturesCommandFactory())($container)); + + $this->assertSame(Command::SUCCESS, $tester->execute([])); + $this->assertStringContainsString(RoleFixture::class, $tester->getDisplay()); } } diff --git a/test/Fixtures/Container.php b/test/Fixtures/Container.php new file mode 100644 index 0000000..f87c2c9 --- /dev/null +++ b/test/Fixtures/Container.php @@ -0,0 +1,37 @@ + $services + */ + public function __construct( + private readonly array $services = [], + ) { + } + + public function get(string $id): mixed + { + if (! $this->has($id)) { + throw new ContainerNotFoundException($id); + } + + return $this->services[$id]; + } + + public function has(string $id): bool + { + return array_key_exists($id, $this->services); + } +} diff --git a/test/Fixtures/ContainerNotFoundException.php b/test/Fixtures/ContainerNotFoundException.php new file mode 100644 index 0000000..07f97ed --- /dev/null +++ b/test/Fixtures/ContainerNotFoundException.php @@ -0,0 +1,18 @@ +persist(new Role('admin')); + $manager->flush(); + } +} diff --git a/test/Fixtures/Data/Sub/NestedFixture.php b/test/Fixtures/Data/Sub/NestedFixture.php new file mode 100644 index 0000000..1fdb9fd --- /dev/null +++ b/test/Fixtures/Data/Sub/NestedFixture.php @@ -0,0 +1,18 @@ +persist(new Role('nested')); + $manager->flush(); + } +} diff --git a/test/Fixtures/Entity/Role.php b/test/Fixtures/Entity/Role.php new file mode 100644 index 0000000..de6691a --- /dev/null +++ b/test/Fixtures/Entity/Role.php @@ -0,0 +1,23 @@ +setMetadataDriverImpl(new AttributeDriver([__DIR__ . '/Entity'])); + // ORM 3.5+ on PHP 8.4+ needs native lazy objects; otherwise ORM generates proxy classes, + // and before ORM 3.5 the ProxyFactory requires a proxy directory and namespace (as ORMSetup sets them). + $ormVersion = InstalledVersions::getVersion('doctrine/orm') ?? '0'; + if (PHP_VERSION_ID >= 80400 && version_compare($ormVersion, '3.5.0', '>=')) { + $config->enableNativeLazyObjects(true); + } else { + $config->setProxyDir(sys_get_temp_dir()); + $config->setProxyNamespace('DotTestDataFixturesProxies'); + } + + $connection = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true], $config); + $entityManager = new EntityManager($connection, $config); + (new SchemaTool($entityManager))->createSchema($entityManager->getMetadataFactory()->getAllMetadata()); + + return $entityManager; + } + + /** + * @return list + */ + public static function roleNames(EntityManager $entityManager): array + { + return $entityManager->getConnection()->fetchFirstColumn('SELECT name FROM role ORDER BY id'); + } +} diff --git a/test/Fixtures/Legacy/LegacyExecuteFixturesCommand.php b/test/Fixtures/Legacy/LegacyExecuteFixturesCommand.php new file mode 100644 index 0000000..d46349f --- /dev/null +++ b/test/Fixtures/Legacy/LegacyExecuteFixturesCommand.php @@ -0,0 +1,16 @@ +persist(new Role('outside')); + $manager->flush(); + } +}