From 5b085df37c6ca4b2fde289f1c4949990610ec6a8 Mon Sep 17 00:00:00 2001 From: bidi Date: Tue, 10 Nov 2026 17:48:09 +0200 Subject: [PATCH 1/4] code refactor, updated composer, docs, workflow, tests Signed-off-by: bidi --- .github/workflows/codecov.yml | 3 +- .github/workflows/static-analysis.yml | 5 +- .gitignore | 1 + .laminas-ci.json | 5 +- CHANGELOG.md | 97 ++++- README.md | 47 +- SECURITY.md | 1 + composer.json | 14 +- docs/book/v2/attributes-vs-factories.md | 156 +++++++ docs/book/v2/configuration.md | 19 + docs/book/v2/factories.md | 92 ++++ docs/book/v2/factories/repository.md | 122 ++++++ docs/book/v2/factories/service.md | 139 ++++++ docs/book/v2/faq.md | 176 ++++++++ docs/book/v2/installation.md | 24 ++ docs/book/v2/overview.md | 30 ++ docs/book/v2/upgrading.md | 70 +++ docs/book/v2/usage.md | 14 + mkdocs.yml | 15 +- phpstan.neon | 2 +- phpunit.xml | 17 +- src/ConfigProvider.php | 3 + src/Exception/InvalidArgumentException.php | 9 +- src/Exception/RuntimeException.php | 45 +- src/Factory/AttributedRepositoryFactory.php | 18 +- src/Factory/AttributedServiceFactory.php | 105 ++--- test/ConfigProviderTest.php | 3 +- test/Exception/RuntimeExceptionTest.php | 26 ++ .../AttributedRepositoryFactoryTest.php | 109 +++-- test/Factory/AttributedServiceFactoryTest.php | 402 ++++++++++++------ test/TestData/AbstractService.php | 9 + test/TestData/ArgumentService.php | 12 + test/TestData/ChildRepository.php | 12 + test/TestData/ChildService.php | 9 + test/TestData/Container.php | 49 +++ test/TestData/EnumService.php | 10 + test/TestData/ParentService.php | 15 + test/TestData/PrivateConstructorService.php | 12 + test/TestData/ServiceNotFoundException.php | 18 + test/TestData/ValidService.php | 6 +- test/TestData/VariadicService.php | 19 + 41 files changed, 1679 insertions(+), 261 deletions(-) create mode 100644 docs/book/v2/attributes-vs-factories.md create mode 100644 docs/book/v2/configuration.md create mode 100644 docs/book/v2/factories.md create mode 100644 docs/book/v2/factories/repository.md create mode 100644 docs/book/v2/factories/service.md create mode 100644 docs/book/v2/faq.md create mode 100644 docs/book/v2/installation.md create mode 100644 docs/book/v2/overview.md create mode 100644 docs/book/v2/upgrading.md create mode 100644 docs/book/v2/usage.md create mode 100644 test/Exception/RuntimeExceptionTest.php create mode 100644 test/TestData/AbstractService.php create mode 100644 test/TestData/ArgumentService.php create mode 100644 test/TestData/ChildRepository.php create mode 100644 test/TestData/ChildService.php create mode 100644 test/TestData/Container.php create mode 100644 test/TestData/EnumService.php create mode 100644 test/TestData/ParentService.php create mode 100644 test/TestData/PrivateConstructorService.php create mode 100644 test/TestData/ServiceNotFoundException.php create mode 100644 test/TestData/VariadicService.php diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml index c8de574..9652006 100644 --- a/.github/workflows/codecov.yml +++ b/.github/workflows/codecov.yml @@ -18,6 +18,7 @@ jobs: - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout @@ -49,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/static-analysis.yml b/.github/workflows/static-analysis.yml index 9f01888..b428224 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -4,7 +4,7 @@ on: name: Run PHPStan checks jobs: - mutation: + static-analysis: name: PHPStan ${{ matrix.php }}-${{ matrix.os }} runs-on: ${{ matrix.os }} @@ -18,6 +18,7 @@ jobs: - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout @@ -27,7 +28,7 @@ jobs: uses: shivammathur/setup-php@v2 with: php-version: "${{ matrix.php }}" - coverage: pcov + coverage: none ini-values: assert.exception=1, zend.assertions=1, error_reporting=-1, log_errors_max_len=0, display_errors=On tools: composer:v2, cs2pr diff --git a/.gitignore b/.gitignore index 4b3643b..620b02e 100644 --- a/.gitignore +++ b/.gitignore @@ -37,6 +37,7 @@ composer.phar # You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file composer.lock .phpunit.result.cache +.phpunit.cache .phpcs-cache /documentation-theme/ /docs/html/ diff --git a/.laminas-ci.json b/.laminas-ci.json index 29216fa..efdd72e 100644 --- a/.laminas-ci.json +++ b/.laminas-ci.json @@ -1,3 +1,6 @@ { - "backwardCompatibilityCheck": true + "ignore_php_platform_requirements": { + "8.6": true + }, + "backwardCompatibilityCheck": false } diff --git a/CHANGELOG.md b/CHANGELOG.md index 431976b..529de4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,96 @@ -## 1.0.0 - 2024-06-06 +# Changelog -Initial tagged release +All notable changes to this project are documented in this file. + +## 2.0.0 - TBD + +### Added + +- PHP 8.6 support +- `RuntimeException::notInstantiable()`, `dependencyNotInstantiable()`, `argumentCountMismatch()`, `invalidService()` and `missingPackage()` +- `InvalidArgumentException::emptySegment()` +- Documentation for version 2, including an upgrade guide + +### Changed + +- `doctrine/orm` moved from `require` to `suggest`; applications using `AttributedRepositoryFactory` must require it, and versions below 2.9 or from 4.0 conflict +- `psr/container` requirement raised to `^1.1 || ^2.0` +- `AttributedServiceFactory::readKeysFromArray()` takes the full service key as its third parameter +- PHPUnit 12.5 and PHPStan level 8; the test suite fails on notices, warnings, deprecations and risky tests + +### Deprecated + +- Nothing. + +### Removed + +- `AttributedServiceFactory::$originalKey` + +### Fixed + +- Requesting an abstract class, an enum or a class with a non-public constructor throws `RuntimeException` instead of a PHP `Error` +- An unregistered dependency that cannot be instantiated without arguments throws `RuntimeException` instead of `ArgumentCountError` or `Error` +- The number of `#[Inject]` entries is checked against the constructor; extra entries were silently ignored +- Empty dot-notation segments throw `InvalidArgumentException` instead of reading the `''` key +- `AttributedRepositoryFactory` checks the type of the entity manager service +- `AttributedRepositoryFactory` names the missing package when `doctrine/orm` is not installed + +## 1.4.1 - 2026-09-16 + +### Fixed + +- FAQ menu entry ([#14](https://github.com/dotkernel/dot-dependency-injection/pull/14)) + +## 1.4.0 - 2026-09-16 + +### Changed + +- `#[Entity]` targets classes and `#[Inject]` targets methods only ([#13](https://github.com/dotkernel/dot-dependency-injection/pull/13)) +- Documentation expanded with the "Attributes vs. factories" and FAQ pages ([#13](https://github.com/dotkernel/dot-dependency-injection/pull/13)) + +### Removed + +- PHP 8.2 support ([#13](https://github.com/dotkernel/dot-dependency-injection/pull/13)) + +### Fixed + +- A configuration value of `null` was treated as a missing key ([#13](https://github.com/dotkernel/dot-dependency-injection/pull/13)) +- Dot-notation paths continuing past a scalar were silently truncated ([#13](https://github.com/dotkernel/dot-dependency-injection/pull/13)) +- `AttributedRepositoryFactory` returned a repository of the wrong class when the entity did not declare `repositoryClass` ([#13](https://github.com/dotkernel/dot-dependency-injection/pull/13)) +- An `#[Entity]` attribute naming a missing class was not reported ([#13](https://github.com/dotkernel/dot-dependency-injection/pull/13)) + +## 1.3.0 - 2025-10-30 + +### Added + +- PHP 8.4 and 8.5 support ([#11](https://github.com/dotkernel/dot-dependency-injection/pull/11)) + +### Removed + +- PHP 8.1 support ([#11](https://github.com/dotkernel/dot-dependency-injection/pull/11)) + +## 1.2.0 - 2025-03-04 + +### Changed + +- Psalm replaced with PHPStan ([#9](https://github.com/dotkernel/dot-dependency-injection/pull/9)) + +## 1.1.1 - 2025-01-28 + +### Changed + +- Psalm 6.x ([#7](https://github.com/dotkernel/dot-dependency-injection/pull/7)) + +## 1.1.0 - 2024-10-22 + +### Added + +- PHP 8.4 support ([#5](https://github.com/dotkernel/dot-dependency-injection/pull/5)) + +### Changed + +- `laminas/laminas-coding-standard` 3.x + +## 1.0.0 - 2024-06-07 + +Initial tagged release. diff --git a/README.md b/README.md index af218e5..7cee931 100644 --- a/README.md +++ b/README.md @@ -5,40 +5,48 @@ Instead of a hand-written factory class per service, you declare a class's dependencies with the `#[Inject]` attribute on its constructor - or a repository's entity with `#[Entity]` - and register one of the two reusable factories this package ships. That removes an entire category of boilerplate files from a project and keeps the dependency list next to the constructor it feeds. -See [Attributes vs. factories](https://docs.dotkernel.org/dot-dependency-injection/v1/attributes-vs-factories/) for the full comparison and the trade-offs. +See [Attributes vs. factories](https://docs.dotkernel.org/dot-dependency-injection/v2/attributes-vs-factories/) for the full comparison and the trade-offs. ## Documentation Documentation is available at: . -- [Installation](https://docs.dotkernel.org/dot-dependency-injection/v1/installation/) -- [Configuration](https://docs.dotkernel.org/dot-dependency-injection/v1/configuration/) -- [Attributes vs. factories](https://docs.dotkernel.org/dot-dependency-injection/v1/attributes-vs-factories/) -- [Factories](https://docs.dotkernel.org/dot-dependency-injection/v1/factories/) -- [Inject class dependencies](https://docs.dotkernel.org/dot-dependency-injection/v1/factories/service/) -- [Inject entity repositories](https://docs.dotkernel.org/dot-dependency-injection/v1/factories/repository/) -- [FAQ](https://docs.dotkernel.org/dot-dependency-injection/v1/faq/) +- [Installation](https://docs.dotkernel.org/dot-dependency-injection/v2/installation/) +- [Configuration](https://docs.dotkernel.org/dot-dependency-injection/v2/configuration/) +- [Attributes vs. factories](https://docs.dotkernel.org/dot-dependency-injection/v2/attributes-vs-factories/) +- [Factories](https://docs.dotkernel.org/dot-dependency-injection/v2/factories/) +- [Inject class dependencies](https://docs.dotkernel.org/dot-dependency-injection/v2/factories/service/) +- [Inject entity repositories](https://docs.dotkernel.org/dot-dependency-injection/v2/factories/repository/) +- [FAQ](https://docs.dotkernel.org/dot-dependency-injection/v2/faq/) +- [Upgrading from 1.x](https://docs.dotkernel.org/dot-dependency-injection/v2/upgrading/) + +## Versions + +| Version | Branch | PHP | Status | Documentation | +| --- | --- | --- | --- | --- | +| 2.x | `2.0` | 8.3, 8.4, 8.5, 8.6 | active | [v2](https://docs.dotkernel.org/dot-dependency-injection/v2/overview/) | +| 1.x | `1.0` | 8.3, 8.4, 8.5 | supported | [v1](https://docs.dotkernel.org/dot-dependency-injection/v1/overview/) | ## Badges ![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-dependency-injection) -![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-dependency-injection/1.4.1) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-dependency-injection/2.0.0) [![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-dependency-injection)](https://github.com/dotkernel/dot-dependency-injection/issues) [![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-dependency-injection)](https://github.com/dotkernel/dot-dependency-injection/network) [![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-dependency-injection)](https://github.com/dotkernel/dot-dependency-injection/stargazers) -[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-dependency-injection)](https://github.com/dotkernel/dot-dependency-injection/blob/1.0/LICENSE.md) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-dependency-injection)](https://github.com/dotkernel/dot-dependency-injection/blob/2.0/LICENSE.md) -[![Build Static](https://github.com/dotkernel/dot-dependency-injection/actions/workflows/continuous-integration.yml/badge.svg?branch=1.0)](https://github.com/dotkernel/dot-dependency-injection/actions/workflows/continuous-integration.yml) +[![Build Static](https://github.com/dotkernel/dot-dependency-injection/actions/workflows/continuous-integration.yml/badge.svg?branch=2.0)](https://github.com/dotkernel/dot-dependency-injection/actions/workflows/continuous-integration.yml) [![codecov](https://codecov.io/gh/dotkernel/dot-dependency-injection/graph/badge.svg?token=DayAoD2Oj6)](https://codecov.io/gh/dotkernel/dot-dependency-injection) [![docs-build](https://github.com/dotkernel/dot-dependency-injection/actions/workflows/docs-build.yml/badge.svg)](https://github.com/dotkernel/dot-dependency-injection/actions/workflows/docs-build.yml) -[![PHPStan](https://github.com/dotkernel/dot-dependency-injection/actions/workflows/static-analysis.yml/badge.svg?branch=1.0)](https://github.com/dotkernel/dot-dependency-injection/actions/workflows/static-analysis.yml) +[![PHPStan](https://github.com/dotkernel/dot-dependency-injection/actions/workflows/static-analysis.yml/badge.svg?branch=2.0)](https://github.com/dotkernel/dot-dependency-injection/actions/workflows/static-analysis.yml) ## Requirements -- PHP 8.3, 8.4 or 8.5 -- a PSR-11 container, usually `laminas/laminas-servicemanager` -- `doctrine/orm` ^2.9 || ^3.0, if you use `AttributedRepositoryFactory` +- PHP 8.3, 8.4, 8.5 or 8.6 +- a PSR-11 container (`psr/container` ^1.1 || ^2.0), usually `laminas/laminas-servicemanager` +- `doctrine/orm` ^2.9 || ^3.0, installed by your application, if you use `AttributedRepositoryFactory` ## Installation @@ -94,7 +102,8 @@ public function __construct( The `#[Inject]` attribute is telling `AttributedServiceFactory` to inject the services specified as parameters, in the same order as the constructor parameters. Valid service names should be provided, as registered in the service manager. -A name that is not registered in the container, but is an existing class, is instantiated directly. +A name that is not registered in the container, but is a class that can be instantiated without arguments, is instantiated directly. +The number of entries is checked against the constructor; trailing parameters with a default value may be left out. A class without a constructor does not need the attribute. @@ -113,6 +122,12 @@ which will inject `$container->get('config')['debug'];`. ### Using the AttributedRepositoryFactory +`AttributedRepositoryFactory` needs `doctrine/orm`, which this package does not install: + +```shell +composer require doctrine/orm +``` + You can register doctrine repositories and inject them using the `AttributedRepositoryFactory` as below: ```php diff --git a/SECURITY.md b/SECURITY.md index e54209b..e1c83a3 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -4,6 +4,7 @@ | Version | Supported | PHP Version | | --- | --- | --- | +| 2.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-dependency-injection/2.0.0) | | 1.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-dependency-injection/1.4.1) | ## Reporting Potential Security Issues diff --git a/composer.json b/composer.json index 85c8e44..e106233 100644 --- a/composer.json +++ b/composer.json @@ -24,15 +24,21 @@ "service" ], "require": { - "php": "~8.3.0 || ~8.4.0 || ~8.5.0", - "doctrine/orm": "^2.9 || ^3.0", - "psr/container": "^1.0 || ^2.0" + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", + "psr/container": "^1.1 || ^2.0" }, "require-dev": { + "doctrine/orm": "^2.9 || ^3.0", "laminas/laminas-coding-standard": "^3.0", "phpstan/phpstan": "^2.1", "phpstan/phpstan-phpunit": "^2.0", - "phpunit/phpunit": "^10.5" + "phpunit/phpunit": "^12.5" + }, + "suggest": { + "doctrine/orm": "Required to use AttributedRepositoryFactory" + }, + "conflict": { + "doctrine/orm": "<2.9 || >=4.0" }, "autoload": { "psr-4": { diff --git a/docs/book/v2/attributes-vs-factories.md b/docs/book/v2/attributes-vs-factories.md new file mode 100644 index 0000000..740eeed --- /dev/null +++ b/docs/book/v2/attributes-vs-factories.md @@ -0,0 +1,156 @@ +# Attributes vs. factories + +A PSR-11 container needs to know how to build every service. +The usual answer is a factory class per service, which means that a project ends up carrying one extra file for every class it wires up. +`dot-dependency-injection` replaces those files with a single attribute on the constructor and two reusable factories. + +## The same service, both ways + +### With a hand-written factory + +Two files, plus the registration. + +```php +get(UserRepository::class), + $container->get(UrlHelper::class), + $container->get('config')['user'], + ); + } +} +``` + +```php +'factories' => [ + UserService::class => UserServiceFactory::class, +], +``` + +### With `#[Inject]` + +One file, and the registration. + +```php + [ + UserService::class => AttributedServiceFactory::class, +], +``` + +## Why this is an advantage + +**Fewer files, less code.** +A module with 20 services no longer needs 20 factory classes. +The wiring shrinks from a class per service to four lines inside the class that already exists. + +**One source of truth.** +The dependency list sits directly above the constructor it feeds. +Adding a constructor parameter and forgetting to update the factory is the single most common wiring bug in a factory-based project, and it cannot happen when both live on the same lines. + +**No drift, no duplication.** +Hand-written factories repeat the same `$container->get(...)` pattern hundreds of times across a project. +Every repetition is a place where a typo, a stale service name, or a copy-paste mistake can hide. + +**Nothing to test.** +A trivial factory is still code, so it shows up in coverage reports and either gets a test that asserts nothing meaningful or drags coverage down. +The two factories in this package are tested once, here. + +**Configuration without boilerplate.** +`'config.user'` replaces `$container->get('config')['user']` and fails with a clear, package-level exception naming the full path when that key is missing, instead of an `Undefined array key` notice or a silent `null`. + +**Repositories for free.** +`AttributedRepositoryFactory` removes an entire category of factories: every Doctrine repository in a project is otherwise a near-identical factory calling `$container->get(EntityManagerInterface::class)->getRepository(...)`. + +**Consistent failures.** +All wiring errors surface as `Dot\DependencyInjection\Exception\ExceptionInterface`, with messages that name the class, the attribute and the factory involved, rather than whatever each hand-written factory happened to do. +That includes classes that cannot be instantiated, dependencies that are not registered, and an `#[Inject]` list that does not fit the constructor, which would otherwise end in a PHP `Error` or `ArgumentCountError`. + +**Readable classes.** +Anyone opening the class sees what it needs and where each dependency comes from without opening a second file. + +## What you give up + +Being explicit about the trade-offs matters more than the line count. + +| | Hand-written factory | `#[Inject]` | +| --- | --- | --- | +| Wiring is checked by the type system | yes, `new UserService(...)` is analysed | no, names are strings resolved at runtime | +| Order of arguments verified statically | yes | no, the attribute order must match the constructor; the count is checked at runtime | +| Reflection at build time | none | one `ReflectionClass` per service creation, not cached | +| Conditional or computed wiring | anything PHP allows | not supported | +| Works on third-party classes | yes | only on classes you can annotate | + +## When to keep writing a factory + +`#[Inject]` covers the common case: a constructor that receives services and configuration. +Write a factory by hand when you need something else. + +- the arguments are computed, conditional, or come from something other than the container +- the service is decorated, or built through a delegator or an abstract factory +- you are wiring a class you do not own and cannot annotate +- the class is intentionally constructed with runtime arguments rather than resolved from the container +- injection has to happen somewhere other than the constructor + +Both styles coexist without any friction: the factory is chosen per service in your `ConfigProvider`, so you can use `AttributedServiceFactory` for the bulk of a module and a hand-written factory for the few services that need one. diff --git a/docs/book/v2/configuration.md b/docs/book/v2/configuration.md new file mode 100644 index 0000000..a9e596b --- /dev/null +++ b/docs/book/v2/configuration.md @@ -0,0 +1,19 @@ +# Configuration + +After installation, register `dot-dependency-injection` in your project by adding the below line to your configuration aggregator (usually: `config/config.php`): + +```php +Dot\DependencyInjection\ConfigProvider::class, +``` + +`Dot\DependencyInjection\ConfigProvider` currently returns an empty array: the package exposes factories that you reference from your own modules, so it does not need to register any service of its own. +Registering it keeps your configuration aggregate consistent with the other Dotkernel packages and makes sure that future configuration shipped by this package is picked up automatically. + +There is no package-specific configuration to set. +Everything else is declared where it belongs: + +- the dependencies of a class, through the `#[Inject]` attribute on its constructor +- the entity of a repository, through the `#[Entity]` attribute on the repository class +- the mapping between a class and the factory that builds it, under the `dependencies.factories` key of the `ConfigProvider` of your own module + +See [Inject class dependencies](factories/service.md) and [Inject entity repositories](factories/repository.md). diff --git a/docs/book/v2/factories.md b/docs/book/v2/factories.md new file mode 100644 index 0000000..7764e1b --- /dev/null +++ b/docs/book/v2/factories.md @@ -0,0 +1,92 @@ +# Factories + +`dot-dependency-injection` is based on two reusable factories - `AttributedServiceFactory` and `AttributedRepositoryFactory` - able to inject any dependency into a class. + +Both are plain invokable factories, so they work with any PSR-11 container that passes the requested service name to the factory (for example `laminas/laminas-servicemanager`): + +```php +$factory = new Dot\DependencyInjection\Factory\AttributedServiceFactory(); +$service = $factory($container, YourApp\Service\Example::class); +``` + +Both expose the same logic through `createObject(ContainerInterface $container, string $requestedName)`, which `__invoke()` simply delegates to. +Use `createObject()` when you extend one of the factories and need to call the parent implementation explicitly. + +> Because the service name is also the class to instantiate, you can only register these factories under the fully qualified class name of the service. +> Aliases still work, as long as the alias points to a service registered under its FQCN. + +## AttributedServiceFactory + +Injects class dependencies into classes. + +The factory looks for the `#[Inject]` attribute on the constructor of the requested class and resolves each of its parameters, in the declared order, into a constructor argument. + +Resolution of a single dependency happens as follows: + +1. if the container has a service registered under the exact name, that service is used - this is checked first, even when the name contains dots +2. otherwise, if the name contains dots, the part before the first dot is resolved from the container and the remaining parts are read as keys from the returned array (or `ArrayAccess` object); an empty part, as in `config.` or `config..debug`, is rejected +3. otherwise, if the name is a class that can be instantiated without arguments, the factory instantiates it directly with `new $name()` +4. otherwise, a `RuntimeException` is thrown + +Before resolving anything, the factory checks that the number of `#[Inject]` entries fits the constructor: at least the number of required parameters, and at most the total number of parameters unless the last one is variadic. + +A class without a constructor does not need the `#[Inject]` attribute: it is instantiated directly. + +### Exceptions thrown by AttributedServiceFactory + +- `Dot\DependencyInjection\Exception\RuntimeException` if the requested class does not exist +- `Dot\DependencyInjection\Exception\RuntimeException` if the requested class cannot be instantiated: it is abstract, an enum, or its constructor is not public +- `Dot\DependencyInjection\Exception\RuntimeException` if the requested class has a constructor without the `#[Inject]` attribute +- `Dot\DependencyInjection\Exception\RuntimeException` if the class tries to inject itself +- `Dot\DependencyInjection\Exception\RuntimeException` if the number of `#[Inject]` entries does not fit the constructor +- `Dot\DependencyInjection\Exception\RuntimeException` if a dependency is neither a registered service nor an existing class +- `Dot\DependencyInjection\Exception\RuntimeException` if a dependency is an existing class that is not registered and cannot be instantiated without arguments +- `Dot\DependencyInjection\Exception\InvalidArgumentException` if a key of a dot-separated dependency cannot be found in the array service +- `Dot\DependencyInjection\Exception\InvalidArgumentException` if a dot-separated dependency contains an empty segment +- `Psr\Container\NotFoundExceptionInterface` if a dependency does not exist in the service container +- `Psr\Container\ContainerExceptionInterface` if the service manager is unable to provide an instance of a dependency + +## AttributedRepositoryFactory + +Injects entity repositories into a class. + +It requires `doctrine/orm` ^2.9 or ^3.0, which your application installs: this package only suggests it. + +The factory looks for the `#[Entity]` attribute on the requested repository class and returns `$container->get(EntityManagerInterface::class)->getRepository($entityName)`. + +Since Doctrine decides which repository class to build from the mapping of the entity, the entity referenced by the `#[Entity]` attribute must declare the repository back: + +```php +#[ORM\Entity(repositoryClass: ExampleRepository::class)] +``` + +If it does not, Doctrine returns its default repository and the factory throws a `RuntimeException` instead of handing back an object of an unexpected type. + +### Exceptions thrown by AttributedRepositoryFactory + +- `Dot\DependencyInjection\Exception\RuntimeException` if `doctrine/orm` is not installed +- `Dot\DependencyInjection\Exception\RuntimeException` if the repository class does not exist +- `Dot\DependencyInjection\Exception\RuntimeException` if the repository class does not extend `Doctrine\ORM\EntityRepository` +- `Dot\DependencyInjection\Exception\RuntimeException` if the repository class does not have the `#[Entity]` attribute +- `Dot\DependencyInjection\Exception\RuntimeException` if the class referenced by the `#[Entity]` attribute does not exist +- `Dot\DependencyInjection\Exception\RuntimeException` if the `Doctrine\ORM\EntityManagerInterface` service is not an entity manager +- `Dot\DependencyInjection\Exception\RuntimeException` if Doctrine returns a repository that is not an instance of the requested class +- `Psr\Container\NotFoundExceptionInterface` if `Doctrine\ORM\EntityManagerInterface` does not exist in the service container +- `Psr\Container\ContainerExceptionInterface` if the service manager is unable to provide an instance of `Doctrine\ORM\EntityManagerInterface` + +## Exception hierarchy + +Both exceptions implement `Dot\DependencyInjection\Exception\ExceptionInterface`, so you can catch anything thrown by this package with a single `catch` block: + +```php +try { + $service = $container->get(YourApp\Service\Example::class); +} catch (Dot\DependencyInjection\Exception\ExceptionInterface $exception) { + // ... +} +``` + +| Exception | Extends | Meaning | +| --- | --- | --- | +| `RuntimeException` | `\RuntimeException` | the class or service graph cannot be built as declared | +| `InvalidArgumentException` | `\InvalidArgumentException` | a dot-separated dependency points to a missing array key | diff --git a/docs/book/v2/factories/repository.md b/docs/book/v2/factories/repository.md new file mode 100644 index 0000000..7155987 --- /dev/null +++ b/docs/book/v2/factories/repository.md @@ -0,0 +1,122 @@ +# Inject entity repositories + +`AttributedRepositoryFactory` requires `doctrine/orm` ^2.9 or ^3.0 in your application: + +```shell +composer require doctrine/orm +``` + +Without it, the factory throws a `Dot\DependencyInjection\Exception\RuntimeException` that names the missing package. + +## Prepare entity + +Doctrine decides which repository class to instantiate based on the mapping of the entity, so the entity must point to its repository: + +```php + + */ +#[Entity(name: Example::class)] +class ExampleRepository extends EntityRepository +{ +} +``` + +- the `name` field has to be the fully qualified class name of the entity +- each entity repository must extend `Doctrine\ORM\EntityRepository` +- `#[Entity]` targets classes only +- `#[Entity]` is not inherited: PHP does not pass attributes down to subclasses, so a repository extending another repository needs its own `#[Entity]` + +The factory returns `$container->get(EntityManagerInterface::class)->getRepository(Example::class)`, which means the repository is built and managed by Doctrine, with the entity manager already injected. +Do not declare a constructor with a different signature on your repository. + +> If the entity does not declare `repositoryClass`, Doctrine returns its default `EntityRepository` and the factory throws a `Dot\DependencyInjection\Exception\RuntimeException` naming both classes, instead of returning an object of an unexpected type under your repository's service name. + +## Register repository + +Open the ConfigProvider of the module where your repository resides. + +Add a new entry under `factories`, where the key is your repository FQCN and the value is `Dot\DependencyInjection\Factory\AttributedRepositoryFactory::class`. + +See the below example for a better understanding of the file structure. + +```php + $this->getDependencies(), + ]; + } + + public function getDependencies(): array + { + return [ + 'factories' => [ + ExampleRepository::class => AttributedRepositoryFactory::class, + ], + ]; + } +} +``` + +`Doctrine\ORM\EntityManagerInterface` must be registered in your container, and the service must be an entity manager; anything else throws a `Dot\DependencyInjection\Exception\RuntimeException` naming the type that was found. +In Dotkernel projects this is provided by `doctrine/doctrine-orm-module` / `dot-cache` configuration and is already in place. + +## Inject the repository into a service + +Once registered, the repository is an ordinary service, so it can be injected with `#[Inject]`: + +```php +#[Inject( + ExampleRepository::class, +)] +public function __construct( + protected ExampleRepository $exampleRepository, +) { +} +``` + +## Caching + +The `#[Entity]` attribute is read with reflection on every repository creation and is not cached by this package. diff --git a/docs/book/v2/factories/service.md b/docs/book/v2/factories/service.md new file mode 100644 index 0000000..05ef027 --- /dev/null +++ b/docs/book/v2/factories/service.md @@ -0,0 +1,139 @@ +# Inject class dependencies + +## Prepare class + +`dot-dependency-injection` determines the dependencies by looking at the `#[Inject]` attribute, added to the constructor of a class. +Dependencies are specified as separate parameters of the `#[Inject]` attribute, in the same order as the constructor parameters. + +```php + `#[Inject]` targets methods only, and only the constructor is inspected. +> Injecting dependencies into property setters is not supported. + +## Inject a configuration value + +If your class needs the value of a specific configuration key, you can specify the path using dot notation: + +```php + #[Inject( + Dependency1::class, + 'config.example', + )] + public function __construct( + protected Dependency1 $dependency1, + protected array $exampleConfig, + ) { + } +``` + +`'config.example'` injects `$container->get('config')['example']`, and paths of any depth work: `'config.example.nested.value'`. + +Things worth knowing about dot notation: + +- the full name is always looked up in the container first, so a service literally registered as `config.example` takes precedence over the `example` key of the `config` service +- only the part before the first dot is resolved from the container; every following segment is an array key +- both arrays and objects implementing `ArrayAccess` can be traversed +- a key holding `null` is injected as `null`, it is not treated as missing +- an empty segment, as in `config.`, `.config` or `config..debug`, throws `Dot\DependencyInjection\Exception\InvalidArgumentException`, unless a service is registered under that exact name +- if a segment does not exist, or the path continues past a scalar value, `Dot\DependencyInjection\Exception\InvalidArgumentException` is thrown, naming the full path you declared + +## Register class + +Open the ConfigProvider of the module where your class resides. + +Add a new entry under `factories`, where the key is your class FQCN and the value is `Dot\DependencyInjection\Factory\AttributedServiceFactory::class`. + +See the below example for a better understanding of the file structure. + +```php + $this->getDependencies(), + ]; + } + + public function getDependencies(): array + { + return [ + 'factories' => [ + Example::class => AttributedServiceFactory::class, + ], + ]; + } +} +``` + +> The service key must be the fully qualified class name of the class to build, because the factory instantiates the requested service name. +> Register an alias if you need a shorter name. + +## Recursion + +A class cannot inject itself: + +```php +#[Inject(self::class)] +public function __construct(protected ?Example $example = null) +{ +} +``` + +This throws a `Dot\DependencyInjection\Exception\RuntimeException`. + +> Only direct self-injection is detected. +> A cycle spanning several classes (`A` needs `B`, `B` needs `A`) is not detected by this package and will end in infinite recursion, exactly as it would with hand-written factories. + +## Caching + +Dependencies declared through `#[Inject]` are resolved with reflection on every service creation, and the result is not cached by this package. +The container's own instance cache still applies: a shared service is built once per request, no matter how many classes inject it. diff --git a/docs/book/v2/faq.md b/docs/book/v2/faq.md new file mode 100644 index 0000000..a7359f2 --- /dev/null +++ b/docs/book/v2/faq.md @@ -0,0 +1,176 @@ +# FAQ + +## Setup and registration + +### Do I still have to register every service in a ConfigProvider? + +Yes. +This package replaces the factory class you would write for a service, not the `dependencies.factories` entry that tells the container which factory to use. +Each service still needs one line mapping its FQCN to `AttributedServiceFactory` or `AttributedRepositoryFactory`. + +### Why does it not read the dependencies from my constructor type hints? + +Container identifiers are not types. +The same type can be registered several times under different names, plenty of services are registered under strings such as `config`, and a parameter typed against an interface gives no indication of which implementation you want. +`#[Inject]` asks you for the identifier because that is the only thing the container can actually resolve. + +### Can I register a service under a name other than its fully qualified class name? + +Not directly, because the factory instantiates the requested service name. +Register the service under its FQCN and add an alias pointing to it if you need a shorter name. + +### Can I keep some hand-written factories? + +Yes, the factory is chosen per service, so both styles can live side by side in the same module. +See [Attributes vs. factories](attributes-vs-factories.md) for the cases where a hand-written factory is still the better choice. + +## The `#[Inject]` attribute + +### My constructor takes no arguments, do I need the attribute? + +It depends on whether the constructor exists at all. +A class with no constructor is instantiated directly and needs no attribute. +A class that explicitly declares `public function __construct()` does need the attribute, otherwise you get `You need to use the "...\Inject" attribute on the "..." class`. +Use `#[Inject()]` with no parameters, or delete the empty constructor. + +### What happens if the order in the attribute does not match the constructor? + +The order is not checked, only the number of entries is, and the arguments are passed positionally in the order you listed them. +If the types differ you get a `TypeError` when the service is created; if they happen to be compatible, the wrong values are injected silently. +Keep the attribute parameters in the same order as the constructor parameters. + +### Can I leave out some constructor parameters? + +Only trailing ones that have a default value. +Arguments are passed positionally, so you cannot skip a parameter in the middle of the list and you cannot inject by parameter name. + +### What if I list more or fewer dependencies than the constructor takes? + +The factory throws a `Dot\DependencyInjection\Exception\RuntimeException` before resolving anything, naming the class, the number of entries and the number of parameters the constructor accepts. +A variadic last parameter accepts any number of extra entries. + +### Why do I get "is not registered in the container and can not be instantiated without arguments"? + +A dependency named in `#[Inject]` is an existing class, but it is not registered in the container and the factory cannot build it with `new` alone: its constructor has required parameters, it is abstract or an enum, or its constructor is not public. +Register the dependency in your container, for example with `AttributedServiceFactory` and its own `#[Inject]`. + +### Can I inject a plain value, such as a string or a number? + +No. +Every parameter of the attribute is resolved as a container identifier, a class name, or a dot-separated path into an array service. +Put the literal in your configuration and inject it with dot notation instead. + +### Is `#[Inject]` inherited by subclasses? + +Yes. +If a subclass does not declare its own constructor, the factory reads the attribute from the inherited constructor and builds the subclass with the dependencies the parent declared. +Declare a constructor with its own `#[Inject]` in the subclass to change them. + +### Can I put `#[Inject]` on a property or a setter? + +No. +The attribute targets methods, and only the constructor is inspected. + +### Can I inject the same service twice? + +Yes, list it as many times as your constructor needs it. +A shared service is resolved from the container each time, so both parameters receive the same instance. + +## Configuration values + +### How do I inject a single configuration key? + +Use dot notation: `#[Inject('config.example')]` injects `$container->get('config')['example']`. +Paths of any depth work, and both arrays and `ArrayAccess` objects can be traversed. + +### What if a service is registered under a name that contains dots? + +The full name is always looked up in the container first, so a service literally registered as `config.example` wins over the `example` key of the `config` service. + +### What if the key has a stray dot, such as `config.` or `config..debug`? + +`Dot\DependencyInjection\Exception\InvalidArgumentException` is thrown, because an empty segment is almost always a typo. +A service registered under that exact name still wins, since the full name is looked up first. + +### Can I address a configuration key that itself contains a dot? + +No. +Only the segment before the first dot is treated as a service identifier; every following dot starts a new array key, so a key named `my.key` cannot be reached. +Nest the value one level deeper, or expose it as its own service. + +### What if the configuration value is `null`? + +It is injected as `null`. +A key that exists but holds `null` is not treated as missing. + +### What if the key does not exist? + +`Dot\DependencyInjection\Exception\InvalidArgumentException` is thrown, naming the full path you declared. +You get the same exception when the path continues past a scalar value, for example `config.debug.verbose` where `config.debug` is a boolean. + +## Doctrine repositories + +### Why do I get a repository of the wrong class, or an "unexpected repository" error? + +Doctrine, not this package, decides which class to instantiate, and it reads that from the mapping of the entity. +Add `#[ORM\Entity(repositoryClass: ExampleRepository::class)]` to the entity, so that it points back to the repository that declares it through `#[Entity]`. + +### Do I still need `#[Entity]` if the entity already declares `repositoryClass`? + +Yes. +The two point at each other: `repositoryClass` tells Doctrine which class to build, and `#[Entity]` tells the factory which entity to ask for. + +### Can I inject extra dependencies into a repository? + +No. +The repository is constructed by Doctrine with the entity manager and the class metadata, so its constructor signature is not yours to change. +Put the extra dependencies in a service that receives the repository through `#[Inject]`. + +### How do I inject a repository into a service? + +Register the repository with `AttributedRepositoryFactory`, then list it like any other service: `#[Inject(ExampleRepository::class)]`. + +### Do I need `doctrine/orm` if I only use `AttributedServiceFactory`? + +No. +Install it yourself (`composer require doctrine/orm`) only if you use `AttributedRepositoryFactory`. + +### Is `#[Entity]` inherited by a subclass of my repository? + +No. +PHP does not pass attributes down to subclasses, so each repository registered with `AttributedRepositoryFactory` needs its own `#[Entity]`. + +## Performance + +### Is the attribute lookup cached? + +No. +One `ReflectionClass` is created per service creation and the attribute is read every time. +The container's own instance cache still applies, so a shared service is built once per request no matter how many classes inject it. + +### Does that slow down my application? + +The reflection happens once per service that a request actually builds, and it is a lookup on an already-loaded class rather than file parsing. +If a profile ever shows it mattering for a specific hot service, write a factory by hand for that one service. + +## Testing and debugging + +### How do I unit test a class that uses `#[Inject]`? + +Exactly as you would test any other class: instantiate it with `new` and pass test doubles. +The attribute is inert outside the factory, so it has no effect on your tests. + +### I get "You need to use the ... attribute on the ... class", what now? + +The requested class has a constructor without the `#[Inject]` attribute, or the attribute sits somewhere other than the constructor. +Check that the attribute is imported from `Dot\DependencyInjection\Attribute\Inject`, because an attribute of another `Inject` class is ignored. + +### Are circular dependencies detected? + +Only direct self-injection, which throws a `RuntimeException`. +A cycle spanning several classes, where `A` needs `B` and `B` needs `A`, is not detected and ends in infinite recursion, exactly as it would with hand-written factories. + +### Which exception should I catch? + +Both exceptions of this package implement `Dot\DependencyInjection\Exception\ExceptionInterface`, so a single `catch` covers every wiring error. +Note that your container may wrap them; for example, Laminas Service Manager wraps them in `Laminas\ServiceManager\Exception\ServiceNotCreatedException`, so inspect the previous exception. diff --git a/docs/book/v2/installation.md b/docs/book/v2/installation.md new file mode 100644 index 0000000..3cce363 --- /dev/null +++ b/docs/book/v2/installation.md @@ -0,0 +1,24 @@ +# Installation + +## Requirements + +- PHP 8.3, 8.4, 8.5 or 8.6 +- A PSR-11 container (`psr/container` ^1.1 || ^2.0), usually `laminas/laminas-servicemanager` +- `doctrine/orm` ^2.9 || ^3.0, installed by your application, only if you use `AttributedRepositoryFactory` + +## Install + +Install `dotkernel/dot-dependency-injection` by executing the following Composer command: + +```shell +composer require dotkernel/dot-dependency-injection +``` + +`doctrine/orm` is not installed with this package. +If you use `AttributedRepositoryFactory`, require it in your application: + +```shell +composer require doctrine/orm +``` + +Upgrading from 1.x? See [Upgrading from 1.x](upgrading.md). diff --git a/docs/book/v2/overview.md b/docs/book/v2/overview.md new file mode 100644 index 0000000..241b058 --- /dev/null +++ b/docs/book/v2/overview.md @@ -0,0 +1,30 @@ +# Overview + +`dot-dependency-injection` is Dotkernel's dependency injection service. + +Instead of a handwritten factory class per service, you declare a class's dependencies with the `#[Inject]` attribute on its constructor - or a repository's entity with `#[Entity]` - and register one of the two reusable factories this package ships. +That removes an entire category of boilerplate files from a project and keeps the dependency list next to the constructor it feeds. + +It provides: + +- `Dot\DependencyInjection\Attribute\Inject` - declares the dependencies of a constructor +- `Dot\DependencyInjection\Attribute\Entity` - declares the entity of a Doctrine repository +- `Dot\DependencyInjection\Factory\AttributedServiceFactory` - builds any class from its `#[Inject]` attribute +- `Dot\DependencyInjection\Factory\AttributedRepositoryFactory` - builds any Doctrine repository from its `#[Entity]` attribute + +Continue with [Attributes vs. factories](attributes-vs-factories.md) for the comparison and the trade-offs, or with [Installation](installation.md). + +## Badges + +![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-dependency-injection) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-dependency-injection/2.0.0) + +[![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-dependency-injection)](https://github.com/dotkernel/dot-dependency-injection/issues) +[![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-dependency-injection)](https://github.com/dotkernel/dot-dependency-injection/network) +[![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-dependency-injection)](https://github.com/dotkernel/dot-dependency-injection/stargazers) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-dependency-injection)](https://github.com/dotkernel/dot-dependency-injection/blob/2.0/LICENSE.md) + +[![Build Static](https://github.com/dotkernel/dot-dependency-injection/actions/workflows/continuous-integration.yml/badge.svg?branch=2.0)](https://github.com/dotkernel/dot-dependency-injection/actions/workflows/continuous-integration.yml) +[![codecov](https://codecov.io/gh/dotkernel/dot-dependency-injection/graph/badge.svg?token=DayAoD2Oj6)](https://codecov.io/gh/dotkernel/dot-dependency-injection) +[![docs-build](https://github.com/dotkernel/dot-dependency-injection/actions/workflows/docs-build.yml/badge.svg)](https://github.com/dotkernel/dot-dependency-injection/actions/workflows/docs-build.yml) +[![PHPStan](https://github.com/dotkernel/dot-dependency-injection/actions/workflows/static-analysis.yml/badge.svg?branch=2.0)](https://github.com/dotkernel/dot-dependency-injection/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..ebf417f --- /dev/null +++ b/docs/book/v2/upgrading.md @@ -0,0 +1,70 @@ +# Upgrading from 1.x + +Version 2.0 keeps the attributes, the factories and the way you register them. +Most applications upgrade by changing the version constraint and, if they use `AttributedRepositoryFactory`, requiring `doctrine/orm` themselves. + +```shell +composer require dotkernel/dot-dependency-injection:^2.0 +``` + +## Requirements + +| | 1.x | 2.0 | +| --- | --- | --- | +| PHP | 8.3, 8.4, 8.5 | 8.3, 8.4, 8.5, 8.6 | +| `psr/container` | ^1.0 \|\| ^2.0 | ^1.1 \|\| ^2.0 | +| `doctrine/orm` | ^2.9 \|\| ^3.0, installed by this package | ^2.9 \|\| ^3.0, installed by your application when you use `AttributedRepositoryFactory` | + +## Changes that can break your code + +| Change | Symptom | Fix | +| --- | --- | --- | +| `doctrine/orm` is no longer installed by this package | `"Dot\DependencyInjection\Factory\AttributedRepositoryFactory" requires "doctrine/orm"`, or `Class "Doctrine\ORM\..." not found` in your own code | `composer require doctrine/orm` | +| `doctrine/orm` 4 is blocked by a `conflict` rule | Composer refuses to resolve | stay on `doctrine/orm` ^2.9 or ^3.0 | +| `psr/container` 1.0 is no longer supported | Composer refuses to resolve | update `psr/container` to 1.1 or 2.x | +| `AttributedServiceFactory::$originalKey` was removed | `Undefined property` in a subclass of the factory | use the `$serviceKey` parameter of `readKeysFromArray()` | +| `readKeysFromArray()` has a third parameter, `string $serviceKey` | fatal error in a subclass that overrides it: declaration must be compatible | add the parameter to your override | +| an abstract class, an enum or a class with a non-public constructor is requested | `RuntimeException` instead of PHP `Error` | register a concrete class | +| an unregistered dependency needs constructor arguments, or is abstract or an enum | `RuntimeException` instead of `ArgumentCountError` or `Error` | register the dependency in your container | +| the number of `#[Inject]` entries is checked against the constructor | `RuntimeException` for missing or extra entries; extra entries used to be ignored silently | make the list match the constructor | +| empty dot-notation segments are rejected | `InvalidArgumentException` for keys such as `config.` or `config..debug` | remove the stray dot | +| the `Doctrine\ORM\EntityManagerInterface` service is type-checked | `RuntimeException` instead of PHP `Error` when the service is not an entity manager | register an entity manager under that key | + +All new exceptions implement `Dot\DependencyInjection\Exception\ExceptionInterface`, so code that catches it keeps working. + +## Overriding `readKeysFromArray()` + +Before: + +```php +use Dot\DependencyInjection\Factory\AttributedServiceFactory; + +class MyFactory extends AttributedServiceFactory +{ + protected function readKeysFromArray(array $keys, mixed $array): mixed + { + // $this->originalKey held the full dotted key + return parent::readKeysFromArray($keys, $array); + } +} +``` + +After: + +```php +use Dot\DependencyInjection\Factory\AttributedServiceFactory; + +class MyFactory extends AttributedServiceFactory +{ + protected function readKeysFromArray(array $keys, mixed $array, string $serviceKey): mixed + { + // $serviceKey holds the full dotted key + return parent::readKeysFromArray($keys, $array, $serviceKey); + } +} +``` + +## Checking an application + +After upgrading, build every service once, for example with a test that requests each key of your `dependencies.factories` configuration from the container. +The new checks run when a service is built, so a mismatch that 1.x ignored shows up there with a message naming the class. diff --git a/docs/book/v2/usage.md b/docs/book/v2/usage.md new file mode 100644 index 0000000..535ea00 --- /dev/null +++ b/docs/book/v2/usage.md @@ -0,0 +1,14 @@ +# Usage + +Start with [Attributes vs. factories](attributes-vs-factories.md) for what this package replaces and why. + +You can use it to: + +- [Inject class dependencies](factories/service.md) +- [Inject entity repositories](factories/repository.md) + +Both are described in detail in [Factories](factories.md). + +For the questions that come up most often, see the [FAQ](faq.md). + +Coming from 1.x? See [Upgrading from 1.x](upgrading.md). diff --git a/mkdocs.yml b/mkdocs.yml index 2123c6f..5f9c893 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -2,11 +2,24 @@ 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 + - FAQ: v2/faq.md + - "Attributes vs. factories": v2/attributes-vs-factories.md + - Factories: v2/factories.md + - Reference: + - "Inject class dependencies": v2/factories/service.md + - "Inject entity repositories": v2/factories/repository.md + - "Upgrading from 1.x": 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 2f742e5..5243a45 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,13 +1,24 @@ - + ./test ./test/TestData - - + ./src diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index 03452bb..5c8fd4e 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -6,6 +6,9 @@ class ConfigProvider { + /** + * @return array + */ public function __invoke(): array { return []; diff --git a/src/Exception/InvalidArgumentException.php b/src/Exception/InvalidArgumentException.php index 026ee4b..e38a8df 100644 --- a/src/Exception/InvalidArgumentException.php +++ b/src/Exception/InvalidArgumentException.php @@ -8,11 +8,18 @@ class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface { - public const MESSAGE_MISSING_KEY = + public const MESSAGE_EMPTY_SEGMENT = + 'The dotted key "%s" contains an empty segment.'; + public const MESSAGE_MISSING_KEY = 'The key "%s" provided in the dotted notation could not be found in the array service.'; public static function missingKey(string $serviceKey): self { return new self(sprintf(self::MESSAGE_MISSING_KEY, $serviceKey)); } + + public static function emptySegment(string $serviceKey): self + { + return new self(sprintf(self::MESSAGE_EMPTY_SEGMENT, $serviceKey)); + } } diff --git a/src/Exception/RuntimeException.php b/src/Exception/RuntimeException.php index 14c73b9..8a85608 100644 --- a/src/Exception/RuntimeException.php +++ b/src/Exception/RuntimeException.php @@ -8,15 +8,25 @@ class RuntimeException extends \RuntimeException implements ExceptionInterface { - public const MESSAGE_ATTRIBUTE_NOT_FOUND = + public const MESSAGE_ARGUMENT_COUNT = + 'The #[Inject] attribute of "%s" lists %d dependencies, but its constructor accepts %d to %d.'; + public const MESSAGE_ATTRIBUTE_NOT_FOUND = 'You need to use the "%s" attribute on the "%s" class so that "%s" can create it.'; - public const MESSAGE_CLASS_NOT_FOUND = + public const MESSAGE_CLASS_NOT_FOUND = 'Defined injectable "%s" could not be found in container or as a class.'; - public const MESSAGE_DOES_NOT_EXTEND = + public const MESSAGE_DEPENDENCY_NOT_INSTANTIABLE = + 'Injectable "%s" is not registered in the container and can not be instantiated without arguments.'; + public const MESSAGE_DOES_NOT_EXTEND = 'Class "%s" must extend class "%s".'; - public const MESSAGE_RECURSIVE_INJECT = + public const MESSAGE_INVALID_SERVICE = + 'Service "%s" must be an instance of "%s", "%s" given.'; + public const MESSAGE_MISSING_PACKAGE = + '"%2$s" requires "%1$s": run "composer require %1$s".'; + public const MESSAGE_NOT_INSTANTIABLE = + 'Class "%s" can not be instantiated: it is abstract, an enum, or its constructor is not public.'; + public const MESSAGE_RECURSIVE_INJECT = 'Class "%s" can not be injected into itself.'; - public const MESSAGE_UNEXPECTED_REPOSITORY = + public const MESSAGE_UNEXPECTED_REPOSITORY = 'Doctrine returned an instance of "%s" instead of "%s". ' . 'Make sure that entity "%s" declares #[ORM\Entity(repositoryClass: ...)] pointing to it.'; @@ -44,4 +54,29 @@ public static function unexpectedRepository(string $actual, string $requestedNam { return new self(sprintf(self::MESSAGE_UNEXPECTED_REPOSITORY, $actual, $requestedName, $entity)); } + + public static function invalidService(string $serviceName, string $class, string $actual): self + { + return new self(sprintf(self::MESSAGE_INVALID_SERVICE, $serviceName, $class, $actual)); + } + + public static function missingPackage(string $package, string $class): self + { + return new self(sprintf(self::MESSAGE_MISSING_PACKAGE, $package, $class)); + } + + public static function notInstantiable(string $requestedName): self + { + return new self(sprintf(self::MESSAGE_NOT_INSTANTIABLE, $requestedName)); + } + + public static function dependencyNotInstantiable(string $dependency): self + { + return new self(sprintf(self::MESSAGE_DEPENDENCY_NOT_INSTANTIABLE, $dependency)); + } + + public static function argumentCountMismatch(string $requestedName, int $count, int $min, int $max): self + { + return new self(sprintf(self::MESSAGE_ARGUMENT_COUNT, $requestedName, $count, $min, $max)); + } } diff --git a/src/Factory/AttributedRepositoryFactory.php b/src/Factory/AttributedRepositoryFactory.php index dc38488..c44bbed 100644 --- a/src/Factory/AttributedRepositoryFactory.php +++ b/src/Factory/AttributedRepositoryFactory.php @@ -14,6 +14,7 @@ use ReflectionClass; use function class_exists; +use function get_debug_type; use function is_a; /** @@ -22,6 +23,7 @@ class AttributedRepositoryFactory { /** + * @return EntityRepository * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface * @throws RuntimeException @@ -32,12 +34,17 @@ public function __invoke(ContainerInterface $container, string $requestedName): } /** + * @return EntityRepository * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface * @throws RuntimeException */ public function createObject(ContainerInterface $container, string $requestedName): EntityRepository { + if (! class_exists(EntityRepository::class)) { + throw RuntimeException::missingPackage('doctrine/orm', static::class); + } + if (! class_exists($requestedName)) { throw RuntimeException::classNotFound($requestedName); } @@ -57,7 +64,16 @@ public function createObject(ContainerInterface $container, string $requestedNam throw RuntimeException::classNotFound($entityName); } - $repository = $container->get(EntityManagerInterface::class)->getRepository($entityName); + $entityManager = $container->get(EntityManagerInterface::class); + if (! $entityManager instanceof EntityManagerInterface) { + throw RuntimeException::invalidService( + EntityManagerInterface::class, + EntityManagerInterface::class, + get_debug_type($entityManager) + ); + } + + $repository = $entityManager->getRepository($entityName); if (! is_a($repository, $requestedName)) { throw RuntimeException::unexpectedRepository($repository::class, $requestedName, $entityName); } diff --git a/src/Factory/AttributedServiceFactory.php b/src/Factory/AttributedServiceFactory.php index 4bea971..18a02fe 100644 --- a/src/Factory/AttributedServiceFactory.php +++ b/src/Factory/AttributedServiceFactory.php @@ -27,12 +27,6 @@ */ class AttributedServiceFactory { - /** - * Retained for backwards compatibility with subclasses overriding readKeysFromArray(). - * Assigned immediately before the call, so a nested service creation cannot overwrite it. - */ - protected string $originalKey = ''; - /** * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface @@ -56,9 +50,14 @@ public function createObject(ContainerInterface $container, string $requestedNam throw RuntimeException::classNotFound($requestedName); } - $constructor = (new ReflectionClass($requestedName))->getConstructor(); + $reflectionClass = new ReflectionClass($requestedName); + if (! $reflectionClass->isInstantiable()) { + throw RuntimeException::notInstantiable($requestedName); + } + + $constructor = $reflectionClass->getConstructor(); if ($constructor === null) { - return new $requestedName(); + return $reflectionClass->newInstance(); } $injectAttribute = $this->findInjectAttribute($constructor); @@ -66,13 +65,25 @@ public function createObject(ContainerInterface $container, string $requestedNam throw RuntimeException::attributeNotFound(Inject::class, $requestedName, static::class); } - if (in_array($requestedName, $injectAttribute->getServices(), true)) { + $serviceKeys = $injectAttribute->getServices(); + if (in_array($requestedName, $serviceKeys, true)) { throw RuntimeException::recursiveInject($requestedName); } - $services = $this->getServicesToInject($container, $injectAttribute->getServices()); + $count = count($serviceKeys); + if ( + $count < $constructor->getNumberOfRequiredParameters() + || (! $constructor->isVariadic() && $count > $constructor->getNumberOfParameters()) + ) { + throw RuntimeException::argumentCountMismatch( + $requestedName, + $count, + $constructor->getNumberOfRequiredParameters(), + $constructor->getNumberOfParameters() + ); + } - return new $requestedName(...$services); + return $reflectionClass->newInstanceArgs($this->getServicesToInject($container, $serviceKeys)); } protected function findInjectAttribute(ReflectionMethod $constructor): ?Inject @@ -114,69 +125,67 @@ protected function getServiceToInject(ContainerInterface $container, string $ser * Even when dots are found, try to find a service with the full name. * If it is not found, then assume dots are used to get part of an array service */ - $parts = explode('.', $serviceKey); - $identifier = $serviceKey; - if (count($parts) > 1 && ! $container->has($serviceKey)) { - $identifier = array_shift($parts); - } else { - $parts = []; + if ($container->has($serviceKey)) { + return $container->get($serviceKey); + } + + $keys = explode('.', $serviceKey); + $identifier = array_shift($keys); + if (in_array('', $keys, true) || ($keys !== [] && $identifier === '')) { + throw InvalidArgumentException::emptySegment($serviceKey); } if ($container->has($identifier)) { $service = $container->get($identifier); - } elseif (class_exists($identifier)) { + } elseif ($this->canInstantiateWithoutArguments($identifier)) { $service = new $identifier(); + } elseif (class_exists($identifier)) { + throw RuntimeException::dependencyNotInstantiable($identifier); } else { throw RuntimeException::classNotFound($identifier); } - if ($parts === []) { + if ($keys === []) { return $service; } - $this->originalKey = $serviceKey; - - return $this->readKeysFromArray($parts, $service); + return $this->readKeysFromArray($keys, $service, $serviceKey); } /** * @param non-empty-list $keys + * @param string $serviceKey The full dotted key, used in the exception message. * @throws InvalidArgumentException */ - protected function readKeysFromArray(array $keys, mixed $array): mixed + protected function readKeysFromArray(array $keys, mixed $array, string $serviceKey): mixed { - $key = array_shift($keys); - if (! $this->hasKey($array, $key)) { - throw InvalidArgumentException::missingKey($this->originalKey); - } - - $value = $array[$key]; - if ($keys === []) { - return $value; + foreach ($keys as $key) { + if (is_array($array) && array_key_exists($key, $array)) { + $array = $array[$key]; + continue; + } + + if ($array instanceof ArrayAccess && $array->offsetExists($key)) { + $array = $array[$key]; + continue; + } + + throw InvalidArgumentException::missingKey($serviceKey); } - if (! is_array($value) && ! $value instanceof ArrayAccess) { - throw InvalidArgumentException::missingKey($this->originalKey); - } - - return $this->readKeysFromArray($keys, $value); + return $array; } - /** - * Unlike isset(), this does not treat a null value as a missing key. - * - * Private so that it cannot collide with a method of the same name in a subclass. - */ - private function hasKey(mixed $array, string $key): bool + private function canInstantiateWithoutArguments(string $class): bool { - if (is_array($array)) { - return array_key_exists($key, $array); + if (! class_exists($class)) { + return false; } - if ($array instanceof ArrayAccess) { - return $array->offsetExists($key); - } + $reflectionClass = new ReflectionClass($class); + $constructor = $reflectionClass->getConstructor(); - return false; + return $reflectionClass->isInstantiable() + && ($constructor === null || $constructor->getNumberOfRequiredParameters() === 0); } } diff --git a/test/ConfigProviderTest.php b/test/ConfigProviderTest.php index 02365e6..28b20fb 100644 --- a/test/ConfigProviderTest.php +++ b/test/ConfigProviderTest.php @@ -9,9 +9,10 @@ class ConfigProviderTest extends TestCase { + /** @var array */ protected array $config; - protected function setup(): void + protected function setUp(): void { $this->config = (new ConfigProvider())(); } diff --git a/test/Exception/RuntimeExceptionTest.php b/test/Exception/RuntimeExceptionTest.php new file mode 100644 index 0000000..0940cca --- /dev/null +++ b/test/Exception/RuntimeExceptionTest.php @@ -0,0 +1,26 @@ +assertSame( + '"' . AttributedRepositoryFactory::class . '" requires "doctrine/orm": ' + . 'run "composer require doctrine/orm".', + $exception->getMessage() + ); + } +} diff --git a/test/Factory/AttributedRepositoryFactoryTest.php b/test/Factory/AttributedRepositoryFactoryTest.php index 9937d7e..584e78f 100644 --- a/test/Factory/AttributedRepositoryFactoryTest.php +++ b/test/Factory/AttributedRepositoryFactoryTest.php @@ -10,45 +10,39 @@ use Dot\DependencyInjection\Attribute\Entity; use Dot\DependencyInjection\Exception\RuntimeException; use Dot\DependencyInjection\Factory\AttributedRepositoryFactory; +use DotTest\DependencyInjection\TestData\ChildRepository; +use DotTest\DependencyInjection\TestData\Container; use DotTest\DependencyInjection\TestData\Entity as TestEntity; use DotTest\DependencyInjection\TestData\InvalidEntityRepository; use DotTest\DependencyInjection\TestData\Repository as TestRepository; use PHPUnit\Framework\MockObject\Exception; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use stdClass; use function sprintf; class AttributedRepositoryFactoryTest extends TestCase { /** - * @throws Exception * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ public function testWillThrowExceptionIfClassNotFound(): void { - $container = $this->createMock(ContainerInterface::class); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - sprintf(RuntimeException::MESSAGE_CLASS_NOT_FOUND, 'test') - ); + $this->expectExceptionMessage(sprintf(RuntimeException::MESSAGE_CLASS_NOT_FOUND, 'test')); - (new AttributedRepositoryFactory())($container, 'test'); + (new AttributedRepositoryFactory())(new Container(), 'test'); } /** - * @throws Exception * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ public function testWillThrowExceptionIfRepositoryDoesNotExtendEntityRepository(): void { - $container = $this->createMock(ContainerInterface::class); - $subject = new class { }; @@ -57,7 +51,7 @@ public function testWillThrowExceptionIfRepositoryDoesNotExtendEntityRepository( sprintf(RuntimeException::MESSAGE_DOES_NOT_EXTEND, $subject::class, EntityRepository::class) ); - (new AttributedRepositoryFactory())($container, $subject::class); + (new AttributedRepositoryFactory())(new Container(), $subject::class); } /** @@ -67,13 +61,12 @@ public function testWillThrowExceptionIfRepositoryDoesNotExtendEntityRepository( */ public function testWillThrowExceptionIfAttributeNotFound(): void { - $container = $this->createMock(ContainerInterface::class); - $entityManager = $this->createMock(EntityManagerInterface::class); - - $entity = new class { + $entity = new class { }; - $metadata = new ClassMetadata($entity::class); - $subject = new class ($entityManager, $metadata) extends EntityRepository { + $subject = new class ( + $this->createStub(EntityManagerInterface::class), + new ClassMetadata($entity::class) + ) extends EntityRepository { }; $this->expectException(RuntimeException::class); @@ -86,56 +79,85 @@ public function testWillThrowExceptionIfAttributeNotFound(): void ) ); - (new AttributedRepositoryFactory())($container, $subject::class); + (new AttributedRepositoryFactory())(new Container(), $subject::class); } /** + * @throws Exception * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface - * @throws Exception */ public function testWillCreateRepository(): void { $entityManager = $this->createMock(EntityManagerInterface::class); - $container = $this->createMock(ContainerInterface::class); - - $entity = new TestEntity(); - $metadata = new ClassMetadata($entity::class); - $subject = new TestRepository($entityManager, $metadata); + $subject = new TestRepository($entityManager, new ClassMetadata(TestEntity::class)); - $container - ->expects($this->once()) - ->method('get') - ->with(EntityManagerInterface::class) - ->willReturn($entityManager); $entityManager ->expects($this->once()) ->method('getRepository') ->with(TestEntity::class) ->willReturn($subject); + $container = new Container([EntityManagerInterface::class => $entityManager]); $repository = (new AttributedRepositoryFactory())($container, TestRepository::class); - $this->assertInstanceOf(TestRepository::class, $repository); + + $this->assertSame($subject, $repository); + $this->assertSame([EntityManagerInterface::class], $container->getRequested()); } /** - * @throws Exception * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ public function testWillThrowExceptionIfEntityClassNotFound(): void { - $container = $this->createMock(ContainerInterface::class); + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage( + sprintf(RuntimeException::MESSAGE_CLASS_NOT_FOUND, 'DotTest\\DependencyInjection\\TestData\\NotAnEntity') + ); + + (new AttributedRepositoryFactory())(new Container(), InvalidEntityRepository::class); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testWillThrowExceptionIfEntityAttributeIsOnlyOnTheParentRepository(): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage( + sprintf( + RuntimeException::MESSAGE_ATTRIBUTE_NOT_FOUND, + Entity::class, + ChildRepository::class, + AttributedRepositoryFactory::class + ) + ); + (new AttributedRepositoryFactory())(new Container(), ChildRepository::class); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testWillThrowExceptionIfEntityManagerServiceIsInvalid(): void + { $this->expectException(RuntimeException::class); $this->expectExceptionMessage( sprintf( - RuntimeException::MESSAGE_CLASS_NOT_FOUND, - 'DotTest\\DependencyInjection\\TestData\\NotAnEntity' + RuntimeException::MESSAGE_INVALID_SERVICE, + EntityManagerInterface::class, + EntityManagerInterface::class, + stdClass::class ) ); - (new AttributedRepositoryFactory())($container, InvalidEntityRepository::class); + (new AttributedRepositoryFactory())( + new Container([EntityManagerInterface::class => new stdClass()]), + TestRepository::class + ); } /** @@ -146,17 +168,9 @@ public function testWillThrowExceptionIfEntityClassNotFound(): void public function testWillThrowExceptionIfDoctrineReturnsAnotherRepository(): void { $entityManager = $this->createMock(EntityManagerInterface::class); - $container = $this->createMock(ContainerInterface::class); - - $metadata = new ClassMetadata(TestEntity::class); - $repository = new class ($entityManager, $metadata) extends EntityRepository { + $repository = new class ($entityManager, new ClassMetadata(TestEntity::class)) extends EntityRepository { }; - $container - ->expects($this->once()) - ->method('get') - ->with(EntityManagerInterface::class) - ->willReturn($entityManager); $entityManager ->expects($this->once()) ->method('getRepository') @@ -173,6 +187,9 @@ public function testWillThrowExceptionIfDoctrineReturnsAnotherRepository(): void ) ); - (new AttributedRepositoryFactory())($container, TestRepository::class); + (new AttributedRepositoryFactory())( + new Container([EntityManagerInterface::class => $entityManager]), + TestRepository::class + ); } } diff --git a/test/Factory/AttributedServiceFactoryTest.php b/test/Factory/AttributedServiceFactoryTest.php index 3bfe3e0..dfdc7b3 100644 --- a/test/Factory/AttributedServiceFactoryTest.php +++ b/test/Factory/AttributedServiceFactoryTest.php @@ -9,47 +9,43 @@ use Dot\DependencyInjection\Exception\InvalidArgumentException; use Dot\DependencyInjection\Exception\RuntimeException; use Dot\DependencyInjection\Factory\AttributedServiceFactory; +use DotTest\DependencyInjection\TestData\AbstractService; +use DotTest\DependencyInjection\TestData\ArgumentService; +use DotTest\DependencyInjection\TestData\ChildService; +use DotTest\DependencyInjection\TestData\Container; +use DotTest\DependencyInjection\TestData\EnumService; +use DotTest\DependencyInjection\TestData\PrivateConstructorService; use DotTest\DependencyInjection\TestData\RecursionService; use DotTest\DependencyInjection\TestData\ValidService; -use PHPUnit\Framework\MockObject\Exception; +use DotTest\DependencyInjection\TestData\VariadicService; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; -use function array_key_exists; use function sprintf; class AttributedServiceFactoryTest extends TestCase { /** - * @throws Exception * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ public function testWillThrowExceptionIfClassNotFound(): void { - $container = $this->createMock(ContainerInterface::class); - - $subject = 'test'; - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - sprintf(RuntimeException::MESSAGE_CLASS_NOT_FOUND, $subject) - ); + $this->expectExceptionMessage(sprintf(RuntimeException::MESSAGE_CLASS_NOT_FOUND, 'test')); - (new AttributedServiceFactory())($container, $subject); + (new AttributedServiceFactory())(new Container(), 'test'); } /** - * @throws Exception * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ public function testWillThrowExceptionIfAttributeNotFound(): void { - $container = $this->createMock(ContainerInterface::class); - $subject = new class { public function __construct() { @@ -66,39 +62,28 @@ public function __construct() ) ); - (new AttributedServiceFactory())($container, $subject::class); + (new AttributedServiceFactory())(new Container(), $subject::class); } /** - * @throws Exception * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ public function testWillThrowExceptionOnRecursiveInjection(): void { - $container = $this->createMock(ContainerInterface::class); - - $subject = new RecursionService(); - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - sprintf( - RuntimeException::MESSAGE_RECURSIVE_INJECT, - $subject::class - ) - ); + $this->expectExceptionMessage(sprintf(RuntimeException::MESSAGE_RECURSIVE_INJECT, RecursionService::class)); - (new AttributedServiceFactory())($container, $subject::class); + (new AttributedServiceFactory())(new Container(), RecursionService::class); } /** * @throws ContainerExceptionInterface - * @throws Exception * @throws NotFoundExceptionInterface */ public function testWillThrowExceptionIfDottedServiceNotFound(): void { - $mapping = [ + $container = new Container([ 'config' => [ 'uration' => [ 'test' => [], @@ -108,22 +93,12 @@ public function testWillThrowExceptionIfDottedServiceNotFound(): void 'test' => [], ], 'key' => [], - ]; - - $container = $this->createMock(ContainerInterface::class); - $container->expects($this->any())->method('has')->willReturnCallback( - function (string $key) use ($mapping): bool { - return array_key_exists($key, $mapping); - }, - ); - $container->expects($this->any())->method('get')->willReturnCallback( - function (string $key) use ($mapping): array { - return $mapping[$key] ?? []; - }, - ); + ]); - $subject = new class - { + $subject = new class { + /** + * @param array $config + */ #[Inject('config.uration.key')] public function __construct(public array $config = []) { @@ -131,24 +106,18 @@ public function __construct(public array $config = []) }; $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage( - sprintf(InvalidArgumentException::MESSAGE_MISSING_KEY, 'config.uration.key') - ); + $this->expectExceptionMessage(sprintf(InvalidArgumentException::MESSAGE_MISSING_KEY, 'config.uration.key')); (new AttributedServiceFactory())($container, $subject::class); } /** * @throws ContainerExceptionInterface - * @throws Exception * @throws NotFoundExceptionInterface */ public function testWillThrowExceptionIfDependencyNotFound(): void { - $container = $this->createMock(ContainerInterface::class); - - $subject = new class - { + $subject = new class { #[Inject('test')] public function __construct(public mixed $test = null) { @@ -156,74 +125,47 @@ public function __construct(public mixed $test = null) }; $this->expectException(RuntimeException::class); - $this->expectExceptionMessage( - sprintf(RuntimeException::MESSAGE_CLASS_NOT_FOUND, 'test') - ); + $this->expectExceptionMessage(sprintf(RuntimeException::MESSAGE_CLASS_NOT_FOUND, 'test')); - (new AttributedServiceFactory())($container, $subject::class); + (new AttributedServiceFactory())(new Container(), $subject::class); } /** * @throws ContainerExceptionInterface - * @throws Exception * @throws NotFoundExceptionInterface */ public function testWillCreateServiceIfNoConstructor(): void { - $container = $this->createMock(ContainerInterface::class); - $subject = new class { }; - $service = (new AttributedServiceFactory())($container, $subject::class); + $service = (new AttributedServiceFactory())(new Container(), $subject::class); $this->assertInstanceOf($subject::class, $service); } /** * @throws ContainerExceptionInterface - * @throws Exception * @throws NotFoundExceptionInterface */ public function testWillCreateService(): void { - $mapping = [ + $container = new Container([ 'config' => [ 'uration' => [], ], 'uration' => [], - ]; - - $container = $this->createMock(ContainerInterface::class); - $container->expects($this->any())->method('has')->willReturnCallback( - function (string $key) use ($mapping): bool { - return array_key_exists($key, $mapping); - }, - ); - $container->expects($this->any())->method('get')->willReturnCallback( - function (string $key) use ($mapping): array { - return $mapping[$key] ?? []; - }, - ); - - $subject = new ValidService(); + ]); - $service = (new AttributedServiceFactory())($container, $subject::class); + $service = (new AttributedServiceFactory())($container, ValidService::class); $this->assertInstanceOf(ValidService::class, $service); } /** * @throws ContainerExceptionInterface - * @throws Exception * @throws NotFoundExceptionInterface */ public function testWillInjectNullValueFromDottedNotation(): void { - $container = $this->createMock(ContainerInterface::class); - $container->expects($this->any())->method('has')->willReturnCallback( - fn (string $key): bool => $key === 'config', - ); - $container->expects($this->any())->method('get')->willReturn(['debug' => null]); - $subject = new class { #[Inject('config.debug')] public function __construct(public mixed $debug = 'not injected') @@ -231,23 +173,16 @@ public function __construct(public mixed $debug = 'not injected') } }; - $service = (new AttributedServiceFactory())($container, $subject::class); + $service = (new AttributedServiceFactory())(new Container(['config' => ['debug' => null]]), $subject::class); $this->assertNull($service->debug); } /** * @throws ContainerExceptionInterface - * @throws Exception * @throws NotFoundExceptionInterface */ public function testWillThrowExceptionIfDottedNotationOvershootsAScalar(): void { - $container = $this->createMock(ContainerInterface::class); - $container->expects($this->any())->method('has')->willReturnCallback( - fn (string $key): bool => $key === 'config', - ); - $container->expects($this->any())->method('get')->willReturn(['debug' => true]); - $subject = new class { #[Inject('config.debug.verbose')] public function __construct(public mixed $verbose = null) @@ -256,27 +191,20 @@ public function __construct(public mixed $verbose = null) }; $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage( - sprintf(InvalidArgumentException::MESSAGE_MISSING_KEY, 'config.debug.verbose') - ); + $this->expectExceptionMessage(sprintf(InvalidArgumentException::MESSAGE_MISSING_KEY, 'config.debug.verbose')); - (new AttributedServiceFactory())($container, $subject::class); + (new AttributedServiceFactory())(new Container(['config' => ['debug' => true]]), $subject::class); } /** * @throws ContainerExceptionInterface - * @throws Exception * @throws NotFoundExceptionInterface */ public function testWillReadDottedNotationFromArrayAccessService(): void { - $container = $this->createMock(ContainerInterface::class); - $container->expects($this->any())->method('has')->willReturnCallback( - fn (string $key): bool => $key === 'config', - ); - $container->expects($this->any())->method('get')->willReturn( - new ArrayObject(['nested' => new ArrayObject(['value' => 'injected'])]) - ); + $container = new Container([ + 'config' => new ArrayObject(['nested' => new ArrayObject(['value' => 'injected'])]), + ]); $subject = new class { #[Inject('config.nested.value')] @@ -291,22 +219,19 @@ public function __construct(public ?string $value = null) /** * @throws ContainerExceptionInterface - * @throws Exception * @throws NotFoundExceptionInterface */ public function testWillPreferAServiceNamedLikeTheDottedKey(): void { - $container = $this->createMock(ContainerInterface::class); - $container->expects($this->any())->method('has')->willReturnCallback( - fn (string $key): bool => $key === 'config.debug', - ); - $container - ->expects($this->once()) - ->method('get') - ->with('config.debug') - ->willReturn(['full-service']); + $container = new Container([ + 'config' => ['debug' => ['from-config']], + 'config.debug' => ['full-service'], + ]); $subject = new class { + /** + * @param list $debug + */ #[Inject('config.debug')] public function __construct(public array $debug = []) { @@ -315,18 +240,16 @@ public function __construct(public array $debug = []) $service = (new AttributedServiceFactory())($container, $subject::class); $this->assertSame(['full-service'], $service->debug); + $this->assertSame(['config.debug'], $container->getRequested()); } /** * @throws ContainerExceptionInterface - * @throws Exception * @throws NotFoundExceptionInterface */ public function testWillInstantiateAnUnregisteredClassDependency(): void { - $container = $this->createMock(ContainerInterface::class); - $container->expects($this->any())->method('has')->willReturn(false); - $container->expects($this->never())->method('get'); + $container = new Container(); $subject = new class { #[Inject(ValidService::class)] @@ -337,21 +260,15 @@ public function __construct(public ?ValidService $service = null) $service = (new AttributedServiceFactory())($container, $subject::class); $this->assertInstanceOf(ValidService::class, $service->service); + $this->assertSame([], $container->getRequested()); } /** * @throws ContainerExceptionInterface - * @throws Exception * @throws NotFoundExceptionInterface */ public function testWillThrowExceptionIfDottedNotationIsUsedOnANonArrayService(): void { - $container = $this->createMock(ContainerInterface::class); - $container->expects($this->any())->method('has')->willReturnCallback( - fn (string $key): bool => $key === 'version', - ); - $container->expects($this->any())->method('get')->willReturn('1.0.0'); - $subject = new class { #[Inject('version.major')] public function __construct(public mixed $major = null) @@ -360,10 +277,241 @@ public function __construct(public mixed $major = null) }; $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage(sprintf(InvalidArgumentException::MESSAGE_MISSING_KEY, 'version.major')); + + (new AttributedServiceFactory())(new Container(['version' => '1.0.0']), $subject::class); + } + + /** + * @return iterable + */ + public static function notInstantiableProvider(): iterable + { + yield 'abstract class' => [AbstractService::class]; + yield 'enum' => [EnumService::class]; + yield 'private constructor' => [PrivateConstructorService::class]; + } + + /** + * @param class-string $class + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + #[DataProvider('notInstantiableProvider')] + public function testWillThrowExceptionIfRequestedClassIsNotInstantiable(string $class): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage(sprintf(RuntimeException::MESSAGE_NOT_INSTANTIABLE, $class)); + + (new AttributedServiceFactory())(new Container(), $class); + } + + /** + * @return iterable + */ + public static function dependencyNotInstantiableProvider(): iterable + { + yield 'required constructor argument' => [ArgumentService::class]; + yield 'abstract class' => [AbstractService::class]; + yield 'enum' => [EnumService::class]; + yield 'private constructor' => [PrivateConstructorService::class]; + } + + /** + * @param class-string $dependency + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + #[DataProvider('dependencyNotInstantiableProvider')] + public function testWillThrowExceptionIfUnregisteredDependencyCannotBeInstantiated(string $dependency): void + { + $this->expectException(RuntimeException::class); $this->expectExceptionMessage( - sprintf(InvalidArgumentException::MESSAGE_MISSING_KEY, 'version.major') + sprintf(RuntimeException::MESSAGE_DEPENDENCY_NOT_INSTANTIABLE, $dependency) ); + $this->resolve(new Container(), $dependency); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testWillThrowExceptionIfTooFewDependenciesAreListed(): void + { + $subject = new class ('', '') { + #[Inject('config')] + public function __construct(public mixed $first, public mixed $second) + { + } + }; + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage(sprintf(RuntimeException::MESSAGE_ARGUMENT_COUNT, $subject::class, 1, 2, 2)); + + (new AttributedServiceFactory())(new Container(['config' => []]), $subject::class); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testWillThrowExceptionIfTooManyDependenciesAreListed(): void + { + $container = new Container(['config' => []]); + + $subject = new class { + #[Inject('config', 'config')] + public function __construct(public mixed $config = null) + { + } + }; + + try { + (new AttributedServiceFactory())($container, $subject::class); + $this->fail('Expected ' . RuntimeException::class); + } catch (RuntimeException $exception) { + $this->assertSame( + sprintf(RuntimeException::MESSAGE_ARGUMENT_COUNT, $subject::class, 2, 0, 1), + $exception->getMessage() + ); + } + + $this->assertSame([], $container->getRequested(), 'The count must be checked before resolving'); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testWillAllowOmittingTrailingOptionalParameters(): void + { + $subject = new class { + #[Inject('config')] + public function __construct(public mixed $config = null, public string $optional = 'default') + { + } + }; + + $service = (new AttributedServiceFactory())(new Container(['config' => ['a' => 1]]), $subject::class); + $this->assertSame(['a' => 1], $service->config); + $this->assertSame('default', $service->optional); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testWillAllowExtraDependenciesForVariadicConstructor(): void + { + $container = new Container(['first' => 1, 'second' => 2, 'third' => 3]); + + $service = (new AttributedServiceFactory())($container, VariadicService::class); + $this->assertInstanceOf(VariadicService::class, $service); + $this->assertSame([1, 2, 3], $service->values); + } + + /** + * @return iterable + */ + public static function emptySegmentProvider(): iterable + { + yield 'trailing dot' => ['config.']; + yield 'leading dot' => ['.config']; + yield 'double dot' => ['config..debug']; + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + #[DataProvider('emptySegmentProvider')] + public function testWillThrowExceptionOnEmptyDotSegment(string $serviceKey): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage(sprintf(InvalidArgumentException::MESSAGE_EMPTY_SEGMENT, $serviceKey)); + + $this->resolve(new Container(['config' => ['' => 'empty key', 'debug' => true]]), $serviceKey); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testWillPreferAServiceRegisteredUnderAKeyWithAnEmptySegment(): void + { + $this->assertSame('registered', $this->resolve(new Container(['config.' => 'registered']), 'config.')); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testWillReportTheFullKeyWhenAnArrayAccessKeyIsMissing(): void + { + $container = new Container(['config' => new ArrayObject(['nested' => new ArrayObject([])])]); + + $subject = new class { + #[Inject('config.nested.missing')] + public function __construct(public mixed $value = null) + { + } + }; + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage(sprintf(InvalidArgumentException::MESSAGE_MISSING_KEY, 'config.nested.missing')); + (new AttributedServiceFactory())($container, $subject::class); } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testWillReportTheRightKeyForEachDependency(): void + { + $container = new Container(['config' => ['present' => 1]]); + + $subject = new class { + #[Inject('config.present', 'config.absent')] + public function __construct(public mixed $present = null, public mixed $absent = null) + { + } + }; + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage(sprintf(InvalidArgumentException::MESSAGE_MISSING_KEY, 'config.absent')); + + (new AttributedServiceFactory())($container, $subject::class); + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testWillCreateSubclassFromInheritedInjectAttribute(): void + { + $service = (new AttributedServiceFactory())(new Container(['dependency' => 'injected']), ChildService::class); + + $this->assertInstanceOf(ChildService::class, $service); + $this->assertSame('injected', $service->dependency); + } + + /** + * Resolves a single #[Inject] entry, as the factory does for each constructor argument. + * + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + private function resolve(ContainerInterface $container, string $serviceKey): mixed + { + $factory = new class extends AttributedServiceFactory { + public function resolve(ContainerInterface $container, string $serviceKey): mixed + { + return $this->getServiceToInject($container, $serviceKey); + } + }; + + return $factory->resolve($container, $serviceKey); + } } diff --git a/test/TestData/AbstractService.php b/test/TestData/AbstractService.php new file mode 100644 index 0000000..f8bf455 --- /dev/null +++ b/test/TestData/AbstractService.php @@ -0,0 +1,9 @@ + */ + private array $requested = []; + + /** + * @param array $services + */ + public function __construct(private readonly array $services = []) + { + } + + public function get(string $id): mixed + { + if (! array_key_exists($id, $this->services)) { + throw new ServiceNotFoundException($id); + } + + $this->requested[] = $id; + + return $this->services[$id]; + } + + public function has(string $id): bool + { + return array_key_exists($id, $this->services); + } + + /** + * @return list The identifiers passed to get(), in call order. + */ + public function getRequested(): array + { + return $this->requested; + } +} diff --git a/test/TestData/EnumService.php b/test/TestData/EnumService.php new file mode 100644 index 0000000..401646b --- /dev/null +++ b/test/TestData/EnumService.php @@ -0,0 +1,10 @@ + $config + */ #[Inject( Entity::class, "config.uration", )] public function __construct( - protected ?Entity $service = null + protected ?Entity $service = null, + protected array $config = [], ) { } } diff --git a/test/TestData/VariadicService.php b/test/TestData/VariadicService.php new file mode 100644 index 0000000..bcd8286 --- /dev/null +++ b/test/TestData/VariadicService.php @@ -0,0 +1,19 @@ + */ + public array $values; + + #[Inject('first', 'second', 'third')] + public function __construct(mixed ...$values) + { + $this->values = $values; + } +} From cb5dedcb4ab7d7706cf3461a7e0d79c41faeb838 Mon Sep 17 00:00:00 2001 From: bidi Date: Tue, 10 Nov 2026 18:02:22 +0200 Subject: [PATCH 2/4] update for codecov Signed-off-by: bidi --- src/Factory/AttributedRepositoryFactory.php | 10 ++++++- test/Exception/RuntimeExceptionTest.php | 26 ------------------- .../AttributedRepositoryFactoryTest.php | 21 +++++++++++++++ 3 files changed, 30 insertions(+), 27 deletions(-) delete mode 100644 test/Exception/RuntimeExceptionTest.php diff --git a/src/Factory/AttributedRepositoryFactory.php b/src/Factory/AttributedRepositoryFactory.php index c44bbed..14e82fc 100644 --- a/src/Factory/AttributedRepositoryFactory.php +++ b/src/Factory/AttributedRepositoryFactory.php @@ -41,7 +41,7 @@ public function __invoke(ContainerInterface $container, string $requestedName): */ public function createObject(ContainerInterface $container, string $requestedName): EntityRepository { - if (! class_exists(EntityRepository::class)) { + if (! $this->isOrmInstalled()) { throw RuntimeException::missingPackage('doctrine/orm', static::class); } @@ -92,4 +92,12 @@ protected function findEntityAttribute(ReflectionClass $reflectionClass): ?Entit return $instance instanceof Entity ? $instance : null; } + + /** + * doctrine/orm is only suggested by this package, so it may be missing from the application. + */ + protected function isOrmInstalled(): bool + { + return class_exists(EntityRepository::class); + } } diff --git a/test/Exception/RuntimeExceptionTest.php b/test/Exception/RuntimeExceptionTest.php deleted file mode 100644 index 0940cca..0000000 --- a/test/Exception/RuntimeExceptionTest.php +++ /dev/null @@ -1,26 +0,0 @@ -assertSame( - '"' . AttributedRepositoryFactory::class . '" requires "doctrine/orm": ' - . 'run "composer require doctrine/orm".', - $exception->getMessage() - ); - } -} diff --git a/test/Factory/AttributedRepositoryFactoryTest.php b/test/Factory/AttributedRepositoryFactoryTest.php index 584e78f..1f609f7 100644 --- a/test/Factory/AttributedRepositoryFactoryTest.php +++ b/test/Factory/AttributedRepositoryFactoryTest.php @@ -25,6 +25,27 @@ class AttributedRepositoryFactoryTest extends TestCase { + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function testWillThrowExceptionIfOrmIsNotInstalled(): void + { + $factory = new class extends AttributedRepositoryFactory { + protected function isOrmInstalled(): bool + { + return false; + } + }; + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage( + sprintf(RuntimeException::MESSAGE_MISSING_PACKAGE, 'doctrine/orm', $factory::class) + ); + + $factory(new Container(), TestRepository::class); + } + /** * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface From c1a37a0b1ed824f3395f18ad864b340cf55ee686 Mon Sep 17 00:00:00 2001 From: bidi Date: Wed, 11 Nov 2026 14:58:17 +0200 Subject: [PATCH 3/4] updated based on review Signed-off-by: bidi --- .github/workflows/static-analysis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index b428224..2dd6164 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -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: vendor/bin/phpstan analyse --memory-limit 1G From 76e32c9629cde0f8708e8bf51beafadd1a0364b0 Mon Sep 17 00:00:00 2001 From: bidi Date: Thu, 12 Nov 2026 14:35:11 +0200 Subject: [PATCH 4/4] updated based on review Signed-off-by: bidi --- .laminas-ci.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.laminas-ci.json b/.laminas-ci.json index efdd72e..e827682 100644 --- a/.laminas-ci.json +++ b/.laminas-ci.json @@ -2,5 +2,5 @@ "ignore_php_platform_requirements": { "8.6": true }, - "backwardCompatibilityCheck": false + "backwardCompatibilityCheck": true }