Skip to content

Commit

Permalink
Validator增加Json格式支持 (swoft-cloud/swoft-component#122)
Browse files Browse the repository at this point in the history
* 增加Json Validator支持
* 当content-type为json时,重置$post的数据,进行验证
* get json value by dot notation for validator
  • Loading branch information
limingxinleo authored and huangzhhui committed Jul 12, 2018
1 parent f54584c commit 649e67a
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions src/Validator/HttpValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@

use Swoft\Bean\Annotation\Bean;
use Swoft\Bean\Annotation\ValidatorFrom;
use Swoft\Helper\ArrayHelper;
use Swoft\Helper\JsonHelper;
use Swoft\Http\Message\Server\Request;
use Swoft\Http\Message\Stream\SwooleStream;
use Swoft\Validator\AbstractValidator;

/**
Expand Down Expand Up @@ -53,10 +56,17 @@ private function validateField($request, array $matches, string $type, array $va
{
$get = $request->getQueryParams();
$post = $request->getParsedBody();
$contentType = $request->getHeader('content-type');
$isPostJson = false;
if ($contentType && \in_array('application/json', $contentType)) {
$isPostJson = true;
$post = $request->json();
}

foreach ($validatorAry as $name => $info) {
$default = array_pop($info['params']);
if ($type === ValidatorFrom::GET) {
if (! isset($get[$name])) {
if (!isset($get[$name])) {
$request = $request->addQueryParam($name, $default);
$this->doValidation($name, $default, $info);
continue;
Expand All @@ -66,16 +76,22 @@ private function validateField($request, array $matches, string $type, array $va
continue;
}
if ($type === ValidatorFrom::POST && \is_array($post)) {
if (! isset($post[$name])) {
$request = $request->addParserBody($name, $default);
if (! ArrayHelper::has($post, $name)) {
ArrayHelper::set($post, $name, $default);
if ($isPostJson) {
$request = $request->withBody(new SwooleStream(JsonHelper::encode($post)));
} else {
$request = $request->addParserBody($name, $default);
}

$this->doValidation($name, $default, $info);
continue;
}
$this->doValidation($name, $post[$name], $info);
$this->doValidation($name, ArrayHelper::get($post, $name), $info);
continue;
}
if ($type === ValidatorFrom::PATH) {
if (! isset($matches[$name])) {
if (!isset($matches[$name])) {
continue;
}
$this->doValidation($name, $matches[$name], $info);
Expand Down

0 comments on commit 649e67a

Please sign in to comment.