Skip to content

Commit e4ae2b3

Browse files
committed
add scenarios() support. update readme and testing.
1 parent 2d9c423 commit e4ae2b3

File tree

6 files changed

+135
-18
lines changed

6 files changed

+135
-18
lines changed

README.md

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -87,41 +87,54 @@ class PageRequest extends Validation
8787
public function rules()
8888
{
8989
return [
90+
// 字段必须存在且不能为空
9091
['tagId,title,userId,freeTime', 'required'],
92+
9193
// 4<= tagId <=567
9294
['tagId', 'size', 'min'=>4, 'max'=>567, 'filter' => 'int'],
95+
9396
           // title length >= 40. 注意只需一个参数的验证,无需加 key, 如这里的 40
9497
           ['title', 'min', 40, 'filter' => 'trim'],
95-
           // 大于0
98+
99+
           // 大于 0
96100
           ['freeTime', 'number'],
101+
97102
// 含有前置条件
98103
['tagId', 'number', 'when' => function($data) {
99104
return isset($data['status']) && $data['status'] > 2;
100105
}],
106+
101107
// 在验证前会先过滤转换为 int。并且仅会在指明场景名为 'scene1' 时规则有效
102108
           ['userId', 'number', 'on' => 'scene1', 'filter' => 'int'],
103109
['username', 'string', 'on' => 'scene2', 'filter' => 'trim'],
110+
104111
// 使用自定义正则表达式
105112
['username', 'regexp' ,'/^[a-z]\w{2,12}$/'],
113+
106114
// 自定义验证器,并指定当前规则的消息
107115
['title', 'custom', 'msg' => '{attr} error msg!' ],
108-
['status', function($status) { // 直接使用闭包验证
116+
117+
// 直接使用闭包验证
118+
['status', function($status) {
109119
if (is_int($status) && $status > 3) {
110120
return true;
111121
}
112122
return false;
113123
}],
124+
114125
           // 标记字段是安全可靠的 无需验证
115126
           ['createdAt, updatedAt', 'safe'],
116127
];
117128
}
118129

119-
// 添加一个验证器。必须返回一个布尔值标明验证失败或成功
120-
protected function customValidator($title)
130+
// 定义不同场景需要验证的字段。
131+
// 功能跟规则里的 'on' 类似,两者尽量不要同时使用,以免混淆。
132+
public function scenarios(): array
121133
{
122-
// some logic ...
123-
124-
return true; // Or false;
134+
return [
135+
'create' => ['user', 'pwd', 'code'],
136+
'update' => ['user', 'pwd'],
137+
];
125138
}
126139

127140
// 定义字段翻译
@@ -141,6 +154,14 @@ class PageRequest extends Validation
141154
'title.required' => 'O, 标题是必填项。are you known?',
142155
];
143156
}
157+
158+
// 添加一个验证器。必须返回一个布尔值标明验证失败或成功
159+
protected function customValidator($title)
160+
{
161+
// some logic ...
162+
163+
return true; // Or false;
164+
}
144165
}
145166
```
146167

src/AbstractValidation.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,17 @@ public function __construct(
5959
}
6060
}
6161

62+
/**
63+
* @param array $data
64+
* @param string $scene
65+
* @param bool $startValidate
66+
* @return AbstractValidation
67+
*/
68+
public static function quick(array $data, string $scene = '', $startValidate = false)
69+
{
70+
return new static($data, [], [], $scene, $startValidate);
71+
}
72+
6273
/**
6374
* @param array $data
6475
* @param array $rules

src/Utils/ErrorMessageTrait.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -309,13 +309,13 @@ public function lastError($onlyMsg = true)
309309
}
310310

311311
/**
312-
* @param bool|null $stopOnError
312+
* @param bool|null $_stopOnError
313313
* @return $this
314314
*/
315-
public function setStopOnError($stopOnError = null): self
315+
public function setStopOnError($_stopOnError = null): self
316316
{
317-
if (null !== $stopOnError) {
318-
$this->_stopOnError = (bool)$stopOnError;
317+
if (null !== $_stopOnError) {
318+
$this->_stopOnError = (bool)$_stopOnError;
319319
}
320320

321321
return $this;

src/ValidationTrait.php

Lines changed: 40 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,11 @@ trait ValidationTrait
3737
/** @var \Closure after validate handler */
3838
private $_afterHandler;
3939

40+
/** @var array Used rules at current scene */
41+
protected $_usedRules = [];
42+
4043
/**
41-
* current scenario name
44+
* setting current scenario name
4245
* 当前验证的场景 -- 如果需要让规则列表在多个类似情形下使用
4346
* (
4447
* e.g: 在MVC框架中,
@@ -49,8 +52,12 @@ trait ValidationTrait
4952
*/
5053
protected $scene = '';
5154

52-
/** @var array Used rules at current scene */
53-
protected $_usedRules = [];
55+
/**
56+
* Whether to skip when empty(When not required)
57+
* default is TRUE, need you manual add 'required'.
58+
* @var bool
59+
*/
60+
private $_skipOnEmpty = true;
5461

5562
/**
5663
* @return array
@@ -87,8 +94,8 @@ public function messages()
8794
}
8895

8996
/**
90-
* 当前场景需要收集的字段
91-
* @todo un-complete
97+
* The field that the current scene needs to collect
98+
* @return array
9299
*/
93100
public function scenarios(): array
94101
{
@@ -163,6 +170,10 @@ public function validate(array $onlyChecked = [], bool $stopOnError = null)
163170
$cb($this);
164171
}
165172

173+
if (!$onlyChecked) {
174+
$onlyChecked = $this->getSceneFields();
175+
}
176+
166177
foreach ($this->collectRules() as $fields => $rule) {
167178
$fields = \is_string($fields) ? Helper::explode($fields) : (array)$fields;
168179
$validator = \array_shift($rule);
@@ -180,7 +191,7 @@ public function validate(array $onlyChecked = [], bool $stopOnError = null)
180191
}
181192

182193
// Whether to skip when empty(When not required). ref yii2
183-
$skipOnEmpty = $rule['skipOnEmpty'] ?? true;
194+
$skipOnEmpty = $rule['skipOnEmpty'] ?? $this->_skipOnEmpty;
184195
$filters = $rule['filter'] ?? null; // filter
185196
$defMsg = $rule['msg'] ?? null; // Custom error message
186197
$defValue = $rule['default'] ?? null;// Allow default
@@ -474,6 +485,19 @@ protected function prepareRule(array &$rule)
474485
* getter/setter/helper
475486
******************************************************************************/
476487

488+
/**
489+
* get fields for the scene.
490+
* @return array
491+
*/
492+
public function getSceneFields(): array
493+
{
494+
if ($this->scene && $conf = $this->scenarios()) {
495+
return $conf[$this->scene] ?? [];
496+
}
497+
498+
return [];
499+
}
500+
477501
/**
478502
* @param string $path 'users.*.id' 'goods.*' 'foo.bar.*.id'
479503
* @param null|mixed $default
@@ -570,7 +594,6 @@ public function getScene(): string
570594
public function atScene(string $scene): self
571595
{
572596
$this->scene = \trim($scene);
573-
574597
return $this;
575598
}
576599

@@ -594,6 +617,16 @@ public function onScene(string $scene)
594617
return $this->atScene($scene);
595618
}
596619

620+
/**
621+
* @param bool $_skipOnEmpty
622+
* @return static
623+
*/
624+
public function setSkipOnEmpty(bool $_skipOnEmpty)
625+
{
626+
$this->_skipOnEmpty = $_skipOnEmpty;
627+
return $this;
628+
}
629+
597630
/**
598631
* Get all items in collection
599632
* @return array The collection's source data

test/FieldValidationTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,4 +59,31 @@ public function testValidate()
5959
$this->assertNotEmpty($errors);
6060
$this->assertCount(1, $errors);
6161
}
62+
63+
public function testScenarios()
64+
{
65+
$data = [
66+
'user' => 'inhere',
67+
'pwd' => '123456',
68+
'code' => '1234',
69+
];
70+
71+
$v = FieldSample::quick($data,'create')->validate();
72+
$this->assertTrue($v->isOk());
73+
$this->assertEmpty($v->getErrors());
74+
75+
$data = [
76+
'user' => 'inhere',
77+
'pwd' => '123456',
78+
'code' => '12345',
79+
];
80+
81+
$v = FieldSample::quick($data,'create')->validate();
82+
$this->assertFalse($v->isOk());
83+
$this->assertEquals('code length must is 4', $v->firstError());
84+
85+
$v = FieldSample::quick($data,'update')->validate();
86+
$this->assertTrue($v->isOk());
87+
$this->assertEmpty($v->getErrors());
88+
}
6289
}

test/boot.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,28 @@
44
*/
55

66
require dirname(__DIR__) . '/example/simple-loader.php';
7+
8+
class FieldSample extends \Inhere\Validate\FieldValidation
9+
{
10+
public function rules(): array
11+
{
12+
return [
13+
['user', 'required|string:1,12'],
14+
['pwd', 'required|string:6,16'],
15+
['code', 'lengthEq:4'],
16+
];
17+
}
18+
19+
public function scenarios(): array
20+
{
21+
return [
22+
'create' => ['user', 'pwd', 'code'],
23+
'update' => ['user', 'pwd'],
24+
];
25+
}
26+
}
27+
28+
class RuleSample extends \Inhere\Validate\Validation
29+
{
30+
31+
}

0 commit comments

Comments
 (0)