testfest - respect\validation 1.0

43
Respect\Validation O mais incrível mecanismo de validação já criado para PHP

Upload: henrique-moody

Post on 13-Apr-2017

930 views

Category:

Software


1 download

TRANSCRIPT

Page 1: TestFest - Respect\Validation 1.0

Respect\ValidationO mais incrível mecanismo de validação já criado para PHP

Page 2: TestFest - Respect\Validation 1.0

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

Page 3: TestFest - Respect\Validation 1.0

Exemplo

Page 4: TestFest - Respect\Validation 1.0

• Obter dados via $_POST

• Validar se a chave “email” é um email válido

• Exibir mensagem de erro

Page 5: TestFest - Respect\Validation 1.0

Validator - Zenduse Zend\InputFilter\Input;use Zend\InputFilter\InputFilter;use Zend\Validator\EmailAddress;

$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; }}

Page 6: TestFest - Respect\Validation 1.0

Validation - Illuminateuse Illuminate\Validation\Factory;use Symfony\Component\Translation\Translator;

$factory = new Factory(new Translator('en'));$validator = $factory->make( $_POST, array('email' => 'required|email'));

if ($validator->fails()) { echo $validator->messages()->first();}

Page 7: TestFest - Respect\Validation 1.0

Validator - Symfonyuse Symfony\Component\Validator\Validation;use Symfony\Component\Validator\Constraints as Assert;

$constraint = new Assert\Collection(array( 'email' => new Assert\Email(),));

$validator = Validation::createValidator();$violations = $validator->validateValue($_POST, $constraint);if (count($violations) > 0) { echo $violations;}

Page 8: TestFest - Respect\Validation 1.0

Validation - Respectuse Respect\Validation\Validator as v;

try { v::key('email', v::email())->check($_POST);} catch (Exception $exception) { echo $exception->getMessage();}

Page 9: TestFest - Respect\Validation 1.0

Validando

Page 10: TestFest - Respect\Validation 1.0

Método validate()if (!v::email()->validate($input)) { // ...}

Page 11: TestFest - Respect\Validation 1.0

Método check()try { v::stringType()->length(2, 15)->check(0);} catch (ValidationExceptionInterface $exception) { echo $exception->getMainMessage();}

// Resultado://// 0 must be a string

Page 12: TestFest - Respect\Validation 1.0

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

Page 13: TestFest - Respect\Validation 1.0

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

Page 14: TestFest - Respect\Validation 1.0

E se eu quiser…

Page 15: TestFest - Respect\Validation 1.0

Não utilizar estáticosuse Respect\Validation\Rules;use Respect\Validation\Validator;

$validator = new Validator();$validator->addRule(new Rules\Key('email', new Rules\Email()));$validator->assert($_POST);

Page 16: TestFest - Respect\Validation 1.0

Reutilizar cadeia de validação$validator = v::stringType()->length(2, 15);

$validator->assert($input1);$validator->check($input2);

if ($validator->validate($input3)) { // ...}

if ($validator($input4)) { // ...}

Page 17: TestFest - Respect\Validation 1.0

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// )

Page 18: TestFest - Respect\Validation 1.0

Traduzir mensagenstry { v::stringType()->length(2, 15)->check(0);} catch (ValidationException $exception) { $exception->setParam('translator', 'gettext'); // ...}

Page 19: TestFest - Respect\Validation 1.0

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// )

Page 20: TestFest - Respect\Validation 1.0

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// )

Page 21: TestFest - Respect\Validation 1.0

Trabalhar com valores opcionaisv::optional(v::email())->validate(''); // truev::optional(v::email())->validate(null); // true

Page 22: TestFest - Respect\Validation 1.0

Inverter uma regrav::not(v::equals('foo'))->validate('bar'); //truev::not(v::equals('foo'))->validate('foo'); //false

Page 23: TestFest - Respect\Validation 1.0

Utilizar minhas próprias regrasv::with('My\\Validation\\Rules\\');v::myRule(); // Tenta carregar "My\Validation\Rules\MyRule" se existir

Page 24: TestFest - Respect\Validation 1.0

Como testar?

Page 25: TestFest - Respect\Validation 1.0

Regra: IntType<?php

namespace Respect\Validation\Rules;

class IntType extends AbstractRule{ public function validate($input) { return is_int($input); }}

Page 26: TestFest - Respect\Validation 1.0

Teste unitário: IntTypeTestnamespace Respect\Validation\Rules;

/** * @group rule * @covers Respect\Validation\Rules\IntType */class IntTypeTest extends \PHPUnit_Framework_TestCase{}

Page 27: TestFest - Respect\Validation 1.0

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)); } // ...

Page 28: TestFest - Respect\Validation 1.0

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)); } // ...

Page 29: TestFest - Respect\Validation 1.0

Exception: IntTypeExceptionnamespace Respect\Validation\Exceptions;

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', ), );}

Page 30: TestFest - Respect\Validation 1.0

Teste de integração: PHPT--FILE--<?phprequire 'vendor/autoload.php';

use Respect\Validation\Validator as v;

// ..?>--EXPECTF--

Page 31: TestFest - Respect\Validation 1.0

Teste1: intType_1.phpt--FILE--<?phprequire 'vendor/autoload.php';

use Respect\Validation\Validator as v;

v::intType()->assert(42);v::intType()->check(1984);?>--EXPECTF--

Page 32: TestFest - Respect\Validation 1.0

Teste2: intType_2.phpt--FILE--<?phprequire 'vendor/autoload.php';

use Respect\Validation\Validator as v;use Respect\Validation\Exceptions\IntTypeException;

try { v::intType()->check('42');} catch (IntTypeException $exception) { echo $exception->getMainMessage();}?>--EXPECTF--"42" must be an integer

Page 33: TestFest - Respect\Validation 1.0

Teste3: intType_3.phpt--FILE--<?phprequire 'vendor/autoload.php';

use Respect\Validation\Validator as v;use Respect\Validation\Exceptions\AllOfException;

try { v::intType()->assert('1984');} catch (AllOfException $exception) { echo $exception->getFullMessage();}?>--EXPECTF--\-"1984" must be an integer

Page 34: TestFest - Respect\Validation 1.0

Teste4: intType_4.phpt--FILE--<?phprequire 'vendor/autoload.php';

use Respect\Validation\Validator as v;use Respect\Validation\Exceptions\IntTypeException;

try { v::not(v::intType())->check(42);} catch (IntTypeException $exception) { echo $exception->getMainMessage();}?>--EXPECTF--42 must not be an integer

Page 35: TestFest - Respect\Validation 1.0

Teste5: intType_5.phpt--FILE--<?phprequire 'vendor/autoload.php';

use Respect\Validation\Validator as v;use Respect\Validation\Exceptions\AllOfException;

try { v::not(v::intType())->assert(1984);} catch (AllOfException $exception) { echo $exception->getFullMessage();}?>--EXPECTF--\-1984 must not be an integer

Page 36: TestFest - Respect\Validation 1.0

Como não testar?

Page 37: TestFest - Respect\Validation 1.0

/** * @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)) }

Page 38: TestFest - Respect\Validation 1.0

/** * @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)) }

Page 39: TestFest - Respect\Validation 1.0

/** * @dataProvider providerForInvalidIntType * @expectedException Respect\Validation\Exceptions\IntTypeException */ public function testShouldInvalidateInputWhenItIsNotAValidIntType($input) { $rule = new IntType();

$this->assertFalse($rule->check($input)); $this->assertFalse($rule->assert($input)); }

Page 40: TestFest - Respect\Validation 1.0

/** * @dataProvider providerForInvalidIntType * @expectedException Respect\Validation\Exceptions\IntTypeException */ public function testShouldInvalidateInputWhenItIsNotAValidIntType($input) { $rule = new IntType();

$this->assertFalse($rule->check($input)); $this->assertFalse($rule->assert($input)); }

Page 41: TestFest - Respect\Validation 1.0

/** * @dataProvider providerForInvalidIntType * @expectedException Respect\Validation\Exceptions\IntTypeException */ public function testShouldInvalidateInputWhenItIsNotAValidIntType($input) { $rule = new IntType();

$this->assertFalse($rule->check($input)); }

Page 42: TestFest - Respect\Validation 1.0

/** * @dataProvider providerForInvalidIntType * @expectedException Respect\Validation\Exceptions\IntTypeException */ public function testShouldInvalidateInputWhenItIsNotAValidIntType($input) { $rule = new IntType();

$this->assertFalse($rule->check($input)); }

Page 43: TestFest - Respect\Validation 1.0

Let’s test!