Last active
July 22, 2020 10:07
-
-
Save webdevilopers/31c8e39d786f2e02ecb2321f9c2486ac to your computer and use it in GitHub Desktop.
Symfony Validator Constraints Regex behaves differently to PHP preg_match condition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Improved by @freshp: