|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Marcosh\PhpValidationDSL\Basic; |
|
6
|
|
|
|
|
7
|
|
|
use Marcosh\PhpValidationDSL\Result\ValidationResult; |
|
8
|
|
|
use Marcosh\PhpValidationDSL\Translator\Translator; |
|
9
|
|
|
use Marcosh\PhpValidationDSL\Validation; |
|
10
|
|
|
use function is_callable; |
|
11
|
|
|
use function preg_match; |
|
12
|
|
|
|
|
13
|
|
|
final class Regex implements Validation |
|
14
|
|
|
{ |
|
15
|
|
|
public const MATCH_FAILED = 'regex.match-failed'; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var string |
|
19
|
|
|
*/ |
|
20
|
|
|
private $pattern; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @var callable $key -> $data -> string[] |
|
24
|
|
|
*/ |
|
25
|
|
|
private $errorFormatter; |
|
26
|
|
|
|
|
27
|
|
|
private function __construct(string $pattern, ?callable $errorFormatter = null) |
|
28
|
|
|
{ |
|
29
|
|
|
$this->pattern = $pattern; |
|
30
|
|
|
$this->errorFormatter = is_callable($errorFormatter) ? |
|
31
|
|
|
$errorFormatter : |
|
32
|
|
|
function (string $key, $data) { |
|
|
|
|
|
|
33
|
|
|
return [self::MATCH_FAILED]; |
|
34
|
|
|
}; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
public static function withPattern(string $pattern):self |
|
38
|
|
|
{ |
|
39
|
|
|
return new self($pattern); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
public static function withPatternAndFormatter(string $pattern, callable $errorFormatter):self |
|
43
|
|
|
{ |
|
44
|
|
|
return new self($pattern, $errorFormatter); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
public static function withPatternAndTranslator(string $pattern, Translator $translator): self |
|
48
|
|
|
{ |
|
49
|
|
|
return new self( |
|
50
|
|
|
$pattern, |
|
51
|
|
|
function (string $key, $data) use ($translator) { |
|
|
|
|
|
|
52
|
|
|
return [$translator->translate(self::MATCH_FAILED)]; |
|
53
|
|
|
} |
|
54
|
|
|
); |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
public function validate($data, array $context = []): ValidationResult |
|
58
|
|
|
{ |
|
59
|
|
|
$match = preg_match($this->pattern, $data); |
|
60
|
|
|
|
|
61
|
|
|
if (false === $match || 0 === $match) { |
|
62
|
|
|
return ValidationResult::errors(($this->errorFormatter)($this->pattern, $data)); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
return ValidationResult::valid($data); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.