Domine Validação de Dados em 45min

Preview:

Citation preview

30 de Novembro PHP Conference 2012 1

Domine

Validação de Dadosem 45min

30 de Novembro PHP Conference 2012 2

Alexandre Gaigalashttp://about.me/alganet

30 de Novembro PHP Conference 2012 3

@alganet

30 de Novembro PHP Conference 2012 4

@alganet

Alfanumérico

30 de Novembro PHP Conference 2012 5

@alganet

Alfanumérico Aceita _

30 de Novembro PHP Conference 2012 6

@alganet

Alfanumérico Aceita _

Sem espaços

30 de Novembro PHP Conference 2012 7

@alganet

Alfanumérico Aceita _

1-15 caracteresSem espaços

30 de Novembro PHP Conference 2012 8

@alganet

Alfanumérico Aceita _

1-15 caracteresSem espaços

/^[[:alnum:]_]{1,15}$/(Expressão Regular)

30 de Novembro PHP Conference 2012 9

@alexandre_gomes_gaigalas

Alfanumérico Aceita _

1-15 caracteresSem espaços

/^[[:alnum:]_]{1,15}$/

30 de Novembro PHP Conference 2012 10

@al-ga-net

Alfanumérico Aceita _

1-15 caracteresSem espaços

/^[[:alnum:]_]{1,15}$/

30 de Novembro PHP Conference 2012 11

@Alexandre Gomes

Alfanumérico Aceita _

1-15 caracteresSem espaços

/^[[:alnum:]_]{1,15}$/

30 de Novembro PHP Conference 2012 12

E se eu quiser exibir os erros?

30 de Novembro PHP Conference 2012 13

@alganet

Alfanumérico Aceita _

1-15 caracteresSem espaços

if (!ctype_alnum(str_replace('_', '', $username))) echo “Username pode conter apenas letras, números e _”;

30 de Novembro PHP Conference 2012 14

@alganet

Alfanumérico Aceita _

1-15 caracteresSem espaços

if (!ctype_alnum(str_replace('_', '', $username))) echo “Username pode conter apenas letras, números e _”;if (strlen($username) < 1 || strlen($username) > 15) echo “Username pode conter de 1 a 15 caracteres”;

30 de Novembro PHP Conference 2012 15

@alganet

Alfanumérico Aceita _

1-15 caracteresSem espaços

$e = array();if (!ctype_alnum(str_replace('_', '', $username))) $e[] = “Username pode conter apenas letras, números e _”;if (strlen($username) < 1 || strlen($username) > 15) $e[] = “Username pode conter de 1 a 15 caracteres”;if ($e) echo implode($e);

30 de Novembro PHP Conference 2012 16

E o erro para o “Sem espaços”?

30 de Novembro PHP Conference 2012 17

@alganet

Alfanumérico Aceita _

1-15 caracteresSem espaços

$e = array();if (!ctype_alnum(str_replace('_', '', $username))) $e[] = “Username pode conter apenas letras, números e _”;if (strlen($username) < 1 || strlen($username) > 15) $e[] = “Username pode conter de 1 a 15 caracteres”;if (false !== strpos($username, “ ”) $e[] = “Username não pode conter espaços”;/*...*/

30 de Novembro PHP Conference 2012 18

Validation

30 de Novembro PHP Conference 2012 19

use Respect\Validation\Rules as r;

$validator = new r\AllOf(

);

Construindo um Validator

30 de Novembro PHP Conference 2012 20

use Respect\Validation\Rules as r;

$validator = new r\AllOf( new r\Alnum(“_”)

);

Construindo um Validator

30 de Novembro PHP Conference 2012 21

use Respect\Validation\Rules as r;

$validator = new r\AllOf( new r\Alnum(“_”), new r\NoWhitespace );

Construindo um Validator

30 de Novembro PHP Conference 2012 22

use Respect\Validation\Rules as r;

$validator = new r\AllOf( new r\Alnum(“_”), new r\NoWhitespace, new r\Length(1, 15));

Construindo um Validator

30 de Novembro PHP Conference 2012 23

use Respect\Validation\Rules as r;

$validator = new r\AllOf( new r\Alnum(“_”), new r\NoWhitespace, new r\Length(1, 15));

$isOk = $validator->validate(“alganet”);

Construindo um Validator

30 de Novembro PHP Conference 2012 24

Tem um jeito mais simples?

30 de Novembro PHP Conference 2012 25

use Respect\Validation\Validator as v;

$validator = v::alnum('_') ->noWhitespace() ->length(1, 15);

$isOk = $validator->validate(“alganet”);

Construção via Fluent Builder

30 de Novembro PHP Conference 2012 26

//true or false$validator->validate($algo);

30 de Novembro PHP Conference 2012 27

E se eu quiser coletar os erros?

30 de Novembro PHP Conference 2012 28

try { $validator->check(“e ae”);} catch (InvalidArgumentException $e) { echo $e->getMessage();}

30 de Novembro PHP Conference 2012 29

use Respect\Validation\Exceptions as e;

/* … */

try { $validator->check(“e ae”);} catch (e\AlnumException $e) { //faz algo} catch (e\NoWhitespaceException $e) { //faz algo} catch (e\LengthException $e) { //faz algo}

30 de Novembro PHP Conference 2012 30

//Dispara exception para o primeiro//erro$validator->check($algo);

30 de Novembro PHP Conference 2012 31

E se eu quiser todos os erros?

30 de Novembro PHP Conference 2012 32

try { $validator->assert(“e ae”);} catch (InvalidArgumentException $e) { echo $e->getFullMessage();}

30 de Novembro PHP Conference 2012 33

\-All of the 3 required rules must pass |-"td errado#" must contain only letters (a-z) | and digits (0-9) |-"td errado#" must not contain whitespace \-"td errado#" must have a length between 1 and 15

$validator->assert(“td errado#”);

30 de Novembro PHP Conference 2012 34

E se eu quiser agrupar só alguns erros?

30 de Novembro PHP Conference 2012 35

try { $validator->assert(“e ae”);} catch (InvalidArgumentException $e) { $e->findMessages(array( 'alnum', 'length' ));}

30 de Novembro PHP Conference 2012 36

E se eu quiser mensagens diferentes?

30 de Novembro PHP Conference 2012 37

try { $validator->assert(“e ae”);} catch (InvalidArgumentException $e) { $e->findMessages(array( 'alnum' => “{{name}} Inválido”, 'length' => “Tamanho de {{name}} incorreto” ));}

30 de Novembro PHP Conference 2012 38

//Dispara exception com todos os erros$validator->assert($algo);

30 de Novembro PHP Conference 2012 39

E se eu quiser validar objetos inteiros?

30 de Novembro PHP Conference 2012 40

class Tweet { public $text; public $created_at; public $user;}

class User{ public $name;}

30 de Novembro PHP Conference 2012 41

$user = new User;$user->name = 'alganet';

$tweet = new Tweet;$tweet->user = $user;$tweet->text = “http://respect.li”; $tweet->created_at = new DateTime;

30 de Novembro PHP Conference 2012 42

$tweetValidator = v::object() ->instance(“Tweet”) ->attribute(“text”, v::string()->length(1, 140)) ->attribute(“created_at”, v::date()) ->attribute(“user”, v::object() ->instance(“User”) ->attribute(“name”, $usernameValidator)) );

30 de Novembro PHP Conference 2012 43

$tweetValidator = v::object() ->instance(“Tweet”) ->attribute(“text”, v::string()->length(1, 140)) ->attribute(“created_at”, v::date()) ->attribute(“user”, v::object() ->instance(“User”) ->attribute(“name”, $usernameValidator)) );

30 de Novembro PHP Conference 2012 44

$tweetValidator = v::object() ->instance(“Tweet”) ->attribute(“text”, v::string()->length(1, 140)) ->attribute(“created_at”, v::date()) ->attribute(“user”, v::object() ->instance(“User”) ->attribute(“name”, $usernameValidator)) );

30 de Novembro PHP Conference 2012 45

$tweetValidator = v::object() ->instance(“Tweet”) ->attribute(“text”, v::string()->length(1, 140)) ->attribute(“created_at”, v::date()) ->attribute(“user”, v::object() ->instance(“User”) ->attribute(“name”, $usernameValidator)) );

30 de Novembro PHP Conference 2012 46

$tweetValidator = v::object() ->instance(“Tweet”) ->attribute(“text”, v::string()->length(1, 140)) ->attribute(“created_at”, v::date()) ->attribute(“user”, v::object() ->instance(“User”) ->attribute(“name”, $usernameValidator)) );

30 de Novembro PHP Conference 2012 47

//Valida atributos de objetosv::object()->attribute(“name”);

//Valida chaves de arrayv::arr()->key(“email”);

30 de Novembro PHP Conference 2012 48

//Valida atributos de objetosv::object()->attribute(“name”) //N atributos... ->attribute(“sex”);

//Valida chaves de arrayv::arr()->key(“email”) ->key(“sex”);

30 de Novembro PHP Conference 2012 49

//Valida atributos de objetosv::object()->attribute(“name”) //N atributos... ->attribute(“sex”, //Valida o valor também v::in('F', 'M'));

//Valida chaves de arrayv::arr()->key(“email”) ->key(“sex”, v::in('F', 'M'));

30 de Novembro PHP Conference 2012 50

E se eu quiser negar uma regra?

30 de Novembro PHP Conference 2012 51

//Nega qualquer regrav::not(v::string());

30 de Novembro PHP Conference 2012 52

E as mensagens pra regras negadas?

30 de Novembro PHP Conference 2012 53

//”123” must be a stringv::string()->check(123);

//”bla bla” must not be a stringv::not(v::string())->check('bla bla');

30 de Novembro PHP Conference 2012 54

Dá pra mudar o “123” e “bla bla” nas mensagens?

30 de Novembro PHP Conference 2012 55

//Nome Completo must be a stringv::string() ->setName(“Nome Completo”) ->check(123);

//Idade must not be a stringv::not(v::string()) ->setName(“Idade”) ->check('bla bla');

30 de Novembro PHP Conference 2012 56

//Validadores Básicos de Tipo

v::arr() v::date()v::float()v::int()v::nullValue()v::numeric()v::object()v::string()v::instance()

30 de Novembro PHP Conference 2012 57

//Validadores Básicos de Comparação

v::equals($algo) // ==v::equals($algo, true) // ===v::max($a) // <v::max($a, true) // <=v::min($a) // >v::min($a, true) // >=v::between($a, $b) // >, <v::between($a, $b, true) // >=, <=

30 de Novembro PHP Conference 2012 58

//Validadores Básicos Numéricos

v::even()v::odd()v::negative()v::positive()v::primeNumber()v::roman() // XVIv::multiple($algo)v::perfectSquare($algo)

30 de Novembro PHP Conference 2012 59

//Validadores Básicos de String

v::alnum()v::alpha()v::digits()v::consonants()v::vowels()v::lowercase()v::uppercase()v::version()v::slug() // this-is-a-slugv::regex($exp)

30 de Novembro PHP Conference 2012 60

//Validadores do Zendv::zend('Hostname')->check('google.com');

//Validadores do Symfonyv::sf('Time')->check('22:30:00');

30 de Novembro PHP Conference 2012 61

//Validadores Legaisv::arr() ->each(v::instance(“MeuProduto”)) ->check($produtos); );

30 de Novembro PHP Conference 2012 62

//Validadores Legais

v::between(1, 15) ->check(7);

v::between(“yesterday”, “tomorrow”) ->check(new DateTime);

30 de Novembro PHP Conference 2012 63

//Validadores Legais

v::minimumAge(18) ->check(“1987-07-01”);

30 de Novembro PHP Conference 2012 64

//Validadores Legais

v::leapDate() ->check(“1998-02-29”);

v::leapYear() ->check(“1998”);

30 de Novembro PHP Conference 2012 65

//Validadores Legais

v::contains(“bar”) ->check(“foo bar baz”);

v::startsWith(“foo”) ->check(“foo bar baz”);

v::endsWith(“baz”) ->check(“foo bar baz”);

30 de Novembro PHP Conference 2012 66

//Validadores Legais

v::contains(“bar”) ->check(array(“foo bar baz”));

v::startsWith(“foo”) ->check(array(“foo bar baz”));

v::endsWith(“baz”) ->check(array(“foo bar baz”));

30 de Novembro PHP Conference 2012 67

//Validadores Legais

v::oneOf( v::arr()->length(1, 15), v::object()->attribute(“items”));

30 de Novembro PHP Conference 2012 68

Posso ter as minhas próprias regras?

30 de Novembro PHP Conference 2012 69

v::callback(function ($input) { return $input === 42;});

30 de Novembro PHP Conference 2012 70

Ok, mas posso ter meu próprio objeto?

30 de Novembro PHP Conference 2012 71

use Respect\Validation;

class Universe implements Validation\Validatable extends Validation\Rules\AbstractRule{ public function validate($input) { return $input === 42; }}

v::int()->addRule(new Universe);

30 de Novembro PHP Conference 2012 72

E as mensagens?

30 de Novembro PHP Conference 2012 73

use Respect\Validation;

class UniverseException extends Validation\Exceptions\ValidationException{ public static $defaultTemplates = array( self::MODE_DEFAULT => array( self::STANDARD => '{{name}} must be 42', ), self::MODE_NEGATIVE => array( self::STANDARD => '{{name}} must not be 42', ) );}

30 de Novembro PHP Conference 2012 74

Onde eu baixo?

30 de Novembro PHP Conference 2012 75

github.com/Respect/ValidationPackagistrespect.li/pear

30 de Novembro PHP Conference 2012 76

github.com/Respect/ValidationPackagistrespect.li/pear

Perguntas?

30 de Novembro PHP Conference 2012 77

github.com/Respect/ValidationPackagistrespect.li/pear

Obrigado!

alexandre@gaigalas.net

Recommended