Skip to content

Instantly share code, notes, and snippets.

@webdevilopers
Last active July 22, 2020 10:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webdevilopers/31c8e39d786f2e02ecb2321f9c2486ac to your computer and use it in GitHub Desktop.
Save webdevilopers/31c8e39d786f2e02ecb2321f9c2486ac to your computer and use it in GitHub Desktop.
Symfony Validator Constraints Regex behaves differently to PHP preg_match condition
<?php
namespace Acme\PersonnelManagement\Application\Service\Person;
use Acme\Common\Domain\Model\FirstName;
use Symfony\Component\Validator\Constraints as Assert;
final class ChangeName
{
/**
* @var FirstName
* @Assert\NotNull
* @Assert\NotBlank
* @Assert\Type(type="string")
* @Assert\Regex(pattern="/^[\p{L}\\-\\. \']+$/u")
*/
private $firstName;
}
<?php
namespace Acme\Common\Domain\Model\PersonalName;
final class NamePolicy
{
public static function isSatisfiedBy(string $name): bool
{
if (empty($name)) {
return false;
}
// Allowed are unicode letters only and `.`, `-`, `'`, no numbers.
if (0 === preg_match("/^[\p{L}\\-\\. \']+$/u", $name)) {
return false;
}
// Continuous uppercase letters are not allowed.
if (1 === preg_match("/[\p{Lu}]{2,}/u", $name)) {
return false;
}
return true;
}
}
<?php
namespace Tests\Acme\Common\Domain\PersonalName;
use PHPUnit\Framework\TestCase;
use Acme\Common\Domain\Model\PersonalName\NamePolicy;
final class NamePolicyTest extends TestCase
{
/** @test */
public function hyphenSeparatedDoubleNamesAreAllowed(): void
{
$policy = NamePolicy::isSatisfiedBy('Hans-Werner');
$this->assertTrue($policy);
}
}
@webdevilopers
Copy link
Author

Improved by @freshp:

        // Allowed are unicode letters only and `.`, `-`, `'`, no numbers.
        if (1 !== preg_match("/^[\p{L}\-\.\s\']+$/u", $name)) {
            return false;
        }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment