1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* @author AIZAWA Hina <[email protected]> |
5
|
|
|
* @copyright 2015 by AIZAWA Hina <[email protected]> |
6
|
|
|
* @license https://github.com/fetus-hina/yii2-jp-postalcode-validator/blob/master/LICENSE MIT |
7
|
|
|
* @since 1.0.0 |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace jp3cki\yii2\jppostalcode; |
11
|
|
|
|
12
|
|
|
use Yii; |
13
|
|
|
use yii\validators\Validator; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Validate Postal Code (JAPAN spec) |
17
|
|
|
*/ |
18
|
|
|
class JpPostalCodeValidator extends Validator |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* ハイフンの許可 |
22
|
|
|
* |
23
|
|
|
* @var bool|null null=気にしない, true=要求, false=許可しない |
24
|
|
|
*/ |
25
|
|
|
public $hyphen = null; |
26
|
|
|
|
27
|
|
|
/** @inheritdoc */ |
28
|
|
|
public function init() |
29
|
|
|
{ |
30
|
|
|
parent::init(); |
31
|
|
|
if ($this->message === null) { |
32
|
|
|
$this->message = Yii::t('jp3ckiJpPostalCode', '{attribute} is not a valid postal code.'); |
33
|
|
|
} |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** @inheritdoc */ |
37
|
|
|
public function validateAttribute($model, $attribute) |
38
|
|
|
{ |
39
|
|
|
if (!$this->isValid($model->$attribute)) { |
40
|
|
|
$this->addError($model, $attribute, $this->message); |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** @inheritdoc */ |
45
|
|
|
protected function validateValue($value) |
46
|
|
|
{ |
47
|
|
|
if (!$this->isValid($value)) { |
48
|
|
|
return [$this->message, []]; |
49
|
|
|
} |
50
|
|
|
return null; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
private function isValid($value) |
54
|
|
|
{ |
55
|
|
|
return $this->isValidFormat($value) && $this->isValidNumber($value); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
private function isValidFormat($value) |
59
|
|
|
{ |
60
|
|
|
if (preg_match('/^\d{3}-?\d{4}$/', $value)) { |
61
|
|
|
if ($this->hyphen === true) { |
62
|
|
|
return strpos($value, '-') !== false; |
63
|
|
|
} |
64
|
|
|
if ($this->hyphen === false) { |
65
|
|
|
return strpos($value, '-') === false; |
66
|
|
|
} |
67
|
|
|
return true; |
68
|
|
|
} |
69
|
|
|
return false; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
private function isValidNumber($value) |
73
|
|
|
{ |
74
|
|
|
$value = preg_replace('/[^0-9]+/', '', $value); |
75
|
|
|
$code1 = substr($value, 0, 3); |
76
|
|
|
$code2 = substr($value, 3, 4); |
77
|
|
|
$list = $this->loadJson($code1); |
78
|
|
|
return !!in_array($code2, $list, true); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
private function loadJson($code1) |
82
|
|
|
{ |
83
|
|
|
$path = __DIR__ . '/../data/postalcode/jp/' . $code1 . '.json.gz'; |
84
|
|
|
if (!file_exists($path)) { |
85
|
|
|
return []; |
86
|
|
|
} |
87
|
|
|
$ret = @json_decode(file_get_contents('compress.zlib://' . $path)); |
88
|
|
|
return is_array($ret) ? $ret : []; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|