Skip to content

Latest commit

 

History

History
449 lines (280 loc) · 11.9 KB

Request.md

File metadata and controls

449 lines (280 loc) · 11.9 KB

Request

A request is represented by a Request instance. The initial request is usually created from the $_SERVER array (Request::from_server()), while sub requests are created from arrays of Request::OPTION_* options (see RequestOptions).

<?php

namespace ICanBoogie\HTTP;

$initial_request = Request::from_server();

# a custom request in the same environment

$request = Request::from('path/to/file.html', $_SERVER);

# a request created from scratch

$request = Request::from([

    Request::OPTION_PATH => 'path/to/file.html',
    Request::OPTION_IS_LOCAL => true, // or OPTION_IP => '::1'
    Request::OPTION_METHOD => RequestMethod::METHOD_POST,
    Request::OPTION_HEADERS => [

        'Cache-Control' => 'no-cache'

    ]

]);

Client IP

The ip property returns the address of the peer that connected to the server (REMOTE_ADDR), and is_local is derived from it. Forwarding headers are ignored because any client can send them.

When the application runs behind proxies, use client_ip() with the addresses or CIDR ranges of the proxies you trust. X-Forwarded-For is only considered if the peer is a trusted proxy, and it is read from right to left until an address that isn't a trusted proxy is found.

<?php

namespace ICanBoogie\HTTP;

/* @var $request Request */

$request->ip; // 10.0.0.1, the load balancer
$request->client_ip([ '10.0.0.0/8' ]); // 198.51.100.1, the client

Request method

method is the method the client sent, read from REQUEST_METHOD, and GET if it is not defined.

HTML forms only send GET and POST, so target POST routes with them. A _method field has no effect. An application that needs forms to reach other methods can create a request with another one, before routing it:

<?php

namespace ICanBoogie\HTTP;

$request = Request::from_server();

if (
    $request->method === RequestMethod::METHOD_POST
    && ($request->request_params['_method'] ?? null) === 'DELETE'
) {
    $request = $request->with([ Request::OPTION_METHOD => RequestMethod::METHOD_DELETE ]);
}

A form of another site can send such a request, which a real DELETE can't do without the consent of the server (CORS). Only do this if the application verifies a CSRF token.

Safe and idempotent requests

Safe methods are HTTP methods that don't modify resources. For instance, using GET or HEAD on a resource URL, should NEVER change the resource.

The is_safe() method of the request method (RequestMethod) may be used to check if a request is safe or not.

<?php

use ICanBoogie\HTTP\Request;
use ICanBoogie\HTTP\RequestMethod;

Request::from([ Request::OPTION_METHOD => RequestMethod::METHOD_GET ])->method->is_safe(); // true
Request::from([ Request::OPTION_METHOD => RequestMethod::METHOD_POST ])->method->is_safe(); // false
Request::from([ Request::OPTION_METHOD => RequestMethod::METHOD_DELETE ])->method->is_safe(); // false

An idempotent HTTP method is an HTTP method that can be called many times without different outcomes. It would not matter if the method is called only once, or ten times over. The result should be the same.

The is_idempotent() method may be used to check if a request is idempotent or not.

<?php

use ICanBoogie\HTTP\Request;
use ICanBoogie\HTTP\RequestMethod;

Request::from([ Request::OPTION_METHOD => RequestMethod::METHOD_GET ])->method->is_idempotent(); // true
Request::from([ Request::OPTION_METHOD => RequestMethod::METHOD_POST ])->method->is_idempotent(); // false
Request::from([ Request::OPTION_METHOD => RequestMethod::METHOD_DELETE ])->method->is_idempotent(); // true

A request with changed properties

Requests are for the most part immutable, the with() method creates an instance copy with changed properties.

<?php

namespace ICanBoogie\HTTP;

$request = Request::from_server()->with([

    Request::OPTION_METHOD => RequestMethod::METHOD_HEAD,
    Request::OPTION_IS_XHR => true

]);

With OPTION_URI, query_params is parsed from the query string of the new URI, like from() does. If the URI has no query string, query_params is the OPTION_QUERY_PARAMS option, or an empty array.

The content_length, referer, user_agent, is_xhr and authorization properties are read from the headers of the request. Accordingly, OPTION_CACHE_CONTROL, OPTION_CONTENT_LENGTH, OPTION_IS_XHR, OPTION_REFERER and OPTION_USER_AGENT define header fields, with from() as well as with with(). They win over the same fields in OPTION_HEADERS, and a null value removes the field.

<?php

namespace ICanBoogie\HTTP;

/* @var $request Request */

$changed = $request->with([ Request::OPTION_USER_AGENT => 'Mozilla' ]);

$changed->user_agent;            // Mozilla
$changed->headers['User-Agent']; // Mozilla

Request parameters

Whether they're sent as part of the query string, the POST body, or the path info, parameters sent along a request are collected in arrays. The query_params, request_params, and path_params properties give you access to these parameters.

You can access each type of parameter as follows:

<?php

namespace ICanBoogie\HTTP;

/* @var $request Request */

$id = $request->query_params['id'];
$method = $request->request_params['method'];
$info = $request->path_params['info'];

All the request parameters are also available through the read-only params property, which merges the path, request and query parameters. It is computed on read, so it always reflects the three arrays. When the same key is found more than once, the path parameter wins over the request body, which wins over the query string:

<?php

namespace ICanBoogie\HTTP;

/* @var $request Request */

$id = $request->params['id'];
$method = $request->params['method'];
$info = $request->params['info'];

Request body

The initial request created with Request::from_server() exposes its body through body_stream, a SplFileObject of php://input. The body is not decoded, whatever its content type, which leaves the application free to read JSON, XML, or any other payload, and to stream large ones.

<?php

namespace ICanBoogie\HTTP;

$request = Request::from_server();

# the whole body, e.g. JSON

$body = '';

while (!$request->body_stream->eof()) {
    $body .= $request->body_stream->fread(8192);
}

$data = json_decode($body, true, flags: JSON_THROW_ON_ERROR);

# or line by line, e.g. NDJSON

foreach ($request->body_stream as $line) {
    $record = json_decode($line, true, flags: JSON_THROW_ON_ERROR);
}

Other requests have no body stream (body_stream is null). To provide one, e.g. in tests, use OPTION_BODY_STREAM:

<?php

namespace ICanBoogie\HTTP;

use SplFileObject;

$stream = new SplFileObject('php://memory', 'w+');
$stream->fwrite('{"name":"Madonna"}');
$stream->rewind();

$request = Request::from([ Request::OPTION_BODY_STREAM => $stream ]);

Note that PHP doesn't populate php://input for multipart/form-data requests, use files and request_params for those. The stream is shared by the clones created with with().

Conversely, request_params is a reference to $_POST, which PHP only fills for application/x-www-form-urlencoded and multipart/form-data, and only for a POST request. For an application/json request, or a PUT one, it is empty, even though the body is there. Code that reads request_params, e.g. #[Part] of icanboogie/routing, finds nothing until the body is decoded into it. For JSON, that package provides the middleware DecodeJsonBody. Without it, the application decodes the body and assigns the data, which must be an array.

Request files

Files associated with a request are collected in a FileList instance. The initial request created with $_SERVER obtain its files from $_FILES. For custom requests, files are defined using OPTION_FILES.

<?php

namespace ICanBoogie\HTTP;

$request = Request::from_server();

# or

$request = Request::from([

    Request::OPTION_FILES => [

        'uploaded' => [ FileOptions::OPTION_PATHNAME => '/path/to/my/example.zip' ]

    ]

]);

#

$files = $request->files;    // instanceof FileList
$file = $files['uploaded'];  // instanceof File
$file = $files['undefined']; // null

File represents uploaded files, and pretend uploaded files, with a single API. The is_uploaded property helps you set them apart.

The is_valid property is a simple way to check if a file is valid. The move() method lets you move the file out of the temporary folder or around the filesystem.

<?php

namespace ICanBoogie\HTTP;

/* @var $file File */

echo $file->name;            // example.zip
echo $file->unsuffixed_name; // example
echo $file->extension;       // .zip
echo $file->size;            // 1234
echo $file->type;            // application/zip
echo $file->is_uploaded;     // false

if ($file->is_valid)
{
    $file->move('/path/to/repository/' . $file->name, File::MOVE_OVERWRITE);
}

The match() method is used to check if a file matches a MIME type, a MIME class, or a file extension:

<?php

namespace ICanBoogie\HTTP;

/* @var $file File */

echo $file->match('application/zip');             // true
echo $file->match('application');                 // true
echo $file->match('.zip');                        // true
echo $file->match('image/png');                   // false
echo $file->match('image');                       // false
echo $file->match('.png');                        // false

The method also handles sets, and returns true if there is any match:

<?php

echo $file->match([ '.png', 'application/zip' ]); // true
echo $file->match([ '.png', '.zip' ]);            // true
echo $file->match([ 'image/png', '.zip' ]);       // true
echo $file->match([ 'image/png', 'text/plain' ]); // false

File instances can be converted into arrays with the to_array() method:

<?php

$file->to_array();
/*
[
    'name' => 'example.zip',
    'unsuffixed_name' => 'example',
    'extension' => '.zip',
    'type' => 'application/zip',
    'size' => 1234,
    'pathname' => '/path/to/my/example.zip',
    'error' => null,
    'error_message' => null
]
*/

Request context

Because requests may be nested, the request context offers a safe place where you can store the state of your application that is relative to a request. For instance, the context can store the relative site, page, route, dispatcher…

The following example demonstrates how to store a value in a request context:

<?php

namespace ICanBoogie\HTTP;

/** @var Request $request */
/** @var \ICanBoogie\Routing\Route $route */

$request->context->add($route);

// …

$route = $request->context->find(Route::class);
# or, if the value is required
$route = $request->context->get(Route::class);

Obtaining a response

A response is the result of a Responder's respond() method. An exception is thrown when a response can't be provided; for example, NotFound.

<?php

namespace ICanBoogie\HTTP;

/* @var $request Request */
/* @var ResponderProvider $responder_provider */

// The Responder Provider matches a request with a Responder
$responder = $responder_provider->responder_for_request($request);

// The Responder responds to the request with a Response, it might also throw an exception.
$response = $responder->respond($request);

// The response is sent to the client.
(new SimpleResponseSender())->send($response->finalize($request));