2017-05-31 05:40:22 +05:30
|
|
|
<?php
|
2019-12-14 00:57:13 +05:30
|
|
|
declare(strict_types=1);
|
|
|
|
|
2017-05-31 05:40:22 +05:30
|
|
|
namespace api\request;
|
|
|
|
|
|
|
|
use Yii;
|
|
|
|
use yii\web\JsonParser;
|
|
|
|
use yii\web\RequestParserInterface;
|
|
|
|
|
|
|
|
/**
|
2019-07-15 04:29:56 +05:30
|
|
|
* Since Yii2 doesn't provide an opportunity to make a fallback for an unparsed request,
|
|
|
|
* the query parsing logic must be fully reimplemented.
|
2017-05-31 05:40:22 +05:30
|
|
|
*
|
2019-07-15 04:29:56 +05:30
|
|
|
* The code is taken from \yii\web\Request::getBodyParams() and reworked in such a way
|
|
|
|
* that it tries to parse the request by the next steps:
|
|
|
|
* - first check if PHP has managed to do it by itself, then we return its value;
|
|
|
|
* - then we try to parse JSON, which is encoded in the body;
|
|
|
|
* - if it doesn't work out, let's assume it's a PUT, DELETE or other request
|
|
|
|
* that PHP doesn't automatically overpower to parse, so we try to parse it ourselves.
|
2017-05-31 05:40:22 +05:30
|
|
|
*/
|
|
|
|
class RequestParser implements RequestParserInterface {
|
|
|
|
|
2019-12-14 00:57:13 +05:30
|
|
|
/**
|
|
|
|
* @param string $rawBody
|
|
|
|
* @param string $contentType
|
|
|
|
*
|
|
|
|
* @return array
|
|
|
|
* @throws \yii\web\BadRequestHttpException
|
|
|
|
*/
|
|
|
|
public function parse($rawBody, $contentType): array {
|
2017-05-31 05:40:22 +05:30
|
|
|
if (!empty($_POST)) {
|
|
|
|
return $_POST;
|
|
|
|
}
|
|
|
|
|
|
|
|
/** @var JsonParser $parser */
|
|
|
|
$parser = Yii::createObject(JsonParser::class);
|
|
|
|
$parser->throwException = false;
|
|
|
|
$result = $parser->parse($rawBody, $contentType);
|
|
|
|
if (!empty($result)) {
|
|
|
|
return $result;
|
|
|
|
}
|
|
|
|
|
|
|
|
mb_parse_str($rawBody, $bodyParams);
|
|
|
|
if (!empty($bodyParams)) {
|
|
|
|
return $bodyParams;
|
|
|
|
}
|
|
|
|
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|