/
HandleValidator.php
98 lines (87 loc) · 2.45 KB
/
HandleValidator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\validators;
use Craft;
use yii\validators\Validator;
/**
* Class HandleValidator.
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.0
*/
class HandleValidator extends Validator
{
// Static
// =========================================================================
/**
* @var string
*/
public static $handlePattern = '[a-zA-Z][a-zA-Z0-9_]*';
/**
* @var array
*/
public static $baseReservedWords = [
'attribute',
'attributeLabels',
'attributeNames',
'attributes',
'classHandle',
'content',
'dateCreated',
'dateUpdated',
'false',
'fields',
'handle',
'id',
'n',
'name',
'no',
'rawContent',
'rules',
'searchKeywords',
'section',
'this',
'true',
'type',
'uid',
'value',
'y',
'yes',
];
// Properties
// =========================================================================
/**
* @var array
*/
public $reservedWords = [];
// Public Methods
// =========================================================================
/**
* @inheritdoc
*/
public function validateAttribute($model, $attribute)
{
$handle = $model->$attribute;
// Handles are always required, so if it's blank, the required validator will catch this.
if ($handle) {
$reservedWords = array_merge($this->reservedWords, static::$baseReservedWords);
$reservedWords = array_map('strtolower', $reservedWords);
$lcHandle = strtolower($handle);
if (in_array($lcHandle, $reservedWords, true)) {
$message = Craft::t('app', '“{handle}” is a reserved word.',
['handle' => $handle]);
$this->addError($model, $attribute, $message);
} else {
if (!preg_match('/^' . static::$handlePattern . '$/', $handle)) {
$altMessage = Craft::t('app', '“{handle}” isn’t a valid handle.', ['handle' => $handle]);
$message = $this->message ?? $altMessage;
$this->addError($model, $attribute, $message);
}
}
}
}
}