Download the PHP package djb/guard without Composer
On this page you can find all versions of the php package djb/guard. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package guard
guard
Swift 2 inspired guard for PHP to make simple validation more readable.
Will add more methods as and when I need extended functionality, or if requested - pull requests welcome as well!
installation
composer require djb/guard
suggested usage
Common validation required: email address, string, int, greaterthan, less than etc should be handled by the package.
After that I suggest extending the class to incorporate your own readable guard methods:
In use:
Note that to use the guard()
function with your new class, you will need to modify the helpers.php
file in the package to instantiate your new class instead of the package base class.
syntax
The syntax is inspired by Swift 2's guard feature, to guard a simple variable with an exception you could use the otherwise
method:
or you can get a boolean pass or fail using passes
:
or you can have guard raise an Exception
for you with raises
:
All validation methods handled by guard have a built in validation error description like the one above.
You can override this by subclassing \DJB\Guard\Guard
, as in the example in suggested usage, and providing the $exceptionMessages
property with keys matching the error code you want to override. i.e:
would override the between($min, $max)
validation method's error message.
validation methods
You can check if the variable:
exists
- exists (if the var has length, or is abool
orarray
)isTrue
- evaluates to booltrue
isFalse
- evaluates to boolfalse
isDate
- is in a valid date formatisClass($className)
- is an instance of class$className
isArray
- is anarray
isInteger
- is aninteger
isString
- is astring
isAlpha
- contains only alphabetic charactersisNumeric
- contains only numeric charactersisEmailAddress
- is in email address formatisURL
- is a URLisActiveURL
- is an URL which can be reached (i.e. website is live)isJSON
- is a valid JSON stringisIP
- is IP address formatlength($length)
- is the length specifiedin(Array $acceptable)
- is one of the accepted valuesnotIn(Array $excluded)
- is not one of the excluded valuesafter($date)
- is after the provided date (can be a date format string, or an instance ofDateTime
)before($date)
- is before the provided date (can be a date format string, or an instance ofDateTime
)between($min, $max)
- is between the$min
and$max
values (can be a date format string, instance ofDateTime
or numbers)equal($value)
- is equal to the provided value (number, string)lessThan($value)
- is less than the provided value (number)greaterThan($value)
- is greater than the provided value (number)equalOrLessThan($value)
- is equal or less than the provided value (number)equalOrGreaterThan($value)
- is equal or greater than the provided value (number)