takemo101/simple-prop-check

v0.2.2 2022-09-19 05:20 UTC

This package is auto-updated.

Last update: 2024-09-19 09:35:47 UTC


README

Testing PHPStan Validate Composer

Simple Prop Check 是一个简单的属性验证器。
享受吧!

安装

执行以下 composer 命令。

composer require takemo101/simple-prop-check

如何使用

请按照以下方式使用

PHP 属性

使用 PHP 的属性功能验证属性。

<?php

use Takemo101\SimplePropCheck\PropCheckFacade;
use Takemo101\SimplePropCheck\Preset\String\ {
    Email,
    Between,
    Pattern,
};
use Takemo101\SimplePropCheck\Preset\Numeric\Min;
use Takemo101\SimplePropCheck\Preset\Array\TypedValue;
use Takemo101\SimplePropCheck\Preset\NotEmpty;

/**
 * You can check the value by setting Attribute to the property of the class.
 */
class Test
{
    #[Email]
    public static string $email = 'xxx@example.com',

    public function __construct(
        #[Between(1, 10)]
        private string $between,
        // Exception message can also be set.
        #[Pattern('/[a]+/', 'not match')]
        private string $pattern,
        #[Min(3)]
        private integer $min,
        // Validate array values ​​by type.
        #[TypedValue('integer|string')]
        private array $nums,
        #[NotEmpty]
        private $notEmpty = null,
    ) {
        //
    }
}

$test = new Test(
    'hello',
    'are',
    4,
    [
        1,
        2,
        'hello',
    ]
);

// Validate the property by passing the object to the check method.
// The result is true or false.
$result = PropCheckFacade::check($test); // $result == false

// By passing an object to the exception method, the validation result will be returned as an exception.
PropCheckFacade::exception($test); // throw exception

提供的属性

以下属性类可用。

自定义

您可以对属性类等进行自定义。

如何自定义属性属性

首先,创建一个实现 AbstractValidatable 或 Validatable 的属性类。

<?php

use Takemo101\SimplePropCheck\AbstractValidatable;

/**
 * Implement the AbstractValidatable class by extending it,
 * or implement the Validatable interface.
 * 
 * @extends AbstractValidatable<string>
 */
#[Attribute(Attribute::TARGET_PROPERTY)]
class MatchText extends AbstractValidatable
{
    /**
     * constructor
     *
     * @param string|null $message
     */
    public function __construct(
        private ?string $message = null,
    ) {
        //
    }

    /**
     * Verify the value of $data with the verify method.
     * Returns true if the value is not invalid.
     *
     * @param string $data
     * @return boolean returns true if the data is OK
     */
    public function verify($data): bool
    {
        return $data == $this->text;
    }

    /**
     * Returns an error message if the value of the property is incorrect
     *
     * @return string
     */
    public function message(): string
    {
        // You can use the value set by the placeholders method in the error message as a placeholder.
        return $this->message ?? "data dose not match :text";
    }

    /**
     * Returns the value available in the error message placeholder.
     *
     * @return array<string,mixed>
     */
    public function placeholders(): array
    {
        return [
            'text' => $this->text, // The placeholder will be ':text'
        ];
    }

    /**
     * Return whether the value of the property is verifiable.
     * Basically check the value type.
     *
     * @param mixed $data
     * @return bool
     */
    public function canVerified($data): bool
    {
        return is_string($data);
    }

}

如下使用创建的属性类。

<?php

use Takemo101\SimplePropCheck\PropCheckFacade;

class Test
{
    public function __construct(
        #[MatchText('hello')]
        private string $hello,
    ) {
        //
    }
}

$test = new Test('hi');
$result = PropCheckFacade::check($test); // $result == false

$test = new Test('hello');
$result = PropCheckFacade::check($test); // $result == true

如何自定义异常属性

首先,创建一个实现 AbstractException 或 ExceptionFactory 的属性类。

<?php

use Throwable;
use LogicException;
use Takemo101\SimplePropCheck\Exception\AbstractException;

/**
 * Implement the AbstractException class by extending it,
 * or implement the ExceptionFactory interface.
 */
#[Attribute(Attribute::TARGET_PROPERTY)]
class TestException extends AbstractException
{
    /**
     * Generate an exception in the factory method and return.
     *
     * @param string $message
     * @return Throwable
     */
    public function factory(string $message): Throwable
    {
        return new LogicException("property logic error: {$message}");
    }
}

如下使用创建的属性类。

<?php

use Takemo101\SimplePropCheck\PropCheckFacade;

class Test
{
    public function __construct(
        // You can set an exception to throw for the property you want to validate.
        #[MatchText('hello')]
        #[TestException]
        private string $hello,
    ) {
        //
    }
}

$test = new Test('hi');
PropCheckFacade::exception($test); // throw LogicException

关于 Effect 类

Effect 属性允许您将验证效果应用于感兴趣的属性。

<?php

use Takemo101\SimplePropCheck\Preset\NotEmpty;
use Takemo101\SimplePropCheck\ {
    PropCheckFacade,
    Effect,
};

class First
{
    public function __construct(
        #[NotEmpty]
        private string $text,
        // Validate the object.
        #[Effect]
        private Second $second,
    ) {}
}

class Second
{
    public function __construct(
        #[NotEmpty]
        private string $text,
        // Apply validation to object array.
        #[Effect]
        private array $third,

    ) {}
}

class Third
{
    public function __construct(
        #[NotEmpty]
        private string $text,
    ) {}
}

$first = new First(
    'text',
    new Second(
        'text',
        [
            new Third(
                'text',
            ),
            new Third(
                'text',
            ),
            // Invalid validation of this object
            new Third(
                '',
            ),
        ],
    ),
);

$result = PropCheckFacade::check($first); // $result == false

PropCheckFacade::exception($first); // throw exception

关于 AfterCall 类

AfterCall 属性类允许您设置在验证属性的值之后要调用的方法。

<?php

use Takemo101\SimplePropCheck\Preset\NotEmpty;
use Takemo101\SimplePropCheck\ {
    PropCheckFacade,
    AfterCall,
};

// Set the method name in the argument of AfterCall attribute class.
#[AfterCall('print')]
class CallClass
{
    public function __construct(
        #[NotEmpty]
        private string $text,
    ) {}

    private function print(): void
    {
        echo 'call';
    }

}

$call = new CallClass('text');

// If the value validation is successful, the specified method will be executed.
$result = PropCheckFacade::check($call); // $result == true

$call = new CallClass('');

// If the value validation fails, the specified method will not be executed.
$result = PropCheckFacade::check($call); // $result == false