Issues (40)

php-src/Validation/Validator.php (2 issues)

1
<?php
2
3
namespace kalanis\Restful\Validation;
4
5
6
use kalanis\Restful\Exceptions\InvalidArgumentException;
7
use kalanis\Restful\Exceptions\InvalidStateException;
8
use kalanis\Restful\Validation\Exceptions\ValidationException;
9
use Nette\Utils\Strings;
10
use Nette\Utils\Validators;
11
12
13
/**
14
 * Rule validator
15
 * @package kalanis\Restful\Validation
16
 */
17 1
class Validator implements IValidator
18
{
19
20
    /** @var array<string, array<string, string>|callable|callable-string> Command handle callbacks */
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<string, array<stri...llable|callable-string> at position 13 could not be parsed: Unknown type name 'callable-string' at position 13 in array<string, array<string, string>|callable|callable-string>.
Loading history...
21
    public array $handle = [
22
        self::EMAIL => [self::class, 'validateEmail'],
23
        self::URL => [self::class, 'validateUrl'],
24
        self::REGEXP => [self::class, 'validateRegexp'],
25
        self::EQUAL => [self::class, 'validateEquality'],
26
        self::UUID => [self::class, 'validateUuid'],
27
        self::CALLBACK => [self::class, 'validateCallback'],
28
        self::REQUIRED => [self::class, 'validateRequired'],
29
    ];
30
31
    /**
32
     * Validate callback rule
33
     * @param string|int|float|null $value
34
     *
35
     * @throws  ValidationException If callback returns false
36
     */
37
    public static function validateCallback(mixed $value, Rule $rule): void
38
    {
39 1
        $arguments = $rule->getArgument();
40 1
        if (isset($arguments[0]) && is_callable($arguments[0])) {
41 1
            $result = $arguments[0]($value);
42 1
            if (true === $result) {
43 1
                return;
44
            }
45
        }
46 1
        throw ValidationException::createFromRule($rule, $value);
47
    }
48
49
    /**
50
     * Validate required rule
51
     * @param string|int|float|null $value
52
     *
53
     * @throws  ValidationException If field value is missing (is null)
54
     */
55
    public static function validateRequired(mixed $value, Rule $rule): void
56
    {
57 1
        if (is_null($value)) {
58 1
            throw ValidationException::createFromRule($rule, $value);
59
        }
60 1
    }
61
62
    /******************** Special validators ********************/
63
    /**
64
     * Validate regexp
65
     *
66
     * @throws InvalidArgumentException
67
     * @throws ValidationException
68
     */
69
    public static function validateRegexp(mixed $value, Rule $rule): void
70
    {
71 1
        if (!isset($rule->getArgument()[0])) {
72 1
            throw new InvalidArgumentException('No regular expression found in pattern validation rule');
73
        }
74
75 1
        if (!Strings::match(strval($value), strval($rule->getArgument()[0]))) {
0 ignored issues
show
Are you sure the usage of Nette\Utils\Strings::mat...ule->getArgument()[0])) targeting Nette\Utils\Strings::match() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
76 1
            throw ValidationException::createFromRule($rule, $value);
77
        }
78 1
    }
79
80
    /**
81
     * Validate equality
82
     * @param string $value
83
     * @throws ValidationException
84
     */
85
    public static function validateEquality(mixed $value, Rule $rule): void
86
    {
87 1
        if (!in_array(strval($value), $rule->getArgument())) {
88 1
            throw ValidationException::createFromRule($rule, $value);
89
        }
90 1
    }
91
92
    /**
93
     * Validate email
94
     * @param string $value
95
     * @throws ValidationException
96
     */
97
    public static function validateEmail(mixed $value, Rule $rule): void
98
    {
99 1
        if (!Validators::isEmail(strval($value))) {
100 1
            throw ValidationException::createFromRule($rule, $value);
101
        }
102 1
    }
103
104
    /**
105
     * Validate URL
106
     * @param string $value
107
     * @throws ValidationException
108
     */
109
    public static function validateUrl(mixed $value, Rule $rule): void
110
    {
111 1
        if (!Validators::isUrl(strval($value))) {
112 1
            throw ValidationException::createFromRule($rule, $value);
113
        }
114 1
    }
115
116
    /**
117
     * Validate UUID
118
     * @param string $value
119
     * @throws ValidationException
120
     */
121
    public static function validateUuid(mixed $value, Rule $rule): void
122
    {
123 1
        $isUuid = (bool) preg_match("/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i", strval($value));
124 1
        if (!$isUuid) {
125 1
            throw ValidationException::createFromRule($rule, $value);
126
        }
127 1
    }
128
129
    /**
130
     * Validate value for this rule
131
     * @param mixed $value
132
     * @param Rule $rule
133
     * @throws InvalidStateException
134
     * @throws ValidationException
135
     * @return void
136
     */
137
    public function validate(mixed $value, Rule $rule): void
138
    {
139 1
        if (isset($this->handle[$rule->getExpression()])) {
140 1
            $callback = $this->handle[$rule->getExpression()];
141 1
            if (!is_callable($callback)) {
142 1
                throw new InvalidStateException(
143 1
                    'Handle for expression ' . $rule->getExpression() . ' not found or is not callable');
144
            }
145 1
            $params = [$value, $rule];
146 1
            call_user_func_array($callback, $params);
147 1
            return;
148
        }
149
150 1
        $expression = $this->parseExpression($rule);
151 1
        if (!Validators::is($value, $expression)) {
152 1
            throw ValidationException::createFromRule($rule, $value);
153
        }
154 1
    }
155
156
    /**
157
     * Parse nette validator expression
158
     */
159
    private function parseExpression(Rule $rule): string
160
    {
161 1
        $givenArgumentsCount = count($rule->getArgument());
162 1
        $expectedArgumentsCount = substr_count($rule->getExpression(), '%');
163 1
        if ($expectedArgumentsCount != $givenArgumentsCount) {
164 1
            throw new InvalidArgumentException(
165 1
                'Invalid number of arguments for expression "' . $rule->getExpression() . '". Expected ' . $expectedArgumentsCount . ', ' . $givenArgumentsCount . ' given.'
166
            );
167
        }
168 1
        return vsprintf($rule->getExpression(), $rule->getArgument());
169
    }
170
}
171