locomotivemtl/charcoal-validator

dev-master 2020-05-06 14:34 UTC

This package is auto-updated.

Last update: 2024-12-07 00:16:24 UTC


README

Powerful data validation.

Table of content

How to install

The preferred (and only supported) way of installing charcoal-rule is with composer:

composer require locomotivemtl/charcoal-rule

Dependencies

  • PHP 7.2+
  • ext-json
  • For result serialization.
  • ext-mb
    • For multibytes (unicode) string length validation.
  • ext-fileinfo
    • For reading file's mimetype information.

Example usage

$validator = new Validator([
	new NullRule(),
	new LengthRule([ 'min' => 3, 'max' => 200 ])
],
[
	new LengthRule([ 'max' => 150 ])
]);

$stringToValidate = 'foobar';
$result = $validator($stringToValidate);
echo $result->isValid();

The Validator

The validator is the main interface to all validations. Its goal is to link various validators to perform series of validations in a unified way. It also allows to split the validations by level (error, warning or info).

It has a single function, validate(), which is also invokable, and returns a Validation object.

public function __construct(
  array $errorRules,
  array $warningRules,
  array $infoRules
);
public function __invoke($val): Validation;

The Validation object

The Validation object is a collection of results (\Charcoal\Validator\Result) for each validation levels. It is typically not instantiated directly, but returned from invoking a Validator instance.

public function results(
    ?string $level=null,
    bool $returnFailures=true,
    bool $returnSkipped=false,
    bool $returnSuccess=false
) : array;
public function isValid(?string $level=null) : bool;
public function isSkipped(): bool;

Validator options

Validation runners are stateless; all options must be passed directly to the constructor.

The only options available are the different types of rules to use. See the example

Rules

Every rule is stateless, all options must be passed directly to the constructor.

Every rule have only one public method: process($val), which can also be invoked directly. It always returns a Result object.

Result

Result holds the result code after processing a rule on.a value. It is typically not instantiated directly, but returned from invoking a Rule instance.

public function getType(): string;
public function getCode(): string;
public function getMessage(): string;
public function isValid() : bool;
public function isSkipped(): bool;

Available rules

Date Validator

The date validator ensures a value is a date-compatible string or a DateTime object and, optionally, in a specific range between min and max.

Options

Result messages

Email Validator

The email validator ensures a value is a proper email address.

Options

Result messages

Empty Validator

The empty validator ensures a value is not "empty". In PHP, empty means '', [] (an empty array), 0, '0', false or null. Any object instance is not considered empty.

Options

Result Messages

Length Validator

The length validator ensures a string (or a string-object) is of a certain length.

This validator skips null or empty strings. Use the Null Validator or the Empty Validator to check for those cases, if need.

This validator works with unicode by default (using mb_strlen for comparison). It can be disabled by setting the unicode option to false.

Options

Using the unicode flag uses the mb_strlen to calculate strin length. Therefore, the mb PHP extension is required.

Result messages

Null Validator

The empty validator ensures a value is not null.

It can also performs the opposite validation (ensuring a value is null) by setting the require_null option to true.

Options

Result messages

Pattern Validator

The pattern validator ensures a string (or a string-object) is of a certain length.

Options

Messages

Custom Rules

It's very simple to add a custom rule to a Validator constructor. The abstract \Charcoal\Validator\Rule can be extended to create custom rule service. Alternatively callback rules are supported as long as they have the following signature:

use \Charcoal\Validator\Result;
function(mixed $value) : Result;

Here is an example of a callback custom rule:

use \Charcoal\Validator\Validator;
use \Charcoal\Validator\NullRule;
use \Charcoal\Validator\Result;

$validator = new Validator([
	new NullRule(),
	function($value) : Result  {
		if (!is_string($value)) {
			 return new Result(
				 Result::TYPE_SKIPPED,
				 'fullstop.skipped.invalid-type',
				 'Value is not a string.'
				);
		}
		if (substr($val, -1) !== '.') {
			return new Result(
				Result::TYPE_FAILURE,
				'fullstop.error.no-fullstop',
				'The sentence does not end with a full stop.'
			);
		} else {
			return new Result(
				Result::TYPE_SUCCESS,
				'fullstop.success.fullstop',
				'The sentence ends with a full stop.'
			);
		}
	}
]);
$validationResult = $validator($val);
$success = $validationResult->isValid();
$results = $validationResult->results(Validator::LEVEL_ERROR);

It is also possible to use an instance of Rule, which provides some helper functions to generate responses and messages:

use \Charcoal\Validator\Validator;
use \Charcoal\Validator\NullRule;
use \Charcoal\Validator\Rule;
use \Charcoal\Validator\Result;

class FullStopRule extends Rule
{
	public function process($val): Result {
		if (!is_string($val)) {
			return $this->skip('fullstop.skipped.invalid-type');
		}
		if (substr($val, -1) !== '.') {
			return $this->failure('fullstop.error.no-fullstop');
		} else {
			return $this->success('fullstop.success.fullstop');
		}

	}

	public function messages(): array
	{
		return [
			'fullstop.skipped.invalid-type' => '',
			'fullstop.error.no-fullstop' => '',
			'fullstop.success.fullstop' => ''
		];
	}
};

$validator = new Validator([
	new NullRule(),
	new FullStopRule()
]);

$validationResult = $validator($val);
$success = $validationResult->isValid();
$results = $validationResult->results(Validator::LEVEL_ERROR);

Development

To install the development environment:

$ composer install --prefer-source

Run tests with

$ composer test

Development dependencies

  • phpunit/phpunit
  • squizlabs/php_codesniffer
  • satooshi/php-coveralls

Continuous Integration

Coding Style

The Charcoal-Validator module follows the Charcoal coding-style:

Coding style validation / enforcement can be performed with composer phpcs. An auto-fixer is also available with composer phpcbf.

This module should also throw no error when running phpstan analyse --level=max src/ tests/ 👍.

Authors

License

The MIT License (MIT)

Copyright © 2016 Locomotive inc.

See Authors.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.