|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace kalanis\kw_rules\Rules\External; |
|
4
|
|
|
|
|
5
|
|
|
|
|
6
|
|
|
use kalanis\kw_rules\Interfaces\IValidate; |
|
7
|
|
|
use kalanis\kw_rules\Exceptions\RuleException; |
|
8
|
|
|
use kalanis\kw_rules\Rules\ARule; |
|
9
|
|
|
use kalanis\kw_rules\Rules\TCheckString; |
|
10
|
|
|
|
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Class IsPostCode |
|
14
|
|
|
* @package kalanis\kw_rules\Rules\External |
|
15
|
|
|
* Check if input is post code for preset country |
|
16
|
|
|
* @link https://gist.github.com/jamesbar2/1c677c22df8f21e869cca7e439fc3f5b |
|
17
|
|
|
* @codeCoverageIgnore need external source |
|
18
|
|
|
*/ |
|
19
|
|
|
class IsPostCode extends ARule |
|
20
|
|
|
{ |
|
21
|
|
|
use TCheckString; |
|
22
|
|
|
|
|
23
|
|
|
/** @var array<string, array<string, string>> */ |
|
24
|
|
|
protected static array $codes = []; |
|
25
|
|
|
|
|
26
|
|
|
public static function loadCodes(string $pathToCodes): void |
|
27
|
|
|
{ |
|
28
|
|
|
$codeFile = strval(file_get_contents($pathToCodes)); |
|
29
|
|
|
/** @var array<int, array<string, string>> $codes */ |
|
30
|
|
|
$codes = json_decode($codeFile, true); |
|
31
|
|
|
static::$codes = array_combine( |
|
32
|
|
|
array_column($codes, 'ISO'), |
|
33
|
|
|
$codes |
|
34
|
|
|
); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
public function validate(IValidate $entry): void |
|
38
|
|
|
{ |
|
39
|
|
|
if (!isset(static::$codes[$this->againstValue])) { |
|
40
|
|
|
throw new RuleException(sprintf('Unknown preset ISO key for country %s', $this->againstValue) ); |
|
41
|
|
|
} |
|
42
|
|
|
$rule = static::$codes[$this->againstValue]; |
|
43
|
|
|
if (empty($rule['Regex']) && empty($entry->getValue())) { |
|
44
|
|
|
return; |
|
45
|
|
|
} |
|
46
|
|
|
if (!boolval(preg_match($rule['Regex'], $entry->getValue()))) { |
|
47
|
|
|
throw new RuleException($this->errorText); |
|
48
|
|
|
} |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
|