webcore/validation-traits

简单的验证库

v2.0.0 2016-06-10 03:42 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:47:33 UTC


README

Travis SensioLabs Insight Scrutinizer Code Quality Code Coverage Dependency Status license

验证特性

这是一个PHP库/特性集合,旨在通过验证输入值简化不可变值对象的创建。其基本思想也受到Laravel的Eloquent模型验证特性nicolopignatelli/valueobjects的启发。

1.0版本对值对象的态度更为简单,主要通过一个特性提供验证。

安装

通过Composer

composer require webcore/validation-traits

示例

SingleValueObjectInterface 定义获取值的方法和与实现此接口的其他值对象进行比较的方法。

interface SingleValueObjectInterface
{
    /**
     * @return mixed
     */
    public function getValue();

    /**
     * Compare two SingleValueObject and tells whether they can be considered equal
     *
     * @param  SingleValueObjectInterface $object
     * @return bool
     */
    public function sameValueAs(SingleValueObjectInterface $object);
}

让我们定义一个包含3个规则的简单 Token

//example/Token.php
<?php
class Token implements SingleValueObjectInterface
{
    use SingleValueObjectTrait, NotEmptyTrait, Base64Trait, LengthTrait;

    protected function validation($value)
    {
        $this->validateNotEmpty($value);
        $this->validateBase64($value);
        $this->validateLength($value, 64);
    }
}

并尝试用有效和无效的值创建 Token 实例,并相互比较

//example/example.php
<?php
//nette/tester
use Tester\Assert;

//valid value
$value = str_repeat('BeerNowThere0sATemporarySolution', 2);
$tokenFoo = new Token($value);
Assert::same("BeerNowThere0sATemporarySolutionBeerNowThere0sATemporarySolution", $tokenFoo->getValue());

//compare with another object of same value
$tokenBar = new Token("BeerNowThere0sATemporarySolutionBeerNowThere0sATemporarySolution");
$areSame = $tokenBar->sameValueAs($tokenFoo);
Assert::true($areSame);

//compare with another object of different value
$value = str_repeat('CraftBeerLovers0', 4); //
$tokenPub = new Token($value);
Assert::same("CraftBeerLovers0CraftBeerLovers0CraftBeerLovers0CraftBeerLovers0", $tokenPub->getValue());
$areSame = $tokenPub->sameValueAs($tokenBar);
Assert::false($areSame);

//invalid values
Assert::exception(
    function () {
        new Token(null);
    },
    InvalidArgumentException::class,
    "Token must be not empty"
);

Assert::exception(
    function () {
        new Token("InvalidTokenLength123456789");
    },
    InvalidArgumentException::class,
    "Token must be 64 characters long"
);

Assert::exception(
    function () {
        $value = str_repeat('?!@#$%^&', 8);
        new Token($value);
    },
    InvalidArgumentException::class,
    "Token must be valid base_64"
);

MIT许可

版权所有 (c) 2016, Štefan Peťovský