Skip to content

Commit 649e67a

Browse files
limingxinleohuangzhhui
authored andcommitted
Validator增加Json格式支持 (swoft-cloud/swoft-component#122)
* 增加Json Validator支持 * 当content-type为json时,重置$post的数据,进行验证 * get json value by dot notation for validator
1 parent f54584c commit 649e67a

File tree

1 file changed

+21
-5
lines changed

1 file changed

+21
-5
lines changed

src/Validator/HttpValidator.php

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44

55
use Swoft\Bean\Annotation\Bean;
66
use Swoft\Bean\Annotation\ValidatorFrom;
7+
use Swoft\Helper\ArrayHelper;
8+
use Swoft\Helper\JsonHelper;
79
use Swoft\Http\Message\Server\Request;
10+
use Swoft\Http\Message\Stream\SwooleStream;
811
use Swoft\Validator\AbstractValidator;
912

1013
/**
@@ -53,10 +56,17 @@ private function validateField($request, array $matches, string $type, array $va
5356
{
5457
$get = $request->getQueryParams();
5558
$post = $request->getParsedBody();
59+
$contentType = $request->getHeader('content-type');
60+
$isPostJson = false;
61+
if ($contentType && \in_array('application/json', $contentType)) {
62+
$isPostJson = true;
63+
$post = $request->json();
64+
}
65+
5666
foreach ($validatorAry as $name => $info) {
5767
$default = array_pop($info['params']);
5868
if ($type === ValidatorFrom::GET) {
59-
if (! isset($get[$name])) {
69+
if (!isset($get[$name])) {
6070
$request = $request->addQueryParam($name, $default);
6171
$this->doValidation($name, $default, $info);
6272
continue;
@@ -66,16 +76,22 @@ private function validateField($request, array $matches, string $type, array $va
6676
continue;
6777
}
6878
if ($type === ValidatorFrom::POST && \is_array($post)) {
69-
if (! isset($post[$name])) {
70-
$request = $request->addParserBody($name, $default);
79+
if (! ArrayHelper::has($post, $name)) {
80+
ArrayHelper::set($post, $name, $default);
81+
if ($isPostJson) {
82+
$request = $request->withBody(new SwooleStream(JsonHelper::encode($post)));
83+
} else {
84+
$request = $request->addParserBody($name, $default);
85+
}
86+
7187
$this->doValidation($name, $default, $info);
7288
continue;
7389
}
74-
$this->doValidation($name, $post[$name], $info);
90+
$this->doValidation($name, ArrayHelper::get($post, $name), $info);
7591
continue;
7692
}
7793
if ($type === ValidatorFrom::PATH) {
78-
if (! isset($matches[$name])) {
94+
if (!isset($matches[$name])) {
7995
continue;
8096
}
8197
$this->doValidation($name, $matches[$name], $info);

0 commit comments

Comments
 (0)