yii\web\JsonParser::parse PHP Method

parse() public method

Parses a HTTP request body.
public parse ( string $rawBody, string $contentType ) : array
$rawBody string the raw HTTP request body.
$contentType string the content type specified for the request body.
return array parameters parsed from the request body
    public function parse($rawBody, $contentType)
    {
        try {
            $parameters = Json::decode($rawBody, $this->asArray);
            return $parameters === null ? [] : $parameters;
        } catch (InvalidParamException $e) {
            if ($this->throwException) {
                throw new BadRequestHttpException('Invalid JSON data in request body: ' . $e->getMessage());
            }
            return [];
        }
    }

Usage Example

 /**
  * Parse resource object into the input data to populates the model
  * @inheritdoc
  */
 public function parse($rawBody, $contentType)
 {
     $array = parent::parse($rawBody, $contentType);
     if ($type = ArrayHelper::getValue($array, 'data.type')) {
         $formName = call_user_func($this->formNameCallback, $type);
         if ($attributes = ArrayHelper::getValue($array, 'data.attributes')) {
             $result[$formName] = $attributes;
         } elseif ($id = ArrayHelper::getValue($array, 'data.id')) {
             $result[$formName] = ['id' => $id, 'type' => $type];
         }
         if ($relationships = ArrayHelper::getValue($array, 'data.relationships')) {
             foreach ($relationships as $name => $relationship) {
                 if (isset($relationship[0])) {
                     foreach ($relationship as $item) {
                         if (isset($item['type']) && isset($item['id'])) {
                             $formName = call_user_func($this->formNameCallback, $item['type']);
                             $result[$name][$formName][] = $item;
                         }
                     }
                 } elseif (isset($relationship['type']) && isset($relationship['id'])) {
                     $formName = call_user_func($this->formNameCallback, $relationship['type']);
                     $result[$name][$formName] = $relationship;
                 }
             }
         }
     } else {
         $data = ArrayHelper::getValue($array, 'data', []);
         foreach ($data as $relationLink) {
             if (isset($relationLink['type']) && isset($relationLink['id'])) {
                 $formName = call_user_func($this->formNameCallback, $relationLink['type']);
                 $result[$formName][] = $relationLink;
             }
         }
     }
     return isset($result) ? $result : $array;
 }
All Usage Examples Of yii\web\JsonParser::parse
JsonParser