From 5c4e2e70a7e906a966ee225f394046bf1ae0012a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Franco?= Date: Sat, 21 Nov 2026 13:20:35 +0100 Subject: [PATCH 1/2] feat: register_mapping, mapping_type and entity_manager for DDD hosts (WIP) --- docs/CHANGELOG.md | 12 + docs/CONFIGURATION.md | 21 ++ docs/INSTALLATION.md | 2 +- docs/UPGRADING.md | 13 + docs/USAGE.md | 48 +++- .../Compiler/EntityManagerMappings.php | 97 +++++++ .../Compiler/HttpLogCommitTrackingPass.php | 66 +---- .../Compiler/HttpLogEntityManagerPass.php | 48 ++++ src/DependencyInjection/Configuration.php | 26 ++ .../NowoHttpLogExtension.php | 178 ++++++++++++- src/NowoHttpLogBundle.php | 3 + .../config/doctrine/HttpLogEntry.orm.xml | 61 +++++ .../DedicatedEntityManagerKernelTest.php | 164 ++++++++++++ tests/Kernel/UsageKernel.php | 13 +- .../HttpLogCommitTrackingPassTest.php | 2 + .../Compiler/HttpLogEntityManagerPassTest.php | 85 ++++++ .../DoctrineMappingExtensionTest.php | 248 ++++++++++++++++++ tests/Unit/Doctrine/XmlMappingParityTest.php | 135 ++++++++++ 18 files changed, 1142 insertions(+), 80 deletions(-) create mode 100644 src/DependencyInjection/Compiler/EntityManagerMappings.php create mode 100644 src/DependencyInjection/Compiler/HttpLogEntityManagerPass.php create mode 100644 src/Resources/config/doctrine/HttpLogEntry.orm.xml create mode 100644 tests/Integration/Doctrine/DedicatedEntityManagerKernelTest.php create mode 100644 tests/Unit/DependencyInjection/Compiler/HttpLogEntityManagerPassTest.php create mode 100644 tests/Unit/DependencyInjection/DoctrineMappingExtensionTest.php create mode 100644 tests/Unit/Doctrine/XmlMappingParityTest.php diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 08a15f7..0fd5901 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -57,6 +57,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- DDD host (B3 of the DDD-host checklist, REQ-ARCH-001): the bundle's table can stay off a host's domain entity manager. Three opt-in options under `doctrine`, defaults unchanged (standard Symfony path): + - `register_mapping` (default `true`): `false` leaves the mapping of `HttpLogEntry` to the host; the bundle then adds a disabled `NowoHttpLogBundle` mapping so Doctrine `auto_mapping` does not map the entity on the auto-mapped manager too. + - `mapping_type` (default `attribute`): `xml` registers the shipped `src/Resources/config/doctrine/HttpLogEntry.orm.xml` (same table, columns, options, indexes and repository as the attributes). + - `entity_manager` (default `null`): maps the entity on that manager instead of the default one; the container build fails unless the manager exists and is the only one mapping the bundle entities (`HttpLogEntityManagerPass`). +- Tests: `XmlMappingParityTest` (XML vs attributes: metadata and DDL on SQLite, MySQL and PostgreSQL, with the table-naming and path-prefix listeners), `DedicatedEntityManagerKernelTest` (XML host leg: entries on a dedicated manager and connection, mapped by the bundle or by the host, with `auto_mapping` on the host manager; a pending host change is never flushed; double mapping fails the build), prepend and pass unit tests. + +### Changed + +- Internal: `HttpLogCommitTrackingPass` reads the managers mapping the entries through the new internal `EntityManagerMappings` helper (same result). + ## [1.23.1] - 2026-11-21 ### Changed diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 1769ff5..8abebc1 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -10,6 +10,7 @@ All options live under the root key `nowo_http_log` (alias `nowo_http_log`). - [redaction](#redaction) - [retention](#retention) - [doctrine](#doctrine) + - [Mapping and entity manager (1.24)](#mapping-and-entity-manager-124) - [export](#export) - [web_ui](#web_ui) - [Form profile (FormKit)](#form-profile-formkit) @@ -92,6 +93,9 @@ nowo_http_log: doctrine: table_name_prefix: nowo_http_log_ # Replaces the nowo_http_log_ part of the table name (REQ-ORM-002) table_prefix: '' # Prefix for nowo_http_log_entry + index names (REQ-ORM-002) + register_mapping: true # 1.24: false = the host maps HttpLogEntry itself (DDD host) + mapping_type: attribute # 1.24: attribute | xml (shipped src/Resources/config/doctrine/HttpLogEntry.orm.xml) + entity_manager: null # 1.24: the manager holding the entries (null = whichever maps them) export: formats: - csv @@ -252,6 +256,23 @@ from its default) rewrites the `HttpLogEntry` mapping only. Changing either opti table: run the rename statements from [UPGRADING](UPGRADING.md#to-1211) (or generate a migration and turn the drop/create into a rename) instead of dropping the table. +### Mapping and entity manager (1.24) + +Three options decide where `HttpLogEntry` is mapped (B3 of the DDD-host checklist). The defaults keep the 1.23 mapping: +the entity attributes, as a bundle mapping named `NowoHttpLogBundle`, on the default entity manager. + +| Key | Default | Description | +| --- | --- | --- | +| `register_mapping` | `true` | `true`: the bundle registers the mapping. `false`: the host maps the entity itself (any mapping name, e.g. from the shipped XML); the bundle then adds a disabled `NowoHttpLogBundle` mapping so Doctrine `auto_mapping` does not map the entity on the auto-mapped manager too (unless the host already uses that mapping name). A literal boolean (no `%env()%`). | +| `mapping_type` | `attribute` | What the bundle registers while `register_mapping` is true: `attribute` (the entity attributes) or `xml` (`src/Resources/config/doctrine/HttpLogEntry.orm.xml`: same table, columns, options, indexes and repository; CI checks the parity and the DDL on SQLite, MySQL and PostgreSQL). Switching it changes no schema. | +| `entity_manager` | `null` | `null`: the services use whichever manager maps the entity (`ManagerRegistry::getManagerForClass()`). A name: with `register_mapping: true` the mapping goes on that manager instead of the default one, which must be declared under `doctrine.orm.entity_managers` (or be the default manager). Either way the container build fails unless that manager exists and is the **only** manager mapping `Nowo\HttpLogBundle\Entity`. A literal name (no `%env()%`). | + +Every option of this section (table names, path prefix and usage columns, rollup tables, exact collations) applies on +whichever manager maps the entity, attribute or XML. The bundle never flushes a host manager: entries are written by +DBAL on the connection of the manager that maps them. Moving the table to another connection is a data move (copy +the rows, or keep both managers on one connection): the bundle does not migrate rows. See +[USAGE](USAGE.md#keeping-the-log-table-off-your-domain-manager-124) for a DDD host configuration. + **PostgreSQL with a SEQUENCE id strategy** (only when you set DoctrineBundle's `identity_generation_preferences` to `SEQUENCE` for PostgreSQL; the ORM 3 default is IDENTITY, whose sequence PostgreSQL names after the prefixed table): the sequence keeps its unprefixed name `nowo_http_log_entry_id_seq`. The listener does not rename it, on purpose: a diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md index 7b34c0a..30c999b 100644 --- a/docs/INSTALLATION.md +++ b/docs/INSTALLATION.md @@ -58,7 +58,7 @@ Copy the default YAML from the recipe or from `src/Resources/config/packages/now ## Database schema -The bundle registers a Doctrine mapping for `Nowo\HttpLogBundle\Entity\HttpLogEntry` (table `nowo_http_log_entry` by default, renamed by `doctrine.table_name_prefix`: see [CONFIGURATION](CONFIGURATION.md#doctrine)). +The bundle registers a Doctrine mapping for `Nowo\HttpLogBundle\Entity\HttpLogEntry` (table `nowo_http_log_entry` by default, renamed by `doctrine.table_name_prefix`: see [CONFIGURATION](CONFIGURATION.md#doctrine)) on the default entity manager. Since 1.24 it can map the shipped XML instead, on a manager of your own, or leave the mapping to you (`doctrine.register_mapping`, `mapping_type`, `entity_manager`: see [CONFIGURATION](CONFIGURATION.md#mapping-and-entity-manager-124)). Generate and run a migration: diff --git a/docs/UPGRADING.md b/docs/UPGRADING.md index abf6e7d..a0e42c4 100644 --- a/docs/UPGRADING.md +++ b/docs/UPGRADING.md @@ -81,6 +81,19 @@ This document describes how to upgrade between versions of **Http Log Bundle**. ## Unreleased +Nothing to change: the defaults keep the 1.23 mapping (attributes, on the default entity manager). + +Opt-in (DDD host): keep the log table off your domain manager with `doctrine.mapping_type: xml` and +`doctrine.entity_manager: `, or map the shipped XML yourself with `doctrine.register_mapping: false` +([CONFIGURATION](CONFIGURATION.md#mapping-and-entity-manager-124)). Notes: + +- If you already map `Nowo\HttpLogBundle\Entity` by hand on another manager (next to the bundle's own mapping on the + default one), set `register_mapping: false` (and `entity_manager`) so only your mapping remains; `entity_manager` + makes the build fail while a second manager still maps the entity. +- Moving the table to another connection does not move the rows: copy them first, or point the dedicated manager at + the same connection. +- `register_mapping`, `mapping_type` and `entity_manager` are read at compile time: `%env()%` is rejected. + ## To 1.23.1 From **1.23.0**: diff --git a/docs/USAGE.md b/docs/USAGE.md index d809e7a..c0874cd 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -27,6 +27,7 @@ How to capture HTTP traffic, use the admin UI, export, purge, and exclude routes - [Backfill](#backfill) - [Standard Symfony host](#standard-symfony-host) - [DDD / hexagonal host](#ddd--hexagonal-host) + - [Keeping the log table off your domain manager (1.24)](#keeping-the-log-table-off-your-domain-manager-124) - [Keeping your domain free of the bundle](#keeping-your-domain-free-of-the-bundle) - [Entry-recorded event](#entry-recorded-event) - [Known limitations](#known-limitations) @@ -729,7 +730,7 @@ hooks are autoconfigured services: the request-context resolver ## DDD / hexagonal host The same bundle, with the domain kept free of Symfony and Doctrine types (REQ-ARCH-001). Nothing is forced: no base -class, no trait, no `resolve_target_entities`, no XML mapping to ship (the bundle owns its table and never maps your +class, no trait, no `resolve_target_entities`, no XML mapping to write (the bundle owns its table and never maps your entities). Every port a host implements or calls takes scalars or bundle value objects: | Need | Port (no framework type) | Value objects | @@ -741,6 +742,51 @@ entities). Every port a host implements or calls takes scalars or bundle value o | Erase / export personal data | `Privacy\HttpLogPersonalDataErasureInterface`, `HttpLogPersonalDataExporterInterface` | `HttpLogPersonalDataSubject`, `HttpLogErasureResult` | | Erase usage of a credential or tenant | `Privacy\HttpLogUsageEraserInterface` | scalars | +### Keeping the log table off your domain manager (1.24) + +By default the bundle maps `HttpLogEntry` (attributes) on the default entity manager. A host whose default manager holds +only its domain moves the table to a manager of its own ([CONFIGURATION](CONFIGURATION.md#doctrine)): + +```yaml +doctrine: + dbal: + connections: + default: { url: '%env(resolve:DATABASE_URL)%' } + http_log: { url: '%env(resolve:HTTP_LOG_DATABASE_URL)%' } # or the same URL: a separate manager is enough + orm: + default_entity_manager: default + entity_managers: + default: { connection: default, mappings: { App: { type: xml, dir: '%kernel.project_dir%/config/doctrine', prefix: 'App\Domain' } } } + http_log: { connection: http_log } + +nowo_http_log: + doctrine: + mapping_type: xml # the shipped src/Resources/config/doctrine/HttpLogEntry.orm.xml + entity_manager: http_log # mapped there only; the build fails if another manager maps it too +``` + +Or map it yourself (`register_mapping: false`) from the shipped XML, under any mapping name; the bundle then keeps +Doctrine `auto_mapping` from mapping it on the auto-mapped manager: + +```yaml +doctrine: + orm: + entity_managers: + http_log: + connection: http_log + mappings: + HttpLog: { type: xml, is_bundle: false, prefix: 'Nowo\HttpLogBundle\Entity', dir: '%kernel.project_dir%/vendor/nowo-tech/http-log-bundle/src/Resources/config/doctrine' } + +nowo_http_log: + doctrine: + register_mapping: false + entity_manager: http_log # optional: checks that this manager, and only it, maps the entries +``` + +The bundle writes entries by DBAL on that manager's connection and never flushes, clears or resets a host manager (it +resets the manager only when it is closed and maps the bundle's entities alone). Give the dedicated manager the bundle's +entities only: none of your entities ever reach it. + ### Keeping your domain free of the bundle - **Feeding context in.** Implement `HttpRequestContextResolverInterface` in your infrastructure layer and return an diff --git a/src/DependencyInjection/Compiler/EntityManagerMappings.php b/src/DependencyInjection/Compiler/EntityManagerMappings.php new file mode 100644 index 0000000..eeab1b1 --- /dev/null +++ b/src/DependencyInjection/Compiler/EntityManagerMappings.php @@ -0,0 +1,97 @@ + + */ + public static function managersMappingTheEntities(ContainerBuilder $container): array + { + $found = []; + foreach (self::managerNames($container) as $name) { + $chainId = sprintf('doctrine.orm.%s_metadata_driver', $name); + if (!$container->hasDefinition($chainId)) { + continue; + } + + foreach ($container->getDefinition($chainId)->getMethodCalls() as $call) { + if ($call[0] === 'addDriver' && self::mapsTheEntities($call[1])) { + $found[] = $name; + + break; + } + } + } + + return $found; + } + + /** + * Names of the configured entity managers (DoctrineBundle's `doctrine.entity_managers` parameter). + * + * @return list + */ + public static function managerNames(ContainerBuilder $container): array + { + $managers = $container->hasParameter('doctrine.entity_managers') ? $container->getParameter('doctrine.entity_managers') : []; + $names = []; + foreach (array_keys(is_array($managers) ? $managers : []) as $name) { + $names[] = (string) $name; + } + + return $names; + } + + public static function connectionOf(ContainerBuilder $container, string $manager): ?string + { + $id = sprintf('doctrine.orm.%s_entity_manager', $manager); + $argument = $container->hasDefinition($id) ? ($container->getDefinition($id)->getArguments()[0] ?? null) : null; + if ($argument instanceof Reference && preg_match('/^doctrine\.dbal\.(.+)_connection$/D', (string) $argument, $match) === 1) { + return $match[1]; + } + + return null; + } + + /** + * @param array $arguments the `addDriver(driver, namespace)` arguments + */ + private static function mapsTheEntities(array $arguments): bool + { + $namespace = $arguments[1] ?? null; + if (!is_string($namespace)) { + return false; + } + + $mapped = rtrim($namespace, '\\') . '\\'; + $bundle = self::ENTITY_NAMESPACE . '\\'; + + return str_starts_with($bundle, $mapped) || str_starts_with($mapped, $bundle); + } +} diff --git a/src/DependencyInjection/Compiler/HttpLogCommitTrackingPass.php b/src/DependencyInjection/Compiler/HttpLogCommitTrackingPass.php index 816cde0..96eac5b 100644 --- a/src/DependencyInjection/Compiler/HttpLogCommitTrackingPass.php +++ b/src/DependencyInjection/Compiler/HttpLogCommitTrackingPass.php @@ -11,15 +11,9 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; -use function array_keys; use function array_unique; use function array_values; -use function is_array; use function is_string; -use function preg_match; -use function rtrim; -use function sprintf; -use function str_starts_with; /** * 1.22 (REQ-RUNTIME-003 rule 6): scopes the commit tracking of the conflict answer (audit UE-CF-1: never every host @@ -46,7 +40,7 @@ final class HttpLogCommitTrackingPass implements CompilerPassInterface public const TRANSACTION_DOCTRINE_MIDDLEWARE = 'nowo_transaction_doctrine.commit_tracking_middleware'; /** Namespace of the bundle's entities. */ - public const ENTITY_NAMESPACE = 'Nowo\\HttpLogBundle\\Entity'; + public const ENTITY_NAMESPACE = EntityManagerMappings::ENTITY_NAMESPACE; public function process(ContainerBuilder $container): void { @@ -94,11 +88,11 @@ private function transactionDoctrineTracksCommits(ContainerBuilder $container): private function bundleConnections(ContainerBuilder $container): array { $default = $container->hasParameter('doctrine.default_entity_manager') ? $container->getParameter('doctrine.default_entity_manager') : 'default'; - $managers = [is_string($default) && $default !== '' ? $default : 'default', ...$this->managersMappingTheEntities($container)]; + $managers = [is_string($default) && $default !== '' ? $default : 'default', ...EntityManagerMappings::managersMappingTheEntities($container)]; $connections = []; foreach ($managers as $name) { - $connection = $this->connectionOf($container, $name); + $connection = EntityManagerMappings::connectionOf($container, $name); if ($connection !== null) { $connections[] = $connection; } @@ -111,58 +105,4 @@ private function bundleConnections(ContainerBuilder $container): array return array_values(array_unique($connections)); } - - /** - * Every configured manager whose metadata driver chain has a driver for a namespace covering the bundle entities. - * - * @return list - */ - private function managersMappingTheEntities(ContainerBuilder $container): array - { - $managers = $container->hasParameter('doctrine.entity_managers') ? $container->getParameter('doctrine.entity_managers') : []; - $found = []; - foreach (array_keys(is_array($managers) ? $managers : []) as $name) { - $chainId = sprintf('doctrine.orm.%s_metadata_driver', $name); - if (!$container->hasDefinition($chainId)) { - continue; - } - - foreach ($container->getDefinition($chainId)->getMethodCalls() as $call) { - if ($call[0] === 'addDriver' && $this->mapsTheEntities($call[1])) { - $found[] = (string) $name; - - break; - } - } - } - - return $found; - } - - /** - * @param array $arguments the `addDriver(driver, namespace)` arguments - */ - private function mapsTheEntities(array $arguments): bool - { - $namespace = $arguments[1] ?? null; - if (!is_string($namespace)) { - return false; - } - - $mapped = rtrim($namespace, '\\') . '\\'; - $bundle = self::ENTITY_NAMESPACE . '\\'; - - return str_starts_with($bundle, $mapped) || str_starts_with($mapped, $bundle); - } - - private function connectionOf(ContainerBuilder $container, string $manager): ?string - { - $id = sprintf('doctrine.orm.%s_entity_manager', $manager); - $argument = $container->hasDefinition($id) ? ($container->getDefinition($id)->getArguments()[0] ?? null) : null; - if ($argument instanceof Reference && preg_match('/^doctrine\.dbal\.(.+)_connection$/D', (string) $argument, $match) === 1) { - return $match[1]; - } - - return null; - } } diff --git a/src/DependencyInjection/Compiler/HttpLogEntityManagerPass.php b/src/DependencyInjection/Compiler/HttpLogEntityManagerPass.php new file mode 100644 index 0000000..0da653b --- /dev/null +++ b/src/DependencyInjection/Compiler/HttpLogEntityManagerPass.php @@ -0,0 +1,48 @@ +hasParameter(NowoHttpLogExtension::ENTITY_MANAGER_PARAMETER)) { + return; + } + + $manager = $container->getParameter(NowoHttpLogExtension::ENTITY_MANAGER_PARAMETER); + if (!is_string($manager) || !$container->hasParameter('doctrine.entity_managers')) { + return; + } + + $names = EntityManagerMappings::managerNames($container); + if (!in_array($manager, $names, true)) { + throw new InvalidArgumentException(sprintf('nowo_http_log.doctrine.entity_manager "%s" is not a configured entity manager (configured: %s).', $manager, implode(', ', $names))); + } + + $mapping = EntityManagerMappings::managersMappingTheEntities($container); + if ($mapping !== [$manager]) { + throw new InvalidArgumentException(sprintf('nowo_http_log.doctrine.entity_manager is "%s", but the bundle entities (%s) are mapped on: %s. Map them on "%s" only: keep doctrine.register_mapping true, or with register_mapping false map them yourself on that manager and nowhere else (Doctrine auto_mapping included).', $manager, EntityManagerMappings::ENTITY_NAMESPACE, $mapping === [] ? 'no entity manager' : implode(', ', $mapping), $manager)); + } + } +} diff --git a/src/DependencyInjection/Configuration.php b/src/DependencyInjection/Configuration.php index 3d8322d..c45fdd2 100644 --- a/src/DependencyInjection/Configuration.php +++ b/src/DependencyInjection/Configuration.php @@ -54,6 +54,15 @@ final class Configuration implements ConfigurationInterface /** Entries exported at most per subject by the personal-data export (newest first). */ public const DEFAULT_PERSONAL_DATA_EXPORT_LIMIT = 1000; + /** `doctrine.mapping_type`: the entity attributes (default). */ + public const MAPPING_TYPE_ATTRIBUTE = 'attribute'; + + /** `doctrine.mapping_type`: the shipped `src/Resources/config/doctrine/HttpLogEntry.orm.xml` (1.24). */ + public const MAPPING_TYPE_XML = 'xml'; + + /** Allowed `doctrine.entity_manager` names (DoctrineBundle builds service ids from them). */ + public const MANAGER_NAME_PATTERN = '/^[A-Za-z_][A-Za-z0-9_]*\z/'; + /** Composer package name used in configuration deprecations. */ public const PACKAGE = 'nowo-tech/http-log-bundle'; @@ -234,6 +243,23 @@ public function getConfigTreeBuilder(): TreeBuilder ->thenInvalid('Invalid "nowo_http_log.doctrine.table_prefix" %s: use a lowercase letter, then lowercase letters, digits and underscores (or empty).') ->end() ->end() + ->booleanNode('register_mapping') + ->info('1.24 (DDD host): true (default) = the bundle maps HttpLogEntry itself (on the default entity manager, or on doctrine.entity_manager). false = the host maps it (e.g. src/Resources/config/doctrine/HttpLogEntry.orm.xml on a dedicated manager); the bundle then keeps Doctrine auto_mapping from mapping it on the auto-mapped manager. A literal boolean: it is read before the configuration is processed.') + ->defaultTrue() + ->end() + ->enumNode('mapping_type') + ->info('1.24: the mapping the bundle registers while register_mapping is true: attribute (default, the entity attributes) or xml (the shipped src/Resources/config/doctrine/HttpLogEntry.orm.xml: same table, columns and indexes).') + ->values([self::MAPPING_TYPE_ATTRIBUTE, self::MAPPING_TYPE_XML]) + ->defaultValue(self::MAPPING_TYPE_ATTRIBUTE) + ->end() + ->scalarNode('entity_manager') + ->info('1.24: the entity manager that holds the entries. null (default) = whichever manager maps HttpLogEntry (the default manager of a standard application). A name: register_mapping true maps the entity on that manager instead of the default one; the manager must exist and be the ONLY manager that maps the entity (the container build fails otherwise). The bundle never flushes a host manager either way.') + ->defaultNull() + ->validate() + ->ifTrue(static fn (mixed $value): bool => $value !== null && (!is_string($value) || preg_match(self::MANAGER_NAME_PATTERN, $value) !== 1)) + ->thenInvalid('Invalid "nowo_http_log.doctrine.entity_manager" %s: use an entity manager name (letters, digits and underscores) or null.') + ->end() + ->end() ->end() ->end() ->arrayNode('export') diff --git a/src/DependencyInjection/NowoHttpLogExtension.php b/src/DependencyInjection/NowoHttpLogExtension.php index e96f47a..4cbded7 100644 --- a/src/DependencyInjection/NowoHttpLogExtension.php +++ b/src/DependencyInjection/NowoHttpLogExtension.php @@ -78,10 +78,13 @@ use function array_unique; use function array_values; use function class_exists; +use function implode; +use function in_array; use function interface_exists; use function is_array; use function is_bool; use function is_string; +use function preg_match; use function sprintf; use function str_replace; use function trait_exists; @@ -106,6 +109,15 @@ final class NowoHttpLogExtension extends Extension implements PrependExtensionIn /** 1.22: container parameter holding `conflict_response.commit_tracking` (bundle, all or off). */ public const COMMIT_TRACKING_PARAMETER = 'nowo_http_log.conflict_response.commit_tracking'; + /** Doctrine mapping key of the bundle entity (the bundle name: Doctrine auto_mapping skips a bundle mapped under it). */ + public const MAPPING_NAME = 'NowoHttpLogBundle'; + + /** 1.24: directory of the shipped XML mapping (`HttpLogEntry.orm.xml`, same table, columns and indexes). */ + public const XML_MAPPING_DIR = __DIR__ . '/../Resources/config/doctrine'; + + /** 1.24: container parameter holding `doctrine.entity_manager` (string, or null for whichever manager maps it). */ + public const ENTITY_MANAGER_PARAMETER = 'nowo_http_log.doctrine.entity_manager'; + /** * Feature block => [class or trait that must exist, Composer package that provides it]. * @@ -138,16 +150,7 @@ public function prepend(ContainerBuilder $container): void } if ($container->hasExtension('doctrine')) { - $container->prependExtensionConfig('doctrine', [ - 'orm' => [ - 'mappings' => [ - 'NowoHttpLogBundle' => [ - 'type' => 'attribute', - 'is_bundle' => true, - ], - ], - ], - ]); + $this->prependDoctrineMapping($container); } $configs = $container->getExtensionConfig($this->getAlias()); @@ -167,6 +170,151 @@ public function prepend(ContainerBuilder $container): void $this->prependUiKitDefaults($container); } + /** + * 1.24 (DDD host, B3): maps HttpLogEntry as configured by `doctrine.register_mapping`, `mapping_type` and + * `entity_manager` (read raw: prepend() runs before the configuration is processed; the last file that sets a key + * wins, load() validates the values again). + * + * - register_mapping true, no entity_manager: the 1.23 mapping (attribute, as a bundle mapping) on the default + * manager, or the shipped XML with `mapping_type: xml`. + * - register_mapping true with entity_manager: the same mapping on that manager only. Doctrine auto_mapping skips a + * bundle that any manager maps under its name, so the default manager no longer maps the entity. + * - register_mapping false: nothing is mapped; a disabled mapping under the bundle name keeps auto_mapping from + * mapping the entity on the auto-mapped manager, unless the host already uses that mapping name itself. + */ + private function prependDoctrineMapping(ContainerBuilder $container): void + { + [$register, $type, $manager] = $this->rawDoctrineOptions($container); + $doctrine = $container->getExtensionConfig('doctrine'); + + if ($register) { + $mapping = $type === Configuration::MAPPING_TYPE_XML + ? ['type' => 'xml', 'dir' => self::XML_MAPPING_DIR, 'prefix' => HttpLogCommitTrackingPass::ENTITY_NAMESPACE, 'is_bundle' => false] + : ['type' => 'attribute', 'is_bundle' => true]; + + if ($manager === null) { + $container->prependExtensionConfig('doctrine', ['orm' => ['mappings' => [self::MAPPING_NAME => $mapping]]]); + + return; + } + + if (!in_array($manager, $this->declaredManagers($doctrine), true)) { + throw new InvalidConfigurationException(sprintf('nowo_http_log.doctrine.entity_manager "%s" is not a configured entity manager: declare it under doctrine.orm.entity_managers (configured: %s).', $manager, implode(', ', $this->declaredManagers($doctrine)))); + } + + $container->prependExtensionConfig('doctrine', ['orm' => ['entity_managers' => [$manager => ['mappings' => [self::MAPPING_NAME => $mapping]]]]]); + + return; + } + + if ($this->hostMapsTheBundleName($doctrine)) { + return; + } + + $target = $manager ?? $this->declaredManagers($doctrine)[0] ?? null; + if ($target === null) { + return; + } + + $container->prependExtensionConfig('doctrine', ['orm' => ['entity_managers' => [$target => ['mappings' => [self::MAPPING_NAME => ['mapping' => false]]]]]]); + } + + /** + * Raw `doctrine.register_mapping`, `mapping_type` and `entity_manager` of the bundle configuration. + * + * @return array{0: bool, 1: string, 2: string|null} + */ + private function rawDoctrineOptions(ContainerBuilder $container): array + { + $register = true; + $type = Configuration::MAPPING_TYPE_ATTRIBUTE; + $manager = null; + foreach ($container->getExtensionConfig($this->getAlias()) as $config) { + $doctrine = is_array($config['doctrine'] ?? null) ? $config['doctrine'] : []; + if (array_key_exists('register_mapping', $doctrine)) { + if (!is_bool($doctrine['register_mapping'])) { + throw new InvalidConfigurationException('nowo_http_log.doctrine.register_mapping must be a literal boolean: it decides the Doctrine mapping at compile time (no %env()%).'); + } + $register = $doctrine['register_mapping']; + } + if (in_array($doctrine['mapping_type'] ?? null, [Configuration::MAPPING_TYPE_ATTRIBUTE, Configuration::MAPPING_TYPE_XML], true)) { + $type = $doctrine['mapping_type']; + } + if (array_key_exists('entity_manager', $doctrine)) { + $manager = is_string($doctrine['entity_manager']) && $doctrine['entity_manager'] !== '' ? $doctrine['entity_manager'] : null; + } + } + + if ($manager !== null && preg_match(Configuration::MANAGER_NAME_PATTERN, $manager) !== 1) { + throw new InvalidConfigurationException(sprintf('Invalid "nowo_http_log.doctrine.entity_manager" "%s": use a literal entity manager name (letters, digits and underscores; no %%env()%%) or null.', $manager)); + } + + return [$register, $type, $manager]; + } + + /** + * Entity manager names the host declares, the default one first: `default_entity_manager`, then every + * `entity_managers` key; `default` for a short-form `orm` block (DoctrineBundle's name for it). + * + * @param array> $doctrine raw `doctrine` configurations + * + * @return list + */ + private function declaredManagers(array $doctrine): array + { + $default = null; + $managers = []; + foreach ($doctrine as $config) { + $orm = $config['orm'] ?? null; + if (!is_array($orm)) { + continue; + } + if (is_string($orm['default_entity_manager'] ?? null) && $orm['default_entity_manager'] !== '') { + $default = $orm['default_entity_manager']; + } + if (is_array($orm['entity_managers'] ?? null)) { + foreach (array_keys($orm['entity_managers']) as $name) { + $managers[] = (string) $name; + } + } elseif (is_array($orm['entity_manager'] ?? null)) { + foreach (array_keys($orm['entity_manager']) as $name) { + $managers[] = (string) $name; + } + } else { + $managers[] = $default ?? 'default'; + } + } + + if ($default !== null) { + $managers = [$default, ...$managers]; + } + + return array_values(array_unique($managers)); + } + + /** + * True when a host configuration already maps something under the bundle name (on any manager). + * + * @param array> $doctrine raw `doctrine` configurations + */ + private function hostMapsTheBundleName(array $doctrine): bool + { + foreach ($doctrine as $config) { + $orm = is_array($config['orm'] ?? null) ? $config['orm'] : []; + if (is_array($orm['mappings'] ?? null) && array_key_exists(self::MAPPING_NAME, $orm['mappings'])) { + return true; + } + $managers = is_array($orm['entity_managers'] ?? null) ? $orm['entity_managers'] : (is_array($orm['entity_manager'] ?? null) ? $orm['entity_manager'] : []); + foreach ($managers as $manager) { + if (is_array($manager) && is_array($manager['mappings'] ?? null) && array_key_exists(self::MAPPING_NAME, $manager['mappings'])) { + return true; + } + } + } + + return false; + } + /** * When FormKit is installed, register the http_log profile. Forms select it via #[FormKitConfig]. */ @@ -345,6 +493,16 @@ public function load(array $configs, ContainerBuilder $container): void // REQ-ORM-002: the table naming listener only exists when a name differs from the mapped one. $container->setParameter($alias . '.doctrine.table_prefix', $config['doctrine']['table_prefix']); $container->setParameter($alias . '.doctrine.table_name_prefix', $config['doctrine']['table_name_prefix']); + // 1.24: the mapping switch was applied in prepend(); the manager name is checked by HttpLogEntityManagerPass. + foreach (['mapping_type', 'entity_manager'] as $option) { + $value = $config['doctrine'][$option]; + if (is_string($value) && $container->resolveEnvPlaceholders($value) !== $value) { + throw new InvalidConfigurationException(sprintf('nowo_http_log.doctrine.%s does not support %%env()%%: it decides the Doctrine mapping at compile time; set a literal value.', $option)); + } + } + $container->setParameter($alias . '.doctrine.register_mapping', $config['doctrine']['register_mapping']); + $container->setParameter($alias . '.doctrine.mapping_type', $config['doctrine']['mapping_type']); + $container->setParameter(self::ENTITY_MANAGER_PARAMETER, $config['doctrine']['entity_manager']); $container->setParameter($alias . '.web_ui.filter_match', $config['web_ui']['filter_match']); if ($config['web_ui']['filter_match'] === Configuration::FILTER_MATCH_PREFIX) { // Prefix filters (PERF-1147-02): map path_prefix and its index, before TablePrefixListener (priority 0). diff --git a/src/NowoHttpLogBundle.php b/src/NowoHttpLogBundle.php index 778d237..b5ac1e6 100644 --- a/src/NowoHttpLogBundle.php +++ b/src/NowoHttpLogBundle.php @@ -7,6 +7,7 @@ use Nowo\HttpLogBundle\DependencyInjection\Compiler\CsrfProtectionPass; use Nowo\HttpLogBundle\DependencyInjection\Compiler\DeprecatedRequestContextResolverPass; use Nowo\HttpLogBundle\DependencyInjection\Compiler\HttpLogCommitTrackingPass; +use Nowo\HttpLogBundle\DependencyInjection\Compiler\HttpLogEntityManagerPass; use Nowo\HttpLogBundle\DependencyInjection\Compiler\OutboundHttpClientPass; use Nowo\HttpLogBundle\DependencyInjection\Compiler\TwigPathsPass; use Nowo\HttpLogBundle\DependencyInjection\NowoHttpLogExtension; @@ -26,6 +27,8 @@ public function build(ContainerBuilder $container): void $container->addCompilerPass(new DeprecatedRequestContextResolverPass()); // 1.22 (REQ-RUNTIME-003): scope the commit-tracking middleware before DoctrineBundle's MiddlewaresPass (priority 0). $container->addCompilerPass(new HttpLogCommitTrackingPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 5); + // 1.24 (DDD host): doctrine.entity_manager must be the only manager that maps the entries. + $container->addCompilerPass(new HttpLogEntityManagerPass()); } public function getContainerExtension(): ExtensionInterface diff --git a/src/Resources/config/doctrine/HttpLogEntry.orm.xml b/src/Resources/config/doctrine/HttpLogEntry.orm.xml new file mode 100644 index 0000000..48baa58 --- /dev/null +++ b/src/Resources/config/doctrine/HttpLogEntry.orm.xml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/Integration/Doctrine/DedicatedEntityManagerKernelTest.php b/tests/Integration/Doctrine/DedicatedEntityManagerKernelTest.php new file mode 100644 index 0000000..98137b5 --- /dev/null +++ b/tests/Integration/Doctrine/DedicatedEntityManagerKernelTest.php @@ -0,0 +1,164 @@ + false, + 'sampling_rate' => 1.0, + ]; + + #[Test] + public function theBundleMapsItsXmlOnTheNamedManagerOnly(): void + { + $this->assertEntriesLiveOnTheDedicatedManager( + ['doctrine' => ['mapping_type' => 'xml', 'entity_manager' => 'http_log']], + [], + 'bundle-xml', + ); + } + + #[Test] + public function theHostMapsTheXmlItselfUnderItsOwnName(): void + { + // what Beacon does by hand today: its own mapping name, so the bundle only keeps auto_mapping off the entity + $this->assertEntriesLiveOnTheDedicatedManager( + ['doctrine' => ['register_mapping' => false, 'entity_manager' => 'http_log']], + ['HttpLog' => ['type' => 'xml', 'dir' => NowoHttpLogExtension::XML_MAPPING_DIR, 'prefix' => 'Nowo\\HttpLogBundle\\Entity', 'is_bundle' => false]], + 'host-xml', + ); + } + + #[Test] + public function aSecondManagerMappingTheEntriesFailsTheBuild(): void + { + $kernel = $this->kernel( + ['doctrine' => ['entity_manager' => 'http_log']], + [], + ['NowoHttpLogBundleAgain' => ['type' => 'attribute', 'dir' => dirname(__DIR__, 3) . '/src/Entity', 'prefix' => 'Nowo\\HttpLogBundle\\Entity', 'is_bundle' => false]], + 'double-mapping', + ); + + try { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('are mapped on: default, http_log'); + $kernel->boot(); + } finally { + $kernel->shutdown(); + } + } + + /** + * @param array $httpLog nowo_http_log configuration + * @param array $hostMappings mappings the host adds on the dedicated manager + */ + private function assertEntriesLiveOnTheDedicatedManager(array $httpLog, array $hostMappings, string $variant): void + { + $kernel = $this->kernel($httpLog, $hostMappings, [], $variant); + $kernel->boot(); + + try { + $container = $kernel->getContainer()->get('test.service_container'); + self::assertInstanceOf(ContainerInterface::class, $container); + $registry = $container->get('doctrine'); + self::assertInstanceOf(ManagerRegistry::class, $registry); + $default = $registry->getManager('default'); + $logs = $registry->getManager('http_log'); + self::assertInstanceOf(EntityManagerInterface::class, $default); + self::assertInstanceOf(EntityManagerInterface::class, $logs); + + self::assertSame($logs, $registry->getManagerForClass(HttpLogEntry::class)); + self::assertTrue($default->getMetadataFactory()->isTransient(HttpLogEntry::class), 'the host manager never maps the entries'); + self::assertSame([HttpLogEntry::class], array_map(static fn (ClassMetadata $m): string => $m->getName(), $logs->getMetadataFactory()->getAllMetadata()), 'the dedicated manager maps the entries alone'); + self::assertSame([HostArticle::class], array_map(static fn (ClassMetadata $m): string => $m->getName(), $default->getMetadataFactory()->getAllMetadata())); + + (new SchemaTool($default))->createSchema($default->getMetadataFactory()->getAllMetadata()); + (new SchemaTool($logs))->createSchema($logs->getMetadataFactory()->getAllMetadata()); + self::assertFalse($default->getConnection()->createSchemaManager()->tablesExist(['nowo_http_log_entry']), 'no bundle table on the host database'); + + // the host leaves a pending change on its manager; recording at terminate never flushes it + $default->persist(new HostArticle('pending')); + foreach (['/hello', '/hello'] as $path) { + $request = Request::create($path, 'GET', [], [], [], ['REMOTE_ADDR' => '127.0.0.1']); + $response = $kernel->handle($request); + self::assertSame(200, $response->getStatusCode()); + $kernel->terminate($request, $response); + } + + self::assertSame(2, (int) $logs->getConnection()->fetchOne('SELECT COUNT(*) FROM nowo_http_log_entry')); + self::assertSame(0, (int) $default->getConnection()->fetchOne('SELECT COUNT(*) FROM host_article')); + self::assertCount(1, $default->getUnitOfWork()->getScheduledEntityInsertions()); + + $repository = $container->get(HttpLogEntryRepository::class); + self::assertInstanceOf(HttpLogEntryRepository::class, $repository); + self::assertSame(2, $repository->countAll()); + self::assertSame($logs->getConnection(), $repository->connection()); + } finally { + $kernel->shutdown(); + } + } + + /** + * Two in-memory SQLite connections: `default` (the host's, auto_mapping on, the host entity) and `logs`. + * + * @param array $httpLog + * @param array $logMappings mappings the host adds on the dedicated manager + * @param array $defaultMappings mappings the host adds on its default manager + */ + private function kernel(array $httpLog, array $logMappings, array $defaultMappings, string $variant): UsageKernel + { + $doctrine = [ + 'dbal' => [ + 'default_connection' => 'default', + 'connections' => [ + 'default' => ['url' => 'sqlite:///:memory:'], + 'logs' => ['url' => 'sqlite:///:memory:'], + ], + ], + 'orm' => [ + 'default_entity_manager' => 'default', + 'entity_managers' => [ + 'default' => [ + 'connection' => 'default', + 'auto_mapping' => true, + 'mappings' => ['HostFixtures' => ['type' => 'attribute', 'dir' => dirname(__DIR__, 2) . '/Fixtures/Entity', 'prefix' => 'Nowo\\HttpLogBundle\\Tests\\Fixtures\\Entity', 'is_bundle' => false]] + $defaultMappings, + ], + 'http_log' => ['connection' => 'logs', 'mappings' => $logMappings], + ], + ], + ]; + + return new UsageKernel(self::HTTP_LOG + $httpLog, [], static function (ContainerBuilder $container): void { + $container->register('logger', NullLogger::class)->setPublic(true); + }, 'dedicated-em-' . $variant, $doctrine); + } +} diff --git a/tests/Kernel/UsageKernel.php b/tests/Kernel/UsageKernel.php index 330ca17..5c24d87 100644 --- a/tests/Kernel/UsageKernel.php +++ b/tests/Kernel/UsageKernel.php @@ -23,6 +23,7 @@ use function dirname; use function getmypid; +use function is_array; use function md5; use function serialize; use function sys_get_temp_dir; @@ -41,12 +42,15 @@ final class UsageKernel extends Kernel * @param array $httpLog `nowo_http_log` configuration * @param array $framework extra `framework` configuration (http_client, mailer, messenger…) * @param (callable(ContainerBuilder): void)|null $build extra services + * @param array $doctrine `doctrine` configuration replacing the default one (one in-memory SQLite + * connection, short-form ORM); `orm` gets the native lazy objects option */ public function __construct( private readonly array $httpLog = [], private readonly array $framework = [], private $build = null, private readonly string $variant = '', + private readonly array $doctrine = [], ) { parent::__construct('test', false); } @@ -70,7 +74,7 @@ public function getProjectDir(): string public function getCacheDir(): string { - return sys_get_temp_dir() . '/nowo-http-log-usage-kernel/' . getmypid() . '/' . md5(serialize([$this->httpLog, $this->framework, $this->variant])); + return sys_get_temp_dir() . '/nowo-http-log-usage-kernel/' . getmypid() . '/' . md5(serialize([$this->httpLog, $this->framework, $this->variant, $this->doctrine])); } public function getLogDir(): string @@ -108,10 +112,9 @@ private function configureContainer(ContainerConfigurator $container): void 'main' => ['lazy' => true, 'provider' => 'memory'], ], ]); - $container->extension('doctrine', [ - 'dbal' => ['url' => 'sqlite:///:memory:'], - 'orm' => $this->ormConfig(), - ]); + $doctrine = $this->doctrine === [] ? ['dbal' => ['url' => 'sqlite:///:memory:'], 'orm' => []] : $this->doctrine; + $orm = $doctrine['orm'] ?? []; + $container->extension('doctrine', ['orm' => (is_array($orm) ? $orm : []) + $this->ormConfig()] + $doctrine); $container->extension('nowo_http_log', $this->httpLog + ['web_ui' => ['enabled' => false]]); $container->services()->set(UsageTestController::class)->public()->tag('controller.service_arguments'); } diff --git a/tests/Unit/DependencyInjection/Compiler/HttpLogCommitTrackingPassTest.php b/tests/Unit/DependencyInjection/Compiler/HttpLogCommitTrackingPassTest.php index 7e3678c..ad890d7 100644 --- a/tests/Unit/DependencyInjection/Compiler/HttpLogCommitTrackingPassTest.php +++ b/tests/Unit/DependencyInjection/Compiler/HttpLogCommitTrackingPassTest.php @@ -5,6 +5,7 @@ namespace Nowo\HttpLogBundle\Tests\Unit\DependencyInjection\Compiler; use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\MiddlewaresPass; +use Nowo\HttpLogBundle\DependencyInjection\Compiler\EntityManagerMappings; use Nowo\HttpLogBundle\DependencyInjection\Compiler\HttpLogCommitTrackingPass; use Nowo\HttpLogBundle\DependencyInjection\NowoHttpLogExtension; use Nowo\HttpLogBundle\EventSubscriber\HttpLogConflictListener; @@ -21,6 +22,7 @@ * and is not registered at all when transaction-doctrine's commit_detection already counts commits (UE3-CF-1/2). */ #[CoversClass(HttpLogCommitTrackingPass::class)] +#[CoversClass(EntityManagerMappings::class)] final class HttpLogCommitTrackingPassTest extends TestCase { private const MIDDLEWARE = NowoHttpLogExtension::COMMIT_TRACKING_MIDDLEWARE; diff --git a/tests/Unit/DependencyInjection/Compiler/HttpLogEntityManagerPassTest.php b/tests/Unit/DependencyInjection/Compiler/HttpLogEntityManagerPassTest.php new file mode 100644 index 0000000..e847b24 --- /dev/null +++ b/tests/Unit/DependencyInjection/Compiler/HttpLogEntityManagerPassTest.php @@ -0,0 +1,85 @@ +container('http_log', ['http_log' => 'Nowo\\HttpLogBundle\\Entity', 'default' => 'App\\Entity']); + + (new HttpLogEntityManagerPass())->process($container); + + self::assertSame(['http_log'], EntityManagerMappings::managersMappingTheEntities($container)); + } + + public function testNothingIsCheckedWithoutTheOptionOrWithoutDoctrine(): void + { + $this->expectNotToPerformAssertions(); + + (new HttpLogEntityManagerPass())->process(new ContainerBuilder()); + // 1.23 behaviour: no manager named, the entries may be mapped anywhere + (new HttpLogEntityManagerPass())->process($this->container(null, ['default' => 'Nowo\\HttpLogBundle\\Entity', 'http_log' => 'Nowo\\HttpLogBundle\\Entity'])); + + $container = new ContainerBuilder(); + $container->setParameter(NowoHttpLogExtension::ENTITY_MANAGER_PARAMETER, 'http_log'); + (new HttpLogEntityManagerPass())->process($container); + } + + public function testAnUnknownManagerFails(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('nowo_http_log.doctrine.entity_manager "logs" is not a configured entity manager (configured: default, http_log).'); + + (new HttpLogEntityManagerPass())->process($this->container('logs', ['http_log' => 'Nowo\\HttpLogBundle\\Entity'])); + } + + public function testASecondManagerMappingTheEntitiesFails(): void + { + // e.g. Doctrine auto_mapping on the default manager next to a host mapping on the dedicated one + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('nowo_http_log.doctrine.entity_manager is "http_log", but the bundle entities (Nowo\\HttpLogBundle\\Entity) are mapped on: default, http_log.'); + + (new HttpLogEntityManagerPass())->process($this->container('http_log', ['default' => 'Nowo\\HttpLogBundle\\Entity', 'http_log' => 'Nowo\\HttpLogBundle\\Entity'])); + } + + public function testTheNamedManagerNotMappingTheEntitiesFails(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('are mapped on: no entity manager.'); + + (new HttpLogEntityManagerPass())->process($this->container('http_log', ['default' => 'App\\Entity'])); + } + + /** + * @param array $mappings manager => mapped namespace + */ + private function container(?string $manager, array $mappings): ContainerBuilder + { + $container = new ContainerBuilder(); + $container->setParameter(NowoHttpLogExtension::ENTITY_MANAGER_PARAMETER, $manager); + $container->setParameter('doctrine.entity_managers', ['default' => 'doctrine.orm.default_entity_manager', 'http_log' => 'doctrine.orm.http_log_entity_manager']); + foreach ($mappings as $name => $namespace) { + $container->setDefinition('doctrine.orm.' . $name . '_metadata_driver', (new Definition())->addMethodCall('addDriver', [new Definition(), $namespace])); + } + + return $container; + } +} diff --git a/tests/Unit/DependencyInjection/DoctrineMappingExtensionTest.php b/tests/Unit/DependencyInjection/DoctrineMappingExtensionTest.php new file mode 100644 index 0000000..167d20f --- /dev/null +++ b/tests/Unit/DependencyInjection/DoctrineMappingExtensionTest.php @@ -0,0 +1,248 @@ + 'xml', + 'dir' => NowoHttpLogExtension::XML_MAPPING_DIR, + 'prefix' => 'Nowo\\HttpLogBundle\\Entity', + 'is_bundle' => false, + ]; + + #[Test] + public function theDefaultsKeepThe123Mapping(): void + { + $config = (new Processor())->processConfiguration(new Configuration(), [[]]); + + self::assertTrue($config['doctrine']['register_mapping']); + self::assertSame('attribute', $config['doctrine']['mapping_type']); + self::assertNull($config['doctrine']['entity_manager']); + self::assertSame([['orm' => ['mappings' => ['NowoHttpLogBundle' => ['type' => 'attribute', 'is_bundle' => true]]]]], $this->prepended([])); + } + + #[Test] + public function theXmlMappingIsRegisteredOnTheDefaultManager(): void + { + self::assertSame( + [['orm' => ['mappings' => ['NowoHttpLogBundle' => self::XML]]]], + $this->prepended([['doctrine' => ['mapping_type' => 'attribute']], ['doctrine' => ['mapping_type' => 'xml']]]), + ); + self::assertFileExists(NowoHttpLogExtension::XML_MAPPING_DIR . '/HttpLogEntry.orm.xml'); + } + + #[Test] + public function aNamedManagerGetsTheMappingAlone(): void + { + $host = [['orm' => ['default_entity_manager' => 'default', 'entity_managers' => ['default' => ['auto_mapping' => true], 'http_log' => ['connection' => 'logs']]]]]; + + self::assertSame( + [['orm' => ['entity_managers' => ['http_log' => ['mappings' => ['NowoHttpLogBundle' => self::XML]]]]], ...$host], + $this->prepended([['doctrine' => ['mapping_type' => 'xml', 'entity_manager' => 'http_log']]], $host), + ); + self::assertSame( + [['orm' => ['entity_managers' => ['http_log' => ['mappings' => ['NowoHttpLogBundle' => ['type' => 'attribute', 'is_bundle' => true]]]]]], ...$host], + $this->prepended([['doctrine' => ['entity_manager' => 'http_log']]], $host), + ); + } + + #[Test] + public function theDefaultManagerOfAShortFormConfigurationCanBeNamed(): void + { + $host = [['dbal' => ['url' => 'sqlite:///:memory:'], 'orm' => ['auto_mapping' => true]]]; + + self::assertSame( + [['orm' => ['entity_managers' => ['default' => ['mappings' => ['NowoHttpLogBundle' => ['type' => 'attribute', 'is_bundle' => true]]]]]], ...$host], + $this->prepended([['doctrine' => ['entity_manager' => 'default']]], $host), + ); + + $host = [['orm' => ['default_entity_manager' => 'main', 'mappings' => []]], ['orm' => ['entity_manager' => ['reports' => []]]]]; + self::assertCount(3, $this->prepended([['doctrine' => ['entity_manager' => 'main']]], $host)); + self::assertCount(3, $this->prepended([['doctrine' => ['entity_manager' => 'reports']]], $host)); + } + + #[Test] + public function anUndeclaredManagerFailsInsteadOfCreatingOne(): void + { + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('nowo_http_log.doctrine.entity_manager "http_log" is not a configured entity manager: declare it under doctrine.orm.entity_managers (configured: default).'); + + $this->prepended([['doctrine' => ['entity_manager' => 'http_log']]], [['orm' => ['auto_mapping' => true]], ['dbal' => []]]); + } + + #[Test] + public function withoutRegisterMappingAutoMappingIsKeptOffTheEntity(): void + { + $host = [['orm' => ['default_entity_manager' => 'main', 'entity_managers' => ['main' => ['auto_mapping' => true], 'http_log' => []]]]]; + + self::assertSame( + [['orm' => ['entity_managers' => ['main' => ['mappings' => ['NowoHttpLogBundle' => ['mapping' => false]]]]]], ...$host], + $this->prepended([['doctrine' => ['register_mapping' => false]]], $host), + ); + self::assertSame( + [['orm' => ['entity_managers' => ['http_log' => ['mappings' => ['NowoHttpLogBundle' => ['mapping' => false]]]]]], ...$host], + $this->prepended([['doctrine' => ['register_mapping' => false, 'entity_manager' => 'http_log']]], $host), + ); + } + + #[Test] + public function withoutRegisterMappingAHostMappingUnderTheBundleNameIsLeftAlone(): void + { + foreach ([ + [['orm' => ['mappings' => ['NowoHttpLogBundle' => ['type' => 'xml']]]]], + [['orm' => ['entity_managers' => ['logs' => ['mappings' => ['NowoHttpLogBundle' => ['type' => 'xml']]]]]]], + [['orm' => ['entity_manager' => ['logs' => ['mappings' => ['NowoHttpLogBundle' => ['type' => 'xml']]]]]]], + ] as $host) { + self::assertSame($host, $this->prepended([['doctrine' => ['register_mapping' => false]]], $host)); + } + + // no ORM configured at all: nothing to keep auto_mapping off + self::assertSame([['dbal' => []]], $this->prepended([['doctrine' => ['register_mapping' => false]]], [['dbal' => []]])); + } + + #[Test] + public function registerMappingMustBeALiteralBoolean(): void + { + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('nowo_http_log.doctrine.register_mapping must be a literal boolean'); + + $this->prepended([['doctrine' => ['register_mapping' => '%env(bool:HTTP_LOG_MAPPING)%']]]); + } + + #[Test] + public function anInvalidRawManagerNameFails(): void + { + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('Invalid "nowo_http_log.doctrine.entity_manager" "%env(HTTP_LOG_EM)%"'); + + $this->prepended([['doctrine' => ['entity_manager' => '%env(HTTP_LOG_EM)%']]]); + } + + #[Test] + public function aNullManagerMeansTheDefault(): void + { + $expected = [['orm' => ['mappings' => ['NowoHttpLogBundle' => ['type' => 'attribute', 'is_bundle' => true]]]]]; + + self::assertSame($expected, $this->prepended([['doctrine' => ['entity_manager' => 'x']], ['doctrine' => ['entity_manager' => null]]])); + } + + #[Test] + #[DataProvider('invalidManagerNames')] + public function configurationRejectsInvalidManagerNames(mixed $value): void + { + $this->expectException(InvalidConfigurationException::class); + + (new Processor())->processConfiguration(new Configuration(), [['doctrine' => ['entity_manager' => $value]]]); + } + + /** @return iterable */ + public static function invalidManagerNames(): iterable + { + yield 'dash' => ['http-log']; + yield 'empty' => ['']; + yield 'digit first' => ['1logs']; + } + + #[Test] + public function configurationRejectsAnUnknownMappingType(): void + { + $this->expectException(InvalidConfigurationException::class); + + (new Processor())->processConfiguration(new Configuration(), [['doctrine' => ['mapping_type' => 'yaml']]]); + } + + #[Test] + public function loadPublishesTheOptions(): void + { + $container = $this->loaded(['doctrine' => ['register_mapping' => false, 'mapping_type' => 'xml', 'entity_manager' => 'http_log']]); + + self::assertFalse($container->getParameter('nowo_http_log.doctrine.register_mapping')); + self::assertSame('xml', $container->getParameter('nowo_http_log.doctrine.mapping_type')); + self::assertSame('http_log', $container->getParameter(NowoHttpLogExtension::ENTITY_MANAGER_PARAMETER)); + + self::assertNull($this->loaded([])->getParameter(NowoHttpLogExtension::ENTITY_MANAGER_PARAMETER)); + } + + #[Test] + public function loadRejectsAnEnvManagerName(): void + { + $container = new ContainerBuilder(new EnvPlaceholderParameterBag()); + $container->setParameter('kernel.environment', 'test'); + $value = $container->getParameterBag()->get('env(HTTP_LOG_EM)'); + self::assertIsString($value); + + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage('nowo_http_log.doctrine.entity_manager does not support %env()%'); + + (new NowoHttpLogExtension())->load([['security' => ['allow_unauthenticated' => true], 'doctrine' => ['entity_manager' => $value]]], $container); + } + + /** @param array $config */ + private function loaded(array $config): ContainerBuilder + { + $container = new ContainerBuilder(); + $container->setParameter('kernel.environment', 'test'); + (new NowoHttpLogExtension())->load([['security' => ['allow_unauthenticated' => true]] + $config], $container); + + return $container; + } + + /** + * @param list> $bundle raw nowo_http_log configurations + * @param list> $host raw doctrine configurations of the host + * + * @return list> the doctrine configurations after prepend() + */ + private function prepended(array $bundle, array $host = []): array + { + $container = new ContainerBuilder(); + $container->registerExtension($this->extension('doctrine')); + $container->registerExtension(new NowoHttpLogExtension()); + foreach ($host as $config) { + $container->loadFromExtension('doctrine', $config); + } + foreach ($bundle as $config) { + $container->loadFromExtension('nowo_http_log', $config); + } + + (new NowoHttpLogExtension())->prepend($container); + + return $container->getExtensionConfig('doctrine'); + } + + private function extension(string $alias): Extension + { + return new class($alias) extends Extension { + public function __construct(private readonly string $aliasName) + { + } + + public function load(array $configs, ContainerBuilder $container): void + { + } + + public function getAlias(): string + { + return $this->aliasName; + } + }; + } +} diff --git a/tests/Unit/Doctrine/XmlMappingParityTest.php b/tests/Unit/Doctrine/XmlMappingParityTest.php new file mode 100644 index 0000000..b535986 --- /dev/null +++ b/tests/Unit/Doctrine/XmlMappingParityTest.php @@ -0,0 +1,135 @@ +metadata(new AttributeDriver([dirname(__DIR__, 3) . '/src/Entity'])); + $xml = $this->metadata($this->xmlDriver()); + + self::assertSame($attribute->getTableName(), $xml->getTableName()); + self::assertSame('nowo_http_log_entry', $xml->getTableName()); + self::assertSame($attribute->table, $xml->table); + self::assertSame($attribute->getIdentifier(), $xml->getIdentifier()); + self::assertSame($attribute->generatorType, $xml->generatorType); + self::assertSame($attribute->customRepositoryClassName, $xml->customRepositoryClassName); + self::assertSame($this->fields($attribute), $this->fields($xml)); + self::assertSame([], $xml->associationMappings); + } + + #[Test] + public function bothMappingsGenerateTheSameSchema(): void + { + foreach ([[], ['app_', 'http_log_']] as $prefixes) { + $attribute = $this->createTableSql(new AttributeDriver([dirname(__DIR__, 3) . '/src/Entity']), $prefixes); + $xml = $this->createTableSql($this->xmlDriver(), $prefixes); + + self::assertSame($attribute, $xml); + self::assertNotSame([], $attribute['sqlite']); + } + } + + private function xmlDriver(): SimplifiedXmlDriver + { + // what DoctrineBundle registers for `mapping_type: xml` (type xml, dir, prefix) + return new SimplifiedXmlDriver([NowoHttpLogExtension::XML_MAPPING_DIR => 'Nowo\\HttpLogBundle\\Entity']); + } + + /** @return ClassMetadata */ + private function metadata(MappingDriver $driver): ClassMetadata + { + return $this->entityManager($driver)->getClassMetadata(HttpLogEntry::class); + } + + /** + * @param list $prefixes [table_prefix, table_name_prefix] of TablePrefixListener, none when empty + * + * @return array> + */ + private function createTableSql(MappingDriver $driver, array $prefixes): array + { + $manager = $this->entityManager($driver); + // the bundle's listeners apply to either driver (here: prefix filters and table naming) + $manager->getEventManager()->addEventListener('loadClassMetadata', new PathPrefixColumnListener()); + if ($prefixes !== []) { + $manager->getEventManager()->addEventListener('loadClassMetadata', new TablePrefixListener($prefixes[0], $prefixes[1])); + } + $schema = (new SchemaTool($manager))->getSchemaFromMetadata([$manager->getClassMetadata(HttpLogEntry::class)]); + $sql = []; + foreach (['sqlite' => $manager->getConnection()->getDatabasePlatform(), 'mysql' => new MySQL80Platform(), 'postgresql' => new PostgreSQLPlatform()] as $name => $platform) { + /* @var AbstractPlatform $platform */ + $sql[$name] = []; + foreach ($schema->getTables() as $table) { + foreach ($platform->getCreateTableSQL($table) as $statement) { + $sql[$name][] = $statement; + } + } + } + + return $sql; + } + + /** + * @param ClassMetadata $metadata + * + * @return array> + */ + private function fields(ClassMetadata $metadata): array + { + $fields = array_map(static fn (object $mapping): array => (array) $mapping, $metadata->fieldMappings); + ksort($fields); + + return $fields; + } + + private function entityManager(MappingDriver $driver): EntityManager + { + $configuration = ORMSetup::createConfiguration(true); + $configuration->setMetadataDriverImpl($driver); + $this->lazyObjects($configuration); + + return new EntityManager(DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true], $configuration), $configuration); + } + + private function lazyObjects(Configuration $configuration): void + { + if (PHP_VERSION_ID >= 80400) { + $configuration->enableNativeLazyObjects(true); + } + } +} From f125db0d30e68aa97ce09451250affacc8dea885 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Franco?= Date: Sat, 21 Nov 2026 13:30:31 +0100 Subject: [PATCH 2/2] test: XML parity by column declaration, one request per pending-change check --- .../config/doctrine/HttpLogEntry.orm.xml | 9 ++-- .../DedicatedEntityManagerKernelTest.php | 22 +++++--- tests/Unit/Doctrine/XmlMappingParityTest.php | 53 ++++++++++++++----- 3 files changed, 60 insertions(+), 24 deletions(-) diff --git a/src/Resources/config/doctrine/HttpLogEntry.orm.xml b/src/Resources/config/doctrine/HttpLogEntry.orm.xml index 48baa58..b8736e8 100644 --- a/src/Resources/config/doctrine/HttpLogEntry.orm.xml +++ b/src/Resources/config/doctrine/HttpLogEntry.orm.xml @@ -4,6 +4,9 @@ entity itself (`doctrine.register_mapping: false`). Same table, columns and indexes as the attributes (tests/Unit/Doctrine/XmlMappingParityTest.php). The path_prefix and usage columns are not mapped here either: PathPrefixColumnListener and UsageColumnsListener add them, and TablePrefixListener renames the table, on both. + Doctrine's XML driver maps the id after the fields: the id column comes last in a CREATE TABLE (the schema + comparator ignores column order, so existing tables see no diff). Boolean defaults are written "0", which every + platform renders like the attributes' false. --> - + - + - + diff --git a/tests/Integration/Doctrine/DedicatedEntityManagerKernelTest.php b/tests/Integration/Doctrine/DedicatedEntityManagerKernelTest.php index 98137b5..1caffd3 100644 --- a/tests/Integration/Doctrine/DedicatedEntityManagerKernelTest.php +++ b/tests/Integration/Doctrine/DedicatedEntityManagerKernelTest.php @@ -70,7 +70,7 @@ public function aSecondManagerMappingTheEntriesFailsTheBuild(): void try { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('are mapped on: default, http_log'); + $this->expectExceptionMessageMatches('/are mapped on: (default, http_log|http_log, default)\\./'); $kernel->boot(); } finally { $kernel->shutdown(); @@ -106,17 +106,15 @@ private function assertEntriesLiveOnTheDedicatedManager(array $httpLog, array $h self::assertFalse($default->getConnection()->createSchemaManager()->tablesExist(['nowo_http_log_entry']), 'no bundle table on the host database'); // the host leaves a pending change on its manager; recording at terminate never flushes it + // (one request: the kernel resets its services, the managers included, before the next main request) $default->persist(new HostArticle('pending')); - foreach (['/hello', '/hello'] as $path) { - $request = Request::create($path, 'GET', [], [], [], ['REMOTE_ADDR' => '127.0.0.1']); - $response = $kernel->handle($request); - self::assertSame(200, $response->getStatusCode()); - $kernel->terminate($request, $response); - } + $this->request($kernel); + self::assertSame(0, (int) $default->getConnection()->fetchOne('SELECT COUNT(*) FROM host_article')); + self::assertCount(1, $default->getUnitOfWork()->getScheduledEntityInsertions()); + $this->request($kernel); self::assertSame(2, (int) $logs->getConnection()->fetchOne('SELECT COUNT(*) FROM nowo_http_log_entry')); self::assertSame(0, (int) $default->getConnection()->fetchOne('SELECT COUNT(*) FROM host_article')); - self::assertCount(1, $default->getUnitOfWork()->getScheduledEntityInsertions()); $repository = $container->get(HttpLogEntryRepository::class); self::assertInstanceOf(HttpLogEntryRepository::class, $repository); @@ -127,6 +125,14 @@ private function assertEntriesLiveOnTheDedicatedManager(array $httpLog, array $h } } + private function request(UsageKernel $kernel): void + { + $request = Request::create('/hello', 'GET', [], [], [], ['REMOTE_ADDR' => '127.0.0.1']); + $response = $kernel->handle($request); + self::assertSame(200, $response->getStatusCode()); + $kernel->terminate($request, $response); + } + /** * Two in-memory SQLite connections: `default` (the host's, auto_mapping on, the host entity) and `logs`. * diff --git a/tests/Unit/Doctrine/XmlMappingParityTest.php b/tests/Unit/Doctrine/XmlMappingParityTest.php index b535986..dbae4dc 100644 --- a/tests/Unit/Doctrine/XmlMappingParityTest.php +++ b/tests/Unit/Doctrine/XmlMappingParityTest.php @@ -23,8 +23,9 @@ use PHPUnit\Framework\Attributes\Test; use PHPUnit\Framework\TestCase; -use function array_map; +use function array_key_exists; use function dirname; +use function is_array; use function ksort; use const PHP_VERSION_ID; @@ -32,7 +33,7 @@ /** * 1.24 (DDD host, B3): the shipped `HttpLogEntry.orm.xml` (validated against Doctrine's XSD) describes exactly what the * entity attributes do: same table, columns, types, options, indexes, id generator and repository, and therefore the - * same DDL on every platform, before and after the bundle's metadata listeners. + * same column declarations and indexes on every platform, before and after the bundle's metadata listeners. */ final class XmlMappingParityTest extends TestCase { @@ -60,7 +61,7 @@ public function bothMappingsGenerateTheSameSchema(): void $xml = $this->createTableSql($this->xmlDriver(), $prefixes); self::assertSame($attribute, $xml); - self::assertNotSame([], $attribute['sqlite']); + self::assertNotSame([], $attribute); } } @@ -77,9 +78,12 @@ private function metadata(MappingDriver $driver): ClassMetadata } /** + * Column declarations (per platform, by column name: the XML driver maps the id after the fields, a column order + * the schema comparator ignores), indexes and primary key of every table. + * * @param list $prefixes [table_prefix, table_name_prefix] of TablePrefixListener, none when empty * - * @return array> + * @return array> */ private function createTableSql(MappingDriver $driver, array $prefixes): array { @@ -89,15 +93,25 @@ private function createTableSql(MappingDriver $driver, array $prefixes): array if ($prefixes !== []) { $manager->getEventManager()->addEventListener('loadClassMetadata', new TablePrefixListener($prefixes[0], $prefixes[1])); } - $schema = (new SchemaTool($manager))->getSchemaFromMetadata([$manager->getClassMetadata(HttpLogEntry::class)]); - $sql = []; - foreach (['sqlite' => $manager->getConnection()->getDatabasePlatform(), 'mysql' => new MySQL80Platform(), 'postgresql' => new PostgreSQLPlatform()] as $name => $platform) { - /* @var AbstractPlatform $platform */ - $sql[$name] = []; - foreach ($schema->getTables() as $table) { - foreach ($platform->getCreateTableSQL($table) as $statement) { - $sql[$name][] = $statement; + $schema = (new SchemaTool($manager))->getSchemaFromMetadata([$manager->getClassMetadata(HttpLogEntry::class)]); + $platforms = ['sqlite' => $manager->getConnection()->getDatabasePlatform(), 'mysql' => new MySQL80Platform(), 'postgresql' => new PostgreSQLPlatform()]; + $sql = []; + foreach ($schema->getTables() as $table) { + $name = $table->getName(); + $indexes = []; + foreach ($table->getIndexes() as $index) { + $indexes[$index->getName()] = [$index->getColumns(), $index->isUnique(), $index->isPrimary()]; + } + ksort($indexes); + $sql[$name]['indexes'] = $indexes; + foreach ($platforms as $platformName => $platform) { + /** @var AbstractPlatform $platform */ + $columns = []; + foreach ($table->getColumns() as $column) { + $columns[$column->getName()] = $platform->getColumnDeclarationSQL($column->getName(), $column->toArray()); } + ksort($columns); + $sql[$name][$platformName] = $columns; } } @@ -111,7 +125,20 @@ private function createTableSql(MappingDriver $driver, array $prefixes): array */ private function fields(ClassMetadata $metadata): array { - $fields = array_map(static fn (object $mapping): array => (array) $mapping, $metadata->fieldMappings); + $fields = []; + foreach ($metadata->fieldMappings as $name => $mapping) { + $field = (array) $mapping; + // the attribute driver writes false where the XML driver leaves null (same meaning), and only it numbers ids + foreach (['unique', 'index', 'nullable'] as $flag) { + $field[$flag] = (bool) ($field[$flag] ?? false); + } + unset($field['idPosition']); + // a boolean column default: false (attribute) and "0" (XML) are the same DEFAULT 0 + if (is_array($field['options'] ?? null) && array_key_exists('default', $field['options']) && $field['type'] === 'boolean') { + $field['options']['default'] = (string) (int) (bool) $field['options']['default']; + } + $fields[$name] = $field; + } ksort($fields); return $fields;