harp-orm/validate

Object validaiton library

0.4 2014-08-28 08:39 UTC

This package is auto-updated.

Last update: 2024-03-21 19:27:22 UTC


README

Build Status Scrutinizer Code Quality Code Coverage Latest Stable Version

Harp Validate is a validation library. It generates errors for objects based on a predefined assertions.

Quick Example:

use Harp\Validate\Assert;
use Harp\Validate\Asserts;

$asserts = new Asserts(array(
    new Assert\Present('title'),
    new Assert\LengthBetween('title', 20, 100),
    new Assert\Email('newsletter_email'),
));

$subject = new stdClass();
$subject->title = 'small title';
$subject->newsletter_email = 'invalid email';

// title should be between 10 and 20 letters, newsletter_email should be a valid email
echo $asserts->getErrors($subject);

Errors

The result of $asserts->getErrors($subject) is actually an Errors object. It's an Iterator that holds all the erorrs and has ->humanize() mehtod to display all the errors. You can also foreach it and get all the errors separately. Casting it to string calls ->humanize() automatically.

$errors = $asserts->getErrors($subject);

foreach($errors => $error) {
    echo $error->getName();
    echo $error->getMessage();
}

You can also traverse through the Errors object using getFirst and getNext methods.

$errors = $asserts->validate($subject);

echo $errors->getFirst();
echo $errors->getNext();

ValidateTrait

You can also add a special trait to an object to make it "validatable".

use Harp\Validate\ValidateTrait;
use Harp\Validate\Asserts;
use Harp\Validate\Assert\Present;

class Model
{
    use ValidateTrait;

    public $test;

    public function getValidationAsserts()
    {
        return new Asserts(array(
            new Present('test'),
        ));
    }
}

It will addd these methods to your class:

Method Description
validate() Perform the assertions, specified in the getValidationAsserts(). Will return true or false, and will set the errors object
getErrors() Returns an Errors object. If validate has not been called yet, will return an empty Errors object
isEmptyErrors() Return true or false
assertValid() Throw Harp\Validate\InvalidException if there are any errors

Available Asserts

Callback

Assert that the result of a given callback is true. You must use a closure object, and will recieve the subject and the value as arguments.

new Callback('state', function ($subject, $value) {
    return $value !== 'test';
})

Email

Assert if the value is not a proper email address. uses a small and fast regex which should handle most cases.

new Email('email_address')
new Email('email_address', 'some custom message')

EmailStrict

Assert if the value is not a proper email address. Uses a slower but more comprehensive check thane Email.

new EmailStrict('email_address')
new EmailStrict('email_address', 'some custom message')

GreaterThan

Assert that the value is greater than a set length. Value can be int or float or even numeric string

new GreaterThan('price', 20)
new GreaterThan('price', 20, 'some custom message')

InArray

Assert if the value is present in an array, uses a simple in_array call. Will throw InvalidArgumentException if the array is empty.

new InArray('state', array('big', 'small'))
new InArray('state', array('big', 'small'), 'some custom message')

IP

Assert that the value's is a valid IP address uses filter_var() internally

new IP('last_login_ip')
new IP('last_login_ip', 'some custom message')

IsInstanceOf

Assert if the value is an object of a given class is_a call. Will throw InvalidArgumentException if the class does not exist.

new IsInstanceOf('state', 'My\Example\Item')
new IsInstanceOf('state', 'My\Example\Item', 'some custom message')

LengthBetween

Assert that the value's string length is between two set lengths (including). Uses mb_strlen() internally.

new LengthLessThan('name', 10, 200)
new LengthLessThan('name', 10, 200, 'some custom message')

LengthEquals

Assert that the value is of exact string length. Uses mb_strlen() internally.

new LengthEquals('name', 20),
new LengthEquals('name', 20, 'some custom message')

LengthGreaterThan

Assert that the value's string length is longer than a set length. Uses mb_strlen() internally.

new LengthGreaterThan('name', 20)
new LengthGreaterThan('name', 20, 'some custom message')

LengthLessThan

Assert that the value's string length is shorter than a set length. Uses mb_strlen() internally.

new LengthLessThan('name', 20)
new LengthLessThan('name', 20, 'some custom message')

LessThan

Assert that the value is less than a set length. Value can be int or float or even numeric string

new LessThan('price', 20)
new LessThan('price', 20, 'some custom message')

Matches

Assert that a value of one property matches to the value of another

new Matches('password', 'password_confirmation')
new Matches('password', 'password_confirmation', 'some custom message')

IsInteger

Assert that the value is a integer number.

new IsInteger('quantity')
new IsInteger('quantity', 'some custom message')

IsFloat

Assert that the value is a float number.

new IsFloat('frequency')
new IsFloat('frequency', 'some custom message')

Present

Assert if the value is empty

new Present('title')
new Present('title', 'some custom message if needed')

RegEx

Assert that the value matches a given regex. Passed directly to preg_match()

new RegEx('card_number', '/\d{20}/')
new RegEx('card_number', '/\d{20}/', 'some custom message')

URL

Assert if the value is a valid url. Converts all UTF related charecters in the url to their proper encoding. It also will convert non-ASCII domain names, using "idn" if the "intl" extension is available. This is similar to what browsers normally do.

new URL('website')
new URL('website', 'some custom message')

URLStrict

Assert if the value is a valid url. Uses php's filter_var() method.

new URLStrict('website')
new URLStrict('website', 'some custom message')

AssertsTrait

This trait gives you the ability to easily add assertions to another object.

class TestConfig {
    use AssertsTrait;
}

$config = new TestConfig();

$config
    ->assertPresent('name')
    ->assertURL('homepage', 'must have a valid homepage');

// Return the Asserts object
$config->getAsserts();

Here are all the methods added by this trait.

Method Description
getAsserts() Get the Asserts object
addAssert(AbstractAssertion) Add arbitrary asserts
assertCallback($name, $message) Add an Assert\Callback object
assertEmail($name, $message) Add an Assert\Email object
assertEmailStrict($name, $message) Add an Assert\EmailStrict object
assertGreaterThan($name, $value, $message) Add an Assert\GreaterThan object
assertInArray($name, $array, $message) Add an Assert\InArray object
assertIP($name, $message) Add an Assert\IP object
assertIsInteger($name, $message) Add an Assert\IsInteger object
assertIsInstanceOf($name, $class, $message) Add an Assert\IsInstanceOf object
assertIsFloat($name, $message) Add an Assert\IsFloat object
assertLengthBetween($name, $min, $max, $message) Add an Assert\LengthBetween object
assertLengthEquals($name, $length, $message) Add an Assert\LengthEquals object
assertLengthGreaterThan($name, $length, $message) Add an Assert\LengthGreaterThan object
assertLengthLessThan($name, $length, $message) Add an Assert\LengthLessThan object
assertLessThan($name, $value, $message) Add an Assert\LessThan object
assertMatches($name, $property, $message) Add an Assert\Matches object
assertPresent($name, $message) Add an Assert\Present object
assertRegEx($name, $pattern, $message) Add an Assert\RegEx object
assertURL($name, $message) Add an Assert\URL object
assertURLStrict($name, $message) Add an Assert\URLStrict object

License

Copyright (c) 2014, Clippings Ltd. Developed by Ivan Kerin as part of clippings.com

Under BSD-3-Clause license, read LICENSE file.