Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
Regex
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
2 / 2
4
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 execute
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2
3/**
4 * @license MIT
5 * @author hazuki3417<hazuki3417@gmail.com>
6 * @copyright 2022 hazuki3417 all rights reserved.
7 */
8
9namespace Selen\MongoDB\Validator\Attributes;
10
11use Attribute;
12use Selen\MongoDB\Validator\Model\ValidateResult;
13use Selen\MongoDB\Validator\ValueValidateInterface;
14
15#[Attribute(Attribute::TARGET_PROPERTY)]
16class Regex implements ValueValidateInterface
17{
18    /** @var string */
19    protected $messageFormat = 'Invalid value. expected value %s.';
20
21    /** @var string */
22    protected $pattern;
23
24    public function __construct(string $pattern)
25    {
26        $this->pattern = $pattern;
27    }
28
29    /**
30     * 検証を実行します
31     *
32     * @param mixed          $value  検証する値を渡します
33     * @param ValidateResult $result 検証結果を格納するオブジェクトを渡します
34     */
35    public function execute($value, ValidateResult $result): ValidateResult
36    {
37        // NOTE: string型以外が来たときはバリデーションを行わない
38        if (!\is_string($value)) {
39            $mes = 'Skip validation. Executed only when the value is of string type';
40            return $result->setResult(true)->setMessage($mes);
41        }
42
43        if (!\preg_match("/{$this->pattern}/", $value)) {
44            $mes = \sprintf($this->messageFormat, $this->pattern);
45            return $result->setResult(false)->setMessage($mes);
46        }
47        return $result->setResult(true);
48    }
49}