Download the PHP package i-am-tom/schemer without Composer
On this page you can find all versions of the php package i-am-tom/schemer. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download i-am-tom/schemer
More information about i-am-tom/schemer
Files in i-am-tom/schemer
Package schemer
Short Description A Joi-like interface for validating data structures.
License ISC
Informations about the package schemer
Schemer
Schemer is a Joi-inspired library for validating and formatting data structures. Complex structures' validators can be constructed by composition.
Quickstart
The full API can be accessed via the Schemer\Validator
and Schemer\Formatter
sets of static functions. We'll bring them in with an alias:
Now, we'll declare a validator and a formatter:
We've used the Assoc
validator and formatter to create more complicated validators that nest data. The Collection
interfaces can do similar things for sequential arrays. So, let's look at the formatter:
We see that age
is now an integer, and the friends
key has been created with an empty array, as per the formatting instructions. When handling data from other sources, you'll probably want to attempt to format the data before validating it.
Validation comes in two flavours. First, we'll start with simple validation:
This flattens all the errors down to one Result
whose errors
method will return them in an array. While this may be suitable for validation of API requests, for example, it's often helpful for the structure of the errors to mimic the structure of the data. This can be achieved using nestedValidate
:
Although the above represents the result as an array, it is actually an instance of Schemer\NestedResult
, which implements both ArrayAccess
and Traversable
, which allows you to use foreach
syntax as well as array access to get at the results (e.g. $output['age']->errors() === ['missing key']
). If there's a nestable (Assoc
or Collection
) within your structure, nestedValidate
will recurse down through these in the same pattern, too!
Well, that's all there is to it! The API will fill in the rest of the blanks.
API
All methods are immutable. Calling a method will return a new object, and not change the previous one in any way:
Schemer\Formatter
Schemer\Validator
Many of these methods accept an optional custom $error
string, which overrides the default error.
Contributing
Get involved! PRs are cool.