Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add UUID validation rule, and test #754

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
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
77 changes: 77 additions & 0 deletions src/Rule/Uuid.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Validator\Rule;

use Attribute;
use Closure;
use Yiisoft\Validator\DumpedRuleInterface;
use Yiisoft\Validator\Rule\Trait\SkipOnEmptyTrait;
use Yiisoft\Validator\Rule\Trait\SkipOnErrorTrait;
use Yiisoft\Validator\Rule\Trait\WhenTrait;
use Yiisoft\Validator\SkipOnEmptyInterface;
use Yiisoft\Validator\SkipOnErrorInterface;
use Yiisoft\Validator\WhenInterface;

#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
class Uuid implements DumpedRuleInterface, SkipOnEmptyInterface, SkipOnErrorInterface, WhenInterface {
use SkipOnEmptyTrait;
use SkipOnErrorTrait;
use WhenTrait;

/**
* @param bool $replaceChars
* @param string $message
* @param string $notPassedMessage
* @param bool $skipOnError
* @param Closure|null $when
*/
public function __construct(

Check warning on line 30 in src/Rule/Uuid.php

View check run for this annotation

Codecov / codecov/patch

src/Rule/Uuid.php#L30

Added line #L30 was not covered by tests
private bool $replaceChars = false,
private string $message = 'The value of {property} does not conform to the UUID format.',
private string $notPassedMessage = '{Property} not passed.',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This property is not used.

private bool $skipOnError = false,
private Closure|null $when = null,
) {
}

Check warning on line 37 in src/Rule/Uuid.php

View check run for this annotation

Codecov / codecov/patch

src/Rule/Uuid.php#L37

Added line #L37 was not covered by tests

/**
* @return bool
*/
public function getReplaceChars(): bool {
return $this->replaceChars;

Check warning on line 43 in src/Rule/Uuid.php

View check run for this annotation

Codecov / codecov/patch

src/Rule/Uuid.php#L42-L43

Added lines #L42 - L43 were not covered by tests
}

/**
* Gets error message used when validation fails because the validated value is empty.
*
* @return string Error message / template.
*
* @see $message
*/
public function getMessage(): string {
return $this->message;

Check warning on line 54 in src/Rule/Uuid.php

View check run for this annotation

Codecov / codecov/patch

src/Rule/Uuid.php#L53-L54

Added lines #L53 - L54 were not covered by tests
}

/**
* @return string
*/
public function getName(): string {
return self::class;

Check warning on line 61 in src/Rule/Uuid.php

View check run for this annotation

Codecov / codecov/patch

src/Rule/Uuid.php#L60-L61

Added lines #L60 - L61 were not covered by tests
}

/**
* @return array
*/
public function getOptions(): array {
return [];

Check warning on line 68 in src/Rule/Uuid.php

View check run for this annotation

Codecov / codecov/patch

src/Rule/Uuid.php#L67-L68

Added lines #L67 - L68 were not covered by tests
}

/**
* @return string
*/
public function getHandler(): string {
return UuidHandler::class;

Check warning on line 75 in src/Rule/Uuid.php

View check run for this annotation

Codecov / codecov/patch

src/Rule/Uuid.php#L74-L75

Added lines #L74 - L75 were not covered by tests
}
}
52 changes: 52 additions & 0 deletions src/Rule/UuidHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Validator\Rule;

use Yiisoft\Validator\Exception\UnexpectedRuleException;
use Yiisoft\Validator\Result;
use Yiisoft\Validator\RuleHandlerInterface;
use Yiisoft\Validator\RuleInterface;
use Yiisoft\Validator\ValidationContext;

class UuidHandler implements RuleHandlerInterface {
private const PATTERN = '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i';
private const NIL = '00000000-0000-0000-0000-000000000000';

/**
* @param mixed $value
* @param RuleInterface $rule
* @param ValidationContext $context
* @return Result
*/
public function validate(mixed $value, RuleInterface $rule, ValidationContext $context): Result {
if (!$rule instanceof Uuid) {
throw new UnexpectedRuleException(Uuid::class, $rule);

Check warning on line 25 in src/Rule/UuidHandler.php

View check run for this annotation

Codecov / codecov/patch

src/Rule/UuidHandler.php#L23-L25

Added lines #L23 - L25 were not covered by tests
}

$result = new Result();

Check warning on line 28 in src/Rule/UuidHandler.php

View check run for this annotation

Codecov / codecov/patch

src/Rule/UuidHandler.php#L28

Added line #L28 was not covered by tests

if ($this->validateUuid($value, $rule->getReplaceChars())) {

Check failure on line 30 in src/Rule/UuidHandler.php

View workflow job for this annotation

GitHub Actions / psalm83 / PHP 8.3-ubuntu-latest

MixedArgument

src/Rule/UuidHandler.php:30:33: MixedArgument: Argument 1 of Yiisoft\Validator\Rule\UuidHandler::validateUuid cannot be mixed, expecting string (see https://psalm.dev/030)

Check failure on line 30 in src/Rule/UuidHandler.php

View workflow job for this annotation

GitHub Actions / psalm / PHP 8.1-ubuntu-latest

MixedArgument

src/Rule/UuidHandler.php:30:33: MixedArgument: Argument 1 of Yiisoft\Validator\Rule\UuidHandler::validateUuid cannot be mixed, expecting string (see https://psalm.dev/030)

Check failure on line 30 in src/Rule/UuidHandler.php

View workflow job for this annotation

GitHub Actions / psalm / PHP 8.2-ubuntu-latest

MixedArgument

src/Rule/UuidHandler.php:30:33: MixedArgument: Argument 1 of Yiisoft\Validator\Rule\UuidHandler::validateUuid cannot be mixed, expecting string (see https://psalm.dev/030)
return $result;

Check warning on line 31 in src/Rule/UuidHandler.php

View check run for this annotation

Codecov / codecov/patch

src/Rule/UuidHandler.php#L30-L31

Added lines #L30 - L31 were not covered by tests
}

return $result->addError($rule->getMessage(), [
'property' => $context->getTranslatedProperty(),
'Property' => $context->getCapitalizedTranslatedProperty(),
]);

Check warning on line 37 in src/Rule/UuidHandler.php

View check run for this annotation

Codecov / codecov/patch

src/Rule/UuidHandler.php#L34-L37

Added lines #L34 - L37 were not covered by tests
}

/**
* @param string $uuid
* @param bool $replaceChars
* @return bool
*/
protected function validateUuid(string $uuid, bool $replaceChars): bool {
if ($replaceChars) {
$uuid = str_replace(['urn:', 'uuid:', 'URN:', 'UUID:', '{', '}'], '', $uuid);

Check warning on line 47 in src/Rule/UuidHandler.php

View check run for this annotation

Codecov / codecov/patch

src/Rule/UuidHandler.php#L45-L47

Added lines #L45 - L47 were not covered by tests
}

return $uuid === self::NIL || preg_match('/' . self::PATTERN . '/Dms', $uuid);

Check warning on line 50 in src/Rule/UuidHandler.php

View check run for this annotation

Codecov / codecov/patch

src/Rule/UuidHandler.php#L50

Added line #L50 was not covered by tests
}
}
70 changes: 70 additions & 0 deletions tests/Rule/UuidTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

namespace Yiisoft\Validator\Tests\Rule;

use Yiisoft\Validator\Rule\Url;
use Yiisoft\Validator\Rule\Uuid;
use Yiisoft\Validator\Rule\UuidHandler;
use Yiisoft\Validator\Tests\Rule\Base\DifferentRuleInHandlerTestTrait;
use Yiisoft\Validator\Tests\Rule\Base\RuleTestCase;
use Yiisoft\Validator\Tests\Rule\Base\RuleWithOptionsTestTrait;
use Yiisoft\Validator\Tests\Rule\Base\SkipOnErrorTestTrait;
use Yiisoft\Validator\Tests\Rule\Base\WhenTestTrait;

class UuidTest extends RuleTestCase {
use DifferentRuleInHandlerTestTrait;
use RuleWithOptionsTestTrait;
use SkipOnErrorTestTrait;
use WhenTestTrait;

public function testGetName(): void {
$rule = new Uuid();
$this->assertSame(Uuid::class, $rule->getName());
}

/**
* @return string[]
*/
protected function getDifferentRuleInHandlerItems(): array {
return [Uuid::class, UuidHandler::class];
}

/**
* @return array[]
*/
public function dataValidationPassed(): array {
return [
['0193ba64-5ef5-7ba3-90c1-2915349a60d3', [new Uuid()]],
['89ffcfc5-d452-4eb9-8949-d35fb577f09d', [new Uuid()]],

['289cef4c-b873-11ef-9cd2-0242ac120002', [new Uuid()]],
];
}

public function dataValidationFailed(): array {
$errors = ['' => ['The value of value does not conform to the UUID format.']];

return [
['not uuid value', [new Uuid()], $errors],
['ea20aba6-1fb2-45de-8582-6ed15f94501', [new Uuid()], $errors],
];
}

public function dataOptions(): array {
return [
[new Uuid(), []],
];
}

public function testSkipOnError(): void {
$this->testSkipOnErrorInternal(new Url(), new Url(skipOnError: true));
}

/**
* @return void
*/
public function testWhen(): void {
$when = static fn(mixed $value): bool => $value !== null;
$this->testWhenInternal(new Uuid(), new Uuid(when: $when));
}
}
Loading