RespectValidation
O mais incrível mecanismo de validação já criado para PHP
Sobre
• Biblioteca de validação criada por Alexandre Gaigalas (Alganet)
• PHP 5.3+ e HHVM 3.3+
• Interface fluente
• Mais de 100 regras de validação
• Mais de 175 mil instalações via Composer
• Média de 13 mil instalações por mês via Composer
Exemplo
• Obter dados via $_POST
• Validar se a chave “email” é um email válido
• Exibir mensagem de erro
Validator - Zend
use ZendInputFilterInput;
use ZendInputFilterInputFilter;
use ZendValidatorEmailAddress;
$email = new Input('email');
$email->getValidatorChain()
->attach(new EmailAddress());
$inputFilter = new InputFilter();
$inputFilter->add($email)
->setData($_POST);
if (!$inputFilter->isValid()) {
foreach ($inputFilter->getMessages() as $messages) {
echo current($messages);
break;
}
}
Validation - Illuminate
use IlluminateValidationFactory;
use SymfonyComponentTranslationTranslator;
$factory = new Factory(new Translator('en'));
$validator = $factory->make(
$_POST,
array('email' => 'required|email')
);
if ($validator->fails()) {
echo $validator->messages()->first();
}
Validator - Symfony
use SymfonyComponentValidatorValidation;
use SymfonyComponentValidatorConstraints as Assert;
$constraint = new AssertCollection(array(
'email' => new AssertEmail(),
));
$validator = Validation::createValidator();
$violations = $validator->validateValue($_POST, $constraint);
if (count($violations) > 0) {
echo $violations;
}
Validation - Respect
use RespectValidationValidator as v;
try {
v::key('email', v::email())->check($_POST);
} catch (Exception $exception) {
echo $exception->getMessage();
}
Validando
Método validate()
if (!v::email()->validate($input)) {
// ...
}
Método check()
try {
v::stringType()->length(2, 15)->check(0);
} catch (ValidationExceptionInterface $exception) {
echo $exception->getMainMessage();
}
// Resultado:
//
// 0 must be a string
Método check()
try {
v::stringType()->length(2, 15)->check('A');
} catch (ValidationExceptionInterface $exception) {
echo $exception->getMainMessage();
}
// Resultado:
//
// "A" must have a length between 2 and 15
Método assert()
try {
v::stringType()->length(2, 15)->assert(0);
} catch (NestedValidationExceptionInterface $exception) {
echo $exception->getFullMessage();
}
// Resultado:
//
// -All of the required rules must pass for 0
// |-0 must be a string
// -0 must have a length between 2 and 15
E se eu quiser…
Não utilizar estáticos
use RespectValidationRules;
use RespectValidationValidator;
$validator = new Validator();
$validator->addRule(new RulesKey('email', new RulesEmail()));
$validator->assert($_POST);
Reutilizar cadeia de validação
$validator = v::stringType()->length(2, 15);
$validator->assert($input1);
$validator->check($input2);
if ($validator->validate($input3)) {
// ...
}
if ($validator($input4)) {
// ...
}
Obter as mensagens em formato
de array
try {
v::stringType()->length(2, 15)->assert(0);
} catch (NestedValidationExceptionInterface $exception) {
print_r($exception->getMessages());
}
// Resultado:
//
// Array
// (
// [0] => 0 must be a string
// [1] => 0 must have a length between 2 and 15
// )
Traduzir mensagens
try {
v::stringType()->length(2, 15)->check(0);
} catch (ValidationException $exception) {
$exception->setParam('translator', 'gettext');
// ...
}
Customizar mensagens1
try {
v::stringType()->length(2, 15)->assert(0);
} catch (NestedValidationExceptionInterface $exception) {
$messages = $exception->findMessages(array(
'stringType' => 'Valor precisa ser uma string',
'length' => 'Valor precisa conter de 2 a 15 caracteres',
));
print_r($messages);
}
// Resultado:
//
// Array
// (
// [stringType] => Valor precisa ser uma string
// [length] => Valor precisa conter de 2 a 15 caracteres
// )
Customizar mensagens2
try {
v::key('email', v::email())->assert(0);
} catch (NestedValidationExceptionInterface $exception) {
$messages = $exception->findMessages(array(
'email' => ‘Você precisa fornecer um email válido'
));
print_r($messages);
}
// Resultado:
//
// Array
// (
// [email] => Você precisa fornecer um email válido
// )
Trabalhar com valores opcionais
v::optional(v::email())->validate(''); // true
v::optional(v::email())->validate(null); // true
Inverter uma regra
v::not(v::equals('foo'))->validate('bar'); //true
v::not(v::equals('foo'))->validate('foo'); //false
Utilizar minhas próprias regras
v::with('MyValidationRules');
v::myRule(); // Tenta carregar "MyValidationRulesMyRule" se existir
Como testar?
Regra: IntType
<?php
namespace RespectValidationRules;
class IntType extends AbstractRule
{
public function validate($input)
{
return is_int($input);
}
}
Teste unitário: IntTypeTest
namespace RespectValidationRules;
/**
* @group rule
* @covers RespectValidationRulesIntType
*/
class IntTypeTest extends PHPUnit_Framework_TestCase
{
}
Teste1: Sucesso
// ...
public function providerForValidIntType()
{
return array(
array(0),
array(123456),
array(PHP_INT_MAX),
array(PHP_INT_MAX * -1),
);
}
/**
* @dataProvider providerForValidIntType
*/
public function testShouldValidateInputWhenItIsAValidIntType($input)
{
$rule = new IntType();
$this->assertTrue($rule->validate($input));
}
// ...
Teste2: Falha
// ...
public function providerForInvalidIntType()
{
return array(
array('1'),
array(1.0),
array(PHP_INT_MAX + 1),
array(true),
);
}
/**
* @dataProvider providerForInvalidIntType
*/
public function testShouldInvalidateInputWhenItIsNotAValidIntType($input)
{
$rule = new IntType();
$this->assertFalse($rule->validate($input));
}
// ...
Exception: IntTypeException
namespace RespectValidationExceptions;
class IntTypeException extends ValidationException
{
public static $defaultTemplates = array(
self::MODE_DEFAULT => array(
self::STANDARD => '{{name}} must be an integer',
),
self::MODE_NEGATIVE => array(
self::STANDARD => '{{name}} must not be an integer',
),
);
}
Teste de integração: PHPT
--FILE--
<?php
require 'vendor/autoload.php';
use RespectValidationValidator as v;
// ..
?>
--EXPECTF--
Teste1: intType_1.phpt
--FILE--
<?php
require 'vendor/autoload.php';
use RespectValidationValidator as v;
v::intType()->assert(42);
v::intType()->check(1984);
?>
--EXPECTF--
Teste2: intType_2.phpt
--FILE--
<?php
require 'vendor/autoload.php';
use RespectValidationValidator as v;
use RespectValidationExceptionsIntTypeException;
try {
v::intType()->check('42');
} catch (IntTypeException $exception) {
echo $exception->getMainMessage();
}
?>
--EXPECTF--
"42" must be an integer
Teste3: intType_3.phpt
--FILE--
<?php
require 'vendor/autoload.php';
use RespectValidationValidator as v;
use RespectValidationExceptionsAllOfException;
try {
v::intType()->assert('1984');
} catch (AllOfException $exception) {
echo $exception->getFullMessage();
}
?>
--EXPECTF--
-"1984" must be an integer
Teste4: intType_4.phpt
--FILE--
<?php
require 'vendor/autoload.php';
use RespectValidationValidator as v;
use RespectValidationExceptionsIntTypeException;
try {
v::not(v::intType())->check(42);
} catch (IntTypeException $exception) {
echo $exception->getMainMessage();
}
?>
--EXPECTF--
42 must not be an integer
Teste5: intType_5.phpt
--FILE--
<?php
require 'vendor/autoload.php';
use RespectValidationValidator as v;
use RespectValidationExceptionsAllOfException;
try {
v::not(v::intType())->assert(1984);
} catch (AllOfException $exception) {
echo $exception->getFullMessage();
}
?>
--EXPECTF--
-1984 must not be an integer
Como não testar?
/**
* @dataProvider providerForValidIntType
*/
public function testShouldValidateInputWhenItIsAValidIntType($input)
{
$rule = new IntType();
$this->assertTrue($rule->__invoke($input));
$this->assertTrue($rule->validate($input));
$this->assertTrue($rule->check($input));
$this->assertTrue($rule->assert($input))
}
/**
* @dataProvider providerForValidIntType
*/
public function testShouldValidateInputWhenItIsAValidIntType($input)
{
$rule = new IntType();
$this->assertTrue($rule->__invoke($input));
$this->assertTrue($rule->validate($input));
$this->assertTrue($rule->check($input));
$this->assertTrue($rule->assert($input))
}
/**
* @dataProvider providerForInvalidIntType
* @expectedException RespectValidationExceptionsIntTypeException
*/
public function testShouldInvalidateInputWhenItIsNotAValidIntType($input)
{
$rule = new IntType();
$this->assertFalse($rule->check($input));
$this->assertFalse($rule->assert($input));
}
/**
* @dataProvider providerForInvalidIntType
* @expectedException RespectValidationExceptionsIntTypeException
*/
public function testShouldInvalidateInputWhenItIsNotAValidIntType($input)
{
$rule = new IntType();
$this->assertFalse($rule->check($input));
$this->assertFalse($rule->assert($input));
}
/**
* @dataProvider providerForInvalidIntType
* @expectedException RespectValidationExceptionsIntTypeException
*/
public function testShouldInvalidateInputWhenItIsNotAValidIntType($input)
{
$rule = new IntType();
$this->assertFalse($rule->check($input));
}
/**
* @dataProvider providerForInvalidIntType
* @expectedException RespectValidationExceptionsIntTypeException
*/
public function testShouldInvalidateInputWhenItIsNotAValidIntType($input)
{
$rule = new IntType();
$this->assertFalse($rule->check($input));
}
Let’s test!

TestFest - Respect\Validation 1.0

  • 1.
    RespectValidation O mais incrívelmecanismo de validação já criado para PHP
  • 2.
    Sobre • Biblioteca devalidação criada por Alexandre Gaigalas (Alganet) • PHP 5.3+ e HHVM 3.3+ • Interface fluente • Mais de 100 regras de validação • Mais de 175 mil instalações via Composer • Média de 13 mil instalações por mês via Composer
  • 3.
  • 4.
    • Obter dadosvia $_POST • Validar se a chave “email” é um email válido • Exibir mensagem de erro
  • 5.
    Validator - Zend useZendInputFilterInput; use ZendInputFilterInputFilter; use ZendValidatorEmailAddress; $email = new Input('email'); $email->getValidatorChain() ->attach(new EmailAddress()); $inputFilter = new InputFilter(); $inputFilter->add($email) ->setData($_POST); if (!$inputFilter->isValid()) { foreach ($inputFilter->getMessages() as $messages) { echo current($messages); break; } }
  • 6.
    Validation - Illuminate useIlluminateValidationFactory; use SymfonyComponentTranslationTranslator; $factory = new Factory(new Translator('en')); $validator = $factory->make( $_POST, array('email' => 'required|email') ); if ($validator->fails()) { echo $validator->messages()->first(); }
  • 7.
    Validator - Symfony useSymfonyComponentValidatorValidation; use SymfonyComponentValidatorConstraints as Assert; $constraint = new AssertCollection(array( 'email' => new AssertEmail(), )); $validator = Validation::createValidator(); $violations = $validator->validateValue($_POST, $constraint); if (count($violations) > 0) { echo $violations; }
  • 8.
    Validation - Respect useRespectValidationValidator as v; try { v::key('email', v::email())->check($_POST); } catch (Exception $exception) { echo $exception->getMessage(); }
  • 9.
  • 10.
  • 11.
    Método check() try { v::stringType()->length(2,15)->check(0); } catch (ValidationExceptionInterface $exception) { echo $exception->getMainMessage(); } // Resultado: // // 0 must be a string
  • 12.
    Método check() try { v::stringType()->length(2,15)->check('A'); } catch (ValidationExceptionInterface $exception) { echo $exception->getMainMessage(); } // Resultado: // // "A" must have a length between 2 and 15
  • 13.
    Método assert() try { v::stringType()->length(2,15)->assert(0); } catch (NestedValidationExceptionInterface $exception) { echo $exception->getFullMessage(); } // Resultado: // // -All of the required rules must pass for 0 // |-0 must be a string // -0 must have a length between 2 and 15
  • 14.
    E se euquiser…
  • 15.
    Não utilizar estáticos useRespectValidationRules; use RespectValidationValidator; $validator = new Validator(); $validator->addRule(new RulesKey('email', new RulesEmail())); $validator->assert($_POST);
  • 16.
    Reutilizar cadeia devalidação $validator = v::stringType()->length(2, 15); $validator->assert($input1); $validator->check($input2); if ($validator->validate($input3)) { // ... } if ($validator($input4)) { // ... }
  • 17.
    Obter as mensagensem formato de array try { v::stringType()->length(2, 15)->assert(0); } catch (NestedValidationExceptionInterface $exception) { print_r($exception->getMessages()); } // Resultado: // // Array // ( // [0] => 0 must be a string // [1] => 0 must have a length between 2 and 15 // )
  • 18.
    Traduzir mensagens try { v::stringType()->length(2,15)->check(0); } catch (ValidationException $exception) { $exception->setParam('translator', 'gettext'); // ... }
  • 19.
    Customizar mensagens1 try { v::stringType()->length(2,15)->assert(0); } catch (NestedValidationExceptionInterface $exception) { $messages = $exception->findMessages(array( 'stringType' => 'Valor precisa ser uma string', 'length' => 'Valor precisa conter de 2 a 15 caracteres', )); print_r($messages); } // Resultado: // // Array // ( // [stringType] => Valor precisa ser uma string // [length] => Valor precisa conter de 2 a 15 caracteres // )
  • 20.
    Customizar mensagens2 try { v::key('email',v::email())->assert(0); } catch (NestedValidationExceptionInterface $exception) { $messages = $exception->findMessages(array( 'email' => ‘Você precisa fornecer um email válido' )); print_r($messages); } // Resultado: // // Array // ( // [email] => Você precisa fornecer um email válido // )
  • 21.
    Trabalhar com valoresopcionais v::optional(v::email())->validate(''); // true v::optional(v::email())->validate(null); // true
  • 22.
    Inverter uma regra v::not(v::equals('foo'))->validate('bar');//true v::not(v::equals('foo'))->validate('foo'); //false
  • 23.
    Utilizar minhas própriasregras v::with('MyValidationRules'); v::myRule(); // Tenta carregar "MyValidationRulesMyRule" se existir
  • 24.
  • 25.
    Regra: IntType <?php namespace RespectValidationRules; classIntType extends AbstractRule { public function validate($input) { return is_int($input); } }
  • 26.
    Teste unitário: IntTypeTest namespaceRespectValidationRules; /** * @group rule * @covers RespectValidationRulesIntType */ class IntTypeTest extends PHPUnit_Framework_TestCase { }
  • 27.
    Teste1: Sucesso // ... publicfunction providerForValidIntType() { return array( array(0), array(123456), array(PHP_INT_MAX), array(PHP_INT_MAX * -1), ); } /** * @dataProvider providerForValidIntType */ public function testShouldValidateInputWhenItIsAValidIntType($input) { $rule = new IntType(); $this->assertTrue($rule->validate($input)); } // ...
  • 28.
    Teste2: Falha // ... publicfunction providerForInvalidIntType() { return array( array('1'), array(1.0), array(PHP_INT_MAX + 1), array(true), ); } /** * @dataProvider providerForInvalidIntType */ public function testShouldInvalidateInputWhenItIsNotAValidIntType($input) { $rule = new IntType(); $this->assertFalse($rule->validate($input)); } // ...
  • 29.
    Exception: IntTypeException namespace RespectValidationExceptions; classIntTypeException extends ValidationException { public static $defaultTemplates = array( self::MODE_DEFAULT => array( self::STANDARD => '{{name}} must be an integer', ), self::MODE_NEGATIVE => array( self::STANDARD => '{{name}} must not be an integer', ), ); }
  • 30.
    Teste de integração:PHPT --FILE-- <?php require 'vendor/autoload.php'; use RespectValidationValidator as v; // .. ?> --EXPECTF--
  • 31.
    Teste1: intType_1.phpt --FILE-- <?php require 'vendor/autoload.php'; useRespectValidationValidator as v; v::intType()->assert(42); v::intType()->check(1984); ?> --EXPECTF--
  • 32.
    Teste2: intType_2.phpt --FILE-- <?php require 'vendor/autoload.php'; useRespectValidationValidator as v; use RespectValidationExceptionsIntTypeException; try { v::intType()->check('42'); } catch (IntTypeException $exception) { echo $exception->getMainMessage(); } ?> --EXPECTF-- "42" must be an integer
  • 33.
    Teste3: intType_3.phpt --FILE-- <?php require 'vendor/autoload.php'; useRespectValidationValidator as v; use RespectValidationExceptionsAllOfException; try { v::intType()->assert('1984'); } catch (AllOfException $exception) { echo $exception->getFullMessage(); } ?> --EXPECTF-- -"1984" must be an integer
  • 34.
    Teste4: intType_4.phpt --FILE-- <?php require 'vendor/autoload.php'; useRespectValidationValidator as v; use RespectValidationExceptionsIntTypeException; try { v::not(v::intType())->check(42); } catch (IntTypeException $exception) { echo $exception->getMainMessage(); } ?> --EXPECTF-- 42 must not be an integer
  • 35.
    Teste5: intType_5.phpt --FILE-- <?php require 'vendor/autoload.php'; useRespectValidationValidator as v; use RespectValidationExceptionsAllOfException; try { v::not(v::intType())->assert(1984); } catch (AllOfException $exception) { echo $exception->getFullMessage(); } ?> --EXPECTF-- -1984 must not be an integer
  • 36.
  • 37.
    /** * @dataProvider providerForValidIntType */ publicfunction testShouldValidateInputWhenItIsAValidIntType($input) { $rule = new IntType(); $this->assertTrue($rule->__invoke($input)); $this->assertTrue($rule->validate($input)); $this->assertTrue($rule->check($input)); $this->assertTrue($rule->assert($input)) }
  • 38.
    /** * @dataProvider providerForValidIntType */ publicfunction testShouldValidateInputWhenItIsAValidIntType($input) { $rule = new IntType(); $this->assertTrue($rule->__invoke($input)); $this->assertTrue($rule->validate($input)); $this->assertTrue($rule->check($input)); $this->assertTrue($rule->assert($input)) }
  • 39.
    /** * @dataProvider providerForInvalidIntType *@expectedException RespectValidationExceptionsIntTypeException */ public function testShouldInvalidateInputWhenItIsNotAValidIntType($input) { $rule = new IntType(); $this->assertFalse($rule->check($input)); $this->assertFalse($rule->assert($input)); }
  • 40.
    /** * @dataProvider providerForInvalidIntType *@expectedException RespectValidationExceptionsIntTypeException */ public function testShouldInvalidateInputWhenItIsNotAValidIntType($input) { $rule = new IntType(); $this->assertFalse($rule->check($input)); $this->assertFalse($rule->assert($input)); }
  • 41.
    /** * @dataProvider providerForInvalidIntType *@expectedException RespectValidationExceptionsIntTypeException */ public function testShouldInvalidateInputWhenItIsNotAValidIntType($input) { $rule = new IntType(); $this->assertFalse($rule->check($input)); }
  • 42.
    /** * @dataProvider providerForInvalidIntType *@expectedException RespectValidationExceptionsIntTypeException */ public function testShouldInvalidateInputWhenItIsNotAValidIntType($input) { $rule = new IntType(); $this->assertFalse($rule->check($input)); }
  • 43.