Fr3nch13/CakePHP Utilities

Client
in package
implements ClientInterface uses InstanceConfigTrait

The end user interface for doing HTTP requests.

Scoped clients

If you're doing multiple requests to the same hostname it's often convenient to use the constructor arguments to create a scoped client. This allows you to keep your code DRY and not repeat hostnames, authentication, and other options.

Doing requests

Once you've created an instance of Client you can do requests using several methods. Each corresponds to a different HTTP method.

  • get()
  • post()
  • put()
  • delete()
  • patch()

Cookie management

Client will maintain cookies from the responses done with a client instance. These cookies will be automatically added to future requests to matching hosts. Cookies will respect the Expires, Path and Domain attributes. You can get the client's CookieCollection using cookies()

You can use the 'cookieJar' constructor option to provide a custom cookie jar instance you've restored from cache/disk. By default, an empty instance of will be created.

Sending request bodies

By default, any POST/PUT/PATCH/DELETE request with $data will send their data as application/x-www-form-urlencoded unless there are attached files. In that case multipart/form-data will be used.

When sending request bodies you can use the type option to set the Content-Type for the request:

$http->get('/users', [], ['type' => 'json']);

The type option sets both the Content-Type and Accept header, to the same mime type. When using type you can use either a full mime type or an alias. If you need different types in the Accept and Content-Type headers you should set them manually and not use type

Using authentication

By using the auth key you can use authentication. The type sub option can be used to specify which authentication strategy you want to use. CakePHP comes with a few built-in strategies:

  • Basic
  • Digest
  • Oauth

Using proxies

By using the proxy key you can set authentication credentials for a proxy if you need to use one. The type sub option can be used to specify which authentication strategy you want to use. CakePHP comes with built-in support for basic authentication.

Table of Contents

Interfaces

ClientInterface

Properties

$_adapter  : AdapterInterface
Adapter for sending requests.
$_config  : array<string, mixed>
Runtime config
$_configInitialized  : bool
Whether the config property has already been configured with defaults
$_cookies  : CookieCollection
List of cookies from responses made with this client.
$_defaultConfig  : array<string, mixed>
Default configuration for the client.
$_mockAdapter  : Mock|null
Mock adapter for stubbing requests in tests.

Methods

__construct()  : mixed
Create a new HTTP Client.
addCookie()  : $this
Adds a cookie to the Client collection.
addMockResponse()  : void
Add a mocked response.
buildUrl()  : string
Generate a URL based on the scoped client options.
clearMockResponses()  : void
Clear all mocked responses
configShallow()  : $this
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
cookies()  : CookieCollection
Get the cookies stored in the Client.
createFromUrl()  : static
Client instance returned is scoped to the domain, port, and scheme parsed from the passed URL string. The passed string must have a scheme and a domain. Optionally, if a port is included in the string, the port will be scoped too. If a path is included in the URL, the client instance will build urls with it prepended.
delete()  : Response
Do a DELETE request.
get()  : Response
Do a GET request.
getConfig()  : mixed
Returns the config.
getConfigOrFail()  : mixed
Returns the config for this specific key.
head()  : Response
Do a HEAD request.
options()  : Response
Do an OPTIONS request.
patch()  : Response
Do a PATCH request.
post()  : Response
Do a POST request.
put()  : Response
Do a PUT request.
send()  : Response
Send a request.
sendRequest()  : ResponseInterface
Sends a PSR-7 request and returns a PSR-7 response.
setConfig()  : $this
Sets the config.
trace()  : Response
Do a TRACE request.
_addAuthentication()  : Request
Add authentication headers to the request.
_addProxy()  : Request
Add proxy authentication headers.
_configDelete()  : void
Deletes a single config key.
_configRead()  : mixed
Reads a config key.
_configWrite()  : void
Writes a config key.
_createAuth()  : object
Create the authentication strategy.
_createRequest()  : Request
Creates a new request object based on the parameters.
_doRequest()  : Response
Helper method for doing non-GET requests.
_mergeOptions()  : array<string|int, mixed>
Does a recursive merge of the parameter with the scope config.
_sendRequest()  : Response
Send a request without redirection.
_typeHeaders()  : array<string, string>
Returns headers for Accept/Content-Type based on a short type or full mime-type.

Properties

$_configInitialized

Whether the config property has already been configured with defaults

protected bool $_configInitialized = false

$_cookies

List of cookies from responses made with this client.

protected CookieCollection $_cookies

Cookies are indexed by the cookie's domain or request host name.

$_defaultConfig

Default configuration for the client.

protected array<string, mixed> $_defaultConfig = ['auth' => null, 'adapter' => null, 'host' => null, 'port' => null, 'scheme' => 'http', 'basePath' => '', 'timeout' => 30, 'ssl_verify_peer' => true, 'ssl_verify_peer_name' => true, 'ssl_verify_depth' => 5, 'ssl_verify_host' => true, 'redirect' => false, 'protocolVersion' => '1.1']

$_mockAdapter

Mock adapter for stubbing requests in tests.

protected static Mock|null $_mockAdapter

Methods

__construct()

Create a new HTTP Client.

public __construct([array<string, mixed> $config = [] ]) : mixed

Config options

You can set the following options when creating a client:

  • host - The hostname to do requests on.
  • port - The port to use.
  • scheme - The default scheme/protocol to use. Defaults to http.
  • basePath - A path to append to the domain to use. (/api/v1/)
  • timeout - The timeout in seconds. Defaults to 30
  • ssl_verify_peer - Whether SSL certificates should be validated. Defaults to true.
  • ssl_verify_peer_name - Whether peer names should be validated. Defaults to true.
  • ssl_verify_depth - The maximum certificate chain depth to traverse. Defaults to 5.
  • ssl_verify_host - Verify that the certificate and hostname match. Defaults to true.
  • redirect - Number of redirects to follow. Defaults to false.
  • adapter - The adapter class name or instance. Defaults to \Cake\Http\Client\Adapter\Curl if curl extension is loaded else \Cake\Http\Client\Adapter\Stream.
  • protocolVersion - The HTTP protocol version to use. Defaults to 1.1
  • auth - The authentication credentials to use. If a username and password key are provided without a type key Basic authentication will be assumed. You can use the type key to define the authentication adapter classname to use. Short class names are resolved to the Http\Client\Auth namespace.
Parameters
$config : array<string, mixed> = []

Config options for scoped clients.

Tags
throws
InvalidArgumentException

addCookie()

Adds a cookie to the Client collection.

public addCookie(CookieInterface $cookie) : $this
Parameters
$cookie : CookieInterface

Cookie object.

Tags
throws
InvalidArgumentException
Return values
$this

addMockResponse()

Add a mocked response.

public static addMockResponse(string $method, string $url, Response $response[, array<string, mixed> $options = [] ]) : void

Mocked responses are stored in an adapter that is called before the network adapter is called.

Matching Requests

TODO finish this.

Options

  • match An additional closure to match requests with.
Parameters
$method : string

The HTTP method being mocked.

$url : string

The URL being matched. See above for examples.

$response : Response

The response that matches the request.

$options : array<string, mixed> = []

See above.

buildUrl()

Generate a URL based on the scoped client options.

public buildUrl(string $url[, array<string|int, mixed>|string $query = [] ][, array<string, mixed> $options = [] ]) : string
Parameters
$url : string

Either a full URL or just the path.

$query : array<string|int, mixed>|string = []

The query data for the URL.

$options : array<string, mixed> = []

The config options stored with Client::config()

Return values
string

A complete url with scheme, port, host, and path.

clearMockResponses()

Clear all mocked responses

public static clearMockResponses() : void

configShallow()

Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.

public configShallow(array<string, mixed>|string $key[, mixed|null $value = null ]) : $this

Setting a specific value:

$this->configShallow('key', $value);

Setting a nested value:

$this->configShallow('some.nested.key', $value);

Updating multiple config settings at the same time:

$this->configShallow(['one' => 'value', 'another' => 'value']);
Parameters
$key : array<string, mixed>|string

The key to set, or a complete array of configs.

$value : mixed|null = null

The value to set.

Return values
$this

createFromUrl()

Client instance returned is scoped to the domain, port, and scheme parsed from the passed URL string. The passed string must have a scheme and a domain. Optionally, if a port is included in the string, the port will be scoped too. If a path is included in the URL, the client instance will build urls with it prepended.

public static createFromUrl(string $url) : static

Other parts of the url string are ignored.

Parameters
$url : string

A string URL e.g. https://example.com

Tags
throws
InvalidArgumentException
Return values
static

delete()

Do a DELETE request.

public delete(string $url[, mixed $data = [] ][, array<string, mixed> $options = [] ]) : Response
Parameters
$url : string

The url or path you want to request.

$data : mixed = []

The request data you want to send.

$options : array<string, mixed> = []

Additional options for the request.

Return values
Response

get()

Do a GET request.

public get(string $url[, array<string|int, mixed>|string $data = [] ][, array<string, mixed> $options = [] ]) : Response

The $data argument supports a special _content key for providing a request body in a GET request. This is generally not used, but services like ElasticSearch use this feature.

Parameters
$url : string

The url or path you want to request.

$data : array<string|int, mixed>|string = []

The query data you want to send.

$options : array<string, mixed> = []

Additional options for the request.

Return values
Response

getConfig()

Returns the config.

public getConfig([string|null $key = null ][, mixed $default = null ]) : mixed

Usage

Reading the whole config:

$this->getConfig();

Reading a specific value:

$this->getConfig('key');

Reading a nested value:

$this->getConfig('some.nested.key');

Reading with default value:

$this->getConfig('some-key', 'default-value');
Parameters
$key : string|null = null

The key to get or null for the whole config.

$default : mixed = null

The return value when the key does not exist.

Return values
mixed

Configuration data at the named key or null if the key does not exist.

getConfigOrFail()

Returns the config for this specific key.

public getConfigOrFail(string $key) : mixed

The config value for this key must exist, it can never be null.

Parameters
$key : string

The key to get.

Tags
throws
InvalidArgumentException
Return values
mixed

Configuration data at the named key

head()

Do a HEAD request.

public head(string $url[, array<string|int, mixed> $data = [] ][, array<string, mixed> $options = [] ]) : Response
Parameters
$url : string

The url or path you want to request.

$data : array<string|int, mixed> = []

The query string data you want to send.

$options : array<string, mixed> = []

Additional options for the request.

Return values
Response

options()

Do an OPTIONS request.

public options(string $url[, mixed $data = [] ][, array<string, mixed> $options = [] ]) : Response
Parameters
$url : string

The url or path you want to request.

$data : mixed = []

The request data you want to send.

$options : array<string, mixed> = []

Additional options for the request.

Return values
Response

patch()

Do a PATCH request.

public patch(string $url[, mixed $data = [] ][, array<string, mixed> $options = [] ]) : Response
Parameters
$url : string

The url or path you want to request.

$data : mixed = []

The request data you want to send.

$options : array<string, mixed> = []

Additional options for the request.

Return values
Response

post()

Do a POST request.

public post(string $url[, mixed $data = [] ][, array<string, mixed> $options = [] ]) : Response
Parameters
$url : string

The url or path you want to request.

$data : mixed = []

The post data you want to send.

$options : array<string, mixed> = []

Additional options for the request.

Return values
Response

put()

Do a PUT request.

public put(string $url[, mixed $data = [] ][, array<string, mixed> $options = [] ]) : Response
Parameters
$url : string

The url or path you want to request.

$data : mixed = []

The request data you want to send.

$options : array<string, mixed> = []

Additional options for the request.

Return values
Response

send()

Send a request.

public send(RequestInterface $request[, array<string, mixed> $options = [] ]) : Response

Used internally by other methods, but can also be used to send handcrafted Request objects.

Parameters
$request : RequestInterface

The request to send.

$options : array<string, mixed> = []

Additional options to use.

Return values
Response

setConfig()

Sets the config.

public setConfig(array<string, mixed>|string $key[, mixed|null $value = null ][, bool $merge = true ]) : $this

Usage

Setting a specific value:

$this->setConfig('key', $value);

Setting a nested value:

$this->setConfig('some.nested.key', $value);

Updating multiple config settings at the same time:

$this->setConfig(['one' => 'value', 'another' => 'value']);
Parameters
$key : array<string, mixed>|string

The key to set, or a complete array of configs.

$value : mixed|null = null

The value to set.

$merge : bool = true

Whether to recursively merge or overwrite existing config, defaults to true.

Tags
throws
CakeException

When trying to set a key that is invalid.

Return values
$this

trace()

Do a TRACE request.

public trace(string $url[, mixed $data = [] ][, array<string, mixed> $options = [] ]) : Response
Parameters
$url : string

The url or path you want to request.

$data : mixed = []

The request data you want to send.

$options : array<string, mixed> = []

Additional options for the request.

Return values
Response

_addAuthentication()

Add authentication headers to the request.

protected _addAuthentication(Request $request, array<string, mixed> $options) : Request

Uses the authentication type to choose the correct strategy and use its methods to add headers.

Parameters
$request : Request

The request to modify.

$options : array<string, mixed>

Array of options containing the 'auth' key.

Return values
Request

The updated request object.

_addProxy()

Add proxy authentication headers.

protected _addProxy(Request $request, array<string, mixed> $options) : Request

Uses the authentication type to choose the correct strategy and use its methods to add headers.

Parameters
$request : Request

The request to modify.

$options : array<string, mixed>

Array of options containing the 'proxy' key.

Return values
Request

The updated request object.

_configDelete()

Deletes a single config key.

protected _configDelete(string $key) : void
Parameters
$key : string

Key to delete.

Tags
throws
CakeException

if attempting to clobber existing config

_configRead()

Reads a config key.

protected _configRead(string|null $key) : mixed
Parameters
$key : string|null

Key to read.

_configWrite()

Writes a config key.

protected _configWrite(array<string, mixed>|string $key, mixed $value[, string|bool $merge = false ]) : void
Parameters
$key : array<string, mixed>|string

Key to write to.

$value : mixed

Value to write.

$merge : string|bool = false

True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.

Tags
throws
CakeException

if attempting to clobber existing config

_createAuth()

Create the authentication strategy.

protected _createAuth(array<string|int, mixed> $auth, array<string, mixed> $options) : object

Use the configuration options to create the correct authentication strategy handler.

Parameters
$auth : array<string|int, mixed>

The authentication options to use.

$options : array<string, mixed>

The overall request options to use.

Tags
throws
CakeException

when an invalid strategy is chosen.

Return values
object

Authentication strategy instance.

_createRequest()

Creates a new request object based on the parameters.

protected _createRequest(string $method, string $url, mixed $data, array<string, mixed> $options) : Request
Parameters
$method : string

HTTP method name.

$url : string

The url including query string.

$data : mixed

The request body.

$options : array<string, mixed>

The options to use. Contains auth, proxy, etc.

Return values
Request

_doRequest()

Helper method for doing non-GET requests.

protected _doRequest(string $method, string $url, mixed $data, array<string, mixed> $options) : Response
Parameters
$method : string

HTTP method.

$url : string

URL to request.

$data : mixed

The request body.

$options : array<string, mixed>

The options to use. Contains auth, proxy, etc.

Return values
Response

_mergeOptions()

Does a recursive merge of the parameter with the scope config.

protected _mergeOptions(array<string, mixed> $options) : array<string|int, mixed>
Parameters
$options : array<string, mixed>

Options to merge.

Return values
array<string|int, mixed>

Options merged with set config.

_sendRequest()

Send a request without redirection.

protected _sendRequest(RequestInterface $request, array<string, mixed> $options) : Response
Parameters
$request : RequestInterface

The request to send.

$options : array<string, mixed>

Additional options to use.

Return values
Response

_typeHeaders()

Returns headers for Accept/Content-Type based on a short type or full mime-type.

protected _typeHeaders(string $type) : array<string, string>
Parameters
$type : string

short type alias or full mimetype.

Tags
phpstan-param

non-empty-string $type

throws
CakeException

When an unknown type alias is used.

psalm-return

array<non-empty-string, non-empty-string>

Return values
array<string, string>

Headers to set on the request.


        
On this page

Search results