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
3 changes: 2 additions & 1 deletion src/Resolve/DtoResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use DualMedia\DtoRequestBundle\Resolve\Interface\ExtractorInterface;
use DualMedia\DtoRequestBundle\Resolve\Model\PendingEntityValue;
use DualMedia\DtoRequestBundle\Resolve\Model\PendingValue;
use DualMedia\DtoRequestBundle\Util;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Validator\ValidatorInterface;
Expand Down Expand Up @@ -230,7 +231,7 @@ protected function finalValidatePhase(
assert(null !== $vwg);

$provider = $this->groupProviderLocator->get($mainDto->validationGroupsServiceId);
$groups = ($vwg->closure)($provider, $dto, $request);
$groups = Util::mergeDefaultGroup(($vwg->closure)($provider, $dto, $request));
}

$violations = $this->validator->startContext()
Expand Down
81 changes: 81 additions & 0 deletions src/Util.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,57 @@

namespace DualMedia\DtoRequestBundle;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\GroupSequence;

class Util
{
private function __construct()
{
}

/**
* Ensure the `Default` validation group is present in `$groups`.
*
* Without this, a `#[ValidateWithGroups]` closure that returns e.g.
* `['extra']` would silently disable every Default-group constraint
* (NotNull/NotBlank/Length/...) on the DTO.
*
* - `string` → wrapped into `[$g, 'Default']` (no-op when already `Default`).
* - `GroupSequence` → cloned with `Default` appended when absent; left
* intact otherwise (the user's explicit ordering is preserved).
* - `list<string|GroupSequence>` → `Default` appended when no plain
* `'Default'` token is present and no nested `GroupSequence` already
* covers it.
*
* @param string|GroupSequence|list<string|GroupSequence> $groups
*
* @return string|GroupSequence|list<string|GroupSequence>
*/
public static function mergeDefaultGroup(
string|GroupSequence|array $groups
): string|GroupSequence|array {
if (is_string($groups)) {
return Constraint::DEFAULT_GROUP === $groups ? $groups : [$groups, Constraint::DEFAULT_GROUP];
}

if ($groups instanceof GroupSequence) {
if (self::groupsContainDefault($groups->groups)) {
return $groups;
}

return new GroupSequence([...$groups->groups, Constraint::DEFAULT_GROUP]);
}

if (self::groupsContainDefault($groups)) {
return $groups;
}

$groups[] = Constraint::DEFAULT_GROUP;

return $groups;
}

/**
* Builds a validation path from segments, using bracket syntax for numeric indices.
*
Expand Down Expand Up @@ -56,4 +101,40 @@ public static function escapeCharactersForCache(
): string {
return strtr($text, '{}()/\@:', '<>_-,.?\'');
}

/**
* Recursive scan: `Default` may appear at any nesting depth allowed by
* Symfony's group representation — a plain string entry, an entry inside
* a parallel-step sub-array within a `GroupSequence`, or inside a nested
* `GroupSequence`.
*
* @param array<mixed, mixed> $groups
*/
private static function groupsContainDefault(
array $groups
): bool {
foreach ($groups as $entry) {
if (is_string($entry)) {
if (Constraint::DEFAULT_GROUP === $entry) {
return true;
}

continue;
}

if ($entry instanceof GroupSequence) {
if (self::groupsContainDefault($entry->groups)) {
return true;
}

continue;
}

if (is_array($entry) && self::groupsContainDefault($entry)) {
return true;
}
}

return false;
}
}
75 changes: 75 additions & 0 deletions tests/Feature/Resolver/ValidateWithGroupsDefaultTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
<?php

declare(strict_types=1);

namespace DualMedia\DtoRequestBundle\Tests\Feature\Resolver;

use DualMedia\DtoRequestBundle\Resolve\DtoResolver;
use DualMedia\DtoRequestBundle\Tests\Fixture\Dto\ExtraGroupDto;
use DualMedia\DtoRequestBundle\Tests\Fixture\Dto\ExtraGroupValidatedDto;
use DualMedia\DtoRequestBundle\Tests\Fixture\Service\TestExtraGroupProvider;
use DualMedia\DtoRequestBundle\Tests\PHPUnit\KernelTestCase;
use PHPUnit\Framework\Attributes\Group;
use Symfony\Component\HttpFoundation\Request;

#[Group('feature')]
#[Group('resolver')]
class ValidateWithGroupsDefaultTest extends KernelTestCase
{
private DtoResolver $resolver;

protected function setUp(): void
{
$this->resolver = static::getService(DtoResolver::class);
}

public function testBaselineDtoZeroPasses(): void
{
$dto = $this->resolver->resolve(
ExtraGroupDto::class,
new Request(request: ['value' => '0'])
);

// 'extra' group is not invoked → Positive doesn't fire → only NotNull
// is in play, value=0 satisfies it.
static::assertTrue($dto->isValid(), (string)$dto->getConstraintViolationList());
}

public function testBaselineDtoMissingTriggersNotNull(): void
{
$dto = $this->resolver->resolve(
ExtraGroupDto::class,
new Request()
);

static::assertFalse($dto->isValid(), 'NotNull must fire when value is missing');
}

public function testValidateWithGroupsDtoZeroFailsPositiveWhenExtraGroupActive(): void
{
$provider = static::getService(TestExtraGroupProvider::class);
$provider->groups = ['extra'];

$dto = $this->resolver->resolve(
ExtraGroupValidatedDto::class,
new Request(request: ['value' => '0'])
);

static::assertFalse($dto->isValid(), 'Positive(extra) must fire on 0 when the extra group is requested');
}

public function testValidateWithGroupsDtoMissingFailsNotNullEvenWhenOnlyExtraReturned(): void
{
$provider = static::getService(TestExtraGroupProvider::class);
$provider->groups = ['extra'];

$dto = $this->resolver->resolve(
ExtraGroupValidatedDto::class,
new Request()
);

// Even when the closure returns only ['extra'], Default must remain in
// play so NotNull (Default group) still surfaces.
static::assertFalse($dto->isValid(), 'NotNull (Default group) must still fire alongside the extra group');
}
}
15 changes: 15 additions & 0 deletions tests/Fixture/Dto/ExtraGroupDto.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

declare(strict_types=1);

namespace DualMedia\DtoRequestBundle\Tests\Fixture\Dto;

use DualMedia\DtoRequestBundle\Dto\AbstractDto;
use Symfony\Component\Validator\Constraints as Assert;

class ExtraGroupDto extends AbstractDto
{
#[Assert\Positive(groups: ['extra'])]
#[Assert\NotNull]
public int|null $value = null;
}
21 changes: 21 additions & 0 deletions tests/Fixture/Dto/ExtraGroupValidatedDto.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

declare(strict_types=1);

namespace DualMedia\DtoRequestBundle\Tests\Fixture\Dto;

use DualMedia\DtoRequestBundle\Dto\AbstractDto;
use DualMedia\DtoRequestBundle\Dto\Attribute\ValidateWithGroups;
use DualMedia\DtoRequestBundle\Tests\Fixture\Service\TestExtraGroupProvider;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints as Assert;

#[ValidateWithGroups(static function (TestExtraGroupProvider $provider, ExtraGroupValidatedDto $dto, Request $request): array {
return $provider->resolve();
})]
class ExtraGroupValidatedDto extends AbstractDto
{
#[Assert\Positive(groups: ['extra'])]
#[Assert\NotNull]
public int|null $value = null;
}
28 changes: 28 additions & 0 deletions tests/Fixture/Service/TestExtraGroupProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace DualMedia\DtoRequestBundle\Tests\Fixture\Service;

use DualMedia\DtoRequestBundle\Provider\Interface\GroupProviderInterface;

/**
* Returns a custom group set without including `Default`. This is on purpose:
* tests that exercise the bundle's "always-merge-Default" behavior would be
* masked by `TestGroupProvider`, which seeds `['Default']`.
*/
class TestExtraGroupProvider implements GroupProviderInterface
{
/**
* @var list<string>
*/
public array $groups = ['extra'];

/**
* @return list<string>
*/
public function resolve(): array
{
return $this->groups;
}
}
92 changes: 92 additions & 0 deletions tests/Unit/UtilTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\GroupSequence;

#[CoversClass(Util::class)]
#[Group('unit')]
Expand Down Expand Up @@ -39,4 +41,94 @@ public static function provideBuildValidationPathCases(): iterable
yield 'root numeric' => [['0'], '[0]'];
yield 'two segments with index' => [['list', '5'], 'list[5]'];
}

public function testMergeDefaultGroupBareDefaultStringReturnedUnchanged(): void
{
static::assertSame(Constraint::DEFAULT_GROUP, Util::mergeDefaultGroup(Constraint::DEFAULT_GROUP));
}

public function testMergeDefaultGroupBareCustomStringWrappedWithDefault(): void
{
static::assertSame(['extra', Constraint::DEFAULT_GROUP], Util::mergeDefaultGroup('extra'));
}

public function testMergeDefaultGroupListMissingDefaultGetsDefaultAppended(): void
{
static::assertSame(['extra', Constraint::DEFAULT_GROUP], Util::mergeDefaultGroup(['extra']));
}

public function testMergeDefaultGroupListContainingDefaultIsUnchanged(): void
{
$input = ['extra', Constraint::DEFAULT_GROUP, 'admin'];
static::assertSame($input, Util::mergeDefaultGroup($input));
}

public function testMergeDefaultGroupListWithSequenceCoveringDefaultIsUnchanged(): void
{
$sequence = new GroupSequence(['extra', Constraint::DEFAULT_GROUP]);
$input = [$sequence];

$result = Util::mergeDefaultGroup($input);

static::assertSame($input, $result);
}

public function testMergeDefaultGroupListWithSequenceMissingDefaultGetsDefaultAppendedToOuterList(): void
{
$sequence = new GroupSequence(['extra', 'admin']);

$result = Util::mergeDefaultGroup([$sequence]);

static::assertIsArray($result);
static::assertCount(2, $result);
static::assertSame($sequence, $result[0]);
static::assertSame(Constraint::DEFAULT_GROUP, $result[1]);
}

public function testMergeDefaultGroupSequenceContainingDefaultReturnedUnchanged(): void
{
$sequence = new GroupSequence([Constraint::DEFAULT_GROUP, 'extra']);

static::assertSame($sequence, Util::mergeDefaultGroup($sequence));
}

public function testMergeDefaultGroupSequenceMissingDefaultGetsDefaultAppendedInsideSequence(): void
{
$sequence = new GroupSequence(['extra', 'admin']);

$result = Util::mergeDefaultGroup($sequence);

static::assertInstanceOf(GroupSequence::class, $result);
static::assertNotSame($sequence, $result, 'must return a fresh sequence to keep the original immutable from the caller');
static::assertSame(['extra', 'admin', Constraint::DEFAULT_GROUP], $result->groups);
}

public function testMergeDefaultGroupEmptyListGetsDefault(): void
{
static::assertSame([Constraint::DEFAULT_GROUP], Util::mergeDefaultGroup([]));
}

public function testMergeDefaultGroupSequenceWithNestedParallelStepCoveringDefaultIsUnchanged(): void
{
// Symfony allows a parallel step (sub-array) inside a GroupSequence;
// Default living inside that nested step must be detected.
$sequence = new GroupSequence([['extra', Constraint::DEFAULT_GROUP], 'admin']);

static::assertSame($sequence, Util::mergeDefaultGroup($sequence));
}

public function testMergeDefaultGroupListWithNestedSubArrayCoveringDefaultIsUnchanged(): void
{
$input = [['extra', Constraint::DEFAULT_GROUP], 'admin'];

static::assertSame($input, Util::mergeDefaultGroup($input)); // @phpstan-ignore-line
}

public function testMergeDefaultGroupSequenceWithDeeplyNestedSequenceCoveringDefaultIsUnchanged(): void
{
$inner = new GroupSequence([Constraint::DEFAULT_GROUP, 'extra']);
$outer = new GroupSequence([$inner, 'admin']);

static::assertSame($outer, Util::mergeDefaultGroup($outer));
}
}
Loading