code
stringlengths 17
247k
| docstring
stringlengths 30
30.3k
| func_name
stringlengths 1
89
| language
stringclasses 1
value | repo
stringlengths 7
63
| path
stringlengths 7
153
| url
stringlengths 51
209
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
public function getRaw(string $key, bool $consistent)
{
$response = $this->dynamoDb->getItem([
'TableName' => $this->table,
'ConsistentRead' => $consistent,
'Key' => [
$this->keyAttribute => [
'S' => $this->prefix . $key,
],
],
]);
$item = $response->getItem();
if (empty($item)) {
return null;
}
if ($this->isExpired($item)) {
return null;
}
if (isset($item[$this->valueAttribute])) {
return $this->unserialize(
$item[$this->valueAttribute]->getS() ??
$item[$this->valueAttribute]->getN() ??
null
);
}
return null;
} | Retrieve an item from the cache by key using a possibly consistent read.
@return mixed | getRaw | php | async-aws/aws | src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | https://github.com/async-aws/aws/blob/master/src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | MIT |
public function put($key, $value, $seconds)
{
$this->dynamoDb->putItem([
'TableName' => $this->table,
'Item' => [
$this->keyAttribute => [
'S' => $this->prefix . $key,
],
$this->valueAttribute => [
$this->type($value) => $this->serialize($value),
],
$this->expirationAttribute => [
'N' => (string) $this->toTimestamp($seconds),
],
],
]);
return true;
} | Store an item in the cache for a given number of seconds.
@param string $key
@param mixed $value
@param int $seconds
@return bool | put | php | async-aws/aws | src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | https://github.com/async-aws/aws/blob/master/src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | MIT |
public function add($key, $value, $seconds)
{
try {
$this->dynamoDb->putItem([
'TableName' => $this->table,
'Item' => [
$this->keyAttribute => [
'S' => $this->prefix . $key,
],
$this->valueAttribute => [
$this->type($value) => $this->serialize($value),
],
$this->expirationAttribute => [
'N' => (string) $this->toTimestamp($seconds),
],
],
'ConditionExpression' => 'attribute_not_exists(#key) OR #expires_at < :now',
'ExpressionAttributeNames' => [
'#key' => $this->keyAttribute,
'#expires_at' => $this->expirationAttribute,
],
'ExpressionAttributeValues' => [
':now' => [
'N' => (string) Carbon::now()->getTimestamp(),
],
],
]);
return true;
} catch (ConditionalCheckFailedException $e) {
return false;
}
} | Store an item in the cache if the key doesn't exist.
@param string $key
@param mixed $value
@param int $seconds
@return bool | add | php | async-aws/aws | src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | https://github.com/async-aws/aws/blob/master/src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | MIT |
public function increment($key, $value = 1)
{
try {
$response = $this->dynamoDb->updateItem([
'TableName' => $this->table,
'Key' => [
$this->keyAttribute => [
'S' => $this->prefix . $key,
],
],
'ConditionExpression' => 'attribute_exists(#key) AND #expires_at > :now',
'UpdateExpression' => 'SET #value = #value + :amount',
'ExpressionAttributeNames' => [
'#key' => $this->keyAttribute,
'#value' => $this->valueAttribute,
'#expires_at' => $this->expirationAttribute,
],
'ExpressionAttributeValues' => [
':now' => [
'N' => (string) Carbon::now()->getTimestamp(),
],
':amount' => [
'N' => (string) $value,
],
],
'ReturnValues' => 'UPDATED_NEW',
]);
return (int) $response->getAttributes()[$this->valueAttribute]->getN();
} catch (ConditionalCheckFailedException $e) {
return false;
}
} | Increment the value of an item in the cache.
@param string $key
@param mixed $value
@return int|bool | increment | php | async-aws/aws | src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | https://github.com/async-aws/aws/blob/master/src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | MIT |
public function decrement($key, $value = 1)
{
try {
$response = $this->dynamoDb->updateItem([
'TableName' => $this->table,
'Key' => [
$this->keyAttribute => [
'S' => $this->prefix . $key,
],
],
'ConditionExpression' => 'attribute_exists(#key) AND #expires_at > :now',
'UpdateExpression' => 'SET #value = #value - :amount',
'ExpressionAttributeNames' => [
'#key' => $this->keyAttribute,
'#value' => $this->valueAttribute,
'#expires_at' => $this->expirationAttribute,
],
'ExpressionAttributeValues' => [
':now' => [
'N' => (string) Carbon::now()->getTimestamp(),
],
':amount' => [
'N' => (string) $value,
],
],
'ReturnValues' => 'UPDATED_NEW',
]);
return (int) $response->getAttributes()[$this->valueAttribute]->getN();
} catch (ConditionalCheckFailedException $e) {
return false;
}
} | Decrement the value of an item in the cache.
@param string $key
@param mixed $value
@return int|bool | decrement | php | async-aws/aws | src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | https://github.com/async-aws/aws/blob/master/src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | MIT |
public function forever($key, $value)
{
return $this->put($key, $value, Carbon::now()->addYears(5)->getTimestamp());
} | Store an item in the cache indefinitely.
@param string $key
@param mixed $value
@return bool | forever | php | async-aws/aws | src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | https://github.com/async-aws/aws/blob/master/src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | MIT |
public function forget($key)
{
$this->dynamoDb->deleteItem([
'TableName' => $this->table,
'Key' => [
$this->keyAttribute => [
'S' => $this->prefix . $key,
],
],
]);
return true;
} | Remove an item from the cache.
@param string $key
@return bool | forget | php | async-aws/aws | src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | https://github.com/async-aws/aws/blob/master/src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | MIT |
private function isExpired(array $item, ?\DateTimeInterface $expiration = null)
{
$expiration = $expiration ?: Carbon::now();
return isset($item[$this->expirationAttribute])
&& $expiration->getTimestamp() >= $item[$this->expirationAttribute]->getN();
} | Determine if the given item is expired.
@param array<string, AttributeValue> $item
@return bool | isExpired | php | async-aws/aws | src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | https://github.com/async-aws/aws/blob/master/src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | MIT |
private function type($value)
{
return is_numeric($value) ? 'N' : 'S';
} | Get the DynamoDB type for the given value.
@param mixed $value
@return string | type | php | async-aws/aws | src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | https://github.com/async-aws/aws/blob/master/src/Integration/Laravel/Cache/src/AsyncAwsDynamoDbStore.php | MIT |
private function isLoopBackAddress(string $host)
{
// Validate that the input is a valid IP address
if (!filter_var($host, \FILTER_VALIDATE_IP)) {
return false;
}
// Convert the IP address to binary format
$packedIp = inet_pton($host);
// Check if the IP is in the 127.0.0.0/8 range
if (4 === \strlen($packedIp)) {
return 127 === \ord($packedIp[0]);
}
// Check if the IP is ::1
if (16 === \strlen($packedIp)) {
return $packedIp === inet_pton('::1');
}
// Unknown IP format
return false;
} | Checks if the provided IP address is a loopback address.
@param string $host the host address to check
@return bool true if the IP is a loopback address, false otherwise | isLoopBackAddress | php | async-aws/aws | src/Core/src/Credentials/ContainerProvider.php | https://github.com/async-aws/aws/blob/master/src/Core/src/Credentials/ContainerProvider.php | MIT |
private function addCondition(ConditionInterface $condition)
{
$this->conditions[] = $condition;
} | Adds a new condition to the expression.
@param ConditionInterface $condition the condition to be added
@return void | addCondition | php | ddeboer/imap | src/Search/LogicalOperator/OrConditions.php | https://github.com/ddeboer/imap/blob/master/src/Search/LogicalOperator/OrConditions.php | MIT |
public function __construct(array $loaders)
{
$this->_loaders = $loaders;
} | Receives a list of callable functions or objects that will be executed
one after another until one of them returns a non-empty translations package
@param array<callable> $loaders List of callables to execute | __construct | php | cakephp/cakephp | src/I18n/ChainMessagesLoader.php | https://github.com/cakephp/cakephp/blob/master/src/I18n/ChainMessagesLoader.php | MIT |
public function __construct(array $locales = [])
{
$this->locales = $locales;
} | Constructor.
@param array $locales A list of accepted locales, or ['*'] to accept any
locale header value. | __construct | php | cakephp/cakephp | src/I18n/Middleware/LocaleSelectorMiddleware.php | https://github.com/cakephp/cakephp/blob/master/src/I18n/Middleware/LocaleSelectorMiddleware.php | MIT |
public function __construct(array $config = [])
{
$config += [
'timeout' => null,
'cookie' => null,
'ini' => [],
'handler' => [],
];
if ($config['timeout'] !== null) {
$this->configureSessionLifetime((int)$config['timeout'] * 60);
}
if ($config['cookie']) {
$config['ini']['session.name'] = $config['cookie'];
}
if (!isset($config['ini']['session.cookie_path'])) {
$cookiePath = empty($config['cookiePath']) ? '/' : $config['cookiePath'];
$config['ini']['session.cookie_path'] = $cookiePath;
}
$this->options($config['ini']);
if (!empty($config['handler'])) {
$class = $config['handler']['engine'];
unset($config['handler']['engine']);
$this->engine($class, $config['handler']);
}
$this->_isCLI = (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg');
session_register_shutdown();
} | Constructor.
### Configuration:
- timeout: The time in minutes that a session can be idle and remain valid.
If set to 0, no server side timeout will be applied.
- cookiePath: The url path for which session cookie is set. Maps to the
`session.cookie_path` php.ini config. Defaults to base path of app.
- ini: A list of php.ini directives to change before the session start.
- handler: An array containing at least the `engine` key. To be used as the session
engine for persisting data. The rest of the keys in the array will be passed as
the configuration array for the engine. You can set the `engine` key to an already
instantiated session handler object.
@param array<string, mixed> $config The Configuration to apply to this session object | __construct | php | cakephp/cakephp | src/Http/Session.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Session.php | MIT |
public function __construct(array $options = [])
{
$this->_streamTarget = $options['streamTarget'] ?? $this->_streamTarget;
$this->_streamMode = $options['streamMode'] ?? $this->_streamMode;
if (isset($options['stream'])) {
if (!$options['stream'] instanceof StreamInterface) {
throw new InvalidArgumentException('Stream option must be an object that implements StreamInterface');
}
$this->stream = $options['stream'];
} else {
$this->_createStream();
}
if (isset($options['body'])) {
$this->stream->write($options['body']);
}
if (isset($options['status'])) {
$this->_setStatus($options['status']);
}
if (!isset($options['charset'])) {
$options['charset'] = Configure::read('App.encoding');
}
$this->_charset = $options['charset'];
$type = 'text/html';
if (isset($options['type'])) {
$type = $this->resolveType($options['type']);
}
$this->_setContentType($type);
$this->_cookies = new CookieCollection();
} | Constructor
@param array<string, mixed> $options list of parameters to setup the response. Possible values are:
- body: the response text that should be sent to the client
- status: the HTTP status code to respond with
- type: a complete mime-type string or an extension mapped in this class
- charset: the charset for the response body
@throws \InvalidArgumentException | __construct | php | cakephp/cakephp | src/Http/Response.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Response.php | MIT |
public function allowOrigin(array|string $domains)
{
$allowed = $this->_normalizeDomains((array)$domains);
foreach ($allowed as $domain) {
if (!preg_match($domain['preg'], $this->_origin)) {
continue;
}
$value = $domain['original'] === '*' ? '*' : $this->_origin;
$this->_headers['Access-Control-Allow-Origin'] = $value;
break;
}
return $this;
} | Set the list of allowed domains.
Accepts a string or an array of domains that have CORS enabled.
You can use `*.example.com` wildcards to accept subdomains, or `*` to allow all domains
@param array<string>|string $domains The allowed domains
@return $this | allowOrigin | php | cakephp/cakephp | src/Http/CorsBuilder.php | https://github.com/cakephp/cakephp/blob/master/src/Http/CorsBuilder.php | MIT |
public function allowMethods(array $methods)
{
$this->_headers['Access-Control-Allow-Methods'] = implode(', ', $methods);
return $this;
} | Set the list of allowed HTTP Methods.
@param array<string> $methods The allowed HTTP methods
@return $this | allowMethods | php | cakephp/cakephp | src/Http/CorsBuilder.php | https://github.com/cakephp/cakephp/blob/master/src/Http/CorsBuilder.php | MIT |
public function allowCredentials()
{
$this->_headers['Access-Control-Allow-Credentials'] = 'true';
return $this;
} | Enable cookies to be sent in CORS requests.
@return $this | allowCredentials | php | cakephp/cakephp | src/Http/CorsBuilder.php | https://github.com/cakephp/cakephp/blob/master/src/Http/CorsBuilder.php | MIT |
public function allowHeaders(array $headers)
{
$this->_headers['Access-Control-Allow-Headers'] = implode(', ', $headers);
return $this;
} | Allowed headers that can be sent in CORS requests.
@param array<string> $headers The list of headers to accept in CORS requests.
@return $this | allowHeaders | php | cakephp/cakephp | src/Http/CorsBuilder.php | https://github.com/cakephp/cakephp/blob/master/src/Http/CorsBuilder.php | MIT |
public function exposeHeaders(array $headers)
{
$this->_headers['Access-Control-Expose-Headers'] = implode(', ', $headers);
return $this;
} | Define the headers a client library/browser can expose to scripting
@param array<string> $headers The list of headers to expose CORS responses
@return $this | exposeHeaders | php | cakephp/cakephp | src/Http/CorsBuilder.php | https://github.com/cakephp/cakephp/blob/master/src/Http/CorsBuilder.php | MIT |
public function maxAge(string|int $age)
{
$this->_headers['Access-Control-Max-Age'] = $age;
return $this;
} | Define the max-age preflight OPTIONS requests are valid for.
@param string|int $age The max-age for OPTIONS requests in seconds
@return $this | maxAge | php | cakephp/cakephp | src/Http/CorsBuilder.php | https://github.com/cakephp/cakephp/blob/master/src/Http/CorsBuilder.php | MIT |
public function setEventManager(EventManagerInterface $eventManager)
{
if ($this->app instanceof EventDispatcherInterface) {
$this->app->setEventManager($eventManager);
return $this;
}
throw new InvalidArgumentException('Cannot set the event manager, the application does not support events.');
} | Set the application's event manager.
If the application does not support events, an exception will be raised.
@param \Cake\Event\EventManagerInterface $eventManager The event manager to set.
@return $this
@throws \InvalidArgumentException | setEventManager | php | cakephp/cakephp | src/Http/Server.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Server.php | MIT |
public function addOptionalPlugin(PluginInterface|string $name, array $config = [])
{
try {
$this->addPlugin($name, $config);
} catch (MissingPluginException) {
// Do not halt if the plugin is missing
}
return $this;
} | Add an optional plugin
If it isn't available, ignore it.
@param \Cake\Core\PluginInterface|string $name The plugin name or plugin object.
@param array<string, mixed> $config The configuration data for the plugin if using a string for $name
@return $this | addOptionalPlugin | php | cakephp/cakephp | src/Http/BaseApplication.php | https://github.com/cakephp/cakephp/blob/master/src/Http/BaseApplication.php | MIT |
public function add(MiddlewareInterface|Closure|array|string $middleware)
{
if (is_array($middleware)) {
$this->queue = array_merge($this->queue, $middleware);
return $this;
}
$this->queue[] = $middleware;
return $this;
} | Append a middleware to the end of the queue.
@param \Psr\Http\Server\MiddlewareInterface|\Closure|array|string $middleware The middleware(s) to append.
@return $this | add | php | cakephp/cakephp | src/Http/MiddlewareQueue.php | https://github.com/cakephp/cakephp/blob/master/src/Http/MiddlewareQueue.php | MIT |
public function push(MiddlewareInterface|Closure|array|string $middleware)
{
return $this->add($middleware);
} | Alias for MiddlewareQueue::add().
@param \Psr\Http\Server\MiddlewareInterface|\Closure|array|string $middleware The middleware(s) to append.
@return $this
@see MiddlewareQueue::add() | push | php | cakephp/cakephp | src/Http/MiddlewareQueue.php | https://github.com/cakephp/cakephp/blob/master/src/Http/MiddlewareQueue.php | MIT |
public function prepend(MiddlewareInterface|Closure|array|string $middleware)
{
if (is_array($middleware)) {
$this->queue = array_merge($middleware, $this->queue);
return $this;
}
array_unshift($this->queue, $middleware);
return $this;
} | Prepend a middleware to the start of the queue.
@param \Psr\Http\Server\MiddlewareInterface|\Closure|array|string $middleware The middleware(s) to prepend.
@return $this | prepend | php | cakephp/cakephp | src/Http/MiddlewareQueue.php | https://github.com/cakephp/cakephp/blob/master/src/Http/MiddlewareQueue.php | MIT |
public function insertAt(int $index, MiddlewareInterface|Closure|string $middleware)
{
array_splice($this->queue, $index, 0, [$middleware]);
return $this;
} | Insert a middleware at a specific index.
If the index already exists, the new middleware will be inserted,
and the existing element will be shifted one index greater.
@param int $index The index to insert at.
@param \Psr\Http\Server\MiddlewareInterface|\Closure|string $middleware The middleware to insert.
@return $this | insertAt | php | cakephp/cakephp | src/Http/MiddlewareQueue.php | https://github.com/cakephp/cakephp/blob/master/src/Http/MiddlewareQueue.php | MIT |
public function insertBefore(string $class, MiddlewareInterface|Closure|string $middleware)
{
$found = false;
$i = 0;
foreach ($this->queue as $i => $object) {
if (
(
is_string($object)
&& $object === $class
)
|| is_a($object, $class)
) {
$found = true;
break;
}
}
if ($found) {
return $this->insertAt($i, $middleware);
}
throw new LogicException(sprintf('No middleware matching `%s` could be found.', $class));
} | Insert a middleware before the first matching class.
Finds the index of the first middleware that matches the provided class,
and inserts the supplied middleware before it.
@param string $class The classname to insert the middleware before.
@param \Psr\Http\Server\MiddlewareInterface|\Closure|string $middleware The middleware to insert.
@return $this
@throws \LogicException If middleware to insert before is not found. | insertBefore | php | cakephp/cakephp | src/Http/MiddlewareQueue.php | https://github.com/cakephp/cakephp/blob/master/src/Http/MiddlewareQueue.php | MIT |
public function insertAfter(string $class, MiddlewareInterface|Closure|string $middleware)
{
$found = false;
$i = 0;
foreach ($this->queue as $i => $object) {
if (
(
is_string($object)
&& $object === $class
)
|| is_a($object, $class)
) {
$found = true;
break;
}
}
if ($found) {
return $this->insertAt($i + 1, $middleware);
}
return $this->add($middleware);
} | Insert a middleware object after the first matching class.
Finds the index of the first middleware that matches the provided class,
and inserts the supplied middleware after it. If the class is not found,
this method will behave like add().
@param string $class The classname to insert the middleware before.
@param \Psr\Http\Server\MiddlewareInterface|\Closure|string $middleware The middleware to insert.
@return $this | insertAfter | php | cakephp/cakephp | src/Http/MiddlewareQueue.php | https://github.com/cakephp/cakephp/blob/master/src/Http/MiddlewareQueue.php | MIT |
public function __construct(array $config = [])
{
$config += [
'params' => $this->params,
'query' => [],
'post' => [],
'files' => [],
'cookies' => [],
'environment' => [],
'url' => '',
'uri' => null,
'base' => '',
'webroot' => '',
'input' => null,
];
$this->_setConfig($config);
} | Create a new request object.
You can supply the data as either an array or as a string. If you use
a string you can only supply the URL for the request. Using an array will
let you provide the following keys:
- `post` POST data or non query string data
- `query` Additional data from the query string.
- `files` Uploaded files in a normalized structure, with each leaf an instance of UploadedFileInterface.
- `cookies` Cookies for this request.
- `environment` $_SERVER and $_ENV data.
- `url` The URL without the base path for the request.
- `uri` The PSR7 UriInterface object. If null, one will be created from `url` or `environment`.
- `base` The base URL for the request.
- `webroot` The webroot directory for the request.
- `input` The data that would come from php://input this is useful for simulating
requests with put, patch or delete data.
- `session` An instance of a Session object
@param array<string, mixed> $config An array of request data to create a request with. | __construct | php | cakephp/cakephp | src/Http/ServerRequest.php | https://github.com/cakephp/cakephp/blob/master/src/Http/ServerRequest.php | MIT |
public function __construct(array $config = [])
{
$this->_eventClass = ClientEvent::class;
$this->setConfig($config);
$adapter = $this->_config['adapter'];
if ($adapter === null) {
$adapter = Curl::class;
if (!extension_loaded('curl')) {
$adapter = Stream::class;
}
} else {
$this->setConfig('adapter', null);
}
if (is_string($adapter)) {
$adapter = new $adapter();
}
$this->_adapter = $adapter;
if (!empty($this->_config['cookieJar'])) {
$this->_cookies = $this->_config['cookieJar'];
$this->setConfig('cookieJar', null);
} else {
$this->_cookies = new CookieCollection();
}
} | Create a new HTTP Client.
### 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.
@param array<string, mixed> $config Config options for scoped clients. | __construct | php | cakephp/cakephp | src/Http/Client.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Client.php | MIT |
public function addCookie(CookieInterface $cookie)
{
if (!$cookie->getDomain() || !$cookie->getPath()) {
throw new InvalidArgumentException('Cookie must have a domain and a path set.');
}
$this->_cookies = $this->_cookies->add($cookie);
return $this;
} | Adds a cookie to the Client collection.
@param \Cake\Http\Cookie\CookieInterface $cookie Cookie object.
@return $this
@throws \InvalidArgumentException | addCookie | php | cakephp/cakephp | src/Http/Client.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Client.php | MIT |
public function __construct(string $name, Client $subject, array $data = [])
{
if (isset($data['response'])) {
$this->result = $data['response'];
unset($data['response']);
}
parent::__construct($name, $subject, $data);
} | Constructor
@param string $name Name of the event
@param \Cake\Http\Client $subject The Http Client instance this event applies to.
@param array $data Any value you wish to be transported
with this event to it can be read by listeners. | __construct | php | cakephp/cakephp | src/Http/Client/ClientEvent.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Client/ClientEvent.php | MIT |
public function setResult(mixed $value = null)
{
if ($value !== null && !$value instanceof Response) {
throw new InvalidArgumentException(
'The result for Http Client events must be a `Cake\Http\Client\Response` instance.',
);
}
return parent::setResult($value);
} | Listeners can attach a result value to the event.
@param mixed $value The value to set.
@return $this | setResult | php | cakephp/cakephp | src/Http/Client/ClientEvent.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Client/ClientEvent.php | MIT |
public function __construct(
UriInterface|string $url = '',
string $method = self::METHOD_GET,
array $headers = [],
array|string|null $data = null,
) {
$this->setMethod($method);
$this->uri = $this->createUri($url);
$headers += [
'Connection' => 'close',
'User-Agent' => ini_get('user_agent') ?: 'CakePHP',
];
$this->addHeaders($headers);
if ($data === null || $data === '' || $data === []) {
$this->stream = new Stream('php://memory', 'rw');
} else {
$this->setContent($data);
}
} | Constructor
Provides backwards compatible defaults for some properties.
@phpstan-param array<non-empty-string, non-empty-string> $headers
@param \Psr\Http\Message\UriInterface|string $url The request URL
@param string $method The HTTP method to use.
@param array $headers The HTTP headers to set.
@param array|string|null $data The request body to use. | __construct | php | cakephp/cakephp | src/Http/Client/Request.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Client/Request.php | MIT |
public function __construct(
string $name,
array|string|float|int|bool $value = '',
?DateTimeInterface $expiresAt = null,
?string $path = null,
?string $domain = null,
?bool $secure = null,
?bool $httpOnly = null,
SameSiteEnum|string|null $sameSite = null,
) {
$this->validateName($name);
$this->name = $name;
$this->_setValue($value);
$this->domain = $domain ?? static::$defaults['domain'];
$this->httpOnly = $httpOnly ?? static::$defaults['httponly'];
$this->path = $path ?? static::$defaults['path'];
$this->secure = $secure ?? static::$defaults['secure'];
$this->sameSite = static::resolveSameSiteEnum($sameSite ?? static::$defaults['samesite']);
if ($expiresAt) {
if ($expiresAt instanceof DateTime) {
$expiresAt = clone $expiresAt;
}
/** @var \DateTimeImmutable|\DateTime $expiresAt */
$expiresAt = $expiresAt->setTimezone(new DateTimeZone('GMT'));
} else {
$expiresAt = static::$defaults['expires'];
}
$this->expiresAt = $expiresAt;
} | Constructor
The constructors args are similar to the native PHP `setcookie()` method.
The only difference is the 3rd argument which excepts null or an
DateTime or DateTimeImmutable object instead an integer.
@link https://php.net/manual/en/function.setcookie.php
@param string $name Cookie name
@param array|string|float|int|bool $value Value of the cookie
@param \DateTimeInterface|null $expiresAt Expiration time and date
@param string|null $path Path
@param string|null $domain Domain
@param bool|null $secure Is secure
@param bool|null $httpOnly HTTP Only
@param \Cake\Http\Cookie\SameSiteEnum|string|null $sameSite Samesite | __construct | php | cakephp/cakephp | src/Http/Cookie/Cookie.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Cookie/Cookie.php | MIT |
public function setTimeout(int $timeout)
{
$this->_timeout = $timeout;
return $this;
} | Set the timeout value for sessions.
Primarily used in testing.
@param int $timeout The timeout duration.
@return $this | setTimeout | php | cakephp/cakephp | src/Http/Session/DatabaseSession.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Session/DatabaseSession.php | MIT |
public function __construct(array $config = [])
{
if (empty($config['config'])) {
throw new InvalidArgumentException('The cache configuration name to use is required');
}
$this->_options = $config;
} | Constructor.
@param array<string, mixed> $config The configuration to use for this engine
It requires the key 'config' which is the name of the Cache config to use for
storing the session
@throws \InvalidArgumentException if the 'config' key is not provided | __construct | php | cakephp/cakephp | src/Http/Session/CacheSession.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Session/CacheSession.php | MIT |
public function noSniff()
{
$this->headers['x-content-type-options'] = self::NOSNIFF;
return $this;
} | X-Content-Type-Options
Sets the header value for it to 'nosniff'
@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
@return $this | noSniff | php | cakephp/cakephp | src/Http/Middleware/SecurityHeadersMiddleware.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Middleware/SecurityHeadersMiddleware.php | MIT |
public function noOpen()
{
$this->headers['x-download-options'] = self::NOOPEN;
return $this;
} | X-Download-Options
Sets the header value for it to 'noopen'
@link https://msdn.microsoft.com/en-us/library/jj542450(v=vs.85).aspx
@return $this | noOpen | php | cakephp/cakephp | src/Http/Middleware/SecurityHeadersMiddleware.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Middleware/SecurityHeadersMiddleware.php | MIT |
public function setReferrerPolicy(string $policy = self::SAME_ORIGIN)
{
$available = [
self::NO_REFERRER,
self::NO_REFERRER_WHEN_DOWNGRADE,
self::ORIGIN,
self::ORIGIN_WHEN_CROSS_ORIGIN,
self::SAME_ORIGIN,
self::STRICT_ORIGIN,
self::STRICT_ORIGIN_WHEN_CROSS_ORIGIN,
self::UNSAFE_URL,
];
$this->checkValues($policy, $available);
$this->headers['referrer-policy'] = $policy;
return $this;
} | Referrer-Policy
@link https://w3c.github.io/webappsec-referrer-policy
@param string $policy Policy value. Available Value: 'no-referrer', 'no-referrer-when-downgrade', 'origin',
'origin-when-cross-origin', 'same-origin', 'strict-origin', 'strict-origin-when-cross-origin', 'unsafe-url'
@return $this | setReferrerPolicy | php | cakephp/cakephp | src/Http/Middleware/SecurityHeadersMiddleware.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Middleware/SecurityHeadersMiddleware.php | MIT |
public function setXssProtection(string $mode = self::XSS_BLOCK)
{
if ($mode === self::XSS_BLOCK) {
$mode = self::XSS_ENABLED_BLOCK;
}
$this->checkValues($mode, [self::XSS_ENABLED, self::XSS_DISABLED, self::XSS_ENABLED_BLOCK]);
$this->headers['x-xss-protection'] = $mode;
return $this;
} | X-XSS-Protection. It's a non standard feature and outdated. For modern browsers
use a strong Content-Security-Policy that disables the use of inline JavaScript
via 'unsafe-inline' option.
@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection
@param string $mode Mode value. Available Values: '1', '0', 'block'
@return $this | setXssProtection | php | cakephp/cakephp | src/Http/Middleware/SecurityHeadersMiddleware.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Middleware/SecurityHeadersMiddleware.php | MIT |
public function setCrossDomainPolicy(string $policy = self::ALL)
{
$this->checkValues($policy, [
self::ALL,
self::NONE,
self::MASTER_ONLY,
self::BY_CONTENT_TYPE,
self::BY_FTP_FILENAME,
]);
$this->headers['x-permitted-cross-domain-policies'] = $policy;
return $this;
} | X-Permitted-Cross-Domain-Policies
@link https://web.archive.org/web/20170607190356/https://www.adobe.com/devnet/adobe-media-server/articles/cross-domain-xml-for-streaming.html
@param string $policy Policy value. Available Values: 'all', 'none', 'master-only', 'by-content-type',
'by-ftp-filename'
@return $this | setCrossDomainPolicy | php | cakephp/cakephp | src/Http/Middleware/SecurityHeadersMiddleware.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Middleware/SecurityHeadersMiddleware.php | MIT |
public function setMethods(array $methods)
{
$this->methods = $methods;
return $this;
} | Set the HTTP methods to parse request bodies on.
@param array<string> $methods The methods to parse data on.
@return $this | setMethods | php | cakephp/cakephp | src/Http/Middleware/BodyParserMiddleware.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Middleware/BodyParserMiddleware.php | MIT |
public function skipCheckCallback(callable $callback)
{
$this->skipCheckCallback = $callback;
return $this;
} | Set callback for allowing to skip token check for particular request.
The callback will receive request instance as argument and must return
`true` if you want to skip token check for the current request.
@param callable $callback A callable.
@return $this | skipCheckCallback | php | cakephp/cakephp | src/Http/Middleware/CsrfProtectionMiddleware.php | https://github.com/cakephp/cakephp/blob/master/src/Http/Middleware/CsrfProtectionMiddleware.php | MIT |
public function setEventManager(EventManagerInterface $eventManager)
{
$this->_eventManager = $eventManager;
return $this;
} | Returns the Cake\Event\EventManagerInterface instance for this object.
You can use this instance to register any new listeners or callbacks to the
object events, or create your own events and trigger them at will.
@param \Cake\Event\EventManagerInterface $eventManager the eventManager to set
@return $this | setEventManager | php | cakephp/cakephp | src/Event/EventDispatcherTrait.php | https://github.com/cakephp/cakephp/blob/master/src/Event/EventDispatcherTrait.php | MIT |
public function setResult(mixed $value = null)
{
$this->result = $value;
return $this;
} | Listeners can attach a result value to the event.
Setting the result to `false` will also stop event propagation.
@param mixed $value The value to set.
@return $this | setResult | php | cakephp/cakephp | src/Event/Event.php | https://github.com/cakephp/cakephp/blob/master/src/Event/Event.php | MIT |
public function addEventToList(EventInterface $event)
{
$this->_eventList?->add($event);
return $this;
} | Adds an event to the list if the event list object is present.
@template TSubject of object
@param \Cake\Event\EventInterface<TSubject> $event An event to add to the list.
@return $this | addEventToList | php | cakephp/cakephp | src/Event/EventManager.php | https://github.com/cakephp/cakephp/blob/master/src/Event/EventManager.php | MIT |
public function trackEvents(bool $enabled)
{
$this->_trackEvents = $enabled;
return $this;
} | Enables / disables event tracking at runtime.
@param bool $enabled True or false to enable / disable it.
@return $this | trackEvents | php | cakephp/cakephp | src/Event/EventManager.php | https://github.com/cakephp/cakephp/blob/master/src/Event/EventManager.php | MIT |
public function setEventList(EventList $eventList)
{
$this->_eventList = $eventList;
$this->_trackEvents = true;
return $this;
} | Enables the listing of dispatched events.
@param \Cake\Event\EventList $eventList The event list object to use.
@return $this | setEventList | php | cakephp/cakephp | src/Event/EventManager.php | https://github.com/cakephp/cakephp/blob/master/src/Event/EventManager.php | MIT |
public function unsetEventList()
{
$this->_eventList = null;
$this->_trackEvents = false;
return $this;
} | Disables the listing of dispatched events.
@return $this | unsetEventList | php | cakephp/cakephp | src/Event/EventManager.php | https://github.com/cakephp/cakephp/blob/master/src/Event/EventManager.php | MIT |
protected function _getStreamSocketClient(
string $remoteSocketTarget,
int &$errNum,
string &$errStr,
int $timeout,
int $connectAs,
$context,
) {
$resource = stream_socket_client(
$remoteSocketTarget,
$errNum,
$errStr,
$timeout,
$connectAs,
$context,
);
if (!$resource) {
return null;
}
return $resource;
} | Create a stream socket client. Mock utility.
@param string $remoteSocketTarget remote socket
@param int $errNum error number
@param string $errStr error string
@param int $timeout timeout
@param int<0, 7> $connectAs flags
@param resource $context context
@return resource|null | _getStreamSocketClient | php | cakephp/cakephp | src/Network/Socket.php | https://github.com/cakephp/cakephp/blob/master/src/Network/Socket.php | MIT |
protected static function assertWithinRange($expected, $result, $margin, $message = '')
{
$upper = $result + $margin;
$lower = $result - $margin;
static::assertTrue(($expected <= $upper) && ($expected >= $lower), $message);
} | Compatibility function to test if a value is between an acceptable range.
@param float $expected
@param float $result
@param float $margin the rage of acceptation
@param string $message the text to display if the assertion is not correct
@return void | assertWithinRange | php | cakephp/cakephp | src/TestSuite/TestCase.php | https://github.com/cakephp/cakephp/blob/master/src/TestSuite/TestCase.php | MIT |
protected static function assertNotWithinRange($expected, $result, $margin, $message = '')
{
$upper = $result + $margin;
$lower = $result - $margin;
static::assertTrue(($expected > $upper) || ($expected < $lower), $message);
} | Compatibility function to test if a value is not between an acceptable range.
@param float $expected
@param float $result
@param float $margin the rage of acceptation
@param string $message the text to display if the assertion is not correct
@return void | assertNotWithinRange | php | cakephp/cakephp | src/TestSuite/TestCase.php | https://github.com/cakephp/cakephp/blob/master/src/TestSuite/TestCase.php | MIT |
protected static function assertPathEquals($expected, $result, $message = '')
{
$expected = str_replace(DIRECTORY_SEPARATOR, '/', $expected);
$result = str_replace(DIRECTORY_SEPARATOR, '/', $result);
static::assertEquals($expected, $result, $message);
} | Compatibility function to test paths.
@param string $expected
@param string $result
@param string $message the text to display if the assertion is not correct
@return void | assertPathEquals | php | cakephp/cakephp | src/TestSuite/TestCase.php | https://github.com/cakephp/cakephp/blob/master/src/TestSuite/TestCase.php | MIT |
protected function skipUnless($condition, $message = '')
{
if (!$condition) {
$this->markTestSkipped($message);
}
return $condition;
} | Compatibility function for skipping.
@param bool $condition Condition to trigger skipping
@param string $message Message for skip
@return bool | skipUnless | php | cakephp/cakephp | src/TestSuite/TestCase.php | https://github.com/cakephp/cakephp/blob/master/src/TestSuite/TestCase.php | MIT |
protected function addFixture(string $fixture)
{
$this->fixtures[] = $fixture;
return $this;
} | Adds a fixture to this test case.
Examples:
- core.Tags
- app.MyRecords
- plugin.MyPluginName.MyModelName
Use this method inside your test cases' {@link getFixtures()} method
to build up the fixture list.
@param string $fixture Fixture
@return $this | addFixture | php | cakephp/cakephp | src/TestSuite/TestCase.php | https://github.com/cakephp/cakephp/blob/master/src/TestSuite/TestCase.php | MIT |
public function __construct(Throwable $exception)
{
throw $exception;
} | Simply rethrow the given exception
@param \Throwable $exception Exception.
@return void
@throws \Throwable $exception Rethrows the passed exception. | __construct | php | cakephp/cakephp | src/TestSuite/Stub/TestExceptionRenderer.php | https://github.com/cakephp/cakephp/blob/master/src/TestSuite/Stub/TestExceptionRenderer.php | MIT |
public function __construct(array $config)
{
$this->output = $config['stderr'] ?? new ConsoleOutput('php://stderr');
$this->trace = (bool)($config['trace'] ?? false);
} | Constructor.
### Options
- `stderr` - The ConsoleOutput instance to use. Defaults to `php://stderr`
- `trace` - Whether or not stacktraces should be output.
@param array $config Error handling configuration. | __construct | php | cakephp/cakephp | src/Error/Renderer/ConsoleErrorRenderer.php | https://github.com/cakephp/cakephp/blob/master/src/Error/Renderer/ConsoleErrorRenderer.php | MIT |
public function __construct(Throwable $exception, ?ServerRequest $request = null)
{
$this->error = $exception;
$this->request = $request;
$this->controller = $this->_getController();
} | Creates the controller to perform rendering on the error response.
@param \Throwable $exception Exception.
@param \Cake\Http\ServerRequest|null $request The request if this is set it will be used
instead of creating a new one. | __construct | php | cakephp/cakephp | src/Error/Renderer/WebExceptionRenderer.php | https://github.com/cakephp/cakephp/blob/master/src/Error/Renderer/WebExceptionRenderer.php | MIT |
public function unload(string $name)
{
unset($this->_loaded[$name]);
return $this;
} | Remove a single adapter from the registry.
@param string $name The adapter name.
@return $this | unload | php | cakephp/cakephp | src/Cache/CacheRegistry.php | https://github.com/cakephp/cakephp/blob/master/src/Cache/CacheRegistry.php | MIT |
public function __destruct()
{
if (empty($this->_config['persistent'])) {
$this->_Redis->close();
}
} | Disconnects from the redis server | __destruct | php | cakephp/cakephp | src/Cache/Engine/RedisEngine.php | https://github.com/cakephp/cakephp/blob/master/src/Cache/Engine/RedisEngine.php | MIT |
public function __construct(RouteCollection $collection, string $path, array $params = [], array $options = [])
{
$this->_collection = $collection;
$this->_path = $path;
$this->_params = $params;
if (isset($options['routeClass'])) {
$this->_routeClass = $options['routeClass'];
}
if (isset($options['extensions'])) {
$this->_extensions = $options['extensions'];
}
if (isset($options['namePrefix'])) {
$this->_namePrefix = $options['namePrefix'];
}
if (isset($options['middleware'])) {
$this->middleware = (array)$options['middleware'];
}
} | Constructor
### Options
- `routeClass` - The default route class to use when adding routes.
- `extensions` - The extensions to connect when adding routes.
- `namePrefix` - The prefix to prepend to all route names.
- `middleware` - The names of the middleware routes should have applied.
@param \Cake\Routing\RouteCollection $collection The route collection to append routes into.
@param string $path The path prefix the scope is for.
@param array $params The scope's routing parameters.
@param array<string, mixed> $options Options list. | __construct | php | cakephp/cakephp | src/Routing/RouteBuilder.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/RouteBuilder.php | MIT |
public function setExtensions(array|string $extensions)
{
$this->_extensions = (array)$extensions;
return $this;
} | Set the extensions in this route builder's scope.
Future routes connected in through this builder will have the connected
extensions applied. However, setting extensions does not modify existing routes.
@param array<string>|string $extensions The extensions to set.
@return $this | setExtensions | php | cakephp/cakephp | src/Routing/RouteBuilder.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/RouteBuilder.php | MIT |
public function addExtensions(array|string $extensions)
{
$extensions = array_merge($this->_extensions, (array)$extensions);
$this->_extensions = array_unique($extensions);
return $this;
} | Add additional extensions to what is already in current scope
@param array<string>|string $extensions One or more extensions to add
@return $this | addExtensions | php | cakephp/cakephp | src/Routing/RouteBuilder.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/RouteBuilder.php | MIT |
public function loadPlugin(string $name)
{
$plugins = Plugin::getCollection();
if (!$plugins->has($name)) {
throw new MissingPluginException(['plugin' => $name]);
}
$plugin = $plugins->get($name);
$plugin->routes($this);
// Disable the routes hook to prevent duplicate route issues.
$plugin->disable('routes');
return $this;
} | Load routes from a plugin.
The routes file will have a local variable named `$routes` made available which contains
the current RouteBuilder instance.
@param string $name The plugin name
@return $this
@throws \Cake\Core\Exception\MissingPluginException When the plugin has not been loaded.
@throws \InvalidArgumentException When the plugin does not have a routes file. | loadPlugin | php | cakephp/cakephp | src/Routing/RouteBuilder.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/RouteBuilder.php | MIT |
public function scope(string $path, Closure|array $params, ?Closure $callback = null)
{
if ($params instanceof Closure) {
$callback = $params;
$params = [];
}
if ($callback === null) {
throw new InvalidArgumentException('Need a valid Closure to connect routes.');
}
if ($this->_path !== '/') {
$path = $this->_path . $path;
}
$namePrefix = $this->_namePrefix;
if (isset($params['_namePrefix'])) {
$namePrefix .= $params['_namePrefix'];
}
unset($params['_namePrefix']);
$params += $this->_params;
$builder = new static($this->_collection, $path, $params, [
'routeClass' => $this->_routeClass,
'extensions' => $this->_extensions,
'namePrefix' => $namePrefix,
'middleware' => $this->middleware,
]);
$callback($builder);
return $this;
} | Create a new routing scope.
Scopes created with this method will inherit the properties of the scope they are
added to. This means that both the current path and parameters will be appended
to the supplied parameters.
### Special Keys in $params
- `_namePrefix` Set a prefix used for named routes. The prefix is prepended to the
name of any route created in a scope callback.
@param string $path The path to create a scope for.
@param \Closure|array $params Either the parameters to add to routes, or a callback.
@param \Closure|null $callback The callback to invoke that builds the plugin routes.
Only required when $params is defined.
@return $this
@throws \InvalidArgumentException when there is no callable parameter. | scope | php | cakephp/cakephp | src/Routing/RouteBuilder.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/RouteBuilder.php | MIT |
public function fallbacks(?string $routeClass = null)
{
$routeClass = $routeClass ?: $this->_routeClass;
$this->connect('/{controller}', ['action' => 'index'], compact('routeClass'));
$this->connect('/{controller}/{action}/*', [], compact('routeClass'));
return $this;
} | Connect the `/{controller}` and `/{controller}/{action}/*` fallback routes.
This is a shortcut method for connecting fallback routes in a given scope.
@param string|null $routeClass the route class to use, uses the default routeClass
if not specified
@return $this | fallbacks | php | cakephp/cakephp | src/Routing/RouteBuilder.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/RouteBuilder.php | MIT |
public function registerMiddleware(string $name, MiddlewareInterface|Closure|string $middleware)
{
$this->_collection->registerMiddleware($name, $middleware);
return $this;
} | Register a middleware with the RouteCollection.
Once middleware has been registered, it can be applied to the current routing
scope or any child scopes that share the same RouteCollection.
@param string $name The name of the middleware. Used when applying middleware to a scope.
@param \Psr\Http\Server\MiddlewareInterface|\Closure|string $middleware The middleware to register.
@return $this
@see \Cake\Routing\RouteCollection | registerMiddleware | php | cakephp/cakephp | src/Routing/RouteBuilder.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/RouteBuilder.php | MIT |
public function applyMiddleware(string ...$names)
{
/** @var array<string> $names */
foreach ($names as $name) {
if (!$this->_collection->middlewareExists($name)) {
$message = "Cannot apply `{$name}` middleware or middleware group. " .
'Use `registerMiddleware()` to register middleware.';
throw new InvalidArgumentException($message);
}
}
$this->middleware = array_unique(array_merge($this->middleware, $names));
return $this;
} | Apply one or many middleware to the current route scope.
Requires middleware to be registered via `registerMiddleware()`.
@param string ...$names The names of the middleware to apply to the current scope.
@return $this
@throws \InvalidArgumentException If it cannot apply one of the given middleware or middleware groups.
@see \Cake\Routing\RouteCollection::addMiddlewareToScope() | applyMiddleware | php | cakephp/cakephp | src/Routing/RouteBuilder.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/RouteBuilder.php | MIT |
public function middlewareGroup(string $name, array $middlewareNames)
{
$this->_collection->middlewareGroup($name, $middlewareNames);
return $this;
} | Apply a set of middleware to a group
@param string $name Name of the middleware group
@param array<string> $middlewareNames Names of the middleware
@return $this | middlewareGroup | php | cakephp/cakephp | src/Routing/RouteBuilder.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/RouteBuilder.php | MIT |
public function setExtensions(array $extensions, bool $merge = true)
{
if ($merge) {
$extensions = array_unique(array_merge(
$this->_extensions,
$extensions,
));
}
$this->_extensions = $extensions;
return $this;
} | Set the extensions that the route collection can handle.
@param array<string> $extensions The list of extensions to set.
@param bool $merge Whether to merge with or override existing extensions.
Defaults to `true`.
@return $this | setExtensions | php | cakephp/cakephp | src/Routing/RouteCollection.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/RouteCollection.php | MIT |
public function registerMiddleware(string $name, MiddlewareInterface|Closure|string $middleware)
{
$this->_middleware[$name] = $middleware;
return $this;
} | Register a middleware with the RouteCollection.
Once middleware has been registered, it can be applied to the current routing
scope or any child scopes that share the same RouteCollection.
@param string $name The name of the middleware. Used when applying middleware to a scope.
@param \Psr\Http\Server\MiddlewareInterface|\Closure|string $middleware The middleware to register.
@return $this | registerMiddleware | php | cakephp/cakephp | src/Routing/RouteCollection.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/RouteCollection.php | MIT |
public function middlewareGroup(string $name, array $middlewareNames)
{
if ($this->hasMiddleware($name)) {
$message = "Cannot add middleware group '{$name}'. A middleware by this name has already been registered.";
throw new InvalidArgumentException($message);
}
foreach ($middlewareNames as $middlewareName) {
if (!$this->hasMiddleware($middlewareName)) {
$message = "Cannot add '{$middlewareName}' middleware to group '{$name}'. It has not been registered.";
throw new InvalidArgumentException($message);
}
}
$this->_middlewareGroups[$name] = $middlewareNames;
return $this;
} | Add middleware to a middleware group
@param string $name Name of the middleware group
@param array<string> $middlewareNames Names of the middleware
@return $this
@throws \InvalidArgumentException | middlewareGroup | php | cakephp/cakephp | src/Routing/RouteCollection.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/RouteCollection.php | MIT |
public function setExtensions(array $extensions)
{
$this->_extensions = array_map('strtolower', $extensions);
return $this;
} | Set the supported extensions for this route.
@param array<string> $extensions The extensions to set.
@return $this | setExtensions | php | cakephp/cakephp | src/Routing/Route/Route.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/Route/Route.php | MIT |
public function setMethods(array $methods)
{
$this->defaults['_method'] = $this->normalizeAndValidateMethods($methods);
return $this;
} | Set the accepted HTTP methods for this route.
@param array<string> $methods The HTTP methods to accept.
@return $this
@throws \InvalidArgumentException When methods are not in `VALID_METHODS` list. | setMethods | php | cakephp/cakephp | src/Routing/Route/Route.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/Route/Route.php | MIT |
public function setPatterns(array $patterns)
{
$patternValues = implode('', $patterns);
if (mb_strlen($patternValues) < strlen($patternValues)) {
$this->options['multibytePattern'] = true;
}
$this->options = $patterns + $this->options;
return $this;
} | Set regexp patterns for routing parameters
If any of your patterns contain multibyte values, the `multibytePattern`
mode will be enabled.
@param array<string, string> $patterns The patterns to apply to routing elements
@return $this | setPatterns | php | cakephp/cakephp | src/Routing/Route/Route.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/Route/Route.php | MIT |
public function setPass(array $names)
{
$this->options['pass'] = $names;
return $this;
} | Set the names of parameters that will be converted into passed parameters
@param array<string> $names The names of the parameters that should be passed.
@return $this | setPass | php | cakephp/cakephp | src/Routing/Route/Route.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/Route/Route.php | MIT |
public function setMiddleware(array $middleware)
{
$this->middleware = $middleware;
return $this;
} | Set the names of the middleware that should be applied to this route.
@param array $middleware The list of middleware names to apply to this route.
Middleware names will not be checked until the route is matched.
@return $this | setMiddleware | php | cakephp/cakephp | src/Routing/Route/Route.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/Route/Route.php | MIT |
public function __construct(array|string $message, ?int $code = 404, ?Throwable $previous = null)
{
if (is_array($message)) {
if (isset($message['message'])) {
$this->_messageTemplate = $message['message'];
} elseif (isset($message['method']) && $message['method']) {
$this->_messageTemplate = $this->_messageTemplateWithMethod;
}
}
parent::__construct($message, $code, $previous);
} | Constructor.
@param array<string, mixed>|string $message Either the string of the error message, or an array of attributes
that are made available in the view, and sprintf()'d into Exception::$_messageTemplate
@param int|null $code The code of the error, is also the HTTP status code for the error. Defaults to 404.
@param \Throwable|null $previous the previous exception. | __construct | php | cakephp/cakephp | src/Routing/Exception/MissingRouteException.php | https://github.com/cakephp/cakephp/blob/master/src/Routing/Exception/MissingRouteException.php | MIT |
public function setVirtual(array $fields, bool $merge = false)
{
if ($merge === false) {
$this->_virtual = $fields;
return $this;
}
$fields = array_merge($this->_virtual, $fields);
$this->_virtual = array_unique($fields);
return $this;
} | Sets the virtual fields on this entity.
@param array<string> $fields An array of fields to treat as virtual.
@param bool $merge Merge the new fields with the existing. By default false.
@return $this | setVirtual | php | cakephp/cakephp | src/Datasource/EntityTrait.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/EntityTrait.php | MIT |
public function setDirty(string $field, bool $isDirty = true)
{
if ($isDirty === false) {
$this->setOriginalField($field);
unset($this->_dirty[$field], $this->_original[$field]);
return $this;
}
$this->_dirty[$field] = true;
unset($this->_errors[$field], $this->_invalid[$field]);
return $this;
} | Sets the dirty status of a single field.
@param string $field the field to set or check status for
@param bool $isDirty true means the field was changed, false means
it was not changed. Defaults to true.
@return $this | setDirty | php | cakephp/cakephp | src/Datasource/EntityTrait.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/EntityTrait.php | MIT |
public function setNew(bool $new)
{
if ($new) {
foreach ($this->_fields as $k => $p) {
$this->_dirty[$k] = true;
}
}
$this->_new = $new;
return $this;
} | Set the status of this entity.
Using `true` means that the entity has not been persisted in the database,
`false` that it already is.
@param bool $new Indicate whether this entity has been persisted.
@return $this | setNew | php | cakephp/cakephp | src/Datasource/EntityTrait.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/EntityTrait.php | MIT |
public function setInvalid(array $fields, bool $overwrite = false)
{
foreach ($fields as $field => $value) {
if ($overwrite) {
$this->_invalid[$field] = $value;
continue;
}
$this->_invalid += [$field => $value];
}
return $this;
} | Set fields as invalid and not patchable into the entity.
This is useful for batch operations when one needs to get the original value for an error message after patching.
This value could not be patched into the entity and is simply copied into the _invalid property for debugging
purposes or to be able to log it away.
@param array<string, mixed> $fields The values to set.
@param bool $overwrite Whether to overwrite pre-existing values for $field.
@return $this | setInvalid | php | cakephp/cakephp | src/Datasource/EntityTrait.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/EntityTrait.php | MIT |
public function setInvalidField(string $field, mixed $value)
{
$this->_invalid[$field] = $value;
return $this;
} | Sets a field as invalid and not patchable into the entity.
@param string $field The value to set.
@param mixed $value The invalid value to be set for $field.
@return $this | setInvalidField | php | cakephp/cakephp | src/Datasource/EntityTrait.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/EntityTrait.php | MIT |
public function setAccess(array|string $field, bool $set)
{
if ($field === '*') {
$this->_accessible = array_map(fn($p) => $set, $this->_accessible);
$this->_accessible['*'] = $set;
return $this;
}
foreach ((array)$field as $prop) {
$this->_accessible[$prop] = $set;
}
return $this;
} | Stores whether a field value can be changed or set in this entity.
The special field `*` can also be marked as accessible or protected, meaning
that any other field specified before will take its value. For example
`$entity->setAccess('*', true)` means that any field not specified already
will be accessible by default.
You can also call this method with an array of fields, in which case they
will each take the accessibility value specified in the second argument.
### Example:
```
$entity->setAccess('id', true); // Mark id as not protected
$entity->setAccess('author_id', false); // Mark author_id as protected
$entity->setAccess(['id', 'user_id'], true); // Mark both fields as accessible
$entity->setAccess('*', false); // Mark all fields as protected
```
@param array<string>|string $field Single or list of fields to change its accessibility
@param bool $set True marks the field as accessible, false will
mark it as protected.
@return $this | setAccess | php | cakephp/cakephp | src/Datasource/EntityTrait.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/EntityTrait.php | MIT |
public function __construct(callable $rule, ?string $name, array $options = [])
{
$this->rule = $rule;
$this->name = $name;
$this->options = $options;
} | Constructor
### Options
- `errorField` The field errors should be set onto.
- `message` The error message.
Individual rules may have additional options that can be
set here. Any options will be passed into the rule as part of the
rule $scope.
@param callable $rule The rule to be invoked.
@param string|null $name The name of the rule. Used in error messages.
@param array<string, mixed> $options The options for the rule. See above. | __construct | php | cakephp/cakephp | src/Datasource/RuleInvoker.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/RuleInvoker.php | MIT |
public function setOptions(array $options)
{
$this->options = $options + $this->options;
return $this;
} | Set options for the rule invocation.
Old options will be merged with the new ones.
@param array<string, mixed> $options The options to set.
@return $this | setOptions | php | cakephp/cakephp | src/Datasource/RuleInvoker.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/RuleInvoker.php | MIT |
public function setName(?string $name)
{
if ($name) {
$this->name = $name;
}
return $this;
} | Set the rule name.
Only truthy names will be set.
@param string|null $name The name to set.
@return $this | setName | php | cakephp/cakephp | src/Datasource/RuleInvoker.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/RuleInvoker.php | MIT |
public function setModelType(string $modelType)
{
$this->_modelType = $modelType;
return $this;
} | Set the model type to be used by this class
@param string $modelType The model type
@return $this | setModelType | php | cakephp/cakephp | src/Datasource/ModelAwareTrait.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/ModelAwareTrait.php | MIT |
public function __construct(array $options = [])
{
$this->_options = $options;
$this->_useI18n = function_exists('\Cake\I18n\__d');
} | Constructor. Takes the options to be passed to all rules.
@param array<string, mixed> $options The options to pass to every rule | __construct | php | cakephp/cakephp | src/Datasource/RulesChecker.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/RulesChecker.php | MIT |
public function add(callable $rule, array|string|null $name = null, array $options = [])
{
if (is_string($name)) {
$this->checkName($name, $this->_rules);
$this->_rules[$name] = $this->_addError($rule, $name, $options);
} else {
$this->_rules[] = $this->_addError($rule, $name, $options);
}
return $this;
} | Adds a rule that will be applied to the entity on create, update and delete
operations.
### Options
The options array accept the following special keys:
- `errorField`: The name of the entity field that will be marked as invalid
if the rule does not pass.
- `message`: The error message to set to `errorField` if the rule does not pass.
@param callable $rule A callable function or object that will return whether
the entity is valid or not.
@param array|string|null $name The alias for a rule, or an array of options.
@param array<string, mixed> $options List of extra options to pass to the rule callable as
second argument.
@return $this
@throws \Cake\Core\Exception\CakeException If a rule with the same name already exists | add | php | cakephp/cakephp | src/Datasource/RulesChecker.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/RulesChecker.php | MIT |
public function addCreate(callable $rule, array|string|null $name = null, array $options = [])
{
if (is_string($name)) {
$this->checkName($name, $this->_createRules);
$this->_createRules[$name] = $this->_addError($rule, $name, $options);
} else {
$this->_createRules[] = $this->_addError($rule, $name, $options);
}
return $this;
} | Adds a rule that will be applied to the entity on create operations.
### Options
The options array accept the following special keys:
- `errorField`: The name of the entity field that will be marked as invalid
if the rule does not pass.
- `message`: The error message to set to `errorField` if the rule does not pass.
@param callable $rule A callable function or object that will return whether
the entity is valid or not.
@param array|string|null $name The alias for a rule or an array of options.
@param array<string, mixed> $options List of extra options to pass to the rule callable as
second argument.
@return $this
@throws \Cake\Core\Exception\CakeException If a rule with the same name already exists | addCreate | php | cakephp/cakephp | src/Datasource/RulesChecker.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/RulesChecker.php | MIT |
public function removeCreate(string $name)
{
unset($this->_createRules[$name]);
return $this;
} | Removes a rule from the create set.
@param string $name The name of the rule to remove.
@return $this
@since 5.1.0 | removeCreate | php | cakephp/cakephp | src/Datasource/RulesChecker.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/RulesChecker.php | MIT |
public function addUpdate(callable $rule, array|string|null $name = null, array $options = [])
{
if (is_string($name)) {
$this->checkName($name, $this->_updateRules);
$this->_updateRules[$name] = $this->_addError($rule, $name, $options);
} else {
$this->_updateRules[] = $this->_addError($rule, $name, $options);
}
return $this;
} | Adds a rule that will be applied to the entity on update operations.
### Options
The options array accept the following special keys:
- `errorField`: The name of the entity field that will be marked as invalid
if the rule does not pass.
- `message`: The error message to set to `errorField` if the rule does not pass.
@param callable $rule A callable function or object that will return whether
the entity is valid or not.
@param array|string|null $name The alias for a rule, or an array of options.
@param array<string, mixed> $options List of extra options to pass to the rule callable as
second argument.
@return $this
@throws \Cake\Core\Exception\CakeException If a rule with the same name already exists | addUpdate | php | cakephp/cakephp | src/Datasource/RulesChecker.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/RulesChecker.php | MIT |
public function removeUpdate(string $name)
{
unset($this->_updateRules[$name]);
return $this;
} | Removes a rule from the update set.
@param string $name The name of the rule to remove.
@return $this
@since 5.1.0 | removeUpdate | php | cakephp/cakephp | src/Datasource/RulesChecker.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/RulesChecker.php | MIT |
public function addDelete(callable $rule, array|string|null $name = null, array $options = [])
{
if (is_string($name)) {
$this->checkName($name, $this->_deleteRules);
$this->_deleteRules[$name] = $this->_addError($rule, $name, $options);
} else {
$this->_deleteRules[] = $this->_addError($rule, $name, $options);
}
return $this;
} | Adds a rule that will be applied to the entity on delete operations.
### Options
The options array accept the following special keys:
- `errorField`: The name of the entity field that will be marked as invalid
if the rule does not pass.
- `message`: The error message to set to `errorField` if the rule does not pass.
@param callable $rule A callable function or object that will return whether
the entity is valid or not.
@param array|string|null $name The alias for a rule, or an array of options.
@param array<string, mixed> $options List of extra options to pass to the rule callable as
second argument.
@return $this
@throws \Cake\Core\Exception\CakeException If a rule with the same name already exists | addDelete | php | cakephp/cakephp | src/Datasource/RulesChecker.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/RulesChecker.php | MIT |
public function removeDelete(string $name)
{
unset($this->_deleteRules[$name]);
return $this;
} | Removes a rule from the delete set.
@param string $name The name of the rule to remove.
@return $this
@since 5.1.0 | removeDelete | php | cakephp/cakephp | src/Datasource/RulesChecker.php | https://github.com/cakephp/cakephp/blob/master/src/Datasource/RulesChecker.php | MIT |
public function set(string $name, object $object)
{
// Just call unload if the object was loaded before
if (array_key_exists($name, $this->_loaded)) {
$this->unload($name);
}
if ($this instanceof EventDispatcherInterface && $object instanceof EventListenerInterface) {
$this->getEventManager()->on($object);
}
$this->_loaded[$name] = $object;
return $this;
} | Set an object directly into the registry by name.
If this collection implements events, the passed object will
be attached into the event manager
@param string $name The name of the object to set in the registry.
@param object $object instance to store in the registry
@return $this
@phpstan-param TObject $object | set | php | cakephp/cakephp | src/Core/ObjectRegistry.php | https://github.com/cakephp/cakephp/blob/master/src/Core/ObjectRegistry.php | MIT |
public function unload(string $name)
{
if (!isset($this->_loaded[$name])) {
throw new CakeException(sprintf('Object named `%s` is not loaded.', $name));
}
$object = $this->_loaded[$name];
if ($this instanceof EventDispatcherInterface && $object instanceof EventListenerInterface) {
$this->getEventManager()->off($object);
}
unset($this->_loaded[$name]);
return $this;
} | Remove an object from the registry.
If this registry has an event manager, the object will be detached from any events as well.
@param string $name The name of the object to remove from the registry.
@return $this | unload | php | cakephp/cakephp | src/Core/ObjectRegistry.php | https://github.com/cakephp/cakephp/blob/master/src/Core/ObjectRegistry.php | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.