From cb6bf8b9dec1eb9fcc7ff1b439d4ab4262eb52e2 Mon Sep 17 00:00:00 2001 From: silverbackdan Date: Wed, 25 Nov 2026 00:25:59 +0000 Subject: [PATCH 1/2] Restrict the UI and styles of the components a group takes ComponentGroup.allowedComponentUi, keyed by component collection IRI, lists the uiComponent values and uiClassNames entries a group's components may have. Placing a disallowed component, or changing a placed component's UI or styles to a disallowed value, is a 422. The fixture builder, generate-fixtures and make:rename-component carry it. --- CHANGELOG.md | 6 + CLAUDE.md | 13 +- src/Entity/Core/AbstractComponent.php | 1 + src/Entity/Core/ComponentGroup.php | 15 + src/Fixture/Builder/ComponentBuilder.php | 4 +- src/Fixture/Builder/GroupBuilder.php | 9 + src/Fixture/Builder/LayoutBuilder.php | 4 +- src/Fixture/Builder/PageBuilder.php | 4 +- src/Fixture/CwaFixtureBuilder.php | 18 +- src/Fixture/Generator/Plan/GroupPlanner.php | 22 + src/Maker/MakeRenameComponent.php | 2 +- .../Core/ComponentGroupRepository.php | 17 + src/Resources/config/services.php | 24 + .../migration/RenameComponentBody.tpl.php | 14 + src/Utility/AllowedComponentUi.php | 54 ++ .../Constraints/AllowedComponentUi.php | 23 + .../AllowedComponentUiValidator.php | 105 ++++ .../Constraints/ComponentPosition.php | 2 + .../ComponentPositionValidator.php | 47 +- .../ComponentUiAllowedInGroups.php | 26 + .../ComponentUiAllowedInGroupsValidator.php | 99 ++++ tests/Entity/Core/ComponentGroupTest.php | 18 + tests/Fixture/CwaFixtureBuilderTest.php | 35 ++ .../Generator/Plan/GroupPlannerTest.php | 27 + .../ComponentGroupAllowedComponentUiTest.php | 488 ++++++++++++++++++ .../Component/ComponentMoveTest.php | 13 + .../Component/ComponentSiteTrait.php | 36 ++ .../Fixture/FixtureScenarioTrait.php | 27 + .../Fixture/GenerateFixturesRoundTripTest.php | 11 + .../Functional/Maker/RenameComponentTest.php | 36 ++ .../Functional/assets/schema/page.schema.json | 2 +- tests/Maker/RenameComponentMigrationTest.php | 50 +- .../ComponentGroupRepositoryTest.php | 45 ++ tests/Utility/AllowedComponentUiTest.php | 78 +++ .../AllowedComponentUiValidatorTest.php | 210 ++++++++ .../ComponentPositionValidatorTest.php | 66 +++ ...omponentUiAllowedInGroupsValidatorTest.php | 341 ++++++++++++ 37 files changed, 1961 insertions(+), 31 deletions(-) create mode 100644 src/Utility/AllowedComponentUi.php create mode 100644 src/Validator/Constraints/AllowedComponentUi.php create mode 100644 src/Validator/Constraints/AllowedComponentUiValidator.php create mode 100644 src/Validator/Constraints/ComponentUiAllowedInGroups.php create mode 100644 src/Validator/Constraints/ComponentUiAllowedInGroupsValidator.php create mode 100644 tests/Functional/Component/ComponentGroupAllowedComponentUiTest.php create mode 100644 tests/Repository/ComponentGroupRepositoryTest.php create mode 100644 tests/Utility/AllowedComponentUiTest.php create mode 100644 tests/Validator/Constraints/AllowedComponentUiValidatorTest.php create mode 100644 tests/Validator/Constraints/ComponentUiAllowedInGroupsValidatorTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index babb44561..f202c4225 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,12 @@ Every change that reaches `main` adds a line under **Unreleased**. When a versio - Assigning a role the signed-in user does not reach is a 422 on `roles`, and editing or deleting a user who reaches a role the caller does not is a 403 ([#611](https://github.com/components-web-app/api-components-bundle/pull/611)) - `http_cache.personalised_resource_classes`, `scheduled_expiry_resource_classes` and `purge_rendered_html_classes` always keep the CWA defaults; configured or prepended classes are added to them instead of replacing them ([#611](https://github.com/components-web-app/api-components-bundle/pull/611)) +### Added +- `ComponentGroup.allowedComponentUi` restricts, per component collection IRI, the `uiComponent` values (`ui`) and `uiClassNames` entries (`styles`) a group's components may have: placing a component the group does not allow is a 422 on `component` (`to.componentGroup` for `/move`), and changing a placed component's UI or styles to a value one of its groups does not allow is a 422 on `uiComponent` or `uiClassNames`, a draft checked through its published component; `CwaFixtureBuilder` groups take `allowUi:`, `generate-fixtures` writes it and `make:rename-component` renames its keys (PR_LINK) + +### Tooling +- The page JSON schema's `$ref` to the page data schema is a valid JSON pointer, which `justinrainbow/json-schema` 6.15 requires (PR_LINK) + ### Fixed - Normalizing a user no longer writes its reachable roles onto the entity, so a later flush in the same request cannot store them; `roles` in the output (including `/me`) is still every role the user reaches ([#611](https://github.com/components-web-app/api-components-bundle/pull/611)) diff --git a/CLAUDE.md b/CLAUDE.md index 242931074..a1d7ccee2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -385,6 +385,7 @@ Resources are fetched and cached **individually**. Never embed related data outs - `#[Silverback\ExplicitAllowOnly]` (#196): the type may only be placed in a group whose `allowedComponents` lists its collection IRI, enforced on both direct and dynamic positions. Exposed as `explicitAllowOnly: true` on the Hydra `supportedClass` (a locked contract; absent means false). - `allowedComponents` matches by class-level (collection) IRI. - **`ComponentGroup.maxComponents` (#464): `null` is unlimited, otherwise `Assert\Positive`.** It has exactly `allowedComponents`' serialization groups. What counts is `Helper\ComponentPosition\ListedComponentPositions::of()`, the positions the group's response lists (`ComponentGroupNormalizer` uses it too): every position, a dynamic `pageDataProperty` slot as one, minus a static position whose component `allowedComponents` hides. So the module's `componentPositions.length` is the count. A draft is reached through its published component's position, so the pair counts once. +- **`ComponentGroup.allowedComponentUi` restricts the UI of the components a group takes** (cwa-nuxt-module#488, a cross-repo contract with the module). It has exactly `allowedComponents`' serialization groups, and `allowedComponents` is unchanged. Shape: `{: {ui?: [string|null, …], styles?: [string, …]}}`, keyed as `allowedComponents` stores IRIs (no class names). `ui` lists the allowed `uiComponent` values and `styles` the allowed `uiClassNames` entries, both matched exactly as stored (no prefixing, case-sensitive); the primary UI `null` is allowed only when listed, every style a component has must be listed, and an omitted `ui` or `styles`, or a type that is not a key, is unrestricted. `null` or `{}` is stored as `null` (`setAllowedComponentUi()`). `#[AllowedComponentUi]` refuses on `allowedComponentUi` a key that is not the collection IRI of a concrete `AbstractComponent` resource, a rule that is not an object of only `ui` and/or `styles`, a `ui` that is not a list of strings or nulls, `styles` that is not a list of strings, and an **empty** `ui` or `styles` (blocking a type is `allowedComponents`' job). `Utility\AllowedComponentUi` is the one matching rule. **Two checks, and only on a write:** `ComponentPositionValidator` refuses on `component` a position that places a component (new, or its `component` or `componentGroup` changed, as for the cycle check), covering a position `POST`, a clone and `#[AddedComponentPositions]`, and `/move` reports it as `to.componentGroup`; `#[ComponentUiAllowedInGroups]` on `AbstractComponent` refuses on `uiComponent` or `uiClassNames` a component write that changes that field (compared with the unit of work's original data) to a value any group holding it in a position disallows (`ComponentGroupRepository::findRestrictingUiOf()`, one query). **A draft of a published component is compared with and checked against its published component** (a new draft has no original data and no positions); a never-published draft against its own positions. Only the changed field is checked, so a component that already breaks a rule stays editable, and its position re-sortable. A dynamic position's fallback `component` is a placement and is checked; page data component properties are not, as for `allowedComponents`. Saving a restriction never checks a group's existing contents, publishing adds no check, and a component that breaks a rule is never hidden on read (`ListedComponentPositions` ignores it). - **The limit refuses adding, never holding.** `ComponentPositionValidator` checks it only for a position not already in its group's `componentPositions` (created, or moved in from another group), with a violation on `componentGroup`. A position already in the group can be re-sorted or re-pointed even when the group is over its limit, and lowering the limit deletes nothing. The over-limit state is not reported by the API; the module compares the two fields. - **A component is never placed inside its own subtree** (#502). `Helper\ComponentPosition\ComponentCycleDetector` is the one rule: walk upward from a group (its owners, the groups holding them, their owners…, pages and layouts ending it) with a visited set, on the in-memory collections the write is building, and a published component and its draft count as one. `ComponentPositionValidator` refuses a placement on `component` only when the position is new or its `component` or `componentGroup` changed (the unit of work's original data), so editing inside a cycle already held is never blocked; `#[AcyclicComponentGroupOwners]` on `ComponentGroup::$components` refuses an owner from inside the group on `components`, only for an owner not already held (the owner's `componentGroups` snapshot). Unlike the limit, a cycle is never allowed to be added, but one already in the database (fixtures and SQL bypass validation) must still read: every upward walk (`ComponentVoter::getComponentPages()`, `ManifestKeyResolver`) carries its own visited set. `Component\ComponentPositionCycleTest` pins both. - **A position written inside a component (`componentPositions` on a component write, the module's add flow) is validated by `#[AddedComponentPositions]`** on `AbstractComponent::$componentPositions`, which runs the whole `ComponentPosition` constraint on each position not already in its group, at `componentPositions[i]`. Never replace it with `Assert\Valid`: that would re-check every existing position on any component edit, so a group whose `allowedComponents` or limit changed later would block editing its components. @@ -527,7 +528,7 @@ The bundle does not set `use_symfony_listeners`. API Platform's default (`false` - **API Platform resets its skolem IRI converter itself from 4.4.5 and 5.0.4** (api-platform/core#8681), which is why the bundle requires them: it keeps every anonymous object it gives a `/.well-known/genid/` IRI (each `_metadata` object) until a services reset. `Page\WorkerModeMemoryTest` pins it. - Optional collaborators (logger, purger) are wired as `new Reference(..., NULL_ON_INVALID_REFERENCE)`. - **Config nodes:** never put `isRequired()` on a child of a node with `addDefaultsIfNotSet()` or `canBeDisabled()`. The default is inserted without finalising, so the check never runs (#214). Give the child a real default or make the parent required. Use `->validate()` for invalid combinations. Env placeholders skip node validators, so validate again at run time. -- `make:rename-component` generates through `doctrine.migrations.dependency_factory` and reads table names from `ClassMetadata`. **Never `LIKE`-match an IRI in a `json` column** (slashes are escaped). AP's `getIriFromResource()` returns a `/.well-known/genid/` blank node, not an exception, for a non-resource class. +- `make:rename-component` generates through `doctrine.migrations.dependency_factory` and reads table names from `ClassMetadata`. Its migration rewrites `allowed_components` entries and renames `allowed_component_ui` keys (order and rules kept), decoding each row in PHP. **Never `LIKE`-match an IRI in a `json` column** (slashes are escaped). AP's `getIriFromResource()` returns a `/.well-known/genid/` blank node, not an exception, for a non-resource class. --- @@ -548,10 +549,10 @@ CwaFixtureBuilder ->publish(object, ?at: DateTimeInterface): object (sets the publishable date now, or to `at`, in the class the mapping uses; returns the object; never persists) ->asset(sha256, ?name): UploadedFile (a copy of a fixture asset from the store, under its manifest name or `name`; only while an AbstractCwaScaffold loads) ->getSummary(): CwaFixtureSummary, ->reportSummary() (what the last load created, kept and skipped) -LayoutBuilder ->group(name, allow: [], ?Closure, ?locationReference, ?max): GroupBuilder, ->uiClassNames(...) -PageBuilder ->title(), ->metaDescription(), ->uiClassNames(), ->group(name, ?Closure, ?locationReference, allow: [], ?max), ->liveAt(?DateTimeImmutable), ->withoutRoute(), ->reachableWithoutRoute(bool = true), ->redirectTo(routeName), ->nested(Closure): self, ->getRoute() +LayoutBuilder ->group(name, allow: [], ?Closure, ?locationReference, ?max, allowUi: []): GroupBuilder, ->uiClassNames(...) +PageBuilder ->title(), ->metaDescription(), ->uiClassNames(), ->group(name, ?Closure, ?locationReference, allow: [], ?max, allowUi: []), ->liveAt(?DateTimeImmutable), ->withoutRoute(), ->reachableWithoutRoute(bool = true), ->redirectTo(routeName), ->nested(Closure): self, ->getRoute() PageDataBuilder ->liveAt(?DateTimeImmutable), ->withoutRoute(), ->redirectTo(routeName), ->nested(Closure): self, ->linkRoute(property, routeName|page:), ->linkIri(property, ?key, page:|layout:|pageData:|route:), ->onRoutesCreated(Closure(array)), ->getRoute() -ComponentBuilder ->uiComponent(suffix), ->uiClassNames(...), ->group(name, allow: [], ?Closure, ?locationReference, ?max), ->linkRoute(property, routeName|page:), ->linkIri(property, ?key, page:|layout:|pageData:|route:), ->draft(AbstractComponent) +ComponentBuilder ->uiComponent(suffix), ->uiClassNames(...), ->group(name, allow: [], ?Closure, ?locationReference, ?max, allowUi: []), ->linkRoute(property, routeName|page:), ->linkIri(property, ?key, page:|layout:|pageData:|route:), ->draft(AbstractComponent) GroupBuilder ->add(AbstractComponent, ?sort), ->pageDataPosition(pageDataClass, propertyName, ?sort) ``` @@ -568,7 +569,7 @@ GroupBuilder ->add(AbstractComponent, ?sort), ->pageDataPosition(pageDataCla - **A kept group's scaffold positions are counted in the summary** (`skipped N positions (group kept)`) and the notice names the group and its owner (`the page \`home\``), so a component added to an existing group is never dropped silently. - **`ComponentBuilder::draft()` links the draft at once** (the publishable `associationName`) and persists it in the positions phase, skipped as `linked to skipped content` when its published component is. `publish()` and `draft()` need the `PublishableAttributeReader` (the builder's last constructor argument) and throw `\LogicException` for a class that is not publishable. Both go through `CwaFixtureBuilder` (a `ComponentBuilder` is given its `linkDraft` closure), so there is one check and one property accessor. - **A draft of a published component given to `GroupBuilder::add()`, a page data component field or a component field is stored as its published component** (#520), by `DraftComponentReferenceListener` at flush, not by the builder; the draft is still persisted and linked. **A group declared on such a draft (`$cwa->component($draft)->group()`) is created for its published component**, named after the published component's IRI (`publishedGroupOwner()`), as the module names a group's location. `GenerateFixturesRoundTripTest` pins each. -- `PageBuilder::group()` takes `allow:` and `max:` last so existing positional closure calls keep working. `max:` sets the group's `maxComponents` only when the builder creates the group (a kept group is untouched), and the builder does not enforce it: fixtures bypass validation, as for `allow:`. +- `PageBuilder::group()` takes `allow:`, `max:` and `allowUi:` last so existing positional closure calls keep working. `max:` and `allowUi:` (keyed by class name, resolved to collection IRIs like `allow:`, the rule written as the API takes it) are set only when the builder creates the group (a kept group is untouched), and the builder enforces neither: fixtures bypass validation, as for `allow:`. - `onRoutesCreated` may only mutate entities already persisted (set on the page data before `->pageData()` so phase one cascades them); it never calls `persist()`. - The builder handles timestamping, persisting, dedup of layouts/pages and groups, position sort values (from 0, in steps of 1, as the API orders a group), bidirectional links and parent propagation. `allow:` takes class names and resolves collection IRIs. - **Every entity the builder persists through `persistWithAssociations()` is timestamped there**, whether it came from a builder, `persist()` or the walk of owning associations (a component held only in a page data field), when it is `#[Timestamped]` and new: not yet managed, or scheduled for insert by a cascade. An entity already in the database keeps its dates. Groups, positions and routes are persisted with `manager->persist()` directly and timestamp themselves; anything new persisted that way must too. @@ -613,7 +614,7 @@ A redirect's name registers to whatever route holds its path or its name, whethe - **A component is inline** (`new X()`, or `$cwa->publish(new X())`) only with one use and nothing to set, link, draft or own. A related component placed nowhere is declared before the one that refers to it; a cycle's back edge is assigned after every declaration of the method. - **Names**: the first non-blank `label`, `title`, `name`, `heading` or `reference`, else the text of the first `

`–`

` in any string field (a tag or ` ` separates words), else the owner's reference and group name; a word repeated consecutively counts once (`trainingMainContainer`, never `trainingMainMainMain…`); up to 4 words, then the short class name. Leading numbers follow the first word (`results2024DummyNavigationLink`); numbers alone put the class first (`page404`). A clash gets `2`, `3`…, after an underscore when the name ends in a digit (`dummyNavigationLink2024_2`). A draft is its published component's name plus `Draft`, the published name is fitted 5 characters shorter so both share one stem, and a taken draft name is a clash on the pair (`live2`/`live2Draft`). **No identifier is over 40 characters**: stop words (`to`, `the`, `our`…) go first unless only stop words are left, then identifying words from the end, then the class name loses its leading words, never its last; a clash suffix counts. A name starting with the class lower-cases a leading acronym whole (`htmlBlock`). `make:cwa-scaffold` uses the same `VariableNamer`. - **`PhpValueExporter` keeps every string byte-exact.** Never insert a newline that is not in the value: long HTML is split after top-level block closing tags into concatenated pieces, a value with newlines is a flexible nowdoc only when no line starts with a tab or ends in a space or tab (an editor or php-cs-fixer would strip it), it has no other control character and no line could close the marker (`HTML2`… otherwise), and anything with a control character is a double-quoted piece. Lists are written without keys (`array_is_list()`). -- **Arguments**: a group's `allow:` then `max:` (only when not null). A layout's and page's `uiComponent:` is named, since the bare suffix (`'Primary'`) does not say what it is. +- **Arguments**: a group's `allow:`, then `max:` (only when not null), then `allowUi:` (only when set; a key that matches no component class is reported). A layout's and page's `uiComponent:` is named, since the bare suffix (`'Primary'`) does not say what it is. - **Routes**: a route is always written as an explicit `route:`. A link is `->linkRoute('route', routeName: 'about')`, the second argument named so the call says it is a route name. `routeName:` and a redirect's `name:` are left out only when the builder would derive the same name; both sides use `Utility\RouteName::fromPath()`, and the redirect simulation makes the name unique against the site's routes and the redirects before it, as `CwaFixtureBuilder` does. A route association is `->linkRoute()` next to its component or page data; `afterRoutes()` is never generated. A page's or page data's own route that redirects is `->redirectTo(routeName: …)` after its `liveAt()` (#461); a target that is not part of the site is reported, never dropped (`test_no_route_redirect_is_left_out_without_being_reported`). - **Dates**: a past `publishedAt` is `$cwa->publish($x)` (published at load time), a future one `publish($x, at: …)` exactly, and only a future or null `liveAt` is written. `--keep-timestamps` writes every one exactly. A draft is `$cwa->component($published)->draft($draft)`. - Component and page data fields come from Doctrine metadata through `Site\EntityStateReader`, which reads through `initializeObject()` first (`getFieldValue()` does not initialise a lazy object), and skips identifiers, timestamps, the publishable fields, uploadable storage fields and values equal to the property default. Each is written through its public property, else its setter. diff --git a/src/Entity/Core/AbstractComponent.php b/src/Entity/Core/AbstractComponent.php index c55334352..891371f79 100644 --- a/src/Entity/Core/AbstractComponent.php +++ b/src/Entity/Core/AbstractComponent.php @@ -35,6 +35,7 @@ #[ORM\DiscriminatorColumn(name: 'dtype', type: 'string', length: 255)] #[ApiResource] #[Get] +#[AcbAssert\ComponentUiAllowedInGroups] abstract class AbstractComponent implements ComponentInterface, VersionedInterface { use IdTrait; diff --git a/src/Entity/Core/ComponentGroup.php b/src/Entity/Core/ComponentGroup.php index c824586e4..b76f3f9cf 100644 --- a/src/Entity/Core/ComponentGroup.php +++ b/src/Entity/Core/ComponentGroup.php @@ -81,6 +81,14 @@ class ComponentGroup #[Groups(['ComponentGroup:read', 'ComponentGroup:write', 'Layout:read', 'Page:read'])] public ?array $allowedComponents = null; + /** + * @var array, styles?: list}>|null + */ + #[ORM\Column(name: 'allowed_component_ui', type: 'json', nullable: true)] + #[Groups(['ComponentGroup:read', 'ComponentGroup:write', 'Layout:read', 'Page:read'])] + #[AcbAssert\AllowedComponentUi] + public ?array $allowedComponentUi = null; + #[ORM\Column(name: 'max_components', type: 'integer', nullable: true)] #[Groups(['ComponentGroup:read', 'ComponentGroup:write', 'Layout:read', 'Page:read'])] #[Assert\Positive] @@ -211,4 +219,11 @@ public function addAllowedComponent(string $allowedComponent): self return $this; } + + public function setAllowedComponentUi(?array $allowedComponentUi): self + { + $this->allowedComponentUi = $allowedComponentUi ?: null; + + return $this; + } } diff --git a/src/Fixture/Builder/ComponentBuilder.php b/src/Fixture/Builder/ComponentBuilder.php index deef15c4f..aa8e538b7 100644 --- a/src/Fixture/Builder/ComponentBuilder.php +++ b/src/Fixture/Builder/ComponentBuilder.php @@ -51,10 +51,10 @@ public function uiClassNames(string ...$classes): self return $this; } - public function group(string $name, array $allow = [], ?\Closure $configure = null, ?string $locationReference = null, ?int $max = null): GroupBuilder + public function group(string $name, array $allow = [], ?\Closure $configure = null, ?string $locationReference = null, ?int $max = null, array $allowUi = []): GroupBuilder { if (!isset($this->groupBuilders[$name])) { - $this->groupBuilders[$name] = new GroupBuilder($name, $allow, $locationReference, $max); + $this->groupBuilders[$name] = new GroupBuilder($name, $allow, $locationReference, $max, $allowUi); } if (null !== $configure) { $configure($this->groupBuilders[$name]); diff --git a/src/Fixture/Builder/GroupBuilder.php b/src/Fixture/Builder/GroupBuilder.php index b55d3a3d9..9ff4331d1 100644 --- a/src/Fixture/Builder/GroupBuilder.php +++ b/src/Fixture/Builder/GroupBuilder.php @@ -26,6 +26,7 @@ public function __construct( private readonly array $allowedClasses = [], private readonly ?string $locationReference = null, private readonly ?int $maxComponents = null, + private readonly array $allowedComponentUi = [], ) { } @@ -60,6 +61,14 @@ public function getMaxComponents(): ?int return $this->maxComponents; } + /** + * @return array, styles?: list}> + */ + public function getAllowedComponentUi(): array + { + return $this->allowedComponentUi; + } + public function getLocationReference(): ?string { return $this->locationReference; diff --git a/src/Fixture/Builder/LayoutBuilder.php b/src/Fixture/Builder/LayoutBuilder.php index 33bba7476..0814492fc 100644 --- a/src/Fixture/Builder/LayoutBuilder.php +++ b/src/Fixture/Builder/LayoutBuilder.php @@ -22,10 +22,10 @@ public function __construct(private readonly Layout $layout) { } - public function group(string $name, array $allow = [], ?\Closure $configure = null, ?string $locationReference = null, ?int $max = null): GroupBuilder + public function group(string $name, array $allow = [], ?\Closure $configure = null, ?string $locationReference = null, ?int $max = null, array $allowUi = []): GroupBuilder { if (!isset($this->groupBuilders[$name])) { - $this->groupBuilders[$name] = new GroupBuilder($name, $allow, $locationReference, $max); + $this->groupBuilders[$name] = new GroupBuilder($name, $allow, $locationReference, $max, $allowUi); } if (null !== $configure) { $configure($this->groupBuilders[$name]); diff --git a/src/Fixture/Builder/PageBuilder.php b/src/Fixture/Builder/PageBuilder.php index 3614b5b00..b6fa10270 100644 --- a/src/Fixture/Builder/PageBuilder.php +++ b/src/Fixture/Builder/PageBuilder.php @@ -119,10 +119,10 @@ public function takeRedirectTo(): ?string return $routeName; } - public function group(string $name, ?\Closure $configure = null, ?string $locationReference = null, array $allow = [], ?int $max = null): GroupBuilder + public function group(string $name, ?\Closure $configure = null, ?string $locationReference = null, array $allow = [], ?int $max = null, array $allowUi = []): GroupBuilder { if (!isset($this->groupBuilders[$name])) { - $this->groupBuilders[$name] = new GroupBuilder($name, $allow, $locationReference, $max); + $this->groupBuilders[$name] = new GroupBuilder($name, $allow, $locationReference, $max, $allowUi); } if (null !== $configure) { $configure($this->groupBuilders[$name]); diff --git a/src/Fixture/CwaFixtureBuilder.php b/src/Fixture/CwaFixtureBuilder.php index ed1dd5860..eb6508c7e 100644 --- a/src/Fixture/CwaFixtureBuilder.php +++ b/src/Fixture/CwaFixtureBuilder.php @@ -762,14 +762,13 @@ private function createAndLinkComponentGroup(GroupBuilder $groupBuilder, Layout| $componentGroup->maxComponents = $groupBuilder->getMaxComponents(); foreach ($groupBuilder->getAllowedClasses() as $class) { - $componentGroup->addAllowedComponent( - $this->iriConverter->getIriFromResource( - $class, - UrlGeneratorInterface::ABS_PATH, - (new GetCollection())->withClass($class) - ) - ); + $componentGroup->addAllowedComponent($this->collectionIri($class)); } + $allowedComponentUi = []; + foreach ($groupBuilder->getAllowedComponentUi() as $class => $rule) { + $allowedComponentUi[$this->collectionIri($class)] = $rule; + } + $componentGroup->setAllowedComponentUi($allowedComponentUi); $this->timestampedPersister->persistTimestampedFields($componentGroup, true); $this->manager->persist($componentGroup); @@ -784,6 +783,11 @@ private function createAndLinkComponentGroup(GroupBuilder $groupBuilder, Layout| $this->componentGroupMap[$groupBuilderId] = $componentGroup; } + private function collectionIri(string $class): string + { + return (string) $this->iriConverter->getIriFromResource($class, UrlGeneratorInterface::ABS_PATH, (new GetCollection())->withClass($class)); + } + private function publishedGroupOwner(Layout|Page|AbstractComponent $owner): Layout|Page|AbstractComponent { if (!$owner instanceof AbstractComponent || null === $this->publishableAttributeReader || !$this->publishableAttributeReader->isConfigured($owner)) { diff --git a/src/Fixture/Generator/Plan/GroupPlanner.php b/src/Fixture/Generator/Plan/GroupPlanner.php index 76df0b56e..174e8baed 100644 --- a/src/Fixture/Generator/Plan/GroupPlanner.php +++ b/src/Fixture/Generator/Plan/GroupPlanner.php @@ -86,6 +86,10 @@ public function plan(ComponentGroup $group, Layout|Page|AbstractComponent $owner if (null !== $group->maxComponents) { $arguments[] = 'max: ' . $group->maxComponents; } + $allowedUi = $this->resolveAllowedComponentUi($group); + if ([] !== $allowedUi) { + $arguments[] = 'allowUi: [' . implode(', ', $allowedUi) . ']'; + } return new GroupPlan($name, $arguments); } @@ -108,6 +112,24 @@ private function resolveAllowedClasses(ComponentGroup $group): array return $allowed; } + /** + * @return list + */ + private function resolveAllowedComponentUi(ComponentGroup $group): array + { + $allowed = []; + foreach ($group->allowedComponentUi ?? [] as $iri => $rule) { + $class = $this->getComponentClassesByIri()[$iri] ?? null; + if (null === $class) { + $this->report->add(\sprintf('Allowed component UI for "%s" on the component group "%s" does not match a component class.', $iri, $group->reference)); + continue; + } + $allowed[] = $this->imports->add($class) . '::class => ' . $this->export($rule); + } + + return $allowed; + } + /** * @return array */ diff --git a/src/Maker/MakeRenameComponent.php b/src/Maker/MakeRenameComponent.php index 5443e43ef..37f867513 100644 --- a/src/Maker/MakeRenameComponent.php +++ b/src/Maker/MakeRenameComponent.php @@ -48,7 +48,7 @@ public static function getCommandName(): string public static function getCommandDescription(): string { - return 'Generate a Doctrine migration to rename a CWA component type (dtype + allowedComponents)'; + return 'Generate a Doctrine migration to rename a CWA component type (dtype, allowedComponents and allowedComponentUi)'; } public function configureCommand(Command $command, InputConfiguration $inputConf): void diff --git a/src/Repository/Core/ComponentGroupRepository.php b/src/Repository/Core/ComponentGroupRepository.php index eed4a6e25..8bab4e30c 100644 --- a/src/Repository/Core/ComponentGroupRepository.php +++ b/src/Repository/Core/ComponentGroupRepository.php @@ -15,6 +15,7 @@ use Doctrine\Persistence\ManagerRegistry; use Ramsey\Uuid\Exception\InvalidUuidStringException; use Ramsey\Uuid\Uuid; +use Silverback\ApiComponentsBundle\Entity\Core\AbstractComponent; use Silverback\ApiComponentsBundle\Entity\Core\ComponentGroup; /** @@ -50,4 +51,20 @@ public function findOneByIdOrReference(string $idOrRef): ?ComponentGroup return null; } + + /** + * @return list + */ + public function findRestrictingUiOf(AbstractComponent $component): array + { + return $this->createQueryBuilder('g') + ->distinct() + ->innerJoin('g.componentPositions', 'p') + ->where('p.component = :component') + ->andWhere('g.allowedComponentUi IS NOT NULL') + ->setParameter('component', $component) + ->orderBy('g.reference', 'ASC') + ->getQuery() + ->getResult(); + } } diff --git a/src/Resources/config/services.php b/src/Resources/config/services.php index 7b9eaf77e..6e93b57f7 100644 --- a/src/Resources/config/services.php +++ b/src/Resources/config/services.php @@ -234,8 +234,10 @@ use Silverback\ApiComponentsBundle\Utility\ApiResourceRouteFinder; use Silverback\ApiComponentsBundle\Validator\Constraints\AcyclicComponentGroupOwnersValidator; use Silverback\ApiComponentsBundle\Validator\Constraints\AddedComponentPositionsValidator; +use Silverback\ApiComponentsBundle\Validator\Constraints\AllowedComponentUiValidator; use Silverback\ApiComponentsBundle\Validator\Constraints\AssignableRolesValidator; use Silverback\ApiComponentsBundle\Validator\Constraints\ComponentPositionValidator; +use Silverback\ApiComponentsBundle\Validator\Constraints\ComponentUiAllowedInGroupsValidator; use Silverback\ApiComponentsBundle\Validator\Constraints\FormTypeClassValidator; use Silverback\ApiComponentsBundle\Validator\Constraints\NewEmailAddressRequiresPasswordValidator; use Silverback\ApiComponentsBundle\Validator\Constraints\NewEmailAddressValidator; @@ -553,6 +555,28 @@ ->tag('validator.constraint_validator'); $services->alias(AddedComponentPositionsValidator::class, 'silverback.api_components.validator.added_component_positions'); + $services + ->set('silverback.api_components.validator.allowed_component_ui') + ->class(AllowedComponentUiValidator::class) + ->args([ + new Reference(ResourceNameCollectionFactoryInterface::class), + new Reference(IriConverterInterface::class), + ]) + ->tag('validator.constraint_validator'); + $services->alias(AllowedComponentUiValidator::class, 'silverback.api_components.validator.allowed_component_ui'); + + $services + ->set('silverback.api_components.validator.component_ui_allowed_in_groups') + ->class(ComponentUiAllowedInGroupsValidator::class) + ->args([ + new Reference(ManagerRegistry::class), + new Reference('silverback.doctrine.repository.component_group'), + new Reference(PublishableAttributeReader::class), + new Reference(IriConverterInterface::class), + ]) + ->tag('validator.constraint_validator'); + $services->alias(ComponentUiAllowedInGroupsValidator::class, 'silverback.api_components.validator.component_ui_allowed_in_groups'); + $services ->set('silverback.api_components.api_platform.property_metadata_factory.component') ->class(ComponentPropertyMetadataFactory::class) diff --git a/src/Resources/skeleton/migration/RenameComponentBody.tpl.php b/src/Resources/skeleton/migration/RenameComponentBody.tpl.php index bc63b3f54..15e080d1b 100644 --- a/src/Resources/skeleton/migration/RenameComponentBody.tpl.php +++ b/src/Resources/skeleton/migration/RenameComponentBody.tpl.php @@ -9,3 +9,17 @@ ['components' => json_encode(array_map(static fn (string $c): string => === $c ? : $c, $components)), 'id' => $row['id']] ); } +foreach ($this->connection->fetchAllAssociative('SELECT id, allowed_component_ui FROM WHERE allowed_component_ui IS NOT NULL') as $row) { + $rules = json_decode((string) $row['allowed_component_ui'], true); + if (!\is_array($rules) || !\array_key_exists(, $rules)) { + continue; + } + $renamed = []; + foreach ($rules as $iri => $rule) { + $renamed[ === $iri ? : $iri] = $rule; + } + $this->connection->executeStatement( + 'UPDATE SET allowed_component_ui = :rules WHERE id = :id', + ['rules' => json_encode($renamed), 'id' => $row['id']] + ); +} diff --git a/src/Utility/AllowedComponentUi.php b/src/Utility/AllowedComponentUi.php new file mode 100644 index 000000000..a55664773 --- /dev/null +++ b/src/Utility/AllowedComponentUi.php @@ -0,0 +1,54 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Silverback\ApiComponentsBundle\Utility; + +final class AllowedComponentUi +{ + /** + * @param array|null $allowedComponentUi + */ + public static function allowsUiComponent(?array $allowedComponentUi, string $componentIri, ?string $uiComponent): bool + { + if (!isset($allowedComponentUi[$componentIri]['ui'])) { + return true; + } + + return \in_array($uiComponent, $allowedComponentUi[$componentIri]['ui'], true); + } + + /** + * @param array|null $allowedComponentUi + * @param array|null $uiClassNames + * + * @return list + */ + public static function disallowedStyles(?array $allowedComponentUi, string $componentIri, ?array $uiClassNames): array + { + if (!isset($allowedComponentUi[$componentIri]['styles']) || null === $uiClassNames) { + return []; + } + + $disallowed = []; + foreach ($uiClassNames as $style) { + if (!\in_array($style, $allowedComponentUi[$componentIri]['styles'], true)) { + $disallowed[] = \is_string($style) ? $style : json_encode($style, \JSON_THROW_ON_ERROR); + } + } + + return $disallowed; + } + + public static function describeUiComponent(?string $uiComponent): string + { + return $uiComponent ?? 'null'; + } +} diff --git a/src/Validator/Constraints/AllowedComponentUi.php b/src/Validator/Constraints/AllowedComponentUi.php new file mode 100644 index 000000000..c637bfe7f --- /dev/null +++ b/src/Validator/Constraints/AllowedComponentUi.php @@ -0,0 +1,23 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Silverback\ApiComponentsBundle\Validator\Constraints; + +use Symfony\Component\Validator\Constraint; + +#[\Attribute(\Attribute::TARGET_PROPERTY)] +final class AllowedComponentUi extends Constraint +{ + public string $keyMessage = '`{{ key }}` is not the collection IRI of a component resource.'; + public string $ruleMessage = 'The rule for `{{ key }}` must be an object with `ui`, `styles` or both, and nothing else.'; + public string $uiMessage = 'The `ui` for `{{ key }}` must be a non-empty list of strings or nulls.'; + public string $stylesMessage = 'The `styles` for `{{ key }}` must be a non-empty list of strings.'; +} diff --git a/src/Validator/Constraints/AllowedComponentUiValidator.php b/src/Validator/Constraints/AllowedComponentUiValidator.php new file mode 100644 index 000000000..d65853e53 --- /dev/null +++ b/src/Validator/Constraints/AllowedComponentUiValidator.php @@ -0,0 +1,105 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Silverback\ApiComponentsBundle\Validator\Constraints; + +use ApiPlatform\Metadata\Exception\ExceptionInterface; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\IriConverterInterface; +use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface; +use ApiPlatform\Metadata\UrlGeneratorInterface; +use Silverback\ApiComponentsBundle\Entity\Core\AbstractComponent; +use Symfony\Component\Validator\Constraint; +use Symfony\Component\Validator\ConstraintValidator; + +final class AllowedComponentUiValidator extends ConstraintValidator +{ + public function __construct( + private readonly ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory, + private readonly IriConverterInterface $iriConverter, + ) { + } + + /** + * @param array|null $value + * @param AllowedComponentUi $constraint + */ + public function validate(mixed $value, Constraint $constraint): void + { + if (null === $value) { + return; + } + + $componentIris = $this->componentCollectionIris(); + foreach ($value as $key => $rule) { + if (!\in_array($key, $componentIris, true)) { + $this->addViolation($constraint->keyMessage, $key); + + continue; + } + + if (!\is_array($rule) || [] === $rule || [] !== array_diff(array_keys($rule), ['ui', 'styles'])) { + $this->addViolation($constraint->ruleMessage, $key); + + continue; + } + + if (\array_key_exists('ui', $rule) && !self::isNonEmptyListOfStrings($rule['ui'], true)) { + $this->addViolation($constraint->uiMessage, $key); + } + + if (\array_key_exists('styles', $rule) && !self::isNonEmptyListOfStrings($rule['styles'], false)) { + $this->addViolation($constraint->stylesMessage, $key); + } + } + } + + private function addViolation(string $message, int|string $key): void + { + $this->context->buildViolation($message) + ->setParameter('{{ key }}', (string) $key) + ->addViolation(); + } + + /** + * @return list + */ + private function componentCollectionIris(): array + { + $iris = []; + foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) { + if (!is_subclass_of($resourceClass, AbstractComponent::class) || (new \ReflectionClass($resourceClass))->isAbstract()) { + continue; + } + try { + $iris[] = (string) $this->iriConverter->getIriFromResource($resourceClass, UrlGeneratorInterface::ABS_PATH, (new GetCollection())->withClass($resourceClass)); + } catch (ExceptionInterface) { + } + } + + return $iris; + } + + private static function isNonEmptyListOfStrings(mixed $values, bool $nullable): bool + { + if (!\is_array($values) || [] === $values || !array_is_list($values)) { + return false; + } + + foreach ($values as $value) { + if (!\is_string($value) && !($nullable && null === $value)) { + return false; + } + } + + return true; + } +} diff --git a/src/Validator/Constraints/ComponentPosition.php b/src/Validator/Constraints/ComponentPosition.php index ca3c4b3ab..03789c6c4 100644 --- a/src/Validator/Constraints/ComponentPosition.php +++ b/src/Validator/Constraints/ComponentPosition.php @@ -29,6 +29,8 @@ class ComponentPosition extends Constraint public string $anchorWithSortValueMessage = 'Send an anchor or a sortValue, not both: the server chooses the sortValue.'; public string $bothAnchorsMessage = 'Send either after or before, not both.'; public string $cycleMessage = 'The component cannot be placed in the component group `{{ reference }}`: the group is inside the component.'; + public string $uiMessage = 'The UI `{{ ui }}` is not allowed for `{{ iri }}` in the component group `{{ reference }}`.'; + public string $stylesMessage = 'The styles `{{ styles }}` are not allowed for `{{ iri }}` in the component group `{{ reference }}`.'; public string $selfAnchorMessage = 'A position cannot be placed relative to itself.'; public string $invalidPageDataPropertyMessage = '`{{ property }}` is not a component-typed property on `{{ class }}`'; diff --git a/src/Validator/Constraints/ComponentPositionValidator.php b/src/Validator/Constraints/ComponentPositionValidator.php index 11959884f..6f78186f6 100644 --- a/src/Validator/Constraints/ComponentPositionValidator.php +++ b/src/Validator/Constraints/ComponentPositionValidator.php @@ -24,6 +24,7 @@ use Silverback\ApiComponentsBundle\Helper\ComponentPosition\ComponentPositionIriResolver; use Silverback\ApiComponentsBundle\Helper\ComponentPosition\ListedComponentPositions; use Silverback\ApiComponentsBundle\Metadata\Provider\PageDataMetadataProvider; +use Silverback\ApiComponentsBundle\Utility\AllowedComponentUi; use Silverback\ApiComponentsBundle\Validator\Constraints\ComponentPosition as ComponentPositionConstraint; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; @@ -60,8 +61,12 @@ public function validate($componentPosition, Constraint $constraint): void $component = $componentPosition->component; if ($component) { - $this->validateDirectComponent($componentPosition, $constraint, $component, $collection); - $this->validateNoCycle($componentPosition, $constraint, $component, $collection); + $iri = $this->collectionIri($component::class); + $this->validateDirectComponent($constraint, $component, $iri, $collection); + if ($this->isPlacementWritten($componentPosition)) { + $this->validateComponentUi($constraint, $component, $iri, $collection); + $this->validateNoCycle($constraint, $component, $collection); + } return; } @@ -92,9 +97,36 @@ private function validateMaxComponents(ComponentPosition $componentPosition, Com ->addViolation(); } - private function validateNoCycle(ComponentPosition $componentPosition, ComponentPositionConstraint $constraint, AbstractComponent $component, ComponentGroup $collection): void + private function collectionIri(string $resourceClass): string + { + return (string) $this->iriConverter->getIriFromResource($resourceClass, UrlGeneratorInterface::ABS_PATH, (new GetCollection())->withClass($resourceClass)); + } + + private function validateComponentUi(ComponentPositionConstraint $constraint, AbstractComponent $component, string $iri, ComponentGroup $collection): void { - if (!$this->isPlacementWritten($componentPosition) || !$this->cycleDetector->isPlacementCyclic($component, $collection)) { + if (!AllowedComponentUi::allowsUiComponent($collection->allowedComponentUi, $iri, $component->uiComponent)) { + $this->context->buildViolation($constraint->uiMessage) + ->atPath('component') + ->setParameter('{{ ui }}', AllowedComponentUi::describeUiComponent($component->uiComponent)) + ->setParameter('{{ iri }}', $iri) + ->setParameter('{{ reference }}', (string) $collection->reference) + ->addViolation(); + } + + $disallowedStyles = AllowedComponentUi::disallowedStyles($collection->allowedComponentUi, $iri, $component->uiClassNames); + if ($disallowedStyles) { + $this->context->buildViolation($constraint->stylesMessage) + ->atPath('component') + ->setParameter('{{ styles }}', implode(', ', $disallowedStyles)) + ->setParameter('{{ iri }}', $iri) + ->setParameter('{{ reference }}', (string) $collection->reference) + ->addViolation(); + } + } + + private function validateNoCycle(ComponentPositionConstraint $constraint, AbstractComponent $component, ComponentGroup $collection): void + { + if (!$this->cycleDetector->isPlacementCyclic($component, $collection)) { return; } @@ -160,11 +192,8 @@ private function validateAnchors(ComponentPosition $componentPosition, Component } } - private function validateDirectComponent(ComponentPosition $componentPosition, ComponentPositionConstraint $constraint, object $component, object $collection): void + private function validateDirectComponent(ComponentPositionConstraint $constraint, object $component, string $iri, object $collection): void { - $resourceClass = $component::class; - $iri = $this->iriConverter->getIriFromResource($resourceClass, UrlGeneratorInterface::ABS_PATH, (new GetCollection())->withClass($resourceClass)); - if ($allowedComponents = $collection->allowedComponents) { if (!\in_array($iri, $allowedComponents, true)) { $this->context->buildViolation($constraint->message) @@ -221,7 +250,7 @@ private function validateDynamicPosition(ComponentPosition $componentPosition, C } $componentClass = $propertyMetadata->getComponentClass(); - $iri = $this->iriConverter->getIriFromResource($componentClass, UrlGeneratorInterface::ABS_PATH, (new GetCollection())->withClass($componentClass)); + $iri = $this->collectionIri($componentClass); if ($allowedComponents = $collection->allowedComponents) { if (!\in_array($iri, $allowedComponents, true)) { diff --git a/src/Validator/Constraints/ComponentUiAllowedInGroups.php b/src/Validator/Constraints/ComponentUiAllowedInGroups.php new file mode 100644 index 000000000..a928241e2 --- /dev/null +++ b/src/Validator/Constraints/ComponentUiAllowedInGroups.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Silverback\ApiComponentsBundle\Validator\Constraints; + +use Symfony\Component\Validator\Constraint; + +#[\Attribute(\Attribute::TARGET_CLASS)] +final class ComponentUiAllowedInGroups extends Constraint +{ + public string $uiMessage = 'The UI `{{ ui }}` is not allowed for `{{ iri }}` in the component group `{{ reference }}`.'; + public string $stylesMessage = 'The styles `{{ styles }}` are not allowed for `{{ iri }}` in the component group `{{ reference }}`.'; + + public function getTargets(): string + { + return self::CLASS_CONSTRAINT; + } +} diff --git a/src/Validator/Constraints/ComponentUiAllowedInGroupsValidator.php b/src/Validator/Constraints/ComponentUiAllowedInGroupsValidator.php new file mode 100644 index 000000000..db61f347b --- /dev/null +++ b/src/Validator/Constraints/ComponentUiAllowedInGroupsValidator.php @@ -0,0 +1,99 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Silverback\ApiComponentsBundle\Validator\Constraints; + +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\IriConverterInterface; +use ApiPlatform\Metadata\UrlGeneratorInterface; +use Doctrine\ORM\EntityManagerInterface; +use Doctrine\Persistence\ManagerRegistry; +use Silverback\ApiComponentsBundle\AttributeReader\PublishableAttributeReader; +use Silverback\ApiComponentsBundle\Entity\Core\AbstractComponent; +use Silverback\ApiComponentsBundle\Repository\Core\ComponentGroupRepository; +use Silverback\ApiComponentsBundle\Utility\AllowedComponentUi; +use Symfony\Component\Validator\Constraint; +use Symfony\Component\Validator\ConstraintValidator; + +final class ComponentUiAllowedInGroupsValidator extends ConstraintValidator +{ + public function __construct( + private readonly ManagerRegistry $registry, + private readonly ComponentGroupRepository $componentGroupRepository, + private readonly PublishableAttributeReader $publishableAttributeReader, + private readonly IriConverterInterface $iriConverter, + ) { + } + + /** + * @param ComponentUiAllowedInGroups $constraint + */ + public function validate(mixed $component, Constraint $constraint): void + { + if (!$component instanceof AbstractComponent) { + return; + } + + $manager = $this->registry->getManagerForClass($component::class); + if (!$manager instanceof EntityManagerInterface) { + return; + } + + $placed = $this->publishedComponent($manager, $component) ?? $component; + $original = $manager->getUnitOfWork()->getOriginalEntityData($component); + if (!$original) { + if ($placed === $component) { + return; + } + $original = ['uiComponent' => $placed->uiComponent, 'uiClassNames' => $placed->uiClassNames]; + } + + $uiChanged = $original['uiComponent'] !== $component->uiComponent; + $stylesChanged = $original['uiClassNames'] !== $component->uiClassNames; + if (!$uiChanged && !$stylesChanged) { + return; + } + + $iri = (string) $this->iriConverter->getIriFromResource($component::class, UrlGeneratorInterface::ABS_PATH, (new GetCollection())->withClass($component::class)); + foreach ($this->componentGroupRepository->findRestrictingUiOf($placed) as $group) { + if ($uiChanged && !AllowedComponentUi::allowsUiComponent($group->allowedComponentUi, $iri, $component->uiComponent)) { + $this->context->buildViolation($constraint->uiMessage) + ->atPath('uiComponent') + ->setParameter('{{ ui }}', AllowedComponentUi::describeUiComponent($component->uiComponent)) + ->setParameter('{{ iri }}', $iri) + ->setParameter('{{ reference }}', (string) $group->reference) + ->addViolation(); + } + + $disallowedStyles = $stylesChanged ? AllowedComponentUi::disallowedStyles($group->allowedComponentUi, $iri, $component->uiClassNames) : []; + if ($disallowedStyles) { + $this->context->buildViolation($constraint->stylesMessage) + ->atPath('uiClassNames') + ->setParameter('{{ styles }}', implode(', ', $disallowedStyles)) + ->setParameter('{{ iri }}', $iri) + ->setParameter('{{ reference }}', (string) $group->reference) + ->addViolation(); + } + } + } + + private function publishedComponent(EntityManagerInterface $manager, AbstractComponent $component): ?AbstractComponent + { + if (!$this->publishableAttributeReader->isConfigured($component)) { + return null; + } + + $associationName = $this->publishableAttributeReader->getConfiguration($component)->associationName; + $published = $manager->getClassMetadata($component::class)->getFieldValue($component, $associationName); + + return $published instanceof AbstractComponent ? $published : null; + } +} diff --git a/tests/Entity/Core/ComponentGroupTest.php b/tests/Entity/Core/ComponentGroupTest.php index f07d44b65..322cb0590 100644 --- a/tests/Entity/Core/ComponentGroupTest.php +++ b/tests/Entity/Core/ComponentGroupTest.php @@ -53,4 +53,22 @@ public function test_set_allowed_components_null_clears_array(): void self::assertNull($group->allowedComponents); } + + public function test_set_allowed_component_ui_stores_the_rules(): void + { + $group = new ComponentGroup(); + $rules = ['/component/images' => ['ui' => [null, 'CwaHero'], 'styles' => ['style:large']]]; + + self::assertSame($group, $group->setAllowedComponentUi($rules)); + self::assertSame($rules, $group->allowedComponentUi); + } + + public function test_set_allowed_component_ui_stores_empty_rules_as_null(): void + { + $group = new ComponentGroup(); + $group->setAllowedComponentUi(['/component/images' => ['ui' => ['CwaHero']]]); + $group->setAllowedComponentUi([]); + + self::assertNull($group->allowedComponentUi); + } } diff --git a/tests/Fixture/CwaFixtureBuilderTest.php b/tests/Fixture/CwaFixtureBuilderTest.php index 33da558c0..1eed9b257 100644 --- a/tests/Fixture/CwaFixtureBuilderTest.php +++ b/tests/Fixture/CwaFixtureBuilderTest.php @@ -11,7 +11,9 @@ namespace Silverback\ApiComponentsBundle\Tests\Fixture; +use ApiPlatform\Metadata\GetCollection; use ApiPlatform\Metadata\IriConverterInterface; +use ApiPlatform\Metadata\UrlGeneratorInterface; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Mapping\ClassMetadata as OrmClassMetadata; use Doctrine\ORM\UnitOfWork; @@ -2440,6 +2442,39 @@ public function test_a_group_takes_its_maximum_number_of_components_from_every_o $this->assertSame(['footer' => null, 'items' => 3, 'nav' => 1, 'primary' => 2], $limits); } + public function test_a_group_takes_its_allowed_component_ui_by_collection_iri_from_every_owner_kind(): void + { + $persisted = []; + $em = $this->collectingEm($persisted); + $iriConverter = $this->createStub(IriConverterInterface::class); + $iriConverter->method('getIriFromResource')->willReturnCallback( + static fn ($resource, $referenceType = UrlGeneratorInterface::ABS_PATH, $operation = null) => \is_string($resource) + ? (UrlGeneratorInterface::ABS_PATH === $referenceType && $operation instanceof GetCollection && $operation->getClass() === $resource ? '/component/' . strtolower((new \ReflectionClass($resource))->getShortName()) : '/wrong') + : '/_/owners/' . spl_object_id($resource) + ); + + $builder = $this->makeBuilder($em, iriConverter: $iriConverter); + $builder->layout('main', 'Primary')->group('nav', allowUi: [\stdClass::class => ['ui' => [null, 'CwaHero']]]); + $builder->page('home', 'Primary', layout: 'main', route: '/')->group('primary', allowUi: [\stdClass::class => ['styles' => ['style:large']], \ArrayObject::class => ['ui' => ['CwaList']]]); + $builder->component(new class extends AbstractComponent {})->group('items', allowUi: [\ArrayObject::class => ['ui' => ['CwaGrid'], 'styles' => ['style:dark']]]); + $builder->layout('other', 'Primary')->group('footer'); + $builder->flush(); + + $rules = []; + foreach ($persisted as $entity) { + if ($entity instanceof ComponentGroup) { + $rules[strstr((string) $entity->reference, '_', true)] = $entity->allowedComponentUi; + } + } + ksort($rules); + $this->assertSame([ + 'footer' => null, + 'items' => ['/component/arrayobject' => ['ui' => ['CwaGrid'], 'styles' => ['style:dark']]], + 'nav' => ['/component/stdclass' => ['ui' => [null, 'CwaHero']]], + 'primary' => ['/component/stdclass' => ['styles' => ['style:large']], '/component/arrayobject' => ['ui' => ['CwaList']]], + ], $rules); + } + public function test_page_live_at_is_set_on_an_explicit_route(): void { $persisted = []; diff --git a/tests/Fixture/Generator/Plan/GroupPlannerTest.php b/tests/Fixture/Generator/Plan/GroupPlannerTest.php index 95c09b1ef..a266b3d01 100644 --- a/tests/Fixture/Generator/Plan/GroupPlannerTest.php +++ b/tests/Fixture/Generator/Plan/GroupPlannerTest.php @@ -122,6 +122,33 @@ public function test_a_maximum_number_of_components_is_written_after_the_allowed self::assertSame([], $this->report->all()); } + public function test_the_allowed_component_ui_is_written_after_the_maximum_keyed_by_imported_component_classes(): void + { + $group = $this->group('top_/_/layouts/main', '/_/layouts/main'); + $group->maxComponents = 1; + $group->allowedComponentUi = [ + '/component/dummy_components' => ['ui' => [null, 'CwaHero'], 'styles' => ['style:large']], + '/component/abstract_components' => ['ui' => ['CwaLost']], + ]; + + $plan = $this->plan($group, $this->layout('main', 'CwaLayoutPrimary')); + + self::assertSame(["'top'", 'max: 1', "allowUi: [DummyComponent::class => ['ui' => [null, 'CwaHero'], 'styles' => ['style:large']]]"], $plan?->arguments); + self::assertContains('use ' . DummyComponent::class . ';', $this->imports->lines()); + self::assertSame(['Allowed component UI for "/component/abstract_components" on the component group "top_/_/layouts/main" does not match a component class.'], $this->report->all()); + } + + public function test_an_allowed_component_ui_whose_keys_match_no_component_class_is_left_out(): void + { + $group = $this->group('top_/_/layouts/main', '/_/layouts/main'); + $group->allowedComponentUi = ['/component/pages' => ['ui' => ['CwaLost']]]; + + $plan = $this->plan($group, $this->layout('main', 'CwaLayoutPrimary')); + + self::assertSame(["'top'"], $plan?->arguments); + self::assertCount(1, $this->report->all()); + } + public function test_a_component_class_without_a_collection_iri_matches_nothing(): void { $iriConverter = $this->createStub(IriConverterInterface::class); diff --git a/tests/Functional/Component/ComponentGroupAllowedComponentUiTest.php b/tests/Functional/Component/ComponentGroupAllowedComponentUiTest.php new file mode 100644 index 000000000..2ca0b7b18 --- /dev/null +++ b/tests/Functional/Component/ComponentGroupAllowedComponentUiTest.php @@ -0,0 +1,488 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Silverback\ApiComponentsBundle\Tests\Functional\Component; + +use PHPUnit\Framework\Attributes\DataProvider; +use Silverback\ApiComponentsBundle\Entity\Core\ComponentGroup; +use Silverback\ApiComponentsBundle\Entity\Core\ComponentPosition; +use Silverback\ApiComponentsBundle\Tests\Functional\FunctionalTestCase; +use Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity\DummyPublishableComponent; +use Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity\PageDataWithComponent; +use Silverback\ApiComponentsBundle\Tests\Functional\Trait\AuthenticationTrait; + +final class ComponentGroupAllowedComponentUiTest extends FunctionalTestCase +{ + use AuthenticationTrait; + use ComponentSiteTrait; + + private const string DUMMY = '/component/dummy_components'; + + private const array HERO_ONLY = [self::DUMMY => ['ui' => ['CwaComponentHero']]]; + + private const array LARGE_ONLY = [self::DUMMY => ['styles' => ['style:large']]]; + + public function test_a_component_group_stores_the_allowed_component_ui_and_returns_it(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $allowed = [self::DUMMY => ['ui' => [null, 'CwaComponentHero'], 'styles' => ['style:large']]]; + + self::requestJsonLd($client, 'POST', '/_/component_groups', ['reference' => 'hero', 'location' => 'top', 'allowedComponentUi' => $allowed]); + self::assertResponseStatusCodeSame(201); + self::requestJsonLd($client, 'GET', (string) self::lastJson()['@id']); + + self::assertResponseStatusCodeSame(200); + self::assertJsonNodeSame('allowedComponentUi', $allowed); + } + + public function test_a_component_group_with_no_allowed_component_ui_has_a_null_one(): void + { + $client = static::createClient(); + $group = self::createGroupWithComponentIris(0); + + self::requestJsonLd($client, 'GET', $group['group']); + + self::assertResponseStatusCodeSame(200); + self::assertNull(self::lastJson()['allowedComponentUi'] ?? null); + } + + public function test_an_empty_allowed_component_ui_is_stored_as_null(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + self::setAllowedComponentUi($group['group'], self::HERO_ONLY); + + self::requestJsonLd($client, 'PATCH', $group['group'], '{"allowedComponentUi": {}}'); + + self::assertResponseStatusCodeSame(200); + $stored = self::findByIri($group['group']); + self::assertInstanceOf(ComponentGroup::class, $stored); + self::assertNull($stored->allowedComponentUi); + } + + #[DataProvider('malformedAllowedComponentUi')] + public function test_a_malformed_allowed_component_ui_is_refused(string $allowedComponentUi): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + + self::requestJsonLd($client, 'PATCH', $group['group'], \sprintf('{"allowedComponentUi": %s}', $allowedComponentUi)); + + self::assertResponseStatusCodeSame(422); + self::assertJsonNodeSame('violations[0].propertyPath', 'allowedComponentUi'); + } + + /** + * @return iterable + */ + public static function malformedAllowedComponentUi(): iterable + { + yield 'a list instead of an object' => ['[{"ui": ["X"]}]']; + yield 'a key that is not an IRI' => ['{"dummy": {"ui": ["X"]}}']; + yield 'a key that is the class name of a component' => ['{"Silverback\\\\ApiComponentsBundle\\\\Tests\\\\Functional\\\\TestBundle\\\\Entity\\\\DummyComponent": {"ui": ["X"]}}']; + yield 'a key that is the collection IRI of a resource that is not a component' => ['{"/_/pages": {"ui": ["X"]}}']; + yield 'a key that is an item IRI of a component' => ['{"/component/dummy_components/abc": {"ui": ["X"]}}']; + yield 'a value that is a string' => ['{"/component/dummy_components": "X"}']; + yield 'a value that is null' => ['{"/component/dummy_components": null}']; + yield 'a value that is a list' => ['{"/component/dummy_components": ["X"]}']; + yield 'an empty value' => ['{"/component/dummy_components": {}}']; + yield 'a value with another key' => ['{"/component/dummy_components": {"ui": ["X"], "other": ["Y"]}}']; + yield 'ui that is a string' => ['{"/component/dummy_components": {"ui": "X"}}']; + yield 'ui that is an object' => ['{"/component/dummy_components": {"ui": {"a": "X"}}}']; + yield 'ui that holds a number' => ['{"/component/dummy_components": {"ui": [1]}}']; + yield 'ui that holds a list' => ['{"/component/dummy_components": {"ui": [["X"]]}}']; + yield 'an empty ui' => ['{"/component/dummy_components": {"ui": []}}']; + yield 'styles that is a string' => ['{"/component/dummy_components": {"styles": "style:large"}}']; + yield 'styles that is an object' => ['{"/component/dummy_components": {"styles": {"a": "style:large"}}}']; + yield 'styles that holds a null' => ['{"/component/dummy_components": {"styles": [null]}}']; + yield 'styles that holds a number' => ['{"/component/dummy_components": {"styles": [1]}}']; + yield 'empty styles' => ['{"/component/dummy_components": {"styles": []}}']; + } + + public function test_a_component_whose_ui_is_not_allowed_cannot_be_placed_in_the_group(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + self::setAllowedComponentUi($group['group'], self::HERO_ONLY); + $component = self::createComponentWithUi('CwaComponentBanner'); + + self::requestJsonLd($client, 'POST', '/_/component_positions', ['componentGroup' => $group['group'], 'component' => $component]); + + self::assertResponseStatusCodeSame(422); + self::assertJsonNodeSame('violations[0].propertyPath', 'component'); + self::assertJsonNodeSame('violations[0].message', 'The UI `CwaComponentBanner` is not allowed for `/component/dummy_components` in the component group `collection`.'); + self::assertSame(0, self::countEntities(ComponentPosition::class)); + } + + public function test_a_component_whose_ui_is_allowed_can_be_placed_in_the_group(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + self::setAllowedComponentUi($group['group'], self::HERO_ONLY); + $component = self::createComponentWithUi('CwaComponentHero'); + + self::requestJsonLd($client, 'POST', '/_/component_positions', ['componentGroup' => $group['group'], 'component' => $component]); + + self::assertResponseStatusCodeSame(201); + } + + public function test_a_position_cannot_be_given_a_component_whose_ui_is_not_allowed(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(1); + self::setAllowedComponentUi($group['group'], [self::DUMMY => ['ui' => [null]]]); + $component = self::createComponentWithUi('CwaComponentBanner'); + + self::requestJsonLd($client, 'PATCH', $group['positions'][0], ['component' => $component]); + + self::assertResponseStatusCodeSame(422); + self::assertJsonNodeSame('violations[0].propertyPath', 'component'); + } + + public function test_a_position_holding_a_component_whose_ui_is_not_allowed_cannot_be_moved_into_the_group(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + self::setAllowedComponentUi($group['group'], self::HERO_ONLY); + $other = self::createGroupWithComponentIris(1, 'other_collection'); + + self::requestJsonLd($client, 'PATCH', $other['positions'][0], ['componentGroup' => $group['group']]); + + self::assertResponseStatusCodeSame(422); + self::assertJsonNodeSame('violations[0].propertyPath', 'component'); + self::assertJsonNodeSame('violations[0].message', 'The UI `null` is not allowed for `/component/dummy_components` in the component group `collection`.'); + } + + public function test_a_component_whose_ui_is_not_allowed_cannot_be_created_straight_into_the_group(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + self::setAllowedComponentUi($group['group'], self::HERO_ONLY); + + self::requestJsonLd($client, 'POST', self::DUMMY, ['uiComponent' => 'CwaComponentBanner', 'componentPositions' => [['componentGroup' => $group['group']]]]); + + self::assertResponseStatusCodeSame(422); + self::assertJsonNodeSame('violations[0].propertyPath', 'componentPositions[0].component'); + self::assertSame(0, self::countEntities(ComponentPosition::class)); + } + + public function test_a_component_whose_ui_is_allowed_can_be_created_straight_into_the_group(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + self::setAllowedComponentUi($group['group'], self::HERO_ONLY); + + self::requestJsonLd($client, 'POST', self::DUMMY, ['uiComponent' => 'CwaComponentHero', 'componentPositions' => [['componentGroup' => $group['group']]]]); + + self::assertResponseStatusCodeSame(201); + self::assertSame(1, self::countEntities(ComponentPosition::class)); + } + + public function test_a_component_with_a_style_that_is_not_allowed_cannot_be_placed_in_the_group(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + self::setAllowedComponentUi($group['group'], self::LARGE_ONLY); + $component = self::createComponentWithUi(null, ['style:large', 'style:dark', 'style:wide']); + + self::requestJsonLd($client, 'POST', '/_/component_positions', ['componentGroup' => $group['group'], 'component' => $component]); + + self::assertResponseStatusCodeSame(422); + self::assertJsonNodeSame('violations[0].propertyPath', 'component'); + self::assertJsonNodeSame('violations[0].message', 'The styles `style:dark, style:wide` are not allowed for `/component/dummy_components` in the component group `collection`.'); + } + + public function test_a_component_with_only_allowed_styles_can_be_placed_in_the_group(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + self::setAllowedComponentUi($group['group'], self::LARGE_ONLY); + $component = self::createComponentWithUi('AnyUi', ['style:large']); + + self::requestJsonLd($client, 'POST', '/_/component_positions', ['componentGroup' => $group['group'], 'component' => $component]); + + self::assertResponseStatusCodeSame(201); + } + + public function test_a_component_with_no_styles_can_be_placed_in_a_group_that_restricts_styles(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + self::setAllowedComponentUi($group['group'], self::LARGE_ONLY); + $component = self::createComponentWithUi(null); + + self::requestJsonLd($client, 'POST', '/_/component_positions', ['componentGroup' => $group['group'], 'component' => $component]); + + self::assertResponseStatusCodeSame(201); + } + + public function test_a_group_that_lists_no_ui_allows_any_ui(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + self::setAllowedComponentUi($group['group'], self::LARGE_ONLY); + $component = self::createComponentWithUi('CwaComponentBanner'); + + self::requestJsonLd($client, 'POST', '/_/component_positions', ['componentGroup' => $group['group'], 'component' => $component]); + + self::assertResponseStatusCodeSame(201); + } + + public function test_a_group_that_lists_no_styles_allows_any_styles(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + self::setAllowedComponentUi($group['group'], self::HERO_ONLY); + $component = self::createComponentWithUi('CwaComponentHero', ['style:anything']); + + self::requestJsonLd($client, 'POST', '/_/component_positions', ['componentGroup' => $group['group'], 'component' => $component]); + + self::assertResponseStatusCodeSame(201); + } + + public function test_a_component_type_the_group_does_not_list_is_unrestricted(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + self::setAllowedComponentUi($group['group'], ['/component/dummy_publishable_components' => ['ui' => ['CwaComponentHero'], 'styles' => ['style:large']]]); + $component = self::createComponentWithUi('CwaComponentBanner', ['style:dark']); + + self::requestJsonLd($client, 'POST', '/_/component_positions', ['componentGroup' => $group['group'], 'component' => $component]); + + self::assertResponseStatusCodeSame(201); + } + + public function test_the_primary_ui_is_refused_when_null_is_not_listed(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + self::setAllowedComponentUi($group['group'], self::HERO_ONLY); + $component = self::createComponentWithUi(null); + + self::requestJsonLd($client, 'POST', '/_/component_positions', ['componentGroup' => $group['group'], 'component' => $component]); + + self::assertResponseStatusCodeSame(422); + self::assertJsonNodeSame('violations[0].propertyPath', 'component'); + } + + public function test_the_primary_ui_is_allowed_when_null_is_listed(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + self::setAllowedComponentUi($group['group'], [self::DUMMY => ['ui' => [null, 'CwaComponentHero']]]); + $component = self::createComponentWithUi(null); + + self::requestJsonLd($client, 'POST', '/_/component_positions', ['componentGroup' => $group['group'], 'component' => $component]); + + self::assertResponseStatusCodeSame(201); + } + + public function test_the_fallback_of_a_dynamic_position_must_have_an_allowed_ui(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + self::setAllowedComponentUi($group['group'], self::HERO_ONLY); + $component = self::createComponentWithUi('CwaComponentBanner'); + + self::requestJsonLd($client, 'POST', '/_/component_positions', [ + 'componentGroup' => $group['group'], + 'component' => $component, + 'pageDataProperty' => 'component', + 'pageDataClass' => PageDataWithComponent::class, + ]); + + self::assertResponseStatusCodeSame(422); + self::assertJsonNodeSame('violations[0].propertyPath', 'component'); + } + + public function test_changing_a_components_ui_to_one_its_group_does_not_allow_is_refused(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(1); + self::setComponentUi($group['components'][0], 'CwaComponentHero'); + self::setAllowedComponentUi($group['group'], self::HERO_ONLY); + + self::requestJsonLd($client, 'PATCH', $group['components'][0], ['uiComponent' => 'CwaComponentBanner']); + + self::assertResponseStatusCodeSame(422); + self::assertJsonNodeSame('violations[0].propertyPath', 'uiComponent'); + self::assertJsonNodeSame('violations[0].message', 'The UI `CwaComponentBanner` is not allowed for `/component/dummy_components` in the component group `collection`.'); + } + + public function test_changing_a_components_styles_to_ones_its_group_does_not_allow_is_refused(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(1); + self::setAllowedComponentUi($group['group'], self::LARGE_ONLY); + + self::requestJsonLd($client, 'PATCH', $group['components'][0], ['uiClassNames' => ['style:large', 'style:dark']]); + + self::assertResponseStatusCodeSame(422); + self::assertJsonNodeSame('violations[0].propertyPath', 'uiClassNames'); + self::assertJsonNodeSame('violations[0].message', 'The styles `style:dark` are not allowed for `/component/dummy_components` in the component group `collection`.'); + } + + public function test_changing_a_components_ui_to_one_its_group_allows_is_accepted(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(1); + self::setAllowedComponentUi($group['group'], [self::DUMMY => ['ui' => [null, 'CwaComponentHero'], 'styles' => ['style:large']]]); + + self::requestJsonLd($client, 'PATCH', $group['components'][0], ['uiComponent' => 'CwaComponentHero', 'uiClassNames' => ['style:large']]); + + self::assertResponseStatusCodeSame(200); + self::assertJsonNodeSame('uiComponent', 'CwaComponentHero'); + } + + public function test_a_component_in_two_groups_must_have_a_ui_both_allow(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(1); + self::setAllowedComponentUi($group['group'], [self::DUMMY => ['ui' => [null, 'CwaComponentHero']]]); + $other = self::createGroupWithComponentIris(0, 'other_collection'); + self::setAllowedComponentUi($other['group'], [self::DUMMY => ['ui' => [null, 'CwaComponentBanner']]]); + self::addPositionTo($other['group'], $group['components'][0], 0); + + self::requestJsonLd($client, 'PATCH', $group['components'][0], ['uiComponent' => 'CwaComponentHero']); + + self::assertResponseStatusCodeSame(422); + self::assertJsonNodeSame('violations[0].propertyPath', 'uiComponent'); + self::assertJsonNodeSame('violations[0].message', 'The UI `CwaComponentHero` is not allowed for `/component/dummy_components` in the component group `other_collection`.'); + } + + public function test_a_new_draft_is_checked_against_its_published_components_groups(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + $published = self::addPublishedComponentToGroup($group['group']); + self::setAllowedComponentUi($group['group'], ['/component/dummy_publishable_components' => ['ui' => [null]]]); + + self::requestJsonLd($client, 'PATCH', $published, ['uiComponent' => 'CwaComponentBanner']); + + self::assertResponseStatusCodeSame(422); + self::assertJsonNodeSame('violations[0].propertyPath', 'uiComponent'); + self::assertSame(1, self::countEntities(DummyPublishableComponent::class)); + } + + public function test_an_existing_draft_is_checked_against_its_published_components_groups(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(0); + $pair = self::addPublishedComponentWithDraftTo($group['group']); + self::setAllowedComponentUi($group['group'], ['/component/dummy_publishable_components' => ['ui' => [null]]]); + + self::requestJsonLd($client, 'PATCH', $pair['draft'], ['uiComponent' => 'CwaComponentBanner']); + + self::assertResponseStatusCodeSame(422); + self::assertJsonNodeSame('violations[0].propertyPath', 'uiComponent'); + } + + public function test_a_restriction_its_groups_components_already_break_can_be_saved(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(1); + self::setComponentUi($group['components'][0], 'CwaComponentBanner', ['style:dark']); + + self::requestJsonLd($client, 'PATCH', $group['group'], ['allowedComponentUi' => [self::DUMMY => ['ui' => ['CwaComponentHero'], 'styles' => ['style:large']]]]); + + self::assertResponseStatusCodeSame(200); + self::assertJsonNodeCount('componentPositions', 1); + } + + public function test_a_component_that_breaks_its_groups_restriction_is_still_listed(): void + { + $client = static::createClient(); + $group = self::createGroupWithComponentIris(1); + self::setComponentUi($group['components'][0], 'CwaComponentBanner'); + self::setAllowedComponentUi($group['group'], self::HERO_ONLY); + + self::requestJsonLd($client, 'GET', $group['group']); + + self::assertResponseStatusCodeSame(200); + self::assertJsonNodeSame('componentPositions', $group['positions']); + } + + public function test_a_component_that_breaks_its_groups_restriction_can_be_saved_with_its_ui_unchanged(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(1); + self::setComponentUi($group['components'][0], 'CwaComponentBanner', ['style:dark']); + self::setAllowedComponentUi($group['group'], [self::DUMMY => ['ui' => ['CwaComponentHero'], 'styles' => ['style:large']]]); + + self::requestJsonLd($client, 'PATCH', $group['components'][0], ['uiComponent' => 'CwaComponentBanner', 'uiClassNames' => ['style:dark']]); + + self::assertResponseStatusCodeSame(200); + } + + public function test_a_component_that_breaks_its_groups_ui_restriction_can_change_only_its_styles(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(1); + self::setComponentUi($group['components'][0], 'CwaComponentBanner', ['style:dark']); + self::setAllowedComponentUi($group['group'], [self::DUMMY => ['ui' => ['CwaComponentHero'], 'styles' => ['style:large']]]); + + self::requestJsonLd($client, 'PATCH', $group['components'][0], ['uiClassNames' => ['style:large']]); + + self::assertResponseStatusCodeSame(200); + } + + public function test_the_position_of_a_component_that_breaks_its_groups_restriction_can_be_re_sorted(): void + { + $client = static::createClient(); + self::loginAsAdmin($client); + $group = self::createGroupWithComponentIris(2); + self::setComponentUi($group['components'][0], 'CwaComponentBanner'); + self::setAllowedComponentUi($group['group'], self::HERO_ONLY); + + self::requestJsonLd($client, 'PATCH', $group['positions'][0], ['after' => $group['positions'][1]]); + + self::assertResponseStatusCodeSame(200); + self::assertSortValues([$group['positions'][1] => 1, $group['positions'][0] => 2]); + } + + private static function addPublishedComponentToGroup(string $groupIri): string + { + $group = self::findByIri($groupIri); + self::assertInstanceOf(ComponentGroup::class, $group); + $published = new DummyPublishableComponent(); + $published->setPublishedAt(new \DateTime('-1 day')); + self::persistAndFlush($published, self::newComponentPosition($group, $published, 0)); + + return self::iriOf($published); + } +} diff --git a/tests/Functional/Component/ComponentMoveTest.php b/tests/Functional/Component/ComponentMoveTest.php index 6c496c91c..b90d84c28 100644 --- a/tests/Functional/Component/ComponentMoveTest.php +++ b/tests/Functional/Component/ComponentMoveTest.php @@ -439,6 +439,19 @@ public function test_an_explicit_allow_only_component_cannot_be_moved_into_a_gro self::assertJsonNodeMatches('violations[0].message', '/must be specifically allowed within the collection other_collection/'); } + public function test_a_component_whose_ui_the_target_group_does_not_allow_cannot_be_moved_into_it(): void + { + $client = self::adminClient(); + $names = self::createGroupWithPositions('A0'); + $other = self::createGroupWithPositions('X0', 'other_collection'); + self::setAllowedComponentUi($other['group'], ['/component/dummy_components' => ['ui' => ['CwaComponentHero']]]); + + self::move($client, self::componentOf($names['A']), ['componentPosition' => $names['A']], ['componentGroup' => $other['group']]); + + self::assertViolation('to.componentGroup', 'The UI `null` is not allowed for `/component/dummy_components` in the component group `other_collection`.'); + self::assertGroupHoldsPositions($names['group'], 'A0', $names); + } + public function test_a_component_cannot_be_moved_into_a_group_inside_itself(): void { $client = self::adminClient(); diff --git a/tests/Functional/Component/ComponentSiteTrait.php b/tests/Functional/Component/ComponentSiteTrait.php index 0fec40c93..2db2be5e9 100644 --- a/tests/Functional/Component/ComponentSiteTrait.php +++ b/tests/Functional/Component/ComponentSiteTrait.php @@ -154,6 +154,42 @@ protected static function setAllowedComponent(string $groupIri, string $allowedC }); } + /** + * @param array, styles?: list}> $allowedComponentUi + */ + protected static function setAllowedComponentUi(string $groupIri, array $allowedComponentUi): void + { + static::updateResource($groupIri, static function (object $group) use ($allowedComponentUi): void { + \assert($group instanceof ComponentGroup); + $group->allowedComponentUi = $allowedComponentUi; + }); + } + + /** + * @param list|null $uiClassNames + */ + protected static function setComponentUi(string $componentIri, ?string $uiComponent, ?array $uiClassNames = null): void + { + static::updateResource($componentIri, static function (object $component) use ($uiComponent, $uiClassNames): void { + \assert($component instanceof AbstractComponent); + $component->uiComponent = $uiComponent; + $component->uiClassNames = $uiClassNames; + }); + } + + /** + * @param list|null $uiClassNames + */ + protected static function createComponentWithUi(?string $uiComponent, ?array $uiClassNames = null): string + { + $component = new DummyComponent(); + $component->uiComponent = $uiComponent; + $component->uiClassNames = $uiClassNames; + static::persistAndFlush($component); + + return static::iriOf($component); + } + protected static function addPositionTo(string $groupIri, AbstractComponent|string|null $component, int $sortValue, ?string $pageDataProperty = null): string { $existing = \is_string($component) ? static::findByIri($component) : null; diff --git a/tests/Functional/Fixture/FixtureScenarioTrait.php b/tests/Functional/Fixture/FixtureScenarioTrait.php index 945cbaa3a..d3acd5456 100644 --- a/tests/Functional/Fixture/FixtureScenarioTrait.php +++ b/tests/Functional/Fixture/FixtureScenarioTrait.php @@ -143,6 +143,15 @@ protected function siteHasGroupsWithAndWithoutAMaximum(int $max): void }); } + protected function siteHasGroupsWithAndWithoutAllowedComponentUi(): void + { + $cwa = $this->siteBuilder(); + $cwa->layout('main', 'Primary')->group('top', allowUi: [DummyComponent::class => ['ui' => [null, 'CwaComponentHero'], 'styles' => ['style:large']]])->add(new DummyComponent()); + $cwa->page('home', 'Primary', layout: 'main', route: '/', routeName: 'home', configure: static function (PageBuilder $page): void { + $page->group('primary')->add(new DummyComponent()); + }); + } + protected function siteHasAPublishedComponentWithADraft(string $reference, string $draftReference): void { $cwa = $this->siteBuilder(); @@ -963,6 +972,24 @@ protected function assertGroupOfTheLayoutHoldsAtMost(string $group, string $layo self::assertSame($max, self::findOwnedGroup($owner?->getComponentGroups() ?? [], $group)->maxComponents); } + /** + * @param array|null $expected + */ + protected function assertGroupOfTheLayoutAllowsComponentUi(string $group, string $layout, ?array $expected): void + { + $owner = self::getEntityManager()->getRepository(Layout::class)->findOneBy(['reference' => $layout]); + self::assertSame($expected, self::findOwnedGroup($owner?->getComponentGroups() ?? [], $group)->allowedComponentUi); + } + + /** + * @param array|null $expected + */ + protected function assertGroupOfThePageAllowsComponentUi(string $group, string $page, ?array $expected): void + { + $owner = self::getEntityManager()->getRepository(Page::class)->findOneBy(['reference' => $page]); + self::assertSame($expected, self::findOwnedGroup($owner?->getComponentGroups() ?? [], $group)->allowedComponentUi); + } + protected function assertGroupOfThePageHasNoMaximum(string $group, string $page): void { $owner = self::getEntityManager()->getRepository(Page::class)->findOneBy(['reference' => $page]); diff --git a/tests/Functional/Fixture/GenerateFixturesRoundTripTest.php b/tests/Functional/Fixture/GenerateFixturesRoundTripTest.php index 41070e712..07ec3ac00 100644 --- a/tests/Functional/Fixture/GenerateFixturesRoundTripTest.php +++ b/tests/Functional/Fixture/GenerateFixturesRoundTripTest.php @@ -42,6 +42,17 @@ public function test_a_group_keeps_its_maximum_number_of_components(): void $this->assertCommandOutputNotContains('could not be reproduced'); } + public function test_a_group_keeps_its_allowed_component_ui(): void + { + $this->siteHasGroupsWithAndWithoutAllowedComponentUi(); + $this->generateSiteAndReload(); + + $this->assertGroupOfTheLayoutAllowsComponentUi('top', 'main', ['/component/dummy_components' => ['ui' => [null, 'CwaComponentHero'], 'styles' => ['style:large']]]); + $this->assertGroupOfThePageAllowsComponentUi('primary', 'home', null); + $this->assertGeneratedFixturesContain("allowUi: [DummyComponent::class => ['ui' => [null, 'CwaComponentHero'], 'styles' => ['style:large']]]"); + $this->assertCommandOutputNotContains('could not be reproduced'); + } + public function test_published_components_stay_published_and_a_draft_stays_linked_to_its_published_component(): void { $this->siteHasAPublishedComponentWithADraft('live', 'live-draft'); diff --git a/tests/Functional/Maker/RenameComponentTest.php b/tests/Functional/Maker/RenameComponentTest.php index a47d6c4eb..4a3cb71ef 100644 --- a/tests/Functional/Maker/RenameComponentTest.php +++ b/tests/Functional/Maker/RenameComponentTest.php @@ -106,6 +106,32 @@ public function test_the_generated_migration_rewrites_allowed_components_and_the self::assertEveryComponentHasTheDiscriminator('dummycomponent'); } + public function test_the_generated_migration_renames_the_allowed_component_ui_key_and_reverts_it(): void + { + $group = self::newComponentGroup('collection'); + $group->setCreatedAt(new \DateTimeImmutable())->setModifiedAt(new \DateTime()); + $group->allowedComponentUi = ['/component/dummy_components' => ['ui' => [null, 'CwaHero'], 'styles' => ['style:large']]]; + self::persistAndFlush($group); + self::getEntityManager()->clear(); + + $failure = $this->generateRenameComponentMigration([ + 'old-name' => 'DummyComponent', + 'new-name' => 'RenamedComponent', + '--old-fqcn' => DummyComponent::class, + '--new-fqcn' => 'App\Entity\Component\RenamedComponent', + '--old-dtype' => 'dummycomponent', + '--new-dtype' => 'renamedcomponent', + '--new-iri' => '/component/renamed_components', + ]); + self::assertNull($failure, (string) $failure?->getMessage()); + + $this->generatedMigration()->migrate(self::connection(), 'up'); + self::assertAllowedComponentUi(['/component/renamed_components' => ['ui' => [null, 'CwaHero'], 'styles' => ['style:large']]]); + + $this->generatedMigration()->migrate(self::connection(), 'down'); + self::assertAllowedComponentUi(['/component/dummy_components' => ['ui' => [null, 'CwaHero'], 'styles' => ['style:large']]]); + } + public function test_the_console_command_asks_for_each_missing_value_and_only_the_iri_it_cannot_resolve(): void { $other = new DoctrineMigrationsFixture(); @@ -192,6 +218,16 @@ private static function assertEveryComponentGroupAllowsExactly(string $iri): voi } } + /** + * @param array $expected + */ + private static function assertAllowedComponentUi(array $expected): void + { + $rows = self::connection()->fetchFirstColumn(\sprintf('SELECT allowed_component_ui FROM %s', self::tableName(ComponentGroup::class))); + self::assertCount(1, $rows); + self::assertSame($expected, json_decode((string) $rows[0], true)); + } + private static function assertEveryComponentHasTheDiscriminator(string $dtype): void { $rows = self::connection()->fetchFirstColumn(\sprintf('SELECT dtype FROM %s', self::tableName(AbstractComponent::class))); diff --git a/tests/Functional/assets/schema/page.schema.json b/tests/Functional/assets/schema/page.schema.json index 034bd8b18..a69ad64eb 100644 --- a/tests/Functional/assets/schema/page.schema.json +++ b/tests/Functional/assets/schema/page.schema.json @@ -7,7 +7,7 @@ "description": "", "allOf": [ { - "$ref": "abstract_page_data.schema.json#definitions/AbstractPageData:jsonld" + "$ref": "abstract_page_data.schema.json#/definitions/AbstractPageData:jsonld" }, { "required": [ diff --git a/tests/Maker/RenameComponentMigrationTest.php b/tests/Maker/RenameComponentMigrationTest.php index bdccf7c6a..ef53ac83c 100644 --- a/tests/Maker/RenameComponentMigrationTest.php +++ b/tests/Maker/RenameComponentMigrationTest.php @@ -46,7 +46,7 @@ protected function setUp(): void { $this->connection = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'memory' => true]); $this->connection->executeStatement(\sprintf('CREATE TABLE %s (id VARCHAR(36) PRIMARY KEY, dtype VARCHAR(255) NOT NULL)', self::COMPONENT_TABLE)); - $this->connection->executeStatement(\sprintf('CREATE TABLE %s (id VARCHAR(36) PRIMARY KEY, allowed_components CLOB DEFAULT NULL)', self::GROUP_TABLE)); + $this->connection->executeStatement(\sprintf('CREATE TABLE %s (id VARCHAR(36) PRIMARY KEY, allowed_components CLOB DEFAULT NULL, allowed_component_ui CLOB DEFAULT NULL)', self::GROUP_TABLE)); } public function test_up_renames_the_discriminator_in_the_mapped_component_table(): void @@ -88,6 +88,54 @@ public function test_up_leaves_groups_without_the_old_iri_untouched(): void $this->assertSame($before, $this->connection->fetchOne(\sprintf('SELECT allowed_components FROM %s WHERE id = ?', self::GROUP_TABLE), ['g1'])); } + public function test_up_renames_the_old_iri_key_of_allowed_component_ui_keeping_its_rule_and_order(): void + { + $this->insertGroupUi('g1', ['/component/images' => ['ui' => ['CwaHero']], self::OLD_IRI => ['ui' => [null, 'CwaLead'], 'styles' => ['style:large']], '/component/navigation_links' => ['styles' => ['style:dark']]]); + + $this->runMigration('up'); + + $this->assertSame(['/component/images' => ['ui' => ['CwaHero']], self::NEW_IRI => ['ui' => [null, 'CwaLead'], 'styles' => ['style:large']], '/component/navigation_links' => ['styles' => ['style:dark']]], $this->allowedComponentUi('g1')); + } + + public function test_down_reverts_the_allowed_component_ui_key(): void + { + $this->insertGroupUi('g1', [self::NEW_IRI => ['ui' => ['CwaLead']]]); + + $this->runMigration('down'); + + $this->assertSame([self::OLD_IRI => ['ui' => ['CwaLead']]], $this->allowedComponentUi('g1')); + } + + public function test_up_leaves_allowed_component_ui_without_the_old_iri_untouched(): void + { + $this->insertGroupUi('g1', ['/component/navigation_links' => ['ui' => [self::OLD_IRI]]]); + $this->insertGroupUi('g2', null); + $before = $this->connection->fetchAllAssociative(\sprintf('SELECT id, allowed_component_ui FROM %s ORDER BY id', self::GROUP_TABLE)); + + $this->runMigration('up'); + + $this->assertSame($before, $this->connection->fetchAllAssociative(\sprintf('SELECT id, allowed_component_ui FROM %s ORDER BY id', self::GROUP_TABLE))); + } + + /** + * @param array|null $allowedComponentUi + */ + private function insertGroupUi(string $id, ?array $allowedComponentUi): void + { + $this->connection->insert(self::GROUP_TABLE, [ + 'id' => $id, + 'allowed_component_ui' => Type::getType('json')->convertToDatabaseValue($allowedComponentUi, $this->connection->getDatabasePlatform()), + ]); + } + + /** + * @return array + */ + private function allowedComponentUi(string $id): array + { + return json_decode((string) $this->connection->fetchOne(\sprintf('SELECT allowed_component_ui FROM %s WHERE id = ?', self::GROUP_TABLE), [$id]), true); + } + private function insertGroup(string $id, array $allowedComponents): void { $this->connection->insert(self::GROUP_TABLE, [ diff --git a/tests/Repository/ComponentGroupRepositoryTest.php b/tests/Repository/ComponentGroupRepositoryTest.php new file mode 100644 index 000000000..418efdea6 --- /dev/null +++ b/tests/Repository/ComponentGroupRepositoryTest.php @@ -0,0 +1,45 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Silverback\ApiComponentsBundle\Tests\Repository; + +use Silverback\ApiComponentsBundle\Entity\Core\ComponentGroup; +use Silverback\ApiComponentsBundle\Repository\Core\ComponentGroupRepository; +use Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity\DummyComponent; +use Silverback\ApiComponentsBundle\Tests\Helper\OrphanedResource\OrphanedResourceDatabaseTestCase; + +final class ComponentGroupRepositoryTest extends OrphanedResourceDatabaseTestCase +{ + public function test_the_groups_restricting_a_components_ui_are_those_holding_it_in_a_position_once_each_by_reference(): void + { + $component = new DummyComponent(); + $second = $this->restrictingGroup('b'); + $first = $this->restrictingGroup('a'); + $this->position($second, $component); + $this->position($second, $component); + $this->position($first, $component); + $this->position($this->group('unrestricted'), $component); + $this->position($this->restrictingGroup('another-component'), new DummyComponent()); + $owned = $this->restrictingGroup('owned'); + $component->addComponentGroup($owned); + $this->entityManager->flush(); + + self::assertSame([$first, $second], (new ComponentGroupRepository($this->registry))->findRestrictingUiOf($component)); + } + + private function restrictingGroup(string $reference): ComponentGroup + { + $group = $this->group($reference); + $group->allowedComponentUi = ['/component/dummy_components' => ['ui' => ['CwaHero']]]; + + return $group; + } +} diff --git a/tests/Utility/AllowedComponentUiTest.php b/tests/Utility/AllowedComponentUiTest.php new file mode 100644 index 000000000..06b3fee00 --- /dev/null +++ b/tests/Utility/AllowedComponentUiTest.php @@ -0,0 +1,78 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Silverback\ApiComponentsBundle\Tests\Utility; + +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\TestCase; +use Silverback\ApiComponentsBundle\Utility\AllowedComponentUi; + +final class AllowedComponentUiTest extends TestCase +{ + private const string IRI = '/component/images'; + + /** + * @param array|null $allowedComponentUi + */ + #[DataProvider('uiComponents')] + public function test_a_ui_component_is_allowed_only_when_listed_or_unrestricted(?array $allowedComponentUi, ?string $uiComponent, bool $allowed): void + { + self::assertSame($allowed, AllowedComponentUi::allowsUiComponent($allowedComponentUi, self::IRI, $uiComponent)); + } + + /** + * @return iterable|null, string|null, bool}> + */ + public static function uiComponents(): iterable + { + yield 'no restrictions at all' => [null, 'CwaHero', true]; + yield 'another component type restricted' => [['/component/other' => ['ui' => ['CwaOther']]], 'CwaHero', true]; + yield 'only styles restricted' => [[self::IRI => ['styles' => ['style:large']]], 'CwaHero', true]; + yield 'a listed ui' => [[self::IRI => ['ui' => ['CwaBanner', 'CwaHero']]], 'CwaHero', true]; + yield 'an unlisted ui' => [[self::IRI => ['ui' => ['CwaBanner']]], 'CwaHero', false]; + yield 'a ui differing only in case' => [[self::IRI => ['ui' => ['cwahero']]], 'CwaHero', false]; + yield 'the primary ui when null is listed' => [[self::IRI => ['ui' => [null, 'CwaHero']]], null, true]; + yield 'the primary ui when null is not listed' => [[self::IRI => ['ui' => ['CwaHero']]], null, false]; + yield 'an empty string when null is listed' => [[self::IRI => ['ui' => [null]]], '', false]; + } + + /** + * @param array|null $allowedComponentUi + * @param array|null $uiClassNames + * @param list $disallowed + */ + #[DataProvider('styles')] + public function test_the_disallowed_styles_are_those_the_rule_does_not_list(?array $allowedComponentUi, ?array $uiClassNames, array $disallowed): void + { + self::assertSame($disallowed, AllowedComponentUi::disallowedStyles($allowedComponentUi, self::IRI, $uiClassNames)); + } + + /** + * @return iterable|null, array|null, list}> + */ + public static function styles(): iterable + { + yield 'no restrictions at all' => [null, ['style:dark'], []]; + yield 'another component type restricted' => [['/component/other' => ['styles' => ['style:large']]], ['style:dark'], []]; + yield 'only ui restricted' => [[self::IRI => ['ui' => ['CwaHero']]], ['style:dark'], []]; + yield 'no styles' => [[self::IRI => ['styles' => ['style:large']]], null, []]; + yield 'an empty list of styles' => [[self::IRI => ['styles' => ['style:large']]], [], []]; + yield 'only listed styles' => [[self::IRI => ['styles' => ['style:large', 'style:dark']]], ['style:dark', 'style:large'], []]; + yield 'unlisted styles in order' => [[self::IRI => ['styles' => ['style:large']]], ['style:wide', 'style:large', 'style:dark'], ['style:wide', 'style:dark']]; + yield 'a style that is not a string' => [[self::IRI => ['styles' => ['style:large']]], [['nested' => 1], 2], ['{"nested":1}', '2']]; + } + + public function test_the_primary_ui_is_described_as_null(): void + { + self::assertSame('null', AllowedComponentUi::describeUiComponent(null)); + self::assertSame('CwaHero', AllowedComponentUi::describeUiComponent('CwaHero')); + } +} diff --git a/tests/Validator/Constraints/AllowedComponentUiValidatorTest.php b/tests/Validator/Constraints/AllowedComponentUiValidatorTest.php new file mode 100644 index 000000000..cbad6ace7 --- /dev/null +++ b/tests/Validator/Constraints/AllowedComponentUiValidatorTest.php @@ -0,0 +1,210 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Silverback\ApiComponentsBundle\Tests\Validator\Constraints; + +use ApiPlatform\Metadata\Exception\InvalidArgumentException; +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\IriConverterInterface; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface; +use ApiPlatform\Metadata\Resource\ResourceNameCollection; +use ApiPlatform\Metadata\UrlGeneratorInterface; +use PHPUnit\Framework\Attributes\DataProvider; +use Silverback\ApiComponentsBundle\Entity\Core\AbstractComponent; +use Silverback\ApiComponentsBundle\Entity\Core\Page; +use Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity\AbstractDummyAppComponent; +use Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity\DummyComponent; +use Silverback\ApiComponentsBundle\Validator\Constraints\AllowedComponentUi; +use Silverback\ApiComponentsBundle\Validator\Constraints\AllowedComponentUiValidator; +use Symfony\Component\Validator\ConstraintValidatorInterface; +use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; + +/** + * @extends ConstraintValidatorTestCase + */ +final class AllowedComponentUiValidatorTest extends ConstraintValidatorTestCase +{ + private const string DUMMY = '/component/dummy_components'; + + /** @var list */ + private array $iriCalls = []; + + private ?string $failingClass = null; + + protected function createValidator(): ConstraintValidatorInterface + { + $names = $this->createStub(ResourceNameCollectionFactoryInterface::class); + $names->method('create')->willReturn(new ResourceNameCollection([Page::class, AbstractComponent::class, AbstractDummyAppComponent::class, DummyComponent::class])); + $iriConverter = $this->createStub(IriConverterInterface::class); + $iriConverter->method('getIriFromResource')->willReturnCallback(function (object|string $resource, int $referenceType = UrlGeneratorInterface::ABS_PATH, ?Operation $operation = null): string { + \assert(\is_string($resource)); + $this->iriCalls[] = [$resource, $referenceType, $operation]; + if ($resource === $this->failingClass) { + throw new InvalidArgumentException('No collection operation.'); + } + + return [Page::class => '/_/pages', AbstractComponent::class => '/abstract_components', AbstractDummyAppComponent::class => '/component/abstract_dummy_app_components', DummyComponent::class => self::DUMMY][$resource]; + }); + + return new AllowedComponentUiValidator($names, $iriConverter); + } + + public function test_a_component_resource_with_no_collection_iri_matches_no_key(): void + { + $this->failingClass = DummyComponent::class; + $constraint = new AllowedComponentUi(); + + $this->validator->validate([self::DUMMY => ['ui' => ['X']]], $constraint); + + $this->buildViolation($constraint->keyMessage)->setParameter('{{ key }}', self::DUMMY)->assertRaised(); + } + + public function test_null_is_valid_and_lists_no_resources(): void + { + $this->validator->validate(null, new AllowedComponentUi()); + + $this->assertNoViolation(); + self::assertSame([], $this->iriCalls); + } + + public function test_the_keys_are_compared_with_the_collection_iris_of_concrete_component_resources(): void + { + $this->validator->validate([self::DUMMY => ['ui' => [null, 'CwaHero'], 'styles' => ['style:large']]], new AllowedComponentUi()); + + $this->assertNoViolation(); + self::assertCount(1, $this->iriCalls); + [$resource, $referenceType, $operation] = $this->iriCalls[0]; + self::assertSame(DummyComponent::class, $resource); + self::assertSame(UrlGeneratorInterface::ABS_PATH, $referenceType); + self::assertInstanceOf(GetCollection::class, $operation); + self::assertSame(DummyComponent::class, $operation->getClass()); + } + + public function test_a_rule_may_restrict_only_the_ui_or_only_the_styles(): void + { + $this->validator->validate([self::DUMMY => ['ui' => ['CwaHero']]], new AllowedComponentUi()); + $this->validator->validate([self::DUMMY => ['styles' => ['style:large']]], new AllowedComponentUi()); + + $this->assertNoViolation(); + } + + /** + * @param array $value + */ + #[DataProvider('invalidKeys')] + public function test_a_key_that_is_not_the_collection_iri_of_a_concrete_component_resource_is_refused(array $value, string $key): void + { + $constraint = new AllowedComponentUi(); + $this->validator->validate($value, $constraint); + + $this->buildViolation($constraint->keyMessage)->setParameter('{{ key }}', $key)->assertRaised(); + } + + /** + * @return iterable, string}> + */ + public static function invalidKeys(): iterable + { + yield 'a resource that is not a component' => [['/_/pages' => ['ui' => ['X']]], '/_/pages']; + yield 'the abstract component resource' => [['/abstract_components' => ['ui' => ['X']]], '/abstract_components']; + yield 'an abstract component subclass' => [['/component/abstract_dummy_app_components' => ['ui' => ['X']]], '/component/abstract_dummy_app_components']; + yield 'a list index' => [[['ui' => ['X']]], '0']; + } + + /** + * @param array $rule + */ + #[DataProvider('invalidRules')] + public function test_a_rule_that_is_not_an_object_of_ui_and_styles_is_refused(mixed $rule): void + { + $constraint = new AllowedComponentUi(); + $this->validator->validate([self::DUMMY => $rule], $constraint); + + $this->buildViolation($constraint->ruleMessage)->setParameter('{{ key }}', self::DUMMY)->assertRaised(); + } + + /** + * @return iterable + */ + public static function invalidRules(): iterable + { + yield 'a string' => ['CwaHero']; + yield 'null' => [null]; + yield 'empty' => [[]]; + yield 'a list' => [['CwaHero']]; + yield 'another key beside ui' => [['ui' => ['CwaHero'], 'other' => ['X']]]; + } + + #[DataProvider('invalidUi')] + public function test_ui_that_is_not_a_non_empty_list_of_strings_or_nulls_is_refused(mixed $ui): void + { + $constraint = new AllowedComponentUi(); + $this->validator->validate([self::DUMMY => ['ui' => $ui, 'styles' => ['style:large']]], $constraint); + + $this->buildViolation($constraint->uiMessage)->setParameter('{{ key }}', self::DUMMY)->assertRaised(); + } + + /** + * @return iterable + */ + public static function invalidUi(): iterable + { + yield 'a string' => ['CwaHero']; + yield 'null' => [null]; + yield 'empty' => [[]]; + yield 'an object' => [['a' => 'CwaHero']]; + yield 'a number after a string' => [['CwaHero', 1]]; + yield 'a list' => [[['CwaHero']]]; + } + + #[DataProvider('invalidStyles')] + public function test_styles_that_are_not_a_non_empty_list_of_strings_are_refused(mixed $styles): void + { + $constraint = new AllowedComponentUi(); + $this->validator->validate([self::DUMMY => ['ui' => [null], 'styles' => $styles]], $constraint); + + $this->buildViolation($constraint->stylesMessage)->setParameter('{{ key }}', self::DUMMY)->assertRaised(); + } + + /** + * @return iterable + */ + public static function invalidStyles(): iterable + { + yield 'a string' => ['style:large']; + yield 'empty' => [[]]; + yield 'an object' => [['a' => 'style:large']]; + yield 'a null after a string' => [['style:large', null]]; + yield 'a number' => [[1]]; + } + + public function test_both_a_bad_ui_and_bad_styles_are_reported(): void + { + $constraint = new AllowedComponentUi(); + $this->validator->validate([self::DUMMY => ['ui' => [], 'styles' => []]], $constraint); + + $this->buildViolation($constraint->uiMessage)->setParameter('{{ key }}', self::DUMMY) + ->buildNextViolation($constraint->stylesMessage)->setParameter('{{ key }}', self::DUMMY) + ->assertRaised(); + } + + public function test_every_rule_is_checked(): void + { + $constraint = new AllowedComponentUi(); + $this->validator->validate(['/_/pages' => ['ui' => ['X']], self::DUMMY => 'X', '/other' => []], $constraint); + + $this->buildViolation($constraint->keyMessage)->setParameter('{{ key }}', '/_/pages') + ->buildNextViolation($constraint->ruleMessage)->setParameter('{{ key }}', self::DUMMY) + ->buildNextViolation($constraint->keyMessage)->setParameter('{{ key }}', '/other') + ->assertRaised(); + } +} diff --git a/tests/Validator/Constraints/ComponentPositionValidatorTest.php b/tests/Validator/Constraints/ComponentPositionValidatorTest.php index 5a1db7b89..507579377 100644 --- a/tests/Validator/Constraints/ComponentPositionValidatorTest.php +++ b/tests/Validator/Constraints/ComponentPositionValidatorTest.php @@ -413,6 +413,72 @@ public function test_a_position_hidden_by_the_allowed_components_does_not_count_ $this->assertNoViolation(); } + public function test_a_new_position_whose_component_ui_the_group_does_not_allow_is_refused_on_component(): void + { + $group = $this->groupHolding(0); + $group->allowedComponentUi = ['/component/dummy_components' => ['ui' => ['CwaHero']]]; + $position = $this->newPosition($group); + \assert($position->component instanceof AbstractComponent); + $position->component->uiComponent = 'CwaBanner'; + + $this->validator->validate($position, new ComponentPositionConstraint()); + + $this->buildViolation('The UI `{{ ui }}` is not allowed for `{{ iri }}` in the component group `{{ reference }}`.') + ->atPath('property.path.component') + ->setParameter('{{ ui }}', 'CwaBanner') + ->setParameter('{{ iri }}', '/component/dummy_components') + ->setParameter('{{ reference }}', 'header') + ->assertRaised(); + } + + public function test_a_new_position_whose_component_styles_the_group_does_not_allow_is_refused_on_component(): void + { + $group = new ComponentGroup(); + $group->allowedComponentUi = ['/component/dummy_components' => ['styles' => ['style:large']]]; + $position = $this->newPosition($group); + \assert($position->component instanceof AbstractComponent); + $position->component->uiClassNames = ['style:large', 'style:dark', 'style:wide']; + + $this->validator->validate($position, new ComponentPositionConstraint()); + + $this->buildViolation('The styles `{{ styles }}` are not allowed for `{{ iri }}` in the component group `{{ reference }}`.') + ->atPath('property.path.component') + ->setParameter('{{ styles }}', 'style:dark, style:wide') + ->setParameter('{{ iri }}', '/component/dummy_components') + ->setParameter('{{ reference }}', '') + ->assertRaised(); + } + + public function test_a_new_position_whose_component_ui_and_styles_the_group_allows_is_allowed(): void + { + $group = $this->groupHolding(0); + $group->allowedComponentUi = ['/component/dummy_components' => ['ui' => ['CwaHero'], 'styles' => ['style:large']]]; + $position = $this->newPosition($group); + \assert($position->component instanceof AbstractComponent); + $position->component->uiComponent = 'CwaHero'; + $position->component->uiClassNames = ['style:large']; + + $this->validator->validate($position, new ComponentPositionConstraint()); + + $this->assertNoViolation(); + } + + public function test_an_unchanged_position_whose_component_ui_the_group_does_not_allow_is_not_checked(): void + { + $group = $this->groupHolding(0); + $group->allowedComponentUi = ['/component/dummy_components' => ['ui' => ['CwaHero'], 'styles' => ['style:large']]]; + $position = $this->newPosition($group); + \assert($position->component instanceof AbstractComponent); + $position->component->uiComponent = 'CwaBanner'; + $position->component->uiClassNames = ['style:dark']; + $group->addComponentPosition($position); + $this->originalData[$position] = ['component' => $position->component, 'componentGroup' => $group]; + + $this->validator->validate($position, new ComponentPositionConstraint()); + + $this->assertNoViolation(); + } + private function groupHolding(int $count): ComponentGroup { $group = new ComponentGroup(); diff --git a/tests/Validator/Constraints/ComponentUiAllowedInGroupsValidatorTest.php b/tests/Validator/Constraints/ComponentUiAllowedInGroupsValidatorTest.php new file mode 100644 index 000000000..43b3d34c7 --- /dev/null +++ b/tests/Validator/Constraints/ComponentUiAllowedInGroupsValidatorTest.php @@ -0,0 +1,341 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Silverback\ApiComponentsBundle\Tests\Validator\Constraints; + +use ApiPlatform\Metadata\GetCollection; +use ApiPlatform\Metadata\IriConverterInterface; +use ApiPlatform\Metadata\Operation; +use ApiPlatform\Metadata\UrlGeneratorInterface; +use Doctrine\ORM\EntityManagerInterface; +use Doctrine\ORM\Mapping\ClassMetadata; +use Doctrine\ORM\UnitOfWork; +use Doctrine\Persistence\ManagerRegistry; +use Doctrine\Persistence\ObjectManager; +use Silverback\ApiComponentsBundle\AttributeReader\PublishableAttributeReader; +use Silverback\ApiComponentsBundle\Entity\Core\AbstractComponent; +use Silverback\ApiComponentsBundle\Entity\Core\ComponentGroup; +use Silverback\ApiComponentsBundle\Repository\Core\ComponentGroupRepository; +use Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity\DummyComponent; +use Silverback\ApiComponentsBundle\Tests\Functional\TestBundle\Entity\DummyPublishableComponent; +use Silverback\ApiComponentsBundle\Validator\Constraints\ComponentUiAllowedInGroups; +use Silverback\ApiComponentsBundle\Validator\Constraints\ComponentUiAllowedInGroupsValidator; +use Symfony\Component\Validator\ConstraintValidatorInterface; +use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; + +/** + * @extends ConstraintValidatorTestCase + */ +final class ComponentUiAllowedInGroupsValidatorTest extends ConstraintValidatorTestCase +{ + private const string DUMMY = '/component/dummy_components'; + private const string PUBLISHABLE = '/component/dummy_publishable_components'; + + private ?\WeakMap $originalData = null; + + /** @var list */ + private array $groups = []; + + /** @var list */ + private array $queriedFor = []; + + /** @var list */ + private array $iriCalls = []; + + private bool $withEntityManager = true; + + protected function createValidator(): ConstraintValidatorInterface + { + $this->originalData = new \WeakMap(); + $unitOfWork = $this->createStub(UnitOfWork::class); + $unitOfWork->method('getOriginalEntityData')->willReturnCallback(fn (object $entity): array => $this->originalData[$entity] ?? []); + $classMetadata = $this->createStub(ClassMetadata::class); + $classMetadata->method('getFieldValue')->willReturnCallback(static fn (object $entity, string $field): mixed => 'publishedResource' === $field && $entity instanceof DummyPublishableComponent ? $entity->getPublishedResource() : null); + $entityManager = $this->createStub(EntityManagerInterface::class); + $entityManager->method('getUnitOfWork')->willReturn($unitOfWork); + $entityManager->method('getClassMetadata')->willReturn($classMetadata); + $registry = $this->createStub(ManagerRegistry::class); + $registry->method('getManagerForClass')->willReturnCallback(fn (string $class): ObjectManager => $this->withEntityManager ? $entityManager : $this->createStub(ObjectManager::class)); + + $repository = $this->createStub(ComponentGroupRepository::class); + $repository->method('findRestrictingUiOf')->willReturnCallback(function (AbstractComponent $component): array { + $this->queriedFor[] = $component; + + return $this->groups; + }); + + $iriConverter = $this->createStub(IriConverterInterface::class); + $iriConverter->method('getIriFromResource')->willReturnCallback(function (object|string $resource, int $referenceType = UrlGeneratorInterface::ABS_PATH, ?Operation $operation = null): string { + \assert(\is_string($resource)); + $this->iriCalls[] = [$resource, $referenceType, $operation]; + + return DummyComponent::class === $resource ? self::DUMMY : self::PUBLISHABLE; + }); + + return new ComponentUiAllowedInGroupsValidator($registry, $repository, new PublishableAttributeReader($this->createStub(ManagerRegistry::class)), $iriConverter); + } + + public function test_the_constraint_targets_the_class(): void + { + self::assertSame(ComponentUiAllowedInGroups::CLASS_CONSTRAINT, (new ComponentUiAllowedInGroups())->getTargets()); + } + + public function test_a_value_that_is_not_a_component_is_ignored(): void + { + $this->validator->validate(new \stdClass(), new ComponentUiAllowedInGroups()); + + $this->assertNoViolation(); + self::assertSame([], $this->queriedFor); + } + + public function test_a_component_without_an_entity_manager_is_not_checked(): void + { + $this->withEntityManager = false; + $component = $this->storedComponent('CwaHero', 'CwaBanner'); + $this->groupsAllowing(['ui' => ['CwaHero']]); + + $this->validator->validate($component, new ComponentUiAllowedInGroups()); + + $this->assertNoViolation(); + self::assertSame([], $this->queriedFor); + } + + public function test_a_new_component_is_not_checked(): void + { + $component = new DummyComponent(); + $component->uiComponent = 'CwaBanner'; + $this->groupsAllowing(['ui' => ['CwaHero']]); + + $this->validator->validate($component, new ComponentUiAllowedInGroups()); + + $this->assertNoViolation(); + self::assertSame([], $this->queriedFor); + } + + public function test_a_component_whose_ui_and_styles_are_unchanged_is_not_checked(): void + { + $component = $this->storedComponent('CwaBanner', 'CwaBanner', ['style:dark'], ['style:dark']); + $this->groupsAllowing(['ui' => ['CwaHero'], 'styles' => ['style:large']]); + + $this->validator->validate($component, new ComponentUiAllowedInGroups()); + + $this->assertNoViolation(); + self::assertSame([], $this->queriedFor); + } + + public function test_a_changed_ui_its_group_does_not_allow_is_refused_on_ui_component(): void + { + $component = $this->storedComponent('CwaHero', 'CwaBanner'); + $this->groupsAllowing(['ui' => ['CwaHero']]); + + $this->validator->validate($component, new ComponentUiAllowedInGroups()); + + $this->buildViolation('The UI `{{ ui }}` is not allowed for `{{ iri }}` in the component group `{{ reference }}`.') + ->atPath('property.path.uiComponent') + ->setParameter('{{ ui }}', 'CwaBanner') + ->setParameter('{{ iri }}', self::DUMMY) + ->setParameter('{{ reference }}', 'group_0') + ->assertRaised(); + self::assertSame([$component], $this->queriedFor); + self::assertCount(1, $this->iriCalls); + [$resource, $referenceType, $operation] = $this->iriCalls[0]; + self::assertSame(DummyComponent::class, $resource); + self::assertSame(UrlGeneratorInterface::ABS_PATH, $referenceType); + self::assertInstanceOf(GetCollection::class, $operation); + self::assertSame(DummyComponent::class, $operation->getClass()); + } + + public function test_a_changed_ui_to_null_its_group_does_not_allow_is_refused(): void + { + $component = $this->storedComponent('CwaHero', null); + $this->groupsAllowing(['ui' => ['CwaHero']]); + + $this->validator->validate($component, new ComponentUiAllowedInGroups()); + + $this->buildViolation('The UI `{{ ui }}` is not allowed for `{{ iri }}` in the component group `{{ reference }}`.') + ->atPath('property.path.uiComponent') + ->setParameter('{{ ui }}', 'null') + ->setParameter('{{ iri }}', self::DUMMY) + ->setParameter('{{ reference }}', 'group_0') + ->assertRaised(); + } + + public function test_changed_styles_its_group_does_not_allow_are_refused_on_ui_class_names(): void + { + $component = $this->storedComponent('CwaHero', 'CwaHero', null, ['style:large', 'style:dark', 'style:wide']); + $this->groupsAllowing(['styles' => ['style:large']]); + + $this->validator->validate($component, new ComponentUiAllowedInGroups()); + + $this->buildViolation('The styles `{{ styles }}` are not allowed for `{{ iri }}` in the component group `{{ reference }}`.') + ->atPath('property.path.uiClassNames') + ->setParameter('{{ styles }}', 'style:dark, style:wide') + ->setParameter('{{ iri }}', self::DUMMY) + ->setParameter('{{ reference }}', 'group_0') + ->assertRaised(); + } + + public function test_only_the_changed_ui_is_checked_when_the_styles_already_break_the_rule(): void + { + $component = $this->storedComponent('CwaBanner', 'CwaHero', ['style:dark'], ['style:dark']); + $this->groupsAllowing(['ui' => ['CwaHero'], 'styles' => ['style:large']]); + + $this->validator->validate($component, new ComponentUiAllowedInGroups()); + + $this->assertNoViolation(); + } + + public function test_only_the_changed_styles_are_checked_when_the_ui_already_breaks_the_rule(): void + { + $component = $this->storedComponent('CwaBanner', 'CwaBanner', ['style:dark'], ['style:large']); + $this->groupsAllowing(['ui' => ['CwaHero'], 'styles' => ['style:large']]); + + $this->validator->validate($component, new ComponentUiAllowedInGroups()); + + $this->assertNoViolation(); + } + + public function test_every_group_holding_the_component_must_allow_its_ui(): void + { + $component = $this->storedComponent(null, 'CwaHero', null, ['style:dark']); + $this->groupsAllowing(['ui' => ['CwaHero']], ['ui' => ['CwaBanner'], 'styles' => ['style:large']], ['ui' => ['CwaBanner']]); + + $this->validator->validate($component, new ComponentUiAllowedInGroups()); + + $this->buildViolation('The UI `{{ ui }}` is not allowed for `{{ iri }}` in the component group `{{ reference }}`.') + ->atPath('property.path.uiComponent') + ->setParameter('{{ ui }}', 'CwaHero') + ->setParameter('{{ iri }}', self::DUMMY) + ->setParameter('{{ reference }}', 'group_1') + ->buildNextViolation('The styles `{{ styles }}` are not allowed for `{{ iri }}` in the component group `{{ reference }}`.') + ->atPath('property.path.uiClassNames') + ->setParameter('{{ styles }}', 'style:dark') + ->setParameter('{{ iri }}', self::DUMMY) + ->setParameter('{{ reference }}', 'group_1') + ->buildNextViolation('The UI `{{ ui }}` is not allowed for `{{ iri }}` in the component group `{{ reference }}`.') + ->atPath('property.path.uiComponent') + ->setParameter('{{ ui }}', 'CwaHero') + ->setParameter('{{ iri }}', self::DUMMY) + ->setParameter('{{ reference }}', 'group_2') + ->assertRaised(); + } + + public function test_a_new_draft_is_compared_with_and_checked_against_its_published_component(): void + { + $published = new DummyPublishableComponent(); + $published->uiComponent = 'CwaHero'; + $draft = new DummyPublishableComponent(); + $draft->setPublishedResource($published); + $draft->uiComponent = 'CwaBanner'; + $this->groupsAllowingFor(self::PUBLISHABLE, ['ui' => ['CwaHero']]); + + $this->validator->validate($draft, new ComponentUiAllowedInGroups()); + + self::assertSame([$published], $this->queriedFor); + self::assertCount(1, $this->context->getViolations()); + self::assertSame('property.path.uiComponent', $this->context->getViolations()->get(0)->getPropertyPath()); + } + + public function test_a_new_draft_with_the_ui_and_styles_of_its_published_component_is_not_checked(): void + { + $published = new DummyPublishableComponent(); + $published->uiComponent = 'CwaBanner'; + $published->uiClassNames = ['style:dark']; + $draft = new DummyPublishableComponent(); + $draft->setPublishedResource($published); + $draft->uiComponent = 'CwaBanner'; + $draft->uiClassNames = ['style:dark']; + $this->groupsAllowingFor(self::PUBLISHABLE, ['ui' => ['CwaHero'], 'styles' => ['style:large']]); + + $this->validator->validate($draft, new ComponentUiAllowedInGroups()); + + $this->assertNoViolation(); + self::assertSame([], $this->queriedFor); + } + + public function test_a_new_draft_whose_styles_differ_from_its_published_component_is_checked(): void + { + $published = new DummyPublishableComponent(); + $draft = new DummyPublishableComponent(); + $draft->setPublishedResource($published); + $draft->uiClassNames = ['style:dark']; + $this->groupsAllowingFor(self::PUBLISHABLE, ['styles' => ['style:large']]); + + $this->validator->validate($draft, new ComponentUiAllowedInGroups()); + + self::assertCount(1, $this->context->getViolations()); + self::assertSame('property.path.uiClassNames', $this->context->getViolations()->get(0)->getPropertyPath()); + } + + public function test_a_stored_draft_is_checked_against_its_published_components_groups(): void + { + $published = new DummyPublishableComponent(); + $draft = new DummyPublishableComponent(); + $draft->setPublishedResource($published); + $draft->uiComponent = 'CwaBanner'; + $this->originalData[$draft] = ['uiComponent' => null, 'uiClassNames' => null]; + $this->groupsAllowingFor(self::PUBLISHABLE, ['ui' => [null]]); + + $this->validator->validate($draft, new ComponentUiAllowedInGroups()); + + self::assertSame([$published], $this->queriedFor); + self::assertCount(1, $this->context->getViolations()); + } + + public function test_a_stored_publishable_component_with_no_published_version_is_checked_against_its_own_groups(): void + { + $component = new DummyPublishableComponent(); + $component->uiComponent = 'CwaBanner'; + $this->originalData[$component] = ['uiComponent' => null, 'uiClassNames' => null]; + $this->groupsAllowingFor(self::PUBLISHABLE, ['ui' => [null]]); + + $this->validator->validate($component, new ComponentUiAllowedInGroups()); + + self::assertSame([$component], $this->queriedFor); + self::assertCount(1, $this->context->getViolations()); + } + + /** + * @param list|null $originalStyles + * @param list|null $styles + */ + private function storedComponent(?string $originalUi, ?string $ui, ?array $originalStyles = null, ?array $styles = null): DummyComponent + { + $component = new DummyComponent(); + $component->uiComponent = $ui; + $component->uiClassNames = $styles; + $this->originalData[$component] = ['uiComponent' => $originalUi, 'uiClassNames' => $originalStyles]; + + return $component; + } + + /** + * @param array ...$rules + */ + private function groupsAllowing(array ...$rules): void + { + $this->groupsAllowingFor(self::DUMMY, ...$rules); + } + + /** + * @param array ...$rules + */ + private function groupsAllowingFor(string $iri, array ...$rules): void + { + $this->groups = []; + foreach ($rules as $index => $rule) { + $group = new ComponentGroup(); + $group->reference = 'group_' . $index; + $group->allowedComponentUi = [$iri => $rule]; + $this->groups[] = $group; + } + } +} From a5bfb9919ad17af5cb1f84efa10d009e45393a5d Mon Sep 17 00:00:00 2001 From: silverbackdan Date: Wed, 25 Nov 2026 00:26:27 +0000 Subject: [PATCH 2/2] Link the changelog lines to #613 --- CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f202c4225..3705ee3ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,10 +12,10 @@ Every change that reaches `main` adds a line under **Unreleased**. When a versio - `http_cache.personalised_resource_classes`, `scheduled_expiry_resource_classes` and `purge_rendered_html_classes` always keep the CWA defaults; configured or prepended classes are added to them instead of replacing them ([#611](https://github.com/components-web-app/api-components-bundle/pull/611)) ### Added -- `ComponentGroup.allowedComponentUi` restricts, per component collection IRI, the `uiComponent` values (`ui`) and `uiClassNames` entries (`styles`) a group's components may have: placing a component the group does not allow is a 422 on `component` (`to.componentGroup` for `/move`), and changing a placed component's UI or styles to a value one of its groups does not allow is a 422 on `uiComponent` or `uiClassNames`, a draft checked through its published component; `CwaFixtureBuilder` groups take `allowUi:`, `generate-fixtures` writes it and `make:rename-component` renames its keys (PR_LINK) +- `ComponentGroup.allowedComponentUi` restricts, per component collection IRI, the `uiComponent` values (`ui`) and `uiClassNames` entries (`styles`) a group's components may have: placing a component the group does not allow is a 422 on `component` (`to.componentGroup` for `/move`), and changing a placed component's UI or styles to a value one of its groups does not allow is a 422 on `uiComponent` or `uiClassNames`, a draft checked through its published component; `CwaFixtureBuilder` groups take `allowUi:`, `generate-fixtures` writes it and `make:rename-component` renames its keys ([#613](https://github.com/components-web-app/api-components-bundle/pull/613)) ### Tooling -- The page JSON schema's `$ref` to the page data schema is a valid JSON pointer, which `justinrainbow/json-schema` 6.15 requires (PR_LINK) +- The page JSON schema's `$ref` to the page data schema is a valid JSON pointer, which `justinrainbow/json-schema` 6.15 requires ([#613](https://github.com/components-web-app/api-components-bundle/pull/613)) ### Fixed - Normalizing a user no longer writes its reachable roles onto the entity, so a later flush in the same request cannot store them; `roles` in the output (including `/me`) is still every role the user reaches ([#611](https://github.com/components-web-app/api-components-bundle/pull/611))