Created
October 11, 2020 12:19
-
-
Save szabacsik/d4562dd8dec362205fe747f7f3828f6f to your computer and use it in GitHub Desktop.
PHP Validation & Assertion
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 | |
/* | |
* composer require symfony/validator | |
* composer require beberlei/assert | |
* composer require webmozart/assert | |
* composer require respect/validation | |
* composer require laminas/laminas-validator | |
* composer require laminas/laminas-servicemanager | |
{ | |
"require": { | |
"symfony/validator": "*", | |
"beberlei/assert": "*", | |
"webmozart/assert": "*", | |
"respect/validation": "*", | |
"laminas/laminas-validator": "*", | |
"laminas/laminas-servicemanager": "*" | |
} | |
} | |
*/ | |
declare(strict_types=1); | |
require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php'; | |
use Assert\Assert as BeberleiAssert; | |
use Assert\LazyAssertionException; | |
use Symfony\Component\Validator\Constraints\Length; | |
use Symfony\Component\Validator\Constraints\NotBlank; | |
use Symfony\Component\Validator\Constraints\Regex; | |
use Symfony\Component\Validator\Validation; | |
use Webmozart\Assert\Assert as WebmozartAssert; | |
use Respect\Validation\Exceptions\NestedValidationException; | |
use Respect\Validation\Validator as RespectValidator; | |
use Respect\Validation\Rules; | |
use Laminas\Validator\StringLength; | |
use Laminas\Validator\ValidatorChain; | |
$invalidString = '-lorem_Ipsum--dolor Sit-amet-'; | |
$validString = 'lorem-ipsum-dolor-sit_amet_consectetur-adipiscing-elit'; | |
$minimumLength = 2; | |
$maximumLength = 10; | |
$regexPattern = '/^(?!.*[-_]{2})(?=.*[a-z0-9]$)[a-z0-9][a-z0-9-_]*$/m'; | |
$validCharacterSet = [ | |
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', | |
't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-' | |
]; | |
/* | |
* Traditional Assertions | |
* https://www.php.net/manual/en/function.assert.php | |
*/ | |
assert(preg_match($regexPattern, $invalidString), 'This value is not valid.'); | |
echo(PHP_EOL . PHP_EOL); | |
/* | |
* Symfony Validator Component | |
* https://symfony.com/doc/current/validation.html | |
*/ | |
$validator = Validation::createValidator(); | |
$violations = $validator->validate($invalidString, [ | |
new NotBlank(['payload' => ['code' => 'error-0001']]), | |
new Length(['min' => $minimumLength, 'payload' => ['code' => 'error-0002']]), | |
new Length(['max' => $maximumLength, 'payload' => ['code' => 'error-0003']]), | |
new Regex(['pattern' => $regexPattern, 'payload' => ['code' => 'error-0004'], 'message' => 'This value is not valid. It must contains lowercase alphanumeric characters hyphens and underscores only.']) | |
]); | |
$errors = []; | |
if (0 !== count($violations)) { | |
foreach ($violations as $violation) { | |
$error = [ | |
'type' => get_class($violation->getConstraint()), | |
'code' => (isset($violation->getConstraint()->payload['code']) ? $violation->getConstraint()->payload['code'] : ''), | |
'message' => $violation->getMessage(), | |
'href' => 'http://www.example.com/documentations/errors', | |
]; | |
$errors[] = $error; | |
} | |
} | |
echo json_encode($errors, JSON_PRETTY_PRINT); | |
echo(PHP_EOL . PHP_EOL); | |
/* | |
* beberlei/assert | |
* https://packagist.org/packages/beberlei/assert | |
* https://github.com/beberlei/assert | |
*/ | |
$errors = []; | |
try { | |
BeberleiAssert::lazy() | |
->that($invalidString, 'error-0001')->notEmpty() | |
->that($invalidString, 'error-0002')->string() | |
->that($invalidString, 'error-0003')->betweenLength($minimumLength, $maximumLength) | |
->that($invalidString, 'error-0004')->startsWith('lorem') | |
->that($invalidString, 'error-0005')->endsWith('amet') | |
->that($invalidString, 'error-0006')->regex($regexPattern) | |
->verifyNow(); | |
} catch (LazyAssertionException $exception) { | |
foreach ($exception->getErrorExceptions() as $e) { | |
$error = [ | |
'type' => get_class($e), | |
'code' => $e->getPropertyPath(), | |
'message' => $e->getMessage(), | |
'href' => 'http://www.example.com/documentations/errors', | |
]; | |
$errors[] = $error; | |
} | |
} | |
echo json_encode($errors, JSON_PRETTY_PRINT); | |
echo(PHP_EOL . PHP_EOL); | |
/* | |
* webmozart/assert | |
* https://packagist.org/packages/webmozart/assert | |
* https://webmozart.github.io/assert/api/latest/class-Webmozart.Assert.Assert.html | |
* https://webmozart.io/ | |
*/ | |
try { | |
WebmozartAssert::notEmpty($invalidString); | |
WebmozartAssert::string($invalidString); | |
WebmozartAssert::notStartsWith($invalidString, '-'); | |
WebmozartAssert::notEndsWith($invalidString, '-'); | |
WebmozartAssert::lengthBetween($invalidString, $minimumLength, $maximumLength); | |
WebmozartAssert::regex($invalidString, $regexPattern); | |
} catch (Exception $exception) { | |
echo $exception; | |
//echo $exception->getCode().PHP_EOL; | |
//echo $exception->getMessage().PHP_EOL; | |
} | |
echo(PHP_EOL . PHP_EOL); | |
/* | |
* respect/validation | |
* https://packagist.org/packages/respect/validation | |
* https://respect-validation.readthedocs.io/en/latest/ | |
*/ | |
/* | |
$errors = []; | |
$validator = RespectValidator::stringType() | |
->notEmpty() | |
->length($minimumLength,$maximumLength) | |
->not(new Rules\StartsWith('-')) | |
->not(new Rules\EndsWith('-')) | |
->regex($regexPattern); | |
try { | |
$validator->check($invalidString); | |
}catch (InvalidArgumentException $exception) | |
{ | |
echo "That's bad."; | |
} | |
*/ | |
$validator = new Rules\AllOf( | |
new Rules\NotEmpty(), | |
new Rules\StringType(), | |
new Rules\Length($minimumLength, $maximumLength), | |
new Rules\Not(new Rules\StartsWith('-')), | |
new Rules\Not(new Rules\EndsWith('-')), | |
new Rules\Regex($regexPattern), | |
); | |
try { | |
$validator->assert($invalidString); | |
} catch (NestedValidationException $exception) { | |
foreach ($exception->getChildren() as $e) { | |
$error = [ | |
'type' => get_class($e), | |
'code' => '', | |
'message' => $e->getMessage(), | |
'href' => '' | |
]; | |
$errors[] = $error; | |
} | |
} | |
echo json_encode($errors, JSON_PRETTY_PRINT); | |
echo(PHP_EOL . PHP_EOL); | |
/* | |
* laminas-validator | |
* https://docs.laminas.dev/laminas-validator/ | |
* https://packagist.org/packages/laminas/laminas-validator | |
*/ | |
$errors = []; | |
$validatorChain = new ValidatorChain(); | |
$validatorChain->attach(new Laminas\Validator\NotEmpty(Laminas\Validator\NotEmpty::STRING)); | |
$validatorChain->attach(new StringLength(['min' => $minimumLength, 'max' => $maximumLength])); | |
$validatorChain->attach(new Laminas\Validator\Regex(['pattern' => $regexPattern])); | |
if ($validatorChain->isValid($invalidString)) { | |
echo 'ok' . PHP_EOL; | |
} else { | |
foreach ($validatorChain->getMessages() as $message) { | |
echo "$message\n"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment