SlideShare ist ein Scribd-Unternehmen logo
1 von 43
Downloaden Sie, um offline zu lesen
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!

Weitere ähnliche Inhalte

Was ist angesagt?

Melhorando sua API com DSLs
Melhorando sua API com DSLsMelhorando sua API com DSLs
Melhorando sua API com DSLsAugusto Pascutti
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsGuilherme Blanco
 
SfCon: Test Driven Development
SfCon: Test Driven DevelopmentSfCon: Test Driven Development
SfCon: Test Driven DevelopmentAugusto Pascutti
 
Storytelling By Numbers
Storytelling By NumbersStorytelling By Numbers
Storytelling By NumbersMichael King
 
The command dispatcher pattern
The command dispatcher patternThe command dispatcher pattern
The command dispatcher patternolvlvl
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix itRafael Dohms
 
Perl Bag of Tricks - Baltimore Perl mongers
Perl Bag of Tricks  -  Baltimore Perl mongersPerl Bag of Tricks  -  Baltimore Perl mongers
Perl Bag of Tricks - Baltimore Perl mongersbrian d foy
 
Pim Elshoff "Final Class Aggregate"
Pim Elshoff "Final Class Aggregate"Pim Elshoff "Final Class Aggregate"
Pim Elshoff "Final Class Aggregate"Fwdays
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6 brian d foy
 
Php tutorial handout
Php tutorial handoutPhp tutorial handout
Php tutorial handoutSBalan Balan
 
Parsing JSON with a single regex
Parsing JSON with a single regexParsing JSON with a single regex
Parsing JSON with a single regexbrian d foy
 
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Jakub Zalas
 
Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)brian d foy
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionIan Barber
 
Teaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersTeaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersIan Barber
 
The Magic Of Tie
The Magic Of TieThe Magic Of Tie
The Magic Of Tiebrian d foy
 
Symfony War Stories
Symfony War StoriesSymfony War Stories
Symfony War StoriesJakub Zalas
 

Was ist angesagt? (20)

Melhorando sua API com DSLs
Melhorando sua API com DSLsMelhorando sua API com DSLs
Melhorando sua API com DSLs
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object Calisthenics
 
Bag of tricks
Bag of tricksBag of tricks
Bag of tricks
 
SfCon: Test Driven Development
SfCon: Test Driven DevelopmentSfCon: Test Driven Development
SfCon: Test Driven Development
 
Storytelling By Numbers
Storytelling By NumbersStorytelling By Numbers
Storytelling By Numbers
 
The command dispatcher pattern
The command dispatcher patternThe command dispatcher pattern
The command dispatcher pattern
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
Perl Bag of Tricks - Baltimore Perl mongers
Perl Bag of Tricks  -  Baltimore Perl mongersPerl Bag of Tricks  -  Baltimore Perl mongers
Perl Bag of Tricks - Baltimore Perl mongers
 
Table through php
Table through phpTable through php
Table through php
 
Pim Elshoff "Final Class Aggregate"
Pim Elshoff "Final Class Aggregate"Pim Elshoff "Final Class Aggregate"
Pim Elshoff "Final Class Aggregate"
 
Learning Perl 6
Learning Perl 6 Learning Perl 6
Learning Perl 6
 
Php tutorial handout
Php tutorial handoutPhp tutorial handout
Php tutorial handout
 
Parsing JSON with a single regex
Parsing JSON with a single regexParsing JSON with a single regex
Parsing JSON with a single regex
 
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12
 
Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)Learning Perl 6 (NPW 2007)
Learning Perl 6 (NPW 2007)
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 Version
 
Teaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersTeaching Your Machine To Find Fraudsters
Teaching Your Machine To Find Fraudsters
 
The Magic Of Tie
The Magic Of TieThe Magic Of Tie
The Magic Of Tie
 
Symfony War Stories
Symfony War StoriesSymfony War Stories
Symfony War Stories
 
PHP pod mikroskopom
PHP pod mikroskopomPHP pod mikroskopom
PHP pod mikroskopom
 

Ähnlich wie TestFest - Respect\Validation 1.0

Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitmfrost503
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitmfrost503
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mockingKonstantin Kudryashov
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2eugenio pombi
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web servicesMichelangelo van Dam
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsBastian Feder
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitsmueller_sandsmedia
 
How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014Guillaume POTIER
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection apiMatthieu Aubry
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and youmarkstory
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにYuya Takeyama
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConRafael Dohms
 

Ähnlich wie TestFest - Respect\Validation 1.0 (20)

Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mocking
 
Workshop unittesting
Workshop unittestingWorkshop unittesting
Workshop unittesting
 
Mocking Demystified
Mocking DemystifiedMocking Demystified
Mocking Demystified
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web services
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
 
How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014How to test complex SaaS applications - The family july 2014
How to test complex SaaS applications - The family july 2014
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection api
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and you
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くために
 
Test driven development_for_php
Test driven development_for_phpTest driven development_for_php
Test driven development_for_php
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 

Mehr von Henrique Moody

Commit to good commit messages
Commit to good commit messagesCommit to good commit messages
Commit to good commit messagesHenrique Moody
 
Cutting Back Processing Time
Cutting Back Processing TimeCutting Back Processing Time
Cutting Back Processing TimeHenrique Moody
 
Introdução ao Respect\Validation (1.0)
Introdução ao Respect\Validation (1.0)Introdução ao Respect\Validation (1.0)
Introdução ao Respect\Validation (1.0)Henrique Moody
 

Mehr von Henrique Moody (6)

Commit to good commit messages
Commit to good commit messagesCommit to good commit messages
Commit to good commit messages
 
Cutting Back Processing Time
Cutting Back Processing TimeCutting Back Processing Time
Cutting Back Processing Time
 
O esquecido do PHP
O esquecido do PHPO esquecido do PHP
O esquecido do PHP
 
Introdução ao Respect\Validation (1.0)
Introdução ao Respect\Validation (1.0)Introdução ao Respect\Validation (1.0)
Introdução ao Respect\Validation (1.0)
 
PHP e seus demônios
PHP e seus demôniosPHP e seus demônios
PHP e seus demônios
 
PHP-CLI em 7 passos
PHP-CLI em 7 passosPHP-CLI em 7 passos
PHP-CLI em 7 passos
 

Kürzlich hochgeladen

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 

Kürzlich hochgeladen (20)

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 

TestFest - Respect\Validation 1.0

  • 1. RespectValidation O mais incrível mecanismo de validação já criado para PHP
  • 2. 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
  • 4. • Obter dados via $_POST • Validar se a chave “email” é um email válido • Exibir mensagem de erro
  • 5. 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; } }
  • 6. 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(); }
  • 7. 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; }
  • 8. Validation - Respect use RespectValidationValidator as v; try { v::key('email', v::email())->check($_POST); } catch (Exception $exception) { echo $exception->getMessage(); }
  • 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 eu quiser…
  • 15. Não utilizar estáticos use RespectValidationRules; use RespectValidationValidator; $validator = new Validator(); $validator->addRule(new RulesKey('email', new RulesEmail())); $validator->assert($_POST);
  • 16. Reutilizar cadeia de validação $validator = v::stringType()->length(2, 15); $validator->assert($input1); $validator->check($input2); if ($validator->validate($input3)) { // ... } if ($validator($input4)) { // ... }
  • 17. 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 // )
  • 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 valores opcionais 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óprias regras v::with('MyValidationRules'); v::myRule(); // Tenta carregar "MyValidationRulesMyRule" se existir
  • 25. Regra: IntType <?php namespace RespectValidationRules; class IntType extends AbstractRule { public function validate($input) { return is_int($input); } }
  • 26. Teste unitário: IntTypeTest namespace RespectValidationRules; /** * @group rule * @covers RespectValidationRulesIntType */ class IntTypeTest extends PHPUnit_Framework_TestCase { }
  • 27. 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)); } // ...
  • 28. 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)); } // ...
  • 29. 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', ), ); }
  • 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'; use RespectValidationValidator as v; v::intType()->assert(42); v::intType()->check(1984); ?> --EXPECTF--
  • 32. 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
  • 33. 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
  • 34. 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
  • 35. 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
  • 37. /** * @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)) }
  • 38. /** * @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)) }
  • 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)); }