\Cake\Http\MiddlewareBodyParserMiddleware

Parse encoded request body data.

Enables JSON and XML request payloads to be parsed into the request's Provides CSRF protection & validation.

You can also add your own request body parsers using the addParser() method.

Summary

Methods
Properties
Constants
__construct()
setMethods()
addParser()
__invoke()
No public properties found
No constants found
decodeJson()
decodeXml()
$parsers
$methods
N/A
No private methods found
No private properties found
N/A

Properties

$parsers

$parsers : array

Registered Parsers

Type

array

$methods

$methods : array

The HTTP methods to parse data on.

Type

array

Methods

__construct()

__construct(array  $options = array()) 

Constructor

Options

  • json Set to false to disable json body parsing.
  • xml Set to true to enable XML parsing. Defaults to false, as XML handling requires more care than JSON does.
  • methods The HTTP methods to parse on. Defaults to PUT, POST, PATCH DELETE.

Parameters

array $options

The options to use. See above.

setMethods()

setMethods(array  $methods) : $this

Set the HTTP methods to parse request bodies on.

Parameters

array $methods

The methods to parse data on.

Returns

$this

addParser()

addParser(array  $types, callable  $parser) : $this

Add a parser.

Map a set of content-type header values to be parsed by the $parser.

Example

An naive CSV request body parser could be built like so:

$parser->addParser(['text/csv'], function ($body) {
  return str_getcsv($body);
});

Parameters

array $types

An array of content-type header values to match. eg. application/json

callable $parser

The parser function. Must return an array of data to be inserted into the request.

Returns

$this

__invoke()

__invoke(\Psr\Http\Message\ServerRequestInterface  $request, \Psr\Http\Message\ResponseInterface  $response, callable  $next) : \Cake\Http\Response

Apply the middleware.

Will modify the request adding a parsed body if the content-type is known.

Parameters

\Psr\Http\Message\ServerRequestInterface $request

The request.

\Psr\Http\Message\ResponseInterface $response

The response.

callable $next

Callback to invoke the next middleware.

Returns

\Cake\Http\Response

A response

decodeJson()

decodeJson(string  $body) : array

Decode JSON into an array.

Parameters

string $body

The request body to decode

Returns

array

decodeXml()

decodeXml(string  $body) : array

Decode XML into an array.

Parameters

string $body

The request body to decode

Returns

array