Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[Validator] Add Slug constraint #58542

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

Merged
merged 1 commit into from
Jan 6, 2025
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
1 change: 1 addition & 0 deletions 1 src/Symfony/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
---

* Add support for ratio checks for SVG files to the `Image` constraint
* Add the `Slug` constraint

7.2
---
Expand Down
41 changes: 41 additions & 0 deletions 41 src/Symfony/Component/Validator/Constraints/Slug.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
* Validates that a value is a valid slug.
*
* @author Raffaele Carelle <raffaele.carelle@gmail.com>
*/
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class Slug extends Constraint
{
public const NOT_SLUG_ERROR = '14e6df1e-c8ab-4395-b6ce-04b132a3765e';

public string $message = 'This value is not a valid slug.';
Copy link
Member

Choose a reason for hiding this comment

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

This message needs to be added in translation files (so that the translators from the community can provide translations for it in core, like other default messages of constraints)

Copy link
Member

Choose a reason for hiding this comment

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

this has already been done in #59383

public string $regex = '/^[a-z0-9]+(?:-[a-z0-9]+)*$/';

public function __construct(
?array $options = null,
?string $regex = null,
?string $message = null,
?array $groups = null,
mixed $payload = null,
) {
parent::__construct($options, $groups, $payload);

$this->message = $message ?? $this->message;
$this->regex = $regex ?? $this->regex;
}
}
47 changes: 47 additions & 0 deletions 47 src/Symfony/Component/Validator/Constraints/SlugValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;

/**
* @author Raffaele Carelle <raffaele.carelle@gmail.com>
*/
class SlugValidator extends ConstraintValidator
{
public function validate(mixed $value, Constraint $constraint): void
{
if (!$constraint instanceof Slug) {
throw new UnexpectedTypeException($constraint, Slug::class);
}

if (null === $value || '' === $value) {
return;
}

if (!\is_scalar($value) && !$value instanceof \Stringable) {
throw new UnexpectedValueException($value, 'string');
}

$value = (string) $value;

if (0 === preg_match($constraint->regex, $value)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode(Slug::NOT_SLUG_ERROR)
->addViolation();
}
}
}
47 changes: 47 additions & 0 deletions 47 src/Symfony/Component/Validator/Tests/Constraints/SlugTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Validator\Tests\Constraints;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Constraints\Slug;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\AttributeLoader;

class SlugTest extends TestCase
{
public function testAttributes()
{
$metadata = new ClassMetadata(SlugDummy::class);
$loader = new AttributeLoader();
self::assertTrue($loader->loadClassMetadata($metadata));

[$bConstraint] = $metadata->properties['b']->getConstraints();
self::assertSame('myMessage', $bConstraint->message);
self::assertSame(['Default', 'SlugDummy'], $bConstraint->groups);

[$cConstraint] = $metadata->properties['c']->getConstraints();
self::assertSame(['my_group'], $cConstraint->groups);
self::assertSame('some attached data', $cConstraint->payload);
}
}

class SlugDummy
{
#[Slug]
private $a;

#[Slug(message: 'myMessage')]
private $b;

#[Slug(groups: ['my_group'], payload: 'some attached data')]
private $c;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Validator\Tests\Constraints;

use Symfony\Component\Validator\Constraints\Slug;
use Symfony\Component\Validator\Constraints\SlugValidator;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;

class SlugValidatorTest extends ConstraintValidatorTestCase
{
protected function createValidator(): SlugValidator
{
return new SlugValidator();
}

public function testNullIsValid()
{
$this->validator->validate(null, new Slug());

$this->assertNoViolation();
}

public function testEmptyStringIsValid()
{
$this->validator->validate('', new Slug());

$this->assertNoViolation();
}

public function testExpectsStringCompatibleType()
{
$this->expectException(UnexpectedValueException::class);
$this->validator->validate(new \stdClass(), new Slug());
}

/**
* @testWith ["test-slug"]
* ["slug-123-test"]
* ["slug"]
*/
public function testValidSlugs($slug)
{
$this->validator->validate($slug, new Slug());

$this->assertNoViolation();
}

/**
* @testWith ["NotASlug"]
* ["Not a slug"]
* ["not-á-slug"]
* ["not-@-slug"]
*/
public function testInvalidSlugs($slug)
{
$constraint = new Slug([
'message' => 'myMessage',
]);

$this->validator->validate($slug, $constraint);

$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$slug.'"')
->setCode(Slug::NOT_SLUG_ERROR)
->assertRaised();
}

/**
* @testWith ["test-slug", true]
* ["slug-123-test", true]
*/
public function testCustomRegexInvalidSlugs($slug)
{
$constraint = new Slug(regex: '/^[a-z0-9]+$/i');

$this->validator->validate($slug, $constraint);

$this->buildViolation($constraint->message)
->setParameter('{{ value }}', '"'.$slug.'"')
->setCode(Slug::NOT_SLUG_ERROR)
->assertRaised();
}

/**
* @testWith ["slug"]
* @testWith ["test1234"]
*/
public function testCustomRegexValidSlugs($slug)
{
$constraint = new Slug(regex: '/^[a-z0-9]+$/i');

$this->validator->validate($slug, $constraint);

$this->assertNoViolation();
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.