Added vendor/ directory for Composer's installed files

This commit is contained in:
Ascendings
2015-08-30 12:33:20 -04:00
parent 45df179c49
commit b66a773ed8
1162 changed files with 112457 additions and 0 deletions

262
vendor/alexgarrett/violin/README.md vendored Executable file
View File

@ -0,0 +1,262 @@
# violin
[![Build Status](https://travis-ci.org/alexgarrett/violin.svg?branch=master)](https://travis-ci.org/alexgarrett/violin)
Violin is an easy to use, highly customisable PHP validator.
**Note: This package is under heavy development and is not recommended for production.**
## Installing
Install using Composer.
```json
{
"require": {
"alexgarrett/violin": "2.*"
}
}
```
## Basic usage
```php
use Violin\Violin;
$v = new Violin;
$v->validate([
'name' => ['billy', 'required'],
'age' => [20, 'required|int']
]);
if($v->passes()) {
echo 'Validation passed, woo!';
} else {
echo '<pre>', var_dump($v->errors()->all()), '</pre>';
}
```
## Adding custom rules
Adding custom rules is simple. If the closure returns false, the rule fails.
```php
$v->addRuleMessage('isbanana', 'The {field} field expects "banana", found "{value}" instead.');
$v->addRule('isbanana', function($value, $input, $args) {
return $value === 'banana';
});
$v->validate([
'fruit' => ['apple', 'isbanana']
]);
```
## Adding custom error messages
You can add rule messages, or field messages for total flexibility.
### Adding a rule message
```php
$v->addRuleMessage('required', 'You better fill in the {field} field, or else.');
```
### Adding rule messages in bulk
```php
$v->addRuleMessages([
'required' => 'You better fill in the {field} field, or else.',
'int' => 'The {field} needs to be an integer, but I found {value}.',
]);
```
### Adding a field message
Any field messages you add are used before any default or custom rule messages.
```php
$v->addFieldMessage('username', 'required', 'You need to enter a username to sign up.');
```
### Adding field messages in bulk
```php
$v->addFieldMessages([
'username' => [
'required' => 'You need to enter a username to sign up.'
],
'age' => [
'required' => 'I need your age.',
'int' => 'Your age needs to be an integer.',
]
]);
```
### Using Field Aliases
Field Aliases helps you format any error messages without showing weird form names or the need to create a custom error.
```php
$v->validate([
'username_box|Username' => ['' => 'required']
]);
// Error output: "Username is required."
```
### Extending Violin
You can extend the Violin class to add custom rules, rule messages and field messages. This way, you can keep a tidy class to handle custom validation if you have any dependencies, like a database connection or language files.
```php
class MyValidator extends Violin
{
protected $db;
public function __construct(PDO $db)
{
$this->db = $db;
// Add rule message for custom rule method.
$this->addRuleMessage('uniqueUsername', 'That username is taken.');
}
// Custom rule method for checking a unique username in our database.
// Just prepend custom rules with validate_
public function validate_uniqueUsername($value, $input, $args)
{
$user = $this->db->prepare("
SELECT count(*) as count
FROM users
WHERE username = :username
");
$user->execute(['username' => $value]);
if($user->fetchObject()->count) {
return false; // Username exists, so return false.
}
return true;
}
}
// A database connection.
$db = new PDO('mysql:host=127.0.0.1;dbname=website', 'root', 'root');
// Instantiate your custom class with dependencies.
$v = new MyValidator($db);
$v->validate([
'username' => ['billy', 'required|uniqueUsername']
]);
```
## Rules
This list of rules are **in progress**. Of course, you can always contribute to the project if you'd like to add more to the base ruleset.
#### alnum
If the value is alphanumeric.
#### alnumDash
If the value is alphanumeric. Dashes and underscores are permitted.
#### alpha
If the value is alphabetic letters only.
#### alphaDash
If the value is alphabetic letters only. Dashes and underscores are permitted.
#### array
If the value is an array.
#### between(int, int)
Checks if the value is within the intervals defined. This check is inclusive, so 5 is between 5 and 10.
#### bool
If the value is a boolean.
#### email
If the value is a valid email.
#### int
If the value is an integer, including numbers within strings. 1 and '1' are both classed as integers.
#### number
If the value is a number, including numbers within strings.
> Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but only without sign, decimal and exponential part.
#### ip
If the value is a valid IP address.
#### min(int, [number])
Check if string length is greater than or equal to given `int`. To check the size of a number, pass the optional `number` option.
```php
$v->validate([
'username' => ['billy', 'required|min(3)|max(20)'],
'age' => ['20', 'required|min(18, number)|max(100, number)']
]);
```
#### max(int, [number])
Check if string length is less than or equal to given `int`. To check the size of a number, pass the optional `number` option.
#### required
If the value is present.
#### url
If the value is formatted as a valid URL.
#### matches(field)
Checks if one given input matches the other. For example, checking if *password* matches *password_confirm*.
#### date
If the given input is a valid date.
You can validate human readable dates like '25th October 1961' and instances of `DateTime`. For example:
```php
$twoDaysAgo = new DateTime('2 days ago');
$date = $twoDaysAgo->format('d M Y');
$v->validate([
'date' => [$date, 'required|date']
]);
```
#### checked
If a field has been 'checked' or not, meaning it contains one of the following values: *'yes'*, *'on'*, *'1'*, *1*, *true*, or *'true'*. This can be used for determining if an HTML checkbox has been checked.
#### regex(expression)
If the given input has a match for the regular expression given.
## Contributing
Please file issues under GitHub, or submit a pull request if you'd like to directly contribute.
### Running tests
Tests are run with phpunit. Run `./vendor/bin/phpunit` to run tests.

27
vendor/alexgarrett/violin/composer.json vendored Executable file
View File

@ -0,0 +1,27 @@
{
"name": "alexgarrett/violin",
"type": "library",
"description": "Violin is an easy to use, highly customisable PHP validator.",
"keywords": ["validation"],
"homepage": "https://github.com/alexgarrett/violin",
"license": "MIT",
"authors": [
{
"name": "Alex Garrett",
"email": "alex@codecourse.com",
"homepage": "http://itsmealex.com"
}
],
"require": {
"php": ">=5.4"
},
"require-dev": {
"squizlabs/php_codesniffer": "2.1.*",
"phpunit/phpunit": "~4.5"
},
"autoload": {
"psr-4": {
"Violin\\": "src/"
}
}
}

View File

@ -0,0 +1,77 @@
<?php
/**
* Violin example. Extending.
*
* You can extend the Violin class to create your own validator,
* making it easier to keep everything in one place, and more
* importantly, the ability to pass dependencies into the
* class.
*
* This example checks a specfic value isn't already taken
* within a table in your database.
*/
require '../../vendor/autoload.php';
//-- Validator.php
use Violin\Violin;
class Validator extends Violin
{
protected $db;
public function __construct(PDO $db)
{
$this->db = $db;
$this->addRuleMessage('unique', 'That {field} is already taken.');
}
/**
* Check if a value already exists in a database table.
*
* @param mixed $value
* @param array $input
* @param array $args
*
* @return bool
*/
public function validate_unique($value, $input, $args)
{
$table = $args[0];
$column = $args[1];
$value = trim($value);
$exists = $this->db->prepare("
SELECT count(*) as count
FROM {$table}
WHERE {$column} = :value
");
$exists->execute([
'value' => $value
]);
return ! (bool) $exists->fetchObject()->count;
}
}
//-- Any other file
// Some database dependency
$db = new PDO('mysql:dbname=project;host=localhost', 'root', 'root');
$v = new Validator($db);
$v->validate([
'username' => ['alex', 'required|alpha|min(3)|max(20)|unique(users, username)'],
'email' => ['alex@codecourse.com', 'required|email|unique(users, email)']
]);
if ($v->passes()) {
// Passed
} else {
var_dump($v->errors()->all());
}

28
vendor/alexgarrett/violin/examples/basic.php vendored Executable file
View File

@ -0,0 +1,28 @@
<?php
/**
* Violin example. Basic validation.
*
* This shows basic validation, passing in an array to the
* validate method and checking if the validation passes
* with the passes method. Then dumps errors if failed.
*/
require '../vendor/autoload.php';
use Violin\Violin;
$v = new Violin;
$v->validate([
'username' => ['dale', 'required|alpha|min(3)|max(20)'],
'email' => ['dale@codecourse.com', 'required|email'],
'password' => ['ilovecats', 'required'],
'password_confirm' => ['ilovecats', 'required|matches(password)']
]);
if ($v->passes()) {
// Passed
} else {
var_dump($v->errors()->all());
}

View File

@ -0,0 +1,37 @@
<?php
/**
* Violin example. Basic validation, two arrays.
*
* This shows basic validation using two arrays, one for data,
* and one for the ruleset. This is useful if you'd like to
* extract the rules to a seperate class or variable.
*/
require '../vendor/autoload.php';
use Violin\Violin;
$v = new Violin;
$data = [
'username' => 'dale',
'email' => 'dale@codecourse.com',
'password' => 'ilovecats',
'password_confirm' => 'ilovecats'
];
$rules = [
'username' => 'required|alpha|min(3)|max(20)',
'email' => 'required|email',
'password' => 'required',
'password_confirm' => 'required|matches(password)'
];
$v->validate($data, $rules);
if ($v->passes()) {
// Passed
} else {
var_dump($v->errors()->all());
}

View File

@ -0,0 +1,21 @@
<?php
/**
* Violin example. All errors.
*
* Simply getting a list of errors that occured while trying
* to validate the data passed in against the rules given.
*/
require '../../vendor/autoload.php';
use Violin\Violin;
$v = new Violin;
$v->validate([
'username' => ['dalegarrett1234567890', 'required|alpha|min(3)|max(20)'],
'email' => ['dale.codecourse.com', 'required|email']
]);
var_dump($v->errors()->all()); // Array of all errors.

View File

@ -0,0 +1,22 @@
<?php
/**
* Violin example. Errors for a specific field.
*
* Simply getting a list of errors for a specific field that
* occured while trying to validate the data passed in
* against the rules given.
*/
require '../../vendor/autoload.php';
use Violin\Violin;
$v = new Violin;
$v->validate([
'username' => ['dalegarrett1234567890', 'required|alpha|min(3)|max(20)'],
'email' => ['dale.codecourse.com', 'required|email']
]);
var_dump($v->errors()->get('username')); // Array of all 'username' errors.

View File

@ -0,0 +1,25 @@
<?php
/**
* Violin example. Checking and getting first error.
*
* This checks a specific field has an error, and then outputs
* the first error that occured for that field. This is most
* likely what you'd use in a real life situation within
* your HTML form.
*/
require '../../vendor/autoload.php';
use Violin\Violin;
$v = new Violin;
$v->validate([
'username' => ['dalegarrett1234567890', 'required|alpha|min(3)|max(20)'],
'email' => ['dale.codecourse.com', 'required|email']
]);
if ($v->errors()->has('email')) { // Check if any errors exist for 'email'.
echo $v->errors()->first('email'); // First 'email' error (string).
}

View File

@ -0,0 +1,29 @@
<?php
/**
* Violin example. Custom field message.
*
* Defining an error message for a particular field, when a
* particular rule fails.
*/
require '../vendor/autoload.php';
use Violin\Violin;
$v = new Violin;
$v->addFieldMessage('username', 'required', 'We need a username to sign you up.');
$v->validate([
'username' => ['', 'required|alpha|min(3)|max(20)'],
'email' => ['dale@codecourse.com', 'required|email'],
'password' => ['ilovecats', 'required'],
'password_confirm' => ['ilovecats', 'required|matches(password)']
]);
if ($v->passes()) {
// Passed
} else {
var_dump($v->errors()->all());
}

View File

@ -0,0 +1,40 @@
<?php
/**
* Violin example. Custom field messages.
*
* Defining an error message for a particular field, when a
* particular rule fails.
*
* This is the same as addFieldMessage, but allows adding
* of multiple field messages in one go.
*/
require '../vendor/autoload.php';
use Violin\Violin;
$v = new Violin;
$v->addFieldMessages([
'username' => [
'required' => 'We need a username to sign you up.',
'alpha' => 'Your username can only contain letters.'
],
'email' => [
'email' => 'That email doesn\'t look valid.'
]
]);
$v->validate([
'username' => ['cats4life', 'required|alpha|min(3)|max(20)'],
'email' => ['dale.codecourse.com', 'required|email'],
'password' => ['ilovecats', 'required'],
'password_confirm' => ['ilovecats', 'required|matches(password)']
]);
if ($v->passes()) {
// Passed
} else {
var_dump($v->errors()->all());
}

View File

@ -0,0 +1,28 @@
<?php
/**
* Violin example. Custom rule message.
*
* Defining an error message for when a particular rule fails.
*/
require '../vendor/autoload.php';
use Violin\Violin;
$v = new Violin;
$v->addRuleMessage('required', 'Hold up, the {field} field is required!');
$v->validate([
'username' => ['', 'required|alpha|min(3)|max(20)'],
'email' => ['dale@codecourse.com', 'required|email'],
'password' => ['ilovecats', 'required'],
'password_confirm' => ['ilovecats', 'required|matches(password)']
]);
if ($v->passes()) {
// Passed
} else {
var_dump($v->errors()->all());
}

View File

@ -0,0 +1,34 @@
<?php
/**
* Violin example. Custom rule message.
*
* Defining an error message for when a particular rule fails.
*
* This is the same as addRuleMessage, but allows adding
* of multiple rule messages in one go.
*/
require '../vendor/autoload.php';
use Violin\Violin;
$v = new Violin;
$v->addRuleMessages([
'required' => 'Hold up, the {field} field is required!',
'email' => 'That doesn\'t look like a valid email address to me.'
]);
$v->validate([
'username' => ['', 'required|alpha|min(3)|max(20)'],
'email' => ['dale.codecourse.com', 'required|email'],
'password' => ['ilovecats', 'required'],
'password_confirm' => ['ilovecats', 'required|matches(password)']
]);
if ($v->passes()) {
// Passed
} else {
var_dump($v->errors()->all());
}

View File

@ -0,0 +1,26 @@
<?php
/**
* Violin example. Field aliases.
*
* Shows using field aliases to rename fields without having
* to define custom rule or field messages, making it a
* cleaner solution if this will suffice.
*/
require '../vendor/autoload.php';
use Violin\Violin;
$v = new Violin;
$v->validate([
'username|Username' => ['', 'required'],
'password|Password' => ['', 'required']
]);
if ($v->passes()) {
// Passed
} else {
var_dump($v->errors()->all());
}

View File

@ -0,0 +1,27 @@
<?php
/**
* Violin example. Message placeholders.
*
* Shows the placeholders you can use when defining messages. You can
* output the name of the field, the value given by the user, and
* the arguments that were passed into the rule.
*/
require '../vendor/autoload.php';
use Violin\Violin;
$v = new Violin;
$v->addRuleMessage('between', 'The {field} must be between {$0} and {$1}, you gave {value}');
$v->validate([
'age' => ['82', 'required|between(18, 35)']
]);
if ($v->passes()) {
// Passed
} else {
var_dump($v->errors()->all());
}

View File

@ -0,0 +1,31 @@
<?php
/**
* Violin example. Message placeholders.
*
* Shows how you can output all arguments as a comma seperated list,
* if you have a variable amount of arguments for a rule.
*/
require '../../../vendor/autoload.php';
use Violin\Violin;
$v = new Violin;
$v->addRuleMessage('isoneof', '{field} must be one of {$*}');
$v->addRule('isoneof', function($value, $input, $args) {
$value = trim($value);
return in_array($value, $args);
});
$v->validate([
'age' => ['sheep', 'required|isoneof(apples, pears)']
]);
if ($v->passes()) {
// Passed
} else {
var_dump($v->errors()->all());
}

View File

@ -0,0 +1,32 @@
<?php
/**
* Violin example. Custom rule.
*
* Creating a custom rule using the addRule method, passing in a
* closure which should return false if the check has failed,
* or true if the check has passed.
*/
require '../vendor/autoload.php';
use Violin\Violin;
$v = new Violin;
$v->addRuleMessage('startsWithNumber', 'The {field} must start with a number.');
$v->addRule('startsWithNumber', function($value, $input, $args) {
$value = trim($value);
return is_numeric($value[0]);
});
$v->validate([
'username' => ['dale', 'required|min(3)|max(20)|startsWithNumber']
]);
if ($v->passes()) {
// Passed
} else {
var_dump($v->errors()->all());
}

View File

@ -0,0 +1,35 @@
<?php
/**
* Violin example. Custom rule.
*
* Creating a custom rule using the addRule method, passing in a
* closure which should return false if the check has failed,
* or true if the check has passed.
*
* This example shows the use of arguments that can be used
* to make rules that require arguments.
*/
require '../vendor/autoload.php';
use Violin\Violin;
$v = new Violin;
$v->addRuleMessage('startsWith', 'The {field} must start with "{$0}".');
$v->addRule('startsWith', function($value, $input, $args) {
$value = trim($value);
return $value[0] === $args[0];
});
$v->validate([
'username' => ['dale', 'required|min(3)|max(20)|startsWith(a)']
]);
if ($v->passes()) {
// Passed
} else {
var_dump($v->errors()->all());
}

18
vendor/alexgarrett/violin/phpunit.xml vendored Executable file
View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="false"
>
<testsuites>
<testsuite name="Violin Test Suite">
<directory>./tests/</directory>
</testsuite>
</testsuites>
</phpunit>

View File

@ -0,0 +1,12 @@
<?php
namespace Violin\Contracts;
interface MessageBagContract
{
public function has($key);
public function first($key);
public function get($key);
public function all();
public function keys();
}

View File

@ -0,0 +1,33 @@
<?php
namespace Violin\Contracts;
interface RuleContract
{
/**
* Runs the rule to check validity. Returning false fails
* the check and returning true passes the check.
*
* @param mixed $value
* @param array $input
* @param array $args
*
* @return bool
*/
public function run($value, $input, $args);
/**
* The error given if the rule fails.
*
* @return string
*/
public function error();
/**
* If the rule can be skipped, if the value given
* to the validator is not required.
*
* @return [type] [description]
*/
public function canSkip();
}

View File

@ -0,0 +1,18 @@
<?php
namespace Violin\Contracts;
use Closure;
interface ValidatorContract
{
public function validate(array $input, $rules = []);
public function passes();
public function fails();
public function errors();
public function addRuleMessage($rule, $message);
public function addRuleMessages(array $messages);
public function addFieldMessage($field, $rule, $message);
public function addFieldMessages(array $messages);
public function addRule($name, Closure $callback);
}

View File

@ -0,0 +1,23 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class AlnumDashRule implements RuleContract
{
public function run($value, $input, $args)
{
return (bool) preg_match('/^[\pL\pM\pN_-]+$/u', $value);
}
public function error()
{
return '{field} must be alphanumeric with dashes and underscores permitted.';
}
public function canSkip()
{
return true;
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class AlnumRule implements RuleContract
{
public function run($value, $input, $args)
{
return (bool) preg_match('/^[\pL\pM\pN]+$/u', $value);
}
public function error()
{
return '{field} must be alphanumeric.';
}
public function canSkip()
{
return true;
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class AlphaRule implements RuleContract
{
public function run($value, $input, $args)
{
return (bool) preg_match('/^[\pL\pM]+$/u', $value);
}
public function error()
{
return '{field} must be alphabetic.';
}
public function canSkip()
{
return true;
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class ArrayRule implements RuleContract
{
public function run($value, $input, $args)
{
return is_array($value);
}
public function error()
{
return '{field} must be an array.';
}
public function canSkip()
{
return true;
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class BetweenRule implements RuleContract
{
public function run($value, $input, $args)
{
return ($value >= $args[0] && $value <= $args[1]) ? true : false;
}
public function error()
{
return '{field} must be between {$0} and {$1}.';
}
public function canSkip()
{
return true;
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class BoolRule implements RuleContract
{
public function run($value, $input, $args)
{
return is_bool($value);
}
public function error()
{
return '{field} must be a boolean.';
}
public function canSkip()
{
return true;
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class CheckedRule implements RuleContract
{
public function run($value, $input, $args)
{
return in_array($value, ['yes', 'on', '1', 1, true, 'true'], true);
}
public function error()
{
return 'You need to check the {field} field.';
}
public function canSkip()
{
return true;
}
}

View File

@ -0,0 +1,33 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class DateRule implements RuleContract
{
public function run($value, $input, $args)
{
if ($value instanceof DateTime) {
return true;
}
if (strtotime($value) === false) {
return false;
}
$date = date_parse($value);
return checkdate($date['month'], $date['day'], $date['year']);
}
public function error()
{
return '{field} must be a valid date.';
}
public function canSkip()
{
return true;
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class EmailRule implements RuleContract
{
public function run($value, $input, $args)
{
return filter_var($value, FILTER_VALIDATE_EMAIL) !== false;
}
public function error()
{
return '{field} must be a valid email address.';
}
public function canSkip()
{
return true;
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class IntRule implements RuleContract
{
public function run($value, $input, $args)
{
return is_numeric($value) && (int)$value == $value;
}
public function error()
{
return '{field} must be a number.';
}
public function canSkip()
{
return true;
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class IpRule implements RuleContract
{
public function run($value, $input, $args)
{
return filter_var($value, FILTER_VALIDATE_IP) !== false;
}
public function error()
{
return '{field} must be a valid IP address.';
}
public function canSkip()
{
return true;
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class MatchesRule implements RuleContract
{
public function run($value, $input, $args)
{
return $value === $input[$args[0]];
}
public function error()
{
return '{field} must match {$0}.';
}
public function canSkip()
{
return true;
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class MaxRule implements RuleContract
{
public function run($value, $input, $args)
{
$number = isset($args[1]) && $args[1] === 'number';
if ($number) {
return (float) $value <= (float) $args[0];
}
return mb_strlen($value) <= (int) $args[0];
}
public function error()
{
return '{field} must be a maximum of {$0}.';
}
public function canSkip()
{
return true;
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class MinRule implements RuleContract
{
public function run($value, $input, $args)
{
$number = isset($args[1]) && $args[1] === 'number';
if ($number) {
return (float) $value >= (float) $args[0];
}
return mb_strlen($value) >= (int) $args[0];
}
public function error()
{
return '{field} must be a minimum of {$0}.';
}
public function canSkip()
{
return true;
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class NumberRule implements RuleContract
{
public function run($value, $input, $args)
{
return is_numeric($value);
}
public function error()
{
return '{field} must be a number.';
}
public function canSkip()
{
return true;
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class RegexRule implements RuleContract
{
public function run($value, $input, $args)
{
return (bool) preg_match($args[0], $value);
}
public function error()
{
return '{field} was not in the correct format.';
}
public function canSkip()
{
return true;
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class RequiredRule implements RuleContract
{
public function run($value, $input, $args)
{
$value = preg_replace('/^[\pZ\pC]+|[\pZ\pC]+$/u', '', $value);
return !empty($value);
}
public function error()
{
return '{field} is required.';
}
public function canSkip()
{
return false;
}
}

View File

@ -0,0 +1,23 @@
<?php
namespace Violin\Rules;
use Violin\Contracts\RuleContract;
class UrlRule implements RuleContract
{
public function run($value, $input, $args)
{
return filter_var($value, FILTER_VALIDATE_URL) !== false;
}
public function error()
{
return '{field} must be a valid URL.';
}
public function canSkip()
{
return true;
}
}

View File

@ -0,0 +1,96 @@
<?php
namespace Violin\Support;
use RecursiveArrayIterator;
use RecursiveIteratorIterator;
use Violin\Contracts\MessageBagContract;
class MessageBag implements MessageBagContract
{
/**
* The registered messages.
*
* @var array
*/
protected $messages = [];
/**
* Creates a new instange of the MessageBag instance.
*
* @param array $messages
* @return void
*/
public function __construct(array $messages)
{
foreach ($messages as $key => $value) {
$this->messages[$key] = (array) $value;
}
}
/**
* Checks if the bag has messages for a given key.
*
* @param string $key
* @return boolean
*/
public function has($key)
{
return ! is_null($this->first($key));
}
/**
* Get the first message with a given key.
* If the given key doesn't exist, it returns the first
* message of the bag.
* Returns null if the bag is empty.
*
* @param string $key
* @return string|null
*/
public function first($key = null)
{
$messages = is_null($key) ? $this->all() : $this->get($key);
return (count($messages) > 0) ? $messages[0] : null;
}
/**
* Get all of the messages from a given key.
* Returns null if the given key is empty, or
* if it doesn't exist.
*
* @param string $key
* @return array|null
*/
public function get($key)
{
if (array_key_exists($key, $this->messages)) {
return !empty($this->messages[$key]) ? $this->messages[$key] : null;
}
return null;
}
/**
* Get all of the messages in the bag.
*
* @return array
*/
public function all()
{
return iterator_to_array(new RecursiveIteratorIterator(
new RecursiveArrayIterator($this->messages)
), false);
}
/**
* Return all of the keys in the bag.
*
* @return array
*/
public function keys()
{
return array_keys($this->messages);
}
}

506
vendor/alexgarrett/violin/src/Violin.php vendored Executable file
View File

@ -0,0 +1,506 @@
<?php
namespace Violin;
use Closure;
use RecursiveArrayIterator;
use RecursiveIteratorIterator;
use Violin\Support\MessageBag;
use Violin\Contracts\ValidatorContract;
class Violin implements ValidatorContract
{
/**
* Rule objects that have already been instantiated.
*
* @var array
*/
protected $usedRules = [];
/**
* Custom user-defined rules
*
* @var array
*/
protected $customRules = [];
/**
* Collection of errors.
*
* @var array
*/
public $errors = [];
/**
* Inputted fields and values.
*
* @var array
*/
protected $input = [];
/**
* Rule messages.
*
* @var array
*/
protected $ruleMessages = [];
/**
* Field messages.
*
* @var array
*/
protected $fieldMessages = [];
/**
* Field Aliases.
*
* @var array
*/
protected $fieldAliases = [];
/**
* Kick off the validation using input and rules.
*
* @param array $input
* @param array $rules
*
* @return this
*/
public function validate(array $data, $rules = [])
{
$this->clearErrors();
$this->clearFieldAliases();
$data = $this->extractFieldAliases($data);
// If the rules array is empty, then it means we are
// receiving the rules directly with the input, so we need
// to extract the information.
if (empty($rules)) {
$rules = $this->extractRules($data);
$data = $this->extractInput($data);
}
$this->input = $data;
foreach ($data as $field => $value) {
$fieldRules = explode('|', $rules[$field]);
foreach ($fieldRules as $rule) {
$this->validateAgainstRule(
$field,
$value,
$this->getRuleName($rule),
$this->getRuleArgs($rule)
);
}
}
return $this;
}
/**
* Checks if validation has passed.
*
* @return bool
*/
public function passes()
{
return empty($this->errors);
}
/**
* Checks if validation has failed.
*
* @return bool
*/
public function fails()
{
return ! $this->passes();
}
/**
* Gather errors, format them and return them.
*
* @return array
*/
public function errors()
{
$messages = [];
foreach ($this->errors as $rule => $items) {
foreach ($items as $item) {
$field = $item['field'];
$message = $this->fetchMessage($field, $rule);
// If there is any alias for the current field, swap it.
if (isset($this->fieldAliases[$field])) {
$item['field'] = $this->fieldAliases[$field];
}
$messages[$field][] = $this->replaceMessageFormat($message, $item);
}
}
return new MessageBag($messages);
}
/**
* Adds a custom rule message.
*
* @param string $rule
* @param string $message
*/
public function addRuleMessage($rule, $message)
{
$this->ruleMessages[$rule] = $message;
}
/**
* Adds custom rule messages.
*
* @param array $messages
*/
public function addRuleMessages(array $messages)
{
$this->ruleMessages = array_merge($this->ruleMessages, $messages);
}
/**
* Adds a custom field message.
*
* @param string $field
* @param string $rule
* @param string $message
*/
public function addFieldMessage($field, $rule, $message)
{
$this->fieldMessages[$field][$rule] = $message;
}
/**
* Adds custom field messages
*
* @param array $messages
*/
public function addFieldMessages(array $messages)
{
$this->fieldMessages = $messages;
}
/**
* Add a custom rule
*
* @param string $name
* @param Closure $callback
*/
public function addRule($name, Closure $callback)
{
$this->customRules[$name] = $callback;
}
/**
* Fetch the message for an error by field or rule type.
*
* @param string $field
* @param string $rule
*
* @return string
*/
protected function fetchMessage($field, $rule)
{
if (isset($this->fieldMessages[$field][$rule])) {
return $this->fieldMessages[$field][$rule];
}
if (isset($this->ruleMessages[$rule])) {
return $this->ruleMessages[$rule];
}
return $this->usedRules[$rule]->error();
}
/**
* Replaces message variables.
*
* @param string $message
* @param array $item
*
* @return string
*/
protected function replaceMessageFormat($message, array $item)
{
$keys = array_keys($item);
if (!empty($item['args'])) {
$args = $item['args'];
$argReplace = array_map(function($i) {
return "{\${$i}}";
}, array_keys($args));
// Number of arguments
$args[] = count($item['args']);
$argReplace[] = '{$#}';
// All arguments
$args[] = implode(', ', $item['args']);
$argReplace[] = '{$*}';
// Replace arguments
$message = str_replace($argReplace, $args, $message);
}
// Replace field and value
$message = str_replace(
['{field}', '{value}'],
[$item['field'], $item['value']],
$message
);
return $message;
}
/**
* Validates value against a specific rule and handles
* errors if the rule validation fails.
*
* @param string $field
* @param string $value
* @param string $rule
* @param array $args
*
* @return void
*/
protected function validateAgainstRule($field, $value, $rule, array $args)
{
$ruleToCall = $this->getRuleToCall($rule);
if ($this->canSkipRule($ruleToCall, $value)) {
return;
}
$passed = call_user_func_array($ruleToCall, [
$value,
$this->input,
$args
]);
if (!$passed) {
$this->handleError($field, $value, $rule, $args);
}
}
/**
* Method to help skip a rule if a value is empty, since we
* don't need to validate an empty value. If the rule to
* call specifically doesn't allowing skipping, then
* we don't want skip the rule.
*
* @param array $ruleToCall
* @param mixed $value
*
* @return null
*/
protected function canSkipRule($ruleToCall, $value)
{
return (
(is_array($ruleToCall) &&
method_exists($ruleToCall[0], 'canSkip') &&
$ruleToCall[0]->canSkip()) &&
empty($value) &&
!is_array($value)
);
}
/**
* Clears all previously stored errors.
*
* @return void
*/
protected function clearErrors()
{
$this->errors = [];
}
/**
* Stores an error.
*
* @param string $field
* @param string $value
* @param string $rule
* @param array $args
*
* @return void
*/
protected function handleError($field, $value, $rule, array $args)
{
$this->errors[$rule][] = [
'field' => $field,
'value' => $value,
'args' => $args,
];
}
/**
* Gets and instantiates a rule object, e.g. IntRule. If it has
* already been used, it pulls from the stored rule objects.
*
* @param string $rule
*
* @return mixed
*/
protected function getRuleToCall($rule)
{
if (isset($this->customRules[$rule])) {
return $this->customRules[$rule];
}
if (method_exists($this, 'validate_' . $rule)) {
return [$this, 'validate_' . $rule];
}
if (isset($this->usedRules[$rule])) {
return [$this->usedRules[$rule], 'run'];
}
$ruleClass = 'Violin\\Rules\\' . ucfirst($rule) . 'Rule';
$ruleObject = new $ruleClass();
$this->usedRules[$rule] = $ruleObject;
return [$ruleObject, 'run'];
}
/**
* Determine whether a rule has arguments.
*
* @param string $rule
*
* @return bool
*/
protected function ruleHasArgs($rule)
{
return isset(explode('(', $rule)[1]);
}
/**
* Get rule arguments.
*
* @param string $rule
*
* @return array
*/
protected function getRuleArgs($rule)
{
if (!$this->ruleHasArgs($rule)) {
return [];
}
list($ruleName, $argsWithBracketAtTheEnd) = explode('(', $rule);
$args = rtrim($argsWithBracketAtTheEnd, ')');
$args = preg_replace('/\s+/', '', $args);
$args = explode(',', $args);
return $args;
}
/**
* Gets a rule name.
*
* @param string $rule
*
* @return string
*/
protected function getRuleName($rule)
{
return explode('(', $rule)[0];
}
/**
* Flatten an array.
*
* @param array $args
*
* @return array
*/
protected function flattenArray(array $args)
{
return iterator_to_array(new RecursiveIteratorIterator(
new RecursiveArrayIterator($args)
), false);
}
/**
* Extracts field aliases from an input.
*
* @param array $data
*
* @return array
*/
protected function extractFieldAliases(array $data)
{
foreach ($data as $field => $fieldRules) {
$extraction = explode('|', $field);
if (isset($extraction[1])) {
$updatedField = $extraction[0];
$alias = $extraction[1];
$this->fieldAliases[$updatedField] = $alias;
$data[$updatedField] = $data[$field];
unset($data[$field]);
}
}
return $data;
}
/**
* Clears all field aliases.
*
* @return void
*/
protected function clearFieldAliases()
{
$this->fieldAliases = [];
}
/**
* Extract the field input from the data array.
* @param array $data
* @return array
*/
protected function extractInput(array $data)
{
$input = [];
foreach ($data as $field => $fieldData) {
$input[$field] = $fieldData[0];
}
return $input;
}
/**
* Extract the field ruleset from the data array.
*
* @param array $data
* @return array
*/
protected function extractRules(array $data)
{
$rules = [];
foreach ($data as $field => $fieldData) {
$rules[$field] = $fieldData[1];
}
return $rules;
}
}

View File

@ -0,0 +1,68 @@
<?php
use Violin\Support\MessageBag;
class MessageBagTest extends PHPUnit_Framework_TestCase
{
protected $mb;
protected $messages = [
'name' => [
'You must fill in the name field.',
'Your name must only be letters.',
],
'username' => [
'Your username is required.',
'Your username must be alphanumeric (with dashes and underscores permitted)'
],
'password' => [
'Your password must be greater than 6 characters.'
]
];
public function setUp()
{
$this->mb = new MessageBag($this->messages);
}
public function testMessageBagContainsCorrectKeys()
{
$keys = $this->mb->keys();
$this->assertContains('name', $keys);
$this->assertContains('username', $keys);
$this->assertContains('password', $keys);
}
public function testFirstErrorForFieldExists()
{
$this->assertEquals(
$this->mb->first('name'),
$this->messages['name'][0]
);
}
public function testAllErrorsForFieldExist()
{
$this->assertEquals(
$this->mb->get('name'),
$this->messages['name']
);
}
public function testAllErrorsExist()
{
$flatMessages = iterator_to_array(new RecursiveIteratorIterator(
new RecursiveArrayIterator($this->messages)
), false);
$this->assertEquals($flatMessages, $this->mb->all());
}
public function testMessageBagHasError()
{
$this->assertTrue($this->mb->has('name'));
$this->assertTrue($this->mb->has('username'));
$this->assertTrue($this->mb->has('password'));
}
}

567
vendor/alexgarrett/violin/tests/RulesTest.php vendored Executable file
View File

@ -0,0 +1,567 @@
<?php
use Violin\Rules\IpRule;
use Violin\Rules\IntRule;
use Violin\Rules\UrlRule;
use Violin\Rules\MaxRule;
use Violin\Rules\MinRule;
use Violin\Rules\BoolRule;
use Violin\Rules\DateRule;
use Violin\Rules\RegexRule;
use Violin\Rules\AlnumRule;
use Violin\Rules\AlphaRule;
use Violin\Rules\EmailRule;
use Violin\Rules\ArrayRule;
use Violin\Rules\NumberRule;
use Violin\Rules\CheckedRule;
use Violin\Rules\BetweenRule;
use Violin\Rules\MatchesRule;
use Violin\Rules\RequiredRule;
use Violin\Rules\AlnumDashRule;
use Violin\Support\MessageBag;
class RulesTest extends PHPUnit_Framework_TestCase
{
public function testBetweenRule()
{
$betweenRule = new BetweenRule;
$this->assertFalse(
$betweenRule->run('5', [], [10, 15])
);
$this->assertFalse(
$betweenRule->run(5, [], [10, 15])
);
$this->assertTrue(
$betweenRule->run('100', [], [100, 500])
);
$this->assertTrue(
$betweenRule->run(499, [], [100, 500])
);
$this->assertTrue(
$betweenRule->run('300', [], [100, 500])
);
}
public function testIntRule()
{
$intRule = new IntRule;
$this->assertFalse(
$intRule->run('two', [], [])
);
$this->assertTrue(
$intRule->run('2', [], [])
);
$this->assertTrue(
$intRule->run(10, [], [])
);
}
public function testNumberRule()
{
$numberRule = new NumberRule;
$this->assertFalse(
$numberRule->run('dale', [], [])
);
$this->assertFalse(
$numberRule->run('', [], [])
);
$this->assertFalse(
$numberRule->run('three', [], [])
);
$this->assertTrue(
$numberRule->run('1', [], [])
);
$this->assertTrue(
$numberRule->run('3.14159265359', [], [])
);
$this->assertTrue(
$numberRule->run(3.14159265359, [], [])
);
}
public function testMatchesRule()
{
$matchesRule = new MatchesRule;
$this->assertFalse(
$matchesRule->run('cats', [
'password' => 'cats',
'password_again' => 'catz',
], ['password_again'])
);
$this->assertTrue(
$matchesRule->run('cats', [
'password' => 'cats',
'password_again' => 'cats',
], ['password_again'])
);
}
public function testRequiredRule()
{
$requiredRule = new RequiredRule;
$this->assertFalse(
$requiredRule->run('', [], [])
);
$this->assertFalse(
$requiredRule->run(' ', [], [])
);
$this->assertFalse(
$requiredRule->run(' ', [], [])
); // Contains whitespace character
$this->assertTrue(
$requiredRule->run('cats', [], [])
);
$this->assertTrue(
$requiredRule->run(' cats ', [], [])
);
}
public function testAlnumRule()
{
$alnumRule = new AlnumRule;
$this->assertFalse(
$alnumRule->run('cats_123', [], [])
);
$this->assertFalse(
$alnumRule->run('cats-_123', [], [])
);
$this->assertFalse(
$alnumRule->run('cats123!', [], [])
);
$this->assertTrue(
$alnumRule->run('cats123', [], [])
);
$this->assertTrue(
$alnumRule->run('cats', [], [])
);
}
public function testAlnumDashRule()
{
$alnumDashRule = new AlnumDashRule;
$this->assertFalse(
$alnumDashRule->run('cats123!', [], [])
);
$this->assertFalse(
$alnumDashRule->run('cats(123)', [], [])
);
$this->assertTrue(
$alnumDashRule->run('cats_123', [], [])
);
$this->assertTrue(
$alnumDashRule->run('i_love-cats', [], [])
);
$this->assertTrue(
$alnumDashRule->run('cat__love', [], [])
);
$this->assertTrue(
$alnumDashRule->run('cat--love', [], [])
);
}
public function testAlphaRule()
{
$alphaRule = new AlphaRule;
$this->assertFalse(
$alphaRule->run('cats123', [], [])
);
$this->assertFalse(
$alphaRule->run('cats!', [], [])
);
$this->assertFalse(
$alphaRule->run(' cats ', [], [])
);
$this->assertTrue(
$alphaRule->run('cats', [], [])
);
}
public function testArrayRule()
{
$arrayRule = new ArrayRule;
$this->assertFalse(
$arrayRule->run('not an array', [], [])
);
$this->assertFalse(
$arrayRule->run("['not', 'an', 'array']", [], [])
);
$this->assertTrue(
$arrayRule->run(['an', 'array'], [], [])
);
$this->assertTrue(
$arrayRule->run([], [], [])
);
}
public function testBoolRule()
{
$boolRule = new BoolRule;
$this->assertFalse(
$boolRule->run('false', [], [])
);
$this->assertFalse(
$boolRule->run('true', [], [])
);
$this->assertFalse(
$boolRule->run(1, [], [])
);
$this->assertFalse(
$boolRule->run(0, [], [])
);
$this->assertTrue(
$boolRule->run(true, [], [])
);
$this->assertTrue(
$boolRule->run(false, [], [])
);
}
public function testEmailRule()
{
$emailRule = new EmailRule;
$this->assertFalse(
$emailRule->run('ilove@', [], [])
);
$this->assertFalse(
$emailRule->run('ilove@cats', [], [])
);
$this->assertTrue(
$emailRule->run('ilove@cats.com', [], [])
);
}
public function testIpRule()
{
$ipRule = new IpRule;
$this->assertFalse(
$ipRule->run('127', [], [])
);
$this->assertFalse(
$ipRule->run('127.0.0', [], [])
);
$this->assertFalse(
$ipRule->run('www.duckduckgo.com', [], [])
);
$this->assertTrue(
$ipRule->run('0.0.0.0', [], [])
);
$this->assertTrue(
$ipRule->run('127.0.0.1', [], [])
);
$this->assertTrue(
$ipRule->run('FE80:0000:0000:0000:0202:B3FF:FE1E:8329', [], [])
);
$this->assertTrue(
$ipRule->run('FE80::0202:B3FF:FE1E:8329', [], [])
);
$this->assertTrue(
$ipRule->run('::1', [], [])
);
}
public function testMaxRuleWithNumbers()
{
$maxRule = new MaxRule;
$this->assertFalse(
$maxRule->run('100', [], ['10', 'number'])
);
$this->assertFalse(
$maxRule->run(100, [], ['99', 'number'])
);
$this->assertFalse(
$maxRule->run(3.14, [], ['3.10', 'number'])
);
$this->assertTrue(
$maxRule->run('50', [], ['100', 'number'])
);
$this->assertTrue(
$maxRule->run(50, [], ['100', 'number'])
);
$this->assertTrue(
$maxRule->run('5.5', [], ['100', 'number'])
);
}
public function testMinRuleWithNumbers()
{
$minRule = new MinRule;
$this->assertFalse(
$minRule->run('10', [], ['100', 'number'])
);
$this->assertFalse(
$minRule->run(99, [], ['100', 'number'])
);
$this->assertFalse(
$minRule->run(3.10, [], ['3.14', 'number'])
);
$this->assertTrue(
$minRule->run('100', [], ['50', 'number'])
);
$this->assertTrue(
$minRule->run(100, [], ['50', 'number'])
);
$this->assertTrue(
$minRule->run('100', [], ['5.5', 'number'])
);
}
public function testMaxRuleWithStrings()
{
$maxRule = new MaxRule;
$this->assertFalse(
$maxRule->run('william', [], ['5'])
);
$this->assertFalse(
$maxRule->run('100000', [], ['5'])
);
$this->assertTrue(
$maxRule->run('billy', [], ['5'])
);
$this->assertTrue(
$maxRule->run('100', [], ['5'])
);
$this->assertTrue(
$maxRule->run('99999', [], ['5'])
);
}
public function testMinRuleWithStrings()
{
$minRule = new MinRule;
$this->assertFalse(
$minRule->run('billy', [], ['10'])
);
$this->assertFalse(
$minRule->run('5', [], ['10'])
);
$this->assertFalse(
$minRule->run('10', [], ['10'])
);
$this->assertTrue(
$minRule->run('william', [], ['5'])
);
$this->assertTrue(
$minRule->run('99999', [], ['5'])
);
}
public function testUrlRule()
{
$urlRule = new UrlRule;
$this->assertFalse(
$urlRule->run('www.com', [], [])
);
$this->assertFalse(
$urlRule->run('duckduckgo.com', [], [])
);
$this->assertFalse(
$urlRule->run('www.duckduckgo', [], [])
);
$this->assertFalse(
$urlRule->run('127.0.0.1', [], [])
);
$this->assertTrue(
$urlRule->run('http://www.duckduckgo.com', [], [])
);
$this->assertTrue(
$urlRule->run('http://127.0.0.1', [], [])
);
$this->assertTrue(
$urlRule->run('ftp://127.0.0.1', [], [])
);
$this->assertTrue(
$urlRule->run('ssl://codecourse.com', [], [])
);
$this->assertTrue(
$urlRule->run('ssl://127.0.0.1', [], [])
);
$this->assertTrue(
$urlRule->run('http://codecourse.com', [], [])
);
}
public function testDateRule()
{
$dateRule = new DateRule;
$this->assertFalse(
$dateRule->run('', [], [])
);
$this->assertFalse(
$dateRule->run('0000-00-00', [], [])
);
$this->assertFalse(
$dateRule->run('40th November 1989', [], [])
);
$this->assertTrue(
$dateRule->run('16th November 1989', [], [])
);
$this->assertTrue(
$dateRule->run('1989-11-16', [], [])
);
$this->assertTrue(
$dateRule->run('16-11-1989', [], [])
);
$dateTime = new DateTime('2 days ago');
$this->assertFalse(
$dateRule->run($dateTime->format('x y z'), [], [])
);
$this->assertTrue(
$dateRule->run($dateTime->format('d M Y'), [], [])
);
}
public function testCheckedRule()
{
$checkedRule = new CheckedRule;
$this->assertFalse(
$checkedRule->run('', [], [])
);
$this->assertFalse(
$checkedRule->run(' ', [], [])
);
$this->assertTrue(
$checkedRule->run('on', [], [])
);
$this->assertTrue(
$checkedRule->run('yes', [], [])
);
$this->assertTrue(
$checkedRule->run(1, [], [])
);
$this->assertTrue(
$checkedRule->run('1', [], [])
);
$this->assertTrue(
$checkedRule->run(true, [], [])
);
$this->assertTrue(
$checkedRule->run('true', [], [])
);
}
public function testRegexRule()
{
$regexRule = new RegexRule;
$exampleRegex = '/b[aeiou]g/';
$this->assertFalse(
$regexRule->run('banter', [], [$exampleRegex])
);
$this->assertTrue(
$regexRule->run('bag', [], [$exampleRegex])
);
$this->assertTrue(
$regexRule->run('big', [], [$exampleRegex])
);
}
}

View File

@ -0,0 +1,272 @@
<?php
use Violin\Violin;
class ValidatorTest extends PHPUnit_Framework_TestCase
{
protected $v;
public function setUp()
{
$this->v = new Violin;
}
public function testBasicValidValidation()
{
$this->v->validate([
'first_name' => ['Billy', 'required|alpha|max(20)'],
'last_name' => ['Garrett', 'required|alpha|max(20)'],
'email|Email' => ['billy@codecourse.com', 'required|email'],
'password' => ['ilovecats', 'required'],
'password_again' => ['ilovecats', 'required|matches(password)']
]);
$this->assertTrue($this->v->passes());
$this->assertFalse($this->v->fails());
$input = [
'first_name' => 'Billy',
'last_name' => 'Garrett',
'email|Email' => 'billy@codecourse.com',
'password' => 'ilovecats',
'password' => 'ilovecats'
];
$rules = [
'first_name' => 'required|alpha|max(20)',
'last_name' => 'required|alpha|max(20)',
'email' => 'required|email',
'password' => 'required',
'password_again' => 'required|matches(password)'
];
$this->v->validate($input, $rules);
$this->assertTrue($this->v->passes());
$this->assertFalse($this->v->fails());
}
public function testBasicInvalidValidation()
{
$this->v->validate([
'first_name' => ['Billy', 'required|alpha|max(20)'],
'last_name' => ['', 'required|alpha|max(20)'],
'email' => ['billy@codecourse', 'required|email'],
'password' => ['ilovecats', 'required'],
'password_again' => ['ilovecatsanddogs' , 'required|matches(password)']
]);
$this->assertTrue($this->v->fails());
$this->assertFalse($this->v->passes());
}
public function testRuleMessage()
{
$this->v->addRuleMessage('required', 'This field is required!');
$this->v->validate([
'username' => ['', 'required']
]);
$this->assertEquals(
$this->v->errors()->first('username'),
'This field is required!'
);
}
public function testReplaceMessageFormatOnError()
{
$this->v->addRule('testRule', function($value, $input, $args) {
return false;
});
$this->v->addRuleMessage('testRule', 'We got {$#} arguments: {$*}.');
$this->v->validate([
'age' => [0, 'testRule(1, 2, 3)']
]);
$this->assertEquals(
$this->v->errors()->first(),
'We got 3 arguments: 1, 2, 3.'
);
}
public function testRuleMessages()
{
$this->v->addRuleMessages([
'required' => 'This field is required!',
'alpha' => 'Only alpha characters please!',
'email' => 'Enter a valid email!'
]);
$this->v->validate([
'username' => ['', 'required|alpha'],
'name' => ['123', 'alpha'],
'email' => ['notanemail', 'required|email']
]);
$errors = $this->v->errors();
$this->assertEquals(
$errors->get('username'),
['This field is required!']
);
$this->assertEquals(
$errors->first('name'),
'Only alpha characters please!'
);
$this->assertEquals(
$errors->first('email'),
'Enter a valid email!'
);
}
public function testFieldMessage()
{
$this->v->addFieldMessage('username', 'required', 'We need a username, please.');
$this->v->validate([
'username' => ['', 'required']
]);
$this->assertEquals(
$this->v->errors()->first('username'),
'We need a username, please.'
);
}
public function testFieldMessages()
{
$this->v->addFieldMessages([
'username' => [
'required' => 'We need a username, please.'
],
'email' => [
'required' => 'How do you expect us to contact you without an email?'
]
]);
$this->v->validate([
'username' => ['', 'required|alpha'],
'email' => ['', 'required|email']
]);
$errors = $this->v->errors();
$this->assertEquals(
$errors->get('username'),
['We need a username, please.']
);
$this->assertEquals(
$errors->first('email'),
'How do you expect us to contact you without an email?'
);
}
public function testPassingCustomRule()
{
$this->v->addRule('isbanana', function($value, $input, $args) {
return $value === 'banana';
});
$this->v->validate([
'fruit' => ['apple', 'isbanana']
]);
$this->assertFalse($this->v->passes());
}
public function testFailingCustomRule()
{
$this->v->addRule('isbanana', function($value, $input, $args) {
return $value === 'banana';
});
$this->v->validate([
'fruit' => ['banana', 'isbanana']
]);
$this->assertTrue($this->v->passes());
}
public function testMultipleCustomRules()
{
$this->v->addRule('isbanana', function($value, $input, $args) {
return $value === 'banana';
});
$this->v->addRule('isapple', function($value, $input, $args) {
return $value === 'apple';
});
$this->v->validate([
'fruit_one' => ['banana', 'isbanana'],
'fruit_two' => ['apple', 'isapple']
]);
$this->assertTrue($this->v->passes());
}
public function testPassingCustomRuleWithArguments()
{
$this->v->addRule('isoneof', function($value, $input, $args) {
return in_array($value, $args);
});
$this->v->validate([
'items' => ['seeds', 'isoneof(seeds, nuts, fruit)']
]);
$this->assertTrue($this->v->passes());
}
public function testFailingCustomRuleWithArguments()
{
$this->v->addRule('isoneof', function($value, $input, $args) {
return in_array($value, $args);
});
$this->v->validate([
'items' => ['burger', 'isoneof(seeds, nuts, fruit)']
]);
$this->assertFalse($this->v->passes());
}
public function testValidationWithAliases()
{
$this->v->addFieldMessages([
'username_box' => [
'required' => 'We need a username in the {field} field, please.'
]
]);
$this->v->validate([
'username_box|Username' => ['', 'required'],
'password' => ['secret', 'required|alpha']
]);
$errors = $this->v->errors();
$this->assertFalse($this->v->passes());
$this->assertTrue($this->v->fails());
$this->assertEquals(
$errors->first('username_box'),
'We need a username in the Username field, please.'
);
}
public function testSkippingOtherRulesIfNotRequired()
{
$this->v->validate([
'username' => ['alex', 'required|alpha'],
'email' => ['', 'alpha|email']
]);
$this->assertEmpty($this->v->errors()->all());
}
}