Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 ([#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 ([#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))

Expand Down
13 changes: 7 additions & 6 deletions CLAUDE.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions src/Entity/Core/AbstractComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
#[ORM\DiscriminatorColumn(name: 'dtype', type: 'string', length: 255)]
#[ApiResource]
#[Get]
#[AcbAssert\ComponentUiAllowedInGroups]
abstract class AbstractComponent implements ComponentInterface, VersionedInterface
{
use IdTrait;
Expand Down
15 changes: 15 additions & 0 deletions src/Entity/Core/ComponentGroup.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,14 @@ class ComponentGroup
#[Groups(['ComponentGroup:read', 'ComponentGroup:write', 'Layout:read', 'Page:read'])]
public ?array $allowedComponents = null;

/**
* @var array<string, array{ui?: list<string|null>, styles?: list<string>}>|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]
Expand Down Expand Up @@ -211,4 +219,11 @@ public function addAllowedComponent(string $allowedComponent): self

return $this;
}

public function setAllowedComponentUi(?array $allowedComponentUi): self
{
$this->allowedComponentUi = $allowedComponentUi ?: null;

return $this;
}
}
4 changes: 2 additions & 2 deletions src/Fixture/Builder/ComponentBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand Down
9 changes: 9 additions & 0 deletions src/Fixture/Builder/GroupBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [],
) {
}

Expand Down Expand Up @@ -60,6 +61,14 @@ public function getMaxComponents(): ?int
return $this->maxComponents;
}

/**
* @return array<class-string, array{ui?: list<string|null>, styles?: list<string>}>
*/
public function getAllowedComponentUi(): array
{
return $this->allowedComponentUi;
}

public function getLocationReference(): ?string
{
return $this->locationReference;
Expand Down
4 changes: 2 additions & 2 deletions src/Fixture/Builder/LayoutBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand Down
4 changes: 2 additions & 2 deletions src/Fixture/Builder/PageBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand Down
18 changes: 11 additions & 7 deletions src/Fixture/CwaFixtureBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -762,14 +762,13 @@
$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);
Expand All @@ -784,6 +783,11 @@
$this->componentGroupMap[$groupBuilderId] = $componentGroup;
}

private function collectionIri(string $class): string
{
return (string) $this->iriConverter->getIriFromResource($class, UrlGeneratorInterface::ABS_PATH, (new GetCollection())->withClass($class));

Check warning on line 788 in src/Fixture/CwaFixtureBuilder.php

View workflow job for this annotation

GitHub Actions / PHPUnit (Symfony 7.4) (PHP 8.5)

Escaped Mutant for Mutator "CastString": @@ @@ private function collectionIri(string $class): string { - return (string) $this->iriConverter->getIriFromResource($class, UrlGeneratorInterface::ABS_PATH, (new GetCollection())->withClass($class)); + return $this->iriConverter->getIriFromResource($class, UrlGeneratorInterface::ABS_PATH, (new GetCollection())->withClass($class)); } private function publishedGroupOwner(Layout|Page|AbstractComponent $owner): Layout|Page|AbstractComponent
}

private function publishedGroupOwner(Layout|Page|AbstractComponent $owner): Layout|Page|AbstractComponent
{
if (!$owner instanceof AbstractComponent || null === $this->publishableAttributeReader || !$this->publishableAttributeReader->isConfigured($owner)) {
Expand Down
22 changes: 22 additions & 0 deletions src/Fixture/Generator/Plan/GroupPlanner.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@
if (null !== $group->maxComponents) {
$arguments[] = 'max: ' . $group->maxComponents;
}
$allowedUi = $this->resolveAllowedComponentUi($group);
if ([] !== $allowedUi) {
$arguments[] = 'allowUi: [' . implode(', ', $allowedUi) . ']';
}

return new GroupPlan($name, $arguments);
}
Expand All @@ -108,6 +112,24 @@
return $allowed;
}

/**
* @return list<string>
*/
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;

Check warning on line 125 in src/Fixture/Generator/Plan/GroupPlanner.php

View workflow job for this annotation

GitHub Actions / PHPUnit (Symfony 7.4) (PHP 8.5)

Escaped Mutant for Mutator "Continue_": @@ @@ $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; + break; } $allowed[] = $this->imports->add($class) . '::class => ' . $this->export($rule); }
}
$allowed[] = $this->imports->add($class) . '::class => ' . $this->export($rule);
}

return $allowed;

Check warning on line 130 in src/Fixture/Generator/Plan/GroupPlanner.php

View workflow job for this annotation

GitHub Actions / PHPUnit (Symfony 7.4) (PHP 8.5)

Escaped Mutant for Mutator "ArrayOneItem": @@ @@ $allowed[] = $this->imports->add($class) . '::class => ' . $this->export($rule); } - return $allowed; + return count($allowed) > 1 ? array_slice($allowed, 0, 1, true) : $allowed; } /**
}

/**
* @return array<string, string>
*/
Expand Down
2 changes: 1 addition & 1 deletion src/Maker/MakeRenameComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions src/Repository/Core/ComponentGroupRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -50,4 +51,20 @@ public function findOneByIdOrReference(string $idOrRef): ?ComponentGroup

return null;
}

/**
* @return list<ComponentGroup>
*/
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();
}
}
24 changes: 24 additions & 0 deletions src/Resources/config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)
Expand Down
14 changes: 14 additions & 0 deletions src/Resources/skeleton/migration/RenameComponentBody.tpl.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,17 @@
['components' => json_encode(array_map(static fn (string $c): string => <?php echo var_export($from_iri, true); ?> === $c ? <?php echo var_export($to_iri, true); ?> : $c, $components)), 'id' => $row['id']]
);
}
foreach ($this->connection->fetchAllAssociative('SELECT id, allowed_component_ui FROM <?php echo $group_table; ?> 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(<?php echo var_export($from_iri, true); ?>, $rules)) {
continue;
}
$renamed = [];
foreach ($rules as $iri => $rule) {
$renamed[<?php echo var_export($from_iri, true); ?> === $iri ? <?php echo var_export($to_iri, true); ?> : $iri] = $rule;
}
$this->connection->executeStatement(
'UPDATE <?php echo $group_table; ?> SET allowed_component_ui = :rules WHERE id = :id',
['rules' => json_encode($renamed), 'id' => $row['id']]
);
}
54 changes: 54 additions & 0 deletions src/Utility/AllowedComponentUi.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

/*
* This file is part of the Silverback API Components Bundle Project
*
* (c) Daniel West <daniel@silverback.is>
*
* 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<mixed>|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<mixed>|null $allowedComponentUi
* @param array<mixed>|null $uiClassNames
*
* @return list<string>
*/
public static function disallowedStyles(?array $allowedComponentUi, string $componentIri, ?array $uiClassNames): array
{
if (!isset($allowedComponentUi[$componentIri]['styles']) || null === $uiClassNames) {

Check warning on line 36 in src/Utility/AllowedComponentUi.php

View workflow job for this annotation

GitHub Actions / PHPUnit (Symfony 7.4) (PHP 8.5)

Escaped Mutant for Mutator "Identical": @@ @@ */ public static function disallowedStyles(?array $allowedComponentUi, string $componentIri, ?array $uiClassNames): array { - if (!isset($allowedComponentUi[$componentIri]['styles']) || null === $uiClassNames) { + if (!isset($allowedComponentUi[$componentIri]['styles']) || null !== $uiClassNames) { return []; }
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';
}
}
23 changes: 23 additions & 0 deletions src/Validator/Constraints/AllowedComponentUi.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

/*
* This file is part of the Silverback API Components Bundle Project
*
* (c) Daniel West <daniel@silverback.is>
*
* 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.';
}
Loading
Loading