code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
cakephp Namespace Widget Namespace Widget
================
### Interfaces
* ##### [WidgetInterface](interface-cake.view.widget.widgetinterface)
Interface for input widgets.
### Classes
* ##### [BasicWidget](class-cake.view.widget.basicwidget)
Basic input class.
* ##### [ButtonWidget](class-cake.view.widget.buttonwidget)
Button input class
* ##### [CheckboxWidget](class-cake.view.widget.checkboxwidget)
Input widget for creating checkbox widgets.
* ##### [DateTimeWidget](class-cake.view.widget.datetimewidget)
Input widget class for generating a date time input widget.
* ##### [FileWidget](class-cake.view.widget.filewidget)
Input widget class for generating a file upload control.
* ##### [LabelWidget](class-cake.view.widget.labelwidget)
Form 'widget' for creating labels.
* ##### [MultiCheckboxWidget](class-cake.view.widget.multicheckboxwidget)
Input widget class for generating multiple checkboxes.
* ##### [NestingLabelWidget](class-cake.view.widget.nestinglabelwidget)
Form 'widget' for creating labels that contain their input.
* ##### [RadioWidget](class-cake.view.widget.radiowidget)
Input widget class for generating a set of radio buttons.
* ##### [SelectBoxWidget](class-cake.view.widget.selectboxwidget)
Input widget class for generating a selectbox.
* ##### [TextareaWidget](class-cake.view.widget.textareawidget)
Input widget class for generating a textarea control.
* ##### [WidgetLocator](class-cake.view.widget.widgetlocator)
A registry/factory for input widgets.
* ##### [YearWidget](class-cake.view.widget.yearwidget)
Input widget class for generating a calendar year select box.
cakephp Class FormHelper Class FormHelper
=================
Form helper library.
Automatic generation of HTML FORMs from given data.
**Namespace:** [Cake\View\Helper](namespace-cake.view.helper)
**Link:** https://book.cakephp.org/4/en/views/helpers/form.html
Constants
---------
* `string` **SECURE\_SKIP**
```
'skip'
```
Constant used internally to skip the securing process, and neither add the field to the hash or to the unlocked fields.
Property Summary
----------------
* [$Html](#%24Html) public @property `Cake\View\Helper\HtmlHelper`
* [$Url](#%24Url) public @property `Cake\View\Helper\UrlHelper`
* [$\_View](#%24_View) protected `Cake\View\View` The View instance this helper is attached to
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_context](#%24_context) protected `Cake\View\Form\ContextInterface|null` Context for the current form.
* [$\_contextFactory](#%24_contextFactory) protected `Cake\View\Form\ContextFactory|null` Context factory.
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for the helper.
* [$\_defaultWidgets](#%24_defaultWidgets) protected `array<string, array<string>>` Default widgets
* [$\_groupedInputTypes](#%24_groupedInputTypes) protected `array<string>` Grouped input types.
* [$\_helperMap](#%24_helperMap) protected `array<string, array>` A helper lookup table used to lazy load helper objects.
* [$\_idPrefix](#%24_idPrefix) protected `string|null` Prefix for id attribute.
* [$\_idSuffixes](#%24_idSuffixes) protected `array<string>` A list of id suffixes used in the current rendering.
* [$\_lastAction](#%24_lastAction) protected `string` The action attribute value of the last created form. Used to make form/request specific hashes for form tampering protection.
* [$\_locator](#%24_locator) protected `Cake\View\Widget\WidgetLocator` Locator for input widgets.
* [$\_templater](#%24_templater) protected `Cake\View\StringTemplate|null` StringTemplate instance.
* [$\_valueSources](#%24_valueSources) protected `array<string>` The default sources.
* [$formProtector](#%24formProtector) protected `Cake\Form\FormProtector|null` Form protector
* [$helpers](#%24helpers) protected `array` Other helpers used by FormHelper
* [$requestType](#%24requestType) public `string|null` Defines the type of form being created. Set by FormHelper::create().
* [$supportedValueSources](#%24supportedValueSources) protected `array<string>` The supported sources that can be used to populate input values.
Method Summary
--------------
* ##### [\_\_call()](#__call()) public
Missing method handler - implements various simple input types. Is used to create inputs of various types. e.g. `$this->Form->text();` will create `<input type="text"/>` while `$this->Form->range();` will create `<input type="range"/>`
* ##### [\_\_construct()](#__construct()) public
Construct the widgets and binds the default context providers
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_get()](#__get()) public
Lazy loads helpers.
* ##### [\_clearIds()](#_clearIds()) protected
Clear the stored ID suffixes.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_confirm()](#_confirm()) protected
Returns a string to be used as onclick handler for confirm dialogs.
* ##### [\_csrfField()](#_csrfField()) protected
Return a CSRF input if the request data is present. Used to secure forms in conjunction with CsrfMiddleware.
* ##### [\_domId()](#_domId()) protected
Generate an ID suitable for use in an ID attribute.
* ##### [\_extractOption()](#_extractOption()) protected
Extracts a single option from an options array.
* ##### [\_formUrl()](#_formUrl()) protected
Create the URL for a form based on the options.
* ##### [\_getContext()](#_getContext()) protected
Find the matching context provider for the data.
* ##### [\_getInput()](#_getInput()) protected
Generates an input element
* ##### [\_getLabel()](#_getLabel()) protected
Generate label for input
* ##### [\_groupTemplate()](#_groupTemplate()) protected
Generates an group template element
* ##### [\_id()](#_id()) protected
Generate an ID attribute for an element.
* ##### [\_idSuffix()](#_idSuffix()) protected
Generate an ID suffix.
* ##### [\_initInputField()](#_initInputField()) protected
Sets field defaults and adds field to form security input hash. Will also add the error class if the field contains validation errors.
* ##### [\_inputContainerTemplate()](#_inputContainerTemplate()) protected
Generates an input container template
* ##### [\_inputLabel()](#_inputLabel()) protected
Generate a label for an input() call.
* ##### [\_inputType()](#_inputType()) protected
Returns the input type that was guessed for the provided fieldName, based on the internal type it is associated too, its name and the variables that can be found in the view template
* ##### [\_isDisabled()](#_isDisabled()) protected
Determine if a field is disabled.
* ##### [\_lastAction()](#_lastAction()) protected
Correctly store the last created form action URL.
* ##### [\_magicOptions()](#_magicOptions()) protected
Magically set option type and corresponding options
* ##### [\_optionsOptions()](#_optionsOptions()) protected
Selects the variable containing the options for a select field if present, and sets the value to the 'options' key in the options array.
* ##### [\_parseOptions()](#_parseOptions()) protected
Generates input options array
* ##### [addClass()](#addClass()) public
Adds the given class to the element options
* ##### [addContextProvider()](#addContextProvider()) public
Add a new context type.
* ##### [addWidget()](#addWidget()) public
Add a new widget to FormHelper.
* ##### [allControls()](#allControls()) public
Generate a set of controls for `$fields`. If $fields is empty the fields of current model will be used.
* ##### [button()](#button()) public
Creates a `<button>` tag.
* ##### [checkbox()](#checkbox()) public
Creates a checkbox input widget.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [context()](#context()) public
Get the context instance for the current form set.
* ##### [contextFactory()](#contextFactory()) public
Set the context factory the helper will use.
* ##### [control()](#control()) public
Generates a form control element complete with label and wrapper div.
* ##### [controls()](#controls()) public
Generate a set of controls for `$fields` wrapped in a fieldset element.
* ##### [create()](#create()) public
Returns an HTML form element.
* ##### [createFormProtector()](#createFormProtector()) protected
Create FormProtector instance.
* ##### [date()](#date()) public
Generate an input tag with type "date".
* ##### [dateTime()](#dateTime()) public
Generate an input tag with type "datetime-local".
* ##### [email()](#email()) public @method
Creates input of type email.
* ##### [end()](#end()) public
Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden input fields where appropriate.
* ##### [error()](#error()) public
Returns a formatted error message for given form field, '' if no errors.
* ##### [fieldset()](#fieldset()) public
Wrap a set of inputs in a fieldset
* ##### [file()](#file()) public
Creates file input widget.
* ##### [formatTemplate()](#formatTemplate()) public
Formats a template string with $data
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getFormProtector()](#getFormProtector()) public
Get form protector instance.
* ##### [getSourceValue()](#getSourceValue()) public
Gets a single field value from the sources available.
* ##### [getTemplates()](#getTemplates()) public
Gets templates to use or a specific template.
* ##### [getValueSources()](#getValueSources()) public
Gets the value sources.
* ##### [getView()](#getView()) public
Get the view instance this helper is bound to.
* ##### [getWidgetLocator()](#getWidgetLocator()) public
Get the widget locator currently used by the helper.
* ##### [hidden()](#hidden()) public
Creates a hidden input field.
* ##### [implementedEvents()](#implementedEvents()) public
Event listeners.
* ##### [initialize()](#initialize()) public
Constructor hook method.
* ##### [isFieldError()](#isFieldError()) public
Returns true if there is an error for the given field, otherwise false
* ##### [label()](#label()) public
Returns a formatted LABEL element for HTML forms.
* ##### [month()](#month()) public
Generate an input tag with type "month".
* ##### [multiCheckbox()](#multiCheckbox()) public
Creates a set of checkboxes out of options.
* ##### [number()](#number()) public @method
Creates input of type number.
* ##### [password()](#password()) public @method
Creates input of type password.
* ##### [postButton()](#postButton()) public
Create a `<button>` tag with a surrounding `<form>` that submits via POST as default.
* ##### [postLink()](#postLink()) public
Creates an HTML link, but access the URL using the method you specify (defaults to POST). Requires javascript to be enabled in browser.
* ##### [radio()](#radio()) public
Creates a set of radio widgets.
* ##### [resetTemplates()](#resetTemplates()) public
Restores the default values built into FormHelper.
* ##### [search()](#search()) public @method
Creates input of type search.
* ##### [secure()](#secure()) public
Generates a hidden field with a security hash based on the fields used in the form.
* ##### [select()](#select()) public
Returns a formatted SELECT element.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setRequiredAndCustomValidity()](#setRequiredAndCustomValidity()) protected
Set required attribute and custom validity JS.
* ##### [setTemplates()](#setTemplates()) public
Sets templates to use.
* ##### [setValueSources()](#setValueSources()) public
Sets the value sources.
* ##### [setWidgetLocator()](#setWidgetLocator()) public
Set the widget locator the helper will use.
* ##### [submit()](#submit()) public
Creates a submit button element. This method will generate `<input />` elements that can be used to submit, and reset forms by using $options. image submits can be created by supplying an image path for $caption.
* ##### [templater()](#templater()) public
Returns the templater instance.
* ##### [text()](#text()) public @method
Creates input of type text.
* ##### [textarea()](#textarea()) public
Creates a textarea widget.
* ##### [time()](#time()) public
Generate an input tag with type "time".
* ##### [unlockField()](#unlockField()) public
Add to the list of fields that are currently unlocked.
* ##### [validateValueSources()](#validateValueSources()) protected
Validate value sources.
* ##### [widget()](#widget()) public
Render a named widget.
* ##### [year()](#year()) public
Returns a SELECT element for years
Method Detail
-------------
### \_\_call() public
```
__call(string $method, array $params): string
```
Missing method handler - implements various simple input types. Is used to create inputs of various types. e.g. `$this->Form->text();` will create `<input type="text"/>` while `$this->Form->range();` will create `<input type="range"/>`
### Usage
```
$this->Form->search('User.query', ['value' => 'test']);
```
Will make an input like:
`<input type="search" id="UserQuery" name="User[query]" value="test"/>`
The first argument to an input type should always be the fieldname, in `Model.field` format. The second argument should always be an array of attributes for the input.
#### Parameters
`string` $method Method name / input type to make.
`array` $params Parameters for the method call
#### Returns
`string`
#### Throws
`Cake\Core\Exception\CakeException`
When there are no params for the method call. ### \_\_construct() public
```
__construct(Cake\View\View $view, array<string, mixed> $config = [])
```
Construct the widgets and binds the default context providers
#### Parameters
`Cake\View\View` $view The View this helper is being attached to.
`array<string, mixed>` $config optional Configuration settings for the helper.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): Cake\View\Helper|null|void
```
Lazy loads helpers.
#### Parameters
`string` $name Name of the property being accessed.
#### Returns
`Cake\View\Helper|null|void`
### \_clearIds() protected
```
_clearIds(): void
```
Clear the stored ID suffixes.
#### Returns
`void`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_confirm() protected
```
_confirm(string $okCode, string $cancelCode): string
```
Returns a string to be used as onclick handler for confirm dialogs.
#### Parameters
`string` $okCode Code to be executed after user chose 'OK'
`string` $cancelCode Code to be executed after user chose 'Cancel'
#### Returns
`string`
### \_csrfField() protected
```
_csrfField(): string
```
Return a CSRF input if the request data is present. Used to secure forms in conjunction with CsrfMiddleware.
#### Returns
`string`
### \_domId() protected
```
_domId(string $value): string
```
Generate an ID suitable for use in an ID attribute.
#### Parameters
`string` $value The value to convert into an ID.
#### Returns
`string`
### \_extractOption() protected
```
_extractOption(string $name, array<string, mixed> $options, mixed $default = null): mixed
```
Extracts a single option from an options array.
#### Parameters
`string` $name The name of the option to pull out.
`array<string, mixed>` $options The array of options you want to extract.
`mixed` $default optional The default option value
#### Returns
`mixed`
### \_formUrl() protected
```
_formUrl(Cake\View\Form\ContextInterface $context, array<string, mixed> $options): array|string
```
Create the URL for a form based on the options.
#### Parameters
`Cake\View\Form\ContextInterface` $context The context object to use.
`array<string, mixed>` $options An array of options from create()
#### Returns
`array|string`
### \_getContext() protected
```
_getContext(mixed $data = []): Cake\View\Form\ContextInterface
```
Find the matching context provider for the data.
If no type can be matched a NullContext will be returned.
#### Parameters
`mixed` $data optional The data to get a context provider for.
#### Returns
`Cake\View\Form\ContextInterface`
#### Throws
`RuntimeException`
when the context class does not implement the ContextInterface. ### \_getInput() protected
```
_getInput(string $fieldName, array<string, mixed> $options): array|string
```
Generates an input element
#### Parameters
`string` $fieldName the field name
`array<string, mixed>` $options The options for the input element
#### Returns
`array|string`
### \_getLabel() protected
```
_getLabel(string $fieldName, array<string, mixed> $options): string|false
```
Generate label for input
#### Parameters
`string` $fieldName The name of the field to generate label for.
`array<string, mixed>` $options Options list.
#### Returns
`string|false`
### \_groupTemplate() protected
```
_groupTemplate(array<string, mixed> $options): string
```
Generates an group template element
#### Parameters
`array<string, mixed>` $options The options for group template
#### Returns
`string`
### \_id() protected
```
_id(string $name, string $val): string
```
Generate an ID attribute for an element.
Ensures that id's for a given set of fields are unique.
#### Parameters
`string` $name The ID attribute name.
`string` $val The ID attribute value.
#### Returns
`string`
### \_idSuffix() protected
```
_idSuffix(string $val): string
```
Generate an ID suffix.
Ensures that id's for a given set of fields are unique.
#### Parameters
`string` $val The ID attribute value.
#### Returns
`string`
### \_initInputField() protected
```
_initInputField(string $field, array<string, mixed>|array<string> $options = []): array<string, mixed>
```
Sets field defaults and adds field to form security input hash. Will also add the error class if the field contains validation errors.
### Options
* `secure` - boolean whether the field should be added to the security fields. Disabling the field using the `disabled` option, will also omit the field from being part of the hashed key.
* `default` - mixed - The value to use if there is no value in the form's context.
* `disabled` - mixed - Either a boolean indicating disabled state, or the string in a numerically indexed value.
* `id` - mixed - If `true` it will be auto generated based on field name.
This method will convert a numerically indexed 'disabled' into an associative array value. FormHelper's internals expect associative options.
The output of this function is a more complete set of input attributes that can be passed to a form widget to generate the actual input.
#### Parameters
`string` $field Name of the field to initialize options for.
`array<string, mixed>|array<string>` $options optional Array of options to append options into.
#### Returns
`array<string, mixed>`
### \_inputContainerTemplate() protected
```
_inputContainerTemplate(array<string, mixed> $options): string
```
Generates an input container template
#### Parameters
`array<string, mixed>` $options The options for input container template
#### Returns
`string`
### \_inputLabel() protected
```
_inputLabel(string $fieldName, array<string, mixed>|string|null $label = null, array<string, mixed> $options = []): string
```
Generate a label for an input() call.
$options can contain a hash of id overrides. These overrides will be used instead of the generated values if present.
#### Parameters
`string` $fieldName The name of the field to generate label for.
`array<string, mixed>|string|null` $label optional Label text or array with label attributes.
`array<string, mixed>` $options optional Options for the label element.
#### Returns
`string`
### \_inputType() protected
```
_inputType(string $fieldName, array<string, mixed> $options): string
```
Returns the input type that was guessed for the provided fieldName, based on the internal type it is associated too, its name and the variables that can be found in the view template
#### Parameters
`string` $fieldName the name of the field to guess a type for
`array<string, mixed>` $options the options passed to the input method
#### Returns
`string`
### \_isDisabled() protected
```
_isDisabled(array<string, mixed> $options): bool
```
Determine if a field is disabled.
#### Parameters
`array<string, mixed>` $options The option set.
#### Returns
`bool`
### \_lastAction() protected
```
_lastAction(array|string|null $url = null): void
```
Correctly store the last created form action URL.
#### Parameters
`array|string|null` $url optional The URL of the last form.
#### Returns
`void`
### \_magicOptions() protected
```
_magicOptions(string $fieldName, array<string, mixed> $options, bool $allowOverride): array<string, mixed>
```
Magically set option type and corresponding options
#### Parameters
`string` $fieldName The name of the field to generate options for.
`array<string, mixed>` $options Options list.
`bool` $allowOverride Whether it is allowed for this method to overwrite the 'type' key in options.
#### Returns
`array<string, mixed>`
### \_optionsOptions() protected
```
_optionsOptions(string $fieldName, array<string, mixed> $options): array<string, mixed>
```
Selects the variable containing the options for a select field if present, and sets the value to the 'options' key in the options array.
#### Parameters
`string` $fieldName The name of the field to find options for.
`array<string, mixed>` $options Options list.
#### Returns
`array<string, mixed>`
### \_parseOptions() protected
```
_parseOptions(string $fieldName, array<string, mixed> $options): array<string, mixed>
```
Generates input options array
#### Parameters
`string` $fieldName The name of the field to parse options for.
`array<string, mixed>` $options Options list.
#### Returns
`array<string, mixed>`
### addClass() public
```
addClass(array<string, mixed> $options, string $class, string $key = 'class'): array<string, mixed>
```
Adds the given class to the element options
#### Parameters
`array<string, mixed>` $options Array options/attributes to add a class to
`string` $class The class name being added.
`string` $key optional the key to use for class. Defaults to `'class'`.
#### Returns
`array<string, mixed>`
### addContextProvider() public
```
addContextProvider(string $type, callable $check): void
```
Add a new context type.
Form context types allow FormHelper to interact with data providers that come from outside CakePHP. For example if you wanted to use an alternative ORM like Doctrine you could create and connect a new context class to allow FormHelper to read metadata from doctrine.
#### Parameters
`string` $type The type of context. This key can be used to overwrite existing providers.
`callable` $check A callable that returns an object when the form context is the correct type.
#### Returns
`void`
### addWidget() public
```
addWidget(string $name, Cake\View\Widget\WidgetInterface|array $spec): void
```
Add a new widget to FormHelper.
Allows you to add or replace widget instances with custom code.
#### Parameters
`string` $name The name of the widget. e.g. 'text'.
`Cake\View\Widget\WidgetInterface|array` $spec Either a string class name or an object implementing the WidgetInterface.
#### Returns
`void`
### allControls() public
```
allControls(array $fields = [], array<string, mixed> $options = []): string
```
Generate a set of controls for `$fields`. If $fields is empty the fields of current model will be used.
You can customize individual controls through `$fields`.
```
$this->Form->allControls([
'name' => ['label' => 'custom label']
]);
```
You can exclude fields by specifying them as `false`:
```
$this->Form->allControls(['title' => false]);
```
In the above example, no field would be generated for the title field.
#### Parameters
`array` $fields optional An array of customizations for the fields that will be generated. This array allows you to set custom types, labels, or other options.
`array<string, mixed>` $options optional Options array. Valid keys are:
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#generating-entire-forms
### button() public
```
button(string $title, array<string, mixed> $options = []): string
```
Creates a `<button>` tag.
### Options:
* `type` - Value for "type" attribute of button. Defaults to "submit".
* `escapeTitle` - HTML entity encode the title of the button. Defaults to true.
* `escape` - HTML entity encode the attributes of button tag. Defaults to true.
* `confirm` - Confirm message to show. Form execution will only continue if confirmed then.
#### Parameters
`string` $title The button's caption. Not automatically HTML encoded
`array<string, mixed>` $options optional Array of options and HTML attributes.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#creating-button-elements
### checkbox() public
```
checkbox(string $fieldName, array<string, mixed> $options = []): array<string>|string
```
Creates a checkbox input widget.
### Options:
* `value` - the value of the checkbox
* `checked` - boolean indicate that this checkbox is checked.
* `hiddenField` - boolean|string. Set to false to disable a hidden input from being generated. Passing a string will define the hidden input value.
* `disabled` - create a disabled input.
* `default` - Set the default value for the checkbox. This allows you to start checkboxes as checked, without having to check the POST data. A matching POST data value, will overwrite the default value.
#### Parameters
`string` $fieldName Name of a field, like this "modelname.fieldname"
`array<string, mixed>` $options optional Array of HTML attributes.
#### Returns
`array<string>|string`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#creating-checkboxes
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### context() public
```
context(Cake\View\Form\ContextInterface|null $context = null): Cake\View\Form\ContextInterface
```
Get the context instance for the current form set.
If there is no active form null will be returned.
#### Parameters
`Cake\View\Form\ContextInterface|null` $context optional Either the new context when setting, or null to get.
#### Returns
`Cake\View\Form\ContextInterface`
### contextFactory() public
```
contextFactory(Cake\View\Form\ContextFactory|null $instance = null, array $contexts = []): Cake\View\Form\ContextFactory
```
Set the context factory the helper will use.
#### Parameters
`Cake\View\Form\ContextFactory|null` $instance optional The context factory instance to set.
`array` $contexts optional An array of context providers.
#### Returns
`Cake\View\Form\ContextFactory`
### control() public
```
control(string $fieldName, array<string, mixed> $options = []): string
```
Generates a form control element complete with label and wrapper div.
### Options
See each field type method for more information. Any options that are part of $attributes or $options for the different **type** methods can be included in `$options` for control(). Additionally, any unknown keys that are not in the list below, or part of the selected type's options will be treated as a regular HTML attribute for the generated input.
* `type` - Force the type of widget you want. e.g. `type => 'select'`
* `label` - Either a string label, or an array of options for the label. See FormHelper::label().
* `options` - For widgets that take options e.g. radio, select.
* `error` - Control the error message that is produced. Set to `false` to disable any kind of error reporting (field error and error messages).
* `empty` - String or boolean to enable empty select box options.
* `nestedInput` - Used with checkbox and radio inputs. Set to false to render inputs outside of label elements. Can be set to true on any input to force the input inside the label. If you enable this option for radio buttons you will also need to modify the default `radioWrapper` template.
* `templates` - The templates you want to use for this input. Any templates will be merged on top of the already loaded templates. This option can either be a filename in /config that contains the templates you want to load, or an array of templates to use.
* `labelOptions` - Either `false` to disable label around nestedWidgets e.g. radio, multicheckbox or an array of attributes for the label tag. `selected` will be added to any classes e.g. `class => 'myclass'` where widget is checked
#### Parameters
`string` $fieldName This should be "modelname.fieldname"
`array<string, mixed>` $options optional Each type of input takes different options.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#creating-form-controls
### controls() public
```
controls(array $fields, array<string, mixed> $options = []): string
```
Generate a set of controls for `$fields` wrapped in a fieldset element.
You can customize individual controls through `$fields`.
```
$this->Form->controls([
'name' => ['label' => 'custom label'],
'email'
]);
```
#### Parameters
`array` $fields An array of the fields to generate. This array allows you to set custom types, labels, or other options.
`array<string, mixed>` $options optional Options array. Valid keys are:
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#generating-entire-forms
### create() public
```
create(mixed $context = null, array<string, mixed> $options = []): string
```
Returns an HTML form element.
### Options:
* `type` Form method defaults to autodetecting based on the form context. If the form context's isCreate() method returns false, a PUT request will be done.
* `method` Set the form's method attribute explicitly.
* `url` The URL the form submits to. Can be a string or a URL array.
* `encoding` Set the accept-charset encoding for the form. Defaults to `Configure::read('App.encoding')`
* `enctype` Set the form encoding explicitly. By default `type => file` will set `enctype` to `multipart/form-data`.
* `templates` The templates you want to use for this form. Any templates will be merged on top of the already loaded templates. This option can either be a filename in /config that contains the templates you want to load, or an array of templates to use.
* `context` Additional options for the context class. For example the EntityContext accepts a 'table' option that allows you to set the specific Table class the form should be based on.
* `idPrefix` Prefix for generated ID attributes.
* `valueSources` The sources that values should be read from. See FormHelper::setValueSources()
* `templateVars` Provide template variables for the formStart template.
#### Parameters
`mixed` $context optional The context for which the form is being defined. Can be a ContextInterface instance, ORM entity, ORM resultset, or an array of meta data. You can use `null` to make a context-less form.
`array<string, mixed>` $options optional An array of html attributes and options.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#Cake\View\Helper\FormHelper::create
### createFormProtector() protected
```
createFormProtector(array<string, mixed> $formTokenData): Cake\Form\FormProtector
```
Create FormProtector instance.
#### Parameters
`array<string, mixed>` $formTokenData Token data.
#### Returns
`Cake\Form\FormProtector`
### date() public
```
date(string $fieldName, array<string, mixed> $options = []): string
```
Generate an input tag with type "date".
### Options:
See dateTime() options.
#### Parameters
`string` $fieldName The field name.
`array<string, mixed>` $options optional Array of options or HTML attributes.
#### Returns
`string`
### dateTime() public
```
dateTime(string $fieldName, array<string, mixed> $options = []): string
```
Generate an input tag with type "datetime-local".
### Options:
* `value` | `default` The default value to be used by the input. If set to `true` current datetime will be used.
#### Parameters
`string` $fieldName The field name.
`array<string, mixed>` $options optional Array of options or HTML attributes.
#### Returns
`string`
### email() public @method
```
email(string $fieldName, array $options = []): string
```
Creates input of type email.
#### Parameters
`string` $fieldName `array` $options optional #### Returns
`string`
### end() public
```
end(array<string, mixed> $secureAttributes = []): string
```
Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden input fields where appropriate.
Resets some parts of the state, shared among multiple FormHelper::create() calls, to defaults.
#### Parameters
`array<string, mixed>` $secureAttributes optional Secure attributes which will be passed as HTML attributes into the hidden input elements generated for the Security Component.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#closing-the-form
### error() public
```
error(string $field, array|string|null $text = null, array<string, mixed> $options = []): string
```
Returns a formatted error message for given form field, '' if no errors.
Uses the `error`, `errorList` and `errorItem` templates. The `errorList` and `errorItem` templates are used to format multiple error messages per field.
### Options:
* `escape` boolean - Whether to html escape the contents of the error.
#### Parameters
`string` $field A field name, like "modelname.fieldname"
`array|string|null` $text optional Error message as string or array of messages. If an array, it should be a hash of key names => messages.
`array<string, mixed>` $options optional See above.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#displaying-and-checking-errors
### fieldset() public
```
fieldset(string $fields = '', array<string, mixed> $options = []): string
```
Wrap a set of inputs in a fieldset
#### Parameters
`string` $fields optional the form inputs to wrap in a fieldset
`array<string, mixed>` $options optional Options array. Valid keys are:
#### Returns
`string`
### file() public
```
file(string $fieldName, array<string, mixed> $options = []): string
```
Creates file input widget.
#### Parameters
`string` $fieldName Name of a field, in the form "modelname.fieldname"
`array<string, mixed>` $options optional Array of HTML attributes.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#creating-file-inputs
### formatTemplate() public
```
formatTemplate(string $name, array<string, mixed> $data): string
```
Formats a template string with $data
#### Parameters
`string` $name The template name.
`array<string, mixed>` $data The data to insert.
#### Returns
`string`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getFormProtector() public
```
getFormProtector(): Cake\Form\FormProtector
```
Get form protector instance.
#### Returns
`Cake\Form\FormProtector`
#### Throws
`Cake\Core\Exception\CakeException`
### getSourceValue() public
```
getSourceValue(string $fieldname, array<string, mixed> $options = []): mixed
```
Gets a single field value from the sources available.
#### Parameters
`string` $fieldname The fieldname to fetch the value for.
`array<string, mixed>` $options optional The options containing default values.
#### Returns
`mixed`
### getTemplates() public
```
getTemplates(string|null $template = null): array|string
```
Gets templates to use or a specific template.
#### Parameters
`string|null` $template optional String for reading a specific template, null for all.
#### Returns
`array|string`
### getValueSources() public
```
getValueSources(): array<string>
```
Gets the value sources.
Returns a list, but at least one item, of valid sources, such as: `'context'`, `'data'` and `'query'`.
#### Returns
`array<string>`
### getView() public
```
getView(): Cake\View\View
```
Get the view instance this helper is bound to.
#### Returns
`Cake\View\View`
### getWidgetLocator() public
```
getWidgetLocator(): Cake\View\Widget\WidgetLocator
```
Get the widget locator currently used by the helper.
#### Returns
`Cake\View\Widget\WidgetLocator`
### hidden() public
```
hidden(string $fieldName, array<string, mixed> $options = []): string
```
Creates a hidden input field.
#### Parameters
`string` $fieldName Name of a field, in the form of "modelname.fieldname"
`array<string, mixed>` $options optional Array of HTML attributes.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#creating-hidden-inputs
### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Event listeners.
By defining one of the callback methods a helper is assumed to be interested in the related event.
Override this method if you need to add non-conventional event listeners. Or if you want helpers to listen to non-standard events.
#### Returns
`array<string, mixed>`
### initialize() public
```
initialize(array<string, mixed> $config): void
```
Constructor hook method.
Implement this method to avoid having to overwrite the constructor and call parent.
#### Parameters
`array<string, mixed>` $config The configuration settings provided to this helper.
#### Returns
`void`
### isFieldError() public
```
isFieldError(string $field): bool
```
Returns true if there is an error for the given field, otherwise false
#### Parameters
`string` $field This should be "modelname.fieldname"
#### Returns
`bool`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#displaying-and-checking-errors
### label() public
```
label(string $fieldName, string|null $text = null, array<string, mixed> $options = []): string
```
Returns a formatted LABEL element for HTML forms.
Will automatically generate a `for` attribute if one is not provided.
### Options
* `for` - Set the for attribute, if its not defined the for attribute will be generated from the $fieldName parameter using FormHelper::\_domId().
* `escape` - Set to `false` to turn off escaping of label text. Defaults to `true`.
Examples:
The text and for attribute are generated off of the fieldname
```
echo $this->Form->label('published');
<label for="PostPublished">Published</label>
```
Custom text:
```
echo $this->Form->label('published', 'Publish');
<label for="published">Publish</label>
```
Custom attributes:
```
echo $this->Form->label('published', 'Publish', [
'for' => 'post-publish'
]);
<label for="post-publish">Publish</label>
```
Nesting an input tag:
```
echo $this->Form->label('published', 'Publish', [
'for' => 'published',
'input' => $this->text('published'),
]);
<label for="post-publish">Publish <input type="text" name="published"></label>
```
If you want to nest inputs in the labels, you will need to modify the default templates.
#### Parameters
`string` $fieldName This should be "modelname.fieldname"
`string|null` $text optional Text that will appear in the label field. If $text is left undefined the text will be inflected from the fieldName.
`array<string, mixed>` $options optional An array of HTML attributes.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#creating-labels
### month() public
```
month(string $fieldName, array<string, mixed> $options = []): string
```
Generate an input tag with type "month".
### Options:
See dateTime() options.
#### Parameters
`string` $fieldName The field name.
`array<string, mixed>` $options optional Array of options or HTML attributes.
#### Returns
`string`
### multiCheckbox() public
```
multiCheckbox(string $fieldName, iterable $options, array<string, mixed> $attributes = []): string
```
Creates a set of checkboxes out of options.
### Options
* `escape` - If true contents of options will be HTML entity encoded. Defaults to true.
* `val` The selected value of the input.
* `class` - When using multiple = checkbox the class name to apply to the divs. Defaults to 'checkbox'.
* `disabled` - Control the disabled attribute. When creating checkboxes, `true` will disable all checkboxes. You can also set disabled to a list of values you want to disable when creating checkboxes.
* `hiddenField` - Set to false to remove the hidden field that ensures a value is always submitted.
* `label` - Either `false` to disable label around the widget or an array of attributes for the label tag. `selected` will be added to any classes e.g. `'class' => 'myclass'` where widget is checked
Can be used in place of a select box with the multiple attribute.
#### Parameters
`string` $fieldName Name attribute of the SELECT
`iterable` $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the checkboxes element.
`array<string, mixed>` $attributes optional The HTML attributes of the select element.
#### Returns
`string`
#### See Also
\Cake\View\Helper\FormHelper::select() for supported option formats. ### number() public @method
```
number(string $fieldName, array $options = []): string
```
Creates input of type number.
#### Parameters
`string` $fieldName `array` $options optional #### Returns
`string`
### password() public @method
```
password(string $fieldName, array $options = []): string
```
Creates input of type password.
#### Parameters
`string` $fieldName `array` $options optional #### Returns
`string`
### postButton() public
```
postButton(string $title, array|string $url, array<string, mixed> $options = []): string
```
Create a `<button>` tag with a surrounding `<form>` that submits via POST as default.
This method creates a `<form>` element. So do not use this method in an already opened form. Instead use FormHelper::submit() or FormHelper::button() to create buttons inside opened forms.
### Options:
* `data` - Array with key/value to pass in input hidden
* `method` - Request method to use. Set to 'delete' or others to simulate HTTP/1.1 DELETE (or others) request. Defaults to 'post'.
* `form` - Array with any option that FormHelper::create() can take
* Other options is the same of button method.
* `confirm` - Confirm message to show. Form execution will only continue if confirmed then.
#### Parameters
`string` $title The button's caption. Not automatically HTML encoded
`array|string` $url URL as string or array
`array<string, mixed>` $options optional Array of options and HTML attributes.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#creating-standalone-buttons-and-post-links
### postLink() public
```
postLink(string $title, array|string|null $url = null, array<string, mixed> $options = []): string
```
Creates an HTML link, but access the URL using the method you specify (defaults to POST). Requires javascript to be enabled in browser.
This method creates a `<form>` element. If you want to use this method inside of an existing form, you must use the `block` option so that the new form is being set to a view block that can be rendered outside of the main form.
If all you are looking for is a button to submit your form, then you should use `FormHelper::button()` or `FormHelper::submit()` instead.
### Options:
* `data` - Array with key/value to pass in input hidden
* `method` - Request method to use. Set to 'delete' to simulate HTTP/1.1 DELETE request. Defaults to 'post'.
* `confirm` - Confirm message to show. Form execution will only continue if confirmed then.
* `block` - Set to true to append form to view block "postLink" or provide custom block name.
* Other options are the same of HtmlHelper::link() method.
* The option `onclick` will be replaced.
#### Parameters
`string` $title The content to be wrapped by tags.
`array|string|null` $url optional Cake-relative URL or array of URL parameters, or external URL (starts with http://)
`array<string, mixed>` $options optional Array of HTML attributes.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#creating-standalone-buttons-and-post-links
### radio() public
```
radio(string $fieldName, iterable $options = [], array<string, mixed> $attributes = []): string
```
Creates a set of radio widgets.
### Attributes:
* `value` - Indicates the value when this radio button is checked.
* `label` - Either `false` to disable label around the widget or an array of attributes for the label tag. `selected` will be added to any classes e.g. `'class' => 'myclass'` where widget is checked
* `hiddenField` - boolean|string. Set to false to not include a hidden input with a value of ''. Can also be a string to set the value of the hidden input. This is useful for creating radio sets that are non-continuous.
* `disabled` - Set to `true` or `disabled` to disable all the radio buttons. Use an array of values to disable specific radio buttons.
* `empty` - Set to `true` to create an input with the value '' as the first option. When `true` the radio label will be 'empty'. Set this option to a string to control the label value.
#### Parameters
`string` $fieldName Name of a field, like this "modelname.fieldname"
`iterable` $options optional Radio button options array.
`array<string, mixed>` $attributes optional Array of attributes.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#creating-radio-buttons
### resetTemplates() public
```
resetTemplates(): void
```
Restores the default values built into FormHelper.
This method will not reset any templates set in custom widgets.
#### Returns
`void`
### search() public @method
```
search(string $fieldName, array $options = []): string
```
Creates input of type search.
#### Parameters
`string` $fieldName `array` $options optional #### Returns
`string`
### secure() public
```
secure(array $fields = [], array<string, mixed> $secureAttributes = []): string
```
Generates a hidden field with a security hash based on the fields used in the form.
If $secureAttributes is set, these HTML attributes will be merged into the hidden input tags generated for the Security Component. This is especially useful to set HTML5 attributes like 'form'.
#### Parameters
`array` $fields optional If set specifies the list of fields to be added to FormProtector for generating the hash.
`array<string, mixed>` $secureAttributes optional will be passed as HTML attributes into the hidden input elements generated for the Security Component.
#### Returns
`string`
### select() public
```
select(string $fieldName, iterable $options = [], array<string, mixed> $attributes = []): string
```
Returns a formatted SELECT element.
### Attributes:
* `multiple` - show a multiple select box. If set to 'checkbox' multiple checkboxes will be created instead.
* `empty` - If true, the empty select option is shown. If a string, that string is displayed as the empty element.
* `escape` - If true contents of options will be HTML entity encoded. Defaults to true.
* `val` The selected value of the input.
* `disabled` - Control the disabled attribute. When creating a select box, set to true to disable the select box. Set to an array to disable specific option elements.
### Using options
A simple array will create normal options:
```
$options = [1 => 'one', 2 => 'two'];
$this->Form->select('Model.field', $options));
```
While a nested options array will create optgroups with options inside them.
```
$options = [
1 => 'bill',
'fred' => [
2 => 'fred',
3 => 'fred jr.'
]
];
$this->Form->select('Model.field', $options);
```
If you have multiple options that need to have the same value attribute, you can use an array of arrays to express this:
```
$options = [
['text' => 'United states', 'value' => 'USA'],
['text' => 'USA', 'value' => 'USA'],
];
```
#### Parameters
`string` $fieldName Name attribute of the SELECT
`iterable` $options optional Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the SELECT element
`array<string, mixed>` $attributes optional The HTML attributes of the select element.
#### Returns
`string`
#### See Also
\Cake\View\Helper\FormHelper::multiCheckbox() for creating multiple checkboxes. #### Links
https://book.cakephp.org/4/en/views/helpers/form.html#creating-select-pickers
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setRequiredAndCustomValidity() protected
```
setRequiredAndCustomValidity(string $fieldName, array<string, mixed> $options): array<string, mixed>
```
Set required attribute and custom validity JS.
#### Parameters
`string` $fieldName The name of the field to generate options for.
`array<string, mixed>` $options Options list.
#### Returns
`array<string, mixed>`
### setTemplates() public
```
setTemplates(array<string> $templates): $this
```
Sets templates to use.
#### Parameters
`array<string>` $templates Templates to be added.
#### Returns
`$this`
### setValueSources() public
```
setValueSources(array<string>|string $sources): $this
```
Sets the value sources.
You need to supply one or more valid sources, as a list of strings. Order sets priority.
#### Parameters
`array<string>|string` $sources A string or a list of strings identifying a source.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
If sources list contains invalid value. #### See Also
FormHelper::$supportedValueSources for valid values. ### setWidgetLocator() public
```
setWidgetLocator(Cake\View\Widget\WidgetLocator $instance): $this
```
Set the widget locator the helper will use.
#### Parameters
`Cake\View\Widget\WidgetLocator` $instance The locator instance to set.
#### Returns
`$this`
### submit() public
```
submit(string|null $caption = null, array<string, mixed> $options = []): string
```
Creates a submit button element. This method will generate `<input />` elements that can be used to submit, and reset forms by using $options. image submits can be created by supplying an image path for $caption.
### Options
* `type` - Set to 'reset' for reset inputs. Defaults to 'submit'
* `templateVars` - Additional template variables for the input element and its container.
* Other attributes will be assigned to the input element.
#### Parameters
`string|null` $caption optional The label appearing on the button OR if string contains :// or the extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension exists, AND the first character is /, image is relative to webroot, OR if the first character is not /, image is relative to webroot/img.
`array<string, mixed>` $options optional Array of options. See above.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#creating-buttons-and-submit-elements
### templater() public
```
templater(): Cake\View\StringTemplate
```
Returns the templater instance.
#### Returns
`Cake\View\StringTemplate`
### text() public @method
```
text(string $fieldName, array $options = []): string
```
Creates input of type text.
#### Parameters
`string` $fieldName `array` $options optional #### Returns
`string`
### textarea() public
```
textarea(string $fieldName, array<string, mixed> $options = []): string
```
Creates a textarea widget.
### Options:
* `escape` - Whether the contents of the textarea should be escaped. Defaults to true.
#### Parameters
`string` $fieldName Name of a field, in the form "modelname.fieldname"
`array<string, mixed>` $options optional Array of HTML attributes, and special options above.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#creating-textareas
### time() public
```
time(string $fieldName, array<string, mixed> $options = []): string
```
Generate an input tag with type "time".
### Options:
See dateTime() options.
#### Parameters
`string` $fieldName The field name.
`array<string, mixed>` $options optional Array of options or HTML attributes.
#### Returns
`string`
### unlockField() public
```
unlockField(string $name): $this
```
Add to the list of fields that are currently unlocked.
Unlocked fields are not included in the form protection field hash.
#### Parameters
`string` $name The dot separated name for the field.
#### Returns
`$this`
### validateValueSources() protected
```
validateValueSources(array<string> $sources): void
```
Validate value sources.
#### Parameters
`array<string>` $sources A list of strings identifying a source.
#### Returns
`void`
#### Throws
`InvalidArgumentException`
If sources list contains invalid value. ### widget() public
```
widget(string $name, array $data = []): string
```
Render a named widget.
This is a lower level method. For built-in widgets, you should be using methods like `text`, `hidden`, and `radio`. If you are using additional widgets you should use this method render the widget without the label or wrapping div.
#### Parameters
`string` $name The name of the widget. e.g. 'text'.
`array` $data optional The data to render.
#### Returns
`string`
### year() public
```
year(string $fieldName, array<string, mixed> $options = []): string
```
Returns a SELECT element for years
### Attributes:
* `empty` - If true, the empty select option is shown. If a string, that string is displayed as the empty element.
* `order` - Ordering of year values in select options. Possible values 'asc', 'desc'. Default 'desc'
* `value` The selected value of the input.
* `max` The max year to appear in the select element.
* `min` The min year to appear in the select element.
#### Parameters
`string` $fieldName The field name.
`array<string, mixed>` $options optional Options & attributes for the select elements.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/form.html#creating-year-inputs
Property Detail
---------------
### $Html public @property
#### Type
`Cake\View\Helper\HtmlHelper`
### $Url public @property
#### Type
`Cake\View\Helper\UrlHelper`
### $\_View protected
The View instance this helper is attached to
#### Type
`Cake\View\View`
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_context protected
Context for the current form.
#### Type
`Cake\View\Form\ContextInterface|null`
### $\_contextFactory protected
Context factory.
#### Type
`Cake\View\Form\ContextFactory|null`
### $\_defaultConfig protected
Default config for the helper.
#### Type
`array<string, mixed>`
### $\_defaultWidgets protected
Default widgets
#### Type
`array<string, array<string>>`
### $\_groupedInputTypes protected
Grouped input types.
#### Type
`array<string>`
### $\_helperMap protected
A helper lookup table used to lazy load helper objects.
#### Type
`array<string, array>`
### $\_idPrefix protected
Prefix for id attribute.
#### Type
`string|null`
### $\_idSuffixes protected
A list of id suffixes used in the current rendering.
#### Type
`array<string>`
### $\_lastAction protected
The action attribute value of the last created form. Used to make form/request specific hashes for form tampering protection.
#### Type
`string`
### $\_locator protected
Locator for input widgets.
#### Type
`Cake\View\Widget\WidgetLocator`
### $\_templater protected
StringTemplate instance.
#### Type
`Cake\View\StringTemplate|null`
### $\_valueSources protected
The default sources.
#### Type
`array<string>`
### $formProtector protected
Form protector
#### Type
`Cake\Form\FormProtector|null`
### $helpers protected
Other helpers used by FormHelper
#### Type
`array`
### $requestType public
Defines the type of form being created. Set by FormHelper::create().
#### Type
`string|null`
### $supportedValueSources protected
The supported sources that can be used to populate input values.
`context` - Corresponds to `ContextInterface` instances. `data` - Corresponds to request data (POST/PUT). `query` - Corresponds to request's query string.
#### Type
`array<string>`
| programming_docs |
cakephp Class SprintfFormatter Class SprintfFormatter
=======================
A formatter that will interpolate variables using sprintf and select the correct plural form when required
**Namespace:** [Cake\I18n\Formatter](namespace-cake.i18n.formatter)
Method Summary
--------------
* ##### [format()](#format()) public
Returns a string with all passed variables interpolated into the original message. Variables are interpolated using the sprintf format.
Method Detail
-------------
### format() public
```
format(string $locale, string $message, array $tokenValues): string
```
Returns a string with all passed variables interpolated into the original message. Variables are interpolated using the sprintf format.
#### Parameters
`string` $locale The locale in which the message is presented.
`string` $message The message to be translated
`array` $tokenValues The list of values to interpolate in the message
#### Returns
`string`
cakephp Class RulesChecker Class RulesChecker
===================
Contains logic for storing and checking rules on entities
RulesCheckers are used by Table classes to ensure that the current entity state satisfies the application logic and business rules.
RulesCheckers afford different rules to be applied in the create and update scenario.
### Adding rules
Rules must be callable objects that return true/false depending on whether the rule has been satisfied. You can use RulesChecker::add(), RulesChecker::addCreate(), RulesChecker::addUpdate() and RulesChecker::addDelete to add rules to a checker.
### Running checks
Generally a Table object will invoke the rules objects, but you can manually invoke the checks by calling RulesChecker::checkCreate(), RulesChecker::checkUpdate() or RulesChecker::checkDelete().
**Namespace:** [Cake\Datasource](namespace-cake.datasource)
Constants
---------
* `string` **CREATE**
```
'create'
```
Indicates that the checking rules to apply are those used for creating entities
* `string` **DELETE**
```
'delete'
```
Indicates that the checking rules to apply are those used for deleting entities
* `string` **UPDATE**
```
'update'
```
Indicates that the checking rules to apply are those used for updating entities
Property Summary
----------------
* [$\_createRules](#%24_createRules) protected `arrayCake\Datasource\RuleInvoker>` The list of rules to check during create operations
* [$\_deleteRules](#%24_deleteRules) protected `arrayCake\Datasource\RuleInvoker>` The list of rules to check during delete operations
* [$\_options](#%24_options) protected `array` List of options to pass to every callable rule
* [$\_rules](#%24_rules) protected `arrayCake\Datasource\RuleInvoker>` The list of rules to be checked on both create and update operations
* [$\_updateRules](#%24_updateRules) protected `arrayCake\Datasource\RuleInvoker>` The list of rules to check during update operations
* [$\_useI18n](#%24_useI18n) protected `bool` Whether to use I18n functions for translating default error messages
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor. Takes the options to be passed to all rules.
* ##### [\_addError()](#_addError()) protected
Utility method for decorating any callable so that if it returns false, the correct property in the entity is marked as invalid.
* ##### [\_checkRules()](#_checkRules()) protected
Used by top level functions checkDelete, checkCreate and checkUpdate, this function iterates an array containing the rules to be checked and checks them all.
* ##### [add()](#add()) public
Adds a rule that will be applied to the entity both on create and update operations.
* ##### [addCreate()](#addCreate()) public
Adds a rule that will be applied to the entity on create operations.
* ##### [addDelete()](#addDelete()) public
Adds a rule that will be applied to the entity on delete operations.
* ##### [addUpdate()](#addUpdate()) public
Adds a rule that will be applied to the entity on update operations.
* ##### [check()](#check()) public
Runs each of the rules by passing the provided entity and returns true if all of them pass. The rules to be applied are depended on the $mode parameter which can only be RulesChecker::CREATE, RulesChecker::UPDATE or RulesChecker::DELETE
* ##### [checkCreate()](#checkCreate()) public
Runs each of the rules by passing the provided entity and returns true if all of them pass. The rules selected will be only those specified to be run on 'create'
* ##### [checkDelete()](#checkDelete()) public
Runs each of the rules by passing the provided entity and returns true if all of them pass. The rules selected will be only those specified to be run on 'delete'
* ##### [checkUpdate()](#checkUpdate()) public
Runs each of the rules by passing the provided entity and returns true if all of them pass. The rules selected will be only those specified to be run on 'update'
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $options = [])
```
Constructor. Takes the options to be passed to all rules.
#### Parameters
`array<string, mixed>` $options optional The options to pass to every rule
### \_addError() protected
```
_addError(callableCake\Datasource\RuleInvoker $rule, array|string|null $name = null, array<string, mixed> $options = []): Cake\Datasource\RuleInvoker
```
Utility method for decorating any callable so that if it returns false, the correct property in the entity is marked as invalid.
#### Parameters
`callableCake\Datasource\RuleInvoker` $rule The rule to decorate
`array|string|null` $name optional The alias for a rule or an array of options
`array<string, mixed>` $options optional The options containing the error message and field.
#### Returns
`Cake\Datasource\RuleInvoker`
### \_checkRules() protected
```
_checkRules(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = [], arrayCake\Datasource\RuleInvoker> $rules = []): bool
```
Used by top level functions checkDelete, checkCreate and checkUpdate, this function iterates an array containing the rules to be checked and checks them all.
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity to check for validity.
`array<string, mixed>` $options optional Extra options to pass to checker functions.
`arrayCake\Datasource\RuleInvoker>` $rules optional The list of rules that must be checked.
#### Returns
`bool`
### add() public
```
add(callable $rule, array|string|null $name = null, array<string, mixed> $options = []): $this
```
Adds a rule that will be applied to the entity both on create and 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.
#### Parameters
`callable` $rule A callable function or object that will return whether the entity is valid or not.
`array|string|null` $name optional The alias for a rule, or an array of options.
`array<string, mixed>` $options optional List of extra options to pass to the rule callable as second argument.
#### Returns
`$this`
### addCreate() public
```
addCreate(callable $rule, array|string|null $name = null, array<string, mixed> $options = []): $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.
#### Parameters
`callable` $rule A callable function or object that will return whether the entity is valid or not.
`array|string|null` $name optional The alias for a rule or an array of options.
`array<string, mixed>` $options optional List of extra options to pass to the rule callable as second argument.
#### Returns
`$this`
### addDelete() public
```
addDelete(callable $rule, array|string|null $name = null, array<string, mixed> $options = []): $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.
#### Parameters
`callable` $rule A callable function or object that will return whether the entity is valid or not.
`array|string|null` $name optional The alias for a rule, or an array of options.
`array<string, mixed>` $options optional List of extra options to pass to the rule callable as second argument.
#### Returns
`$this`
### addUpdate() public
```
addUpdate(callable $rule, array|string|null $name = null, array<string, mixed> $options = []): $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.
#### Parameters
`callable` $rule A callable function or object that will return whether the entity is valid or not.
`array|string|null` $name optional The alias for a rule, or an array of options.
`array<string, mixed>` $options optional List of extra options to pass to the rule callable as second argument.
#### Returns
`$this`
### check() public
```
check(Cake\Datasource\EntityInterface $entity, string $mode, array<string, mixed> $options = []): bool
```
Runs each of the rules by passing the provided entity and returns true if all of them pass. The rules to be applied are depended on the $mode parameter which can only be RulesChecker::CREATE, RulesChecker::UPDATE or RulesChecker::DELETE
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity to check for validity.
`string` $mode Either 'create, 'update' or 'delete'.
`array<string, mixed>` $options optional Extra options to pass to checker functions.
#### Returns
`bool`
#### Throws
`InvalidArgumentException`
if an invalid mode is passed. ### checkCreate() public
```
checkCreate(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): bool
```
Runs each of the rules by passing the provided entity and returns true if all of them pass. The rules selected will be only those specified to be run on 'create'
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity to check for validity.
`array<string, mixed>` $options optional Extra options to pass to checker functions.
#### Returns
`bool`
### checkDelete() public
```
checkDelete(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): bool
```
Runs each of the rules by passing the provided entity and returns true if all of them pass. The rules selected will be only those specified to be run on 'delete'
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity to check for validity.
`array<string, mixed>` $options optional Extra options to pass to checker functions.
#### Returns
`bool`
### checkUpdate() public
```
checkUpdate(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): bool
```
Runs each of the rules by passing the provided entity and returns true if all of them pass. The rules selected will be only those specified to be run on 'update'
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity to check for validity.
`array<string, mixed>` $options optional Extra options to pass to checker functions.
#### Returns
`bool`
Property Detail
---------------
### $\_createRules protected
The list of rules to check during create operations
#### Type
`arrayCake\Datasource\RuleInvoker>`
### $\_deleteRules protected
The list of rules to check during delete operations
#### Type
`arrayCake\Datasource\RuleInvoker>`
### $\_options protected
List of options to pass to every callable rule
#### Type
`array`
### $\_rules protected
The list of rules to be checked on both create and update operations
#### Type
`arrayCake\Datasource\RuleInvoker>`
### $\_updateRules protected
The list of rules to check during update operations
#### Type
`arrayCake\Datasource\RuleInvoker>`
### $\_useI18n protected
Whether to use I18n functions for translating default error messages
#### Type
`bool`
cakephp Class PhpError Class PhpError
===============
Object wrapper around PHP errors that are emitted by `trigger_error()`
**Namespace:** [Cake\Error](namespace-cake.error)
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getCode()](#getCode()) public
Get the PHP error constant.
* ##### [getFile()](#getFile()) public
Get the error file
* ##### [getLabel()](#getLabel()) public
Get the error code label
* ##### [getLine()](#getLine()) public
Get the error line number.
* ##### [getLogLevel()](#getLogLevel()) public
Get the mapped LOG\_ constant.
* ##### [getMessage()](#getMessage()) public
Get the error message.
* ##### [getTrace()](#getTrace()) public
Get the stacktrace as an array.
* ##### [getTraceAsString()](#getTraceAsString()) public
Get the stacktrace as a string.
Method Detail
-------------
### \_\_construct() public
```
__construct(int $code, string $message, string|null $file = null, int|null $line = null, array $trace = [])
```
Constructor
#### Parameters
`int` $code The PHP error code constant
`string` $message The error message.
`string|null` $file optional The filename of the error.
`int|null` $line optional The line number for the error.
`array` $trace optional The backtrace for the error.
### getCode() public
```
getCode(): int
```
Get the PHP error constant.
#### Returns
`int`
### getFile() public
```
getFile(): string|null
```
Get the error file
#### Returns
`string|null`
### getLabel() public
```
getLabel(): string
```
Get the error code label
#### Returns
`string`
### getLine() public
```
getLine(): int|null
```
Get the error line number.
#### Returns
`int|null`
### getLogLevel() public
```
getLogLevel(): int
```
Get the mapped LOG\_ constant.
#### Returns
`int`
### getMessage() public
```
getMessage(): string
```
Get the error message.
#### Returns
`string`
### getTrace() public
```
getTrace(): array
```
Get the stacktrace as an array.
#### Returns
`array`
### getTraceAsString() public
```
getTraceAsString(): string
```
Get the stacktrace as a string.
#### Returns
`string`
cakephp Class MessagesFileLoader Class MessagesFileLoader
=========================
A generic translations package factory that will load translations files based on the file extension and the package name.
This class is a callable, so it can be used as a package loader argument.
**Namespace:** [Cake\I18n](namespace-cake.i18n)
Property Summary
----------------
* [$\_extension](#%24_extension) protected `string` The extension name.
* [$\_locale](#%24_locale) protected `string` The locale to load for the given package.
* [$\_name](#%24_name) protected `string` The package (domain) name.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Creates a translation file loader. The file to be loaded corresponds to the following rules:
* ##### [\_\_invoke()](#__invoke()) public
Loads the translation file and parses it. Returns an instance of a translations package containing the messages loaded from the file.
* ##### [translationsFolders()](#translationsFolders()) public
Returns the folders where the file should be looked for according to the locale and package name.
Method Detail
-------------
### \_\_construct() public
```
__construct(string $name, string $locale, string $extension = 'po')
```
Creates a translation file loader. The file to be loaded corresponds to the following rules:
* The locale is a folder under the `Locale` directory, a fallback will be used if the folder is not found.
* The $name corresponds to the file name to load
* If there is a loaded plugin with the underscored version of $name, the translation file will be loaded from such plugin.
### Examples:
Load and parse resources/locales/fr/validation.po
```
$loader = new MessagesFileLoader('validation', 'fr_FR', 'po');
$package = $loader();
```
Load and parse resources/locales/fr\_FR/validation.mo
```
$loader = new MessagesFileLoader('validation', 'fr_FR', 'mo');
$package = $loader();
```
Load the plugins/MyPlugin/resources/locales/fr/my\_plugin.po file:
```
$loader = new MessagesFileLoader('my_plugin', 'fr_FR', 'mo');
$package = $loader();
```
#### Parameters
`string` $name The name (domain) of the translations package.
`string` $locale The locale to load, this will be mapped to a folder in the system.
`string` $extension optional The file extension to use. This will also be mapped to a messages parser class.
### \_\_invoke() public
```
__invoke(): Cake\I18n\Package|false
```
Loads the translation file and parses it. Returns an instance of a translations package containing the messages loaded from the file.
#### Returns
`Cake\I18n\Package|false`
#### Throws
`RuntimeException`
if no file parser class could be found for the specified file extension. ### translationsFolders() public
```
translationsFolders(): array<string>
```
Returns the folders where the file should be looked for according to the locale and package name.
#### Returns
`array<string>`
Property Detail
---------------
### $\_extension protected
The extension name.
#### Type
`string`
### $\_locale protected
The locale to load for the given package.
#### Type
`string`
### $\_name protected
The package (domain) name.
#### Type
`string`
cakephp Class SqliteSchemaDialect Class SqliteSchemaDialect
==========================
Schema management/reflection features for Sqlite
**Namespace:** [Cake\Database\Schema](namespace-cake.database.schema)
Property Summary
----------------
* [$\_constraintsIdMap](#%24_constraintsIdMap) protected `array<string, mixed>` Array containing the foreign keys constraints names Necessary for composite foreign keys to be handled
* [$\_driver](#%24_driver) protected `Cake\Database\DriverInterface` The driver instance being used.
* [$\_hasSequences](#%24_hasSequences) protected `bool` Whether there is any table in this connection to SQLite containing sequences.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_applyTypeSpecificColumnConversion()](#_applyTypeSpecificColumnConversion()) protected
Tries to use a matching database type to convert a SQL column definition to an abstract type definition.
* ##### [\_convertColumn()](#_convertColumn()) protected
Convert a column definition to the abstract types.
* ##### [\_convertConstraintColumns()](#_convertConstraintColumns()) protected
Convert foreign key constraints references to a valid stringified list
* ##### [\_convertOnClause()](#_convertOnClause()) protected
Convert string on clauses to the abstract ones.
* ##### [\_defaultValue()](#_defaultValue()) protected
Manipulate the default value.
* ##### [\_foreignOnClause()](#_foreignOnClause()) protected
Generate an ON clause for a foreign key.
* ##### [\_getTypeSpecificColumnSql()](#_getTypeSpecificColumnSql()) protected
Tries to use a matching database type to generate the SQL fragment for a single column in a table.
* ##### [addConstraintSql()](#addConstraintSql()) public
Generate the SQL queries needed to add foreign key constraints to the table
* ##### [columnSql()](#columnSql()) public
Generate the SQL fragment for a single column in a table.
* ##### [constraintSql()](#constraintSql()) public
Generate the SQL fragments for defining table constraints.
* ##### [convertColumnDescription()](#convertColumnDescription()) public
Convert field description results into abstract schema fields.
* ##### [convertForeignKeyDescription()](#convertForeignKeyDescription()) public
Convert a foreign key description into constraints on the Table object.
* ##### [convertIndexDescription()](#convertIndexDescription()) public
Convert an index description results into abstract schema indexes or constraints.
* ##### [convertOptionsDescription()](#convertOptionsDescription()) public
Convert options data into table options.
* ##### [createTableSql()](#createTableSql()) public
Generate the SQL to create a table.
* ##### [describeColumnSql()](#describeColumnSql()) public
Generate the SQL to describe a table.
* ##### [describeForeignKeySql()](#describeForeignKeySql()) public
Generate the SQL to describe the foreign keys in a table.
* ##### [describeIndexSql()](#describeIndexSql()) public
Generate the SQL to describe the indexes in a table.
* ##### [describeOptionsSql()](#describeOptionsSql()) public
Generate the SQL to describe table options
* ##### [dropConstraintSql()](#dropConstraintSql()) public
Generate the SQL queries needed to drop foreign key constraints from the table
* ##### [dropTableSql()](#dropTableSql()) public
Generate the SQL to drop a table.
* ##### [hasSequences()](#hasSequences()) public
Returns whether there is any table in this connection to SQLite containing sequences
* ##### [indexSql()](#indexSql()) public
Generate the SQL fragment for a single index in a table.
* ##### [listTablesSql()](#listTablesSql()) public
Generate the SQL to list the tables and views.
* ##### [listTablesWithoutViewsSql()](#listTablesWithoutViewsSql()) public
Generate the SQL to list the tables, excluding all views.
* ##### [truncateTableSql()](#truncateTableSql()) public
Generate the SQL to truncate a table.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Database\DriverInterface $driver)
```
Constructor
This constructor will connect the driver so that methods like columnSql() and others will fail when the driver has not been connected.
#### Parameters
`Cake\Database\DriverInterface` $driver The driver to use.
### \_applyTypeSpecificColumnConversion() protected
```
_applyTypeSpecificColumnConversion(string $columnType, array $definition): array|null
```
Tries to use a matching database type to convert a SQL column definition to an abstract type definition.
#### Parameters
`string` $columnType The column type.
`array` $definition The column definition.
#### Returns
`array|null`
### \_convertColumn() protected
```
_convertColumn(string $column): array<string, mixed>
```
Convert a column definition to the abstract types.
The returned type will be a type that Cake\Database\TypeFactory can handle.
#### Parameters
`string` $column The column type + length
#### Returns
`array<string, mixed>`
#### Throws
`Cake\Database\Exception\DatabaseException`
when unable to parse column type ### \_convertConstraintColumns() protected
```
_convertConstraintColumns(array<string>|string $references): string
```
Convert foreign key constraints references to a valid stringified list
#### Parameters
`array<string>|string` $references The referenced columns of a foreign key constraint statement
#### Returns
`string`
### \_convertOnClause() protected
```
_convertOnClause(string $clause): string
```
Convert string on clauses to the abstract ones.
#### Parameters
`string` $clause The on clause to convert.
#### Returns
`string`
### \_defaultValue() protected
```
_defaultValue(string|int|null $default): string|int|null
```
Manipulate the default value.
Sqlite includes quotes and bared NULLs in default values. We need to remove those.
#### Parameters
`string|int|null` $default The default value.
#### Returns
`string|int|null`
### \_foreignOnClause() protected
```
_foreignOnClause(string $on): string
```
Generate an ON clause for a foreign key.
#### Parameters
`string` $on The on clause
#### Returns
`string`
### \_getTypeSpecificColumnSql() protected
```
_getTypeSpecificColumnSql(string $columnType, Cake\Database\Schema\TableSchemaInterface $schema, string $column): string|null
```
Tries to use a matching database type to generate the SQL fragment for a single column in a table.
#### Parameters
`string` $columnType The column type.
`Cake\Database\Schema\TableSchemaInterface` $schema The table schema instance the column is in.
`string` $column The name of the column.
#### Returns
`string|null`
### addConstraintSql() public
```
addConstraintSql(Cake\Database\Schema\TableSchema $schema): array
```
Generate the SQL queries needed to add foreign key constraints to the table
SQLite can not properly handle adding a constraint to an existing table. This method is no-op
#### Parameters
`Cake\Database\Schema\TableSchema` $schema The table instance the foreign key constraints are.
#### Returns
`array`
### columnSql() public
```
columnSql(Cake\Database\Schema\TableSchema $schema, string $name): string
```
Generate the SQL fragment for a single column in a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema The table instance the column is in.
`string` $name The name of the column.
#### Returns
`string`
#### Throws
`Cake\Database\Exception\DatabaseException`
when the column type is unknown ### constraintSql() public
```
constraintSql(Cake\Database\Schema\TableSchema $schema, string $name): string
```
Generate the SQL fragments for defining table constraints.
Note integer primary keys will return ''. This is intentional as Sqlite requires that integer primary keys be defined in the column definition.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema The table instance the column is in.
`string` $name The name of the column.
#### Returns
`string`
### convertColumnDescription() public
```
convertColumnDescription(Cake\Database\Schema\TableSchema $schema, array $row): void
```
Convert field description results into abstract schema fields.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `array` $row #### Returns
`void`
### convertForeignKeyDescription() public
```
convertForeignKeyDescription(Cake\Database\Schema\TableSchema $schema, array $row): void
```
Convert a foreign key description into constraints on the Table object.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `array` $row #### Returns
`void`
### convertIndexDescription() public
```
convertIndexDescription(Cake\Database\Schema\TableSchema $schema, array $row): void
```
Convert an index description results into abstract schema indexes or constraints.
Since SQLite does not have a way to get metadata about all indexes at once, additional queries are done here. Sqlite constraint names are not stable, and the names for constraints will not match those used to create the table. This is a limitation in Sqlite's metadata features.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema The table object to append an index or constraint to.
`array` $row The row data from `describeIndexSql`.
#### Returns
`void`
### convertOptionsDescription() public
```
convertOptionsDescription(Cake\Database\Schema\TableSchema $schema, array $row): void
```
Convert options data into table options.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema Table instance.
`array` $row The row of data.
#### Returns
`void`
### createTableSql() public
```
createTableSql(Cake\Database\Schema\TableSchema $schema, array<string> $columns, array<string> $constraints, array<string> $indexes): array<string>
```
Generate the SQL to create a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `array<string>` $columns `array<string>` $constraints `array<string>` $indexes #### Returns
`array<string>`
### describeColumnSql() public
```
describeColumnSql(string $tableName, array<string, mixed> $config): array
```
Generate the SQL to describe a table.
#### Parameters
`string` $tableName `array<string, mixed>` $config #### Returns
`array`
### describeForeignKeySql() public
```
describeForeignKeySql(string $tableName, array<string, mixed> $config): array
```
Generate the SQL to describe the foreign keys in a table.
#### Parameters
`string` $tableName `array<string, mixed>` $config #### Returns
`array`
### describeIndexSql() public
```
describeIndexSql(string $tableName, array<string, mixed> $config): array
```
Generate the SQL to describe the indexes in a table.
#### Parameters
`string` $tableName `array<string, mixed>` $config #### Returns
`array`
### describeOptionsSql() public
```
describeOptionsSql(string $tableName, array<string, mixed> $config): array
```
Generate the SQL to describe table options
#### Parameters
`string` $tableName Table name.
`array<string, mixed>` $config The connection configuration.
#### Returns
`array`
### dropConstraintSql() public
```
dropConstraintSql(Cake\Database\Schema\TableSchema $schema): array
```
Generate the SQL queries needed to drop foreign key constraints from the table
SQLite can not properly handle dropping a constraint to an existing table. This method is no-op
#### Parameters
`Cake\Database\Schema\TableSchema` $schema The table instance the foreign key constraints are.
#### Returns
`array`
### dropTableSql() public
```
dropTableSql(Cake\Database\Schema\TableSchema $schema): array
```
Generate the SQL to drop a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema Schema instance
#### Returns
`array`
### hasSequences() public
```
hasSequences(): bool
```
Returns whether there is any table in this connection to SQLite containing sequences
#### Returns
`bool`
### indexSql() public
```
indexSql(Cake\Database\Schema\TableSchema $schema, string $name): string
```
Generate the SQL fragment for a single index in a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `string` $name #### Returns
`string`
### listTablesSql() public
```
listTablesSql(array<string, mixed> $config): array
```
Generate the SQL to list the tables and views.
#### Parameters
`array<string, mixed>` $config The connection configuration to use for getting tables from.
#### Returns
`array`
### listTablesWithoutViewsSql() public
```
listTablesWithoutViewsSql(array<string, mixed> $config): array<mixed>
```
Generate the SQL to list the tables, excluding all views.
#### Parameters
`array<string, mixed>` $config The connection configuration to use for getting tables from.
#### Returns
`array<mixed>`
### truncateTableSql() public
```
truncateTableSql(Cake\Database\Schema\TableSchema $schema): array
```
Generate the SQL to truncate a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema #### Returns
`array`
Property Detail
---------------
### $\_constraintsIdMap protected
Array containing the foreign keys constraints names Necessary for composite foreign keys to be handled
#### Type
`array<string, mixed>`
### $\_driver protected
The driver instance being used.
#### Type
`Cake\Database\DriverInterface`
### $\_hasSequences protected
Whether there is any table in this connection to SQLite containing sequences.
#### Type
`bool`
| programming_docs |
cakephp Class DecimalType Class DecimalType
==================
Decimal type converter.
Use to convert decimal data between PHP and the database types.
**Namespace:** [Cake\Database\Type](namespace-cake.database.type)
Property Summary
----------------
* [$\_name](#%24_name) protected `string|null` Identifier name for this type
* [$\_useLocaleParser](#%24_useLocaleParser) protected `bool` Whether numbers should be parsed using a locale aware parser when marshalling string inputs.
* [$numberClass](#%24numberClass) public static `string` The class to use for representing number objects
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_parseValue()](#_parseValue()) protected
Converts localized string into a decimal string after parsing it using the locale aware parser.
* ##### [getBaseType()](#getBaseType()) public
Returns the base type name that this class is inheriting.
* ##### [getName()](#getName()) public
Returns type identifier name for this object.
* ##### [manyToPHP()](#manyToPHP()) public
Returns an array of the values converted to the PHP representation of this type.
* ##### [marshal()](#marshal()) public
Marshalls request data into decimal strings.
* ##### [newId()](#newId()) public
Generate a new primary key value for a given type.
* ##### [toDatabase()](#toDatabase()) public
Convert decimal strings into the database format.
* ##### [toPHP()](#toPHP()) public
Casts given value from a database type to a PHP equivalent.
* ##### [toStatement()](#toStatement()) public
Get the correct PDO binding type for decimal data.
* ##### [useLocaleParser()](#useLocaleParser()) public
Sets whether to parse numbers passed to the marshal() function by using a locale aware parser.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $name = null)
```
Constructor
#### Parameters
`string|null` $name optional The name identifying this type
### \_parseValue() protected
```
_parseValue(string $value): string
```
Converts localized string into a decimal string after parsing it using the locale aware parser.
#### Parameters
`string` $value The value to parse and convert to an float.
#### Returns
`string`
### getBaseType() public
```
getBaseType(): string|null
```
Returns the base type name that this class is inheriting.
This is useful when extending base type for adding extra functionality, but still want the rest of the framework to use the same assumptions it would do about the base type it inherits from.
#### Returns
`string|null`
### getName() public
```
getName(): string|null
```
Returns type identifier name for this object.
#### Returns
`string|null`
### manyToPHP() public
```
manyToPHP(array $values, array<string> $fields, Cake\Database\DriverInterface $driver): array<string, mixed>
```
Returns an array of the values converted to the PHP representation of this type.
#### Parameters
`array` $values `array<string>` $fields `Cake\Database\DriverInterface` $driver #### Returns
`array<string, mixed>`
### marshal() public
```
marshal(mixed $value): string|null
```
Marshalls request data into decimal strings.
Most useful for converting request data into PHP objects, that make sense for the rest of the ORM/Database layers.
#### Parameters
`mixed` $value The value to convert.
#### Returns
`string|null`
### newId() public
```
newId(): mixed
```
Generate a new primary key value for a given type.
This method can be used by types to create new primary key values when entities are inserted.
#### Returns
`mixed`
### toDatabase() public
```
toDatabase(mixed $value, Cake\Database\DriverInterface $driver): string|float|int|null
```
Convert decimal strings into the database format.
#### Parameters
`mixed` $value The value to convert.
`Cake\Database\DriverInterface` $driver The driver instance to convert with.
#### Returns
`string|float|int|null`
#### Throws
`InvalidArgumentException`
### toPHP() public
```
toPHP(mixed $value, Cake\Database\DriverInterface $driver): string|null
```
Casts given value from a database type to a PHP equivalent.
#### Parameters
`mixed` $value The value to convert.
`Cake\Database\DriverInterface` $driver The driver instance to convert with.
#### Returns
`string|null`
### toStatement() public
```
toStatement(mixed $value, Cake\Database\DriverInterface $driver): int
```
Get the correct PDO binding type for decimal data.
#### Parameters
`mixed` $value The value being bound.
`Cake\Database\DriverInterface` $driver The driver.
#### Returns
`int`
### useLocaleParser() public
```
useLocaleParser(bool $enable = true): $this
```
Sets whether to parse numbers passed to the marshal() function by using a locale aware parser.
#### Parameters
`bool` $enable optional Whether to enable
#### Returns
`$this`
#### Throws
`RuntimeException`
Property Detail
---------------
### $\_name protected
Identifier name for this type
#### Type
`string|null`
### $\_useLocaleParser protected
Whether numbers should be parsed using a locale aware parser when marshalling string inputs.
#### Type
`bool`
### $numberClass public static
The class to use for representing number objects
#### Type
`string`
cakephp Class Folder Class Folder
=============
Folder structure browser, lists folders and files. Provides an Object interface for Common directory related tasks.
**Namespace:** [Cake\Filesystem](namespace-cake.filesystem)
**Deprecated:** 4.0.0 Will be removed in 5.0.
**Link:** https://book.cakephp.org/4/en/core-libraries/file-folder.html#folder-api
Constants
---------
* `string` **MERGE**
```
'merge'
```
Default scheme for Folder::copy Recursively merges subfolders with the same name
* `string` **OVERWRITE**
```
'overwrite'
```
Overwrite scheme for Folder::copy subfolders with the same name will be replaced
* `string` **SKIP**
```
'skip'
```
Skip scheme for Folder::copy if a subfolder with the same name exists it will be skipped
* `string` **SORT\_NAME**
```
'name'
```
Sort mode by name
* `string` **SORT\_TIME**
```
'time'
```
Sort mode by time
Property Summary
----------------
* [$\_directories](#%24_directories) protected `array` Holds array of complete directory paths.
* [$\_errors](#%24_errors) protected `array` Holds errors from last method.
* [$\_files](#%24_files) protected `array` Holds array of complete file paths.
* [$\_fsorts](#%24_fsorts) protected `array<string>` Functions array to be called depending on the sort type chosen.
* [$\_messages](#%24_messages) protected `array` Holds messages from last method.
* [$mode](#%24mode) public `int` Mode to be used on create. Does nothing on windows platforms.
* [$path](#%24path) public `string` Path to Folder.
* [$sort](#%24sort) public `bool` Sortedness. Whether list results should be sorted by name.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_findRecursive()](#_findRecursive()) protected
Private helper function for findRecursive.
* ##### [addPathElement()](#addPathElement()) public static
Returns $path with $element added, with correct slash in-between.
* ##### [cd()](#cd()) public
Change directory to $path.
* ##### [chmod()](#chmod()) public
Change the mode on a directory structure recursively. This includes changing the mode on files as well.
* ##### [copy()](#copy()) public
Recursive directory copy.
* ##### [correctSlashFor()](#correctSlashFor()) public static
Returns a correct set of slashes for given $path. (\ for Windows paths and / for other paths.)
* ##### [create()](#create()) public
Create a directory structure recursively.
* ##### [delete()](#delete()) public
Recursively Remove directories if the system allows.
* ##### [dirsize()](#dirsize()) public
Returns the size in bytes of this Folder and its contents.
* ##### [errors()](#errors()) public
get error from latest method
* ##### [find()](#find()) public
Returns an array of all matching files in current directory.
* ##### [findRecursive()](#findRecursive()) public
Returns an array of all matching files in and below current directory.
* ##### [inPath()](#inPath()) public
Returns true if the Folder is in the given path.
* ##### [isAbsolute()](#isAbsolute()) public static
Returns true if given $path is an absolute path.
* ##### [isRegisteredStreamWrapper()](#isRegisteredStreamWrapper()) public static
Returns true if given $path is a registered stream wrapper.
* ##### [isSlashTerm()](#isSlashTerm()) public static
Returns true if given $path ends in a slash (i.e. is slash-terminated).
* ##### [isWindowsPath()](#isWindowsPath()) public static
Returns true if given $path is a Windows path.
* ##### [messages()](#messages()) public
get messages from latest method
* ##### [move()](#move()) public
Recursive directory move.
* ##### [normalizeFullPath()](#normalizeFullPath()) public static
Returns a correct set of slashes for given $path. (\ for Windows paths and / for other paths.)
* ##### [pwd()](#pwd()) public
Return current path.
* ##### [read()](#read()) public
Returns an array of the contents of the current directory. The returned array holds two arrays: One of directories and one of files.
* ##### [realpath()](#realpath()) public
Get the real path (taking ".." and such into account)
* ##### [slashTerm()](#slashTerm()) public static
Returns $path with added terminating slash (corrected for Windows or other OS).
* ##### [subdirectories()](#subdirectories()) public
Returns an array of subdirectories for the provided or current path.
* ##### [tree()](#tree()) public
Returns an array of nested directories and files in each directory
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $path = null, bool $create = false, int|null $mode = null)
```
Constructor.
#### Parameters
`string|null` $path optional Path to folder
`bool` $create optional Create folder if not found
`int|null` $mode optional Mode (CHMOD) to apply to created folder, false to ignore
### \_findRecursive() protected
```
_findRecursive(string $pattern, bool $sort = false): array
```
Private helper function for findRecursive.
#### Parameters
`string` $pattern Pattern to match against
`bool` $sort optional Whether results should be sorted.
#### Returns
`array`
### addPathElement() public static
```
addPathElement(string $path, array<string>|string $element): string
```
Returns $path with $element added, with correct slash in-between.
#### Parameters
`string` $path Path
`array<string>|string` $element Element to add at end of path
#### Returns
`string`
### cd() public
```
cd(string $path): string|false
```
Change directory to $path.
#### Parameters
`string` $path Path to the directory to change to
#### Returns
`string|false`
### chmod() public
```
chmod(string $path, int|null $mode = null, bool $recursive = true, array<string> $exceptions = []): bool
```
Change the mode on a directory structure recursively. This includes changing the mode on files as well.
#### Parameters
`string` $path The path to chmod.
`int|null` $mode optional Octal value, e.g. 0755.
`bool` $recursive optional Chmod recursively, set to false to only change the current directory.
`array<string>` $exceptions optional Array of files, directories to skip.
#### Returns
`bool`
### copy() public
```
copy(string $to, array<string, mixed> $options = []): bool
```
Recursive directory copy.
### Options
* `from` The directory to copy from, this will cause a cd() to occur, changing the results of pwd().
* `mode` The mode to copy the files/directories with as integer, e.g. 0775.
* `skip` Files/directories to skip.
* `scheme` Folder::MERGE, Folder::OVERWRITE, Folder::SKIP
* `recursive` Whether to copy recursively or not (default: true - recursive)
#### Parameters
`string` $to The directory to copy to.
`array<string, mixed>` $options optional Array of options (see above).
#### Returns
`bool`
### correctSlashFor() public static
```
correctSlashFor(string $path): string
```
Returns a correct set of slashes for given $path. (\ for Windows paths and / for other paths.)
#### Parameters
`string` $path Path to check
#### Returns
`string`
### create() public
```
create(string $pathname, int|null $mode = null): bool
```
Create a directory structure recursively.
Can be used to create deep path structures like `/foo/bar/baz/shoe/horn`
#### Parameters
`string` $pathname The directory structure to create. Either an absolute or relative path. If the path is relative and exists in the process' cwd it will not be created. Otherwise, relative paths will be prefixed with the current pwd().
`int|null` $mode optional octal value 0755
#### Returns
`bool`
### delete() public
```
delete(string|null $path = null): bool
```
Recursively Remove directories if the system allows.
#### Parameters
`string|null` $path optional Path of directory to delete
#### Returns
`bool`
### dirsize() public
```
dirsize(): int
```
Returns the size in bytes of this Folder and its contents.
#### Returns
`int`
### errors() public
```
errors(bool $reset = true): array
```
get error from latest method
#### Parameters
`bool` $reset optional Reset error stack after reading
#### Returns
`array`
### find() public
```
find(string $regexpPattern = '.*', string|bool $sort = false): array<string>
```
Returns an array of all matching files in current directory.
#### Parameters
`string` $regexpPattern optional Preg\_match pattern (Defaults to: .\*)
`string|bool` $sort optional Whether results should be sorted.
#### Returns
`array<string>`
### findRecursive() public
```
findRecursive(string $pattern = '.*', string|bool $sort = false): array
```
Returns an array of all matching files in and below current directory.
#### Parameters
`string` $pattern optional Preg\_match pattern (Defaults to: .\*)
`string|bool` $sort optional Whether results should be sorted.
#### Returns
`array`
### inPath() public
```
inPath(string $path, bool $reverse = false): bool
```
Returns true if the Folder is in the given path.
#### Parameters
`string` $path The absolute path to check that the current `pwd()` resides within.
`bool` $reverse optional Reverse the search, check if the given `$path` resides within the current `pwd()`.
#### Returns
`bool`
#### Throws
`InvalidArgumentException`
When the given `$path` argument is not an absolute path. ### isAbsolute() public static
```
isAbsolute(string $path): bool
```
Returns true if given $path is an absolute path.
#### Parameters
`string` $path Path to check
#### Returns
`bool`
### isRegisteredStreamWrapper() public static
```
isRegisteredStreamWrapper(string $path): bool
```
Returns true if given $path is a registered stream wrapper.
#### Parameters
`string` $path Path to check
#### Returns
`bool`
### isSlashTerm() public static
```
isSlashTerm(string $path): bool
```
Returns true if given $path ends in a slash (i.e. is slash-terminated).
#### Parameters
`string` $path Path to check
#### Returns
`bool`
### isWindowsPath() public static
```
isWindowsPath(string $path): bool
```
Returns true if given $path is a Windows path.
#### Parameters
`string` $path Path to check
#### Returns
`bool`
### messages() public
```
messages(bool $reset = true): array
```
get messages from latest method
#### Parameters
`bool` $reset optional Reset message stack after reading
#### Returns
`array`
### move() public
```
move(string $to, array<string, mixed> $options = []): bool
```
Recursive directory move.
### Options
* `from` The directory to copy from, this will cause a cd() to occur, changing the results of pwd().
* `mode` The mode to copy the files/directories with as integer, e.g. 0775.
* `skip` Files/directories to skip.
* `scheme` Folder::MERGE, Folder::OVERWRITE, Folder::SKIP
* `recursive` Whether to copy recursively or not (default: true - recursive)
#### Parameters
`string` $to The directory to move to.
`array<string, mixed>` $options optional Array of options (see above).
#### Returns
`bool`
### normalizeFullPath() public static
```
normalizeFullPath(string $path): string
```
Returns a correct set of slashes for given $path. (\ for Windows paths and / for other paths.)
#### Parameters
`string` $path Path to transform
#### Returns
`string`
### pwd() public
```
pwd(): string|null
```
Return current path.
#### Returns
`string|null`
### read() public
```
read(string|bool $sort = self::SORT_NAME, array|bool $exceptions = false, bool $fullPath = false): array
```
Returns an array of the contents of the current directory. The returned array holds two arrays: One of directories and one of files.
#### Parameters
`string|bool` $sort optional Whether you want the results sorted, set this and the sort property to false to get unsorted results.
`array|bool` $exceptions optional Either an array or boolean true will not grab dot files
`bool` $fullPath optional True returns the full path
#### Returns
`array`
### realpath() public
```
realpath(string $path): string|false
```
Get the real path (taking ".." and such into account)
#### Parameters
`string` $path Path to resolve
#### Returns
`string|false`
### slashTerm() public static
```
slashTerm(string $path): string
```
Returns $path with added terminating slash (corrected for Windows or other OS).
#### Parameters
`string` $path Path to check
#### Returns
`string`
### subdirectories() public
```
subdirectories(string|null $path = null, bool $fullPath = true): array
```
Returns an array of subdirectories for the provided or current path.
#### Parameters
`string|null` $path optional The directory path to get subdirectories for.
`bool` $fullPath optional Whether to return the full path or only the directory name.
#### Returns
`array`
### tree() public
```
tree(string|null $path = null, array|bool $exceptions = false, string|null $type = null): array
```
Returns an array of nested directories and files in each directory
#### Parameters
`string|null` $path optional the directory path to build the tree from
`array|bool` $exceptions optional Either an array of files/folder to exclude or boolean true to not grab dot files/folders
`string|null` $type optional either 'file' or 'dir'. Null returns both files and directories
#### Returns
`array`
Property Detail
---------------
### $\_directories protected
Holds array of complete directory paths.
#### Type
`array`
### $\_errors protected
Holds errors from last method.
#### Type
`array`
### $\_files protected
Holds array of complete file paths.
#### Type
`array`
### $\_fsorts protected
Functions array to be called depending on the sort type chosen.
#### Type
`array<string>`
### $\_messages protected
Holds messages from last method.
#### Type
`array`
### $mode public
Mode to be used on create. Does nothing on windows platforms.
#### Type
`int`
### $path public
Path to Folder.
#### Type
`string`
### $sort public
Sortedness. Whether list results should be sorted by name.
#### Type
`bool`
| programming_docs |
cakephp Class NoMailSent Class NoMailSent
=================
NoMailSent
**Namespace:** [Cake\TestSuite\Constraint\Email](namespace-cake.testsuite.constraint.email)
Property Summary
----------------
* [$at](#%24at) protected `int|null`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Overwrites the descriptions so we can remove the automatic "expected" message
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [getMessages()](#getMessages()) public
Gets the email or emails to check
* ##### [matches()](#matches()) public
Checks constraint
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message string
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(int|null $at = null): void
```
Constructor
#### Parameters
`int|null` $at optional At
#### Returns
`void`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Overwrites the descriptions so we can remove the automatic "expected" message
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other Value
#### Returns
`string`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### getMessages() public
```
getMessages(): arrayCake\Mailer\Message>
```
Gets the email or emails to check
#### Returns
`arrayCake\Mailer\Message>`
### matches() public
```
matches(mixed $other): bool
```
Checks constraint
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Constraint check
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message string
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $at protected
#### Type
`int|null`
cakephp Namespace Locator Namespace Locator
=================
### Interfaces
* ##### [LocatorInterface](interface-cake.datasource.locator.locatorinterface)
Registries for repository objects should implement this interface.
### Classes
* ##### [AbstractLocator](class-cake.datasource.locator.abstractlocator)
Provides an abstract registry/factory for repository objects.
cakephp Namespace Http Namespace Http
==============
### Namespaces
* [Cake\Http\Client](namespace-cake.http.client)
* [Cake\Http\Cookie](namespace-cake.http.cookie)
* [Cake\Http\Exception](namespace-cake.http.exception)
* [Cake\Http\Middleware](namespace-cake.http.middleware)
* [Cake\Http\Session](namespace-cake.http.session)
* [Cake\Http\TestSuite](namespace-cake.http.testsuite)
### Interfaces
* ##### [ControllerFactoryInterface](interface-cake.http.controllerfactoryinterface)
Factory method for building controllers from request/response pairs.
### Classes
* ##### [BaseApplication](class-cake.http.baseapplication)
Base class for full-stack applications
* ##### [CallbackStream](class-cake.http.callbackstream)
Implementation of PSR HTTP streams.
* ##### [Client](class-cake.http.client)
The end user interface for doing HTTP requests.
* ##### [ContentTypeNegotiation](class-cake.http.contenttypenegotiation)
Negotiates the prefered content type from what the application provides and what the request has in its Accept header.
* ##### [CorsBuilder](class-cake.http.corsbuilder)
A builder object that assists in defining Cross Origin Request related headers.
* ##### [FlashMessage](class-cake.http.flashmessage)
The FlashMessage class provides a way for you to write a flash variable to the session, to be rendered in a view with the FlashHelper.
* ##### [MiddlewareApplication](class-cake.http.middlewareapplication)
Base class for standalone HTTP applications
* ##### [MiddlewareQueue](class-cake.http.middlewarequeue)
Provides methods for creating and manipulating a "queue" of middlewares. This queue is used to process a request and generate response via \Cake\Http\Runner.
* ##### [Response](class-cake.http.response)
Responses contain the response text, status and headers of a HTTP response.
* ##### [ResponseEmitter](class-cake.http.responseemitter)
Emits a Response to the PHP Server API.
* ##### [Runner](class-cake.http.runner)
Executes the middleware queue and provides the `next` callable that allows the queue to be iterated.
* ##### [Server](class-cake.http.server)
Runs an application invoking all the PSR7 middleware and the registered application.
* ##### [ServerRequest](class-cake.http.serverrequest)
A class that helps wrap Request information and particulars about a single request. Provides methods commonly used to introspect on the request headers and request body.
* ##### [ServerRequestFactory](class-cake.http.serverrequestfactory)
Factory for making ServerRequest instances.
* ##### [Session](class-cake.http.session)
This class is a wrapper for the native PHP session functions. It provides several defaults for the most common session configuration via external handlers and helps with using session in CLI without any warnings.
* ##### [Uri](class-cake.http.uri)
The base and webroot properties have piggybacked on the Uri for a long time. To preserve backwards compatibility and avoid dynamic property errors in PHP 8.2 we use this implementation that decorates the Uri from Laminas
cakephp Class App Class App
==========
App is responsible for resource location, and path management.
### Adding paths
Additional paths for Templates and Plugins are configured with Configure now. See config/app.php for an example. The `App.paths.plugins` and `App.paths.templates` variables are used to configure paths for plugins and templates respectively. All class based resources should be mapped using your application's autoloader.
### Inspecting loaded paths
You can inspect the currently loaded paths using `App::classPath('Controller')` for example to see loaded controller paths.
It is also possible to inspect paths for plugin classes, for instance, to get the path to a plugin's helpers you would call `App::classPath('View/Helper', 'MyPlugin')`
### Locating plugins
Plugins can be located with App as well. Using Plugin::path('DebugKit') for example, will give you the full path to the DebugKit plugin.
**Namespace:** [Cake\Core](namespace-cake.core)
**Link:** https://book.cakephp.org/4/en/core-libraries/app.html
Method Summary
--------------
* ##### [\_classExistsInBase()](#_classExistsInBase()) protected static
\_classExistsInBase
* ##### [className()](#className()) public static
Return the class name namespaced. This method checks if the class is defined on the application/plugin, otherwise try to load from the CakePHP core
* ##### [classPath()](#classPath()) public static
Gets the path to a class type in the application or a plugin.
* ##### [core()](#core()) public static
Returns the full path to a package inside the CakePHP core
* ##### [path()](#path()) public static
Used to read information stored path.
* ##### [shortName()](#shortName()) public static
Returns the plugin split name of a class
Method Detail
-------------
### \_classExistsInBase() protected static
```
_classExistsInBase(string $name, string $namespace): bool
```
\_classExistsInBase
Test isolation wrapper
#### Parameters
`string` $name Class name.
`string` $namespace Namespace.
#### Returns
`bool`
### className() public static
```
className(string $class, string $type = '', string $suffix = ''): string|null
```
Return the class name namespaced. This method checks if the class is defined on the application/plugin, otherwise try to load from the CakePHP core
#### Parameters
`string` $class Class name
`string` $type optional Type of class
`string` $suffix optional Class name suffix
#### Returns
`string|null`
### classPath() public static
```
classPath(string $type, string|null $plugin = null): array<string>
```
Gets the path to a class type in the application or a plugin.
Example:
```
App::classPath('Model/Table');
```
Will return the path for tables - e.g. `src/Model/Table/`.
```
App::classPath('Model/Table', 'My/Plugin');
```
Will return the plugin based path for those.
#### Parameters
`string` $type Package type.
`string|null` $plugin optional Plugin name.
#### Returns
`array<string>`
### core() public static
```
core(string $type): array<string>
```
Returns the full path to a package inside the CakePHP core
Usage:
```
App::core('Cache/Engine');
```
Will return the full path to the cache engines package.
#### Parameters
`string` $type Package type.
#### Returns
`array<string>`
### path() public static
```
path(string $type, string|null $plugin = null): array<string>
```
Used to read information stored path.
The 1st character of $type argument should be lower cased and will return the value of `App.paths.$type` config.
Default types:
* plugins
* templates
* locales
Example:
```
App::path('plugins');
```
Will return the value of `App.paths.plugins` config.
Deprecated: 4.0 App::path() is deprecated for class path (inside src/ directory). Use \Cake\Core\App::classPath() instead or directly the method on \Cake\Core\Plugin class.
#### Parameters
`string` $type Type of path
`string|null` $plugin optional Plugin name
#### Returns
`array<string>`
#### Links
https://book.cakephp.org/4/en/core-libraries/app.html#finding-paths-to-namespaces
### shortName() public static
```
shortName(string $class, string $type, string $suffix = ''): string
```
Returns the plugin split name of a class
Examples:
```
App::shortName(
'SomeVendor\SomePlugin\Controller\Component\TestComponent',
'Controller/Component',
'Component'
)
```
Returns: SomeVendor/SomePlugin.Test
```
App::shortName(
'SomeVendor\SomePlugin\Controller\Component\Subfolder\TestComponent',
'Controller/Component',
'Component'
)
```
Returns: SomeVendor/SomePlugin.Subfolder/Test
```
App::shortName(
'Cake\Controller\Component\AuthComponent',
'Controller/Component',
'Component'
)
```
Returns: Auth
#### Parameters
`string` $class Class name
`string` $type Type of class
`string` $suffix optional Class name suffix
#### Returns
`string`
cakephp Class MissingShellMethodException Class MissingShellMethodException
==================================
Used when a shell method cannot be found.
**Namespace:** [Cake\Console\Exception](namespace-cake.console.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Class TextErrorRenderer Class TextErrorRenderer
========================
Plain text error rendering with a stack trace.
Useful in CLI environments.
**Namespace:** [Cake\Error\Renderer](namespace-cake.error.renderer)
Method Summary
--------------
* ##### [render()](#render()) public
Render output for the provided error.
* ##### [write()](#write()) public
Write output to the renderer's output stream
Method Detail
-------------
### render() public
```
render(Cake\Error\PhpError $error, bool $debug): string
```
Render output for the provided error.
#### Parameters
`Cake\Error\PhpError` $error `bool` $debug #### Returns
`string`
### write() public
```
write(string $out): void
```
Write output to the renderer's output stream
#### Parameters
`string` $out #### Returns
`void`
| programming_docs |
cakephp Class AbstractFormatter Class AbstractFormatter
========================
**Abstract**
**Namespace:** [Cake\Log\Formatter](namespace-cake.log.formatter)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this class
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [format()](#format()) abstract public
Formats message.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [setConfig()](#setConfig()) public
Sets the config.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
#### Parameters
`array<string, mixed>` $config optional Config options
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### format() abstract public
```
format(mixed $level, string $message, array $context = []): string
```
Formats message.
#### Parameters
`mixed` $level Logging level
`string` $message Message string
`array` $context optional Mesage context
#### Returns
`string`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this class
#### Type
`array<string, mixed>`
cakephp Class HtmlHelper Class HtmlHelper
=================
Html Helper class for easy use of HTML widgets.
HtmlHelper encloses all methods needed while working with HTML pages.
**Namespace:** [Cake\View\Helper](namespace-cake.view.helper)
**Link:** https://book.cakephp.org/4/en/views/helpers/html.html
Property Summary
----------------
* [$Url](#%24Url) public @property `Cake\View\Helper\UrlHelper`
* [$\_View](#%24_View) protected `Cake\View\View` The View instance this helper is attached to
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this class
* [$\_helperMap](#%24_helperMap) protected `array<string, array>` A helper lookup table used to lazy load helper objects.
* [$\_includedAssets](#%24_includedAssets) protected `array<string, array>` Names of script & css files that have been included once
* [$\_scriptBlockOptions](#%24_scriptBlockOptions) protected `array<string, mixed>` Options for the currently opened script block buffer if any.
* [$\_templater](#%24_templater) protected `Cake\View\StringTemplate|null` StringTemplate instance.
* [$helpers](#%24helpers) protected `array` List of helpers used by this helper
Method Summary
--------------
* ##### [\_\_call()](#__call()) public
Provide non fatal errors on missing method calls.
* ##### [\_\_construct()](#__construct()) public
Default Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_get()](#__get()) public
Lazy loads helpers.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_confirm()](#_confirm()) protected
Returns a string to be used as onclick handler for confirm dialogs.
* ##### [\_nestedListItem()](#_nestedListItem()) protected
Internal function to build a nested list (UL/OL) out of an associative array.
* ##### [\_renderCells()](#_renderCells()) protected
Renders cells for a row of a table.
* ##### [addClass()](#addClass()) public
Adds the given class to the element options
* ##### [charset()](#charset()) public
Returns a charset META-tag.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [css()](#css()) public
Creates a link element for CSS stylesheets.
* ##### [div()](#div()) public
Returns a formatted DIV tag for HTML FORMs.
* ##### [formatTemplate()](#formatTemplate()) public
Formats a template string with $data
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getTemplates()](#getTemplates()) public
Gets templates to use or a specific template.
* ##### [getView()](#getView()) public
Get the view instance this helper is bound to.
* ##### [image()](#image()) public
Creates a formatted IMG element.
* ##### [implementedEvents()](#implementedEvents()) public
Event listeners.
* ##### [initialize()](#initialize()) public
Constructor hook method.
* ##### [link()](#link()) public
Creates an HTML link.
* ##### [linkFromPath()](#linkFromPath()) public
Creates an HTML link from route path string.
* ##### [media()](#media()) public
Returns an audio/video element
* ##### [meta()](#meta()) public
Creates a link to an external resource and handles basic meta tags
* ##### [nestedList()](#nestedList()) public
Build a nested list (UL/OL) out of an associative array.
* ##### [para()](#para()) public
Returns a formatted P tag.
* ##### [script()](#script()) public
Returns one or many `<script>` tags depending on the number of scripts given.
* ##### [scriptBlock()](#scriptBlock()) public
Wrap $script in a script tag.
* ##### [scriptEnd()](#scriptEnd()) public
End a Buffered section of JavaScript capturing. Generates a script tag inline or appends to specified view block depending on the settings used when the scriptBlock was started
* ##### [scriptStart()](#scriptStart()) public
Begin a script block that captures output until HtmlHelper::scriptEnd() is called. This capturing block will capture all output between the methods and create a scriptBlock from it.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setTemplates()](#setTemplates()) public
Sets templates to use.
* ##### [style()](#style()) public
Builds CSS style data from an array of CSS properties
* ##### [tableCell()](#tableCell()) public
Renders a single table cell (A TD with attributes).
* ##### [tableCells()](#tableCells()) public
Returns a formatted string of table rows (TR's with TD's in them).
* ##### [tableHeaders()](#tableHeaders()) public
Returns a row of formatted and named TABLE headers.
* ##### [tableRow()](#tableRow()) public
Renders a single table row (A TR with attributes).
* ##### [tag()](#tag()) public
Returns a formatted block tag, i.e DIV, SPAN, P.
* ##### [templater()](#templater()) public
Returns the templater instance.
Method Detail
-------------
### \_\_call() public
```
__call(string $method, array $params): mixed|void
```
Provide non fatal errors on missing method calls.
#### Parameters
`string` $method Method to invoke
`array` $params Array of params for the method.
#### Returns
`mixed|void`
### \_\_construct() public
```
__construct(Cake\View\View $view, array<string, mixed> $config = [])
```
Default Constructor
#### Parameters
`Cake\View\View` $view The View this helper is being attached to.
`array<string, mixed>` $config optional Configuration settings for the helper.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): Cake\View\Helper|null|void
```
Lazy loads helpers.
#### Parameters
`string` $name Name of the property being accessed.
#### Returns
`Cake\View\Helper|null|void`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_confirm() protected
```
_confirm(string $okCode, string $cancelCode): string
```
Returns a string to be used as onclick handler for confirm dialogs.
#### Parameters
`string` $okCode Code to be executed after user chose 'OK'
`string` $cancelCode Code to be executed after user chose 'Cancel'
#### Returns
`string`
### \_nestedListItem() protected
```
_nestedListItem(array $items, array<string, mixed> $options, array<string, mixed> $itemOptions): string
```
Internal function to build a nested list (UL/OL) out of an associative array.
#### Parameters
`array` $items Set of elements to list.
`array<string, mixed>` $options Additional HTML attributes of the list (ol/ul) tag.
`array<string, mixed>` $itemOptions Options and additional HTML attributes of the list item (LI) tag.
#### Returns
`string`
#### See Also
\Cake\View\Helper\HtmlHelper::nestedList() ### \_renderCells() protected
```
_renderCells(array $line, bool $useCount = false): array<string>
```
Renders cells for a row of a table.
This is a helper method for tableCells(). Overload this method as you need to change the behavior of the cell rendering.
#### Parameters
`array` $line Line data to render.
`bool` $useCount optional Renders the count into the row. Default is false.
#### Returns
`array<string>`
### addClass() public
```
addClass(array<string, mixed> $options, string $class, string $key = 'class'): array<string, mixed>
```
Adds the given class to the element options
#### Parameters
`array<string, mixed>` $options Array options/attributes to add a class to
`string` $class The class name being added.
`string` $key optional the key to use for class. Defaults to `'class'`.
#### Returns
`array<string, mixed>`
### charset() public
```
charset(string|null $charset = null): string
```
Returns a charset META-tag.
#### Parameters
`string|null` $charset optional The character set to be used in the meta tag. If empty, The App.encoding value will be used. Example: "utf-8".
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/html.html#creating-charset-tags
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### css() public
```
css(array<string>|string $path, array<string, mixed> $options = []): string|null
```
Creates a link element for CSS stylesheets.
### Usage
Include one CSS file:
```
echo $this->Html->css('styles.css');
```
Include multiple CSS files:
```
echo $this->Html->css(['one.css', 'two.css']);
```
Add the stylesheet to view block "css":
```
$this->Html->css('styles.css', ['block' => true]);
```
Add the stylesheet to a custom block:
```
$this->Html->css('styles.css', ['block' => 'layoutCss']);
```
### Options
* `block` Set to true to append output to view block "css" or provide custom block name.
* `once` Whether the css file should be checked for uniqueness. If true css files will only be included once, use false to allow the same css to be included more than once per request.
* `plugin` False value will prevent parsing path as a plugin
* `rel` Defaults to 'stylesheet'. If equal to 'import' the stylesheet will be imported.
* `fullBase` If true the URL will get a full address for the css file.
All other options will be treated as HTML attributes. If the request contains a `cspStyleNonce` attribute, that value will be applied as the `nonce` attribute on the generated HTML.
#### Parameters
`array<string>|string` $path The name of a CSS style sheet or an array containing names of CSS stylesheets. If `$path` is prefixed with '/', the path will be relative to the webroot of your application. Otherwise, the path will be relative to your CSS path, usually webroot/css.
`array<string, mixed>` $options optional Array of options and HTML arguments.
#### Returns
`string|null`
#### Links
https://book.cakephp.org/4/en/views/helpers/html.html#linking-to-css-files
### div() public
```
div(string|null $class = null, string|null $text = null, array<string, mixed> $options = []): string
```
Returns a formatted DIV tag for HTML FORMs.
### Options
* `escape` Whether the contents should be html\_entity escaped.
#### Parameters
`string|null` $class optional CSS class name of the div element.
`string|null` $text optional String content that will appear inside the div element. If null, only a start tag will be printed
`array<string, mixed>` $options optional Additional HTML attributes of the DIV tag
#### Returns
`string`
### formatTemplate() public
```
formatTemplate(string $name, array<string, mixed> $data): string
```
Formats a template string with $data
#### Parameters
`string` $name The template name.
`array<string, mixed>` $data The data to insert.
#### Returns
`string`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getTemplates() public
```
getTemplates(string|null $template = null): array|string
```
Gets templates to use or a specific template.
#### Parameters
`string|null` $template optional String for reading a specific template, null for all.
#### Returns
`array|string`
### getView() public
```
getView(): Cake\View\View
```
Get the view instance this helper is bound to.
#### Returns
`Cake\View\View`
### image() public
```
image(array|string $path, array<string, mixed> $options = []): string
```
Creates a formatted IMG element.
This method will set an empty alt attribute if one is not supplied.
### Usage:
Create a regular image:
```
echo $this->Html->image('cake_icon.png', ['alt' => 'CakePHP']);
```
Create an image link:
```
echo $this->Html->image('cake_icon.png', ['alt' => 'CakePHP', 'url' => 'https://cakephp.org']);
```
### Options:
* `url` If provided an image link will be generated and the link will point at `$options['url']`.
* `fullBase` If true the src attribute will get a full address for the image file.
* `plugin` False value will prevent parsing path as a plugin
#### Parameters
`array|string` $path Path to the image file, relative to the webroot/img/ directory.
`array<string, mixed>` $options optional Array of HTML attributes. See above for special options.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/html.html#linking-to-images
### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Event listeners.
By defining one of the callback methods a helper is assumed to be interested in the related event.
Override this method if you need to add non-conventional event listeners. Or if you want helpers to listen to non-standard events.
#### Returns
`array<string, mixed>`
### initialize() public
```
initialize(array<string, mixed> $config): void
```
Constructor hook method.
Implement this method to avoid having to overwrite the constructor and call parent.
#### Parameters
`array<string, mixed>` $config The configuration settings provided to this helper.
#### Returns
`void`
### link() public
```
link(array|string $title, array|string|null $url = null, array<string, mixed> $options = []): string
```
Creates an HTML link.
If $url starts with "http://" this is treated as an external link. Else, it is treated as a path to controller/action and parsed with the UrlHelper::build() method.
If the $url is empty, $title is used instead.
### Options
* `escape` Set to false to disable escaping of title and attributes.
* `escapeTitle` Set to false to disable escaping of title. Takes precedence over value of `escape`)
* `confirm` JavaScript confirmation message.
#### Parameters
`array|string` $title The content to be wrapped by `<a>` tags. Can be an array if $url is null. If $url is null, $title will be used as both the URL and title.
`array|string|null` $url optional Cake-relative URL or array of URL parameters, or external URL (starts with http://)
`array<string, mixed>` $options optional Array of options and HTML attributes.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/html.html#creating-links
### linkFromPath() public
```
linkFromPath(string $title, string $path, array $params = [], array<string, mixed> $options = []): string
```
Creates an HTML link from route path string.
### Options
* `escape` Set to false to disable escaping of title and attributes.
* `escapeTitle` Set to false to disable escaping of title. Takes precedence over value of `escape`)
* `confirm` JavaScript confirmation message.
#### Parameters
`string` $title The content to be wrapped by `<a>` tags.
`string` $path Cake-relative route path.
`array` $params optional An array specifying any additional parameters. Can be also any special parameters supported by `Router::url()`.
`array<string, mixed>` $options optional Array of options and HTML attributes.
#### Returns
`string`
#### See Also
\Cake\Routing\Router::pathUrl() #### Links
https://book.cakephp.org/4/en/views/helpers/html.html#creating-links
### media() public
```
media(array|string $path, array<string, mixed> $options = []): string
```
Returns an audio/video element
### Usage
Using an audio file:
```
echo $this->Html->media('audio.mp3', ['fullBase' => true]);
```
Outputs:
```
<video src="http://www.somehost.com/files/audio.mp3">Fallback text</video>
```
Using a video file:
```
echo $this->Html->media('video.mp4', ['text' => 'Fallback text']);
```
Outputs:
```
<video src="/files/video.mp4">Fallback text</video>
```
Using multiple video files:
```
echo $this->Html->media(
['video.mp4', ['src' => 'video.ogv', 'type' => "video/ogg; codecs='theora, vorbis'"]],
['tag' => 'video', 'autoplay']
);
```
Outputs:
```
<video autoplay="autoplay">
<source src="/files/video.mp4" type="video/mp4"/>
<source src="/files/video.ogv" type="video/ogv; codecs='theora, vorbis'"/>
</video>
```
### Options
* `tag` Type of media element to generate, either "audio" or "video". If tag is not provided it's guessed based on file's mime type.
* `text` Text to include inside the audio/video tag
* `pathPrefix` Path prefix to use for relative URLs, defaults to 'files/'
* `fullBase` If provided the src attribute will get a full address including domain name
#### Parameters
`array|string` $path Path to the video file, relative to the webroot/{$options['pathPrefix']} directory. Or an array where each item itself can be a path string or an associate array containing keys `src` and `type`
`array<string, mixed>` $options optional Array of HTML attributes, and special options above.
#### Returns
`string`
### meta() public
```
meta(array<string, mixed>|string $type, array|string|null $content = null, array<string, mixed> $options = []): string|null
```
Creates a link to an external resource and handles basic meta tags
Create a meta tag that is output inline:
```
$this->Html->meta('icon', 'favicon.ico');
```
Append the meta tag to custom view block "meta":
```
$this->Html->meta('description', 'A great page', ['block' => true]);
```
Append the meta tag to custom view block:
```
$this->Html->meta('description', 'A great page', ['block' => 'metaTags']);
```
Create a custom meta tag:
```
$this->Html->meta(['property' => 'og:site_name', 'content' => 'CakePHP']);
```
### Options
* `block` - Set to true to append output to view block "meta" or provide custom block name.
#### Parameters
`array<string, mixed>|string` $type The title of the external resource, Or an array of attributes for a custom meta tag.
`array|string|null` $content optional The address of the external resource or string for content attribute
`array<string, mixed>` $options optional Other attributes for the generated tag. If the type attribute is html, rss, atom, or icon, the mime-type is returned.
#### Returns
`string|null`
#### Links
https://book.cakephp.org/4/en/views/helpers/html.html#creating-meta-tags
### nestedList() public
```
nestedList(array $list, array<string, mixed> $options = [], array<string, mixed> $itemOptions = []): string
```
Build a nested list (UL/OL) out of an associative array.
Options for $options:
* `tag` - Type of list tag to use (ol/ul)
Options for $itemOptions:
* `even` - Class to use for even rows.
* `odd` - Class to use for odd rows.
#### Parameters
`array` $list Set of elements to list
`array<string, mixed>` $options optional Options and additional HTML attributes of the list (ol/ul) tag.
`array<string, mixed>` $itemOptions optional Options and additional HTML attributes of the list item (LI) tag.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/html.html#creating-nested-lists
### para() public
```
para(string|null $class, string|null $text, array<string, mixed> $options = []): string
```
Returns a formatted P tag.
### Options
* `escape` Whether the contents should be html\_entity escaped.
#### Parameters
`string|null` $class CSS class name of the p element.
`string|null` $text String content that will appear inside the p element.
`array<string, mixed>` $options optional Additional HTML attributes of the P tag
#### Returns
`string`
### script() public
```
script(array<string>|string $url, array<string, mixed> $options = []): string|null
```
Returns one or many `<script>` tags depending on the number of scripts given.
If the filename is prefixed with "/", the path will be relative to the base path of your application. Otherwise, the path will be relative to your JavaScript path, usually webroot/js.
### Usage
Include one script file:
```
echo $this->Html->script('styles.js');
```
Include multiple script files:
```
echo $this->Html->script(['one.js', 'two.js']);
```
Add the script file to a custom block:
```
$this->Html->script('styles.js', ['block' => 'bodyScript']);
```
### Options
* `block` Set to true to append output to view block "script" or provide custom block name.
* `once` Whether the script should be checked for uniqueness. If true scripts will only be included once, use false to allow the same script to be included more than once per request.
* `plugin` False value will prevent parsing path as a plugin
* `fullBase` If true the url will get a full address for the script file.
All other options will be added as attributes to the generated script tag. If the current request has a `cspScriptNonce` attribute, that value will be inserted as a `nonce` attribute on the script tag.
#### Parameters
`array<string>|string` $url String or array of javascript files to include
`array<string, mixed>` $options optional Array of options, and html attributes see above.
#### Returns
`string|null`
#### Links
https://book.cakephp.org/4/en/views/helpers/html.html#linking-to-javascript-files
### scriptBlock() public
```
scriptBlock(string $script, array<string, mixed> $options = []): string|null
```
Wrap $script in a script tag.
### Options
* `block` Set to true to append output to view block "script" or provide custom block name.
#### Parameters
`string` $script The script to wrap
`array<string, mixed>` $options optional The options to use. Options not listed above will be treated as HTML attributes.
#### Returns
`string|null`
#### Links
https://book.cakephp.org/4/en/views/helpers/html.html#creating-inline-javascript-blocks
### scriptEnd() public
```
scriptEnd(): string|null
```
End a Buffered section of JavaScript capturing. Generates a script tag inline or appends to specified view block depending on the settings used when the scriptBlock was started
#### Returns
`string|null`
#### Links
https://book.cakephp.org/4/en/views/helpers/html.html#creating-inline-javascript-blocks
### scriptStart() public
```
scriptStart(array<string, mixed> $options = []): void
```
Begin a script block that captures output until HtmlHelper::scriptEnd() is called. This capturing block will capture all output between the methods and create a scriptBlock from it.
### Options
* `block` Set to true to append output to view block "script" or provide custom block name.
#### Parameters
`array<string, mixed>` $options optional Options for the code block.
#### Returns
`void`
#### Links
https://book.cakephp.org/4/en/views/helpers/html.html#creating-inline-javascript-blocks
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setTemplates() public
```
setTemplates(array<string> $templates): $this
```
Sets templates to use.
#### Parameters
`array<string>` $templates Templates to be added.
#### Returns
`$this`
### style() public
```
style(array<string, string> $data, bool $oneLine = true): string
```
Builds CSS style data from an array of CSS properties
### Usage:
```
echo $this->Html->style(['margin' => '10px', 'padding' => '10px'], true);
// creates
'margin:10px;padding:10px;'
```
#### Parameters
`array<string, string>` $data Style data array, keys will be used as property names, values as property values.
`bool` $oneLine optional Whether the style block should be displayed on one line.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/html.html#creating-css-programatically
### tableCell() public
```
tableCell(string $content, array<string, mixed> $options = []): string
```
Renders a single table cell (A TD with attributes).
#### Parameters
`string` $content The content of the cell.
`array<string, mixed>` $options optional HTML attributes.
#### Returns
`string`
### tableCells() public
```
tableCells(array|string $data, array<string, mixed>|bool|null $oddTrOptions = null, array<string, mixed>|bool|null $evenTrOptions = null, bool $useCount = false, bool $continueOddEven = true): string
```
Returns a formatted string of table rows (TR's with TD's in them).
#### Parameters
`array|string` $data Array of table data
`array<string, mixed>|bool|null` $oddTrOptions optional HTML options for odd TR elements if true useCount is used
`array<string, mixed>|bool|null` $evenTrOptions optional HTML options for even TR elements
`bool` $useCount optional adds class "column-$i"
`bool` $continueOddEven optional If false, will use a non-static $count variable, so that the odd/even count is reset to zero just for that call.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/html.html#creating-table-cells
### tableHeaders() public
```
tableHeaders(array $names, array<string, mixed>|null $trOptions = null, array<string, mixed>|null $thOptions = null): string
```
Returns a row of formatted and named TABLE headers.
#### Parameters
`array` $names Array of tablenames. Each tablename can be string, or array with name and an array with a set of attributes to its specific tag
`array<string, mixed>|null` $trOptions optional HTML options for TR elements.
`array<string, mixed>|null` $thOptions optional HTML options for TH elements.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/html.html#creating-table-headings
### tableRow() public
```
tableRow(string $content, array<string, mixed> $options = []): string
```
Renders a single table row (A TR with attributes).
#### Parameters
`string` $content The content of the row.
`array<string, mixed>` $options optional HTML attributes.
#### Returns
`string`
### tag() public
```
tag(string $name, string|null $text = null, array<string, mixed> $options = []): string
```
Returns a formatted block tag, i.e DIV, SPAN, P.
### Options
* `escape` Whether the contents should be html\_entity escaped.
#### Parameters
`string` $name Tag name.
`string|null` $text optional String content that will appear inside the HTML element. If null, only a start tag will be printed
`array<string, mixed>` $options optional Additional HTML attributes of the HTML tag, see above.
#### Returns
`string`
### templater() public
```
templater(): Cake\View\StringTemplate
```
Returns the templater instance.
#### Returns
`Cake\View\StringTemplate`
Property Detail
---------------
### $Url public @property
#### Type
`Cake\View\Helper\UrlHelper`
### $\_View protected
The View instance this helper is attached to
#### Type
`Cake\View\View`
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this class
#### Type
`array<string, mixed>`
### $\_helperMap protected
A helper lookup table used to lazy load helper objects.
#### Type
`array<string, array>`
### $\_includedAssets protected
Names of script & css files that have been included once
#### Type
`array<string, array>`
### $\_scriptBlockOptions protected
Options for the currently opened script block buffer if any.
#### Type
`array<string, mixed>`
### $\_templater protected
StringTemplate instance.
#### Type
`Cake\View\StringTemplate|null`
### $helpers protected
List of helpers used by this helper
#### Type
`array`
| programming_docs |
cakephp Class InflectedRoute Class InflectedRoute
=====================
This route class will transparently inflect the controller and plugin routing parameters, so that requesting `/my_controller` is parsed as `['controller' => 'MyController']`
**Namespace:** [Cake\Routing\Route](namespace-cake.routing.route)
Constants
---------
* `string` **PLACEHOLDER\_REGEX**
```
'#\\{([a-z][a-z0-9-_]*)\\}#i'
```
Regex for matching braced placholders in route template.
* `array<string>` **VALID\_METHODS**
```
['GET', 'PUT', 'POST', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD']
```
Valid HTTP methods.
Property Summary
----------------
* [$\_compiledRoute](#%24_compiledRoute) protected `string|null` The compiled route regular expression
* [$\_extensions](#%24_extensions) protected `array<string>` List of connected extensions for this route.
* [$\_greedy](#%24_greedy) protected `bool` Is this route a greedy route? Greedy routes have a `/*` in their template
* [$\_inflectedDefaults](#%24_inflectedDefaults) protected `bool` Flag for tracking whether the defaults have been inflected.
* [$\_name](#%24_name) protected `string|null` The name for a route. Fetch with Route::getName();
* [$braceKeys](#%24braceKeys) protected `bool` Track whether brace keys `{var}` were used.
* [$defaults](#%24defaults) public `array` Default parameters for a Route
* [$keys](#%24keys) public `array` An array of named segments in a Route. `/{controller}/{action}/{id}` has 3 key elements
* [$middleware](#%24middleware) protected `array` List of middleware that should be applied.
* [$options](#%24options) public `array` An array of additional parameters for the Route.
* [$template](#%24template) public `string` The routes template string.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor for a Route
* ##### [\_\_set\_state()](#__set_state()) public static
Set state magic method to support var\_export
* ##### [\_matchMethod()](#_matchMethod()) protected
Check whether the URL's HTTP method matches.
* ##### [\_parseArgs()](#_parseArgs()) protected
Parse passed parameters into a list of passed args.
* ##### [\_parseExtension()](#_parseExtension()) protected
Removes the extension from $url if it contains a registered extension. If no registered extension is found, no extension is returned and the URL is returned unmodified.
* ##### [\_persistParams()](#_persistParams()) protected
Apply persistent parameters to a URL array. Persistent parameters are a special key used during route creation to force route parameters to persist when omitted from a URL array.
* ##### [\_underscore()](#_underscore()) protected
Helper method for underscoring keys in a URL array.
* ##### [\_writeRoute()](#_writeRoute()) protected
Builds a route regular expression.
* ##### [\_writeUrl()](#_writeUrl()) protected
Converts a matching route array into a URL string.
* ##### [compile()](#compile()) public
Compiles the route's regular expression.
* ##### [compiled()](#compiled()) public
Check if a Route has been compiled into a regular expression.
* ##### [getExtensions()](#getExtensions()) public
Get the supported extensions for this route.
* ##### [getMiddleware()](#getMiddleware()) public
Get the names of the middleware that should be applied to this route.
* ##### [getName()](#getName()) public
Get the standardized plugin.controller:action name for a route.
* ##### [hostMatches()](#hostMatches()) public
Check to see if the host matches the route requirements
* ##### [match()](#match()) public
Underscores the prefix, controller and plugin params before passing them on to the parent class
* ##### [normalizeAndValidateMethods()](#normalizeAndValidateMethods()) protected
Normalize method names to upper case and validate that they are valid HTTP methods.
* ##### [parse()](#parse()) public
Parses a string URL into an array. If it matches, it will convert the prefix, controller and plugin keys to their camelized form.
* ##### [parseRequest()](#parseRequest()) public
Checks to see if the given URL can be parsed by this route.
* ##### [setExtensions()](#setExtensions()) public
Set the supported extensions for this route.
* ##### [setHost()](#setHost()) public
Set host requirement
* ##### [setMethods()](#setMethods()) public
Set the accepted HTTP methods for this route.
* ##### [setMiddleware()](#setMiddleware()) public
Set the names of the middleware that should be applied to this route.
* ##### [setPass()](#setPass()) public
Set the names of parameters that will be converted into passed parameters
* ##### [setPatterns()](#setPatterns()) public
Set regexp patterns for routing parameters
* ##### [setPersist()](#setPersist()) public
Set the names of parameters that will persisted automatically
* ##### [staticPath()](#staticPath()) public
Get the static path portion for this route.
Method Detail
-------------
### \_\_construct() public
```
__construct(string $template, array $defaults = [], array<string, mixed> $options = [])
```
Constructor for a Route
### Options
* `_ext` - Defines the extensions used for this route.
* `_middleware` - Define the middleware names for this route.
* `pass` - Copies the listed parameters into params['pass'].
* `_method` - Defines the HTTP method(s) the route applies to. It can be a string or array of valid HTTP method name.
* `_host` - Define the host name pattern if you want this route to only match specific host names. You can use `.*` and to create wildcard subdomains/hosts e.g. `*.example.com` matches all subdomains on `example.com`.
* '\_port` - Define the port if you want this route to only match specific port number.
* '\_urldecode' - Set to `false` to disable URL decoding before route parsing.
#### Parameters
`string` $template Template string with parameter placeholders
`array` $defaults optional Defaults for the route.
`array<string, mixed>` $options optional Array of additional options for the Route
#### Throws
`InvalidArgumentException`
When `$options['\_method']` are not in `VALID\_METHODS` list. ### \_\_set\_state() public static
```
__set_state(array<string, mixed> $fields): static
```
Set state magic method to support var\_export
This method helps for applications that want to implement router caching.
#### Parameters
`array<string, mixed>` $fields Key/Value of object attributes
#### Returns
`static`
### \_matchMethod() protected
```
_matchMethod(array $url): bool
```
Check whether the URL's HTTP method matches.
#### Parameters
`array` $url The array for the URL being generated.
#### Returns
`bool`
### \_parseArgs() protected
```
_parseArgs(string $args, array $context): array<string>
```
Parse passed parameters into a list of passed args.
Return true if a given named $param's $val matches a given $rule depending on $context. Currently implemented rule types are controller, action and match that can be combined with each other.
#### Parameters
`string` $args A string with the passed params. eg. /1/foo
`array` $context The current route context, which should contain controller/action keys.
#### Returns
`array<string>`
### \_parseExtension() protected
```
_parseExtension(string $url): array
```
Removes the extension from $url if it contains a registered extension. If no registered extension is found, no extension is returned and the URL is returned unmodified.
#### Parameters
`string` $url The url to parse.
#### Returns
`array`
### \_persistParams() protected
```
_persistParams(array $url, array $params): array
```
Apply persistent parameters to a URL array. Persistent parameters are a special key used during route creation to force route parameters to persist when omitted from a URL array.
#### Parameters
`array` $url The array to apply persistent parameters to.
`array` $params An array of persistent values to replace persistent ones.
#### Returns
`array`
### \_underscore() protected
```
_underscore(array $url): array
```
Helper method for underscoring keys in a URL array.
#### Parameters
`array` $url An array of URL keys.
#### Returns
`array`
### \_writeRoute() protected
```
_writeRoute(): void
```
Builds a route regular expression.
Uses the template, defaults and options properties to compile a regular expression that can be used to parse request strings.
#### Returns
`void`
### \_writeUrl() protected
```
_writeUrl(array $params, array $pass = [], array $query = []): string
```
Converts a matching route array into a URL string.
Composes the string URL using the template used to create the route.
#### Parameters
`array` $params The params to convert to a string url
`array` $pass optional The additional passed arguments
`array` $query optional An array of parameters
#### Returns
`string`
### compile() public
```
compile(): string
```
Compiles the route's regular expression.
Modifies defaults property so all necessary keys are set and populates $this->names with the named routing elements.
#### Returns
`string`
### compiled() public
```
compiled(): bool
```
Check if a Route has been compiled into a regular expression.
#### Returns
`bool`
### getExtensions() public
```
getExtensions(): array<string>
```
Get the supported extensions for this route.
#### Returns
`array<string>`
### getMiddleware() public
```
getMiddleware(): array
```
Get the names of the middleware that should be applied to this route.
#### Returns
`array`
### getName() public
```
getName(): string
```
Get the standardized plugin.controller:action name for a route.
#### Returns
`string`
### hostMatches() public
```
hostMatches(string $host): bool
```
Check to see if the host matches the route requirements
#### Parameters
`string` $host The request's host name
#### Returns
`bool`
### match() public
```
match(array $url, array $context = []): string|null
```
Underscores the prefix, controller and plugin params before passing them on to the parent class
If the URL matches the route parameters and settings, then return a generated string URL. If the URL doesn't match the route parameters, false will be returned. This method handles the reverse routing or conversion of URL arrays into string URLs.
#### Parameters
`array` $url Array of parameters to convert to a string.
`array` $context optional An array of the current request context. Contains information such as the current host, scheme, port, and base directory.
#### Returns
`string|null`
### normalizeAndValidateMethods() protected
```
normalizeAndValidateMethods(array<string>|string $methods): array<string>|string
```
Normalize method names to upper case and validate that they are valid HTTP methods.
#### Parameters
`array<string>|string` $methods Methods.
#### Returns
`array<string>|string`
#### Throws
`InvalidArgumentException`
When methods are not in `VALID\_METHODS` list. ### parse() public
```
parse(string $url, string $method = ''): array|null
```
Parses a string URL into an array. If it matches, it will convert the prefix, controller and plugin keys to their camelized form.
If the route can be parsed an array of parameters will be returned; if not `null` will be returned. String URLs are parsed if they match a routes regular expression.
#### Parameters
`string` $url The URL to parse
`string` $method optional The HTTP method being matched.
#### Returns
`array|null`
### parseRequest() public
```
parseRequest(Psr\Http\Message\ServerRequestInterface $request): array|null
```
Checks to see if the given URL can be parsed by this route.
If the route can be parsed an array of parameters will be returned; if not `null` will be returned.
#### Parameters
`Psr\Http\Message\ServerRequestInterface` $request The URL to attempt to parse.
#### Returns
`array|null`
### setExtensions() public
```
setExtensions(array<string> $extensions): $this
```
Set the supported extensions for this route.
#### Parameters
`array<string>` $extensions The extensions to set.
#### Returns
`$this`
### setHost() public
```
setHost(string $host): $this
```
Set host requirement
#### Parameters
`string` $host The host name this route is bound to
#### Returns
`$this`
### setMethods() public
```
setMethods(array<string> $methods): $this
```
Set the accepted HTTP methods for this route.
#### Parameters
`array<string>` $methods The HTTP methods to accept.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
When methods are not in `VALID\_METHODS` list. ### setMiddleware() public
```
setMiddleware(array $middleware): $this
```
Set the names of the middleware that should be applied to this route.
#### Parameters
`array` $middleware The list of middleware names to apply to this route. Middleware names will not be checked until the route is matched.
#### Returns
`$this`
### setPass() public
```
setPass(array<string> $names): $this
```
Set the names of parameters that will be converted into passed parameters
#### Parameters
`array<string>` $names The names of the parameters that should be passed.
#### Returns
`$this`
### setPatterns() public
```
setPatterns(array<string> $patterns): $this
```
Set regexp patterns for routing parameters
If any of your patterns contain multibyte values, the `multibytePattern` mode will be enabled.
#### Parameters
`array<string>` $patterns The patterns to apply to routing elements
#### Returns
`$this`
### setPersist() public
```
setPersist(array $names): $this
```
Set the names of parameters that will persisted automatically
Persistent parameters allow you to define which route parameters should be automatically included when generating new URLs. You can override persistent parameters by redefining them in a URL or remove them by setting the persistent parameter to `false`.
```
// remove a persistent 'date' parameter
Router::url(['date' => false', ...]);
```
#### Parameters
`array` $names The names of the parameters that should be passed.
#### Returns
`$this`
### staticPath() public
```
staticPath(): string
```
Get the static path portion for this route.
#### Returns
`string`
Property Detail
---------------
### $\_compiledRoute protected
The compiled route regular expression
#### Type
`string|null`
### $\_extensions protected
List of connected extensions for this route.
#### Type
`array<string>`
### $\_greedy protected
Is this route a greedy route? Greedy routes have a `/*` in their template
#### Type
`bool`
### $\_inflectedDefaults protected
Flag for tracking whether the defaults have been inflected.
Default values need to be inflected so that they match the inflections that match() will create.
#### Type
`bool`
### $\_name protected
The name for a route. Fetch with Route::getName();
#### Type
`string|null`
### $braceKeys protected
Track whether brace keys `{var}` were used.
#### Type
`bool`
### $defaults public
Default parameters for a Route
#### Type
`array`
### $keys public
An array of named segments in a Route. `/{controller}/{action}/{id}` has 3 key elements
#### Type
`array`
### $middleware protected
List of middleware that should be applied.
#### Type
`array`
### $options public
An array of additional parameters for the Route.
#### Type
`array`
### $template public
The routes template string.
#### Type
`string`
cakephp Class CommonTableExpression Class CommonTableExpression
============================
An expression that represents a common table expression definition.
**Namespace:** [Cake\Database\Expression](namespace-cake.database.expression)
Property Summary
----------------
* [$fields](#%24fields) protected `arrayCake\Database\Expression\IdentifierExpression>` The field names to use for the CTE.
* [$materialized](#%24materialized) protected `string|null` Whether the CTE is materialized or not materialized.
* [$name](#%24name) protected `Cake\Database\Expression\IdentifierExpression` The CTE name.
* [$query](#%24query) protected `Cake\Database\ExpressionInterface|null` The CTE query definition.
* [$recursive](#%24recursive) protected `bool` Whether the CTE is recursive.
Method Summary
--------------
* ##### [\_\_clone()](#__clone()) public
Clones the inner expression objects.
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [field()](#field()) public
Adds one or more fields (arguments) to the CTE.
* ##### [isRecursive()](#isRecursive()) public
Gets whether this CTE is recursive.
* ##### [materialized()](#materialized()) public
Sets this CTE as materialized.
* ##### [name()](#name()) public
Sets the name of this CTE.
* ##### [notMaterialized()](#notMaterialized()) public
Sets this CTE as not materialized.
* ##### [query()](#query()) public
Sets the query for this CTE.
* ##### [recursive()](#recursive()) public
Sets this CTE as recursive.
* ##### [sql()](#sql()) public
Converts the Node into a SQL string fragment.
* ##### [traverse()](#traverse()) public
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
Method Detail
-------------
### \_\_clone() public
```
__clone(): void
```
Clones the inner expression objects.
#### Returns
`void`
### \_\_construct() public
```
__construct(string $name = '', Cake\Database\ExpressionInterfaceClosure $query = null)
```
Constructor.
#### Parameters
`string` $name optional The CTE name.
`Cake\Database\ExpressionInterfaceClosure` $query optional CTE query
### field() public
```
field(Cake\Database\Expression\IdentifierExpression|arrayCake\Database\Expression\IdentifierExpression>|array<string>|string $fields): $this
```
Adds one or more fields (arguments) to the CTE.
#### Parameters
`Cake\Database\Expression\IdentifierExpression|arrayCake\Database\Expression\IdentifierExpression>|array<string>|string` $fields Field names
#### Returns
`$this`
### isRecursive() public
```
isRecursive(): bool
```
Gets whether this CTE is recursive.
#### Returns
`bool`
### materialized() public
```
materialized(): $this
```
Sets this CTE as materialized.
#### Returns
`$this`
### name() public
```
name(string $name): $this
```
Sets the name of this CTE.
This is the named you used to reference the expression in select, insert, etc queries.
#### Parameters
`string` $name The CTE name.
#### Returns
`$this`
### notMaterialized() public
```
notMaterialized(): $this
```
Sets this CTE as not materialized.
#### Returns
`$this`
### query() public
```
query(Cake\Database\ExpressionInterfaceClosure $query): $this
```
Sets the query for this CTE.
#### Parameters
`Cake\Database\ExpressionInterfaceClosure` $query CTE query
#### Returns
`$this`
### recursive() public
```
recursive(): $this
```
Sets this CTE as recursive.
#### Returns
`$this`
### sql() public
```
sql(Cake\Database\ValueBinder $binder): string
```
Converts the Node into a SQL string fragment.
#### Parameters
`Cake\Database\ValueBinder` $binder #### Returns
`string`
### traverse() public
```
traverse(Closure $callback): $this
```
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
#### Parameters
`Closure` $callback #### Returns
`$this`
Property Detail
---------------
### $fields protected
The field names to use for the CTE.
#### Type
`arrayCake\Database\Expression\IdentifierExpression>`
### $materialized protected
Whether the CTE is materialized or not materialized.
#### Type
`string|null`
### $name protected
The CTE name.
#### Type
`Cake\Database\Expression\IdentifierExpression`
### $query protected
The CTE query definition.
#### Type
`Cake\Database\ExpressionInterface|null`
### $recursive protected
Whether the CTE is recursive.
#### Type
`bool`
| programming_docs |
cakephp Class BelongsTo Class BelongsTo
================
Represents an 1 - N relationship where the source side of the relation is related to only one record in the target table.
An example of a BelongsTo association would be Article belongs to Author.
**Namespace:** [Cake\ORM\Association](namespace-cake.orm.association)
Constants
---------
* `string` **MANY\_TO\_MANY**
```
'manyToMany'
```
Association type for many to many associations.
* `string` **MANY\_TO\_ONE**
```
'manyToOne'
```
Association type for many to one associations.
* `string` **ONE\_TO\_MANY**
```
'oneToMany'
```
Association type for one to many associations.
* `string` **ONE\_TO\_ONE**
```
'oneToOne'
```
Association type for one to one associations.
* `string` **STRATEGY\_JOIN**
```
'join'
```
Strategy name to use joins for fetching associated records
* `string` **STRATEGY\_SELECT**
```
'select'
```
Strategy name to use a select for fetching associated records
* `string` **STRATEGY\_SUBQUERY**
```
'subquery'
```
Strategy name to use a subquery for fetching associated records
Property Summary
----------------
* [$\_bindingKey](#%24_bindingKey) protected `array<string>|string|null` The field name in the owning side table that is used to match with the foreignKey
* [$\_cascadeCallbacks](#%24_cascadeCallbacks) protected `bool` Whether cascaded deletes should also fire callbacks.
* [$\_className](#%24_className) protected `string` The class name of the target table object
* [$\_conditions](#%24_conditions) protected `Closure|array` A list of conditions to be always included when fetching records from the target association
* [$\_dependent](#%24_dependent) protected `bool` Whether the records on the target table are dependent on the source table, often used to indicate that records should be removed if the owning record in the source table is deleted.
* [$\_finder](#%24_finder) protected `array|string` The default finder name to use for fetching rows from the target table With array value, finder name and default options are allowed.
* [$\_foreignKey](#%24_foreignKey) protected `array<string>|string` The name of the field representing the foreign key to the table to load
* [$\_joinType](#%24_joinType) protected `string` The type of join to be used when adding the association to a query
* [$\_name](#%24_name) protected `string` Name given to the association, it usually represents the alias assigned to the target associated table
* [$\_propertyName](#%24_propertyName) protected `string` The property name that should be filled with data from the target table in the source table record.
* [$\_sourceTable](#%24_sourceTable) protected `Cake\ORM\Table` Source table instance
* [$\_strategy](#%24_strategy) protected `string` The strategy name to be used to fetch associated records. Some association types might not implement but one strategy to fetch records.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$\_targetTable](#%24_targetTable) protected `Cake\ORM\Table` Target table instance
* [$\_validStrategies](#%24_validStrategies) protected `array<string>` Valid strategies for this type of association
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
Method Summary
--------------
* ##### [\_\_call()](#__call()) public
Proxies method calls to the target table.
* ##### [\_\_construct()](#__construct()) public
Constructor. Subclasses can override \_options function to get the original list of passed options if expecting any other special key
* ##### [\_\_get()](#__get()) public
Proxies property retrieval to the target table. This is handy for getting this association's associations
* ##### [\_\_isset()](#__isset()) public
Proxies the isset call to the target table. This is handy to check if the target table has another association with the passed name
* ##### [\_appendFields()](#_appendFields()) protected
Helper function used to conditionally append fields to the select clause of a query from the fields found in another query object.
* ##### [\_appendNotMatching()](#_appendNotMatching()) protected
Conditionally adds a condition to the passed Query that will make it find records where there is no match with this association.
* ##### [\_bindNewAssociations()](#_bindNewAssociations()) protected
Applies all attachable associations to `$query` out of the containments found in the `$surrogate` query.
* ##### [\_camelize()](#_camelize()) protected
Creates a camelized version of $name
* ##### [\_dispatchBeforeFind()](#_dispatchBeforeFind()) protected
Triggers beforeFind on the target table for the query this association is attaching to
* ##### [\_entityName()](#_entityName()) protected
Creates the proper entity name (singular) for the specified name
* ##### [\_extractFinder()](#_extractFinder()) protected
Helper method to infer the requested finder and its options.
* ##### [\_fixtureName()](#_fixtureName()) protected
Creates a fixture name
* ##### [\_formatAssociationResults()](#_formatAssociationResults()) protected
Adds a formatter function to the passed `$query` if the `$surrogate` query declares any other formatter. Since the `$surrogate` query correspond to the associated target table, the resulting formatter will be the result of applying the surrogate formatters to only the property corresponding to such table.
* ##### [\_joinCondition()](#_joinCondition()) protected
Returns a single or multiple conditions to be appended to the generated join clause for getting the results on the target table.
* ##### [\_modelKey()](#_modelKey()) protected
Creates the proper underscored model key for associations
* ##### [\_modelNameFromKey()](#_modelNameFromKey()) protected
Creates the proper model name from a foreign key
* ##### [\_options()](#_options()) protected
Override this function to initialize any concrete association class, it will get passed the original list of options used in the constructor
* ##### [\_pluginNamespace()](#_pluginNamespace()) protected
Return plugin's namespace
* ##### [\_pluginPath()](#_pluginPath()) protected
Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
* ##### [\_pluralHumanName()](#_pluralHumanName()) protected
Creates the plural human name used in views
* ##### [\_propertyName()](#_propertyName()) protected
Returns default property name based on association name.
* ##### [\_singularHumanName()](#_singularHumanName()) protected
Creates the singular human name used in views
* ##### [\_singularName()](#_singularName()) protected
Creates the singular name for use in views.
* ##### [\_variableName()](#_variableName()) protected
Creates the plural variable name for views
* ##### [attachTo()](#attachTo()) public
Alters a Query object to include the associated target table data in the final result
* ##### [canBeJoined()](#canBeJoined()) public
Whether this association can be expressed directly in a query join
* ##### [cascadeDelete()](#cascadeDelete()) public
Handle cascading deletes.
* ##### [defaultRowValue()](#defaultRowValue()) public
Returns a modified row after appending a property for this association with the default empty value according to whether the association was joined or fetched externally.
* ##### [deleteAll()](#deleteAll()) public
Proxies the delete operation to the target table's deleteAll method
* ##### [eagerLoader()](#eagerLoader()) public
Eager loads a list of records in the target table that are related to another set of records in the source table. Source records can be specified in two ways: first one is by passing a Query object setup to find on the source table and the other way is by explicitly passing an array of primary key values from the source table.
* ##### [exists()](#exists()) public
Proxies the operation to the target table's exists method after appending the default conditions for this association
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [find()](#find()) public
Proxies the finding operation to the target table's find method and modifies the query accordingly based of this association configuration
* ##### [getBindingKey()](#getBindingKey()) public
Gets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
* ##### [getCascadeCallbacks()](#getCascadeCallbacks()) public
Gets whether cascaded deletes should also fire callbacks.
* ##### [getClassName()](#getClassName()) public
Gets the class name of the target table object.
* ##### [getConditions()](#getConditions()) public
Gets a list of conditions to be always included when fetching records from the target association.
* ##### [getDependent()](#getDependent()) public
Sets whether the records on the target table are dependent on the source table.
* ##### [getFinder()](#getFinder()) public
Gets the default finder to use for fetching rows from the target table.
* ##### [getForeignKey()](#getForeignKey()) public
Gets the name of the field representing the foreign key to the target table.
* ##### [getJoinType()](#getJoinType()) public
Gets the type of join to be used when adding the association to a query.
* ##### [getName()](#getName()) public
Gets the name for this association, usually the alias assigned to the target associated table
* ##### [getProperty()](#getProperty()) public
Gets the property name that should be filled with data from the target table in the source table record.
* ##### [getSource()](#getSource()) public
Gets the table instance for the source side of the association.
* ##### [getStrategy()](#getStrategy()) public
Gets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [getTarget()](#getTarget()) public
Gets the table instance for the target side of the association.
* ##### [isOwningSide()](#isOwningSide()) public
Returns whether the passed table is the owning side for this association. This means that rows in the 'target' table would miss important or required information if the row in 'source' did not exist.
* ##### [requiresKeys()](#requiresKeys()) public
Returns true if the eager loading process will require a set of the owning table's binding keys in order to use them as a filter in the finder query.
* ##### [saveAssociated()](#saveAssociated()) public
Takes an entity from the source table and looks if there is a field matching the property name for this association. The found entity will be saved on the target table for this association by passing supplied `$options`
* ##### [setBindingKey()](#setBindingKey()) public
Sets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
* ##### [setCascadeCallbacks()](#setCascadeCallbacks()) public
Sets whether cascaded deletes should also fire callbacks.
* ##### [setClassName()](#setClassName()) public
Sets the class name of the target table object.
* ##### [setConditions()](#setConditions()) public
Sets a list of conditions to be always included when fetching records from the target association.
* ##### [setDependent()](#setDependent()) public
Sets whether the records on the target table are dependent on the source table.
* ##### [setFinder()](#setFinder()) public
Sets the default finder to use for fetching rows from the target table.
* ##### [setForeignKey()](#setForeignKey()) public
Sets the name of the field representing the foreign key to the target table.
* ##### [setJoinType()](#setJoinType()) public
Sets the type of join to be used when adding the association to a query.
* ##### [setName()](#setName()) public deprecated
Sets the name for this association, usually the alias assigned to the target associated table
* ##### [setProperty()](#setProperty()) public
Sets the property name that should be filled with data from the target table in the source table record.
* ##### [setSource()](#setSource()) public
Sets the table instance for the source side of the association.
* ##### [setStrategy()](#setStrategy()) public
Sets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
* ##### [setTarget()](#setTarget()) public
Sets the table instance for the target side of the association.
* ##### [transformRow()](#transformRow()) public
Correctly nests a result row associated values into the correct array keys inside the source results.
* ##### [type()](#type()) public
Get the relationship type.
* ##### [updateAll()](#updateAll()) public
Proxies the update operation to the target table's updateAll method
Method Detail
-------------
### \_\_call() public
```
__call(string $method, array $argument): mixed
```
Proxies method calls to the target table.
#### Parameters
`string` $method name of the method to be invoked
`array` $argument List of arguments passed to the function
#### Returns
`mixed`
#### Throws
`BadMethodCallException`
### \_\_construct() public
```
__construct(string $alias, array<string, mixed> $options = [])
```
Constructor. Subclasses can override \_options function to get the original list of passed options if expecting any other special key
#### Parameters
`string` $alias The name given to the association
`array<string, mixed>` $options optional A list of properties to be set on this object
### \_\_get() public
```
__get(string $property): Cake\ORM\Association
```
Proxies property retrieval to the target table. This is handy for getting this association's associations
#### Parameters
`string` $property the property name
#### Returns
`Cake\ORM\Association`
#### Throws
`RuntimeException`
if no association with such name exists ### \_\_isset() public
```
__isset(string $property): bool
```
Proxies the isset call to the target table. This is handy to check if the target table has another association with the passed name
#### Parameters
`string` $property the property name
#### Returns
`bool`
### \_appendFields() protected
```
_appendFields(Cake\ORM\Query $query, Cake\ORM\Query $surrogate, array<string, mixed> $options): void
```
Helper function used to conditionally append fields to the select clause of a query from the fields found in another query object.
#### Parameters
`Cake\ORM\Query` $query the query that will get the fields appended to
`Cake\ORM\Query` $surrogate the query having the fields to be copied from
`array<string, mixed>` $options options passed to the method `attachTo`
#### Returns
`void`
### \_appendNotMatching() protected
```
_appendNotMatching(Cake\ORM\Query $query, array<string, mixed> $options): void
```
Conditionally adds a condition to the passed Query that will make it find records where there is no match with this association.
#### Parameters
`Cake\ORM\Query` $query The query to modify
`array<string, mixed>` $options Options array containing the `negateMatch` key.
#### Returns
`void`
### \_bindNewAssociations() protected
```
_bindNewAssociations(Cake\ORM\Query $query, Cake\ORM\Query $surrogate, array<string, mixed> $options): void
```
Applies all attachable associations to `$query` out of the containments found in the `$surrogate` query.
Copies all contained associations from the `$surrogate` query into the passed `$query`. Containments are altered so that they respect the associations chain from which they originated.
#### Parameters
`Cake\ORM\Query` $query the query that will get the associations attached to
`Cake\ORM\Query` $surrogate the query having the containments to be attached
`array<string, mixed>` $options options passed to the method `attachTo`
#### Returns
`void`
### \_camelize() protected
```
_camelize(string $name): string
```
Creates a camelized version of $name
#### Parameters
`string` $name name
#### Returns
`string`
### \_dispatchBeforeFind() protected
```
_dispatchBeforeFind(Cake\ORM\Query $query): void
```
Triggers beforeFind on the target table for the query this association is attaching to
#### Parameters
`Cake\ORM\Query` $query the query this association is attaching itself to
#### Returns
`void`
### \_entityName() protected
```
_entityName(string $name): string
```
Creates the proper entity name (singular) for the specified name
#### Parameters
`string` $name Name
#### Returns
`string`
### \_extractFinder() protected
```
_extractFinder(array|string $finderData): array
```
Helper method to infer the requested finder and its options.
Returns the inferred options from the finder $type.
### Examples:
The following will call the finder 'translations' with the value of the finder as its options: $query->contain(['Comments' => ['finder' => ['translations']]]); $query->contain(['Comments' => ['finder' => ['translations' => []]]]); $query->contain(['Comments' => ['finder' => ['translations' => ['locales' => ['en\_US']]]]]);
#### Parameters
`array|string` $finderData The finder name or an array having the name as key and options as value.
#### Returns
`array`
### \_fixtureName() protected
```
_fixtureName(string $name): string
```
Creates a fixture name
#### Parameters
`string` $name Model class name
#### Returns
`string`
### \_formatAssociationResults() protected
```
_formatAssociationResults(Cake\ORM\Query $query, Cake\ORM\Query $surrogate, array<string, mixed> $options): void
```
Adds a formatter function to the passed `$query` if the `$surrogate` query declares any other formatter. Since the `$surrogate` query correspond to the associated target table, the resulting formatter will be the result of applying the surrogate formatters to only the property corresponding to such table.
#### Parameters
`Cake\ORM\Query` $query the query that will get the formatter applied to
`Cake\ORM\Query` $surrogate the query having formatters for the associated target table.
`array<string, mixed>` $options options passed to the method `attachTo`
#### Returns
`void`
### \_joinCondition() protected
```
_joinCondition(array<string, mixed> $options): arrayCake\Database\Expression\IdentifierExpression>
```
Returns a single or multiple conditions to be appended to the generated join clause for getting the results on the target table.
#### Parameters
`array<string, mixed>` $options list of options passed to attachTo method
#### Returns
`arrayCake\Database\Expression\IdentifierExpression>`
#### Throws
`RuntimeException`
if the number of columns in the foreignKey do not match the number of columns in the target table primaryKey ### \_modelKey() protected
```
_modelKey(string $name): string
```
Creates the proper underscored model key for associations
If the input contains a dot, assume that the right side is the real table name.
#### Parameters
`string` $name Model class name
#### Returns
`string`
### \_modelNameFromKey() protected
```
_modelNameFromKey(string $key): string
```
Creates the proper model name from a foreign key
#### Parameters
`string` $key Foreign key
#### Returns
`string`
### \_options() protected
```
_options(array<string, mixed> $options): void
```
Override this function to initialize any concrete association class, it will get passed the original list of options used in the constructor
#### Parameters
`array<string, mixed>` $options List of options used for initialization
#### Returns
`void`
### \_pluginNamespace() protected
```
_pluginNamespace(string $pluginName): string
```
Return plugin's namespace
#### Parameters
`string` $pluginName Plugin name
#### Returns
`string`
### \_pluginPath() protected
```
_pluginPath(string $pluginName): string
```
Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
#### Parameters
`string` $pluginName Name of the plugin you want ie. DebugKit
#### Returns
`string`
### \_pluralHumanName() protected
```
_pluralHumanName(string $name): string
```
Creates the plural human name used in views
#### Parameters
`string` $name Controller name
#### Returns
`string`
### \_propertyName() protected
```
_propertyName(): string
```
Returns default property name based on association name.
#### Returns
`string`
### \_singularHumanName() protected
```
_singularHumanName(string $name): string
```
Creates the singular human name used in views
#### Parameters
`string` $name Controller name
#### Returns
`string`
### \_singularName() protected
```
_singularName(string $name): string
```
Creates the singular name for use in views.
#### Parameters
`string` $name Name to use
#### Returns
`string`
### \_variableName() protected
```
_variableName(string $name): string
```
Creates the plural variable name for views
#### Parameters
`string` $name Name to use
#### Returns
`string`
### attachTo() public
```
attachTo(Cake\ORM\Query $query, array<string, mixed> $options = []): void
```
Alters a Query object to include the associated target table data in the final result
The options array accept the following keys:
* includeFields: Whether to include target model fields in the result or not
* foreignKey: The name of the field to use as foreign key, if false none will be used
* conditions: array with a list of conditions to filter the join with, this will be merged with any conditions originally configured for this association
* fields: a list of fields in the target table to include in the result
* aliasPath: A dot separated string representing the path of association names followed from the passed query main table to this association.
* propertyPath: A dot separated string representing the path of association properties to be followed from the passed query main entity to this association
* joinType: The SQL join type to use in the query.
* negateMatch: Will append a condition to the passed query for excluding matches. with this association.
#### Parameters
`Cake\ORM\Query` $query the query to be altered to include the target table data
`array<string, mixed>` $options optional Any extra options or overrides to be taken in account
#### Returns
`void`
#### Throws
`RuntimeException`
Unable to build the query or associations. ### canBeJoined() public
```
canBeJoined(array<string, mixed> $options = []): bool
```
Whether this association can be expressed directly in a query join
#### Parameters
`array<string, mixed>` $options optional custom options key that could alter the return value
#### Returns
`bool`
### cascadeDelete() public
```
cascadeDelete(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): bool
```
Handle cascading deletes.
BelongsTo associations are never cleared in a cascading delete scenario.
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity that started the cascaded delete.
`array<string, mixed>` $options optional The options for the original delete.
#### Returns
`bool`
### defaultRowValue() public
```
defaultRowValue(array<string, mixed> $row, bool $joined): array<string, mixed>
```
Returns a modified row after appending a property for this association with the default empty value according to whether the association was joined or fetched externally.
#### Parameters
`array<string, mixed>` $row The row to set a default on.
`bool` $joined Whether the row is a result of a direct join with this association
#### Returns
`array<string, mixed>`
### deleteAll() public
```
deleteAll(Cake\Database\ExpressionInterfaceClosure|array|string|null $conditions): int
```
Proxies the delete operation to the target table's deleteAll method
#### Parameters
`Cake\Database\ExpressionInterfaceClosure|array|string|null` $conditions Conditions to be used, accepts anything Query::where() can take.
#### Returns
`int`
#### See Also
\Cake\ORM\Table::deleteAll() ### eagerLoader() public
```
eagerLoader(array<string, mixed> $options): Closure
```
Eager loads a list of records in the target table that are related to another set of records in the source table. Source records can be specified in two ways: first one is by passing a Query object setup to find on the source table and the other way is by explicitly passing an array of primary key values from the source table.
The required way of passing related source records is controlled by "strategy" When the subquery strategy is used it will require a query on the source table. When using the select strategy, the list of primary keys will be used.
Returns a closure that should be run for each record returned in a specific Query. This callable will be responsible for injecting the fields that are related to each specific passed row.
Options array accepts the following keys:
* query: Query object setup to find the source table records
* keys: List of primary key values from the source table
* foreignKey: The name of the field used to relate both tables
* conditions: List of conditions to be passed to the query where() method
* sort: The direction in which the records should be returned
* fields: List of fields to select from the target table
* contain: List of related tables to eager load associated to the target table
* strategy: The name of strategy to use for finding target table records
* nestKey: The array key under which results will be found when transforming the row
#### Parameters
`array<string, mixed>` $options #### Returns
`Closure`
### exists() public
```
exists(Cake\Database\ExpressionInterfaceClosure|array|string|null $conditions): bool
```
Proxies the operation to the target table's exists method after appending the default conditions for this association
#### Parameters
`Cake\Database\ExpressionInterfaceClosure|array|string|null` $conditions The conditions to use for checking if any record matches.
#### Returns
`bool`
#### See Also
\Cake\ORM\Table::exists() ### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### find() public
```
find(array<string, mixed>|string|null $type = null, array<string, mixed> $options = []): Cake\ORM\Query
```
Proxies the finding operation to the target table's find method and modifies the query accordingly based of this association configuration
#### Parameters
`array<string, mixed>|string|null` $type optional the type of query to perform, if an array is passed, it will be interpreted as the `$options` parameter
`array<string, mixed>` $options optional The options to for the find
#### Returns
`Cake\ORM\Query`
#### See Also
\Cake\ORM\Table::find() ### getBindingKey() public
```
getBindingKey(): array<string>|string
```
Gets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
#### Returns
`array<string>|string`
### getCascadeCallbacks() public
```
getCascadeCallbacks(): bool
```
Gets whether cascaded deletes should also fire callbacks.
#### Returns
`bool`
### getClassName() public
```
getClassName(): string
```
Gets the class name of the target table object.
#### Returns
`string`
### getConditions() public
```
getConditions(): Closure|array
```
Gets a list of conditions to be always included when fetching records from the target association.
#### Returns
`Closure|array`
#### See Also
\Cake\Database\Query::where() for examples on the format of the array ### getDependent() public
```
getDependent(): bool
```
Sets whether the records on the target table are dependent on the source table.
This is primarily used to indicate that records should be removed if the owning record in the source table is deleted.
#### Returns
`bool`
### getFinder() public
```
getFinder(): array|string
```
Gets the default finder to use for fetching rows from the target table.
#### Returns
`array|string`
### getForeignKey() public
```
getForeignKey(): array<string>|string
```
Gets the name of the field representing the foreign key to the target table.
#### Returns
`array<string>|string`
### getJoinType() public
```
getJoinType(): string
```
Gets the type of join to be used when adding the association to a query.
#### Returns
`string`
### getName() public
```
getName(): string
```
Gets the name for this association, usually the alias assigned to the target associated table
#### Returns
`string`
### getProperty() public
```
getProperty(): string
```
Gets the property name that should be filled with data from the target table in the source table record.
#### Returns
`string`
### getSource() public
```
getSource(): Cake\ORM\Table
```
Gets the table instance for the source side of the association.
#### Returns
`Cake\ORM\Table`
### getStrategy() public
```
getStrategy(): string
```
Gets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void.
#### Returns
`string`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### getTarget() public
```
getTarget(): Cake\ORM\Table
```
Gets the table instance for the target side of the association.
#### Returns
`Cake\ORM\Table`
### isOwningSide() public
```
isOwningSide(Cake\ORM\Table $side): bool
```
Returns whether the passed table is the owning side for this association. This means that rows in the 'target' table would miss important or required information if the row in 'source' did not exist.
#### Parameters
`Cake\ORM\Table` $side The potential Table with ownership
#### Returns
`bool`
### requiresKeys() public
```
requiresKeys(array<string, mixed> $options = []): bool
```
Returns true if the eager loading process will require a set of the owning table's binding keys in order to use them as a filter in the finder query.
#### Parameters
`array<string, mixed>` $options optional The options containing the strategy to be used.
#### Returns
`bool`
### saveAssociated() public
```
saveAssociated(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): Cake\Datasource\EntityInterface|false
```
Takes an entity from the source table and looks if there is a field matching the property name for this association. The found entity will be saved on the target table for this association by passing supplied `$options`
#### Parameters
`Cake\Datasource\EntityInterface` $entity an entity from the source table
`array<string, mixed>` $options optional options to be passed to the save method in the target table
#### Returns
`Cake\Datasource\EntityInterface|false`
#### See Also
\Cake\ORM\Table::save() ### setBindingKey() public
```
setBindingKey(array<string>|string $key): $this
```
Sets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
#### Parameters
`array<string>|string` $key the table field or fields to be used to link both tables together
#### Returns
`$this`
### setCascadeCallbacks() public
```
setCascadeCallbacks(bool $cascadeCallbacks): $this
```
Sets whether cascaded deletes should also fire callbacks.
#### Parameters
`bool` $cascadeCallbacks cascade callbacks switch value
#### Returns
`$this`
### setClassName() public
```
setClassName(string $className): $this
```
Sets the class name of the target table object.
#### Parameters
`string` $className Class name to set.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
In case the class name is set after the target table has been resolved, and it doesn't match the target table's class name. ### setConditions() public
```
setConditions(Closure|array $conditions): $this
```
Sets a list of conditions to be always included when fetching records from the target association.
#### Parameters
`Closure|array` $conditions list of conditions to be used
#### Returns
`$this`
#### See Also
\Cake\Database\Query::where() for examples on the format of the array ### setDependent() public
```
setDependent(bool $dependent): $this
```
Sets whether the records on the target table are dependent on the source table.
This is primarily used to indicate that records should be removed if the owning record in the source table is deleted.
If no parameters are passed the current setting is returned.
#### Parameters
`bool` $dependent Set the dependent mode. Use null to read the current state.
#### Returns
`$this`
### setFinder() public
```
setFinder(array|string $finder): $this
```
Sets the default finder to use for fetching rows from the target table.
#### Parameters
`array|string` $finder the finder name to use or array of finder name and option.
#### Returns
`$this`
### setForeignKey() public
```
setForeignKey(array<string>|string $key): $this
```
Sets the name of the field representing the foreign key to the target table.
#### Parameters
`array<string>|string` $key the key or keys to be used to link both tables together
#### Returns
`$this`
### setJoinType() public
```
setJoinType(string $type): $this
```
Sets the type of join to be used when adding the association to a query.
#### Parameters
`string` $type the join type to be used (e.g. INNER)
#### Returns
`$this`
### setName() public
```
setName(string $name): $this
```
Sets the name for this association, usually the alias assigned to the target associated table
#### Parameters
`string` $name Name to be assigned
#### Returns
`$this`
### setProperty() public
```
setProperty(string $name): $this
```
Sets the property name that should be filled with data from the target table in the source table record.
#### Parameters
`string` $name The name of the association property. Use null to read the current value.
#### Returns
`$this`
### setSource() public
```
setSource(Cake\ORM\Table $table): $this
```
Sets the table instance for the source side of the association.
#### Parameters
`Cake\ORM\Table` $table the instance to be assigned as source side
#### Returns
`$this`
### setStrategy() public
```
setStrategy(string $name): $this
```
Sets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void.
#### Parameters
`string` $name The strategy type. Use null to read the current value.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
When an invalid strategy is provided. ### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
### setTarget() public
```
setTarget(Cake\ORM\Table $table): $this
```
Sets the table instance for the target side of the association.
#### Parameters
`Cake\ORM\Table` $table the instance to be assigned as target side
#### Returns
`$this`
### transformRow() public
```
transformRow(array $row, string $nestKey, bool $joined, string|null $targetProperty = null): array
```
Correctly nests a result row associated values into the correct array keys inside the source results.
#### Parameters
`array` $row The row to transform
`string` $nestKey The array key under which the results for this association should be found
`bool` $joined Whether the row is a result of a direct join with this association
`string|null` $targetProperty optional The property name in the source results where the association data shuld be nested in. Will use the default one if not provided.
#### Returns
`array`
### type() public
```
type(): string
```
Get the relationship type.
#### Returns
`string`
### updateAll() public
```
updateAll(array $fields, Cake\Database\ExpressionInterfaceClosure|array|string|null $conditions): int
```
Proxies the update operation to the target table's updateAll method
#### Parameters
`array` $fields A hash of field => new value.
`Cake\Database\ExpressionInterfaceClosure|array|string|null` $conditions Conditions to be used, accepts anything Query::where() can take.
#### Returns
`int`
#### See Also
\Cake\ORM\Table::updateAll() Property Detail
---------------
### $\_bindingKey protected
The field name in the owning side table that is used to match with the foreignKey
#### Type
`array<string>|string|null`
### $\_cascadeCallbacks protected
Whether cascaded deletes should also fire callbacks.
#### Type
`bool`
### $\_className protected
The class name of the target table object
#### Type
`string`
### $\_conditions protected
A list of conditions to be always included when fetching records from the target association
#### Type
`Closure|array`
### $\_dependent protected
Whether the records on the target table are dependent on the source table, often used to indicate that records should be removed if the owning record in the source table is deleted.
#### Type
`bool`
### $\_finder protected
The default finder name to use for fetching rows from the target table With array value, finder name and default options are allowed.
#### Type
`array|string`
### $\_foreignKey protected
The name of the field representing the foreign key to the table to load
#### Type
`array<string>|string`
### $\_joinType protected
The type of join to be used when adding the association to a query
#### Type
`string`
### $\_name protected
Name given to the association, it usually represents the alias assigned to the target associated table
#### Type
`string`
### $\_propertyName protected
The property name that should be filled with data from the target table in the source table record.
#### Type
`string`
### $\_sourceTable protected
Source table instance
#### Type
`Cake\ORM\Table`
### $\_strategy protected
The strategy name to be used to fetch associated records. Some association types might not implement but one strategy to fetch records.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $\_targetTable protected
Target table instance
#### Type
`Cake\ORM\Table`
### $\_validStrategies protected
Valid strategies for this type of association
#### Type
`array<string>`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
| programming_docs |
cakephp Class RecordNotFoundException Class RecordNotFoundException
==============================
Exception raised when a particular record was not found
**Namespace:** [Cake\Datasource\Exception](namespace-cake.datasource.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Class TreePrinter Class TreePrinter
==================
Iterator for flattening elements in a tree structure while adding some visual markers for their relative position in the tree
**Namespace:** [Cake\Collection\Iterator](namespace-cake.collection.iterator)
Property Summary
----------------
* [$\_current](#%24_current) protected `mixed` Cached value for the current iteration element
* [$\_key](#%24_key) protected `callable` A callable to generate the iteration key
* [$\_spacer](#%24_spacer) protected `string` The string to use for prefixing the values according to their depth in the tree.
* [$\_value](#%24_value) protected `callable` A callable to extract the display value
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_createMatcherFilter()](#_createMatcherFilter()) protected
Returns a callable that receives a value and will return whether it matches certain condition.
* ##### [\_extract()](#_extract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
* ##### [\_fetchCurrent()](#_fetchCurrent()) protected
Returns the current iteration element and caches its value
* ##### [\_propertyExtractor()](#_propertyExtractor()) protected
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
* ##### [\_simpleExtract()](#_simpleExtract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path
* ##### [append()](#append()) public
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
* ##### [appendItem()](#appendItem()) public
Append a single item creating a new collection.
* ##### [avg()](#avg()) public
Returns the average of all the values extracted with $path or of this collection.
* ##### [buffered()](#buffered()) public
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
* ##### [cartesianProduct()](#cartesianProduct()) public
Create a new collection that is the cartesian product of the current collection
* ##### [chunk()](#chunk()) public
Breaks the collection into smaller arrays of the given size.
* ##### [chunkWithKeys()](#chunkWithKeys()) public
Breaks the collection into smaller arrays of the given size.
* ##### [combine()](#combine()) public
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
* ##### [compile()](#compile()) public
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
* ##### [contains()](#contains()) public
Returns true if $value is present in this collection. Comparisons are made both by value and type.
* ##### [count()](#count()) public
Returns the amount of elements in the collection.
* ##### [countBy()](#countBy()) public
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
* ##### [countKeys()](#countKeys()) public
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
* ##### [current()](#current()) public
Returns the current iteration value
* ##### [each()](#each()) public
Applies a callback to the elements in this collection.
* ##### [every()](#every()) public
Returns true if all values in this collection pass the truth test provided in the callback.
* ##### [extract()](#extract()) public
Returns a new collection containing the column or property value found in each of the elements.
* ##### [filter()](#filter()) public
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
* ##### [first()](#first()) public
Returns the first result in this collection
* ##### [firstMatch()](#firstMatch()) public
Returns the first result matching all the key-value pairs listed in conditions.
* ##### [groupBy()](#groupBy()) public
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
* ##### [indexBy()](#indexBy()) public
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
* ##### [insert()](#insert()) public
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
* ##### [isEmpty()](#isEmpty()) public
Returns whether there are elements in this collection
* ##### [jsonSerialize()](#jsonSerialize()) public
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
* ##### [key()](#key()) public
Returns the current iteration key
* ##### [last()](#last()) public
Returns the last result in this collection
* ##### [lazy()](#lazy()) public
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
* ##### [listNested()](#listNested()) public
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
* ##### [map()](#map()) public
Returns another collection after modifying each of the values in this one using the provided callable.
* ##### [match()](#match()) public
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
* ##### [max()](#max()) public
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [median()](#median()) public
Returns the median of all the values extracted with $path or of this collection.
* ##### [min()](#min()) public
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [nest()](#nest()) public
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
* ##### [newCollection()](#newCollection()) protected
Returns a new collection.
* ##### [next()](#next()) public
Advances the cursor one position
* ##### [optimizeUnwrap()](#optimizeUnwrap()) protected
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
* ##### [prepend()](#prepend()) public
Prepend a set of items to a collection creating a new collection
* ##### [prependItem()](#prependItem()) public
Prepend a single item creating a new collection.
* ##### [reduce()](#reduce()) public
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
* ##### [reject()](#reject()) public
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
* ##### [sample()](#sample()) public
Returns a new collection with maximum $size random elements from this collection
* ##### [shuffle()](#shuffle()) public
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
* ##### [skip()](#skip()) public
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
* ##### [some()](#some()) public
Returns true if any of the values in this collection pass the truth test provided in the callback.
* ##### [sortBy()](#sortBy()) public
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
* ##### [stopWhen()](#stopWhen()) public
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
* ##### [sumOf()](#sumOf()) public
Returns the total sum of all the values extracted with $matcher or of this collection.
* ##### [take()](#take()) public
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
* ##### [takeLast()](#takeLast()) public
Returns the last N elements of a collection
* ##### [through()](#through()) public
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
* ##### [toArray()](#toArray()) public
Returns an array representation of the results
* ##### [toList()](#toList()) public
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
* ##### [transpose()](#transpose()) public
Transpose rows and columns into columns and rows
* ##### [unfold()](#unfold()) public
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
* ##### [unwrap()](#unwrap()) public
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
* ##### [zip()](#zip()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
* ##### [zipWith()](#zipWith()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
Method Detail
-------------
### \_\_construct() public
```
__construct(RecursiveIterator $items, callable|string $valuePath, callable|string $keyPath, string $spacer, int $mode = RecursiveIteratorIterator::SELF_FIRST)
```
Constructor
#### Parameters
`RecursiveIterator` $items The iterator to flatten.
`callable|string` $valuePath The property to extract or a callable to return the display value.
`callable|string` $keyPath The property to use as iteration key or a callable returning the key value.
`string` $spacer The string to use for prefixing the values according to their depth in the tree.
`int` $mode optional Iterator mode.
### \_createMatcherFilter() protected
```
_createMatcherFilter(array $conditions): Closure
```
Returns a callable that receives a value and will return whether it matches certain condition.
#### Parameters
`array` $conditions A key-value list of conditions to match where the key is the property path to get from the current item and the value is the value to be compared the item with.
#### Returns
`Closure`
### \_extract() protected
```
_extract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### \_fetchCurrent() protected
```
_fetchCurrent(): mixed
```
Returns the current iteration element and caches its value
#### Returns
`mixed`
### \_propertyExtractor() protected
```
_propertyExtractor(callable|string $path): callable
```
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
#### Parameters
`callable|string` $path A dot separated path of column to follow so that the final one can be returned or a callable that will take care of doing that.
#### Returns
`callable`
### \_simpleExtract() protected
```
_simpleExtract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### append() public
```
append(iterable $items): self
```
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
#### Parameters
`iterable` $items #### Returns
`self`
### appendItem() public
```
appendItem(mixed $item, mixed $key = null): self
```
Append a single item creating a new collection.
#### Parameters
`mixed` $item `mixed` $key optional #### Returns
`self`
### avg() public
```
avg(callable|string|null $path = null): float|int|null
```
Returns the average of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->avg('invoice.total');
// Total: 150
$total = (new Collection([1, 2, 3]))->avg();
// Total: 2
```
The average of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int|null`
### buffered() public
```
buffered(): self
```
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
This can also be used to make any non-rewindable iterator rewindable.
#### Returns
`self`
### cartesianProduct() public
```
cartesianProduct(callable|null $operation = null, callable|null $filter = null): Cake\Collection\CollectionInterface
```
Create a new collection that is the cartesian product of the current collection
In order to create a carteisan product a collection must contain a single dimension of data.
### Example
```
$collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
$result = $collection->cartesianProduct()->toArray();
$expected = [
['A', 1],
['A', 2],
['A', 3],
['B', 1],
['B', 2],
['B', 3],
['C', 1],
['C', 2],
['C', 3],
];
```
#### Parameters
`callable|null` $operation optional A callable that allows you to customize the product result.
`callable|null` $filter optional A filtering callback that must return true for a result to be part of the final results.
#### Returns
`Cake\Collection\CollectionInterface`
#### Throws
`LogicException`
### chunk() public
```
chunk(int $chunkSize): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
$chunked = (new Collection($items))->chunk(3)->toList();
// Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
```
#### Parameters
`int` $chunkSize #### Returns
`self`
### chunkWithKeys() public
```
chunkWithKeys(int $chunkSize, bool $keepKeys = true): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
$chunked = (new Collection($items))->chunkWithKeys(3)->toList();
// Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
```
#### Parameters
`int` $chunkSize `bool` $keepKeys optional #### Returns
`self`
### combine() public
```
combine(callable|string $keyPath, callable|string $valuePath, callable|string|null $groupPath = null): self
```
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
### Examples:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent' => 'a'],
['id' => 2, 'name' => 'bar', 'parent' => 'b'],
['id' => 3, 'name' => 'baz', 'parent' => 'a'],
];
$combined = (new Collection($items))->combine('id', 'name');
// Result will look like this when converted to array
[
1 => 'foo',
2 => 'bar',
3 => 'baz',
];
$combined = (new Collection($items))->combine('id', 'name', 'parent');
// Result will look like this when converted to array
[
'a' => [1 => 'foo', 3 => 'baz'],
'b' => [2 => 'bar']
];
```
#### Parameters
`callable|string` $keyPath `callable|string` $valuePath `callable|string|null` $groupPath optional #### Returns
`self`
### compile() public
```
compile(bool $keepKeys = true): self
```
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
A common use case is to re-use the same variable for calculating different data. In those cases it may be helpful and more performant to first compile a collection and then apply more operations to it.
### Example:
```
$collection->map($mapper)->sortBy('age')->extract('name');
$compiled = $collection->compile();
$isJohnHere = $compiled->some($johnMatcher);
$allButJohn = $compiled->filter($johnMatcher);
```
In the above example, had the collection not been compiled before, the iterations for `map`, `sortBy` and `extract` would've been executed twice: once for getting `$isJohnHere` and once for `$allButJohn`
You can think of this method as a way to create save points for complex calculations in a collection.
#### Parameters
`bool` $keepKeys optional #### Returns
`self`
### contains() public
```
contains(mixed $value): bool
```
Returns true if $value is present in this collection. Comparisons are made both by value and type.
#### Parameters
`mixed` $value #### Returns
`bool`
### count() public
```
count(): int
```
Returns the amount of elements in the collection.
WARNINGS:
---------
### Will change the current position of the iterator:
Calling this method at the same time that you are iterating this collections, for example in a foreach, will result in undefined behavior. Avoid doing this.
### Consumes all elements for NoRewindIterator collections:
On certain type of collections, calling this method may render unusable afterwards. That is, you may not be able to get elements out of it, or to iterate on it anymore.
Specifically any collection wrapping a Generator (a function with a yield statement) or a unbuffered database cursor will not accept any other function calls after calling `count()` on it.
Create a new collection with `buffered()` method to overcome this problem.
### Can report more elements than unique keys:
Any collection constructed by appending collections together, or by having internal iterators returning duplicate keys, will report a larger amount of elements using this functions than the final amount of elements when converting the collections to a keyed array. This is because duplicate keys will be collapsed into a single one in the final array, whereas this count method is only concerned by the amount of elements after converting it to a plain list.
If you need the count of elements after taking the keys in consideration (the count of unique keys), you can call `countKeys()`
#### Returns
`int`
### countBy() public
```
countBy(callable|string $path): self
```
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->countBy('parent_id');
// Or
$group = (new Collection($items))->countBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => 2,
11 => 1
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### countKeys() public
```
countKeys(): int
```
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
This method comes with a number of caveats. Please refer to `CollectionInterface::count()` for details.
#### Returns
`int`
### current() public
```
current(): string
```
Returns the current iteration value
#### Returns
`string`
### each() public
```
each(callable $callback): $this
```
Applies a callback to the elements in this collection.
### Example:
```
$collection = (new Collection($items))->each(function ($value, $key) {
echo "Element $key: $value";
});
```
#### Parameters
`callable` $callback #### Returns
`$this`
### every() public
```
every(callable $callback): bool
```
Returns true if all values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$overTwentyOne = (new Collection([24, 45, 60, 15]))->every(function ($value, $key) {
return $value > 21;
});
```
Empty collections always return true.
#### Parameters
`callable` $callback #### Returns
`bool`
### extract() public
```
extract(callable|string $path): self
```
Returns a new collection containing the column or property value found in each of the elements.
The matcher can be a string with a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection, that position is filled with null.
### Example:
Extract the user name for all comments in the array:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->extract('comment.user.name');
// Result will look like this when converted to array
['Mark', 'Renan']
```
It is also possible to extract a flattened collection out of nested properties
```
$items = [
['comment' => ['votes' => [['value' => 1], ['value' => 2], ['value' => 3]]],
['comment' => ['votes' => [['value' => 4]]
];
$extracted = (new Collection($items))->extract('comment.votes.{*}.value');
// Result will contain
[1, 2, 3, 4]
```
#### Parameters
`callable|string` $path #### Returns
`self`
### filter() public
```
filter(callable|null $callback = null): self
```
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering odd numbers in an array, at the end only the value 2 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->filter(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable|null` $callback optional #### Returns
`self`
### first() public
```
first(): mixed
```
Returns the first result in this collection
#### Returns
`mixed`
### firstMatch() public
```
firstMatch(array $conditions): mixed
```
Returns the first result matching all the key-value pairs listed in conditions.
#### Parameters
`array` $conditions #### Returns
`mixed`
### groupBy() public
```
groupBy(callable|string $path): self
```
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->groupBy('parent_id');
// Or
$group = (new Collection($items))->groupBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
],
11 => [
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
]
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### indexBy() public
```
indexBy(callable|string $path): self
```
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo'],
['id' => 2, 'name' => 'bar'],
['id' => 3, 'name' => 'baz'],
];
$indexed = (new Collection($items))->indexBy('id');
// Or
$indexed = (new Collection($items))->indexBy(function ($e) {
return $e['id'];
});
// Result will look like this when converted to array
[
1 => ['id' => 1, 'name' => 'foo'],
3 => ['id' => 3, 'name' => 'baz'],
2 => ['id' => 2, 'name' => 'bar'],
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### insert() public
```
insert(string $path, mixed $values): self
```
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
The $path can be a string with a property name or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection as part of the path, the element will be kept unchanged.
### Example:
Insert ages into a collection containing users:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
];
$ages = [25, 28];
$inserted = (new Collection($items))->insert('comment.user.age', $ages);
// Result will look like this when converted to array
[
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
];
```
#### Parameters
`string` $path `mixed` $values #### Returns
`self`
### isEmpty() public
```
isEmpty(): bool
```
Returns whether there are elements in this collection
### Example:
```
$items [1, 2, 3];
(new Collection($items))->isEmpty(); // false
```
```
(new Collection([]))->isEmpty(); // true
```
#### Returns
`bool`
### jsonSerialize() public
```
jsonSerialize(): array
```
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
Part of JsonSerializable interface.
#### Returns
`array`
### key() public
```
key(): mixed
```
Returns the current iteration key
#### Returns
`mixed`
### last() public
```
last(): mixed
```
Returns the last result in this collection
#### Returns
`mixed`
### lazy() public
```
lazy(): self
```
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
A lazy collection can only be iterated once. A second attempt results in an error.
#### Returns
`self`
### listNested() public
```
listNested(string|int $order = 'desc', callable|string $nestingKey = 'children'): self
```
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
By default all elements in the tree following a Depth First Search will be returned, that is, elements from the top parent to the leaves for each branch.
It is possible to return all elements from bottom to top using a Breadth First Search approach by passing the '$dir' parameter with 'asc'. That is, it will return all elements for the same tree depth first and from bottom to top.
Finally, you can specify to only get a collection with the leaf nodes in the tree structure. You do so by passing 'leaves' in the first argument.
The possible values for the first argument are aliases for the following constants and it is valid to pass those instead of the alias:
* desc: RecursiveIteratorIterator::SELF\_FIRST
* asc: RecursiveIteratorIterator::CHILD\_FIRST
* leaves: RecursiveIteratorIterator::LEAVES\_ONLY
### Example:
```
$collection = new Collection([
['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
['id' => 4, 'children' => [['id' => 5]]]
]);
$flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
```
#### Parameters
`string|int` $order optional `callable|string` $nestingKey optional #### Returns
`self`
### map() public
```
map(callable $callback): self
```
Returns another collection after modifying each of the values in this one using the provided callable.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Getting a collection of booleans where true indicates if a person is female:
```
$collection = (new Collection($people))->map(function ($person, $key) {
return $person->gender === 'female';
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### match() public
```
match(array $conditions): self
```
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
### Example:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->match(['user.name' => 'Renan']);
// Result will look like this when converted to array
[
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
]
```
#### Parameters
`array` $conditions #### Returns
`self`
### max() public
```
max(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$max = $collection->max('age');
$max = $collection->max('user.salary');
$max = $collection->max(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $max->name;
```
#### Parameters
`callable|string` $path `int` $sort optional #### Returns
`mixed`
### median() public
```
median(callable|string|null $path = null): float|int|null
```
Returns the median of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 400]],
['invoice' => ['total' => 500]]
['invoice' => ['total' => 100]]
['invoice' => ['total' => 333]]
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->median('invoice.total');
// Total: 333
$total = (new Collection([1, 2, 3, 4]))->median();
// Total: 2.5
```
The median of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int|null`
### min() public
```
min(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$min = $collection->min('age');
$min = $collection->min('user.salary');
$min = $collection->min(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $min->name;
```
#### Parameters
`callable|string` $path `int` $sort optional #### Returns
`mixed`
### nest() public
```
nest(callable|string $idPath, callable|string $parentPath, string $nestingKey = 'children'): self
```
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
#### Parameters
`callable|string` $idPath `callable|string` $parentPath `string` $nestingKey optional #### Returns
`self`
### newCollection() protected
```
newCollection(mixed ...$args): Cake\Collection\CollectionInterface
```
Returns a new collection.
Allows classes which use this trait to determine their own type of returned collection interface
#### Parameters
`mixed` ...$args Constructor arguments.
#### Returns
`Cake\Collection\CollectionInterface`
### next() public
```
next(): void
```
Advances the cursor one position
#### Returns
`void`
### optimizeUnwrap() protected
```
optimizeUnwrap(): iterable
```
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
#### Returns
`iterable`
### prepend() public
```
prepend(mixed $items): self
```
Prepend a set of items to a collection creating a new collection
#### Parameters
`mixed` $items #### Returns
`self`
### prependItem() public
```
prependItem(mixed $item, mixed $key = null): self
```
Prepend a single item creating a new collection.
#### Parameters
`mixed` $item `mixed` $key optional #### Returns
`self`
### reduce() public
```
reduce(callable $callback, mixed $initial = null): mixed
```
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
#### Parameters
`callable` $callback `mixed` $initial optional #### Returns
`mixed`
### reject() public
```
reject(callable $callback): self
```
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering even numbers in an array, at the end only values 1 and 3 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->reject(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### sample() public
```
sample(int $length = 10): self
```
Returns a new collection with maximum $size random elements from this collection
#### Parameters
`int` $length optional #### Returns
`self`
### shuffle() public
```
shuffle(): self
```
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
#### Returns
`self`
### skip() public
```
skip(int $length): self
```
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
#### Parameters
`int` $length #### Returns
`self`
### some() public
```
some(callable $callback): bool
```
Returns true if any of the values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$hasYoungPeople = (new Collection([24, 45, 15]))->some(function ($value, $key) {
return $value < 21;
});
```
#### Parameters
`callable` $callback #### Returns
`bool`
### sortBy() public
```
sortBy(callable|string $path, int $order = \SORT_DESC, int $sort = \SORT_NUMERIC): self
```
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
The callback will receive as its first argument each of the elements in $items, the value returned by the callback will be used as the value for sorting such element. Please note that the callback function could be called more than once per element.
### Example:
```
$items = $collection->sortBy(function ($user) {
return $user->age;
});
// alternatively
$items = $collection->sortBy('age');
// or use a property path
$items = $collection->sortBy('department.name');
// output all user name order by their age in descending order
foreach ($items as $user) {
echo $user->name;
}
```
#### Parameters
`callable|string` $path `int` $order optional `int` $sort optional #### Returns
`self`
### stopWhen() public
```
stopWhen(callable|array $condition): self
```
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
This is handy for dealing with infinite iterators or any generator that could start returning invalid elements at a certain point. For example, when reading lines from a file stream you may want to stop the iteration after a certain value is reached.
### Example:
Get an array of lines in a CSV file until the timestamp column is less than a date
```
$lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
return (new DateTime($value))->format('Y') < 2012;
})
->toArray();
```
Get elements until the first unapproved message is found:
```
$comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
```
#### Parameters
`callable|array` $condition #### Returns
`self`
### sumOf() public
```
sumOf(callable|string|null $path = null): float|int
```
Returns the total sum of all the values extracted with $matcher or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->sumOf('invoice.total');
// Total: 300
$total = (new Collection([1, 2, 3]))->sumOf();
// Total: 6
```
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int`
### take() public
```
take(int $length = 1, int $offset = 0): self
```
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
#### Parameters
`int` $length optional `int` $offset optional #### Returns
`self`
### takeLast() public
```
takeLast(int $length): self
```
Returns the last N elements of a collection
### Example:
```
$items = [1, 2, 3, 4, 5];
$last = (new Collection($items))->takeLast(3);
// Result will look like this when converted to array
[3, 4, 5];
```
#### Parameters
`int` $length #### Returns
`self`
### through() public
```
through(callable $callback): self
```
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
### Example:
```
$items = [1, 2, 3];
$decorated = (new Collection($items))->through(function ($collection) {
return new MyCustomCollection($collection);
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### toArray() public
```
toArray(bool $keepKeys = true): array
```
Returns an array representation of the results
#### Parameters
`bool` $keepKeys optional #### Returns
`array`
### toList() public
```
toList(): array
```
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
#### Returns
`array`
### transpose() public
```
transpose(): Cake\Collection\CollectionInterface
```
Transpose rows and columns into columns and rows
### Example:
```
$items = [
['Products', '2012', '2013', '2014'],
['Product A', '200', '100', '50'],
['Product B', '300', '200', '100'],
['Product C', '400', '300', '200'],
]
$transpose = (new Collection($items))->transpose()->toList();
// Returns
// [
// ['Products', 'Product A', 'Product B', 'Product C'],
// ['2012', '200', '300', '400'],
// ['2013', '100', '200', '300'],
// ['2014', '50', '100', '200'],
// ]
```
#### Returns
`Cake\Collection\CollectionInterface`
#### Throws
`LogicException`
### unfold() public
```
unfold(callable|null $callback = null): self
```
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
The transformer function will receive the value and the key for each of the items in the collection, in that order, and it must return an array or a Traversable object that can be concatenated to the final result.
If no transformer function is passed, an "identity" function will be used. This is useful when each of the elements in the source collection are lists of items to be appended one after another.
### Example:
```
$items [[1, 2, 3], [4, 5]];
$unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
```
Using a transformer
```
$items [1, 2, 3];
$allItems = (new Collection($items))->unfold(function ($page) {
return $service->fetchPage($page)->toArray();
});
```
#### Parameters
`callable|null` $callback optional #### Returns
`self`
### unwrap() public
```
unwrap(): Traversable
```
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
#### Returns
`Traversable`
### zip() public
```
zip(iterable $items): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
### Example:
```
$collection = new Collection([1, 2]);
$collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
```
#### Parameters
`iterable` $items #### Returns
`self`
### zipWith() public
```
zipWith(iterable $items, callable $callback): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
The resulting element will be the return value of the $callable function.
### Example:
```
$collection = new Collection([1, 2]);
$zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
return array_sum($args);
});
$zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
```
#### Parameters
`iterable` $items `callable` $callback #### Returns
`self`
Property Detail
---------------
### $\_current protected
Cached value for the current iteration element
#### Type
`mixed`
### $\_key protected
A callable to generate the iteration key
#### Type
`callable`
### $\_spacer protected
The string to use for prefixing the values according to their depth in the tree.
#### Type
`string`
### $\_value protected
A callable to extract the display value
#### Type
`callable`
| programming_docs |
cakephp Class Helper Class Helper
=============
Abstract base class for all other Helpers in CakePHP. Provides common methods and features.
### Callback methods
Helpers support a number of callback methods. These callbacks allow you to hook into the various view lifecycle events and either modify existing view content or perform other application specific logic. The events are not implemented by this base class, as implementing a callback method subscribes a helper to the related event. The callback methods are as follows:
* `beforeRender(EventInterface $event, $viewFile)` - beforeRender is called before the view file is rendered.
* `afterRender(EventInterface $event, $viewFile)` - afterRender is called after the view file is rendered but before the layout has been rendered.
* beforeLayout(EventInterface $event, $layoutFile)` - beforeLayout is called before the layout is rendered.
* `afterLayout(EventInterface $event, $layoutFile)` - afterLayout is called after the layout has rendered.
* `beforeRenderFile(EventInterface $event, $viewFile)` - Called before any view fragment is rendered.
* `afterRenderFile(EventInterface $event, $viewFile, $content)` - Called after any view fragment is rendered. If a listener returns a non-null value, the output of the rendered file will be set to that.
**Namespace:** [Cake\View](namespace-cake.view)
Property Summary
----------------
* [$\_View](#%24_View) protected `Cake\View\View` The View instance this helper is attached to
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this helper.
* [$\_helperMap](#%24_helperMap) protected `array<string, array>` A helper lookup table used to lazy load helper objects.
* [$helpers](#%24helpers) protected `array` List of helpers used by this helper
Method Summary
--------------
* ##### [\_\_call()](#__call()) public
Provide non fatal errors on missing method calls.
* ##### [\_\_construct()](#__construct()) public
Default Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_get()](#__get()) public
Lazy loads helpers.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_confirm()](#_confirm()) protected
Returns a string to be used as onclick handler for confirm dialogs.
* ##### [addClass()](#addClass()) public
Adds the given class to the element options
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getView()](#getView()) public
Get the view instance this helper is bound to.
* ##### [implementedEvents()](#implementedEvents()) public
Get the View callbacks this helper is interested in.
* ##### [initialize()](#initialize()) public
Constructor hook method.
* ##### [setConfig()](#setConfig()) public
Sets the config.
Method Detail
-------------
### \_\_call() public
```
__call(string $method, array $params): mixed|void
```
Provide non fatal errors on missing method calls.
#### Parameters
`string` $method Method to invoke
`array` $params Array of params for the method.
#### Returns
`mixed|void`
### \_\_construct() public
```
__construct(Cake\View\View $view, array<string, mixed> $config = [])
```
Default Constructor
#### Parameters
`Cake\View\View` $view The View this helper is being attached to.
`array<string, mixed>` $config optional Configuration settings for the helper.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): Cake\View\Helper|null|void
```
Lazy loads helpers.
#### Parameters
`string` $name Name of the property being accessed.
#### Returns
`Cake\View\Helper|null|void`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_confirm() protected
```
_confirm(string $okCode, string $cancelCode): string
```
Returns a string to be used as onclick handler for confirm dialogs.
#### Parameters
`string` $okCode Code to be executed after user chose 'OK'
`string` $cancelCode Code to be executed after user chose 'Cancel'
#### Returns
`string`
### addClass() public
```
addClass(array<string, mixed> $options, string $class, string $key = 'class'): array<string, mixed>
```
Adds the given class to the element options
#### Parameters
`array<string, mixed>` $options Array options/attributes to add a class to
`string` $class The class name being added.
`string` $key optional the key to use for class. Defaults to `'class'`.
#### Returns
`array<string, mixed>`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getView() public
```
getView(): Cake\View\View
```
Get the view instance this helper is bound to.
#### Returns
`Cake\View\View`
### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Get the View callbacks this helper is interested in.
By defining one of the callback methods a helper is assumed to be interested in the related event.
Override this method if you need to add non-conventional event listeners. Or if you want helpers to listen to non-standard events.
#### Returns
`array<string, mixed>`
### initialize() public
```
initialize(array<string, mixed> $config): void
```
Constructor hook method.
Implement this method to avoid having to overwrite the constructor and call parent.
#### Parameters
`array<string, mixed>` $config The configuration settings provided to this helper.
#### Returns
`void`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. Property Detail
---------------
### $\_View protected
The View instance this helper is attached to
#### Type
`Cake\View\View`
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this helper.
#### Type
`array<string, mixed>`
### $\_helperMap protected
A helper lookup table used to lazy load helper objects.
#### Type
`array<string, array>`
### $helpers protected
List of helpers used by this helper
#### Type
`array`
cakephp Class ShellDispatcher Class ShellDispatcher
======================
Shell dispatcher handles dispatching CLI commands.
Consult /bin/cake.php for how this class is used in practice.
**Namespace:** [Cake\Console](namespace-cake.console)
**Deprecated:** 3.6.0 ShellDispatcher and Shell will be removed in 5.0
Property Summary
----------------
* [$\_aliases](#%24_aliases) protected static `array<string, string>` List of connected aliases.
* [$args](#%24args) public `array` Contains arguments parsed from the command line.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_bootstrap()](#_bootstrap()) protected
Initializes the environment and loads the CakePHP core.
* ##### [\_createShell()](#_createShell()) protected
Create the given shell name, and set the plugin property
* ##### [\_dispatch()](#_dispatch()) protected
Dispatch a request.
* ##### [\_handleAlias()](#_handleAlias()) protected
If the input matches an alias, return the aliased shell name
* ##### [\_initEnvironment()](#_initEnvironment()) protected
Defines current working environment.
* ##### [\_shellExists()](#_shellExists()) protected
Check if a shell class exists for the given name.
* ##### [addShortPluginAliases()](#addShortPluginAliases()) public
For all loaded plugins, add a short alias
* ##### [alias()](#alias()) public static
Add an alias for a shell command.
* ##### [dispatch()](#dispatch()) public
Dispatches a CLI request
* ##### [findShell()](#findShell()) public
Get shell to use, either plugin shell or application shell
* ##### [help()](#help()) public
Shows console help. Performs an internal dispatch to the CommandList Shell
* ##### [resetAliases()](#resetAliases()) public static
Clear any aliases that have been set.
* ##### [run()](#run()) public static
Run the dispatcher
* ##### [shiftArgs()](#shiftArgs()) public
Removes first argument and shifts other arguments up
* ##### [version()](#version()) public
Prints the currently installed version of CakePHP. Performs an internal dispatch to the CommandList Shell
Method Detail
-------------
### \_\_construct() public
```
__construct(array $args = [], bool $bootstrap = true)
```
Constructor
The execution of the script is stopped after dispatching the request with a status code of either 0 or 1 according to the result of the dispatch.
#### Parameters
`array` $args optional the argv from PHP
`bool` $bootstrap optional Should the environment be bootstrapped.
### \_bootstrap() protected
```
_bootstrap(): void
```
Initializes the environment and loads the CakePHP core.
#### Returns
`void`
### \_createShell() protected
```
_createShell(string $className, string $shortName): Cake\Console\Shell
```
Create the given shell name, and set the plugin property
#### Parameters
`string` $className The class name to instantiate
`string` $shortName The plugin-prefixed shell name
#### Returns
`Cake\Console\Shell`
### \_dispatch() protected
```
_dispatch(array $extra = []): int|bool|null
```
Dispatch a request.
#### Parameters
`array` $extra optional Extra parameters that you can manually pass to the Shell to be dispatched. Built-in extra parameter is :
#### Returns
`int|bool|null`
#### Throws
`Cake\Console\Exception\MissingShellMethodException`
### \_handleAlias() protected
```
_handleAlias(string $shell): string
```
If the input matches an alias, return the aliased shell name
#### Parameters
`string` $shell Optionally the name of a plugin or alias
#### Returns
`string`
### \_initEnvironment() protected
```
_initEnvironment(): void
```
Defines current working environment.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
### \_shellExists() protected
```
_shellExists(string $shell): string|null
```
Check if a shell class exists for the given name.
#### Parameters
`string` $shell The shell name to look for.
#### Returns
`string|null`
### addShortPluginAliases() public
```
addShortPluginAliases(): array
```
For all loaded plugins, add a short alias
This permits a plugin which implements a shell of the same name to be accessed Using the shell name alone
#### Returns
`array`
### alias() public static
```
alias(string $short, string|null $original = null): string|null
```
Add an alias for a shell command.
Aliases allow you to call shells by alternate names. This is most useful when dealing with plugin shells that you want to have shorter names for.
If you re-use an alias the last alias set will be the one available.
### Usage
Aliasing a shell named ClassName:
```
$this->alias('alias', 'ClassName');
```
Getting the original name for a given alias:
```
$this->alias('alias');
```
#### Parameters
`string` $short The new short name for the shell.
`string|null` $original optional The original full name for the shell.
#### Returns
`string|null`
### dispatch() public
```
dispatch(array $extra = []): int
```
Dispatches a CLI request
Converts a shell command result into an exit code. Null/True are treated as success. All other return values are an error.
#### Parameters
`array` $extra optional Extra parameters that you can manually pass to the Shell to be dispatched. Built-in extra parameter is :
#### Returns
`int`
### findShell() public
```
findShell(string $shell): Cake\Console\Shell
```
Get shell to use, either plugin shell or application shell
All paths in the loaded shell paths are searched, handles alias dereferencing
#### Parameters
`string` $shell Optionally the name of a plugin
#### Returns
`Cake\Console\Shell`
#### Throws
`Cake\Console\Exception\MissingShellException`
when errors are encountered. ### help() public
```
help(): void
```
Shows console help. Performs an internal dispatch to the CommandList Shell
#### Returns
`void`
### resetAliases() public static
```
resetAliases(): void
```
Clear any aliases that have been set.
#### Returns
`void`
### run() public static
```
run(array $argv, array $extra = []): int
```
Run the dispatcher
#### Parameters
`array` $argv The argv from PHP
`array` $extra optional Extra parameters
#### Returns
`int`
### shiftArgs() public
```
shiftArgs(): mixed
```
Removes first argument and shifts other arguments up
#### Returns
`mixed`
### version() public
```
version(): void
```
Prints the currently installed version of CakePHP. Performs an internal dispatch to the CommandList Shell
#### Returns
`void`
Property Detail
---------------
### $\_aliases protected static
List of connected aliases.
#### Type
`array<string, string>`
### $args public
Contains arguments parsed from the command line.
#### Type
`array`
cakephp Class JsonType Class JsonType
===============
JSON type converter.
Use to convert JSON data between PHP and the database types.
**Namespace:** [Cake\Database\Type](namespace-cake.database.type)
Property Summary
----------------
* [$\_encodingOptions](#%24_encodingOptions) protected `int`
* [$\_name](#%24_name) protected `string|null` Identifier name for this type
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getBaseType()](#getBaseType()) public
Returns the base type name that this class is inheriting.
* ##### [getName()](#getName()) public
Returns type identifier name for this object.
* ##### [manyToPHP()](#manyToPHP()) public
Returns an array of the values converted to the PHP representation of this type.
* ##### [marshal()](#marshal()) public
Marshals request data into a JSON compatible structure.
* ##### [newId()](#newId()) public
Generate a new primary key value for a given type.
* ##### [setEncodingOptions()](#setEncodingOptions()) public
Set json\_encode options.
* ##### [toDatabase()](#toDatabase()) public
Convert a value data into a JSON string
* ##### [toPHP()](#toPHP()) public
Casts given value from a database type to a PHP equivalent.
* ##### [toStatement()](#toStatement()) public
Get the correct PDO binding type for string data.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $name = null)
```
Constructor
#### Parameters
`string|null` $name optional The name identifying this type
### getBaseType() public
```
getBaseType(): string|null
```
Returns the base type name that this class is inheriting.
This is useful when extending base type for adding extra functionality, but still want the rest of the framework to use the same assumptions it would do about the base type it inherits from.
#### Returns
`string|null`
### getName() public
```
getName(): string|null
```
Returns type identifier name for this object.
#### Returns
`string|null`
### manyToPHP() public
```
manyToPHP(array $values, array<string> $fields, Cake\Database\DriverInterface $driver): array<string, mixed>
```
Returns an array of the values converted to the PHP representation of this type.
#### Parameters
`array` $values `array<string>` $fields `Cake\Database\DriverInterface` $driver #### Returns
`array<string, mixed>`
### marshal() public
```
marshal(mixed $value): mixed
```
Marshals request data into a JSON compatible structure.
Most useful for converting request data into PHP objects, that make sense for the rest of the ORM/Database layers.
#### Parameters
`mixed` $value The value to convert.
#### Returns
`mixed`
### newId() public
```
newId(): mixed
```
Generate a new primary key value for a given type.
This method can be used by types to create new primary key values when entities are inserted.
#### Returns
`mixed`
### setEncodingOptions() public
```
setEncodingOptions(int $options): $this
```
Set json\_encode options.
#### Parameters
`int` $options Encoding flags. Use JSON\_\* flags. Set `0` to reset.
#### Returns
`$this`
#### See Also
https://www.php.net/manual/en/function.json-encode.php ### toDatabase() public
```
toDatabase(mixed $value, Cake\Database\DriverInterface $driver): string|null
```
Convert a value data into a JSON string
#### Parameters
`mixed` $value The value to convert.
`Cake\Database\DriverInterface` $driver The driver instance to convert with.
#### Returns
`string|null`
#### Throws
`InvalidArgumentException`
### toPHP() public
```
toPHP(mixed $value, Cake\Database\DriverInterface $driver): array|string|null
```
Casts given value from a database type to a PHP equivalent.
#### Parameters
`mixed` $value The value to convert.
`Cake\Database\DriverInterface` $driver The driver instance to convert with.
#### Returns
`array|string|null`
### toStatement() public
```
toStatement(mixed $value, Cake\Database\DriverInterface $driver): int
```
Get the correct PDO binding type for string data.
#### Parameters
`mixed` $value The value being bound.
`Cake\Database\DriverInterface` $driver The driver.
#### Returns
`int`
Property Detail
---------------
### $\_encodingOptions protected
#### Type
`int`
### $\_name protected
Identifier name for this type
#### Type
`string|null`
| programming_docs |
cakephp Class ConsoleInputOption Class ConsoleInputOption
=========================
An object to represent a single option used in the command line. ConsoleOptionParser creates these when you use addOption()
**Namespace:** [Cake\Console](namespace-cake.console)
**See:** \Cake\Console\ConsoleOptionParser::addOption()
Property Summary
----------------
* [$\_boolean](#%24_boolean) protected `bool` Is the option a boolean option. Boolean options do not consume a parameter.
* [$\_choices](#%24_choices) protected `array<string>` An array of choices for the option.
* [$\_default](#%24_default) protected `string|bool|null` Default value for the option
* [$\_help](#%24_help) protected `string` Help text for the option.
* [$\_multiple](#%24_multiple) protected `bool` Can the option accept multiple value definition.
* [$\_name](#%24_name) protected `string` Name of the option
* [$\_short](#%24_short) protected `string` Short (1 character) alias for the option.
* [$prompt](#%24prompt) protected `string|null` The prompt string
* [$required](#%24required) protected `bool` Is the option required.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Make a new Input Option
* ##### [acceptsMultiple()](#acceptsMultiple()) public
Check if this option accepts multiple values.
* ##### [choices()](#choices()) public
Get the list of choices this option has.
* ##### [defaultValue()](#defaultValue()) public
Get the default value for this option
* ##### [help()](#help()) public
Generate the help for this this option.
* ##### [isBoolean()](#isBoolean()) public
Check if this option is a boolean option
* ##### [isRequired()](#isRequired()) public
Check if this option is required
* ##### [name()](#name()) public
Get the value of the name attribute.
* ##### [prompt()](#prompt()) public
Get the prompt string
* ##### [short()](#short()) public
Get the value of the short attribute.
* ##### [usage()](#usage()) public
Get the usage value for this option
* ##### [validChoice()](#validChoice()) public
Check that a value is a valid choice for this option.
* ##### [xml()](#xml()) public
Append the option's XML into the parent.
Method Detail
-------------
### \_\_construct() public
```
__construct(string $name, string $short = '', string $help = '', bool $isBoolean = false, string|bool|null $default = null, array<string> $choices = [], bool $multiple = false, bool $required = false, string|null $prompt = null)
```
Make a new Input Option
#### Parameters
`string` $name The long name of the option, or an array with all the properties.
`string` $short optional The short alias for this option
`string` $help optional The help text for this option
`bool` $isBoolean optional Whether this option is a boolean option. Boolean options don't consume extra tokens
`string|bool|null` $default optional The default value for this option.
`array<string>` $choices optional Valid choices for this option.
`bool` $multiple optional Whether this option can accept multiple value definition.
`bool` $required optional Whether this option is required or not.
`string|null` $prompt optional The prompt string.
#### Throws
`Cake\Console\Exception\ConsoleException`
### acceptsMultiple() public
```
acceptsMultiple(): bool
```
Check if this option accepts multiple values.
#### Returns
`bool`
### choices() public
```
choices(): array
```
Get the list of choices this option has.
#### Returns
`array`
### defaultValue() public
```
defaultValue(): string|bool|null
```
Get the default value for this option
#### Returns
`string|bool|null`
### help() public
```
help(int $width = 0): string
```
Generate the help for this this option.
#### Parameters
`int` $width optional The width to make the name of the option.
#### Returns
`string`
### isBoolean() public
```
isBoolean(): bool
```
Check if this option is a boolean option
#### Returns
`bool`
### isRequired() public
```
isRequired(): bool
```
Check if this option is required
#### Returns
`bool`
### name() public
```
name(): string
```
Get the value of the name attribute.
#### Returns
`string`
### prompt() public
```
prompt(): string
```
Get the prompt string
#### Returns
`string`
### short() public
```
short(): string
```
Get the value of the short attribute.
#### Returns
`string`
### usage() public
```
usage(): string
```
Get the usage value for this option
#### Returns
`string`
### validChoice() public
```
validChoice(string|bool $value): true
```
Check that a value is a valid choice for this option.
#### Parameters
`string|bool` $value The choice to validate.
#### Returns
`true`
#### Throws
`Cake\Console\Exception\ConsoleException`
### xml() public
```
xml(SimpleXMLElement $parent): SimpleXMLElement
```
Append the option's XML into the parent.
#### Parameters
`SimpleXMLElement` $parent The parent element.
#### Returns
`SimpleXMLElement`
Property Detail
---------------
### $\_boolean protected
Is the option a boolean option. Boolean options do not consume a parameter.
#### Type
`bool`
### $\_choices protected
An array of choices for the option.
#### Type
`array<string>`
### $\_default protected
Default value for the option
#### Type
`string|bool|null`
### $\_help protected
Help text for the option.
#### Type
`string`
### $\_multiple protected
Can the option accept multiple value definition.
#### Type
`bool`
### $\_name protected
Name of the option
#### Type
`string`
### $\_short protected
Short (1 character) alias for the option.
#### Type
`string`
### $prompt protected
The prompt string
#### Type
`string|null`
### $required protected
Is the option required.
#### Type
`bool`
cakephp Class MissingExtensionException Class MissingExtensionException
================================
Class MissingExtensionException
**Namespace:** [Cake\Database\Exception](namespace-cake.database.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Namespace I18n Namespace I18n
==============
### Namespaces
* [Cake\I18n\Exception](namespace-cake.i18n.exception)
* [Cake\I18n\Formatter](namespace-cake.i18n.formatter)
* [Cake\I18n\Middleware](namespace-cake.i18n.middleware)
* [Cake\I18n\Parser](namespace-cake.i18n.parser)
### Interfaces
* ##### [FormatterInterface](interface-cake.i18n.formatterinterface)
Formatter Interface
* ##### [I18nDateTimeInterface](interface-cake.i18n.i18ndatetimeinterface)
Interface for date formatting methods shared by both Time & Date.
### Classes
* ##### [ChainMessagesLoader](class-cake.i18n.chainmessagesloader)
Wraps multiple message loaders calling them one after another until one of them returns a non-empty package.
* ##### [Date](class-cake.i18n.date)
Extends the Date class provided by Chronos.
* ##### [FormatterLocator](class-cake.i18n.formatterlocator)
A ServiceLocator implementation for loading and retaining formatter objects.
* ##### [FrozenDate](class-cake.i18n.frozendate)
Extends the Date class provided by Chronos.
* ##### [FrozenTime](class-cake.i18n.frozentime)
Extends the built-in DateTime class to provide handy methods and locale-aware formatting helpers
* ##### [I18n](class-cake.i18n.i18n)
I18n handles translation of Text and time format strings.
* ##### [MessagesFileLoader](class-cake.i18n.messagesfileloader)
A generic translations package factory that will load translations files based on the file extension and the package name.
* ##### [Number](class-cake.i18n.number)
Number helper library.
* ##### [Package](class-cake.i18n.package)
Message Catalog
* ##### [PackageLocator](class-cake.i18n.packagelocator)
A ServiceLocator implementation for loading and retaining package objects.
* ##### [PluralRules](class-cake.i18n.pluralrules)
Utility class used to determine the plural number to be used for a variable base on the locale.
* ##### [RelativeTimeFormatter](class-cake.i18n.relativetimeformatter)
Helper class for formatting relative dates & times.
* ##### [Time](class-cake.i18n.time)
Extends the built-in DateTime class to provide handy methods and locale-aware formatting helpers
* ##### [Translator](class-cake.i18n.translator)
Translator to translate the message.
* ##### [TranslatorRegistry](class-cake.i18n.translatorregistry)
Constructs and stores instances of translators that can be retrieved by name and locale.
cakephp Class SmtpTransport Class SmtpTransport
====================
Send mail using SMTP protocol
**Namespace:** [Cake\Mailer\Transport](namespace-cake.mailer.transport)
Constants
---------
* **AUTH\_LOGIN**
```
'LOGIN'
```
* **AUTH\_PLAIN**
```
'PLAIN'
```
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_content](#%24_content) protected `array<string, string>` Content of email to return
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this class
* [$\_lastResponse](#%24_lastResponse) protected `array` The response of the last sent SMTP command.
* [$\_socket](#%24_socket) protected `Cake\Network\Socket|null` Socket to SMTP server
* [$authType](#%24authType) protected `string|null` Detected authentication type.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_destruct()](#__destruct()) public
Destructor
* ##### [\_\_wakeup()](#__wakeup()) public
Unserialize handler.
* ##### [\_auth()](#_auth()) protected
Send authentication
* ##### [\_authLogin()](#_authLogin()) protected
Authenticate using AUTH LOGIN mechanism.
* ##### [\_authPlain()](#_authPlain()) protected
Authenticate using AUTH PLAIN mechanism.
* ##### [\_bufferResponseLines()](#_bufferResponseLines()) protected
Parses and stores the response lines in `'code' => 'message'` format.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_connect()](#_connect()) protected
Connect to SMTP Server
* ##### [\_disconnect()](#_disconnect()) protected
Disconnect
* ##### [\_generateSocket()](#_generateSocket()) protected
Helper method to generate socket
* ##### [\_parseAuthType()](#_parseAuthType()) protected
Parses the last response line and extract the preferred authentication type.
* ##### [\_prepareFromAddress()](#_prepareFromAddress()) protected
Prepares the `from` email address.
* ##### [\_prepareFromCmd()](#_prepareFromCmd()) protected
Prepares the `MAIL FROM` SMTP command.
* ##### [\_prepareMessage()](#_prepareMessage()) protected
Prepares the message body.
* ##### [\_prepareRcptCmd()](#_prepareRcptCmd()) protected
Prepares the `RCPT TO` SMTP command.
* ##### [\_prepareRecipientAddresses()](#_prepareRecipientAddresses()) protected
Prepares the recipient email addresses.
* ##### [\_sendData()](#_sendData()) protected
Send Data
* ##### [\_sendRcpt()](#_sendRcpt()) protected
Send emails
* ##### [\_smtpSend()](#_smtpSend()) protected
Protected method for sending data to SMTP connection
* ##### [\_socket()](#_socket()) protected
Get socket instance.
* ##### [checkRecipient()](#checkRecipient()) protected
Check that at least one destination header is set.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [connect()](#connect()) public
Connect to the SMTP server.
* ##### [connected()](#connected()) public
Check whether an open connection to the SMTP server is available.
* ##### [disconnect()](#disconnect()) public
Disconnect from the SMTP server.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getLastResponse()](#getLastResponse()) public
Returns the response of the last sent SMTP command.
* ##### [send()](#send()) public
Send mail
* ##### [setConfig()](#setConfig()) public
Sets the config.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Constructor
#### Parameters
`array<string, mixed>` $config optional Configuration options.
### \_\_destruct() public
```
__destruct()
```
Destructor
Tries to disconnect to ensure that the connection is being terminated properly before the socket gets closed.
### \_\_wakeup() public
```
__wakeup(): void
```
Unserialize handler.
Ensure that the socket property isn't reinitialized in a broken state.
#### Returns
`void`
### \_auth() protected
```
_auth(): void
```
Send authentication
#### Returns
`void`
#### Throws
`Cake\Network\Exception\SocketException`
### \_authLogin() protected
```
_authLogin(string $username, string $password): void
```
Authenticate using AUTH LOGIN mechanism.
#### Parameters
`string` $username Username.
`string` $password Password.
#### Returns
`void`
### \_authPlain() protected
```
_authPlain(string $username, string $password): string|null
```
Authenticate using AUTH PLAIN mechanism.
#### Parameters
`string` $username Username.
`string` $password Password.
#### Returns
`string|null`
### \_bufferResponseLines() protected
```
_bufferResponseLines(array<string> $responseLines): void
```
Parses and stores the response lines in `'code' => 'message'` format.
#### Parameters
`array<string>` $responseLines Response lines to parse.
#### Returns
`void`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_connect() protected
```
_connect(): void
```
Connect to SMTP Server
#### Returns
`void`
#### Throws
`Cake\Network\Exception\SocketException`
### \_disconnect() protected
```
_disconnect(): void
```
Disconnect
#### Returns
`void`
#### Throws
`Cake\Network\Exception\SocketException`
### \_generateSocket() protected
```
_generateSocket(): void
```
Helper method to generate socket
#### Returns
`void`
#### Throws
`Cake\Network\Exception\SocketException`
### \_parseAuthType() protected
```
_parseAuthType(): void
```
Parses the last response line and extract the preferred authentication type.
#### Returns
`void`
### \_prepareFromAddress() protected
```
_prepareFromAddress(Cake\Mailer\Message $message): array
```
Prepares the `from` email address.
#### Parameters
`Cake\Mailer\Message` $message Message instance
#### Returns
`array`
### \_prepareFromCmd() protected
```
_prepareFromCmd(string $message): string
```
Prepares the `MAIL FROM` SMTP command.
#### Parameters
`string` $message The email address to send with the command.
#### Returns
`string`
### \_prepareMessage() protected
```
_prepareMessage(Cake\Mailer\Message $message): string
```
Prepares the message body.
#### Parameters
`Cake\Mailer\Message` $message Message instance
#### Returns
`string`
### \_prepareRcptCmd() protected
```
_prepareRcptCmd(string $message): string
```
Prepares the `RCPT TO` SMTP command.
#### Parameters
`string` $message The email address to send with the command.
#### Returns
`string`
### \_prepareRecipientAddresses() protected
```
_prepareRecipientAddresses(Cake\Mailer\Message $message): array
```
Prepares the recipient email addresses.
#### Parameters
`Cake\Mailer\Message` $message Message instance
#### Returns
`array`
### \_sendData() protected
```
_sendData(Cake\Mailer\Message $message): void
```
Send Data
#### Parameters
`Cake\Mailer\Message` $message Message instance
#### Returns
`void`
#### Throws
`Cake\Network\Exception\SocketException`
### \_sendRcpt() protected
```
_sendRcpt(Cake\Mailer\Message $message): void
```
Send emails
#### Parameters
`Cake\Mailer\Message` $message Message instance
#### Returns
`void`
#### Throws
`Cake\Network\Exception\SocketException`
### \_smtpSend() protected
```
_smtpSend(string|null $data, string|false $checkCode = '250'): string|null
```
Protected method for sending data to SMTP connection
#### Parameters
`string|null` $data Data to be sent to SMTP server
`string|false` $checkCode optional Code to check for in server response, false to skip
#### Returns
`string|null`
#### Throws
`Cake\Network\Exception\SocketException`
### \_socket() protected
```
_socket(): Cake\Network\Socket
```
Get socket instance.
#### Returns
`Cake\Network\Socket`
#### Throws
`RuntimeException`
If socket is not set. ### checkRecipient() protected
```
checkRecipient(Cake\Mailer\Message $message): void
```
Check that at least one destination header is set.
#### Parameters
`Cake\Mailer\Message` $message Message instance.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
If at least one of to, cc or bcc is not specified. ### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### connect() public
```
connect(): void
```
Connect to the SMTP server.
This method tries to connect only in case there is no open connection available already.
#### Returns
`void`
### connected() public
```
connected(): bool
```
Check whether an open connection to the SMTP server is available.
#### Returns
`bool`
### disconnect() public
```
disconnect(): void
```
Disconnect from the SMTP server.
This method tries to disconnect only in case there is an open connection available.
#### Returns
`void`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getLastResponse() public
```
getLastResponse(): array
```
Returns the response of the last sent SMTP command.
A response consists of one or more lines containing a response code and an optional response message text:
```
[
[
'code' => '250',
'message' => 'mail.example.com'
],
[
'code' => '250',
'message' => 'PIPELINING'
],
[
'code' => '250',
'message' => '8BITMIME'
],
// etc...
]
```
#### Returns
`array`
### send() public
```
send(Cake\Mailer\Message $message): array{headers: string, message: string}
```
Send mail
#### Parameters
`Cake\Mailer\Message` $message Message instance
#### Returns
`array{headers: string, message: string}`
#### Throws
`Cake\Network\Exception\SocketException`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_content protected
Content of email to return
#### Type
`array<string, string>`
### $\_defaultConfig protected
Default config for this class
#### Type
`array<string, mixed>`
### $\_lastResponse protected
The response of the last sent SMTP command.
#### Type
`array`
### $\_socket protected
Socket to SMTP server
#### Type
`Cake\Network\Socket|null`
### $authType protected
Detected authentication type.
#### Type
`string|null`
| programming_docs |
cakephp Namespace Exception Namespace Exception
===================
### Classes
* ##### [ClientException](class-cake.http.client.exception.clientexception)
Thrown when a request cannot be sent or response cannot be parsed into a PSR-7 response object.
* ##### [MissingResponseException](class-cake.http.client.exception.missingresponseexception)
Used to indicate that a request did not have a matching mock response.
* ##### [NetworkException](class-cake.http.client.exception.networkexception)
Thrown when the request cannot be completed because of network issues.
* ##### [RequestException](class-cake.http.client.exception.requestexception)
Exception for when a request failed.
cakephp Class CookieSet Class CookieSet
================
CookieSet
**Namespace:** [Cake\TestSuite\Constraint\Response](namespace-cake.testsuite.constraint.response)
Property Summary
----------------
* [$response](#%24response) protected `Cake\Http\Response`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_getBodyAsString()](#_getBodyAsString()) protected
Get the response body as string
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Checks assertion
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(Psr\Http\Message\ResponseInterface|null $response)
```
Constructor
#### Parameters
`Psr\Http\Message\ResponseInterface|null` $response Response
### \_getBodyAsString() protected
```
_getBodyAsString(): string
```
Get the response body as string
#### Returns
`string`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks assertion
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Expected content
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $response protected
#### Type
`Cake\Http\Response`
cakephp Class TableRegistry Class TableRegistry
====================
Provides a registry/factory for Table objects.
This registry allows you to centralize the configuration for tables their connections and other meta-data.
### Configuring instances
You may need to configure your table objects. Using the `TableLocator` you can centralize configuration. Any configuration set before instances are created will be used when creating instances. If you modify configuration after an instance is made, the instances *will not* be updated.
```
TableRegistry::getTableLocator()->setConfig('Users', ['table' => 'my_users']);
// Prior to 3.6.0
TableRegistry::config('Users', ['table' => 'my_users']);
```
Configuration data is stored *per alias* if you use the same table with multiple aliases you will need to set configuration multiple times.
### Getting instances
You can fetch instances out of the registry through `TableLocator::get()`. One instance is stored per alias. Once an alias is populated the same instance will always be returned. This reduces the ORM memory cost and helps make cyclic references easier to solve.
```
$table = TableRegistry::getTableLocator()->get('Users', $config);
// Prior to 3.6.0
$table = TableRegistry::get('Users', $config);
```
**Namespace:** [Cake\ORM](namespace-cake.orm)
Method Summary
--------------
* ##### [clear()](#clear()) public static deprecated
Clears the registry of configuration and instances.
* ##### [exists()](#exists()) public static deprecated
Check to see if an instance exists in the registry.
* ##### [get()](#get()) public static deprecated
Get a table instance from the registry.
* ##### [getTableLocator()](#getTableLocator()) public static
Returns a singleton instance of LocatorInterface implementation.
* ##### [remove()](#remove()) public static deprecated
Removes an instance from the registry.
* ##### [set()](#set()) public static deprecated
Set an instance.
* ##### [setTableLocator()](#setTableLocator()) public static
Sets singleton instance of LocatorInterface implementation.
Method Detail
-------------
### clear() public static
```
clear(): void
```
Clears the registry of configuration and instances.
#### Returns
`void`
### exists() public static
```
exists(string $alias): bool
```
Check to see if an instance exists in the registry.
#### Parameters
`string` $alias The alias to check for.
#### Returns
`bool`
### get() public static
```
get(string $alias, array<string, mixed> $options = []): Cake\ORM\Table
```
Get a table instance from the registry.
See options specification in {@link TableLocator::get()}.
#### Parameters
`string` $alias The alias name you want to get.
`array<string, mixed>` $options optional The options you want to build the table with.
#### Returns
`Cake\ORM\Table`
### getTableLocator() public static
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Returns a singleton instance of LocatorInterface implementation.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### remove() public static
```
remove(string $alias): void
```
Removes an instance from the registry.
#### Parameters
`string` $alias The alias to remove.
#### Returns
`void`
### set() public static
```
set(string $alias, Cake\ORM\Table $object): Cake\ORM\Table
```
Set an instance.
#### Parameters
`string` $alias The alias to set.
`Cake\ORM\Table` $object The table to set.
#### Returns
`Cake\ORM\Table`
### setTableLocator() public static
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): void
```
Sets singleton instance of LocatorInterface implementation.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator Instance of a locator to use.
#### Returns
`void`
cakephp Namespace View Namespace View
==============
### Namespaces
* [Cake\View\Exception](namespace-cake.view.exception)
* [Cake\View\Form](namespace-cake.view.form)
* [Cake\View\Helper](namespace-cake.view.helper)
* [Cake\View\Widget](namespace-cake.view.widget)
### Classes
* ##### [AjaxView](class-cake.view.ajaxview)
A view class that is used for AJAX responses. Currently, only switches the default layout and sets the response type - which just maps to text/html by default.
* ##### [Cell](class-cake.view.cell)
Cell base.
* ##### [Helper](class-cake.view.helper)
Abstract base class for all other Helpers in CakePHP. Provides common methods and features.
* ##### [HelperRegistry](class-cake.view.helperregistry)
HelperRegistry is used as a registry for loaded helpers and handles loading and constructing helper class objects.
* ##### [JsonView](class-cake.view.jsonview)
A view class that is used for JSON responses.
* ##### [NegotiationRequiredView](class-cake.view.negotiationrequiredview)
A view class that responds to any content-type and can be used to create an empty body 406 status code response.
* ##### [SerializedView](class-cake.view.serializedview)
Parent class for view classes generating serialized outputs like JsonView and XmlView.
* ##### [StringTemplate](class-cake.view.stringtemplate)
Provides an interface for registering and inserting content into simple logic-less string templates.
* ##### [View](class-cake.view.view)
View, the V in the MVC triad. View interacts with Helpers and view variables passed in from the controller to render the results of the controller action. Often this is HTML, but can also take the form of JSON, XML, PDF's or streaming files.
* ##### [ViewBlock](class-cake.view.viewblock)
ViewBlock implements the concept of Blocks or Slots in the View layer. Slots or blocks are combined with extending views and layouts to afford slots of content that are present in a layout or parent view, but are defined by the child view or elements used in the view.
* ##### [ViewBuilder](class-cake.view.viewbuilder)
Provides an API for iteratively building a view up.
* ##### [XmlView](class-cake.view.xmlview)
A view class that is used for creating XML responses.
### Traits
* ##### [CellTrait](trait-cake.view.celltrait)
Provides cell() method for usage in Controller and View classes.
* ##### [StringTemplateTrait](trait-cake.view.stringtemplatetrait)
Adds string template functionality to any class by providing methods to load and parse string templates.
* ##### [ViewVarsTrait](trait-cake.view.viewvarstrait)
Provides the set() method for collecting template context.
cakephp Class TranslatorRegistry Class TranslatorRegistry
=========================
Constructs and stores instances of translators that can be retrieved by name and locale.
**Namespace:** [Cake\I18n](namespace-cake.i18n)
Constants
---------
* `string` **FALLBACK\_LOADER**
```
'_fallback'
```
Fallback loader name.
Property Summary
----------------
* [$\_cacher](#%24_cacher) protected `Psr\SimpleCache\CacheInterfaceCake\Cache\CacheEngineInterface)|null` A CacheEngine object that is used to remember translator across requests.
* [$\_defaultFormatter](#%24_defaultFormatter) protected `string` The name of the default formatter to use for newly created translators from the fallback loader
* [$\_loaders](#%24_loaders) protected `array<callable>` A list of loader functions indexed by domain name. Loaders are callables that are invoked as a default for building translation packages where none can be found for the combination of translator name and locale.
* [$\_useFallback](#%24_useFallback) protected `bool` Use fallback-domain for translation loaders.
* [$formatters](#%24formatters) protected `Cake\I18n\FormatterLocator` A formatter locator.
* [$locale](#%24locale) protected `string` The current locale code.
* [$packages](#%24packages) protected `Cake\I18n\PackageLocator` A package locator.
* [$registry](#%24registry) protected `array<string, array<string,Cake\I18n\Translator>>` A registry to retain translator objects.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_getTranslator()](#_getTranslator()) protected
Gets a translator from the registry by package for a locale.
* ##### [createInstance()](#createInstance()) protected
Create translator instance.
* ##### [defaultFormatter()](#defaultFormatter()) public
Sets the name of the default messages formatter to use for future translator instances.
* ##### [get()](#get()) public
Gets a translator from the registry by package for a locale.
* ##### [getFormatters()](#getFormatters()) public
An object of type FormatterLocator
* ##### [getLocale()](#getLocale()) public
Returns the default locale code.
* ##### [getPackages()](#getPackages()) public
Returns the translator packages
* ##### [registerLoader()](#registerLoader()) public
Registers a loader function for a package name that will be used as a fallback in case no package with that name can be found.
* ##### [setCacher()](#setCacher()) public
Sets the CacheEngine instance used to remember translators across requests.
* ##### [setFallbackPackage()](#setFallbackPackage()) public
Set fallback domain for package.
* ##### [setLoaderFallback()](#setLoaderFallback()) public
Set domain fallback for loader.
* ##### [setLocale()](#setLocale()) public
Sets the default locale code.
* ##### [useFallback()](#useFallback()) public
Set if the default domain fallback is used.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\I18n\PackageLocator $packages, Cake\I18n\FormatterLocator $formatters, string $locale)
```
Constructor.
#### Parameters
`Cake\I18n\PackageLocator` $packages The package locator.
`Cake\I18n\FormatterLocator` $formatters The formatter locator.
`string` $locale The default locale code to use.
### \_getTranslator() protected
```
_getTranslator(string $name, string $locale): Cake\I18n\Translator
```
Gets a translator from the registry by package for a locale.
#### Parameters
`string` $name The translator package to retrieve.
`string` $locale The locale to use; if empty, uses the default locale.
#### Returns
`Cake\I18n\Translator`
### createInstance() protected
```
createInstance(string $name, string $locale): Cake\I18n\Translator
```
Create translator instance.
#### Parameters
`string` $name The translator package to retrieve.
`string` $locale The locale to use; if empty, uses the default locale.
#### Returns
`Cake\I18n\Translator`
### defaultFormatter() public
```
defaultFormatter(string|null $name = null): string
```
Sets the name of the default messages formatter to use for future translator instances.
If called with no arguments, it will return the currently configured value.
#### Parameters
`string|null` $name optional The name of the formatter to use.
#### Returns
`string`
### get() public
```
get(string $name, string|null $locale = null): Cake\I18n\Translator|null
```
Gets a translator from the registry by package for a locale.
#### Parameters
`string` $name The translator package to retrieve.
`string|null` $locale optional The locale to use; if empty, uses the default locale.
#### Returns
`Cake\I18n\Translator|null`
#### Throws
`Cake\I18n\Exception\I18nException`
If no translator with that name could be found for the given locale. ### getFormatters() public
```
getFormatters(): Cake\I18n\FormatterLocator
```
An object of type FormatterLocator
#### Returns
`Cake\I18n\FormatterLocator`
### getLocale() public
```
getLocale(): string
```
Returns the default locale code.
#### Returns
`string`
### getPackages() public
```
getPackages(): Cake\I18n\PackageLocator
```
Returns the translator packages
#### Returns
`Cake\I18n\PackageLocator`
### registerLoader() public
```
registerLoader(string $name, callable $loader): void
```
Registers a loader function for a package name that will be used as a fallback in case no package with that name can be found.
Loader callbacks will get as first argument the package name and the locale as the second argument.
#### Parameters
`string` $name The name of the translator package to register a loader for
`callable` $loader A callable object that should return a Package
#### Returns
`void`
### setCacher() public
```
setCacher(Psr\SimpleCache\CacheInterfaceCake\Cache\CacheEngineInterface $cacher): void
```
Sets the CacheEngine instance used to remember translators across requests.
#### Parameters
`Psr\SimpleCache\CacheInterfaceCake\Cache\CacheEngineInterface` $cacher The cacher instance.
#### Returns
`void`
### setFallbackPackage() public
```
setFallbackPackage(string $name, Cake\I18n\Package $package): Cake\I18n\Package
```
Set fallback domain for package.
#### Parameters
`string` $name The name of the package.
`Cake\I18n\Package` $package Package instance
#### Returns
`Cake\I18n\Package`
### setLoaderFallback() public
```
setLoaderFallback(string $name, callable $loader): callable
```
Set domain fallback for loader.
#### Parameters
`string` $name The name of the loader domain
`callable` $loader invokable loader
#### Returns
`callable`
### setLocale() public
```
setLocale(string $locale): void
```
Sets the default locale code.
#### Parameters
`string` $locale The new locale code.
#### Returns
`void`
### useFallback() public
```
useFallback(bool $enable = true): void
```
Set if the default domain fallback is used.
#### Parameters
`bool` $enable optional flag to enable or disable fallback
#### Returns
`void`
Property Detail
---------------
### $\_cacher protected
A CacheEngine object that is used to remember translator across requests.
#### Type
`Psr\SimpleCache\CacheInterfaceCake\Cache\CacheEngineInterface)|null`
### $\_defaultFormatter protected
The name of the default formatter to use for newly created translators from the fallback loader
#### Type
`string`
### $\_loaders protected
A list of loader functions indexed by domain name. Loaders are callables that are invoked as a default for building translation packages where none can be found for the combination of translator name and locale.
#### Type
`array<callable>`
### $\_useFallback protected
Use fallback-domain for translation loaders.
#### Type
`bool`
### $formatters protected
A formatter locator.
#### Type
`Cake\I18n\FormatterLocator`
### $locale protected
The current locale code.
#### Type
`string`
### $packages protected
A package locator.
#### Type
`Cake\I18n\PackageLocator`
### $registry protected
A registry to retain translator objects.
#### Type
`array<string, array<string,Cake\I18n\Translator>>`
| programming_docs |
cakephp Namespace Debug Namespace Debug
===============
### Interfaces
* ##### [FormatterInterface](interface-cake.error.debug.formatterinterface)
Interface for formatters used by Debugger::exportVar()
* ##### [NodeInterface](interface-cake.error.debug.nodeinterface)
Interface for Debugs
### Classes
* ##### [ArrayItemNode](class-cake.error.debug.arrayitemnode)
Dump node for Array Items.
* ##### [ArrayNode](class-cake.error.debug.arraynode)
Dump node for Array values.
* ##### [ClassNode](class-cake.error.debug.classnode)
Dump node for objects/class instances.
* ##### [ConsoleFormatter](class-cake.error.debug.consoleformatter)
A Debugger formatter for generating output with ANSI escape codes
* ##### [DebugContext](class-cake.error.debug.debugcontext)
Context tracking for Debugger::exportVar()
* ##### [HtmlFormatter](class-cake.error.debug.htmlformatter)
A Debugger formatter for generating interactive styled HTML output.
* ##### [PropertyNode](class-cake.error.debug.propertynode)
Dump node for object properties.
* ##### [ReferenceNode](class-cake.error.debug.referencenode)
Dump node for class references.
* ##### [ScalarNode](class-cake.error.debug.scalarnode)
Dump node for scalar values.
* ##### [SpecialNode](class-cake.error.debug.specialnode)
Debug node for special messages like errors or recursion warnings.
* ##### [TextFormatter](class-cake.error.debug.textformatter)
A Debugger formatter for generating unstyled plain text output.
cakephp Interface WindowInterface Interface WindowInterface
==========================
This defines the functions used for building window expressions.
**Namespace:** [Cake\Database\Expression](namespace-cake.database.expression)
Constants
---------
* `string` **FOLLOWING**
```
'FOLLOWING'
```
* `string` **GROUPS**
```
'GROUPS'
```
* `string` **PRECEDING**
```
'PRECEDING'
```
* `string` **RANGE**
```
'RANGE'
```
* `string` **ROWS**
```
'ROWS'
```
Method Summary
--------------
* ##### [excludeCurrent()](#excludeCurrent()) public
Adds current row frame exclusion.
* ##### [excludeGroup()](#excludeGroup()) public
Adds group frame exclusion.
* ##### [excludeTies()](#excludeTies()) public
Adds ties frame exclusion.
* ##### [frame()](#frame()) public
Adds a frame to the window.
* ##### [groups()](#groups()) public
Adds a simple groups frame to the window.
* ##### [order()](#order()) public
Adds one or more order clauses to the window.
* ##### [partition()](#partition()) public
Adds one or more partition expressions to the window.
* ##### [range()](#range()) public
Adds a simple range frame to the window.
* ##### [rows()](#rows()) public
Adds a simple rows frame to the window.
Method Detail
-------------
### excludeCurrent() public
```
excludeCurrent(): $this
```
Adds current row frame exclusion.
#### Returns
`$this`
### excludeGroup() public
```
excludeGroup(): $this
```
Adds group frame exclusion.
#### Returns
`$this`
### excludeTies() public
```
excludeTies(): $this
```
Adds ties frame exclusion.
#### Returns
`$this`
### frame() public
```
frame(string $type, Cake\Database\ExpressionInterface|string|int|null $startOffset, string $startDirection, Cake\Database\ExpressionInterface|string|int|null $endOffset, string $endDirection): $this
```
Adds a frame to the window.
Use the `range()`, `rows()` or `groups()` helpers if you need simple 'BETWEEN offset PRECEDING and offset FOLLOWING' frames.
You can specify any direction for both frame start and frame end.
With both `$startOffset` and `$endOffset`:
* `0` - 'CURRENT ROW'
* `null` - 'UNBOUNDED'
#### Parameters
`string` $type Frame type
`Cake\Database\ExpressionInterface|string|int|null` $startOffset Frame start offset
`string` $startDirection Frame start direction
`Cake\Database\ExpressionInterface|string|int|null` $endOffset Frame end offset
`string` $endDirection Frame end direction
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
WHen offsets are negative. ### groups() public
```
groups(int|null $start, int|null $end = 0): $this
```
Adds a simple groups frame to the window.
See `range()` for details.
#### Parameters
`int|null` $start Frame start
`int|null` $end optional Frame end If not passed in, only frame start SQL will be generated.
#### Returns
`$this`
### order() public
```
order(Cake\Database\ExpressionInterfaceClosure|arrayCake\Database\ExpressionInterface|string>|string $fields): $this
```
Adds one or more order clauses to the window.
#### Parameters
`Cake\Database\ExpressionInterfaceClosure|arrayCake\Database\ExpressionInterface|string>|string` $fields Order expressions
#### Returns
`$this`
### partition() public
```
partition(Cake\Database\ExpressionInterfaceClosure|arrayCake\Database\ExpressionInterface|string>|string $partitions): $this
```
Adds one or more partition expressions to the window.
#### Parameters
`Cake\Database\ExpressionInterfaceClosure|arrayCake\Database\ExpressionInterface|string>|string` $partitions Partition expressions
#### Returns
`$this`
### range() public
```
range(Cake\Database\ExpressionInterface|string|int|null $start, Cake\Database\ExpressionInterface|string|int|null $end = 0): $this
```
Adds a simple range frame to the window.
`$start`:
* `0` - 'CURRENT ROW'
* `null` - 'UNBOUNDED PRECEDING'
* offset - 'offset PRECEDING'
`$end`:
* `0` - 'CURRENT ROW'
* `null` - 'UNBOUNDED FOLLOWING'
* offset - 'offset FOLLOWING'
If you need to use 'FOLLOWING' with frame start or 'PRECEDING' with frame end, use `frame()` instead.
#### Parameters
`Cake\Database\ExpressionInterface|string|int|null` $start Frame start
`Cake\Database\ExpressionInterface|string|int|null` $end optional Frame end If not passed in, only frame start SQL will be generated.
#### Returns
`$this`
### rows() public
```
rows(int|null $start, int|null $end = 0): $this
```
Adds a simple rows frame to the window.
See `range()` for details.
#### Parameters
`int|null` $start Frame start
`int|null` $end optional Frame end If not passed in, only frame start SQL will be generated.
#### Returns
`$this`
cakephp CakePHP 4.4 API CakePHP 4.4 API
===============
Namespace Tree
--------------
* [Global](namespace-global)
* [Cake](https://api.cakephp.org/4.4/namespace-Cake.html)
+ [Cake\Auth](namespace-cake.auth)
- [Cake\Auth\Storage](namespace-cake.auth.storage)
+ [Cake\Cache](namespace-cake.cache)
- [Cake\Cache\Engine](namespace-cake.cache.engine)
+ [Cake\Collection](namespace-cake.collection)
- [Cake\Collection\Iterator](namespace-cake.collection.iterator)
+ [Cake\Command](namespace-cake.command)
+ [Cake\Console](namespace-cake.console)
- [Cake\Console\Command](namespace-cake.console.command)
- [Cake\Console\Exception](namespace-cake.console.exception)
- [Cake\Console\TestSuite](namespace-cake.console.testsuite)
* [Cake\Console\TestSuite\Constraint](namespace-cake.console.testsuite.constraint)
+ [Cake\Controller](namespace-cake.controller)
- [Cake\Controller\Component](namespace-cake.controller.component)
- [Cake\Controller\Exception](namespace-cake.controller.exception)
+ [Cake\Core](namespace-cake.core)
- [Cake\Core\Configure](namespace-cake.core.configure)
* [Cake\Core\Configure\Engine](namespace-cake.core.configure.engine)
- [Cake\Core\Exception](namespace-cake.core.exception)
- [Cake\Core\Retry](namespace-cake.core.retry)
- [Cake\Core\TestSuite](namespace-cake.core.testsuite)
+ [Cake\Database](namespace-cake.database)
- [Cake\Database\Driver](namespace-cake.database.driver)
- [Cake\Database\Exception](namespace-cake.database.exception)
- [Cake\Database\Expression](namespace-cake.database.expression)
- [Cake\Database\Log](namespace-cake.database.log)
- [Cake\Database\Retry](namespace-cake.database.retry)
- [Cake\Database\Schema](namespace-cake.database.schema)
- [Cake\Database\Statement](namespace-cake.database.statement)
- [Cake\Database\Type](namespace-cake.database.type)
+ [Cake\Datasource](namespace-cake.datasource)
- [Cake\Datasource\Exception](namespace-cake.datasource.exception)
- [Cake\Datasource\Locator](namespace-cake.datasource.locator)
- [Cake\Datasource\Paging](namespace-cake.datasource.paging)
* [Cake\Datasource\Paging\Exception](namespace-cake.datasource.paging.exception)
+ [Cake\Error](namespace-cake.error)
- [Cake\Error\Debug](namespace-cake.error.debug)
- [Cake\Error\Middleware](namespace-cake.error.middleware)
- [Cake\Error\Renderer](namespace-cake.error.renderer)
+ [Cake\Event](namespace-cake.event)
- [Cake\Event\Decorator](namespace-cake.event.decorator)
+ [Cake\Filesystem](namespace-cake.filesystem)
+ [Cake\Form](namespace-cake.form)
+ [Cake\Http](namespace-cake.http)
- [Cake\Http\Client](namespace-cake.http.client)
* [Cake\Http\Client\Adapter](namespace-cake.http.client.adapter)
* [Cake\Http\Client\Auth](namespace-cake.http.client.auth)
* [Cake\Http\Client\Exception](namespace-cake.http.client.exception)
- [Cake\Http\Cookie](namespace-cake.http.cookie)
- [Cake\Http\Exception](namespace-cake.http.exception)
- [Cake\Http\Middleware](namespace-cake.http.middleware)
- [Cake\Http\Session](namespace-cake.http.session)
- [Cake\Http\TestSuite](namespace-cake.http.testsuite)
+ [Cake\I18n](namespace-cake.i18n)
- [Cake\I18n\Exception](namespace-cake.i18n.exception)
- [Cake\I18n\Formatter](namespace-cake.i18n.formatter)
- [Cake\I18n\Middleware](namespace-cake.i18n.middleware)
- [Cake\I18n\Parser](namespace-cake.i18n.parser)
+ [Cake\Log](namespace-cake.log)
- [Cake\Log\Engine](namespace-cake.log.engine)
- [Cake\Log\Formatter](namespace-cake.log.formatter)
+ [Cake\Mailer](namespace-cake.mailer)
- [Cake\Mailer\Exception](namespace-cake.mailer.exception)
- [Cake\Mailer\Transport](namespace-cake.mailer.transport)
+ [Cake\Network](namespace-cake.network)
- [Cake\Network\Exception](namespace-cake.network.exception)
+ [Cake\ORM](namespace-cake.orm)
- [Cake\ORM\Association](namespace-cake.orm.association)
* [Cake\ORM\Association\Loader](namespace-cake.orm.association.loader)
- [Cake\ORM\Behavior](namespace-cake.orm.behavior)
* [Cake\ORM\Behavior\Translate](namespace-cake.orm.behavior.translate)
- [Cake\ORM\Exception](namespace-cake.orm.exception)
- [Cake\ORM\Locator](namespace-cake.orm.locator)
- [Cake\ORM\Rule](namespace-cake.orm.rule)
+ [Cake\Routing](namespace-cake.routing)
- [Cake\Routing\Exception](namespace-cake.routing.exception)
- [Cake\Routing\Middleware](namespace-cake.routing.middleware)
- [Cake\Routing\Route](namespace-cake.routing.route)
+ [Cake\Shell](namespace-cake.shell)
- [Cake\Shell\Helper](namespace-cake.shell.helper)
- [Cake\Shell\Task](namespace-cake.shell.task)
+ [Cake\TestSuite](namespace-cake.testsuite)
- [Cake\TestSuite\Constraint](namespace-cake.testsuite.constraint)
* [Cake\TestSuite\Constraint\Email](namespace-cake.testsuite.constraint.email)
* [Cake\TestSuite\Constraint\Response](namespace-cake.testsuite.constraint.response)
* [Cake\TestSuite\Constraint\Session](namespace-cake.testsuite.constraint.session)
* [Cake\TestSuite\Constraint\View](namespace-cake.testsuite.constraint.view)
- [Cake\TestSuite\Fixture](namespace-cake.testsuite.fixture)
- [Cake\TestSuite\Stub](namespace-cake.testsuite.stub)
+ [Cake\Utility](namespace-cake.utility)
- [Cake\Utility\Crypto](namespace-cake.utility.crypto)
- [Cake\Utility\Exception](namespace-cake.utility.exception)
+ [Cake\Validation](namespace-cake.validation)
+ [Cake\View](namespace-cake.view)
- [Cake\View\Exception](namespace-cake.view.exception)
- [Cake\View\Form](namespace-cake.view.form)
- [Cake\View\Helper](namespace-cake.view.helper)
- [Cake\View\Widget](namespace-cake.view.widget)
cakephp Class MissingOptionException Class MissingOptionException
=============================
Exception raised with suggestions
**Namespace:** [Cake\Console\Exception](namespace-cake.console.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
* [$requested](#%24requested) protected `string` The requested thing that was not found.
* [$suggestions](#%24suggestions) protected `array<string>` The valid suggestions.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [findClosestItem()](#findClosestItem()) protected
Find the best match for requested in suggestions
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [getFullMessage()](#getFullMessage()) public
Get the message with suggestions
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(string $message, string $requested = '', array<string> $suggestions = [], int|null $code = null, Throwable|null $previous = null)
```
Constructor.
#### Parameters
`string` $message The string message.
`string` $requested optional The requested value.
`array<string>` $suggestions optional The list of potential values that were valid.
`int|null` $code optional The exception code if relevant.
`Throwable|null` $previous optional the previous exception.
### findClosestItem() protected
```
findClosestItem(string $needle, array<string> $haystack): string
```
Find the best match for requested in suggestions
#### Parameters
`string` $needle Unknown option name trying to be used.
`array<string>` $haystack Suggestions to look through.
#### Returns
`string`
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### getFullMessage() public
```
getFullMessage(): string
```
Get the message with suggestions
#### Returns
`string`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
### $requested protected
The requested thing that was not found.
#### Type
`string`
### $suggestions protected
The valid suggestions.
#### Type
`array<string>`
cakephp Class GoneException Class GoneException
====================
Represents an HTTP 410 error.
**Namespace:** [Cake\Http\Exception](namespace-cake.http.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
* [$headers](#%24headers) protected `array<string, mixed>`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [getHeaders()](#getHeaders()) public
Returns array of response headers.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
* ##### [setHeader()](#setHeader()) public
Set a single HTTP response header.
* ##### [setHeaders()](#setHeaders()) public
Sets HTTP response headers.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $message = null, int|null $code = null, Throwable|null $previous = null)
```
Constructor
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`string|null` $message optional If no message is given 'Gone' will be the message
`int|null` $code optional Status code, defaults to 410
`Throwable|null` $previous optional The previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### getHeaders() public
```
getHeaders(): array<string, mixed>
```
Returns array of response headers.
#### Returns
`array<string, mixed>`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
### setHeader() public
```
setHeader(string $header, array<string>|string|null $value = null): void
```
Set a single HTTP response header.
#### Parameters
`string` $header Header name
`array<string>|string|null` $value optional Header value
#### Returns
`void`
### setHeaders() public
```
setHeaders(array<string, mixed> $headers): void
```
Sets HTTP response headers.
#### Parameters
`array<string, mixed>` $headers Array of header name and value pairs.
#### Returns
`void`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
### $headers protected
#### Type
`array<string, mixed>`
| programming_docs |
cakephp Interface ExpressionInterface Interface ExpressionInterface
==============================
An interface used by Expression objects.
**Namespace:** [Cake\Database](namespace-cake.database)
Method Summary
--------------
* ##### [sql()](#sql()) public
Converts the Node into a SQL string fragment.
* ##### [traverse()](#traverse()) public
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
Method Detail
-------------
### sql() public
```
sql(Cake\Database\ValueBinder $binder): string
```
Converts the Node into a SQL string fragment.
#### Parameters
`Cake\Database\ValueBinder` $binder Parameter binder
#### Returns
`string`
### traverse() public
```
traverse(Closure $callback): $this
```
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
#### Parameters
`Closure` $callback The callable to apply to all nodes.
#### Returns
`$this`
cakephp Namespace Session Namespace Session
=================
### Classes
* ##### [CacheSession](class-cake.http.session.cachesession)
CacheSession provides method for saving sessions into a Cache engine. Used with Session
* ##### [DatabaseSession](class-cake.http.session.databasesession)
DatabaseSession provides methods to be used with Session.
cakephp Class LocaleSelectorMiddleware Class LocaleSelectorMiddleware
===============================
Sets the runtime default locale for the request based on the Accept-Language header. The default will only be set if it matches the list of passed valid locales.
**Namespace:** [Cake\I18n\Middleware](namespace-cake.i18n.middleware)
Property Summary
----------------
* [$locales](#%24locales) protected `array` List of valid locales for the request
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [process()](#process()) public
Set locale based on request headers.
Method Detail
-------------
### \_\_construct() public
```
__construct(array $locales = [])
```
Constructor.
#### Parameters
`array` $locales optional A list of accepted locales, or ['\*'] to accept any locale header value.
### process() public
```
process(ServerRequestInterface $request, RequestHandlerInterface $handler): Psr\Http\Message\ResponseInterface
```
Set locale based on request headers.
Processes an incoming server request in order to produce a response. If unable to produce the response itself, it may delegate to the provided request handler to do so.
#### Parameters
`ServerRequestInterface` $request The request.
`RequestHandlerInterface` $handler The request handler.
#### Returns
`Psr\Http\Message\ResponseInterface`
Property Detail
---------------
### $locales protected
List of valid locales for the request
#### Type
`array`
cakephp Interface EventManagerInterface Interface EventManagerInterface
================================
Interface EventManagerInterface
**Namespace:** [Cake\Event](namespace-cake.event)
Method Summary
--------------
* ##### [dispatch()](#dispatch()) public
Dispatches a new event to all configured listeners
* ##### [listeners()](#listeners()) public
Returns a list of all listeners for an eventKey in the order they should be called
* ##### [off()](#off()) public
Remove a listener from the active listeners.
* ##### [on()](#on()) public
Adds a new listener to an event.
Method Detail
-------------
### dispatch() public
```
dispatch(Cake\Event\EventInterface|string $event): Cake\Event\EventInterface
```
Dispatches a new event to all configured listeners
#### Parameters
`Cake\Event\EventInterface|string` $event The event key name or instance of EventInterface.
#### Returns
`Cake\Event\EventInterface`
### listeners() public
```
listeners(string $eventKey): array
```
Returns a list of all listeners for an eventKey in the order they should be called
#### Parameters
`string` $eventKey Event key.
#### Returns
`array`
### off() public
```
off(Cake\Event\EventListenerInterface|callable|string $eventKey, Cake\Event\EventListenerInterface|callable|null $callable = null): $this
```
Remove a listener from the active listeners.
Remove a EventListenerInterface entirely:
```
$manager->off($listener);
```
Remove all listeners for a given event:
```
$manager->off('My.event');
```
Remove a specific listener:
```
$manager->off('My.event', $callback);
```
Remove a callback from all events:
```
$manager->off($callback);
```
#### Parameters
`Cake\Event\EventListenerInterface|callable|string` $eventKey The event unique identifier name with which the callback has been associated, or the $listener you want to remove.
`Cake\Event\EventListenerInterface|callable|null` $callable optional The callback you want to detach.
#### Returns
`$this`
### on() public
```
on(Cake\Event\EventListenerInterface|string $eventKey, callable|array $options = [], callable|null $callable = null): $this
```
Adds a new listener to an event.
A variadic interface to add listeners that emulates jQuery.on().
Binding an EventListenerInterface:
```
$eventManager->on($listener);
```
Binding with no options:
```
$eventManager->on('Model.beforeSave', $callable);
```
Binding with options:
```
$eventManager->on('Model.beforeSave', ['priority' => 90], $callable);
```
#### Parameters
`Cake\Event\EventListenerInterface|string` $eventKey The event unique identifier name with which the callback will be associated. If $eventKey is an instance of Cake\Event\EventListenerInterface its events will be bound using the `implementedEvents()` methods.
`callable|array` $options optional Either an array of options or the callable you wish to bind to $eventKey. If an array of options, the `priority` key can be used to define the order. Priorities are treated as queues. Lower values are called before higher ones, and multiple attachments added to the same priority queue will be treated in the order of insertion.
`callable|null` $callable optional The callable function you want invoked.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
When event key is missing or callable is not an instance of Cake\Event\EventListenerInterface.
cakephp Namespace Middleware Namespace Middleware
====================
### Classes
* ##### [BodyParserMiddleware](class-cake.http.middleware.bodyparsermiddleware)
Parse encoded request body data.
* ##### [ClosureDecoratorMiddleware](class-cake.http.middleware.closuredecoratormiddleware)
Decorate closures as PSR-15 middleware.
* ##### [CspMiddleware](class-cake.http.middleware.cspmiddleware)
Content Security Policy Middleware
* ##### [CsrfProtectionMiddleware](class-cake.http.middleware.csrfprotectionmiddleware)
Provides CSRF protection & validation.
* ##### [DoublePassDecoratorMiddleware](class-cake.http.middleware.doublepassdecoratormiddleware)
Decorate double-pass middleware as PSR-15 middleware.
* ##### [EncryptedCookieMiddleware](class-cake.http.middleware.encryptedcookiemiddleware)
Middleware for encrypting & decrypting cookies.
* ##### [HttpsEnforcerMiddleware](class-cake.http.middleware.httpsenforcermiddleware)
Enforces use of HTTPS (SSL) for requests.
* ##### [SecurityHeadersMiddleware](class-cake.http.middleware.securityheadersmiddleware)
Handles common security headers in a convenient way
* ##### [SessionCsrfProtectionMiddleware](class-cake.http.middleware.sessioncsrfprotectionmiddleware)
Provides CSRF protection via session based tokens.
cakephp Class Filesystem Class Filesystem
=================
This provides convenience wrappers around common filesystem queries.
This is an internal helper class that should not be used in application code as it provides no guarantee for compatibility.
**Namespace:** [Cake\Filesystem](namespace-cake.filesystem)
Constants
---------
* `string` **TYPE\_DIR**
```
'dir'
```
Directory type constant
Method Summary
--------------
* ##### [copyDir()](#copyDir()) public
Copies directory with all it's contents.
* ##### [deleteDir()](#deleteDir()) public
Delete directory along with all it's contents.
* ##### [dumpFile()](#dumpFile()) public
Dump contents to file.
* ##### [filterIterator()](#filterIterator()) protected
Wrap iterator in additional filtering iterator.
* ##### [find()](#find()) public
Find files / directories (non-recursively) in given directory path.
* ##### [findRecursive()](#findRecursive()) public
Find files/ directories recursively in given directory path.
* ##### [isStream()](#isStream()) public
Check whether the given path is a stream path.
* ##### [mkdir()](#mkdir()) public
Create directory.
Method Detail
-------------
### copyDir() public
```
copyDir(string $source, string $destination): bool
```
Copies directory with all it's contents.
#### Parameters
`string` $source Source path.
`string` $destination Destination path.
#### Returns
`bool`
### deleteDir() public
```
deleteDir(string $path): bool
```
Delete directory along with all it's contents.
#### Parameters
`string` $path Directory path.
#### Returns
`bool`
#### Throws
`Cake\Core\Exception\CakeException`
If path is not a directory. ### dumpFile() public
```
dumpFile(string $filename, string $content): void
```
Dump contents to file.
#### Parameters
`string` $filename File path.
`string` $content Content to dump.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
When dumping fails. ### filterIterator() protected
```
filterIterator(Iterator $iterator, mixed $filter): Iterator
```
Wrap iterator in additional filtering iterator.
#### Parameters
`Iterator` $iterator Iterator
`mixed` $filter Regex string or callback.
#### Returns
`Iterator`
### find() public
```
find(string $path, mixed $filter = null, int|null $flags = null): Iterator
```
Find files / directories (non-recursively) in given directory path.
#### Parameters
`string` $path Directory path.
`mixed` $filter optional If string will be used as regex for filtering using `RegexIterator`, if callable will be as callback for `CallbackFilterIterator`.
`int|null` $flags optional Flags for FilesystemIterator::\_\_construct();
#### Returns
`Iterator`
### findRecursive() public
```
findRecursive(string $path, mixed $filter = null, int|null $flags = null): Iterator
```
Find files/ directories recursively in given directory path.
#### Parameters
`string` $path Directory path.
`mixed` $filter optional If string will be used as regex for filtering using `RegexIterator`, if callable will be as callback for `CallbackFilterIterator`. Hidden directories (starting with dot e.g. .git) are always skipped.
`int|null` $flags optional Flags for FilesystemIterator::\_\_construct();
#### Returns
`Iterator`
### isStream() public
```
isStream(string $path): bool
```
Check whether the given path is a stream path.
#### Parameters
`string` $path Path.
#### Returns
`bool`
### mkdir() public
```
mkdir(string $dir, int $mode = 0755): void
```
Create directory.
#### Parameters
`string` $dir Directory path.
`int` $mode optional Octal mode passed to mkdir(). Defaults to 0755.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
When directory creation fails.
cakephp Class TransportRegistry Class TransportRegistry
========================
An object registry for mailer transports.
**Namespace:** [Cake\Mailer](namespace-cake.mailer)
Property Summary
----------------
* [$\_loaded](#%24_loaded) protected `array<object>` Map of loaded objects.
Method Summary
--------------
* ##### [\_\_debugInfo()](#__debugInfo()) public
Debug friendly object properties.
* ##### [\_\_get()](#__get()) public
Provide public read access to the loaded objects
* ##### [\_\_isset()](#__isset()) public
Provide isset access to \_loaded
* ##### [\_\_set()](#__set()) public
Sets an object.
* ##### [\_\_unset()](#__unset()) public
Unsets an object.
* ##### [\_checkDuplicate()](#_checkDuplicate()) protected
Check for duplicate object loading.
* ##### [\_create()](#_create()) protected
Create the mailer transport instance.
* ##### [\_resolveClassName()](#_resolveClassName()) protected
Resolve a mailer tranport classname.
* ##### [\_throwMissingClassError()](#_throwMissingClassError()) protected
Throws an exception when a cache engine is missing.
* ##### [count()](#count()) public
Returns the number of loaded objects.
* ##### [get()](#get()) public
Get loaded object instance.
* ##### [getIterator()](#getIterator()) public
Returns an array iterator.
* ##### [has()](#has()) public
Check whether a given object is loaded.
* ##### [load()](#load()) public
Loads/constructs an object instance.
* ##### [loaded()](#loaded()) public
Get the list of loaded objects.
* ##### [normalizeArray()](#normalizeArray()) public
Normalizes an object array, creates an array that makes lazy loading easier
* ##### [reset()](#reset()) public
Clear loaded instances in the registry.
* ##### [set()](#set()) public
Set an object directly into the registry by name.
* ##### [unload()](#unload()) public
Remove a single adapter from the registry.
Method Detail
-------------
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Debug friendly object properties.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): object|null
```
Provide public read access to the loaded objects
#### Parameters
`string` $name Name of property to read
#### Returns
`object|null`
### \_\_isset() public
```
__isset(string $name): bool
```
Provide isset access to \_loaded
#### Parameters
`string` $name Name of object being checked.
#### Returns
`bool`
### \_\_set() public
```
__set(string $name, object $object): void
```
Sets an object.
#### Parameters
`string` $name Name of a property to set.
`object` $object Object to set.
#### Returns
`void`
### \_\_unset() public
```
__unset(string $name): void
```
Unsets an object.
#### Parameters
`string` $name Name of a property to unset.
#### Returns
`void`
### \_checkDuplicate() protected
```
_checkDuplicate(string $name, array<string, mixed> $config): void
```
Check for duplicate object loading.
If a duplicate is being loaded and has different configuration, that is bad and an exception will be raised.
An exception is raised, as replacing the object will not update any references other objects may have. Additionally, simply updating the runtime configuration is not a good option as we may be missing important constructor logic dependent on the configuration.
#### Parameters
`string` $name The name of the alias in the registry.
`array<string, mixed>` $config The config data for the new instance.
#### Returns
`void`
#### Throws
`RuntimeException`
When a duplicate is found. ### \_create() protected
```
_create(object|string $class, string $alias, array<string, mixed> $config): Cake\Mailer\AbstractTransport
```
Create the mailer transport instance.
Part of the template method for Cake\Core\ObjectRegistry::load()
#### Parameters
`object|string` $class The classname or object to make.
`string` $alias The alias of the object.
`array<string, mixed>` $config An array of settings to use for the cache engine.
#### Returns
`Cake\Mailer\AbstractTransport`
#### Throws
`RuntimeException`
when an object doesn't implement the correct interface. ### \_resolveClassName() protected
```
_resolveClassName(string $class): string|null
```
Resolve a mailer tranport classname.
Part of the template method for Cake\Core\ObjectRegistry::load()
#### Parameters
`string` $class Partial classname to resolve or transport instance.
#### Returns
`string|null`
### \_throwMissingClassError() protected
```
_throwMissingClassError(string $class, string|null $plugin): void
```
Throws an exception when a cache engine is missing.
Part of the template method for Cake\Core\ObjectRegistry::load()
#### Parameters
`string` $class The classname that is missing.
`string|null` $plugin The plugin the cache is missing in.
#### Returns
`void`
#### Throws
`BadMethodCallException`
### count() public
```
count(): int
```
Returns the number of loaded objects.
#### Returns
`int`
### get() public
```
get(string $name): object
```
Get loaded object instance.
#### Parameters
`string` $name Name of object.
#### Returns
`object`
#### Throws
`RuntimeException`
If not loaded or found. ### getIterator() public
```
getIterator(): Traversable
```
Returns an array iterator.
#### Returns
`Traversable`
### has() public
```
has(string $name): bool
```
Check whether a given object is loaded.
#### Parameters
`string` $name The object name to check for.
#### Returns
`bool`
### load() public
```
load(string $name, array<string, mixed> $config = []): mixed
```
Loads/constructs an object instance.
Will return the instance in the registry if it already exists. If a subclass provides event support, you can use `$config['enabled'] = false` to exclude constructed objects from being registered for events.
Using {@link \Cake\Controller\Component::$components} as an example. You can alias an object by setting the 'className' key, i.e.,
```
protected $components = [
'Email' => [
'className' => 'App\Controller\Component\AliasedEmailComponent'
];
];
```
All calls to the `Email` component would use `AliasedEmail` instead.
#### Parameters
`string` $name The name/class of the object to load.
`array<string, mixed>` $config optional Additional settings to use when loading the object.
#### Returns
`mixed`
#### Throws
`Exception`
If the class cannot be found. ### loaded() public
```
loaded(): array<string>
```
Get the list of loaded objects.
#### Returns
`array<string>`
### normalizeArray() public
```
normalizeArray(array $objects): array<string, array>
```
Normalizes an object array, creates an array that makes lazy loading easier
#### Parameters
`array` $objects Array of child objects to normalize.
#### Returns
`array<string, array>`
### reset() public
```
reset(): $this
```
Clear loaded instances in the registry.
If the registry subclass has an event manager, the objects will be detached from events as well.
#### Returns
`$this`
### set() public
```
set(string $name, object $object): $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
#### Parameters
`string` $name The name of the object to set in the registry.
`object` $object instance to store in the registry
#### Returns
`$this`
### unload() public
```
unload(string $name): $this
```
Remove a single adapter from the registry.
If this registry has an event manager, the object will be detached from any events as well.
#### Parameters
`string` $name The adapter name.
#### Returns
`$this`
Property Detail
---------------
### $\_loaded protected
Map of loaded objects.
#### Type
`array<object>`
| programming_docs |
cakephp Class Cache Class Cache
============
Cache provides a consistent interface to Caching in your application. It allows you to use several different Cache engines, without coupling your application to a specific implementation. It also allows you to change out cache storage or configuration without effecting the rest of your application.
### Configuring Cache engines
You can configure Cache engines in your application's `Config/cache.php` file. A sample configuration would be:
```
Cache::config('shared', [
'className' => Cake\Cache\Engine\ApcuEngine::class,
'prefix' => 'my_app_'
]);
```
This would configure an APCu cache engine to the 'shared' alias. You could then read and write to that cache alias by using it for the `$config` parameter in the various Cache methods.
In general all Cache operations are supported by all cache engines. However, Cache::increment() and Cache::decrement() are not supported by File caching.
There are 7 built-in caching engines:
* `ApcuEngine` - Uses the APCu object cache, one of the fastest caching engines.
* `ArrayEngine` - Uses only memory to store all data, not actually a persistent engine. Can be useful in test or CLI environment.
* `FileEngine` - Uses simple files to store content. Poor performance, but good for storing large objects, or things that are not IO sensitive. Well suited to development as it is an easy cache to inspect and manually flush.
* `MemcacheEngine` - Uses the PECL::Memcache extension and Memcached for storage. Fast reads/writes, and benefits from memcache being distributed.
* `RedisEngine` - Uses redis and php-redis extension to store cache data.
* `WincacheEngine` - Uses Windows Cache Extension for PHP. Supports wincache 1.1.0 and higher. This engine is recommended to people deploying on windows with IIS.
* `XcacheEngine` - Uses the Xcache extension, an alternative to APCu.
See Cache engine documentation for expected configuration keys.
**Namespace:** [Cake\Cache](namespace-cake.cache)
**See:** config/app.php for configuration settings
Property Summary
----------------
* [$\_config](#%24_config) protected static `array<string, mixed>` Configuration sets.
* [$\_dsnClassMap](#%24_dsnClassMap) protected static `array<string, string>` An array mapping URL schemes to fully qualified caching engine class names.
* [$\_enabled](#%24_enabled) protected static `bool` Flag for tracking whether caching is enabled.
* [$\_groups](#%24_groups) protected static `array<string, array>` Group to Config mapping
* [$\_registry](#%24_registry) protected static `Cake\Cache\CacheRegistry|null` Cache Registry used for creating and using cache adapters.
Method Summary
--------------
* ##### [\_buildEngine()](#_buildEngine()) protected static
Finds and builds the instance of the required engine class.
* ##### [add()](#add()) public static
Write data for key into a cache engine if it doesn't exist already.
* ##### [clear()](#clear()) public static
Delete all keys from the cache.
* ##### [clearAll()](#clearAll()) public static
Delete all keys from the cache from all configurations.
* ##### [clearGroup()](#clearGroup()) public static
Delete all keys from the cache belonging to the same group.
* ##### [configured()](#configured()) public static
Returns an array containing the named configurations
* ##### [decrement()](#decrement()) public static
Decrement a number under the key and return decremented value.
* ##### [delete()](#delete()) public static
Delete a key from the cache.
* ##### [deleteMany()](#deleteMany()) public static
Delete many keys from the cache.
* ##### [disable()](#disable()) public static
Disable caching.
* ##### [drop()](#drop()) public static
Drops a constructed adapter.
* ##### [enable()](#enable()) public static
Re-enable caching.
* ##### [enabled()](#enabled()) public static
Check whether caching is enabled.
* ##### [engine()](#engine()) public static deprecated
Get a cache engine object for the named cache config.
* ##### [getConfig()](#getConfig()) public static
Reads existing configuration.
* ##### [getConfigOrFail()](#getConfigOrFail()) public static
Reads existing configuration for a specific key.
* ##### [getDsnClassMap()](#getDsnClassMap()) public static
Returns the DSN class map for this class.
* ##### [getRegistry()](#getRegistry()) public static
Returns the Cache Registry instance used for creating and using cache adapters.
* ##### [groupConfigs()](#groupConfigs()) public static
Retrieve group names to config mapping.
* ##### [increment()](#increment()) public static
Increment a number under the key and return incremented value.
* ##### [parseDsn()](#parseDsn()) public static
Parses a DSN into a valid connection configuration
* ##### [pool()](#pool()) public static
Get a SimpleCacheEngine object for the named cache pool.
* ##### [read()](#read()) public static
Read a key from the cache.
* ##### [readMany()](#readMany()) public static
Read multiple keys from the cache.
* ##### [remember()](#remember()) public static
Provides the ability to easily do read-through caching.
* ##### [setConfig()](#setConfig()) public static
This method can be used to define configuration adapters for an application.
* ##### [setDsnClassMap()](#setDsnClassMap()) public static
Updates the DSN class map for this class.
* ##### [setRegistry()](#setRegistry()) public static
Sets the Cache Registry instance used for creating and using cache adapters.
* ##### [write()](#write()) public static
Write data for key into cache.
* ##### [writeMany()](#writeMany()) public static
Write data for many keys into cache.
Method Detail
-------------
### \_buildEngine() protected static
```
_buildEngine(string $name): void
```
Finds and builds the instance of the required engine class.
#### Parameters
`string` $name Name of the config array that needs an engine instance built
#### Returns
`void`
#### Throws
`Cake\Cache\InvalidArgumentException`
When a cache engine cannot be created.
`RuntimeException`
If loading of the engine failed. ### add() public static
```
add(string $key, mixed $value, string $config = 'default'): bool
```
Write data for key into a cache engine if it doesn't exist already.
### Usage:
Writing to the active cache config:
```
Cache::add('cached_data', $data);
```
Writing to a specific cache config:
```
Cache::add('cached_data', $data, 'long_term');
```
#### Parameters
`string` $key Identifier for the data.
`mixed` $value Data to be cached - anything except a resource.
`string` $config optional Optional string configuration name to write to. Defaults to 'default'.
#### Returns
`bool`
### clear() public static
```
clear(string $config = 'default'): bool
```
Delete all keys from the cache.
#### Parameters
`string` $config optional name of the configuration to use. Defaults to 'default'
#### Returns
`bool`
### clearAll() public static
```
clearAll(): array<string, bool>
```
Delete all keys from the cache from all configurations.
#### Returns
`array<string, bool>`
### clearGroup() public static
```
clearGroup(string $group, string $config = 'default'): bool
```
Delete all keys from the cache belonging to the same group.
#### Parameters
`string` $group name of the group to be cleared
`string` $config optional name of the configuration to use. Defaults to 'default'
#### Returns
`bool`
### configured() public static
```
configured(): array<string>
```
Returns an array containing the named configurations
#### Returns
`array<string>`
### decrement() public static
```
decrement(string $key, int $offset = 1, string $config = 'default'): int|false
```
Decrement a number under the key and return decremented value.
#### Parameters
`string` $key Identifier for the data
`int` $offset optional How much to subtract
`string` $config optional Optional string configuration name. Defaults to 'default'
#### Returns
`int|false`
#### Throws
`Cake\Cache\InvalidArgumentException`
when offset < 0 ### delete() public static
```
delete(string $key, string $config = 'default'): bool
```
Delete a key from the cache.
### Usage:
Deleting from the active cache configuration.
```
Cache::delete('my_data');
```
Deleting from a specific cache configuration.
```
Cache::delete('my_data', 'long_term');
```
#### Parameters
`string` $key Identifier for the data
`string` $config optional name of the configuration to use. Defaults to 'default'
#### Returns
`bool`
### deleteMany() public static
```
deleteMany(iterable $keys, string $config = 'default'): bool
```
Delete many keys from the cache.
### Usage:
Deleting multiple keys from the active cache configuration.
```
Cache::deleteMany(['my_data_1', 'my_data_2']);
```
Deleting from a specific cache configuration.
```
Cache::deleteMany(['my_data_1', 'my_data_2], 'long_term');
```
#### Parameters
`iterable` $keys Array or Traversable of cache keys to be deleted
`string` $config optional name of the configuration to use. Defaults to 'default'
#### Returns
`bool`
#### Throws
`Cake\Cache\InvalidArgumentException`
### disable() public static
```
disable(): void
```
Disable caching.
When disabled all cache operations will return null.
#### Returns
`void`
### drop() public static
```
drop(string $config): bool
```
Drops a constructed adapter.
If you wish to modify an existing configuration, you should drop it, change configuration and then re-add it.
If the implementing objects supports a `$_registry` object the named configuration will also be unloaded from the registry.
#### Parameters
`string` $config An existing configuration you wish to remove.
#### Returns
`bool`
### enable() public static
```
enable(): void
```
Re-enable caching.
If caching has been disabled with Cache::disable() this method will reverse that effect.
#### Returns
`void`
### enabled() public static
```
enabled(): bool
```
Check whether caching is enabled.
#### Returns
`bool`
### engine() public static
```
engine(string $config): Psr\SimpleCache\CacheInterfaceCake\Cache\CacheEngineInterface
```
Get a cache engine object for the named cache config.
#### Parameters
`string` $config The name of the configured cache backend.
#### Returns
`Psr\SimpleCache\CacheInterfaceCake\Cache\CacheEngineInterface`
### getConfig() public static
```
getConfig(string $key): mixed|null
```
Reads existing configuration.
#### Parameters
`string` $key The name of the configuration.
#### Returns
`mixed|null`
### getConfigOrFail() public static
```
getConfigOrFail(string $key): mixed
```
Reads existing configuration for a specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The name of the configuration.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
If value does not exist. ### getDsnClassMap() public static
```
getDsnClassMap(): array<string, string>
```
Returns the DSN class map for this class.
#### Returns
`array<string, string>`
### getRegistry() public static
```
getRegistry(): Cake\Cache\CacheRegistry
```
Returns the Cache Registry instance used for creating and using cache adapters.
#### Returns
`Cake\Cache\CacheRegistry`
### groupConfigs() public static
```
groupConfigs(string|null $group = null): array<string, array>
```
Retrieve group names to config mapping.
```
Cache::config('daily', ['duration' => '1 day', 'groups' => ['posts']]);
Cache::config('weekly', ['duration' => '1 week', 'groups' => ['posts', 'archive']]);
$configs = Cache::groupConfigs('posts');
```
$configs will equal to `['posts' => ['daily', 'weekly']]` Calling this method will load all the configured engines.
#### Parameters
`string|null` $group optional Group name or null to retrieve all group mappings
#### Returns
`array<string, array>`
#### Throws
`Cake\Cache\InvalidArgumentException`
### increment() public static
```
increment(string $key, int $offset = 1, string $config = 'default'): int|false
```
Increment a number under the key and return incremented value.
#### Parameters
`string` $key Identifier for the data
`int` $offset optional How much to add
`string` $config optional Optional string configuration name. Defaults to 'default'
#### Returns
`int|false`
#### Throws
`Cake\Cache\InvalidArgumentException`
When offset < 0 ### parseDsn() public static
```
parseDsn(string $dsn): array<string, mixed>
```
Parses a DSN into a valid connection configuration
This method allows setting a DSN using formatting similar to that used by PEAR::DB. The following is an example of its usage:
```
$dsn = 'mysql://user:pass@localhost/database?';
$config = ConnectionManager::parseDsn($dsn);
$dsn = 'Cake\Log\Engine\FileLog://?types=notice,info,debug&file=debug&path=LOGS';
$config = Log::parseDsn($dsn);
$dsn = 'smtp://user:secret@localhost:25?timeout=30&client=null&tls=null';
$config = Email::parseDsn($dsn);
$dsn = 'file:///?className=\My\Cache\Engine\FileEngine';
$config = Cache::parseDsn($dsn);
$dsn = 'File://?prefix=myapp_cake_core_&serialize=true&duration=+2 minutes&path=/tmp/persistent/';
$config = Cache::parseDsn($dsn);
```
For all classes, the value of `scheme` is set as the value of both the `className` unless they have been otherwise specified.
Note that querystring arguments are also parsed and set as values in the returned configuration.
#### Parameters
`string` $dsn The DSN string to convert to a configuration array
#### Returns
`array<string, mixed>`
#### Throws
`InvalidArgumentException`
If not passed a string, or passed an invalid string ### pool() public static
```
pool(string $config): Psr\SimpleCache\CacheInterfaceCake\Cache\CacheEngineInterface
```
Get a SimpleCacheEngine object for the named cache pool.
#### Parameters
`string` $config The name of the configured cache backend.
#### Returns
`Psr\SimpleCache\CacheInterfaceCake\Cache\CacheEngineInterface`
### read() public static
```
read(string $key, string $config = 'default'): mixed
```
Read a key from the cache.
### Usage:
Reading from the active cache configuration.
```
Cache::read('my_data');
```
Reading from a specific cache configuration.
```
Cache::read('my_data', 'long_term');
```
#### Parameters
`string` $key Identifier for the data
`string` $config optional optional name of the configuration to use. Defaults to 'default'
#### Returns
`mixed`
### readMany() public static
```
readMany(iterable $keys, string $config = 'default'): iterable
```
Read multiple keys from the cache.
### Usage:
Reading multiple keys from the active cache configuration.
```
Cache::readMany(['my_data_1', 'my_data_2]);
```
Reading from a specific cache configuration.
```
Cache::readMany(['my_data_1', 'my_data_2], 'long_term');
```
#### Parameters
`iterable` $keys An array or Traversable of keys to fetch from the cache
`string` $config optional optional name of the configuration to use. Defaults to 'default'
#### Returns
`iterable`
#### Throws
`Cake\Cache\InvalidArgumentException`
### remember() public static
```
remember(string $key, callable $callable, string $config = 'default'): mixed
```
Provides the ability to easily do read-through caching.
When called if the $key is not set in $config, the $callable function will be invoked. The results will then be stored into the cache config at key.
Examples:
Using a Closure to provide data, assume `$this` is a Table object:
```
$results = Cache::remember('all_articles', function () {
return $this->find('all')->toArray();
});
```
#### Parameters
`string` $key The cache key to read/store data at.
`callable` $callable The callable that provides data in the case when the cache key is empty. Can be any callable type supported by your PHP.
`string` $config optional The cache configuration to use for this operation. Defaults to default.
#### Returns
`mixed`
### setConfig() public static
```
setConfig(array<string, mixed>|string $key, object|array<string, mixed>|null $config = null): void
```
This method can be used to define configuration adapters for an application.
To change an adapter's configuration at runtime, first drop the adapter and then reconfigure it.
Adapters will not be constructed until the first operation is done.
### Usage
Assuming that the class' name is `Cache` the following scenarios are supported:
Setting a cache engine up.
```
Cache::setConfig('default', $settings);
```
Injecting a constructed adapter in:
```
Cache::setConfig('default', $instance);
```
Configure multiple adapters at once:
```
Cache::setConfig($arrayOfConfig);
```
#### Parameters
`array<string, mixed>|string` $key The name of the configuration, or an array of multiple configs.
`object|array<string, mixed>|null` $config optional An array of name => configuration data for adapter.
#### Returns
`void`
#### Throws
`BadMethodCallException`
When trying to modify an existing config.
`LogicException`
When trying to store an invalid structured config array. ### setDsnClassMap() public static
```
setDsnClassMap(array<string, string> $map): void
```
Updates the DSN class map for this class.
#### Parameters
`array<string, string>` $map Additions/edits to the class map to apply.
#### Returns
`void`
### setRegistry() public static
```
setRegistry(Cake\Cache\CacheRegistry $registry): void
```
Sets the Cache Registry instance used for creating and using cache adapters.
Also allows for injecting of a new registry instance.
#### Parameters
`Cake\Cache\CacheRegistry` $registry Injectable registry object.
#### Returns
`void`
### write() public static
```
write(string $key, mixed $value, string $config = 'default'): bool
```
Write data for key into cache.
### Usage:
Writing to the active cache config:
```
Cache::write('cached_data', $data);
```
Writing to a specific cache config:
```
Cache::write('cached_data', $data, 'long_term');
```
#### Parameters
`string` $key Identifier for the data
`mixed` $value Data to be cached - anything except a resource
`string` $config optional Optional string configuration name to write to. Defaults to 'default'
#### Returns
`bool`
### writeMany() public static
```
writeMany(iterable $data, string $config = 'default'): bool
```
Write data for many keys into cache.
### Usage:
Writing to the active cache config:
```
Cache::writeMany(['cached_data_1' => 'data 1', 'cached_data_2' => 'data 2']);
```
Writing to a specific cache config:
```
Cache::writeMany(['cached_data_1' => 'data 1', 'cached_data_2' => 'data 2'], 'long_term');
```
#### Parameters
`iterable` $data An array or Traversable of data to be stored in the cache
`string` $config optional Optional string configuration name to write to. Defaults to 'default'
#### Returns
`bool`
#### Throws
`Cake\Cache\InvalidArgumentException`
Property Detail
---------------
### $\_config protected static
Configuration sets.
#### Type
`array<string, mixed>`
### $\_dsnClassMap protected static
An array mapping URL schemes to fully qualified caching engine class names.
#### Type
`array<string, string>`
### $\_enabled protected static
Flag for tracking whether caching is enabled.
#### Type
`bool`
### $\_groups protected static
Group to Config mapping
#### Type
`array<string, array>`
### $\_registry protected static
Cache Registry used for creating and using cache adapters.
#### Type
`Cake\Cache\CacheRegistry|null`
| programming_docs |
cakephp Class TestFixture Class TestFixture
==================
Cake TestFixture is responsible for building and destroying tables to be used during testing.
**Namespace:** [Cake\TestSuite\Fixture](namespace-cake.testsuite.fixture)
Property Summary
----------------
* [$\_constraints](#%24_constraints) protected `array<string, mixed>` Fixture constraints to be created.
* [$\_schema](#%24_schema) protected `Cake\Database\Schema\TableSchemaInterfaceCake\Database\Schema\SqlGeneratorInterface` The schema for this fixture.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$connection](#%24connection) public `string` Fixture Datasource
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
* [$fields](#%24fields) public `array` Fields / Schema for the fixture.
* [$import](#%24import) public `array|null` Configuration for importing fixture schema
* [$records](#%24records) public `array` Fixture records to be inserted.
* [$table](#%24table) public `string` Full Table Name
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Instantiate the fixture.
* ##### [\_getRecords()](#_getRecords()) protected
Converts the internal records into data used to generate a query.
* ##### [\_schemaFromFields()](#_schemaFromFields()) protected
Build the fixtures table schema from the fields property.
* ##### [\_schemaFromImport()](#_schemaFromImport()) protected
Build fixture schema from a table in another datasource.
* ##### [\_schemaFromReflection()](#_schemaFromReflection()) protected
Build fixture schema directly from the datasource
* ##### [\_tableFromClass()](#_tableFromClass()) protected
Returns the table name using the fixture class
* ##### [connection()](#connection()) public
Get the connection name this fixture should be inserted into.
* ##### [create()](#create()) public
Create the fixture schema/mapping/definition
* ##### [createConstraints()](#createConstraints()) public
Build and execute SQL queries necessary to create the constraints for the fixture
* ##### [drop()](#drop()) public
Run after all tests executed, should remove the table/collection from the connection.
* ##### [dropConstraints()](#dropConstraints()) public
Build and execute SQL queries necessary to drop the constraints for the fixture
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [getTableSchema()](#getTableSchema()) public
Get and set the schema for this fixture.
* ##### [init()](#init()) public
Initialize the fixture.
* ##### [insert()](#insert()) public
Run before each test is executed.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
* ##### [setTableSchema()](#setTableSchema()) public
Get and set the schema for this fixture.
* ##### [sourceName()](#sourceName()) public
Get the table/collection name for this fixture.
* ##### [truncate()](#truncate()) public
Truncates the current fixture.
Method Detail
-------------
### \_\_construct() public
```
__construct()
```
Instantiate the fixture.
#### Throws
`Cake\Core\Exception\CakeException`
on invalid datasource usage. ### \_getRecords() protected
```
_getRecords(): array
```
Converts the internal records into data used to generate a query.
#### Returns
`array`
### \_schemaFromFields() protected
```
_schemaFromFields(): void
```
Build the fixtures table schema from the fields property.
#### Returns
`void`
### \_schemaFromImport() protected
```
_schemaFromImport(): void
```
Build fixture schema from a table in another datasource.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
when trying to import from an empty table. ### \_schemaFromReflection() protected
```
_schemaFromReflection(): void
```
Build fixture schema directly from the datasource
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
when trying to reflect a table that does not exist ### \_tableFromClass() protected
```
_tableFromClass(): string
```
Returns the table name using the fixture class
#### Returns
`string`
### connection() public
```
connection(): string
```
Get the connection name this fixture should be inserted into.
#### Returns
`string`
### create() public
```
create(Cake\Datasource\ConnectionInterface $connection): bool
```
Create the fixture schema/mapping/definition
#### Parameters
`Cake\Datasource\ConnectionInterface` $connection #### Returns
`bool`
### createConstraints() public
```
createConstraints(Cake\Datasource\ConnectionInterface $connection): bool
```
Build and execute SQL queries necessary to create the constraints for the fixture
#### Parameters
`Cake\Datasource\ConnectionInterface` $connection #### Returns
`bool`
### drop() public
```
drop(Cake\Datasource\ConnectionInterface $connection): bool
```
Run after all tests executed, should remove the table/collection from the connection.
#### Parameters
`Cake\Datasource\ConnectionInterface` $connection #### Returns
`bool`
### dropConstraints() public
```
dropConstraints(Cake\Datasource\ConnectionInterface $connection): bool
```
Build and execute SQL queries necessary to drop the constraints for the fixture
#### Parameters
`Cake\Datasource\ConnectionInterface` $connection #### Returns
`bool`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### getTableSchema() public
```
getTableSchema(): Cake\Database\Schema\TableSchemaInterfaceCake\Database\Schema\SqlGeneratorInterface
```
Get and set the schema for this fixture.
#### Returns
`Cake\Database\Schema\TableSchemaInterfaceCake\Database\Schema\SqlGeneratorInterface`
### init() public
```
init(): void
```
Initialize the fixture.
#### Returns
`void`
#### Throws
`Cake\ORM\Exception\MissingTableClassException`
When importing from a table that does not exist. ### insert() public
```
insert(Cake\Datasource\ConnectionInterface $connection): Cake\Database\StatementInterface|bool
```
Run before each test is executed.
Should insert all the records into the test database.
#### Parameters
`Cake\Datasource\ConnectionInterface` $connection #### Returns
`Cake\Database\StatementInterface|bool`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
### setTableSchema() public
```
setTableSchema(Cake\Database\Schema\TableSchemaInterfaceCake\Database\Schema\SqlGeneratorInterface $schema): $this
```
Get and set the schema for this fixture.
#### Parameters
`Cake\Database\Schema\TableSchemaInterfaceCake\Database\Schema\SqlGeneratorInterface` $schema #### Returns
`$this`
### sourceName() public
```
sourceName(): string
```
Get the table/collection name for this fixture.
#### Returns
`string`
### truncate() public
```
truncate(Cake\Datasource\ConnectionInterface $connection): bool
```
Truncates the current fixture.
#### Parameters
`Cake\Datasource\ConnectionInterface` $connection #### Returns
`bool`
Property Detail
---------------
### $\_constraints protected
Fixture constraints to be created.
#### Type
`array<string, mixed>`
### $\_schema protected
The schema for this fixture.
#### Type
`Cake\Database\Schema\TableSchemaInterfaceCake\Database\Schema\SqlGeneratorInterface`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $connection public
Fixture Datasource
#### Type
`string`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
### $fields public
Fields / Schema for the fixture.
This array should be compatible with {@link \Cake\Database\Schema\Schema}. The `_constraints`, `_options` and `_indexes` keys are reserved for defining constraints, options and indexes respectively.
#### Type
`array`
### $import public
Configuration for importing fixture schema
Accepts a `connection` and `model` or `table` key, to define which table and which connection contain the schema to be imported.
#### Type
`array|null`
### $records public
Fixture records to be inserted.
#### Type
`array`
### $table public
Full Table Name
#### Type
`string`
cakephp Class JsonView Class JsonView
===============
A view class that is used for JSON responses.
It allows you to omit templates if you just need to emit JSON string as response.
In your controller, you could do the following:
```
$this->set(['posts' => $posts]);
$this->viewBuilder()->setOption('serialize', true);
```
When the view is rendered, the `$posts` view variable will be serialized into JSON.
You can also set multiple view variables for serialization. This will create a top level object containing all the named view variables:
```
$this->set(compact('posts', 'users', 'stuff'));
$this->viewBuilder()->setOption('serialize', true);
```
The above would generate a JSON object that looks like:
`{"posts": [...], "users": [...]}`
You can also set `'serialize'` to a string or array to serialize only the specified view variables.
If you don't set the `serialize` option, you will need a view template. You can use extended views to provide layout-like functionality.
You can also enable JSONP support by setting `jsonp` option to true or a string to specify custom query string parameter name which will contain the callback function name.
**Namespace:** [Cake\View](namespace-cake.view)
Constants
---------
* `string` **NAME\_TEMPLATE**
```
'templates'
```
Constant for type used for App::path().
* `string` **PLUGIN\_TEMPLATE\_FOLDER**
```
'plugin'
```
Constant for folder name containing files for overriding plugin templates.
* `string` **TYPE\_ELEMENT**
```
'element'
```
Constant for view file type 'element'
* `string` **TYPE\_LAYOUT**
```
'layout'
```
Constant for view file type 'layout'
* `string` **TYPE\_MATCH\_ALL**
```
'_match_all_'
```
The magic 'match-all' content type that views can use to behave as a fallback during content-type negotiation.
* `string` **TYPE\_TEMPLATE**
```
'template'
```
Constant for view file type 'template'.
Property Summary
----------------
* [$Blocks](#%24Blocks) public @property `Cake\View\ViewBlock`
* [$Breadcrumbs](#%24Breadcrumbs) public @property `Cake\View\Helper\BreadcrumbsHelper`
* [$Flash](#%24Flash) public @property `Cake\View\Helper\FlashHelper`
* [$Form](#%24Form) public @property `Cake\View\Helper\FormHelper`
* [$Html](#%24Html) public @property `Cake\View\Helper\HtmlHelper`
* [$Number](#%24Number) public @property `Cake\View\Helper\NumberHelper`
* [$Paginator](#%24Paginator) public @property `Cake\View\Helper\PaginatorHelper`
* [$Text](#%24Text) public @property `Cake\View\Helper\TextHelper`
* [$Time](#%24Time) public @property `Cake\View\Helper\TimeHelper`
* [$Url](#%24Url) public @property `Cake\View\Helper\UrlHelper`
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_current](#%24_current) protected `string` The currently rendering view file. Used for resolving parent files.
* [$\_currentType](#%24_currentType) protected `string` Currently rendering an element. Used for finding parent fragments for elements.
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config options.
* [$\_eventClass](#%24_eventClass) protected `string` Default class name for new event objects.
* [$\_eventManager](#%24_eventManager) protected `Cake\Event\EventManagerInterface|null` Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
* [$\_ext](#%24_ext) protected `string` File extension. Defaults to ".php".
* [$\_helpers](#%24_helpers) protected `Cake\View\HelperRegistry` Helpers collection
* [$\_parents](#%24_parents) protected `array<string>` The names of views and their parents used with View::extend();
* [$\_passedVars](#%24_passedVars) protected `array<string>` List of variables to collect from the associated controller.
* [$\_paths](#%24_paths) protected `array<string>` Holds an array of paths.
* [$\_pathsForPlugin](#%24_pathsForPlugin) protected `array<string[]>` Holds an array of plugin paths.
* [$\_responseType](#%24_responseType) protected deprecated `string` Response type.
* [$\_stack](#%24_stack) protected `array<string>` Content stack, used for nested templates that all use View::extend();
* [$\_viewBlockClass](#%24_viewBlockClass) protected `string` ViewBlock class.
* [$autoLayout](#%24autoLayout) protected `bool` Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered templates.
* [$elementCache](#%24elementCache) protected `string` The Cache configuration View will use to store cached elements. Changing this will change the default configuration elements are stored under. You can also choose a cache config per element.
* [$helpers](#%24helpers) protected `array` An array of names of built-in helpers to include.
* [$layout](#%24layout) protected `string` The name of the layout file to render the template inside of. The name specified is the filename of the layout in `templates/layout/` without the .php extension.
* [$layoutPath](#%24layoutPath) protected `string` JSON layouts are located in the JSON subdirectory of `Layouts/`
* [$name](#%24name) protected `string` Name of the controller that created the View if any.
* [$plugin](#%24plugin) protected `string|null` The name of the plugin.
* [$request](#%24request) protected `Cake\Http\ServerRequest` An instance of a \Cake\Http\ServerRequest object that contains information about the current request. This object contains all the information about a request and several methods for reading additional information about the request.
* [$response](#%24response) protected `Cake\Http\Response` Reference to the Response object
* [$subDir](#%24subDir) protected `string` JSON views are located in the 'json' subdirectory for controllers' views.
* [$template](#%24template) protected `string` The name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
* [$templatePath](#%24templatePath) protected `string` The name of the subfolder containing templates for this View.
* [$theme](#%24theme) protected `string|null` The view theme to use.
* [$viewVars](#%24viewVars) protected `array<string, mixed>` An array of variables
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_get()](#__get()) public
Magic accessor for helpers.
* ##### [\_checkFilePath()](#_checkFilePath()) protected
Check that a view file path does not go outside of the defined template paths.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_createCell()](#_createCell()) protected
Create and configure the cell instance.
* ##### [\_dataToSerialize()](#_dataToSerialize()) protected
Returns data to be serialized.
* ##### [\_elementCache()](#_elementCache()) protected
Generate the cache configuration options for an element.
* ##### [\_evaluate()](#_evaluate()) protected
Sandbox method to evaluate a template / view script in.
* ##### [\_getElementFileName()](#_getElementFileName()) protected
Finds an element filename, returns false on failure.
* ##### [\_getLayoutFileName()](#_getLayoutFileName()) protected
Returns layout filename for this template as a string.
* ##### [\_getSubPaths()](#_getSubPaths()) protected
Find all sub templates path, based on $basePath If a prefix is defined in the current request, this method will prepend the prefixed template path to the $basePath, cascading up in case the prefix is nested. This is essentially used to find prefixed template paths for elements and layouts.
* ##### [\_getTemplateFileName()](#_getTemplateFileName()) protected
Returns filename of given action's template file as a string. CamelCased action names will be under\_scored by default. This means that you can have LongActionNames that refer to long\_action\_names.php templates. You can change the inflection rule by overriding \_inflectTemplateFileName.
* ##### [\_inflectTemplateFileName()](#_inflectTemplateFileName()) protected
Change the name of a view template file into underscored format.
* ##### [\_paths()](#_paths()) protected
Return all possible paths to find view files in order
* ##### [\_render()](#_render()) protected
Renders and returns output for given template filename with its array of data. Handles parent/extended templates.
* ##### [\_renderElement()](#_renderElement()) protected
Renders an element and fires the before and afterRender callbacks for it and writes to the cache if a cache is used
* ##### [\_serialize()](#_serialize()) protected
Serialize view vars.
* ##### [append()](#append()) public
Append to an existing or new block.
* ##### [assign()](#assign()) public
Set the content for a block. This will overwrite any existing content.
* ##### [blocks()](#blocks()) public
Get the names of all the existing blocks.
* ##### [cache()](#cache()) public
Create a cached block of view logic.
* ##### [cell()](#cell()) protected
Renders the given cell.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [contentType()](#contentType()) public static
Mime-type this view class renders as.
* ##### [disableAutoLayout()](#disableAutoLayout()) public
Turns off CakePHP's conventional mode of applying layout files. Layouts will not be automatically applied to rendered views.
* ##### [dispatchEvent()](#dispatchEvent()) public
Wrapper for creating and dispatching events.
* ##### [element()](#element()) public
Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
* ##### [elementExists()](#elementExists()) public
Checks if an element exists
* ##### [enableAutoLayout()](#enableAutoLayout()) public
Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered views.
* ##### [end()](#end()) public
End a capturing block. The compliment to View::start()
* ##### [exists()](#exists()) public
Check if a block exists
* ##### [extend()](#extend()) public
Provides template or element extension/inheritance. Templates can extends a parent template and populate blocks in the parent template.
* ##### [fetch()](#fetch()) public
Fetch the content for a block. If a block is empty or undefined '' will be returned.
* ##### [get()](#get()) public
Returns the contents of the given View variable.
* ##### [getConfig()](#getConfig()) public
Get config value.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getCurrentType()](#getCurrentType()) public
Retrieve the current template type
* ##### [getElementPaths()](#getElementPaths()) protected
Get an iterator for element paths.
* ##### [getEventManager()](#getEventManager()) public
Returns the Cake\Event\EventManager manager instance for this object.
* ##### [getLayout()](#getLayout()) public
Get the name of the layout file to render the template inside of. The name specified is the filename of the layout in `templates/layout/` without the .php extension.
* ##### [getLayoutPath()](#getLayoutPath()) public
Get path for layout files.
* ##### [getLayoutPaths()](#getLayoutPaths()) protected
Get an iterator for layout paths.
* ##### [getName()](#getName()) public
Returns the View's controller name.
* ##### [getPlugin()](#getPlugin()) public
Returns the plugin name.
* ##### [getRequest()](#getRequest()) public
Gets the request instance.
* ##### [getResponse()](#getResponse()) public
Gets the response instance.
* ##### [getSubDir()](#getSubDir()) public
Get sub-directory for this template files.
* ##### [getTemplate()](#getTemplate()) public
Get the name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
* ##### [getTemplatePath()](#getTemplatePath()) public
Get path for templates files.
* ##### [getTheme()](#getTheme()) public
Get the current view theme.
* ##### [getVars()](#getVars()) public
Returns a list of variables available in the current View context
* ##### [helpers()](#helpers()) public
Get the helper registry in use by this View class.
* ##### [initialize()](#initialize()) public
Initialization hook method.
* ##### [isAutoLayoutEnabled()](#isAutoLayoutEnabled()) public
Returns if CakePHP's conventional mode of applying layout files is enabled. Disabled means that layouts will not be automatically applied to rendered views.
* ##### [loadHelper()](#loadHelper()) public
Loads a helper. Delegates to the `HelperRegistry::load()` to load the helper
* ##### [loadHelpers()](#loadHelpers()) public
Load helpers only if serialization is disabled.
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [pluginSplit()](#pluginSplit()) public
Splits a dot syntax plugin name into its plugin and filename. If $name does not have a dot, then index 0 will be null. It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
* ##### [prepend()](#prepend()) public
Prepend to an existing or new block.
* ##### [render()](#render()) public
Render a JSON view.
* ##### [renderLayout()](#renderLayout()) public
Renders a layout. Returns output from \_render().
* ##### [reset()](#reset()) public
Reset the content for a block. This will overwrite any existing content.
* ##### [set()](#set()) public
Saves a variable or an associative array of variables for use inside a template.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setContentType()](#setContentType()) protected
Set the response content-type based on the view's contentType()
* ##### [setElementCache()](#setElementCache()) public
Set The cache configuration View will use to store cached elements
* ##### [setEventManager()](#setEventManager()) public
Returns the Cake\Event\EventManagerInterface instance for this object.
* ##### [setLayout()](#setLayout()) public
Set the name of the layout file to render the template inside of. The name specified is the filename of the layout in `templates/layout/` without the .php extension.
* ##### [setLayoutPath()](#setLayoutPath()) public
Set path for layout files.
* ##### [setPlugin()](#setPlugin()) public
Sets the plugin name.
* ##### [setRequest()](#setRequest()) public
Sets the request objects and configures a number of controller properties based on the contents of the request. The properties that get set are:
* ##### [setResponse()](#setResponse()) public
Sets the response instance.
* ##### [setSubDir()](#setSubDir()) public
Set sub-directory for this template files.
* ##### [setTemplate()](#setTemplate()) public
Set the name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
* ##### [setTemplatePath()](#setTemplatePath()) public
Set path for templates files.
* ##### [setTheme()](#setTheme()) public
Set the view theme to use.
* ##### [start()](#start()) public
Start capturing output for a 'block'
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Http\ServerRequest|null $request = null, Cake\Http\Response|null $response = null, Cake\Event\EventManager|null $eventManager = null, array<string, mixed> $viewOptions = [])
```
Constructor
#### Parameters
`Cake\Http\ServerRequest|null` $request optional Request instance.
`Cake\Http\Response|null` $response optional Response instance.
`Cake\Event\EventManager|null` $eventManager optional Event manager instance.
`array<string, mixed>` $viewOptions optional View options. See {@link View::$\_passedVars} for list of options which get set as class properties.
### \_\_get() public
```
__get(string $name): Cake\View\Helper|null
```
Magic accessor for helpers.
#### Parameters
`string` $name Name of the attribute to get.
#### Returns
`Cake\View\Helper|null`
### \_checkFilePath() protected
```
_checkFilePath(string $file, string $path): string
```
Check that a view file path does not go outside of the defined template paths.
Only paths that contain `..` will be checked, as they are the ones most likely to have the ability to resolve to files outside of the template paths.
#### Parameters
`string` $file The path to the template file.
`string` $path Base path that $file should be inside of.
#### Returns
`string`
#### Throws
`InvalidArgumentException`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_createCell() protected
```
_createCell(string $className, string $action, string|null $plugin, array<string, mixed> $options): Cake\View\Cell
```
Create and configure the cell instance.
#### Parameters
`string` $className The cell classname.
`string` $action The action name.
`string|null` $plugin The plugin name.
`array<string, mixed>` $options The constructor options for the cell.
#### Returns
`Cake\View\Cell`
### \_dataToSerialize() protected
```
_dataToSerialize(array|string $serialize): mixed
```
Returns data to be serialized.
#### Parameters
`array|string` $serialize The name(s) of the view variable(s) that need(s) to be serialized.
#### Returns
`mixed`
### \_elementCache() protected
```
_elementCache(string $name, array $data, array<string, mixed> $options): array
```
Generate the cache configuration options for an element.
#### Parameters
`string` $name Element name
`array` $data Data
`array<string, mixed>` $options Element options
#### Returns
`array`
### \_evaluate() protected
```
_evaluate(string $templateFile, array $dataForView): string
```
Sandbox method to evaluate a template / view script in.
#### Parameters
`string` $templateFile Filename of the template.
`array` $dataForView Data to include in rendered view.
#### Returns
`string`
### \_getElementFileName() protected
```
_getElementFileName(string $name, bool $pluginCheck = true): string|false
```
Finds an element filename, returns false on failure.
#### Parameters
`string` $name The name of the element to find.
`bool` $pluginCheck optional * if false will ignore the request's plugin if parsed plugin is not loaded
#### Returns
`string|false`
### \_getLayoutFileName() protected
```
_getLayoutFileName(string|null $name = null): string
```
Returns layout filename for this template as a string.
#### Parameters
`string|null` $name optional The name of the layout to find.
#### Returns
`string`
#### Throws
`Cake\View\Exception\MissingLayoutException`
when a layout cannot be located
`RuntimeException`
### \_getSubPaths() protected
```
_getSubPaths(string $basePath): array<string>
```
Find all sub templates path, based on $basePath If a prefix is defined in the current request, this method will prepend the prefixed template path to the $basePath, cascading up in case the prefix is nested. This is essentially used to find prefixed template paths for elements and layouts.
#### Parameters
`string` $basePath Base path on which to get the prefixed one.
#### Returns
`array<string>`
### \_getTemplateFileName() protected
```
_getTemplateFileName(string|null $name = null): string
```
Returns filename of given action's template file as a string. CamelCased action names will be under\_scored by default. This means that you can have LongActionNames that refer to long\_action\_names.php templates. You can change the inflection rule by overriding \_inflectTemplateFileName.
#### Parameters
`string|null` $name optional Controller action to find template filename for
#### Returns
`string`
#### Throws
`Cake\View\Exception\MissingTemplateException`
when a template file could not be found.
`RuntimeException`
When template name not provided. ### \_inflectTemplateFileName() protected
```
_inflectTemplateFileName(string $name): string
```
Change the name of a view template file into underscored format.
#### Parameters
`string` $name Name of file which should be inflected.
#### Returns
`string`
### \_paths() protected
```
_paths(string|null $plugin = null, bool $cached = true): array<string>
```
Return all possible paths to find view files in order
#### Parameters
`string|null` $plugin optional Optional plugin name to scan for view files.
`bool` $cached optional Set to false to force a refresh of view paths. Default true.
#### Returns
`array<string>`
### \_render() protected
```
_render(string $templateFile, array $data = []): string
```
Renders and returns output for given template filename with its array of data. Handles parent/extended templates.
#### Parameters
`string` $templateFile Filename of the template
`array` $data optional Data to include in rendered view. If empty the current View::$viewVars will be used.
#### Returns
`string`
#### Throws
`LogicException`
When a block is left open. ### \_renderElement() protected
```
_renderElement(string $file, array $data, array<string, mixed> $options): string
```
Renders an element and fires the before and afterRender callbacks for it and writes to the cache if a cache is used
#### Parameters
`string` $file Element file path
`array` $data Data to render
`array<string, mixed>` $options Element options
#### Returns
`string`
### \_serialize() protected
```
_serialize(array|string $serialize): string
```
Serialize view vars.
#### Parameters
`array|string` $serialize #### Returns
`string`
### append() public
```
append(string $name, mixed $value = null): $this
```
Append to an existing or new block.
Appending to a new block will create the block.
#### Parameters
`string` $name Name of the block
`mixed` $value optional The content for the block. Value will be type cast to string.
#### Returns
`$this`
#### See Also
\Cake\View\ViewBlock::concat() ### assign() public
```
assign(string $name, mixed $value): $this
```
Set the content for a block. This will overwrite any existing content.
#### Parameters
`string` $name Name of the block
`mixed` $value The content for the block. Value will be type cast to string.
#### Returns
`$this`
#### See Also
\Cake\View\ViewBlock::set() ### blocks() public
```
blocks(): array<string>
```
Get the names of all the existing blocks.
#### Returns
`array<string>`
#### See Also
\Cake\View\ViewBlock::keys() ### cache() public
```
cache(callable $block, array<string, mixed> $options = []): string
```
Create a cached block of view logic.
This allows you to cache a block of view output into the cache defined in `elementCache`.
This method will attempt to read the cache first. If the cache is empty, the $block will be run and the output stored.
#### Parameters
`callable` $block The block of code that you want to cache the output of.
`array<string, mixed>` $options optional The options defining the cache key etc.
#### Returns
`string`
#### Throws
`RuntimeException`
When $options is lacking a 'key' option. ### cell() protected
```
cell(string $cell, array $data = [], array<string, mixed> $options = []): Cake\View\Cell
```
Renders the given cell.
Example:
```
// Taxonomy\View\Cell\TagCloudCell::smallList()
$cell = $this->cell('Taxonomy.TagCloud::smallList', ['limit' => 10]);
// App\View\Cell\TagCloudCell::smallList()
$cell = $this->cell('TagCloud::smallList', ['limit' => 10]);
```
The `display` action will be used by default when no action is provided:
```
// Taxonomy\View\Cell\TagCloudCell::display()
$cell = $this->cell('Taxonomy.TagCloud');
```
Cells are not rendered until they are echoed.
#### Parameters
`string` $cell You must indicate cell name, and optionally a cell action. e.g.: `TagCloud::smallList` will invoke `View\Cell\TagCloudCell::smallList()`, `display` action will be invoked by default when none is provided.
`array` $data optional Additional arguments for cell method. e.g.: `cell('TagCloud::smallList', ['a1' => 'v1', 'a2' => 'v2'])` maps to `View\Cell\TagCloud::smallList(v1, v2)`
`array<string, mixed>` $options optional Options for Cell's constructor
#### Returns
`Cake\View\Cell`
#### Throws
`Cake\View\Exception\MissingCellException`
If Cell class was not found. ### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### contentType() public static
```
contentType(): string
```
Mime-type this view class renders as.
#### Returns
`string`
### disableAutoLayout() public
```
disableAutoLayout(): $this
```
Turns off CakePHP's conventional mode of applying layout files. Layouts will not be automatically applied to rendered views.
#### Returns
`$this`
### dispatchEvent() public
```
dispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\EventInterface
```
Wrapper for creating and dispatching events.
Returns a dispatched event.
#### Parameters
`string` $name Name of the event.
`array|null` $data optional Any value you wish to be transported with this event to it can be read by listeners.
`object|null` $subject optional The object that this event applies to ($this by default).
#### Returns
`Cake\Event\EventInterface`
### element() public
```
element(string $name, array $data = [], array<string, mixed> $options = []): string
```
Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send data to be used in the element. Elements can be cached improving performance by using the `cache` option.
#### Parameters
`string` $name Name of template file in the `templates/element/` folder, or `MyPlugin.template` to use the template element from MyPlugin. If the element is not found in the plugin, the normal view path cascade will be searched.
`array` $data optional Array of data to be made available to the rendered view (i.e. the Element)
`array<string, mixed>` $options optional Array of options. Possible keys are:
#### Returns
`string`
#### Throws
`Cake\View\Exception\MissingElementException`
When an element is missing and `ignoreMissing` is false. ### elementExists() public
```
elementExists(string $name): bool
```
Checks if an element exists
#### Parameters
`string` $name Name of template file in the `templates/element/` folder, or `MyPlugin.template` to check the template element from MyPlugin. If the element is not found in the plugin, the normal view path cascade will be searched.
#### Returns
`bool`
### enableAutoLayout() public
```
enableAutoLayout(bool $enable = true): $this
```
Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered views.
#### Parameters
`bool` $enable optional Boolean to turn on/off.
#### Returns
`$this`
### end() public
```
end(): $this
```
End a capturing block. The compliment to View::start()
#### Returns
`$this`
#### See Also
\Cake\View\ViewBlock::end() ### exists() public
```
exists(string $name): bool
```
Check if a block exists
#### Parameters
`string` $name Name of the block
#### Returns
`bool`
### extend() public
```
extend(string $name): $this
```
Provides template or element extension/inheritance. Templates can extends a parent template and populate blocks in the parent template.
#### Parameters
`string` $name The template or element to 'extend' the current one with.
#### Returns
`$this`
#### Throws
`LogicException`
when you extend a template with itself or make extend loops.
`LogicException`
when you extend an element which doesn't exist ### fetch() public
```
fetch(string $name, string $default = ''): string
```
Fetch the content for a block. If a block is empty or undefined '' will be returned.
#### Parameters
`string` $name Name of the block
`string` $default optional Default text
#### Returns
`string`
#### See Also
\Cake\View\ViewBlock::get() ### get() public
```
get(string $var, mixed $default = null): mixed
```
Returns the contents of the given View variable.
#### Parameters
`string` $var The view var you want the contents of.
`mixed` $default optional The default/fallback content of $var.
#### Returns
`mixed`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Get config value.
Currently if config is not set it fallbacks to checking corresponding view var with underscore prefix. Using underscore prefixed special view vars is deprecated and this fallback will be removed in CakePHP 4.1.0.
#### Parameters
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getCurrentType() public
```
getCurrentType(): string
```
Retrieve the current template type
#### Returns
`string`
### getElementPaths() protected
```
getElementPaths(string|null $plugin): Generator
```
Get an iterator for element paths.
#### Parameters
`string|null` $plugin The plugin to fetch paths for.
#### Returns
`Generator`
### getEventManager() public
```
getEventManager(): Cake\Event\EventManagerInterface
```
Returns the Cake\Event\EventManager manager 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.
#### Returns
`Cake\Event\EventManagerInterface`
### getLayout() public
```
getLayout(): string
```
Get the name of the layout file to render the template inside of. The name specified is the filename of the layout in `templates/layout/` without the .php extension.
#### Returns
`string`
### getLayoutPath() public
```
getLayoutPath(): string
```
Get path for layout files.
#### Returns
`string`
### getLayoutPaths() protected
```
getLayoutPaths(string|null $plugin): Generator
```
Get an iterator for layout paths.
#### Parameters
`string|null` $plugin The plugin to fetch paths for.
#### Returns
`Generator`
### getName() public
```
getName(): string
```
Returns the View's controller name.
#### Returns
`string`
### getPlugin() public
```
getPlugin(): string|null
```
Returns the plugin name.
#### Returns
`string|null`
### getRequest() public
```
getRequest(): Cake\Http\ServerRequest
```
Gets the request instance.
#### Returns
`Cake\Http\ServerRequest`
### getResponse() public
```
getResponse(): Cake\Http\Response
```
Gets the response instance.
#### Returns
`Cake\Http\Response`
### getSubDir() public
```
getSubDir(): string
```
Get sub-directory for this template files.
#### Returns
`string`
#### See Also
\Cake\View\View::$subDir ### getTemplate() public
```
getTemplate(): string
```
Get the name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
#### Returns
`string`
### getTemplatePath() public
```
getTemplatePath(): string
```
Get path for templates files.
#### Returns
`string`
### getTheme() public
```
getTheme(): string|null
```
Get the current view theme.
#### Returns
`string|null`
### getVars() public
```
getVars(): array<string>
```
Returns a list of variables available in the current View context
#### Returns
`array<string>`
### helpers() public
```
helpers(): Cake\View\HelperRegistry
```
Get the helper registry in use by this View class.
#### Returns
`Cake\View\HelperRegistry`
### initialize() public
```
initialize(): void
```
Initialization hook method.
Properties like $helpers etc. cannot be initialized statically in your custom view class as they are overwritten by values from controller in constructor. So this method allows you to manipulate them as required after view instance is constructed.
#### Returns
`void`
### isAutoLayoutEnabled() public
```
isAutoLayoutEnabled(): bool
```
Returns if CakePHP's conventional mode of applying layout files is enabled. Disabled means that layouts will not be automatically applied to rendered views.
#### Returns
`bool`
### loadHelper() public
```
loadHelper(string $name, array<string, mixed> $config = []): Cake\View\Helper
```
Loads a helper. Delegates to the `HelperRegistry::load()` to load the helper
#### Parameters
`string` $name Name of the helper to load.
`array<string, mixed>` $config optional Settings for the helper
#### Returns
`Cake\View\Helper`
#### See Also
\Cake\View\HelperRegistry::load() ### loadHelpers() public
```
loadHelpers(): $this
```
Load helpers only if serialization is disabled.
#### Returns
`$this`
### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### pluginSplit() public
```
pluginSplit(string $name, bool $fallback = true): array
```
Splits a dot syntax plugin name into its plugin and filename. If $name does not have a dot, then index 0 will be null. It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
#### Parameters
`string` $name The name you want to plugin split.
`bool` $fallback optional If true uses the plugin set in the current Request when parsed plugin is not loaded
#### Returns
`array`
### prepend() public
```
prepend(string $name, mixed $value): $this
```
Prepend to an existing or new block.
Prepending to a new block will create the block.
#### Parameters
`string` $name Name of the block
`mixed` $value The content for the block. Value will be type cast to string.
#### Returns
`$this`
#### See Also
\Cake\View\ViewBlock::concat() ### render() public
```
render(string|null $template = null, string|false|null $layout = null): string
```
Render a JSON view.
Render triggers helper callbacks, which are fired before and after the template are rendered, as well as before and after the layout. The helper callbacks are called:
* `beforeRender`
* `afterRender`
* `beforeLayout`
* `afterLayout`
If View::$autoLayout is set to `false`, the template will be returned bare.
Template and layout names can point to plugin templates or layouts. Using the `Plugin.template` syntax a plugin template/layout/ can be used instead of the app ones. If the chosen plugin is not found the template will be located along the regular view path cascade.
#### Parameters
`string|null` $template optional The template being rendered.
`string|false|null` $layout optional The layout being rendered.
#### Returns
`string`
### renderLayout() public
```
renderLayout(string $content, string|null $layout = null): string
```
Renders a layout. Returns output from \_render().
Several variables are created for use in layout.
#### Parameters
`string` $content Content to render in a template, wrapped by the surrounding layout.
`string|null` $layout optional Layout name
#### Returns
`string`
#### Throws
`Cake\Core\Exception\CakeException`
if there is an error in the view. ### reset() public
```
reset(string $name): $this
```
Reset the content for a block. This will overwrite any existing content.
#### Parameters
`string` $name Name of the block
#### Returns
`$this`
#### See Also
\Cake\View\ViewBlock::set() ### set() public
```
set(array|string $name, mixed $value = null): $this
```
Saves a variable or an associative array of variables for use inside a template.
#### Parameters
`array|string` $name A string or an array of data.
`mixed` $value optional Value in case $name is a string (which then works as the key). Unused if $name is an associative array, otherwise serves as the values to $name's keys.
#### Returns
`$this`
#### Throws
`RuntimeException`
If the array combine operation failed. ### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setContentType() protected
```
setContentType(): void
```
Set the response content-type based on the view's contentType()
#### Returns
`void`
### setElementCache() public
```
setElementCache(string $elementCache): $this
```
Set The cache configuration View will use to store cached elements
#### Parameters
`string` $elementCache Cache config name.
#### Returns
`$this`
#### See Also
\Cake\View\View::$elementCache ### setEventManager() public
```
setEventManager(Cake\Event\EventManagerInterface $eventManager): $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.
#### Parameters
`Cake\Event\EventManagerInterface` $eventManager the eventManager to set
#### Returns
`$this`
### setLayout() public
```
setLayout(string $name): $this
```
Set the name of the layout file to render the template inside of. The name specified is the filename of the layout in `templates/layout/` without the .php extension.
#### Parameters
`string` $name Layout file name to set.
#### Returns
`$this`
### setLayoutPath() public
```
setLayoutPath(string $path): $this
```
Set path for layout files.
#### Parameters
`string` $path Path for layout files.
#### Returns
`$this`
### setPlugin() public
```
setPlugin(string|null $name): $this
```
Sets the plugin name.
#### Parameters
`string|null` $name Plugin name.
#### Returns
`$this`
### setRequest() public
```
setRequest(Cake\Http\ServerRequest $request): $this
```
Sets the request objects and configures a number of controller properties based on the contents of the request. The properties that get set are:
* $this->request - To the $request parameter
* $this->plugin - To the value returned by $request->getParam('plugin')
#### Parameters
`Cake\Http\ServerRequest` $request Request instance.
#### Returns
`$this`
### setResponse() public
```
setResponse(Cake\Http\Response $response): $this
```
Sets the response instance.
#### Parameters
`Cake\Http\Response` $response Response instance.
#### Returns
`$this`
### setSubDir() public
```
setSubDir(string $subDir): $this
```
Set sub-directory for this template files.
#### Parameters
`string` $subDir Sub-directory name.
#### Returns
`$this`
#### See Also
\Cake\View\View::$subDir ### setTemplate() public
```
setTemplate(string $name): $this
```
Set the name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
#### Parameters
`string` $name Template file name to set.
#### Returns
`$this`
### setTemplatePath() public
```
setTemplatePath(string $path): $this
```
Set path for templates files.
#### Parameters
`string` $path Path for template files.
#### Returns
`$this`
### setTheme() public
```
setTheme(string|null $theme): $this
```
Set the view theme to use.
#### Parameters
`string|null` $theme Theme name.
#### Returns
`$this`
### start() public
```
start(string $name): $this
```
Start capturing output for a 'block'
You can use start on a block multiple times to append or prepend content in a capture mode.
```
// Append content to an existing block.
$this->start('content');
echo $this->fetch('content');
echo 'Some new content';
$this->end();
// Prepend content to an existing block
$this->start('content');
echo 'Some new content';
echo $this->fetch('content');
$this->end();
```
#### Parameters
`string` $name The name of the block to capture for.
#### Returns
`$this`
#### See Also
\Cake\View\ViewBlock::start() Property Detail
---------------
### $Blocks public @property
#### Type
`Cake\View\ViewBlock`
### $Breadcrumbs public @property
#### Type
`Cake\View\Helper\BreadcrumbsHelper`
### $Flash public @property
#### Type
`Cake\View\Helper\FlashHelper`
### $Form public @property
#### Type
`Cake\View\Helper\FormHelper`
### $Html public @property
#### Type
`Cake\View\Helper\HtmlHelper`
### $Number public @property
#### Type
`Cake\View\Helper\NumberHelper`
### $Paginator public @property
#### Type
`Cake\View\Helper\PaginatorHelper`
### $Text public @property
#### Type
`Cake\View\Helper\TextHelper`
### $Time public @property
#### Type
`Cake\View\Helper\TimeHelper`
### $Url public @property
#### Type
`Cake\View\Helper\UrlHelper`
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_current protected
The currently rendering view file. Used for resolving parent files.
#### Type
`string`
### $\_currentType protected
Currently rendering an element. Used for finding parent fragments for elements.
#### Type
`string`
### $\_defaultConfig protected
Default config options.
Use ViewBuilder::setOption()/setOptions() in your controller to set these options.
* `serialize`: Option to convert a set of view variables into a serialized response. Its value can be a string for single variable name or array for multiple names. If true all view variables will be serialized. If null or false normal view template will be rendered.
* `jsonOptions`: Options for json\_encode(). For e.g. `JSON_HEX_TAG | JSON_HEX_APOS`.
* `jsonp`: Enables JSONP support and wraps response in callback function provided in query string.
+ Setting it to true enables the default query string parameter "callback".
+ Setting it to a string value, uses the provided query string parameter for finding the JSONP callback name.
#### Type
`array<string, mixed>`
### $\_eventClass protected
Default class name for new event objects.
#### Type
`string`
### $\_eventManager protected
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
#### Type
`Cake\Event\EventManagerInterface|null`
### $\_ext protected
File extension. Defaults to ".php".
#### Type
`string`
### $\_helpers protected
Helpers collection
#### Type
`Cake\View\HelperRegistry`
### $\_parents protected
The names of views and their parents used with View::extend();
#### Type
`array<string>`
### $\_passedVars protected
List of variables to collect from the associated controller.
#### Type
`array<string>`
### $\_paths protected
Holds an array of paths.
#### Type
`array<string>`
### $\_pathsForPlugin protected
Holds an array of plugin paths.
#### Type
`array<string[]>`
### $\_responseType protected deprecated
Response type.
#### Type
`string`
### $\_stack protected
Content stack, used for nested templates that all use View::extend();
#### Type
`array<string>`
### $\_viewBlockClass protected
ViewBlock class.
#### Type
`string`
### $autoLayout protected
Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered templates.
#### Type
`bool`
### $elementCache protected
The Cache configuration View will use to store cached elements. Changing this will change the default configuration elements are stored under. You can also choose a cache config per element.
#### Type
`string`
### $helpers protected
An array of names of built-in helpers to include.
#### Type
`array`
### $layout protected
The name of the layout file to render the template inside of. The name specified is the filename of the layout in `templates/layout/` without the .php extension.
#### Type
`string`
### $layoutPath protected
JSON layouts are located in the JSON subdirectory of `Layouts/`
#### Type
`string`
### $name protected
Name of the controller that created the View if any.
#### Type
`string`
### $plugin protected
The name of the plugin.
#### Type
`string|null`
### $request protected
An instance of a \Cake\Http\ServerRequest object that contains information about the current request. This object contains all the information about a request and several methods for reading additional information about the request.
#### Type
`Cake\Http\ServerRequest`
### $response protected
Reference to the Response object
#### Type
`Cake\Http\Response`
### $subDir protected
JSON views are located in the 'json' subdirectory for controllers' views.
#### Type
`string`
### $template protected
The name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
#### Type
`string`
### $templatePath protected
The name of the subfolder containing templates for this View.
#### Type
`string`
### $theme protected
The view theme to use.
#### Type
`string|null`
### $viewVars protected
An array of variables
#### Type
`array<string, mixed>`
| programming_docs |
cakephp Class FormProtector Class FormProtector
====================
Protects against form tampering. It ensures that:
* Form's action (URL) is not modified.
* Unknown / extra fields are not added to the form.
* Existing fields have not been removed from the form.
* Values of hidden inputs have not been changed.
**Namespace:** [Cake\Form](namespace-cake.form)
Property Summary
----------------
* [$debugMessage](#%24debugMessage) protected `string|null` Error message providing detail for failed validation.
* [$fields](#%24fields) protected `array` Fields list.
* [$unlockedFields](#%24unlockedFields) protected `array<string>` Unlocked fields.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Construct.
* ##### [\_\_debugInfo()](#__debugInfo()) public
Return debug info
* ##### [addField()](#addField()) public
Determine which fields of a form should be used for hash.
* ##### [buildTokenData()](#buildTokenData()) public
Generate the token data.
* ##### [debugCheckFields()](#debugCheckFields()) protected
Iterates data array to check against expected
* ##### [debugExpectedFields()](#debugExpectedFields()) protected
Generate debug message for the expected fields
* ##### [debugTokenNotMatching()](#debugTokenNotMatching()) protected
Create a message for humans to understand why Security token is not matching
* ##### [extractFields()](#extractFields()) protected
Return the fields list for the hash calculation
* ##### [extractHashParts()](#extractHashParts()) protected
Return hash parts for the token generation
* ##### [extractToken()](#extractToken()) protected
Extract token from data.
* ##### [generateHash()](#generateHash()) protected
Generate validation hash.
* ##### [getError()](#getError()) public
Get validation error message.
* ##### [getFieldNameArray()](#getFieldNameArray()) protected
Parses the field name to create a dot separated name value for use in field hash. If fieldname is of form Model[field] or Model.field an array of fieldname parts like ['Model', 'field'] is returned.
* ##### [matchExistingFields()](#matchExistingFields()) protected
Generate array of messages for the existing fields in POST data, matching dataFields in $expectedFields will be unset
* ##### [sortedUnlockedFields()](#sortedUnlockedFields()) protected
Get the sorted unlocked string
* ##### [unlockField()](#unlockField()) public
Add to the list of fields that are currently unlocked.
* ##### [validate()](#validate()) public
Validate submitted form data.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $data = [])
```
Construct.
#### Parameters
`array<string, mixed>` $data optional Data array, can contain key `unlockedFields` with list of unlocked fields.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Return debug info
#### Returns
`array<string, mixed>`
### addField() public
```
addField(array<string>|string $field, bool $lock = true, mixed $value = null): $this
```
Determine which fields of a form should be used for hash.
#### Parameters
`array<string>|string` $field Reference to field to be secured. Can be dot separated string to indicate nesting or array of fieldname parts.
`bool` $lock optional Whether this field should be part of the validation or excluded as part of the unlockedFields. Default `true`.
`mixed` $value optional Field value, if value should not be tampered with.
#### Returns
`$this`
### buildTokenData() public
```
buildTokenData(string $url = '', string $sessionId = ''): array<string, string>
```
Generate the token data.
#### Parameters
`string` $url optional Form URL.
`string` $sessionId optional Session Id.
#### Returns
`array<string, string>`
### debugCheckFields() protected
```
debugCheckFields(array $dataFields, array $expectedFields = [], string $intKeyMessage = '', string $stringKeyMessage = '', string $missingMessage = ''): array<string>
```
Iterates data array to check against expected
#### Parameters
`array` $dataFields Fields array, containing the POST data fields
`array` $expectedFields optional Fields array, containing the expected fields we should have in POST
`string` $intKeyMessage optional Message string if unexpected found in data fields indexed by int (not protected)
`string` $stringKeyMessage optional Message string if tampered found in data fields indexed by string (protected).
`string` $missingMessage optional Message string if missing field
#### Returns
`array<string>`
### debugExpectedFields() protected
```
debugExpectedFields(array $expectedFields = [], string $missingMessage = ''): string|null
```
Generate debug message for the expected fields
#### Parameters
`array` $expectedFields optional Expected fields
`string` $missingMessage optional Message template
#### Returns
`string|null`
### debugTokenNotMatching() protected
```
debugTokenNotMatching(array $formData, array $hashParts): string
```
Create a message for humans to understand why Security token is not matching
#### Parameters
`array` $formData Data.
`array` $hashParts Elements used to generate the Token hash
#### Returns
`string`
### extractFields() protected
```
extractFields(array $formData): array
```
Return the fields list for the hash calculation
#### Parameters
`array` $formData Data array
#### Returns
`array`
### extractHashParts() protected
```
extractHashParts(array<string, array> $formData): array<string, array>
```
Return hash parts for the token generation
#### Parameters
`array<string, array>` $formData Form data.
#### Returns
`array<string, array>`
### extractToken() protected
```
extractToken(mixed $formData): string|null
```
Extract token from data.
#### Parameters
`mixed` $formData Data to validate.
#### Returns
`string|null`
### generateHash() protected
```
generateHash(array $fields, array<string> $unlockedFields, string $url, string $sessionId): string
```
Generate validation hash.
#### Parameters
`array` $fields Fields list.
`array<string>` $unlockedFields Unlocked fields.
`string` $url Form URL.
`string` $sessionId Session Id.
#### Returns
`string`
### getError() public
```
getError(): string|null
```
Get validation error message.
#### Returns
`string|null`
### getFieldNameArray() protected
```
getFieldNameArray(string $name): array<string>
```
Parses the field name to create a dot separated name value for use in field hash. If fieldname is of form Model[field] or Model.field an array of fieldname parts like ['Model', 'field'] is returned.
#### Parameters
`string` $name The form inputs name attribute.
#### Returns
`array<string>`
### matchExistingFields() protected
```
matchExistingFields(array $dataFields, array $expectedFields, string $intKeyMessage, string $stringKeyMessage): array<string>
```
Generate array of messages for the existing fields in POST data, matching dataFields in $expectedFields will be unset
#### Parameters
`array` $dataFields Fields array, containing the POST data fields
`array` $expectedFields Fields array, containing the expected fields we should have in POST
`string` $intKeyMessage Message string if unexpected found in data fields indexed by int (not protected)
`string` $stringKeyMessage Message string if tampered found in data fields indexed by string (protected)
#### Returns
`array<string>`
### sortedUnlockedFields() protected
```
sortedUnlockedFields(array $formData): array<string>
```
Get the sorted unlocked string
#### Parameters
`array` $formData Data array
#### Returns
`array<string>`
### unlockField() public
```
unlockField(string $name): $this
```
Add to the list of fields that are currently unlocked.
Unlocked fields are not included in the field hash.
#### Parameters
`string` $name The dot separated name for the field.
#### Returns
`$this`
### validate() public
```
validate(mixed $formData, string $url, string $sessionId): bool
```
Validate submitted form data.
#### Parameters
`mixed` $formData Form data.
`string` $url URL form was POSTed to.
`string` $sessionId Session id for hash generation.
#### Returns
`bool`
Property Detail
---------------
### $debugMessage protected
Error message providing detail for failed validation.
#### Type
`string|null`
### $fields protected
Fields list.
#### Type
`array`
### $unlockedFields protected
Unlocked fields.
#### Type
`array<string>`
cakephp Namespace Event Namespace Event
===============
### Namespaces
* [Cake\Event\Decorator](namespace-cake.event.decorator)
### Interfaces
* ##### [EventDispatcherInterface](interface-cake.event.eventdispatcherinterface)
Objects implementing this interface can emit events.
* ##### [EventInterface](interface-cake.event.eventinterface)
Represents the transport class of events across the system. It receives a name, subject and an optional payload. The name can be any string that uniquely identifies the event across the application, while the subject represents the object that the event applies to.
* ##### [EventListenerInterface](interface-cake.event.eventlistenerinterface)
Objects implementing this interface should declare the `implementedEvents()` method to notify the event manager what methods should be called when an event is triggered.
* ##### [EventManagerInterface](interface-cake.event.eventmanagerinterface)
Interface EventManagerInterface
### Classes
* ##### [Event](class-cake.event.event)
Class Event
* ##### [EventList](class-cake.event.eventlist)
The Event List
* ##### [EventManager](class-cake.event.eventmanager)
The event manager is responsible for keeping track of event listeners, passing the correct data to them, and firing them in the correct order, when associated events are triggered. You can create multiple instances of this object to manage local events or keep a single instance and pass it around to manage all events in your app.
### Traits
* ##### [EventDispatcherTrait](trait-cake.event.eventdispatchertrait)
Implements Cake\Event\EventDispatcherInterface.
cakephp Class ButtonWidget Class ButtonWidget
===================
Button input class
This input class can be used to render button elements. If you need to make basic submit inputs with type=submit, use the Basic input widget.
**Namespace:** [Cake\View\Widget](namespace-cake.view.widget)
Property Summary
----------------
* [$\_templates](#%24_templates) protected `Cake\View\StringTemplate` StringTemplate instance.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [render()](#render()) public
Render a button.
* ##### [secureFields()](#secureFields()) public
Returns a list of fields that need to be secured for this widget.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\View\StringTemplate $templates)
```
Constructor.
#### Parameters
`Cake\View\StringTemplate` $templates Templates list.
### render() public
```
render(array<string, mixed> $data, Cake\View\Form\ContextInterface $context): string
```
Render a button.
This method accepts a number of keys:
* `text` The text of the button. Unlike all other form controls, buttons do not escape their contents by default.
* `escapeTitle` Set to false to disable escaping of button text.
* `escape` Set to false to disable escaping of attributes.
* `type` The button type defaults to 'submit'.
Any other keys provided in $data will be converted into HTML attributes.
#### Parameters
`array<string, mixed>` $data The data to build a button with.
`Cake\View\Form\ContextInterface` $context The current form context.
#### Returns
`string`
### secureFields() public
```
secureFields(array<string, mixed> $data): array<string>
```
Returns a list of fields that need to be secured for this widget.
#### Parameters
`array<string, mixed>` $data #### Returns
`array<string>`
Property Detail
---------------
### $\_templates protected
StringTemplate instance.
#### Type
`Cake\View\StringTemplate`
cakephp Interface StorageInterface Interface StorageInterface
===========================
Describes the methods that any class representing an Auth data storage should comply with.
**Namespace:** [Cake\Auth\Storage](namespace-cake.auth.storage)
Method Summary
--------------
* ##### [delete()](#delete()) public
Delete user record.
* ##### [read()](#read()) public
Read user record.
* ##### [redirectUrl()](#redirectUrl()) public
Get/set redirect URL.
* ##### [write()](#write()) public
Write user record.
Method Detail
-------------
### delete() public
```
delete(): void
```
Delete user record.
#### Returns
`void`
### read() public
```
read(): ArrayAccess|array|null
```
Read user record.
#### Returns
`ArrayAccess|array|null`
### redirectUrl() public
```
redirectUrl(mixed $url = null): array|string|null
```
Get/set redirect URL.
#### Parameters
`mixed` $url optional Redirect URL. If `null` returns current URL. If `false` deletes currently set URL.
#### Returns
`array|string|null`
### write() public
```
write(mixed $user): void
```
Write user record.
#### Parameters
`mixed` $user array or \ArrayAccess User record.
#### Returns
`void`
cakephp Class ClosureDecoratorMiddleware Class ClosureDecoratorMiddleware
=================================
Decorate closures as PSR-15 middleware.
Decorates closures with the following signature:
```
function (
ServerRequestInterface $request,
RequestHandlerInterface $handler
): ResponseInterface
```
such that it will operate as PSR-15 middleware.
**Namespace:** [Cake\Http\Middleware](namespace-cake.http.middleware)
Property Summary
----------------
* [$callable](#%24callable) protected `Closure` A Closure.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getCallable()](#getCallable()) public
* ##### [process()](#process()) public
Run the callable to process an incoming server request.
Method Detail
-------------
### \_\_construct() public
```
__construct(Closure $callable)
```
Constructor
#### Parameters
`Closure` $callable A closure.
### getCallable() public
```
getCallable(): callable
```
#### Returns
`callable`
### process() public
```
process(ServerRequestInterface $request, RequestHandlerInterface $handler): Psr\Http\Message\ResponseInterface
```
Run the callable to process an incoming server request.
Processes an incoming server request in order to produce a response. If unable to produce the response itself, it may delegate to the provided request handler to do so.
#### Parameters
`ServerRequestInterface` $request Request instance.
`RequestHandlerInterface` $handler Request handler instance.
#### Returns
`Psr\Http\Message\ResponseInterface`
Property Detail
---------------
### $callable protected
A Closure.
#### Type
`Closure`
cakephp Class ContentsContainRow Class ContentsContainRow
=========================
ContentsContainRow
**Namespace:** [Cake\Console\TestSuite\Constraint](namespace-cake.console.testsuite.constraint)
Property Summary
----------------
* [$contents](#%24contents) protected `string`
* [$output](#%24output) protected `string`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) public
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Checks if contents contain expected
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string> $contents, string $output)
```
Constructor
#### Parameters
`array<string>` $contents Contents
`string` $output Output type
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() public
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other Expected content
#### Returns
`string`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks if contents contain expected
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Row
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $contents protected
#### Type
`string`
### $output protected
#### Type
`string`
| programming_docs |
cakephp Interface ConsoleApplicationInterface Interface ConsoleApplicationInterface
======================================
An interface defining the methods that the console runner depend on.
**Namespace:** [Cake\Core](namespace-cake.core)
Method Summary
--------------
* ##### [bootstrap()](#bootstrap()) public
Load all the application configuration and bootstrap logic.
* ##### [console()](#console()) public
Define the console commands for an application.
Method Detail
-------------
### bootstrap() public
```
bootstrap(): void
```
Load all the application configuration and bootstrap logic.
Override this method to add additional bootstrap logic for your application.
#### Returns
`void`
### console() public
```
console(Cake\Console\CommandCollection $commands): Cake\Console\CommandCollection
```
Define the console commands for an application.
#### Parameters
`Cake\Console\CommandCollection` $commands The CommandCollection to add commands into.
#### Returns
`Cake\Console\CommandCollection`
cakephp Class ContentsNotContain Class ContentsNotContain
=========================
ContentsNotContain
**Namespace:** [Cake\Console\TestSuite\Constraint](namespace-cake.console.testsuite.constraint)
Property Summary
----------------
* [$contents](#%24contents) protected `string`
* [$output](#%24output) protected `string`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Checks if contents contain expected
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string> $contents, string $output)
```
Constructor
#### Parameters
`array<string>` $contents Contents
`string` $output Output type
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks if contents contain expected
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Expected
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $contents protected
#### Type
`string`
### $output protected
#### Type
`string`
cakephp Class ConflictException Class ConflictException
========================
Represents an HTTP 409 error.
**Namespace:** [Cake\Http\Exception](namespace-cake.http.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
* [$headers](#%24headers) protected `array<string, mixed>`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [getHeaders()](#getHeaders()) public
Returns array of response headers.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
* ##### [setHeader()](#setHeader()) public
Set a single HTTP response header.
* ##### [setHeaders()](#setHeaders()) public
Sets HTTP response headers.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $message = null, int|null $code = null, Throwable|null $previous = null)
```
Constructor
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`string|null` $message optional If no message is given 'Conflict' will be the message
`int|null` $code optional Status code, defaults to 409
`Throwable|null` $previous optional The previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### getHeaders() public
```
getHeaders(): array<string, mixed>
```
Returns array of response headers.
#### Returns
`array<string, mixed>`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
### setHeader() public
```
setHeader(string $header, array<string>|string|null $value = null): void
```
Set a single HTTP response header.
#### Parameters
`string` $header Header name
`array<string>|string|null` $value optional Header value
#### Returns
`void`
### setHeaders() public
```
setHeaders(array<string, mixed> $headers): void
```
Sets HTTP response headers.
#### Parameters
`array<string, mixed>` $headers Array of header name and value pairs.
#### Returns
`void`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
### $headers protected
#### Type
`array<string, mixed>`
cakephp Class ScalarNode Class ScalarNode
=================
Dump node for scalar values.
**Namespace:** [Cake\Error\Debug](namespace-cake.error.debug)
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getChildren()](#getChildren()) public
Get the child nodes of this node.
* ##### [getType()](#getType()) public
Get the type of value
* ##### [getValue()](#getValue()) public
Get the value
Method Detail
-------------
### \_\_construct() public
```
__construct(string $type, string|float|int|bool|null $value)
```
Constructor
#### Parameters
`string` $type The type of scalar value.
`string|float|int|bool|null` $value The wrapped value.
### getChildren() public
```
getChildren(): arrayCake\Error\Debug\NodeInterface>
```
Get the child nodes of this node.
#### Returns
`arrayCake\Error\Debug\NodeInterface>`
### getType() public
```
getType(): string
```
Get the type of value
#### Returns
`string`
### getValue() public
```
getValue(): string|float|int|bool|null
```
Get the value
#### Returns
`string|float|int|bool|null`
cakephp Interface FieldInterface Interface FieldInterface
=========================
Describes a getter and a setter for the a field property. Useful for expressions that contain an identifier to compare against.
**Namespace:** [Cake\Database\Expression](namespace-cake.database.expression)
Method Summary
--------------
* ##### [getField()](#getField()) public
Returns the field name
* ##### [setField()](#setField()) public
Sets the field name
Method Detail
-------------
### getField() public
```
getField(): Cake\Database\ExpressionInterface|array|string
```
Returns the field name
#### Returns
`Cake\Database\ExpressionInterface|array|string`
### setField() public
```
setField(Cake\Database\ExpressionInterface|array|string $field): void
```
Sets the field name
#### Parameters
`Cake\Database\ExpressionInterface|array|string` $field The field to compare with.
#### Returns
`void`
cakephp Class HeaderContains Class HeaderContains
=====================
HeaderContains
**Namespace:** [Cake\TestSuite\Constraint\Response](namespace-cake.testsuite.constraint.response)
Property Summary
----------------
* [$headerName](#%24headerName) protected `string`
* [$response](#%24response) protected `Psr\Http\Message\ResponseInterface`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_getBodyAsString()](#_getBodyAsString()) protected
Get the response body as string
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Checks assertion
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(Psr\Http\Message\ResponseInterface $response, string $headerName)
```
Constructor.
#### Parameters
`Psr\Http\Message\ResponseInterface` $response A response instance.
`string` $headerName Header name
### \_getBodyAsString() protected
```
_getBodyAsString(): string
```
Get the response body as string
#### Returns
`string`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks assertion
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Expected content
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $headerName protected
#### Type
`string`
### $response protected
#### Type
`Psr\Http\Message\ResponseInterface`
| programming_docs |
cakephp Class LayoutFileEquals Class LayoutFileEquals
=======================
LayoutFileEquals
**Namespace:** [Cake\TestSuite\Constraint\View](namespace-cake.testsuite.constraint.view)
Property Summary
----------------
* [$filename](#%24filename) protected `string`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Checks assertion
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(string $filename)
```
Constructor
#### Parameters
`string` $filename Template file name
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks assertion
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Expected filename
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $filename protected
#### Type
`string`
cakephp Interface TypedResultInterface Interface TypedResultInterface
===============================
Represents an expression that is known to return a specific type
**Namespace:** [Cake\Database](namespace-cake.database)
Method Summary
--------------
* ##### [getReturnType()](#getReturnType()) public
Return the abstract type this expression will return
* ##### [setReturnType()](#setReturnType()) public
Set the return type of the expression
Method Detail
-------------
### getReturnType() public
```
getReturnType(): string
```
Return the abstract type this expression will return
#### Returns
`string`
### setReturnType() public
```
setReturnType(string $type): $this
```
Set the return type of the expression
#### Parameters
`string` $type The type name to use.
#### Returns
`$this`
cakephp Class HtmlErrorRenderer Class HtmlErrorRenderer
========================
Interactive HTML error rendering with a stack trace.
Default output renderer for non CLI SAPI.
**Namespace:** [Cake\Error\Renderer](namespace-cake.error.renderer)
Method Summary
--------------
* ##### [render()](#render()) public
Render output for the provided error.
* ##### [write()](#write()) public
Write output to the renderer's output stream
Method Detail
-------------
### render() public
```
render(Cake\Error\PhpError $error, bool $debug): string
```
Render output for the provided error.
#### Parameters
`Cake\Error\PhpError` $error `bool` $debug #### Returns
`string`
### write() public
```
write(string $out): void
```
Write output to the renderer's output stream
#### Parameters
`string` $out #### Returns
`void`
cakephp Trait BufferResultsTrait Trait BufferResultsTrait
=========================
Contains a setter for marking a Statement as buffered
**Namespace:** [Cake\Database\Statement](namespace-cake.database.statement)
Property Summary
----------------
* [$\_bufferResults](#%24_bufferResults) protected `bool` Whether to buffer results in php
Method Summary
--------------
* ##### [bufferResults()](#bufferResults()) public
Whether to buffer results in php
Method Detail
-------------
### bufferResults() public
```
bufferResults(bool $buffer): $this
```
Whether to buffer results in php
#### Parameters
`bool` $buffer Toggle buffering
#### Returns
`$this`
Property Detail
---------------
### $\_bufferResults protected
Whether to buffer results in php
#### Type
`bool`
cakephp Class NotImplementedException Class NotImplementedException
==============================
Not Implemented Exception - used when an API method is not implemented
**Namespace:** [Cake\Http\Exception](namespace-cake.http.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
* [$headers](#%24headers) protected `array<string, mixed>`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [getHeaders()](#getHeaders()) public
Returns array of response headers.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
* ##### [setHeader()](#setHeader()) public
Set a single HTTP response header.
* ##### [setHeaders()](#setHeaders()) public
Sets HTTP response headers.
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### getHeaders() public
```
getHeaders(): array<string, mixed>
```
Returns array of response headers.
#### Returns
`array<string, mixed>`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
### setHeader() public
```
setHeader(string $header, array<string>|string|null $value = null): void
```
Set a single HTTP response header.
#### Parameters
`string` $header Header name
`array<string>|string|null` $value optional Header value
#### Returns
`void`
### setHeaders() public
```
setHeaders(array<string, mixed> $headers): void
```
Sets HTTP response headers.
#### Parameters
`array<string, mixed>` $headers Array of header name and value pairs.
#### Returns
`void`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
### $headers protected
#### Type
`array<string, mixed>`
cakephp Class TextExceptionRenderer Class TextExceptionRenderer
============================
Plain text exception rendering with a stack trace.
Useful in CI or plain text environments.
**Namespace:** [Cake\Error\Renderer](namespace-cake.error.renderer)
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [render()](#render()) public
Render an exception into a plain text message.
* ##### [write()](#write()) public
Write output to stdout.
Method Detail
-------------
### \_\_construct() public
```
__construct(Throwable $error)
```
Constructor.
#### Parameters
`Throwable` $error The error to render.
### render() public
```
render(): Psr\Http\Message\ResponseInterface|string
```
Render an exception into a plain text message.
#### Returns
`Psr\Http\Message\ResponseInterface|string`
### write() public
```
write(string $output): void
```
Write output to stdout.
#### Parameters
`string` $output The output to print.
#### Returns
`void`
cakephp Class FlashHelper Class FlashHelper
==================
FlashHelper class to render flash messages.
After setting messages in your controllers with FlashComponent, you can use this class to output your flash messages in your views.
**Namespace:** [Cake\View\Helper](namespace-cake.view.helper)
Property Summary
----------------
* [$\_View](#%24_View) protected `Cake\View\View` The View instance this helper is attached to
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this helper.
* [$\_helperMap](#%24_helperMap) protected `array<string, array>` A helper lookup table used to lazy load helper objects.
* [$helpers](#%24helpers) protected `array` List of helpers used by this helper
Method Summary
--------------
* ##### [\_\_call()](#__call()) public
Provide non fatal errors on missing method calls.
* ##### [\_\_construct()](#__construct()) public
Default Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_get()](#__get()) public
Lazy loads helpers.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_confirm()](#_confirm()) protected
Returns a string to be used as onclick handler for confirm dialogs.
* ##### [addClass()](#addClass()) public
Adds the given class to the element options
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getView()](#getView()) public
Get the view instance this helper is bound to.
* ##### [implementedEvents()](#implementedEvents()) public
Event listeners.
* ##### [initialize()](#initialize()) public
Constructor hook method.
* ##### [render()](#render()) public
Used to render the message set in FlashComponent::set()
* ##### [setConfig()](#setConfig()) public
Sets the config.
Method Detail
-------------
### \_\_call() public
```
__call(string $method, array $params): mixed|void
```
Provide non fatal errors on missing method calls.
#### Parameters
`string` $method Method to invoke
`array` $params Array of params for the method.
#### Returns
`mixed|void`
### \_\_construct() public
```
__construct(Cake\View\View $view, array<string, mixed> $config = [])
```
Default Constructor
#### Parameters
`Cake\View\View` $view The View this helper is being attached to.
`array<string, mixed>` $config optional Configuration settings for the helper.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): Cake\View\Helper|null|void
```
Lazy loads helpers.
#### Parameters
`string` $name Name of the property being accessed.
#### Returns
`Cake\View\Helper|null|void`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_confirm() protected
```
_confirm(string $okCode, string $cancelCode): string
```
Returns a string to be used as onclick handler for confirm dialogs.
#### Parameters
`string` $okCode Code to be executed after user chose 'OK'
`string` $cancelCode Code to be executed after user chose 'Cancel'
#### Returns
`string`
### addClass() public
```
addClass(array<string, mixed> $options, string $class, string $key = 'class'): array<string, mixed>
```
Adds the given class to the element options
#### Parameters
`array<string, mixed>` $options Array options/attributes to add a class to
`string` $class The class name being added.
`string` $key optional the key to use for class. Defaults to `'class'`.
#### Returns
`array<string, mixed>`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getView() public
```
getView(): Cake\View\View
```
Get the view instance this helper is bound to.
#### Returns
`Cake\View\View`
### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Event listeners.
By defining one of the callback methods a helper is assumed to be interested in the related event.
Override this method if you need to add non-conventional event listeners. Or if you want helpers to listen to non-standard events.
#### Returns
`array<string, mixed>`
### initialize() public
```
initialize(array<string, mixed> $config): void
```
Constructor hook method.
Implement this method to avoid having to overwrite the constructor and call parent.
#### Parameters
`array<string, mixed>` $config The configuration settings provided to this helper.
#### Returns
`void`
### render() public
```
render(string $key = 'flash', array<string, mixed> $options = []): string|null
```
Used to render the message set in FlashComponent::set()
In your template file: $this->Flash->render('somekey'); Will default to flash if no param is passed
You can pass additional information into the flash message generation. This allows you to consolidate all the parameters for a given type of flash message into the view.
```
echo $this->Flash->render('flash', ['params' => ['name' => $user['User']['name']]]);
```
This would pass the current user's name into the flash message, so you could create personalized messages without the controller needing access to that data.
Lastly you can choose the element that is used for rendering the flash message. Using custom elements allows you to fully customize how flash messages are generated.
```
echo $this->Flash->render('flash', ['element' => 'my_custom_element']);
```
If you want to use an element from a plugin for rendering your flash message you can use the dot notation for the plugin's element name:
```
echo $this->Flash->render('flash', [
'element' => 'MyPlugin.my_custom_element',
]);
```
If you have several messages stored in the Session, each message will be rendered in its own element.
#### Parameters
`string` $key optional The [Flash.]key you are rendering in the view.
`array<string, mixed>` $options optional Additional options to use for the creation of this flash message. Supports the 'params', and 'element' keys that are used in the helper.
#### Returns
`string|null`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. Property Detail
---------------
### $\_View protected
The View instance this helper is attached to
#### Type
`Cake\View\View`
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this helper.
#### Type
`array<string, mixed>`
### $\_helperMap protected
A helper lookup table used to lazy load helper objects.
#### Type
`array<string, array>`
### $helpers protected
List of helpers used by this helper
#### Type
`array`
| programming_docs |
cakephp Class StatementDecorator Class StatementDecorator
=========================
Represents a database statement. Statements contains queries that can be executed multiple times by binding different values on each call. This class also helps convert values to their valid representation for the corresponding types.
This class is but a decorator of an actual statement implementation, such as PDOStatement.
**Namespace:** [Cake\Database\Statement](namespace-cake.database.statement)
Constants
---------
* `string` **FETCH\_TYPE\_ASSOC**
```
'assoc'
```
Used to designate that an associated array be returned in a result when calling fetch methods
* `string` **FETCH\_TYPE\_NUM**
```
'num'
```
Used to designate that numeric indexes be returned in a result when calling fetch methods
* `string` **FETCH\_TYPE\_OBJ**
```
'obj'
```
Used to designate that a stdClass object be returned in a result when calling fetch methods
Property Summary
----------------
* [$\_driver](#%24_driver) protected `Cake\Database\DriverInterface` Reference to the driver object associated to this statement.
* [$\_hasExecuted](#%24_hasExecuted) protected `bool` Whether this statement has already been executed
* [$\_statement](#%24_statement) protected `Cake\Database\StatementInterface` Statement instance implementation, such as PDOStatement or any other custom implementation.
* [$queryString](#%24queryString) public @property-read `string`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_get()](#__get()) public
Magic getter to return $queryString as read-only.
* ##### [bind()](#bind()) public
Binds a set of values to statement object with corresponding type.
* ##### [bindValue()](#bindValue()) public
Assign a value to a positional or named variable in prepared query. If using positional variables you need to start with index one, if using named params then just use the name in any order.
* ##### [cast()](#cast()) public
Converts a give value to a suitable database value based on type and return relevant internal statement type
* ##### [closeCursor()](#closeCursor()) public
Closes a cursor in the database, freeing up any resources and memory allocated to it. In most cases you don't need to call this method, as it is automatically called after fetching all results from the result set.
* ##### [columnCount()](#columnCount()) public
Returns the number of columns this statement's results will contain.
* ##### [count()](#count()) public
Statements can be passed as argument for count() to return the number for affected rows from last execution.
* ##### [errorCode()](#errorCode()) public
Returns the error code for the last error that occurred when executing this statement.
* ##### [errorInfo()](#errorInfo()) public
Returns the error information for the last error that occurred when executing this statement.
* ##### [execute()](#execute()) public
Executes the statement by sending the SQL query to the database. It can optionally take an array or arguments to be bound to the query variables. Please note that binding parameters from this method will not perform any custom type conversion as it would normally happen when calling `bindValue`.
* ##### [fetch()](#fetch()) public
Returns the next row for the result set after executing this statement. Rows can be fetched to contain columns as names or positions. If no rows are left in result set, this method will return false.
* ##### [fetchAll()](#fetchAll()) public
Returns an array with all rows resulting from executing this statement.
* ##### [fetchAssoc()](#fetchAssoc()) public
Returns the next row in a result set as an associative array. Calling this function is the same as calling $statement->fetch(StatementDecorator::FETCH\_TYPE\_ASSOC). If no results are found an empty array is returned.
* ##### [fetchColumn()](#fetchColumn()) public
Returns the value of the result at position.
* ##### [getInnerStatement()](#getInnerStatement()) public
Returns the statement object that was decorated by this class.
* ##### [getIterator()](#getIterator()) public
Statements are iterable as arrays, this method will return the iterator object for traversing all items in the result.
* ##### [lastInsertId()](#lastInsertId()) public
Returns the latest primary inserted using this statement.
* ##### [matchTypes()](#matchTypes()) public
Matches columns to corresponding types
* ##### [rowCount()](#rowCount()) public
Returns the number of rows affected by this SQL statement.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Database\StatementInterface $statement, Cake\Database\DriverInterface $driver)
```
Constructor
#### Parameters
`Cake\Database\StatementInterface` $statement Statement implementation such as PDOStatement.
`Cake\Database\DriverInterface` $driver Driver instance
### \_\_get() public
```
__get(string $property): string|null
```
Magic getter to return $queryString as read-only.
#### Parameters
`string` $property internal property to get
#### Returns
`string|null`
### bind() public
```
bind(array $params, array $types): void
```
Binds a set of values to statement object with corresponding type.
#### Parameters
`array` $params list of values to be bound
`array` $types list of types to be used, keys should match those in $params
#### Returns
`void`
### bindValue() public
```
bindValue(string|int $column, mixed $value, string|int|null $type = 'string'): void
```
Assign a value to a positional or named variable in prepared query. If using positional variables you need to start with index one, if using named params then just use the name in any order.
It is not allowed to combine positional and named variables in the same statement.
### Examples:
```
$statement->bindValue(1, 'a title');
$statement->bindValue('active', true, 'boolean');
$statement->bindValue(5, new \DateTime(), 'date');
```
#### Parameters
`string|int` $column name or param position to be bound
`mixed` $value The value to bind to variable in query
`string|int|null` $type optional name of configured Type class
#### Returns
`void`
### cast() public
```
cast(mixed $value, Cake\Database\TypeInterface|string|int $type = 'string'): array
```
Converts a give value to a suitable database value based on type and return relevant internal statement type
#### Parameters
`mixed` $value The value to cast
`Cake\Database\TypeInterface|string|int` $type optional The type name or type instance to use.
#### Returns
`array`
### closeCursor() public
```
closeCursor(): void
```
Closes a cursor in the database, freeing up any resources and memory allocated to it. In most cases you don't need to call this method, as it is automatically called after fetching all results from the result set.
#### Returns
`void`
### columnCount() public
```
columnCount(): int
```
Returns the number of columns this statement's results will contain.
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
echo $statement->columnCount(); // outputs 2
```
#### Returns
`int`
### count() public
```
count(): int
```
Statements can be passed as argument for count() to return the number for affected rows from last execution.
#### Returns
`int`
### errorCode() public
```
errorCode(): string|int
```
Returns the error code for the last error that occurred when executing this statement.
#### Returns
`string|int`
### errorInfo() public
```
errorInfo(): array
```
Returns the error information for the last error that occurred when executing this statement.
#### Returns
`array`
### execute() public
```
execute(array|null $params = null): bool
```
Executes the statement by sending the SQL query to the database. It can optionally take an array or arguments to be bound to the query variables. Please note that binding parameters from this method will not perform any custom type conversion as it would normally happen when calling `bindValue`.
#### Parameters
`array|null` $params optional list of values to be bound to query
#### Returns
`bool`
### fetch() public
```
fetch(string|int $type = self::FETCH_TYPE_NUM): mixed
```
Returns the next row for the result set after executing this statement. Rows can be fetched to contain columns as names or positions. If no rows are left in result set, this method will return false.
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
print_r($statement->fetch('assoc')); // will show ['id' => 1, 'title' => 'a title']
```
#### Parameters
`string|int` $type optional 'num' for positional columns, assoc for named columns
#### Returns
`mixed`
### fetchAll() public
```
fetchAll(string|int $type = self::FETCH_TYPE_NUM): array|false
```
Returns an array with all rows resulting from executing this statement.
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
print_r($statement->fetchAll('assoc')); // will show [0 => ['id' => 1, 'title' => 'a title']]
```
#### Parameters
`string|int` $type optional num for fetching columns as positional keys or assoc for column names as keys
#### Returns
`array|false`
### fetchAssoc() public
```
fetchAssoc(): array
```
Returns the next row in a result set as an associative array. Calling this function is the same as calling $statement->fetch(StatementDecorator::FETCH\_TYPE\_ASSOC). If no results are found an empty array is returned.
#### Returns
`array`
### fetchColumn() public
```
fetchColumn(int $position): mixed
```
Returns the value of the result at position.
#### Parameters
`int` $position The numeric position of the column to retrieve in the result
#### Returns
`mixed`
### getInnerStatement() public
```
getInnerStatement(): Cake\Database\StatementInterface
```
Returns the statement object that was decorated by this class.
#### Returns
`Cake\Database\StatementInterface`
### getIterator() public
```
getIterator(): Cake\Database\StatementInterface
```
Statements are iterable as arrays, this method will return the iterator object for traversing all items in the result.
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
foreach ($statement as $row) {
//do stuff
}
```
#### Returns
`Cake\Database\StatementInterface`
### lastInsertId() public
```
lastInsertId(string|null $table = null, string|null $column = null): string|int
```
Returns the latest primary inserted using this statement.
#### Parameters
`string|null` $table optional table name or sequence to get last insert value from
`string|null` $column optional the name of the column representing the primary key
#### Returns
`string|int`
### matchTypes() public
```
matchTypes(array $columns, array $types): array
```
Matches columns to corresponding types
Both $columns and $types should either be numeric based or string key based at the same time.
#### Parameters
`array` $columns list or associative array of columns and parameters to be bound with types
`array` $types list or associative array of types
#### Returns
`array`
### rowCount() public
```
rowCount(): int
```
Returns the number of rows affected by this SQL statement.
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
print_r($statement->rowCount()); // will show 1
```
#### Returns
`int`
Property Detail
---------------
### $\_driver protected
Reference to the driver object associated to this statement.
#### Type
`Cake\Database\DriverInterface`
### $\_hasExecuted protected
Whether this statement has already been executed
#### Type
`bool`
### $\_statement protected
Statement instance implementation, such as PDOStatement or any other custom implementation.
#### Type
`Cake\Database\StatementInterface`
### $queryString public @property-read
#### Type
`string`
cakephp Trait MergeVariablesTrait Trait MergeVariablesTrait
==========================
Provides features for merging object properties recursively with parent classes.
**Namespace:** [Cake\Utility](namespace-cake.utility)
Method Summary
--------------
* ##### [\_mergeProperty()](#_mergeProperty()) protected
Merge a single property with the values declared in all parent classes.
* ##### [\_mergePropertyData()](#_mergePropertyData()) protected
Merge each of the keys in a property together.
* ##### [\_mergeVars()](#_mergeVars()) protected
Merge the list of $properties with all parent classes of the current class.
Method Detail
-------------
### \_mergeProperty() protected
```
_mergeProperty(string $property, array<string> $parentClasses, array<string, mixed> $options): void
```
Merge a single property with the values declared in all parent classes.
#### Parameters
`string` $property The name of the property being merged.
`array<string>` $parentClasses An array of classes you want to merge with.
`array<string, mixed>` $options Options for merging the property, see \_mergeVars()
#### Returns
`void`
### \_mergePropertyData() protected
```
_mergePropertyData(array $current, array $parent, bool $isAssoc): array
```
Merge each of the keys in a property together.
#### Parameters
`array` $current The current merged value.
`array` $parent The parent class' value.
`bool` $isAssoc Whether the merging should be done in associative mode.
#### Returns
`array`
### \_mergeVars() protected
```
_mergeVars(array<string> $properties, array<string, mixed> $options = []): void
```
Merge the list of $properties with all parent classes of the current class.
### Options:
* `associative` - A list of properties that should be treated as associative arrays. Properties in this list will be passed through Hash::normalize() before merging.
#### Parameters
`array<string>` $properties An array of properties and the merge strategy for them.
`array<string, mixed>` $options optional The options to use when merging properties.
#### Returns
`void`
cakephp Class IniConfig Class IniConfig
================
Ini file configuration engine.
Since IniConfig uses parse\_ini\_file underneath, you should be aware that this class shares the same behavior, especially with regards to boolean and null values.
In addition to the native `parse_ini_file` features, IniConfig also allows you to create nested array structures through usage of `.` delimited names. This allows you to create nested arrays structures in an ini config file. For example:
`db.password = secret` would turn into `['db' => ['password' => 'secret']]`
You can nest properties as deeply as needed using `.`'s. In addition to using `.` you can use standard ini section notation to create nested structures:
```
[section]
key = value
```
Once loaded into Configure, the above would be accessed using:
`Configure::read('section.key');
You can also use `.` separated values in section names to create more deeply nested structures.
IniConfig also manipulates how the special ini values of 'yes', 'no', 'on', 'off', 'null' are handled. These values will be converted to their boolean equivalents.
**Namespace:** [Cake\Core\Configure\Engine](namespace-cake.core.configure.engine)
**See:** https://secure.php.net/parse\_ini\_file
Property Summary
----------------
* [$\_extension](#%24_extension) protected `string` File extension.
* [$\_path](#%24_path) protected `string` The path this engine finds files on.
* [$\_section](#%24_section) protected `string|null` The section to read, if null all sections will be read.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Build and construct a new ini file parser. The parser can be used to read ini files that are on the filesystem.
* ##### [\_getFilePath()](#_getFilePath()) protected
Get file path
* ##### [\_parseNestedValues()](#_parseNestedValues()) protected
parses nested values out of keys.
* ##### [\_value()](#_value()) protected
Converts a value into the ini equivalent
* ##### [dump()](#dump()) public
Dumps the state of Configure data into an ini formatted string.
* ##### [read()](#read()) public
Read an ini file and return the results as an array.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $path = null, string|null $section = null)
```
Build and construct a new ini file parser. The parser can be used to read ini files that are on the filesystem.
#### Parameters
`string|null` $path optional Path to load ini config files from. Defaults to CONFIG.
`string|null` $section optional Only get one section, leave null to parse and fetch all sections in the ini file.
### \_getFilePath() protected
```
_getFilePath(string $key, bool $checkExists = false): string
```
Get file path
#### Parameters
`string` $key The identifier to write to. If the key has a . it will be treated as a plugin prefix.
`bool` $checkExists optional Whether to check if file exists. Defaults to false.
#### Returns
`string`
#### Throws
`Cake\Core\Exception\CakeException`
When files don't exist or when files contain '..' as this could lead to abusive reads. ### \_parseNestedValues() protected
```
_parseNestedValues(array $values): array
```
parses nested values out of keys.
#### Parameters
`array` $values Values to be exploded.
#### Returns
`array`
### \_value() protected
```
_value(mixed $value): string
```
Converts a value into the ini equivalent
#### Parameters
`mixed` $value Value to export.
#### Returns
`string`
### dump() public
```
dump(string $key, array $data): bool
```
Dumps the state of Configure data into an ini formatted string.
#### Parameters
`string` $key The identifier to write to. If the key has a . it will be treated as a plugin prefix.
`array` $data The data to convert to ini file.
#### Returns
`bool`
### read() public
```
read(string $key): array
```
Read an ini file and return the results as an array.
This method is used for reading configuration information from sources. These sources can either be static resources like files, or dynamic ones like a database, or other datasource.
#### Parameters
`string` $key The identifier to read from. If the key has a . it will be treated as a plugin prefix. The chosen file must be on the engine's path.
#### Returns
`array`
#### Throws
`Cake\Core\Exception\CakeException`
when files don't exist. Or when files contain '..' as this could lead to abusive reads. Property Detail
---------------
### $\_extension protected
File extension.
#### Type
`string`
### $\_path protected
The path this engine finds files on.
#### Type
`string`
### $\_section protected
The section to read, if null all sections will be read.
#### Type
`string|null`
cakephp Class Validator Class Validator
================
Validator object encapsulates all methods related to data validations for a model It also provides an API to dynamically change validation rules for each model field.
Implements ArrayAccess to easily modify rules in the set
**Namespace:** [Cake\Validation](namespace-cake.validation)
**Link:** https://book.cakephp.org/4/en/core-libraries/validation.html
Constants
---------
* `int` **EMPTY\_ALL**
```
self::EMPTY_STRING | self::EMPTY_ARRAY | self::EMPTY_FILE | self::EMPTY_DATE | self::EMPTY_TIME
```
A combination of the all EMPTY\_\* flags
* `int` **EMPTY\_ARRAY**
```
2
```
A flag for allowEmptyFor()
When an empty array is given, it will be recognized as empty.
* `int` **EMPTY\_DATE**
```
8
```
A flag for allowEmptyFor()
When an array is given, if it contains the `year` key, and only empty strings or null values, it will be recognized as empty.
* `int` **EMPTY\_FILE**
```
4
```
A flag for allowEmptyFor()
When an array is given, if it has at least the `name`, `type`, `tmp_name` and `error` keys, and the value of `error` is equal to `UPLOAD_ERR_NO_FILE`, the value will be recognized as empty.
When an instance of \Psr\Http\Message\UploadedFileInterface is given the return value of it's getError() method must be equal to `UPLOAD_ERR_NO_FILE`.
* `int` **EMPTY\_NULL**
```
0
```
A flag for allowEmptyFor()
When `null` is given, it will be recognized as empty.
* `int` **EMPTY\_STRING**
```
1
```
A flag for allowEmptyFor()
When an empty string is given, it will be recognized as empty.
* `int` **EMPTY\_TIME**
```
16
```
A flag for allowEmptyFor()
When an array is given, if it contains the `hour` key, and only empty strings or null values, it will be recognized as empty.
* `string` **NESTED**
```
'_nested'
```
Used to flag nested rules created with addNested() and addNestedMany()
* `string` **WHEN\_CREATE**
```
'create'
```
By using 'create' you can make fields required when records are first created.
* `string` **WHEN\_UPDATE**
```
'update'
```
By using 'update', you can make fields required when they are updated.
Property Summary
----------------
* [$\_allowEmptyFlags](#%24_allowEmptyFlags) protected `array<string, int>` Contains the flags which specify what is empty for each corresponding field.
* [$\_allowEmptyMessages](#%24_allowEmptyMessages) protected `array<string, string>` Contains the validation messages associated with checking the emptiness for each corresponding field.
* [$\_defaultProviders](#%24_defaultProviders) protected static `array<string, object|string>` An associative array of objects or classes used as a default provider list
* [$\_fields](#%24_fields) protected `array<string,Cake\Validation\ValidationSet>` Holds the ValidationSet objects array
* [$\_presenceMessages](#%24_presenceMessages) protected `array<string, string>` Contains the validation messages associated with checking the presence for each corresponding field.
* [$\_providers](#%24_providers) protected `array<string, object|string>` An associative array of objects or classes containing methods used for validation
* [$\_stopOnFailure](#%24_stopOnFailure) protected `bool` Whether to apply last flag to generated rule(s).
* [$\_useI18n](#%24_useI18n) protected `bool` Whether to use I18n functions for translating default error messages
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Get the printable version of this object.
* ##### [\_canBeEmpty()](#_canBeEmpty()) protected
Returns whether the field can be left blank according to `allowEmpty`
* ##### [\_checkPresence()](#_checkPresence()) protected
Returns false if any validation for the passed rule set should be stopped due to the field missing in the data array
* ##### [\_convertValidatorToArray()](#_convertValidatorToArray()) protected
Converts validator to fieldName => $settings array
* ##### [\_fieldIsEmpty()](#_fieldIsEmpty()) protected deprecated
Returns true if the field is empty in the passed data array
* ##### [\_processRules()](#_processRules()) protected
Iterates over each rule in the validation set and collects the errors resulting from executing them
* ##### [add()](#add()) public
Adds a new rule to a field's rule set. If second argument is an array then rules list for the field will be replaced with second argument and third argument will be ignored.
* ##### [addDefaultProvider()](#addDefaultProvider()) public static
Associates an object to a name so it can be used as a default provider.
* ##### [addNested()](#addNested()) public
Adds a nested validator.
* ##### [addNestedMany()](#addNestedMany()) public
Adds a nested validator.
* ##### [allowEmpty()](#allowEmpty()) public deprecated
Allows a field to be empty. You can also pass array. Using an array will let you provide the following keys:
* ##### [allowEmptyArray()](#allowEmptyArray()) public
Allows a field to be an empty array.
* ##### [allowEmptyDate()](#allowEmptyDate()) public
Allows a field to be an empty date.
* ##### [allowEmptyDateTime()](#allowEmptyDateTime()) public
Allows a field to be an empty date/time.
* ##### [allowEmptyFile()](#allowEmptyFile()) public
Allows a field to be an empty file.
* ##### [allowEmptyFor()](#allowEmptyFor()) public
Low-level method to indicate that a field can be empty.
* ##### [allowEmptyString()](#allowEmptyString()) public
Allows a field to be an empty string.
* ##### [allowEmptyTime()](#allowEmptyTime()) public
Allows a field to be an empty time.
* ##### [alphaNumeric()](#alphaNumeric()) public
Add an alphanumeric rule to a field.
* ##### [ascii()](#ascii()) public
Add a validation rule to ensure a field contains only ascii bytes
* ##### [asciiAlphaNumeric()](#asciiAlphaNumeric()) public
Add an ascii-alphanumeric rule to a field.
* ##### [boolean()](#boolean()) public
Add a boolean validation rule to a field.
* ##### [containsNonAlphaNumeric()](#containsNonAlphaNumeric()) public deprecated
Add a rule to check if a field contains non alpha numeric characters.
* ##### [count()](#count()) public
Returns the number of fields having validation rules
* ##### [creditCard()](#creditCard()) public
Add a credit card rule to a field.
* ##### [date()](#date()) public
Add a date format validation rule to a field.
* ##### [dateTime()](#dateTime()) public
Add a date time format validation rule to a field.
* ##### [decimal()](#decimal()) public
Add a decimal validation rule to a field.
* ##### [email()](#email()) public
Add an email validation rule to a field.
* ##### [equalToField()](#equalToField()) public
Add a rule to compare one field is equal to another.
* ##### [equals()](#equals()) public
Add a equal to comparison rule to a field.
* ##### [errors()](#errors()) public deprecated
Validates and returns an array of failed fields and their error messages.
* ##### [field()](#field()) public
Returns a ValidationSet object containing all validation rules for a field, if passed a ValidationSet as second argument, it will replace any other rule set defined before
* ##### [getDefaultProvider()](#getDefaultProvider()) public static
Returns the default provider stored under that name if it exists.
* ##### [getDefaultProviders()](#getDefaultProviders()) public static
Get the list of default providers.
* ##### [getIterator()](#getIterator()) public
Returns an iterator for each of the fields to be validated
* ##### [getNotEmptyMessage()](#getNotEmptyMessage()) public
Gets the notEmpty message for a field
* ##### [getProvider()](#getProvider()) public
Returns the provider stored under that name if it exists.
* ##### [getRequiredMessage()](#getRequiredMessage()) public
Gets the required message for a field
* ##### [greaterThan()](#greaterThan()) public
Add a greater than comparison rule to a field.
* ##### [greaterThanField()](#greaterThanField()) public
Add a rule to compare one field is greater than another.
* ##### [greaterThanOrEqual()](#greaterThanOrEqual()) public
Add a greater than or equal to comparison rule to a field.
* ##### [greaterThanOrEqualToField()](#greaterThanOrEqualToField()) public
Add a rule to compare one field is greater than or equal to another.
* ##### [hasAtLeast()](#hasAtLeast()) public
Add a validation rule to ensure that a field is an array containing at least the specified amount of elements
* ##### [hasAtMost()](#hasAtMost()) public
Add a validation rule to ensure that a field is an array containing at most the specified amount of elements
* ##### [hasField()](#hasField()) public
Check whether a validator contains any rules for the given field.
* ##### [hexColor()](#hexColor()) public
Add a validation rule to ensure a field is a 6 digits hex color value.
* ##### [inList()](#inList()) public
Add a validation rule to ensure the field value is within an allowed list.
* ##### [integer()](#integer()) public
Add a validation rule to ensure a field is an integer value.
* ##### [invertWhenClause()](#invertWhenClause()) protected
Invert a when clause for creating notEmpty rules
* ##### [ip()](#ip()) public
Add an IP validation rule to a field.
* ##### [ipv4()](#ipv4()) public
Add an IPv4 validation rule to a field.
* ##### [ipv6()](#ipv6()) public
Add an IPv6 validation rule to a field.
* ##### [isArray()](#isArray()) public
Add a validation rule to ensure that a field contains an array.
* ##### [isEmpty()](#isEmpty()) protected
Returns true if the field is empty in the passed data array
* ##### [isEmptyAllowed()](#isEmptyAllowed()) public
Returns whether a field can be left empty for a new or already existing record.
* ##### [isPresenceRequired()](#isPresenceRequired()) public
Returns whether a field can be left out for a new or already existing record.
* ##### [latLong()](#latLong()) public
Add a validation rule to ensure the field is a lat/long tuple.
* ##### [latitude()](#latitude()) public
Add a validation rule to ensure the field is a latitude.
* ##### [lengthBetween()](#lengthBetween()) public
Add an rule that ensures a string length is within a range.
* ##### [lessThan()](#lessThan()) public
Add a less than comparison rule to a field.
* ##### [lessThanField()](#lessThanField()) public
Add a rule to compare one field is less than another.
* ##### [lessThanOrEqual()](#lessThanOrEqual()) public
Add a less than or equal comparison rule to a field.
* ##### [lessThanOrEqualToField()](#lessThanOrEqualToField()) public
Add a rule to compare one field is less than or equal to another.
* ##### [localizedTime()](#localizedTime()) public
Add a localized time, date or datetime format validation rule to a field.
* ##### [longitude()](#longitude()) public
Add a validation rule to ensure the field is a longitude.
* ##### [maxLength()](#maxLength()) public
Add a string length validation rule to a field.
* ##### [maxLengthBytes()](#maxLengthBytes()) public
Add a string length validation rule to a field.
* ##### [minLength()](#minLength()) public
Add a string length validation rule to a field.
* ##### [minLengthBytes()](#minLengthBytes()) public
Add a string length validation rule to a field.
* ##### [multipleOptions()](#multipleOptions()) public
Add a validation rule for a multiple select. Comparison is case sensitive by default.
* ##### [naturalNumber()](#naturalNumber()) public
Add a natural number validation rule to a field.
* ##### [nonNegativeInteger()](#nonNegativeInteger()) public
Add a validation rule to ensure a field is a non negative integer.
* ##### [notAlphaNumeric()](#notAlphaNumeric()) public
Add a non-alphanumeric rule to a field.
* ##### [notAsciiAlphaNumeric()](#notAsciiAlphaNumeric()) public
Add a non-ascii alphanumeric rule to a field.
* ##### [notBlank()](#notBlank()) public
Add a notBlank rule to a field.
* ##### [notEmpty()](#notEmpty()) public deprecated
Sets a field to require a non-empty value. You can also pass array. Using an array will let you provide the following keys:
* ##### [notEmptyArray()](#notEmptyArray()) public
Require a field to be a non-empty array
* ##### [notEmptyDate()](#notEmptyDate()) public
Require a non-empty date value
* ##### [notEmptyDateTime()](#notEmptyDateTime()) public
Require a field to be a non empty date/time.
* ##### [notEmptyFile()](#notEmptyFile()) public
Require a field to be a not-empty file.
* ##### [notEmptyString()](#notEmptyString()) public
Requires a field to not be an empty string.
* ##### [notEmptyTime()](#notEmptyTime()) public
Require a field to be a non-empty time.
* ##### [notEqualToField()](#notEqualToField()) public
Add a rule to compare one field is not equal to another.
* ##### [notEquals()](#notEquals()) public
Add a not equal to comparison rule to a field.
* ##### [notSameAs()](#notSameAs()) public
Add a rule to compare that two fields have different values.
* ##### [numeric()](#numeric()) public
Add a numeric value validation rule to a field.
* ##### [offsetExists()](#offsetExists()) public
Returns whether a rule set is defined for a field or not
* ##### [offsetGet()](#offsetGet()) public
Returns the rule set for a field
* ##### [offsetSet()](#offsetSet()) public
Sets the rule set for a field
* ##### [offsetUnset()](#offsetUnset()) public
Unsets the rule set for a field
* ##### [providers()](#providers()) public
Get the list of providers in this validator.
* ##### [range()](#range()) public
Add a validation rule to ensure a field is within a numeric range
* ##### [regex()](#regex()) public
Returns whether a field matches against a regular expression.
* ##### [remove()](#remove()) public
Removes a rule from the set by its name
* ##### [requirePresence()](#requirePresence()) public
Sets whether a field is required to be present in data array. You can also pass array. Using an array will let you provide the following keys:
* ##### [sameAs()](#sameAs()) public
Add a rule to compare two fields to each other.
* ##### [scalar()](#scalar()) public
Add a validation rule to ensure that a field contains a scalar.
* ##### [setProvider()](#setProvider()) public
Associates an object to a name so it can be used as a provider. Providers are objects or class names that can contain methods used during validation of for deciding whether a validation rule can be applied. All validation methods, when called will receive the full list of providers stored in this validator.
* ##### [setStopOnFailure()](#setStopOnFailure()) public
Whether to stop validation rule evaluation on the first failed rule.
* ##### [time()](#time()) public
Add a time format validation rule to a field.
* ##### [uploadedFile()](#uploadedFile()) public
Add a validation rule to ensure the field is an uploaded file
* ##### [url()](#url()) public
Add a validation rule to ensure a field is a URL.
* ##### [urlWithProtocol()](#urlWithProtocol()) public
Add a validation rule to ensure a field is a URL.
* ##### [utf8()](#utf8()) public
Add a validation rule to ensure a field contains only BMP utf8 bytes
* ##### [utf8Extended()](#utf8Extended()) public
Add a validation rule to ensure a field contains only utf8 bytes.
* ##### [uuid()](#uuid()) public
Add a validation rule to ensure the field is a UUID
* ##### [validate()](#validate()) public
Validates and returns an array of failed fields and their error messages.
Method Detail
-------------
### \_\_construct() public
```
__construct()
```
Constructor
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Get the printable version of this object.
#### Returns
`array<string, mixed>`
### \_canBeEmpty() protected
```
_canBeEmpty(Cake\Validation\ValidationSet $field, array<string, mixed> $context): bool
```
Returns whether the field can be left blank according to `allowEmpty`
#### Parameters
`Cake\Validation\ValidationSet` $field the set of rules for a field
`array<string, mixed>` $context a key value list of data containing the validation context.
#### Returns
`bool`
### \_checkPresence() protected
```
_checkPresence(Cake\Validation\ValidationSet $field, array<string, mixed> $context): bool
```
Returns false if any validation for the passed rule set should be stopped due to the field missing in the data array
#### Parameters
`Cake\Validation\ValidationSet` $field The set of rules for a field.
`array<string, mixed>` $context A key value list of data containing the validation context.
#### Returns
`bool`
### \_convertValidatorToArray() protected
```
_convertValidatorToArray(string|int $fieldName, array<string, mixed> $defaults = [], array<string, mixed>|string $settings = []): array<array>
```
Converts validator to fieldName => $settings array
#### Parameters
`string|int` $fieldName name of field
`array<string, mixed>` $defaults optional default settings
`array<string, mixed>|string` $settings optional settings from data
#### Returns
`array<array>`
#### Throws
`InvalidArgumentException`
### \_fieldIsEmpty() protected
```
_fieldIsEmpty(mixed $data): bool
```
Returns true if the field is empty in the passed data array
#### Parameters
`mixed` $data Value to check against.
#### Returns
`bool`
### \_processRules() protected
```
_processRules(string $field, Cake\Validation\ValidationSet $rules, array $data, bool $newRecord): array<string, mixed>
```
Iterates over each rule in the validation set and collects the errors resulting from executing them
#### Parameters
`string` $field The name of the field that is being processed
`Cake\Validation\ValidationSet` $rules the list of rules for a field
`array` $data the full data passed to the validator
`bool` $newRecord whether is it a new record or an existing one
#### Returns
`array<string, mixed>`
### add() public
```
add(string $field, array|string $name, Cake\Validation\ValidationRule|array $rule = []): $this
```
Adds a new rule to a field's rule set. If second argument is an array then rules list for the field will be replaced with second argument and third argument will be ignored.
### Example:
```
$validator
->add('title', 'required', ['rule' => 'notBlank'])
->add('user_id', 'valid', ['rule' => 'numeric', 'message' => 'Invalid User'])
$validator->add('password', [
'size' => ['rule' => ['lengthBetween', 8, 20]],
'hasSpecialCharacter' => ['rule' => 'validateSpecialchar', 'message' => 'not valid']
]);
```
#### Parameters
`string` $field The name of the field from which the rule will be added
`array|string` $name The alias for a single rule or multiple rules array
`Cake\Validation\ValidationRule|array` $rule optional the rule to add
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
If numeric index cannot be resolved to a string one ### addDefaultProvider() public static
```
addDefaultProvider(string $name, object|string $object): void
```
Associates an object to a name so it can be used as a default provider.
#### Parameters
`string` $name The name under which the provider should be set.
`object|string` $object Provider object or class name.
#### Returns
`void`
### addNested() public
```
addNested(string $field, Cake\Validation\Validator $validator, string|null $message = null, callable|string|null $when = null): $this
```
Adds a nested validator.
Nesting validators allows you to define validators for array types. For example, nested validators are ideal when you want to validate a sub-document, or complex array type.
This method assumes that the sub-document has a 1:1 relationship with the parent.
The providers of the parent validator will be synced into the nested validator, when errors are checked. This ensures that any validation rule providers connected in the parent will have the same values in the nested validator when rules are evaluated.
#### Parameters
`string` $field The root field for the nested validator.
`Cake\Validation\Validator` $validator The nested validator.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
### addNestedMany() public
```
addNestedMany(string $field, Cake\Validation\Validator $validator, string|null $message = null, callable|string|null $when = null): $this
```
Adds a nested validator.
Nesting validators allows you to define validators for array types. For example, nested validators are ideal when you want to validate many similar sub-documents or complex array types.
This method assumes that the sub-document has a 1:N relationship with the parent.
The providers of the parent validator will be synced into the nested validator, when errors are checked. This ensures that any validation rule providers connected in the parent will have the same values in the nested validator when rules are evaluated.
#### Parameters
`string` $field The root field for the nested validator.
`Cake\Validation\Validator` $validator The nested validator.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
### allowEmpty() public
```
allowEmpty(array|string $field, callable|string|bool $when = true, string|null $message = null): $this
```
Allows a field to be empty. You can also pass array. Using an array will let you provide the following keys:
* `when` individual when condition for field
* 'message' individual message for field
You can also set when and message for all passed fields, the individual setting takes precedence over group settings.
This is the opposite of notEmpty() which requires a field to not be empty. By using $mode equal to 'create' or 'update', you can allow fields to be empty when records are first created, or when they are updated.
### Example:
```
// Email can be empty
$validator->allowEmpty('email');
// Email can be empty on create
$validator->allowEmpty('email', Validator::WHEN_CREATE);
// Email can be empty on update
$validator->allowEmpty('email', Validator::WHEN_UPDATE);
// Email and subject can be empty on update
$validator->allowEmpty(['email', 'subject'], Validator::WHEN_UPDATE;
// Email can be always empty, subject and content can be empty on update.
$validator->allowEmpty(
[
'email' => [
'when' => true
],
'content' => [
'message' => 'Content cannot be empty'
],
'subject'
],
Validator::WHEN_UPDATE
);
```
It is possible to conditionally allow emptiness on a field by passing a callback as a second argument. The callback will receive the validation context array as argument:
```
$validator->allowEmpty('email', function ($context) {
return !$context['newRecord'] || $context['data']['role'] === 'admin';
});
```
This method will correctly detect empty file uploads and date/time/datetime fields.
Because this and `notEmpty()` modify the same internal state, the last method called will take precedence.
#### Parameters
`array|string` $field the name of the field or a list of fields
`callable|string|bool` $when optional Indicates when the field is allowed to be empty Valid values are true (always), 'create', 'update'. If a callable is passed then the field will allowed to be empty only when the callback returns true.
`string|null` $message optional The message to show if the field is not
#### Returns
`$this`
### allowEmptyArray() public
```
allowEmptyArray(string $field, string|null $message = null, callable|string|bool $when = true): $this
```
Allows a field to be an empty array.
This method is equivalent to calling allowEmptyFor() with EMPTY\_STRING + EMPTY\_ARRAY flags.
#### Parameters
`string` $field The name of the field.
`string|null` $message optional The message to show if the field is not
`callable|string|bool` $when optional Indicates when the field is allowed to be empty Valid values are true, false, 'create', 'update'. If a callable is passed then the field will allowed to be empty only when the callback returns true.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validator::allowEmptyFor() for examples. ### allowEmptyDate() public
```
allowEmptyDate(string $field, string|null $message = null, callable|string|bool $when = true): $this
```
Allows a field to be an empty date.
Empty date values are `null`, `''`, `[]` and arrays where all values are `''` and the `year` key is present.
#### Parameters
`string` $field The name of the field.
`string|null` $message optional The message to show if the field is not
`callable|string|bool` $when optional Indicates when the field is allowed to be empty Valid values are true, false, 'create', 'update'. If a callable is passed then the field will allowed to be empty only when the callback returns true.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validator::allowEmptyFor() for examples ### allowEmptyDateTime() public
```
allowEmptyDateTime(string $field, string|null $message = null, callable|string|bool $when = true): $this
```
Allows a field to be an empty date/time.
Empty date values are `null`, `''`, `[]` and arrays where all values are `''` and the `year` and `hour` keys are present.
This method is equivalent to calling allowEmptyFor() with EMPTY\_STRING + EMPTY\_DATE + EMPTY\_TIME flags.
#### Parameters
`string` $field The name of the field.
`string|null` $message optional The message to show if the field is not
`callable|string|bool` $when optional Indicates when the field is allowed to be empty Valid values are true, false, 'create', 'update'. If a callable is passed then the field will allowed to be empty only when the callback returns false.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validator::allowEmptyFor() for examples. ### allowEmptyFile() public
```
allowEmptyFile(string $field, string|null $message = null, callable|string|bool $when = true): $this
```
Allows a field to be an empty file.
This method is equivalent to calling allowEmptyFor() with EMPTY\_FILE flag. File fields will not accept `''`, or `[]` as empty values. Only `null` and a file upload with `error` equal to `UPLOAD_ERR_NO_FILE` will be treated as empty.
#### Parameters
`string` $field The name of the field.
`string|null` $message optional The message to show if the field is not
`callable|string|bool` $when optional Indicates when the field is allowed to be empty Valid values are true, 'create', 'update'. If a callable is passed then the field will allowed to be empty only when the callback returns true.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validator::allowEmptyFor() For detail usage ### allowEmptyFor() public
```
allowEmptyFor(string $field, int|null $flags = null, callable|string|bool $when = true, string|null $message = null): $this
```
Low-level method to indicate that a field can be empty.
This method should generally not be used and instead you should use:
* `allowEmptyString()`
* `allowEmptyArray()`
* `allowEmptyFile()`
* `allowEmptyDate()`
* `allowEmptyDatetime()`
* `allowEmptyTime()`
Should be used as their APIs are simpler to operate and read.
You can also set flags, when and message for all passed fields, the individual setting takes precedence over group settings.
### Example:
```
// Email can be empty
$validator->allowEmptyFor('email', Validator::EMPTY_STRING);
// Email can be empty on create
$validator->allowEmptyFor('email', Validator::EMPTY_STRING, Validator::WHEN_CREATE);
// Email can be empty on update
$validator->allowEmptyFor('email', Validator::EMPTY_STRING, Validator::WHEN_UPDATE);
```
It is possible to conditionally allow emptiness on a field by passing a callback as a second argument. The callback will receive the validation context array as argument:
```
$validator->allowEmpty('email', Validator::EMPTY_STRING, function ($context) {
return !$context['newRecord'] || $context['data']['role'] === 'admin';
});
```
If you want to allow other kind of empty data on a field, you need to pass other flags:
```
$validator->allowEmptyFor('photo', Validator::EMPTY_FILE);
$validator->allowEmptyFor('published', Validator::EMPTY_STRING | Validator::EMPTY_DATE | Validator::EMPTY_TIME);
$validator->allowEmptyFor('items', Validator::EMPTY_STRING | Validator::EMPTY_ARRAY);
```
You can also use convenience wrappers of this method. The following calls are the same as above:
```
$validator->allowEmptyFile('photo');
$validator->allowEmptyDateTime('published');
$validator->allowEmptyArray('items');
```
#### Parameters
`string` $field The name of the field.
`int|null` $flags optional A bitmask of EMPTY\_\* flags which specify what is empty. If no flags/bitmask is provided only `null` will be allowed as empty value.
`callable|string|bool` $when optional Indicates when the field is allowed to be empty Valid values are true, false, 'create', 'update'. If a callable is passed then the field will allowed to be empty only when the callback returns true.
`string|null` $message optional The message to show if the field is not
#### Returns
`$this`
### allowEmptyString() public
```
allowEmptyString(string $field, string|null $message = null, callable|string|bool $when = true): $this
```
Allows a field to be an empty string.
This method is equivalent to calling allowEmptyFor() with EMPTY\_STRING flag.
#### Parameters
`string` $field The name of the field.
`string|null` $message optional The message to show if the field is not
`callable|string|bool` $when optional Indicates when the field is allowed to be empty Valid values are true, false, 'create', 'update'. If a callable is passed then the field will allowed to be empty only when the callback returns true.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validator::allowEmptyFor() For detail usage ### allowEmptyTime() public
```
allowEmptyTime(string $field, string|null $message = null, callable|string|bool $when = true): $this
```
Allows a field to be an empty time.
Empty date values are `null`, `''`, `[]` and arrays where all values are `''` and the `hour` key is present.
This method is equivalent to calling allowEmptyFor() with EMPTY\_STRING + EMPTY\_TIME flags.
#### Parameters
`string` $field The name of the field.
`string|null` $message optional The message to show if the field is not
`callable|string|bool` $when optional Indicates when the field is allowed to be empty Valid values are true, false, 'create', 'update'. If a callable is passed then the field will allowed to be empty only when the callback returns true.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validator::allowEmptyFor() for examples. ### alphaNumeric() public
```
alphaNumeric(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add an alphanumeric rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::alphaNumeric() ### ascii() public
```
ascii(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure a field contains only ascii bytes
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::ascii() ### asciiAlphaNumeric() public
```
asciiAlphaNumeric(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add an ascii-alphanumeric rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::asciiAlphaNumeric() ### boolean() public
```
boolean(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a boolean validation rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::boolean() ### containsNonAlphaNumeric() public
```
containsNonAlphaNumeric(string $field, int $limit = 1, string|null $message = null, callable|string|null $when = null): $this
```
Add a rule to check if a field contains non alpha numeric characters.
#### Parameters
`string` $field The field you want to apply the rule to.
`int` $limit optional The minimum number of non-alphanumeric fields required.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::containsNonAlphaNumeric() ### count() public
```
count(): int
```
Returns the number of fields having validation rules
#### Returns
`int`
### creditCard() public
```
creditCard(string $field, string $type = 'all', string|null $message = null, callable|string|null $when = null): $this
```
Add a credit card rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`string` $type optional The type of cards you want to allow. Defaults to 'all'. You can also supply an array of accepted card types. e.g `['mastercard', 'visa', 'amex']`
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::creditCard() ### date() public
```
date(string $field, array<string> $formats = ['ymd'], string|null $message = null, callable|string|null $when = null): $this
```
Add a date format validation rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`array<string>` $formats optional A list of accepted date formats.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::date() ### dateTime() public
```
dateTime(string $field, array<string> $formats = ['ymd'], string|null $message = null, callable|string|null $when = null): $this
```
Add a date time format validation rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`array<string>` $formats optional A list of accepted date formats.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::datetime() ### decimal() public
```
decimal(string $field, int|null $places = null, string|null $message = null, callable|string|null $when = null): $this
```
Add a decimal validation rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`int|null` $places optional The number of decimal places to require.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::decimal() ### email() public
```
email(string $field, bool $checkMX = false, string|null $message = null, callable|string|null $when = null): $this
```
Add an email validation rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`bool` $checkMX optional Whether to check the MX records.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::email() ### equalToField() public
```
equalToField(string $field, string $secondField, string|null $message = null, callable|string|null $when = null): $this
```
Add a rule to compare one field is equal to another.
#### Parameters
`string` $field The field you want to apply the rule to.
`string` $secondField The field you want to compare against.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::compareFields() ### equals() public
```
equals(string $field, float|int $value, string|null $message = null, callable|string|null $when = null): $this
```
Add a equal to comparison rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`float|int` $value The value user data must be equal to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::comparison() ### errors() public
```
errors(array $data, bool $newRecord = true): array<array>
```
Validates and returns an array of failed fields and their error messages.
#### Parameters
`array` $data The data to be checked for errors
`bool` $newRecord optional whether the data to be validated is new or to be updated.
#### Returns
`array<array>`
### field() public
```
field(string $name, Cake\Validation\ValidationSet|null $set = null): Cake\Validation\ValidationSet
```
Returns a ValidationSet object containing all validation rules for a field, if passed a ValidationSet as second argument, it will replace any other rule set defined before
#### Parameters
`string` $name [optional] The fieldname to fetch.
`Cake\Validation\ValidationSet|null` $set optional The set of rules for field
#### Returns
`Cake\Validation\ValidationSet`
### getDefaultProvider() public static
```
getDefaultProvider(string $name): object|string|null
```
Returns the default provider stored under that name if it exists.
#### Parameters
`string` $name The name under which the provider should be retrieved.
#### Returns
`object|string|null`
### getDefaultProviders() public static
```
getDefaultProviders(): array<string>
```
Get the list of default providers.
#### Returns
`array<string>`
### getIterator() public
```
getIterator(): Traversable<string,Cake\Validation\ValidationSet>
```
Returns an iterator for each of the fields to be validated
#### Returns
`Traversable<string,Cake\Validation\ValidationSet>`
### getNotEmptyMessage() public
```
getNotEmptyMessage(string $field): string|null
```
Gets the notEmpty message for a field
#### Parameters
`string` $field Field name
#### Returns
`string|null`
### getProvider() public
```
getProvider(string $name): object|string|null
```
Returns the provider stored under that name if it exists.
#### Parameters
`string` $name The name under which the provider should be set.
#### Returns
`object|string|null`
### getRequiredMessage() public
```
getRequiredMessage(string $field): string|null
```
Gets the required message for a field
#### Parameters
`string` $field Field name
#### Returns
`string|null`
### greaterThan() public
```
greaterThan(string $field, float|int $value, string|null $message = null, callable|string|null $when = null): $this
```
Add a greater than comparison rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`float|int` $value The value user data must be greater than.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::comparison() ### greaterThanField() public
```
greaterThanField(string $field, string $secondField, string|null $message = null, callable|string|null $when = null): $this
```
Add a rule to compare one field is greater than another.
#### Parameters
`string` $field The field you want to apply the rule to.
`string` $secondField The field you want to compare against.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::compareFields() ### greaterThanOrEqual() public
```
greaterThanOrEqual(string $field, float|int $value, string|null $message = null, callable|string|null $when = null): $this
```
Add a greater than or equal to comparison rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`float|int` $value The value user data must be greater than or equal to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::comparison() ### greaterThanOrEqualToField() public
```
greaterThanOrEqualToField(string $field, string $secondField, string|null $message = null, callable|string|null $when = null): $this
```
Add a rule to compare one field is greater than or equal to another.
#### Parameters
`string` $field The field you want to apply the rule to.
`string` $secondField The field you want to compare against.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::compareFields() ### hasAtLeast() public
```
hasAtLeast(string $field, int $count, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure that a field is an array containing at least the specified amount of elements
#### Parameters
`string` $field The field you want to apply the rule to.
`int` $count The number of elements the array should at least have
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::numElements() ### hasAtMost() public
```
hasAtMost(string $field, int $count, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure that a field is an array containing at most the specified amount of elements
#### Parameters
`string` $field The field you want to apply the rule to.
`int` $count The number maximum amount of elements the field should have
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::numElements() ### hasField() public
```
hasField(string $name): bool
```
Check whether a validator contains any rules for the given field.
#### Parameters
`string` $name The field name to check.
#### Returns
`bool`
### hexColor() public
```
hexColor(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure a field is a 6 digits hex color value.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::hexColor() ### inList() public
```
inList(string $field, array $list, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure the field value is within an allowed list.
#### Parameters
`string` $field The field you want to apply the rule to.
`array` $list The list of valid options.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::inList() ### integer() public
```
integer(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure a field is an integer value.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::isInteger() ### invertWhenClause() protected
```
invertWhenClause(callable|string|bool $when): callable|string|bool
```
Invert a when clause for creating notEmpty rules
#### Parameters
`callable|string|bool` $when Indicates when the field is not allowed to be empty. Valid values are true (always), 'create', 'update'. If a callable is passed then the field will allowed to be empty only when the callback returns false.
#### Returns
`callable|string|bool`
### ip() public
```
ip(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add an IP validation rule to a field.
This rule will accept both IPv4 and IPv6 addresses.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::ip() ### ipv4() public
```
ipv4(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add an IPv4 validation rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::ip() ### ipv6() public
```
ipv6(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add an IPv6 validation rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::ip() ### isArray() public
```
isArray(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure that a field contains an array.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::isArray() ### isEmpty() protected
```
isEmpty(mixed $data, int $flags): bool
```
Returns true if the field is empty in the passed data array
#### Parameters
`mixed` $data Value to check against.
`int` $flags A bitmask of EMPTY\_\* flags which specify what is empty
#### Returns
`bool`
### isEmptyAllowed() public
```
isEmptyAllowed(string $field, bool $newRecord): bool
```
Returns whether a field can be left empty for a new or already existing record.
#### Parameters
`string` $field Field name.
`bool` $newRecord whether the data to be validated is new or to be updated.
#### Returns
`bool`
### isPresenceRequired() public
```
isPresenceRequired(string $field, bool $newRecord): bool
```
Returns whether a field can be left out for a new or already existing record.
#### Parameters
`string` $field Field name.
`bool` $newRecord Whether the data to be validated is new or to be updated.
#### Returns
`bool`
### latLong() public
```
latLong(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure the field is a lat/long tuple.
e.g. `<lat>, <lng>`
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::uuid() ### latitude() public
```
latitude(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure the field is a latitude.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::latitude() ### lengthBetween() public
```
lengthBetween(string $field, array $range, string|null $message = null, callable|string|null $when = null): $this
```
Add an rule that ensures a string length is within a range.
#### Parameters
`string` $field The field you want to apply the rule to.
`array` $range The inclusive minimum and maximum length you want permitted.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
#### See Also
\Cake\Validation\Validation::alphaNumeric() ### lessThan() public
```
lessThan(string $field, float|int $value, string|null $message = null, callable|string|null $when = null): $this
```
Add a less than comparison rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`float|int` $value The value user data must be less than.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::comparison() ### lessThanField() public
```
lessThanField(string $field, string $secondField, string|null $message = null, callable|string|null $when = null): $this
```
Add a rule to compare one field is less than another.
#### Parameters
`string` $field The field you want to apply the rule to.
`string` $secondField The field you want to compare against.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::compareFields() ### lessThanOrEqual() public
```
lessThanOrEqual(string $field, float|int $value, string|null $message = null, callable|string|null $when = null): $this
```
Add a less than or equal comparison rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`float|int` $value The value user data must be less than or equal to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::comparison() ### lessThanOrEqualToField() public
```
lessThanOrEqualToField(string $field, string $secondField, string|null $message = null, callable|string|null $when = null): $this
```
Add a rule to compare one field is less than or equal to another.
#### Parameters
`string` $field The field you want to apply the rule to.
`string` $secondField The field you want to compare against.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::compareFields() ### localizedTime() public
```
localizedTime(string $field, string $type = 'datetime', string|null $message = null, callable|string|null $when = null): $this
```
Add a localized time, date or datetime format validation rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`string` $type optional Parser type, one out of 'date', 'time', and 'datetime'
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::localizedTime() ### longitude() public
```
longitude(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure the field is a longitude.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::longitude() ### maxLength() public
```
maxLength(string $field, int $max, string|null $message = null, callable|string|null $when = null): $this
```
Add a string length validation rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`int` $max The maximum length allowed.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::maxLength() ### maxLengthBytes() public
```
maxLengthBytes(string $field, int $max, string|null $message = null, callable|string|null $when = null): $this
```
Add a string length validation rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`int` $max The maximum length allowed.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::maxLengthBytes() ### minLength() public
```
minLength(string $field, int $min, string|null $message = null, callable|string|null $when = null): $this
```
Add a string length validation rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`int` $min The minimum length required.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::minLength() ### minLengthBytes() public
```
minLengthBytes(string $field, int $min, string|null $message = null, callable|string|null $when = null): $this
```
Add a string length validation rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`int` $min The minimum length required.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::minLengthBytes() ### multipleOptions() public
```
multipleOptions(string $field, array<string, mixed> $options = [], string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule for a multiple select. Comparison is case sensitive by default.
#### Parameters
`string` $field The field you want to apply the rule to.
`array<string, mixed>` $options optional The options for the validator. Includes the options defined in \Cake\Validation\Validation::multiple() and the `caseInsensitive` parameter.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::multiple() ### naturalNumber() public
```
naturalNumber(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a natural number validation rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::naturalNumber() ### nonNegativeInteger() public
```
nonNegativeInteger(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure a field is a non negative integer.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::naturalNumber() ### notAlphaNumeric() public
```
notAlphaNumeric(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a non-alphanumeric rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::notAlphaNumeric() ### notAsciiAlphaNumeric() public
```
notAsciiAlphaNumeric(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a non-ascii alphanumeric rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::notAlphaNumeric() ### notBlank() public
```
notBlank(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a notBlank rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::notBlank() ### notEmpty() public
```
notEmpty(array|string $field, string|null $message = null, callable|string|bool $when = false): $this
```
Sets a field to require a non-empty value. You can also pass array. Using an array will let you provide the following keys:
* `when` individual when condition for field
* `message` individual error message for field
You can also set `when` and `message` for all passed fields, the individual setting takes precedence over group settings.
This is the opposite of `allowEmpty()` which allows a field to be empty. By using $mode equal to 'create' or 'update', you can make fields required when records are first created, or when they are updated.
### Example:
```
$message = 'This field cannot be empty';
// Email cannot be empty
$validator->notEmpty('email');
// Email can be empty on update, but not create
$validator->notEmpty('email', $message, 'create');
// Email can be empty on create, but required on update.
$validator->notEmpty('email', $message, Validator::WHEN_UPDATE);
// Email and title can be empty on create, but are required on update.
$validator->notEmpty(['email', 'title'], $message, Validator::WHEN_UPDATE);
// Email can be empty on create, title must always be not empty
$validator->notEmpty(
[
'email',
'title' => [
'when' => true,
'message' => 'Title cannot be empty'
]
],
$message,
Validator::WHEN_UPDATE
);
```
It is possible to conditionally disallow emptiness on a field by passing a callback as the third argument. The callback will receive the validation context array as argument:
```
$validator->notEmpty('email', 'Email is required', function ($context) {
return $context['newRecord'] && $context['data']['role'] !== 'admin';
});
```
Because this and `allowEmpty()` modify the same internal state, the last method called will take precedence.
#### Parameters
`array|string` $field the name of the field or list of fields
`string|null` $message optional The message to show if the field is not
`callable|string|bool` $when optional Indicates when the field is not allowed to be empty. Valid values are true (always), 'create', 'update'. If a callable is passed then the field will allowed to be empty only when the callback returns false.
#### Returns
`$this`
### notEmptyArray() public
```
notEmptyArray(string $field, string|null $message = null, callable|string|bool $when = false): $this
```
Require a field to be a non-empty array
Opposite to allowEmptyArray()
#### Parameters
`string` $field The name of the field.
`string|null` $message optional The message to show if the field is empty.
`callable|string|bool` $when optional Indicates when the field is not allowed to be empty. Valid values are false (never), 'create', 'update'. If a callable is passed then the field will be required to be not empty when the callback returns true.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validator::allowEmptyArray() ### notEmptyDate() public
```
notEmptyDate(string $field, string|null $message = null, callable|string|bool $when = false): $this
```
Require a non-empty date value
#### Parameters
`string` $field The name of the field.
`string|null` $message optional The message to show if the field is empty.
`callable|string|bool` $when optional Indicates when the field is not allowed to be empty. Valid values are false (never), 'create', 'update'. If a callable is passed then the field will be required to be not empty when the callback returns true.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validator::allowEmptyDate() for examples ### notEmptyDateTime() public
```
notEmptyDateTime(string $field, string|null $message = null, callable|string|bool $when = false): $this
```
Require a field to be a non empty date/time.
Opposite to allowEmptyDateTime
#### Parameters
`string` $field The name of the field.
`string|null` $message optional The message to show if the field is empty.
`callable|string|bool` $when optional Indicates when the field is not allowed to be empty. Valid values are false (never), 'create', 'update'. If a callable is passed then the field will be required to be not empty when the callback returns true.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validator::allowEmptyDateTime() ### notEmptyFile() public
```
notEmptyFile(string $field, string|null $message = null, callable|string|bool $when = false): $this
```
Require a field to be a not-empty file.
Opposite to allowEmptyFile()
#### Parameters
`string` $field The name of the field.
`string|null` $message optional The message to show if the field is empty.
`callable|string|bool` $when optional Indicates when the field is not allowed to be empty. Valid values are false (never), 'create', 'update'. If a callable is passed then the field will be required to be not empty when the callback returns true.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validator::allowEmptyFile() ### notEmptyString() public
```
notEmptyString(string $field, string|null $message = null, callable|string|bool $when = false): $this
```
Requires a field to not be an empty string.
Opposite to allowEmptyString()
#### Parameters
`string` $field The name of the field.
`string|null` $message optional The message to show if the field is empty.
`callable|string|bool` $when optional Indicates when the field is not allowed to be empty. Valid values are false (never), 'create', 'update'. If a callable is passed then the field will be required to be not empty when the callback returns true.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validator::allowEmptyString() ### notEmptyTime() public
```
notEmptyTime(string $field, string|null $message = null, callable|string|bool $when = false): $this
```
Require a field to be a non-empty time.
Opposite to allowEmptyTime()
#### Parameters
`string` $field The name of the field.
`string|null` $message optional The message to show if the field is empty.
`callable|string|bool` $when optional Indicates when the field is not allowed to be empty. Valid values are false (never), 'create', 'update'. If a callable is passed then the field will be required to be not empty when the callback returns true.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validator::allowEmptyTime() ### notEqualToField() public
```
notEqualToField(string $field, string $secondField, string|null $message = null, callable|string|null $when = null): $this
```
Add a rule to compare one field is not equal to another.
#### Parameters
`string` $field The field you want to apply the rule to.
`string` $secondField The field you want to compare against.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::compareFields() ### notEquals() public
```
notEquals(string $field, float|int $value, string|null $message = null, callable|string|null $when = null): $this
```
Add a not equal to comparison rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`float|int` $value The value user data must be not be equal to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::comparison() ### notSameAs() public
```
notSameAs(string $field, string $secondField, string|null $message = null, callable|string|null $when = null): $this
```
Add a rule to compare that two fields have different values.
#### Parameters
`string` $field The field you want to apply the rule to.
`string` $secondField The field you want to compare against.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::compareFields() ### numeric() public
```
numeric(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a numeric value validation rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::numeric() ### offsetExists() public
```
offsetExists(string $field): bool
```
Returns whether a rule set is defined for a field or not
#### Parameters
`string` $field name of the field to check
#### Returns
`bool`
### offsetGet() public
```
offsetGet(string $field): Cake\Validation\ValidationSet
```
Returns the rule set for a field
#### Parameters
`string` $field name of the field to check
#### Returns
`Cake\Validation\ValidationSet`
### offsetSet() public
```
offsetSet(string $field, Cake\Validation\ValidationSet|array $rules): void
```
Sets the rule set for a field
#### Parameters
`string` $field name of the field to set
`Cake\Validation\ValidationSet|array` $rules set of rules to apply to field
#### Returns
`void`
### offsetUnset() public
```
offsetUnset(string $field): void
```
Unsets the rule set for a field
#### Parameters
`string` $field name of the field to unset
#### Returns
`void`
### providers() public
```
providers(): array<string>
```
Get the list of providers in this validator.
#### Returns
`array<string>`
### range() public
```
range(string $field, array $range, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure a field is within a numeric range
#### Parameters
`string` $field The field you want to apply the rule to.
`array` $range The inclusive upper and lower bounds of the valid range.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
#### See Also
\Cake\Validation\Validation::range() ### regex() public
```
regex(string $field, string $regex, string|null $message = null, callable|string|null $when = null): $this
```
Returns whether a field matches against a regular expression.
#### Parameters
`string` $field Field name.
`string` $regex Regular expression.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
### remove() public
```
remove(string $field, string|null $rule = null): $this
```
Removes a rule from the set by its name
### Example:
```
$validator
->remove('title', 'required')
->remove('user_id')
```
#### Parameters
`string` $field The name of the field from which the rule will be removed
`string|null` $rule optional the name of the rule to be removed
#### Returns
`$this`
### requirePresence() public
```
requirePresence(array|string $field, callable|string|bool $mode = true, string|null $message = null): $this
```
Sets whether a field is required to be present in data array. You can also pass array. Using an array will let you provide the following keys:
* `mode` individual mode for field
* `message` individual error message for field
You can also set mode and message for all passed fields, the individual setting takes precedence over group settings.
#### Parameters
`array|string` $field the name of the field or list of fields.
`callable|string|bool` $mode optional Valid values are true, false, 'create', 'update'. If a callable is passed then the field will be required only when the callback returns true.
`string|null` $message optional The message to show if the field presence validation fails.
#### Returns
`$this`
### sameAs() public
```
sameAs(string $field, string $secondField, string|null $message = null, callable|string|null $when = null): $this
```
Add a rule to compare two fields to each other.
If both fields have the exact same value the rule will pass.
#### Parameters
`string` $field The field you want to apply the rule to.
`string` $secondField The field you want to compare against.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::compareFields() ### scalar() public
```
scalar(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure that a field contains a scalar.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::isScalar() ### setProvider() public
```
setProvider(string $name, object|string $object): $this
```
Associates an object to a name so it can be used as a provider. Providers are objects or class names that can contain methods used during validation of for deciding whether a validation rule can be applied. All validation methods, when called will receive the full list of providers stored in this validator.
#### Parameters
`string` $name The name under which the provider should be set.
`object|string` $object Provider object or class name.
#### Returns
`$this`
### setStopOnFailure() public
```
setStopOnFailure(bool $stopOnFailure = true): $this
```
Whether to stop validation rule evaluation on the first failed rule.
When enabled the first failing rule per field will cause validation to stop. When disabled all rules will be run even if there are failures.
#### Parameters
`bool` $stopOnFailure optional If to apply last flag.
#### Returns
`$this`
### time() public
```
time(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a time format validation rule to a field.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::time() ### uploadedFile() public
```
uploadedFile(string $field, array<string, mixed> $options, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure the field is an uploaded file
#### Parameters
`string` $field The field you want to apply the rule to.
`array<string, mixed>` $options An array of options.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::uploadedFile() For options ### url() public
```
url(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure a field is a URL.
This validator does not require a protocol.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::url() ### urlWithProtocol() public
```
urlWithProtocol(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure a field is a URL.
This validator requires the URL to have a protocol.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::url() ### utf8() public
```
utf8(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure a field contains only BMP utf8 bytes
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::utf8() ### utf8Extended() public
```
utf8Extended(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure a field contains only utf8 bytes.
This rule will accept 3 and 4 byte UTF8 sequences, which are necessary for emoji.
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::utf8() ### uuid() public
```
uuid(string $field, string|null $message = null, callable|string|null $when = null): $this
```
Add a validation rule to ensure the field is a UUID
#### Parameters
`string` $field The field you want to apply the rule to.
`string|null` $message optional The error message when the rule fails.
`callable|string|null` $when optional Either 'create' or 'update' or a callable that returns true when the validation rule should be applied.
#### Returns
`$this`
#### See Also
\Cake\Validation\Validation::uuid() ### validate() public
```
validate(array $data, bool $newRecord = true): array<array>
```
Validates and returns an array of failed fields and their error messages.
#### Parameters
`array` $data The data to be checked for errors
`bool` $newRecord optional whether the data to be validated is new or to be updated.
#### Returns
`array<array>`
Property Detail
---------------
### $\_allowEmptyFlags protected
Contains the flags which specify what is empty for each corresponding field.
#### Type
`array<string, int>`
### $\_allowEmptyMessages protected
Contains the validation messages associated with checking the emptiness for each corresponding field.
#### Type
`array<string, string>`
### $\_defaultProviders protected static
An associative array of objects or classes used as a default provider list
#### Type
`array<string, object|string>`
### $\_fields protected
Holds the ValidationSet objects array
#### Type
`array<string,Cake\Validation\ValidationSet>`
### $\_presenceMessages protected
Contains the validation messages associated with checking the presence for each corresponding field.
#### Type
`array<string, string>`
### $\_providers protected
An associative array of objects or classes containing methods used for validation
#### Type
`array<string, object|string>`
### $\_stopOnFailure protected
Whether to apply last flag to generated rule(s).
#### Type
`bool`
### $\_useI18n protected
Whether to use I18n functions for translating default error messages
#### Type
`bool`
| programming_docs |
cakephp Namespace TestSuite Namespace TestSuite
===================
### Namespaces
* [Cake\Console\TestSuite\Constraint](namespace-cake.console.testsuite.constraint)
### Classes
* ##### [LegacyCommandRunner](class-cake.console.testsuite.legacycommandrunner)
Class that dispatches to the legacy ShellDispatcher using the same signature as the newer CommandRunner
* ##### [LegacyShellDispatcher](class-cake.console.testsuite.legacyshelldispatcher)
Allows injecting mock IO into shells
* ##### [MissingConsoleInputException](class-cake.console.testsuite.missingconsoleinputexception)
Exception class used to indicate missing console input.
* ##### [StubConsoleInput](class-cake.console.testsuite.stubconsoleinput)
Stub class used by the console integration harness.
* ##### [StubConsoleOutput](class-cake.console.testsuite.stubconsoleoutput)
StubOutput makes testing shell commands/shell helpers easier.
### Traits
* ##### [ConsoleIntegrationTestTrait](trait-cake.console.testsuite.consoleintegrationtesttrait)
A bundle of methods that makes testing commands and shell classes easier.
cakephp Class AbstractLocator Class AbstractLocator
======================
Provides an abstract registry/factory for repository objects.
**Abstract**
**Namespace:** [Cake\Datasource\Locator](namespace-cake.datasource.locator)
Property Summary
----------------
* [$instances](#%24instances) protected `array<string,Cake\Datasource\RepositoryInterface>` Instances that belong to the registry.
* [$options](#%24options) protected `array<string, array>` Contains a list of options that were passed to get() method.
Method Summary
--------------
* ##### [clear()](#clear()) public
Clears the registry of configuration and instances.
* ##### [createInstance()](#createInstance()) abstract protected
Create an instance of a given classname.
* ##### [exists()](#exists()) public
Check to see if an instance exists in the registry.
* ##### [get()](#get()) public
Get a repository instance from the registry.
* ##### [remove()](#remove()) public
Removes an repository instance from the registry.
* ##### [set()](#set()) public
Set a repository instance.
Method Detail
-------------
### clear() public
```
clear(): void
```
Clears the registry of configuration and instances.
#### Returns
`void`
### createInstance() abstract protected
```
createInstance(string $alias, array<string, mixed> $options): Cake\Datasource\RepositoryInterface
```
Create an instance of a given classname.
#### Parameters
`string` $alias Repository alias.
`array<string, mixed>` $options The options you want to build the instance with.
#### Returns
`Cake\Datasource\RepositoryInterface`
### exists() public
```
exists(string $alias): bool
```
Check to see if an instance exists in the registry.
#### Parameters
`string` $alias #### Returns
`bool`
### get() public
```
get(string $alias, array<string, mixed> $options = []): Cake\Datasource\RepositoryInterface
```
Get a repository instance from the registry.
#### Parameters
`string` $alias The alias name you want to get.
`array<string, mixed>` $options optional The options you want to build the table with.
#### Returns
`Cake\Datasource\RepositoryInterface`
#### Throws
`RuntimeException`
When trying to get alias for which instance has already been created with different options. ### remove() public
```
remove(string $alias): void
```
Removes an repository instance from the registry.
#### Parameters
`string` $alias #### Returns
`void`
### set() public
```
set(string $alias, Cake\Datasource\RepositoryInterface $repository): Cake\Datasource\RepositoryInterface
```
Set a repository instance.
#### Parameters
`string` $alias `Cake\Datasource\RepositoryInterface` $repository #### Returns
`Cake\Datasource\RepositoryInterface`
Property Detail
---------------
### $instances protected
Instances that belong to the registry.
#### Type
`array<string,Cake\Datasource\RepositoryInterface>`
### $options protected
Contains a list of options that were passed to get() method.
#### Type
`array<string, array>`
cakephp Interface NodeInterface Interface NodeInterface
========================
Interface for Debugs
Provides methods to look at contained value and iterate child nodes in the tree.
**Namespace:** [Cake\Error\Debug](namespace-cake.error.debug)
Method Summary
--------------
* ##### [getChildren()](#getChildren()) public
Get the child nodes of this node.
* ##### [getValue()](#getValue()) public
Get the contained value.
Method Detail
-------------
### getChildren() public
```
getChildren(): arrayCake\Error\Debug\NodeInterface>
```
Get the child nodes of this node.
#### Returns
`arrayCake\Error\Debug\NodeInterface>`
### getValue() public
```
getValue(): mixed
```
Get the contained value.
#### Returns
`mixed`
cakephp Class ContentsEmpty Class ContentsEmpty
====================
ContentsEmpty
**Namespace:** [Cake\Console\TestSuite\Constraint](namespace-cake.console.testsuite.constraint)
Property Summary
----------------
* [$contents](#%24contents) protected `string`
* [$output](#%24output) protected `string`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Overwrites the descriptions so we can remove the automatic "expected" message
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Checks if contents are empty
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string> $contents, string $output)
```
Constructor
#### Parameters
`array<string>` $contents Contents
`string` $output Output type
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Overwrites the descriptions so we can remove the automatic "expected" message
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other Value
#### Returns
`string`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks if contents are empty
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Expected
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $contents protected
#### Type
`string`
### $output protected
#### Type
`string`
cakephp Class EntityContext Class EntityContext
====================
Provides a form context around a single entity and its relations. It also can be used as context around an array or iterator of entities.
This class lets FormHelper interface with entities or collections of entities.
Important Keys:
* `entity` The entity this context is operating on.
* `table` Either the ORM\Table instance to fetch schema/validators from, an array of table instances in the case of a form spanning multiple entities, or the name(s) of the table. If this is null the table name(s) will be determined using naming conventions.
* `validator` Either the Validation\Validator to use, or the name of the validation method to call on the table object. For example 'default'. Defaults to 'default'. Can be an array of table alias=>validators when dealing with associated forms.
**Namespace:** [Cake\View\Form](namespace-cake.view.form)
Constants
---------
* `array<string>` **VALID\_ATTRIBUTES**
```
['length', 'precision', 'comment', 'null', 'default']
```
Property Summary
----------------
* [$\_context](#%24_context) protected `array<string, mixed>` Context data for this object.
* [$\_isCollection](#%24_isCollection) protected `bool` Boolean to track whether the entity is a collection.
* [$\_rootName](#%24_rootName) protected `string` The name of the top level entity/table object.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$\_tables](#%24_tables) protected `arrayCake\ORM\Table>` A dictionary of tables
* [$\_validator](#%24_validator) protected `arrayCake\Validation\Validator>` Dictionary of validators.
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_extractMultiple()](#_extractMultiple()) protected
Helper method used to extract all the primary key values out of an array, The primary key column is guessed out of the provided $path array
* ##### [\_getProp()](#_getProp()) protected
Read property values or traverse arrays/iterators.
* ##### [\_getTable()](#_getTable()) protected
Get the table instance from a property path
* ##### [\_getValidator()](#_getValidator()) protected
Get the validator associated to an entity based on naming conventions.
* ##### [\_prepare()](#_prepare()) protected
Prepare some additional data from the context.
* ##### [\_schemaDefault()](#_schemaDefault()) protected
Get default value from table schema for given entity field.
* ##### [attributes()](#attributes()) public
Get an associative array of other attributes for a field name.
* ##### [entity()](#entity()) public
Fetch the entity or data value for a given path
* ##### [error()](#error()) public
Get the errors for a given field
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [fieldNames()](#fieldNames()) public
Get the field names from the top level entity.
* ##### [getMaxLength()](#getMaxLength()) public
Get field length from validation
* ##### [getPrimaryKey()](#getPrimaryKey()) public
Get the primary key data for the context.
* ##### [getRequiredMessage()](#getRequiredMessage()) public
Gets the default "required" error message for a field
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [hasError()](#hasError()) public
Check whether a field has an error attached to it
* ##### [isCreate()](#isCreate()) public
Check whether this form is a create or update.
* ##### [isPrimaryKey()](#isPrimaryKey()) public
Returns true if the passed field name is part of the primary key for this context
* ##### [isRequired()](#isRequired()) public
Check if a field should be marked as required.
* ##### [leafEntity()](#leafEntity()) protected
Fetch the terminal or leaf entity for the given path.
* ##### [primaryKey()](#primaryKey()) public deprecated
Get the primary key data for the context.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
* ##### [type()](#type()) public
Get the abstract field type for a given field name.
* ##### [val()](#val()) public
Get the value for a given path.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $context)
```
Constructor.
#### Parameters
`array<string, mixed>` $context Context info.
### \_extractMultiple() protected
```
_extractMultiple(mixed $values, array<string> $path): array|null
```
Helper method used to extract all the primary key values out of an array, The primary key column is guessed out of the provided $path array
#### Parameters
`mixed` $values The list from which to extract primary keys from
`array<string>` $path Each one of the parts in a path for a field name
#### Returns
`array|null`
### \_getProp() protected
```
_getProp(mixed $target, string $field): mixed
```
Read property values or traverse arrays/iterators.
#### Parameters
`mixed` $target The entity/array/collection to fetch $field from.
`string` $field The next field to fetch.
#### Returns
`mixed`
### \_getTable() protected
```
_getTable(Cake\Datasource\EntityInterface|array<string>|string $parts, bool $fallback = true): Cake\ORM\Table|null
```
Get the table instance from a property path
#### Parameters
`Cake\Datasource\EntityInterface|array<string>|string` $parts Each one of the parts in a path for a field name
`bool` $fallback optional Whether to fallback to the last found table when a nonexistent field/property is being encountered.
#### Returns
`Cake\ORM\Table|null`
### \_getValidator() protected
```
_getValidator(array $parts): Cake\Validation\Validator
```
Get the validator associated to an entity based on naming conventions.
#### Parameters
`array` $parts Each one of the parts in a path for a field name
#### Returns
`Cake\Validation\Validator`
#### Throws
`RuntimeException`
If validator cannot be retrieved based on the parts. ### \_prepare() protected
```
_prepare(): void
```
Prepare some additional data from the context.
If the table option was provided to the constructor and it was a string, TableLocator will be used to get the correct table instance.
If an object is provided as the table option, it will be used as is.
If no table option is provided, the table name will be derived based on naming conventions. This inference will work with a number of common objects like arrays, Collection objects and ResultSets.
#### Returns
`void`
#### Throws
`RuntimeException`
When a table object cannot be located/inferred. ### \_schemaDefault() protected
```
_schemaDefault(array<string> $parts): mixed
```
Get default value from table schema for given entity field.
#### Parameters
`array<string>` $parts Each one of the parts in a path for a field name
#### Returns
`mixed`
### attributes() public
```
attributes(string $field): array
```
Get an associative array of other attributes for a field name.
#### Parameters
`string` $field A dot separated path to get additional data on.
#### Returns
`array`
### entity() public
```
entity(array|null $path = null): Cake\Datasource\EntityInterface|iterable|null
```
Fetch the entity or data value for a given path
This method will traverse the given path and find the entity or array value for a given path.
If you only want the terminal Entity for a path use `leafEntity` instead.
#### Parameters
`array|null` $path optional Each one of the parts in a path for a field name or null to get the entity passed in constructor context.
#### Returns
`Cake\Datasource\EntityInterface|iterable|null`
#### Throws
`RuntimeException`
When properties cannot be read. ### error() public
```
error(string $field): array
```
Get the errors for a given field
#### Parameters
`string` $field A dot separated path to check errors on.
#### Returns
`array`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### fieldNames() public
```
fieldNames(): array<string>
```
Get the field names from the top level entity.
If the context is for an array of entities, the 0th index will be used.
#### Returns
`array<string>`
### getMaxLength() public
```
getMaxLength(string $field): int|null
```
Get field length from validation
#### Parameters
`string` $field The dot separated path to the field you want to check.
#### Returns
`int|null`
### getPrimaryKey() public
```
getPrimaryKey(): array<string>
```
Get the primary key data for the context.
Gets the primary key columns from the root entity's schema.
#### Returns
`array<string>`
### getRequiredMessage() public
```
getRequiredMessage(string $field): string|null
```
Gets the default "required" error message for a field
#### Parameters
`string` $field #### Returns
`string|null`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### hasError() public
```
hasError(string $field): bool
```
Check whether a field has an error attached to it
#### Parameters
`string` $field A dot separated path to check errors on.
#### Returns
`bool`
### isCreate() public
```
isCreate(): bool
```
Check whether this form is a create or update.
If the context is for a single entity, the entity's isNew() method will be used. If isNew() returns null, a create operation will be assumed.
If the context is for a collection or array the first object in the collection will be used.
#### Returns
`bool`
### isPrimaryKey() public
```
isPrimaryKey(string $field): bool
```
Returns true if the passed field name is part of the primary key for this context
#### Parameters
`string` $field #### Returns
`bool`
### isRequired() public
```
isRequired(string $field): bool|null
```
Check if a field should be marked as required.
In this context class, this is simply defined by the 'required' array.
#### Parameters
`string` $field The dot separated path to the field you want to check.
#### Returns
`bool|null`
### leafEntity() protected
```
leafEntity(array|null $path = null): array
```
Fetch the terminal or leaf entity for the given path.
Traverse the path until an entity cannot be found. Lists containing entities will be traversed if the first element contains an entity. Otherwise, the containing Entity will be assumed to be the terminal one.
#### Parameters
`array|null` $path optional Each one of the parts in a path for a field name or null to get the entity passed in constructor context.
#### Returns
`array`
#### Throws
`RuntimeException`
When properties cannot be read. ### primaryKey() public
```
primaryKey(): array<string>
```
Get the primary key data for the context.
Gets the primary key columns from the root entity's schema.
#### Returns
`array<string>`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
### type() public
```
type(string $field): string|null
```
Get the abstract field type for a given field name.
#### Parameters
`string` $field A dot separated path to get a schema type for.
#### Returns
`string|null`
#### See Also
\Cake\Database\TypeFactory ### val() public
```
val(string $field, array<string, mixed> $options = []): mixed
```
Get the value for a given path.
Traverses the entity data and finds the value for $path.
#### Parameters
`string` $field The dot separated path to the value.
`array<string, mixed>` $options optional Options:
#### Returns
`mixed`
Property Detail
---------------
### $\_context protected
Context data for this object.
#### Type
`array<string, mixed>`
### $\_isCollection protected
Boolean to track whether the entity is a collection.
#### Type
`bool`
### $\_rootName protected
The name of the top level entity/table object.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $\_tables protected
A dictionary of tables
#### Type
`arrayCake\ORM\Table>`
### $\_validator protected
Dictionary of validators.
#### Type
`arrayCake\Validation\Validator>`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
| programming_docs |
cakephp Class I18nCommand Class I18nCommand
==================
Command for interactive I18N management.
**Namespace:** [Cake\Command](namespace-cake.command)
Constants
---------
* `int` **CODE\_ERROR**
```
1
```
Default error code
* `int` **CODE\_SUCCESS**
```
0
```
Default success code
Property Summary
----------------
* [$\_modelFactories](#%24_modelFactories) protected `array<callableCake\Datasource\Locator\LocatorInterface>` A list of overridden model factory functions.
* [$\_modelType](#%24_modelType) protected `string` The model type to use.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
* [$modelClass](#%24modelClass) protected deprecated `string|null` This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
* [$name](#%24name) protected `string` The name of this command.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_setModelClass()](#_setModelClass()) protected
Set the modelClass property based on conventions.
* ##### [abort()](#abort()) public
Halt the the current process with a StopException.
* ##### [buildOptionParser()](#buildOptionParser()) public
Gets the option parser instance and configures it.
* ##### [defaultName()](#defaultName()) public static
Get the command name.
* ##### [displayHelp()](#displayHelp()) protected
Output help content
* ##### [execute()](#execute()) public
Execute interactive mode
* ##### [executeCommand()](#executeCommand()) public
Execute another command with the provided set of arguments.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getDescription()](#getDescription()) public static
Get the command description.
* ##### [getModelType()](#getModelType()) public
Get the model type to be used by this class
* ##### [getName()](#getName()) public
Get the command name.
* ##### [getOptionParser()](#getOptionParser()) public
Get the option parser.
* ##### [getRootName()](#getRootName()) public
Get the root command name.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [initialize()](#initialize()) public
Hook method invoked by CakePHP when a command is about to be executed.
* ##### [loadModel()](#loadModel()) public deprecated
Loads and constructs repository objects required by this object
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [modelFactory()](#modelFactory()) public
Override a existing callable to generate repositories of a given type.
* ##### [run()](#run()) public
Run the command.
* ##### [setModelType()](#setModelType()) public
Set the model type to be used by this class
* ##### [setName()](#setName()) public
Set the name this command uses in the collection.
* ##### [setOutputLevel()](#setOutputLevel()) protected
Set the output level based on the Arguments.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
Method Detail
-------------
### \_\_construct() public
```
__construct()
```
Constructor
By default CakePHP will construct command objects when building the CommandCollection for your application.
### \_setModelClass() protected
```
_setModelClass(string $name): void
```
Set the modelClass property based on conventions.
If the property is already set it will not be overwritten
#### Parameters
`string` $name Class name.
#### Returns
`void`
### abort() public
```
abort(int $code = self::CODE_ERROR): void
```
Halt the the current process with a StopException.
#### Parameters
`int` $code optional The exit code to use.
#### Returns
`void`
#### Throws
`Cake\Console\Exception\StopException`
### buildOptionParser() public
```
buildOptionParser(Cake\Console\ConsoleOptionParser $parser): Cake\Console\ConsoleOptionParser
```
Gets the option parser instance and configures it.
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The parser to update
#### Returns
`Cake\Console\ConsoleOptionParser`
### defaultName() public static
```
defaultName(): string
```
Get the command name.
Returns the command name based on class name. For e.g. for a command with class name `UpdateTableCommand` the default name returned would be `'update_table'`.
#### Returns
`string`
### displayHelp() protected
```
displayHelp(Cake\Console\ConsoleOptionParser $parser, Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Output help content
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser.
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### execute() public
```
execute(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): int|null
```
Execute interactive mode
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`int|null`
### executeCommand() public
```
executeCommand(Cake\Console\CommandInterface|string $command, array $args = [], Cake\Console\ConsoleIo|null $io = null): int|null
```
Execute another command with the provided set of arguments.
If you are using a string command name, that command's dependencies will not be resolved with the application container. Instead you will need to pass the command as an object with all of its dependencies.
#### Parameters
`Cake\Console\CommandInterface|string` $command The command class name or command instance.
`array` $args optional The arguments to invoke the command with.
`Cake\Console\ConsoleIo|null` $io optional The ConsoleIo instance to use for the executed command.
#### Returns
`int|null`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getDescription() public static
```
getDescription(): string
```
Get the command description.
#### Returns
`string`
### getModelType() public
```
getModelType(): string
```
Get the model type to be used by this class
#### Returns
`string`
### getName() public
```
getName(): string
```
Get the command name.
#### Returns
`string`
### getOptionParser() public
```
getOptionParser(): Cake\Console\ConsoleOptionParser
```
Get the option parser.
You can override buildOptionParser() to define your options & arguments.
#### Returns
`Cake\Console\ConsoleOptionParser`
#### Throws
`RuntimeException`
When the parser is invalid ### getRootName() public
```
getRootName(): string
```
Get the root command name.
#### Returns
`string`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### initialize() public
```
initialize(): void
```
Hook method invoked by CakePHP when a command is about to be executed.
Override this method and implement expensive/important setup steps that should not run on every command run. This method will be called *before* the options and arguments are validated and processed.
#### Returns
`void`
### loadModel() public
```
loadModel(string|null $modelClass = null, string|null $modelType = null): Cake\Datasource\RepositoryInterface
```
Loads and constructs repository objects required by this object
Typically used to load ORM Table objects as required. Can also be used to load other types of repository objects your application uses.
If a repository provider does not return an object a MissingModelException will be thrown.
#### Parameters
`string|null` $modelClass optional Name of model class to load. Defaults to $this->modelClass. The name can be an alias like `'Post'` or FQCN like `App\Model\Table\PostsTable::class`.
`string|null` $modelType optional The type of repository to load. Defaults to the getModelType() value.
#### Returns
`Cake\Datasource\RepositoryInterface`
#### Throws
`Cake\Datasource\Exception\MissingModelException`
If the model class cannot be found.
`UnexpectedValueException`
If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty. ### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### modelFactory() public
```
modelFactory(string $type, Cake\Datasource\Locator\LocatorInterface|callable $factory): void
```
Override a existing callable to generate repositories of a given type.
#### Parameters
`string` $type The name of the repository type the factory function is for.
`Cake\Datasource\Locator\LocatorInterface|callable` $factory The factory function used to create instances.
#### Returns
`void`
### run() public
```
run(array $argv, Cake\Console\ConsoleIo $io): int|null
```
Run the command.
#### Parameters
`array` $argv `Cake\Console\ConsoleIo` $io #### Returns
`int|null`
### setModelType() public
```
setModelType(string $modelType): $this
```
Set the model type to be used by this class
#### Parameters
`string` $modelType The model type
#### Returns
`$this`
### setName() public
```
setName(string $name): $this
```
Set the name this command uses in the collection.
Generally invoked by the CommandCollection when the command is added. Required to have at least one space in the name so that the root command can be calculated.
#### Parameters
`string` $name #### Returns
`$this`
### setOutputLevel() protected
```
setOutputLevel(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Set the output level based on the Arguments.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
Property Detail
---------------
### $\_modelFactories protected
A list of overridden model factory functions.
#### Type
`array<callableCake\Datasource\Locator\LocatorInterface>`
### $\_modelType protected
The model type to use.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
### $modelClass protected deprecated
This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
Example: For an object named 'Comments', the modelClass would be 'Comments'. Plugin classes should use `Plugin.Comments` style names to correctly load models from the correct plugin.
Use empty string to not use auto-loading on this object. Null auto-detects based on controller name.
#### Type
`string|null`
### $name protected
The name of this command.
#### Type
`string`
cakephp Class BaseLog Class BaseLog
==============
Base log engine class.
**Abstract**
**Namespace:** [Cake\Log\Engine](namespace-cake.log.engine)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this class
* [$formatter](#%24formatter) protected `Cake\Log\Formatter\AbstractFormatter`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
\_\_construct method
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_format()](#_format()) protected deprecated
Formats the message to be logged.
* ##### [alert()](#alert()) public
Action must be taken immediately.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [critical()](#critical()) public
Critical conditions.
* ##### [debug()](#debug()) public
Detailed debug information.
* ##### [emergency()](#emergency()) public
System is unusable.
* ##### [error()](#error()) public
Runtime errors that do not require immediate action but should typically be logged and monitored.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [info()](#info()) public
Interesting events.
* ##### [interpolate()](#interpolate()) protected
Replaces placeholders in message string with context values.
* ##### [levels()](#levels()) public
Get the levels this logger is interested in.
* ##### [log()](#log()) public
Logs with an arbitrary level.
* ##### [notice()](#notice()) public
Normal but significant events.
* ##### [scopes()](#scopes()) public
Get the scopes this logger is interested in.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [warning()](#warning()) public
Exceptional occurrences that are not errors.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
\_\_construct method
#### Parameters
`array<string, mixed>` $config optional Configuration array
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_format() protected
```
_format(string $message, array $context = []): string
```
Formats the message to be logged.
The context can optionally be used by log engines to interpolate variables or add additional info to the logged message.
#### Parameters
`string` $message The message to be formatted.
`array` $context optional Additional logging information for the message.
#### Returns
`string`
### alert() public
```
alert(string $message, mixed[] $context = array()): void
```
Action must be taken immediately.
Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### critical() public
```
critical(string $message, mixed[] $context = array()): void
```
Critical conditions.
Example: Application component unavailable, unexpected exception.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### debug() public
```
debug(string $message, mixed[] $context = array()): void
```
Detailed debug information.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### emergency() public
```
emergency(string $message, mixed[] $context = array()): void
```
System is unusable.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### error() public
```
error(string $message, mixed[] $context = array()): void
```
Runtime errors that do not require immediate action but should typically be logged and monitored.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### info() public
```
info(string $message, mixed[] $context = array()): void
```
Interesting events.
Example: User logs in, SQL logs.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### interpolate() protected
```
interpolate(string $message, array $context = []): string
```
Replaces placeholders in message string with context values.
#### Parameters
`string` $message Formatted string
`array` $context optional Context for placeholder values.
#### Returns
`string`
### levels() public
```
levels(): array<string>
```
Get the levels this logger is interested in.
#### Returns
`array<string>`
### log() public
```
log(mixed $level, string $message, mixed[] $context = array()): void
```
Logs with an arbitrary level.
#### Parameters
`mixed` $level `string` $message `mixed[]` $context optional #### Returns
`void`
#### Throws
`Psr\Log\InvalidArgumentException`
### notice() public
```
notice(string $message, mixed[] $context = array()): void
```
Normal but significant events.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### scopes() public
```
scopes(): array<string>|false
```
Get the scopes this logger is interested in.
#### Returns
`array<string>|false`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### warning() public
```
warning(string $message, mixed[] $context = array()): void
```
Exceptional occurrences that are not errors.
Example: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this class
#### Type
`array<string, mixed>`
### $formatter protected
#### Type
`Cake\Log\Formatter\AbstractFormatter`
| programming_docs |
cakephp Namespace Parser Namespace Parser
================
### Classes
* ##### [MoFileParser](class-cake.i18n.parser.mofileparser)
Parses file in MO format
* ##### [PoFileParser](class-cake.i18n.parser.pofileparser)
Parses file in PO format
cakephp Namespace Locator Namespace Locator
=================
### Interfaces
* ##### [LocatorInterface](interface-cake.orm.locator.locatorinterface)
Registries for Table objects should implement this interface.
### Classes
* ##### [TableLocator](class-cake.orm.locator.tablelocator)
Provides a default registry/factory for Table objects.
### Traits
* ##### [LocatorAwareTrait](trait-cake.orm.locator.locatorawaretrait)
Contains method for setting and accessing LocatorInterface instance
cakephp Interface TableSchemaInterface Interface TableSchemaInterface
===============================
An interface used by database TableSchema objects.
**Namespace:** [Cake\Database\Schema](namespace-cake.database.schema)
Constants
---------
* `string` **TYPE\_BIGINTEGER**
```
'biginteger'
```
Big Integer column type
* `string` **TYPE\_BINARY**
```
'binary'
```
Binary column type
* `string` **TYPE\_BINARY\_UUID**
```
'binaryuuid'
```
Binary UUID column type
* `string` **TYPE\_BOOLEAN**
```
'boolean'
```
Boolean column type
* `string` **TYPE\_CHAR**
```
'char'
```
Char column type
* `string` **TYPE\_DATE**
```
'date'
```
Date column type
* `string` **TYPE\_DATETIME**
```
'datetime'
```
Datetime column type
* `string` **TYPE\_DATETIME\_FRACTIONAL**
```
'datetimefractional'
```
Datetime with fractional seconds column type
* `string` **TYPE\_DECIMAL**
```
'decimal'
```
Decimal column type
* `string` **TYPE\_FLOAT**
```
'float'
```
Float column type
* `string` **TYPE\_INTEGER**
```
'integer'
```
Integer column type
* `string` **TYPE\_JSON**
```
'json'
```
JSON column type
* `string` **TYPE\_SMALLINTEGER**
```
'smallinteger'
```
Small Integer column type
* `string` **TYPE\_STRING**
```
'string'
```
String column type
* `string` **TYPE\_TEXT**
```
'text'
```
Text column type
* `string` **TYPE\_TIME**
```
'time'
```
Time column type
* `string` **TYPE\_TIMESTAMP**
```
'timestamp'
```
Timestamp column type
* `string` **TYPE\_TIMESTAMP\_FRACTIONAL**
```
'timestampfractional'
```
Timestamp with fractional seconds column type
* `string` **TYPE\_TIMESTAMP\_TIMEZONE**
```
'timestamptimezone'
```
Timestamp with time zone column type
* `string` **TYPE\_TINYINTEGER**
```
'tinyinteger'
```
Tiny Integer column type
* `string` **TYPE\_UUID**
```
'uuid'
```
UUID column type
Method Summary
--------------
* ##### [addColumn()](#addColumn()) public
Add a column to the table.
* ##### [addConstraint()](#addConstraint()) public
Add a constraint.
* ##### [addIndex()](#addIndex()) public
Add an index.
* ##### [baseColumnType()](#baseColumnType()) public
Returns the base type name for the provided column. This represent the database type a more complex class is based upon.
* ##### [columns()](#columns()) public
Get the column names in the table.
* ##### [constraints()](#constraints()) public
Get the names of all the constraints in the table.
* ##### [defaultValues()](#defaultValues()) public
Get a hash of columns and their default values.
* ##### [dropConstraint()](#dropConstraint()) public
Remove a constraint.
* ##### [getColumn()](#getColumn()) public
Get column data in the table.
* ##### [getColumnType()](#getColumnType()) public
Returns column type or null if a column does not exist.
* ##### [getConstraint()](#getConstraint()) public
Read information about a constraint based on name.
* ##### [getIndex()](#getIndex()) public
Read information about an index based on name.
* ##### [getOptions()](#getOptions()) public
Gets the options for a table.
* ##### [getPrimaryKey()](#getPrimaryKey()) public
Get the column(s) used for the primary key.
* ##### [hasAutoincrement()](#hasAutoincrement()) public
Check whether a table has an autoIncrement column defined.
* ##### [hasColumn()](#hasColumn()) public
Returns true if a column exists in the schema.
* ##### [indexes()](#indexes()) public
Get the names of all the indexes in the table.
* ##### [isNullable()](#isNullable()) public
Check whether a field is nullable
* ##### [isTemporary()](#isTemporary()) public
Gets whether the table is temporary in the database.
* ##### [name()](#name()) public
Get the name of the table.
* ##### [removeColumn()](#removeColumn()) public
Remove a column from the table schema.
* ##### [setColumnType()](#setColumnType()) public
Sets the type of a column.
* ##### [setOptions()](#setOptions()) public
Sets the options for a table.
* ##### [setTemporary()](#setTemporary()) public
Sets whether the table is temporary in the database.
* ##### [typeMap()](#typeMap()) public
Returns an array where the keys are the column names in the schema and the values the database type they have.
Method Detail
-------------
### addColumn() public
```
addColumn(string $name, array<string, mixed>|string $attrs): $this
```
Add a column to the table.
### Attributes
Columns can have several attributes:
* `type` The type of the column. This should be one of CakePHP's abstract types.
* `length` The length of the column.
* `precision` The number of decimal places to store for float and decimal types.
* `default` The default value of the column.
* `null` Whether the column can hold nulls.
* `fixed` Whether the column is a fixed length column. This is only present/valid with string columns.
* `unsigned` Whether the column is an unsigned column. This is only present/valid for integer, decimal, float columns.
In addition to the above keys, the following keys are implemented in some database dialects, but not all:
* `comment` The comment for the column.
#### Parameters
`string` $name The name of the column
`array<string, mixed>|string` $attrs The attributes for the column or the type name.
#### Returns
`$this`
### addConstraint() public
```
addConstraint(string $name, array<string, mixed>|string $attrs): $this
```
Add a constraint.
Used to add constraints to a table. For example primary keys, unique keys and foreign keys.
### Attributes
* `type` The type of constraint being added.
* `columns` The columns in the index.
* `references` The table, column a foreign key references.
* `update` The behavior on update. Options are 'restrict', 'setNull', 'cascade', 'noAction'.
* `delete` The behavior on delete. Options are 'restrict', 'setNull', 'cascade', 'noAction'.
The default for 'update' & 'delete' is 'cascade'.
#### Parameters
`string` $name The name of the constraint.
`array<string, mixed>|string` $attrs The attributes for the constraint. If string it will be used as `type`.
#### Returns
`$this`
#### Throws
`Cake\Database\Exception\DatabaseException`
### addIndex() public
```
addIndex(string $name, array<string, mixed>|string $attrs): $this
```
Add an index.
Used to add indexes, and full text indexes in platforms that support them.
### Attributes
* `type` The type of index being added.
* `columns` The columns in the index.
#### Parameters
`string` $name The name of the index.
`array<string, mixed>|string` $attrs The attributes for the index. If string it will be used as `type`.
#### Returns
`$this`
#### Throws
`Cake\Database\Exception\DatabaseException`
### baseColumnType() public
```
baseColumnType(string $column): string|null
```
Returns the base type name for the provided column. This represent the database type a more complex class is based upon.
#### Parameters
`string` $column The column name to get the base type from
#### Returns
`string|null`
### columns() public
```
columns(): array<string>
```
Get the column names in the table.
#### Returns
`array<string>`
### constraints() public
```
constraints(): array<string>
```
Get the names of all the constraints in the table.
#### Returns
`array<string>`
### defaultValues() public
```
defaultValues(): array<string, mixed>
```
Get a hash of columns and their default values.
#### Returns
`array<string, mixed>`
### dropConstraint() public
```
dropConstraint(string $name): $this
```
Remove a constraint.
#### Parameters
`string` $name Name of the constraint to remove
#### Returns
`$this`
### getColumn() public
```
getColumn(string $name): array<string, mixed>|null
```
Get column data in the table.
#### Parameters
`string` $name The column name.
#### Returns
`array<string, mixed>|null`
### getColumnType() public
```
getColumnType(string $name): string|null
```
Returns column type or null if a column does not exist.
#### Parameters
`string` $name The column to get the type of.
#### Returns
`string|null`
### getConstraint() public
```
getConstraint(string $name): array<string, mixed>|null
```
Read information about a constraint based on name.
#### Parameters
`string` $name The name of the constraint.
#### Returns
`array<string, mixed>|null`
### getIndex() public
```
getIndex(string $name): array<string, mixed>|null
```
Read information about an index based on name.
#### Parameters
`string` $name The name of the index.
#### Returns
`array<string, mixed>|null`
### getOptions() public
```
getOptions(): array<string, mixed>
```
Gets the options for a table.
Table options allow you to set platform specific table level options. For example the engine type in MySQL.
#### Returns
`array<string, mixed>`
### getPrimaryKey() public
```
getPrimaryKey(): array<string>
```
Get the column(s) used for the primary key.
#### Returns
`array<string>`
### hasAutoincrement() public
```
hasAutoincrement(): bool
```
Check whether a table has an autoIncrement column defined.
#### Returns
`bool`
### hasColumn() public
```
hasColumn(string $name): bool
```
Returns true if a column exists in the schema.
#### Parameters
`string` $name Column name.
#### Returns
`bool`
### indexes() public
```
indexes(): array<string>
```
Get the names of all the indexes in the table.
#### Returns
`array<string>`
### isNullable() public
```
isNullable(string $name): bool
```
Check whether a field is nullable
Missing columns are nullable.
#### Parameters
`string` $name The column to get the type of.
#### Returns
`bool`
### isTemporary() public
```
isTemporary(): bool
```
Gets whether the table is temporary in the database.
#### Returns
`bool`
### name() public
```
name(): string
```
Get the name of the table.
#### Returns
`string`
### removeColumn() public
```
removeColumn(string $name): $this
```
Remove a column from the table schema.
If the column is not defined in the table, no error will be raised.
#### Parameters
`string` $name The name of the column
#### Returns
`$this`
### setColumnType() public
```
setColumnType(string $name, string $type): $this
```
Sets the type of a column.
#### Parameters
`string` $name The column to set the type of.
`string` $type The type to set the column to.
#### Returns
`$this`
### setOptions() public
```
setOptions(array<string, mixed> $options): $this
```
Sets the options for a table.
Table options allow you to set platform specific table level options. For example the engine type in MySQL.
#### Parameters
`array<string, mixed>` $options The options to set, or null to read options.
#### Returns
`$this`
### setTemporary() public
```
setTemporary(bool $temporary): $this
```
Sets whether the table is temporary in the database.
#### Parameters
`bool` $temporary Whether the table is to be temporary.
#### Returns
`$this`
### typeMap() public
```
typeMap(): array<string, string>
```
Returns an array where the keys are the column names in the schema and the values the database type they have.
#### Returns
`array<string, string>`
cakephp Class BodyParserMiddleware Class BodyParserMiddleware
===========================
Parse encoded request body data.
Enables JSON and XML request payloads to be parsed into the request's body. You can also add your own request body parsers using the `addParser()` method.
**Namespace:** [Cake\Http\Middleware](namespace-cake.http.middleware)
Property Summary
----------------
* [$methods](#%24methods) protected `array<string>` The HTTP methods to parse data on.
* [$parsers](#%24parsers) protected `arrayClosure>` Registered Parsers
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [addParser()](#addParser()) public
Add a parser.
* ##### [decodeJson()](#decodeJson()) protected
Decode JSON into an array.
* ##### [decodeXml()](#decodeXml()) protected
Decode XML into an array.
* ##### [getMethods()](#getMethods()) public
Get the HTTP methods to parse request bodies on.
* ##### [getParsers()](#getParsers()) public
Get the current parsers
* ##### [process()](#process()) public
Apply the middleware.
* ##### [setMethods()](#setMethods()) public
Set the HTTP methods to parse request bodies on.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $options = [])
```
Constructor
### Options
* `json` Set to false to disable JSON body parsing.
* `xml` Set to true to enable XML parsing. Defaults to false, as XML handling requires more care than JSON does.
* `methods` The HTTP methods to parse on. Defaults to PUT, POST, PATCH DELETE.
#### Parameters
`array<string, mixed>` $options optional The options to use. See above.
### addParser() public
```
addParser(array<string> $types, Closure $parser): $this
```
Add a parser.
Map a set of content-type header values to be parsed by the $parser.
### Example
An naive CSV request body parser could be built like so:
```
$parser->addParser(['text/csv'], function ($body) {
return str_getcsv($body);
});
```
#### Parameters
`array<string>` $types An array of content-type header values to match. eg. application/json
`Closure` $parser The parser function. Must return an array of data to be inserted into the request.
#### Returns
`$this`
### decodeJson() protected
```
decodeJson(string $body): array|null
```
Decode JSON into an array.
#### Parameters
`string` $body The request body to decode
#### Returns
`array|null`
### decodeXml() protected
```
decodeXml(string $body): array
```
Decode XML into an array.
#### Parameters
`string` $body The request body to decode
#### Returns
`array`
### getMethods() public
```
getMethods(): array<string>
```
Get the HTTP methods to parse request bodies on.
#### Returns
`array<string>`
### getParsers() public
```
getParsers(): arrayClosure>
```
Get the current parsers
#### Returns
`arrayClosure>`
### process() public
```
process(ServerRequestInterface $request, RequestHandlerInterface $handler): Psr\Http\Message\ResponseInterface
```
Apply the middleware.
Will modify the request adding a parsed body if the content-type is known.
#### Parameters
`ServerRequestInterface` $request The request.
`RequestHandlerInterface` $handler The request handler.
#### Returns
`Psr\Http\Message\ResponseInterface`
### setMethods() public
```
setMethods(array<string> $methods): $this
```
Set the HTTP methods to parse request bodies on.
#### Parameters
`array<string>` $methods The methods to parse data on.
#### Returns
`$this`
Property Detail
---------------
### $methods protected
The HTTP methods to parse data on.
#### Type
`array<string>`
### $parsers protected
Registered Parsers
#### Type
`arrayClosure>`
cakephp Trait EventDispatcherTrait Trait EventDispatcherTrait
===========================
Implements Cake\Event\EventDispatcherInterface.
**Namespace:** [Cake\Event](namespace-cake.event)
Property Summary
----------------
* [$\_eventClass](#%24_eventClass) protected `string` Default class name for new event objects.
* [$\_eventManager](#%24_eventManager) protected `Cake\Event\EventManagerInterface|null` Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
Method Summary
--------------
* ##### [dispatchEvent()](#dispatchEvent()) public
Wrapper for creating and dispatching events.
* ##### [getEventManager()](#getEventManager()) public
Returns the Cake\Event\EventManager manager instance for this object.
* ##### [setEventManager()](#setEventManager()) public
Returns the Cake\Event\EventManagerInterface instance for this object.
Method Detail
-------------
### dispatchEvent() public
```
dispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\EventInterface
```
Wrapper for creating and dispatching events.
Returns a dispatched event.
#### Parameters
`string` $name Name of the event.
`array|null` $data optional Any value you wish to be transported with this event to it can be read by listeners.
`object|null` $subject optional The object that this event applies to ($this by default).
#### Returns
`Cake\Event\EventInterface`
### getEventManager() public
```
getEventManager(): Cake\Event\EventManagerInterface
```
Returns the Cake\Event\EventManager manager 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.
#### Returns
`Cake\Event\EventManagerInterface`
### setEventManager() public
```
setEventManager(Cake\Event\EventManagerInterface $eventManager): $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.
#### Parameters
`Cake\Event\EventManagerInterface` $eventManager the eventManager to set
#### Returns
`$this`
Property Detail
---------------
### $\_eventClass protected
Default class name for new event objects.
#### Type
`string`
### $\_eventManager protected
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
#### Type
`Cake\Event\EventManagerInterface|null`
cakephp Class CacheEngine Class CacheEngine
==================
Storage engine for CakePHP caching
**Abstract**
**Namespace:** [Cake\Cache](namespace-cake.cache)
Constants
---------
* `string` **CHECK\_KEY**
```
'key'
```
* `string` **CHECK\_VALUE**
```
'value'
```
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` The default cache configuration is overridden in most cache adapters. These are the keys that are common to all adapters. If overridden, this property is not used.
* [$\_groupPrefix](#%24_groupPrefix) protected `string` Contains the compiled string with all group prefixes to be prepended to every key in this cache engine
Method Summary
--------------
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_key()](#_key()) protected
Generates a key for cache backend usage.
* ##### [add()](#add()) public
Add a key to the cache if it does not already exist.
* ##### [clear()](#clear()) abstract public
Delete all keys from the cache
* ##### [clearGroup()](#clearGroup()) abstract public
Clears all values belonging to a group. Is up to the implementing engine to decide whether actually delete the keys or just simulate it to achieve the same result.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [decrement()](#decrement()) abstract public
Decrement a number under the key and return decremented value
* ##### [delete()](#delete()) abstract public
Delete a key from the cache
* ##### [deleteMultiple()](#deleteMultiple()) public
Deletes multiple cache items as a list
* ##### [duration()](#duration()) protected
Convert the various expressions of a TTL value into duration in seconds
* ##### [ensureValidKey()](#ensureValidKey()) protected
Ensure the validity of the given cache key.
* ##### [ensureValidType()](#ensureValidType()) protected
Ensure the validity of the argument type and cache keys.
* ##### [get()](#get()) abstract public
Fetches the value for a given key from the cache.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getMultiple()](#getMultiple()) public
Obtains multiple cache items by their unique keys.
* ##### [groups()](#groups()) public
Does whatever initialization for each group is required and returns the `group value` for each of them, this is the token representing each group in the cache key
* ##### [has()](#has()) public
Determines whether an item is present in the cache.
* ##### [increment()](#increment()) abstract public
Increment a number under the key and return incremented value
* ##### [init()](#init()) public
Initialize the cache engine
* ##### [set()](#set()) abstract public
Persists data in the cache, uniquely referenced by the given key with an optional expiration TTL time.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setMultiple()](#setMultiple()) public
Persists a set of key => value pairs in the cache, with an optional TTL.
* ##### [warning()](#warning()) protected
Cache Engines may trigger warnings if they encounter failures during operation, if option warnOnWriteFailures is set to true.
Method Detail
-------------
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_key() protected
```
_key(string $key): string
```
Generates a key for cache backend usage.
If the requested key is valid, the group prefix value and engine prefix are applied. Whitespace in keys will be replaced.
#### Parameters
`string` $key the key passed over
#### Returns
`string`
#### Throws
`Cake\Cache\InvalidArgumentException`
If key's value is invalid. ### add() public
```
add(string $key, mixed $value): bool
```
Add a key to the cache if it does not already exist.
Defaults to a non-atomic implementation. Subclasses should prefer atomic implementations.
#### Parameters
`string` $key Identifier for the data.
`mixed` $value Data to be cached.
#### Returns
`bool`
### clear() abstract public
```
clear(): bool
```
Delete all keys from the cache
#### Returns
`bool`
### clearGroup() abstract public
```
clearGroup(string $group): bool
```
Clears all values belonging to a group. Is up to the implementing engine to decide whether actually delete the keys or just simulate it to achieve the same result.
Each implementation needs to decide whether actually delete the keys or just augment a group generation value to achieve the same result.
#### Parameters
`string` $group name of the group to be cleared
#### Returns
`bool`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### decrement() abstract public
```
decrement(string $key, int $offset = 1): int|false
```
Decrement a number under the key and return decremented value
#### Parameters
`string` $key Identifier for the data
`int` $offset optional How much to subtract
#### Returns
`int|false`
### delete() abstract public
```
delete(string $key): bool
```
Delete a key from the cache
#### Parameters
`string` $key Identifier for the data
#### Returns
`bool`
### deleteMultiple() public
```
deleteMultiple(iterable $keys): bool
```
Deletes multiple cache items as a list
This is a best effort attempt. If deleting an item would create an error it will be ignored, and all items will be attempted.
#### Parameters
`iterable` $keys A list of string-based keys to be deleted.
#### Returns
`bool`
#### Throws
`Cake\Cache\InvalidArgumentException`
If $keys is neither an array nor a Traversable, or if any of the $keys are not a legal value. ### duration() protected
```
duration(DateInterval|int|null $ttl): int
```
Convert the various expressions of a TTL value into duration in seconds
#### Parameters
`DateInterval|int|null` $ttl The TTL value of this item. If null is sent, the driver's default duration will be used.
#### Returns
`int`
### ensureValidKey() protected
```
ensureValidKey(string $key): void
```
Ensure the validity of the given cache key.
#### Parameters
`string` $key Key to check.
#### Returns
`void`
#### Throws
`Cake\Cache\InvalidArgumentException`
When the key is not valid. ### ensureValidType() protected
```
ensureValidType(iterable $iterable, string $check = self::CHECK_VALUE): void
```
Ensure the validity of the argument type and cache keys.
#### Parameters
`iterable` $iterable The iterable to check.
`string` $check optional Whether to check keys or values.
#### Returns
`void`
#### Throws
`Cake\Cache\InvalidArgumentException`
### get() abstract public
```
get(string $key, mixed $default = null): mixed
```
Fetches the value for a given key from the cache.
#### Parameters
`string` $key The unique key of this item in the cache.
`mixed` $default optional Default value to return if the key does not exist.
#### Returns
`mixed`
#### Throws
`Cake\Cache\InvalidArgumentException`
If the $key string is not a legal value. ### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getMultiple() public
```
getMultiple(iterable $keys, mixed $default = null): iterable
```
Obtains multiple cache items by their unique keys.
#### Parameters
`iterable` $keys A list of keys that can obtained in a single operation.
`mixed` $default optional Default value to return for keys that do not exist.
#### Returns
`iterable`
#### Throws
`Cake\Cache\InvalidArgumentException`
If $keys is neither an array nor a Traversable, or if any of the $keys are not a legal value. ### groups() public
```
groups(): array<string>
```
Does whatever initialization for each group is required and returns the `group value` for each of them, this is the token representing each group in the cache key
#### Returns
`array<string>`
### has() public
```
has(string $key): bool
```
Determines whether an item is present in the cache.
NOTE: It is recommended that has() is only to be used for cache warming type purposes and not to be used within your live applications operations for get/set, as this method is subject to a race condition where your has() will return true and immediately after, another script can remove it making the state of your app out of date.
#### Parameters
`string` $key The cache item key.
#### Returns
`bool`
#### Throws
`Cake\Cache\InvalidArgumentException`
If the $key string is not a legal value. ### increment() abstract public
```
increment(string $key, int $offset = 1): int|false
```
Increment a number under the key and return incremented value
#### Parameters
`string` $key Identifier for the data
`int` $offset optional How much to add
#### Returns
`int|false`
### init() public
```
init(array<string, mixed> $config = []): bool
```
Initialize the cache engine
Called automatically by the cache frontend. Merge the runtime config with the defaults before use.
#### Parameters
`array<string, mixed>` $config optional Associative array of parameters for the engine
#### Returns
`bool`
### set() abstract public
```
set(string $key, mixed $value, null|intDateInterval $ttl = null): bool
```
Persists data in the cache, uniquely referenced by the given key with an optional expiration TTL time.
#### Parameters
`string` $key The key of the item to store.
`mixed` $value The value of the item to store, must be serializable.
`null|intDateInterval` $ttl optional Optional. The TTL value of this item. If no value is sent and the driver supports TTL then the library may set a default value for it or let the driver take care of that.
#### Returns
`bool`
#### Throws
`Cake\Cache\InvalidArgumentException`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setMultiple() public
```
setMultiple(iterable $values, null|intDateInterval $ttl = null): bool
```
Persists a set of key => value pairs in the cache, with an optional TTL.
#### Parameters
`iterable` $values A list of key => value pairs for a multiple-set operation.
`null|intDateInterval` $ttl optional Optional. The TTL value of this item. If no value is sent and the driver supports TTL then the library may set a default value for it or let the driver take care of that.
#### Returns
`bool`
#### Throws
`Cake\Cache\InvalidArgumentException`
If $values is neither an array nor a Traversable, or if any of the $values are not a legal value. ### warning() protected
```
warning(string $message): void
```
Cache Engines may trigger warnings if they encounter failures during operation, if option warnOnWriteFailures is set to true.
#### Parameters
`string` $message The warning message.
#### Returns
`void`
Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
The default cache configuration is overridden in most cache adapters. These are the keys that are common to all adapters. If overridden, this property is not used.
* `duration` Specify how long items in this cache configuration last.
* `groups` List of groups or 'tags' associated to every key stored in this config. handy for deleting a complete group from cache.
* `prefix` Prefix appended to all entries. Good for when you need to share a keyspace with either another cache config or another application.
* `warnOnWriteFailures` Some engines, such as ApcuEngine, may raise warnings on write failures.
#### Type
`array<string, mixed>`
### $\_groupPrefix protected
Contains the compiled string with all group prefixes to be prepended to every key in this cache engine
#### Type
`string`
| programming_docs |
cakephp Class SchemaDialect Class SchemaDialect
====================
Base class for schema implementations.
This class contains methods that are common across the various SQL dialects.
**Abstract**
**Namespace:** [Cake\Database\Schema](namespace-cake.database.schema)
Property Summary
----------------
* [$\_driver](#%24_driver) protected `Cake\Database\DriverInterface` The driver instance being used.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_applyTypeSpecificColumnConversion()](#_applyTypeSpecificColumnConversion()) protected
Tries to use a matching database type to convert a SQL column definition to an abstract type definition.
* ##### [\_convertConstraintColumns()](#_convertConstraintColumns()) protected
Convert foreign key constraints references to a valid stringified list
* ##### [\_convertOnClause()](#_convertOnClause()) protected
Convert string on clauses to the abstract ones.
* ##### [\_foreignOnClause()](#_foreignOnClause()) protected
Generate an ON clause for a foreign key.
* ##### [\_getTypeSpecificColumnSql()](#_getTypeSpecificColumnSql()) protected
Tries to use a matching database type to generate the SQL fragment for a single column in a table.
* ##### [addConstraintSql()](#addConstraintSql()) abstract public
Generate the SQL queries needed to add foreign key constraints to the table
* ##### [columnSql()](#columnSql()) abstract public
Generate the SQL fragment for a single column in a table.
* ##### [constraintSql()](#constraintSql()) abstract public
Generate the SQL fragments for defining table constraints.
* ##### [convertColumnDescription()](#convertColumnDescription()) abstract public
Convert field description results into abstract schema fields.
* ##### [convertForeignKeyDescription()](#convertForeignKeyDescription()) abstract public
Convert a foreign key description into constraints on the Table object.
* ##### [convertIndexDescription()](#convertIndexDescription()) abstract public
Convert an index description results into abstract schema indexes or constraints.
* ##### [convertOptionsDescription()](#convertOptionsDescription()) public
Convert options data into table options.
* ##### [createTableSql()](#createTableSql()) abstract public
Generate the SQL to create a table.
* ##### [describeColumnSql()](#describeColumnSql()) abstract public
Generate the SQL to describe a table.
* ##### [describeForeignKeySql()](#describeForeignKeySql()) abstract public
Generate the SQL to describe the foreign keys in a table.
* ##### [describeIndexSql()](#describeIndexSql()) abstract public
Generate the SQL to describe the indexes in a table.
* ##### [describeOptionsSql()](#describeOptionsSql()) public
Generate the SQL to describe table options
* ##### [dropConstraintSql()](#dropConstraintSql()) abstract public
Generate the SQL queries needed to drop foreign key constraints from the table
* ##### [dropTableSql()](#dropTableSql()) public
Generate the SQL to drop a table.
* ##### [indexSql()](#indexSql()) abstract public
Generate the SQL fragment for a single index in a table.
* ##### [listTablesSql()](#listTablesSql()) abstract public
Generate the SQL to list the tables.
* ##### [listTablesWithoutViewsSql()](#listTablesWithoutViewsSql()) public @method
Generate the SQL to list the tables, excluding all views.
* ##### [truncateTableSql()](#truncateTableSql()) abstract public
Generate the SQL to truncate a table.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Database\DriverInterface $driver)
```
Constructor
This constructor will connect the driver so that methods like columnSql() and others will fail when the driver has not been connected.
#### Parameters
`Cake\Database\DriverInterface` $driver The driver to use.
### \_applyTypeSpecificColumnConversion() protected
```
_applyTypeSpecificColumnConversion(string $columnType, array $definition): array|null
```
Tries to use a matching database type to convert a SQL column definition to an abstract type definition.
#### Parameters
`string` $columnType The column type.
`array` $definition The column definition.
#### Returns
`array|null`
### \_convertConstraintColumns() protected
```
_convertConstraintColumns(array<string>|string $references): string
```
Convert foreign key constraints references to a valid stringified list
#### Parameters
`array<string>|string` $references The referenced columns of a foreign key constraint statement
#### Returns
`string`
### \_convertOnClause() protected
```
_convertOnClause(string $clause): string
```
Convert string on clauses to the abstract ones.
#### Parameters
`string` $clause The on clause to convert.
#### Returns
`string`
### \_foreignOnClause() protected
```
_foreignOnClause(string $on): string
```
Generate an ON clause for a foreign key.
#### Parameters
`string` $on The on clause
#### Returns
`string`
### \_getTypeSpecificColumnSql() protected
```
_getTypeSpecificColumnSql(string $columnType, Cake\Database\Schema\TableSchemaInterface $schema, string $column): string|null
```
Tries to use a matching database type to generate the SQL fragment for a single column in a table.
#### Parameters
`string` $columnType The column type.
`Cake\Database\Schema\TableSchemaInterface` $schema The table schema instance the column is in.
`string` $column The name of the column.
#### Returns
`string|null`
### addConstraintSql() abstract public
```
addConstraintSql(Cake\Database\Schema\TableSchema $schema): array
```
Generate the SQL queries needed to add foreign key constraints to the table
#### Parameters
`Cake\Database\Schema\TableSchema` $schema The table instance the foreign key constraints are.
#### Returns
`array`
### columnSql() abstract public
```
columnSql(Cake\Database\Schema\TableSchema $schema, string $name): string
```
Generate the SQL fragment for a single column in a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema The table instance the column is in.
`string` $name The name of the column.
#### Returns
`string`
### constraintSql() abstract public
```
constraintSql(Cake\Database\Schema\TableSchema $schema, string $name): string
```
Generate the SQL fragments for defining table constraints.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema The table instance the column is in.
`string` $name The name of the column.
#### Returns
`string`
### convertColumnDescription() abstract public
```
convertColumnDescription(Cake\Database\Schema\TableSchema $schema, array $row): void
```
Convert field description results into abstract schema fields.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema The table object to append fields to.
`array` $row The row data from `describeColumnSql`.
#### Returns
`void`
### convertForeignKeyDescription() abstract public
```
convertForeignKeyDescription(Cake\Database\Schema\TableSchema $schema, array $row): void
```
Convert a foreign key description into constraints on the Table object.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema The table object to append a constraint to.
`array` $row The row data from `describeForeignKeySql`.
#### Returns
`void`
### convertIndexDescription() abstract public
```
convertIndexDescription(Cake\Database\Schema\TableSchema $schema, array $row): void
```
Convert an index description results into abstract schema indexes or constraints.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema The table object to append an index or constraint to.
`array` $row The row data from `describeIndexSql`.
#### Returns
`void`
### convertOptionsDescription() public
```
convertOptionsDescription(Cake\Database\Schema\TableSchema $schema, array $row): void
```
Convert options data into table options.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema Table instance.
`array` $row The row of data.
#### Returns
`void`
### createTableSql() abstract public
```
createTableSql(Cake\Database\Schema\TableSchema $schema, array<string> $columns, array<string> $constraints, array<string> $indexes): array<string>
```
Generate the SQL to create a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema Table instance.
`array<string>` $columns The columns to go inside the table.
`array<string>` $constraints The constraints for the table.
`array<string>` $indexes The indexes for the table.
#### Returns
`array<string>`
### describeColumnSql() abstract public
```
describeColumnSql(string $tableName, array<string, mixed> $config): array
```
Generate the SQL to describe a table.
#### Parameters
`string` $tableName The table name to get information on.
`array<string, mixed>` $config The connection configuration.
#### Returns
`array`
### describeForeignKeySql() abstract public
```
describeForeignKeySql(string $tableName, array<string, mixed> $config): array
```
Generate the SQL to describe the foreign keys in a table.
#### Parameters
`string` $tableName The table name to get information on.
`array<string, mixed>` $config The connection configuration.
#### Returns
`array`
### describeIndexSql() abstract public
```
describeIndexSql(string $tableName, array<string, mixed> $config): array
```
Generate the SQL to describe the indexes in a table.
#### Parameters
`string` $tableName The table name to get information on.
`array<string, mixed>` $config The connection configuration.
#### Returns
`array`
### describeOptionsSql() public
```
describeOptionsSql(string $tableName, array<string, mixed> $config): array
```
Generate the SQL to describe table options
#### Parameters
`string` $tableName Table name.
`array<string, mixed>` $config The connection configuration.
#### Returns
`array`
### dropConstraintSql() abstract public
```
dropConstraintSql(Cake\Database\Schema\TableSchema $schema): array
```
Generate the SQL queries needed to drop foreign key constraints from the table
#### Parameters
`Cake\Database\Schema\TableSchema` $schema The table instance the foreign key constraints are.
#### Returns
`array`
### dropTableSql() public
```
dropTableSql(Cake\Database\Schema\TableSchema $schema): array
```
Generate the SQL to drop a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema Schema instance
#### Returns
`array`
### indexSql() abstract public
```
indexSql(Cake\Database\Schema\TableSchema $schema, string $name): string
```
Generate the SQL fragment for a single index in a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema The table object the column is in.
`string` $name The name of the column.
#### Returns
`string`
### listTablesSql() abstract public
```
listTablesSql(array<string, mixed> $config): array
```
Generate the SQL to list the tables.
#### Parameters
`array<string, mixed>` $config The connection configuration to use for getting tables from.
#### Returns
`array`
### listTablesWithoutViewsSql() public @method
```
listTablesWithoutViewsSql(array $config): array<mixed>
```
Generate the SQL to list the tables, excluding all views.
#### Parameters
`array` $config #### Returns
`array<mixed>`
### truncateTableSql() abstract public
```
truncateTableSql(Cake\Database\Schema\TableSchema $schema): array
```
Generate the SQL to truncate a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema Table instance.
#### Returns
`array`
Property Detail
---------------
### $\_driver protected
The driver instance being used.
#### Type
`Cake\Database\DriverInterface`
cakephp Class PhpConfig Class PhpConfig
================
PHP engine allows Configure to load configuration values from files containing simple PHP arrays.
Files compatible with PhpConfig should return an array that contains all the configuration data contained in the file.
An example configuration file would look like::
```
<?php
return [
'debug' => false,
'Security' => [
'salt' => 'its-secret'
],
'App' => [
'namespace' => 'App'
]
];
```
**Namespace:** [Cake\Core\Configure\Engine](namespace-cake.core.configure.engine)
**See:** \Cake\Core\Configure::load() for how to load custom configuration files.
Property Summary
----------------
* [$\_extension](#%24_extension) protected `string` File extension.
* [$\_path](#%24_path) protected `string` The path this engine finds files on.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor for PHP Config file reading.
* ##### [\_getFilePath()](#_getFilePath()) protected
Get file path
* ##### [dump()](#dump()) public
Converts the provided $data into a string of PHP code that can be used saved into a file and loaded later.
* ##### [read()](#read()) public
Read a config file and return its contents.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $path = null)
```
Constructor for PHP Config file reading.
#### Parameters
`string|null` $path optional The path to read config files from. Defaults to CONFIG.
### \_getFilePath() protected
```
_getFilePath(string $key, bool $checkExists = false): string
```
Get file path
#### Parameters
`string` $key The identifier to write to. If the key has a . it will be treated as a plugin prefix.
`bool` $checkExists optional Whether to check if file exists. Defaults to false.
#### Returns
`string`
#### Throws
`Cake\Core\Exception\CakeException`
When files don't exist or when files contain '..' as this could lead to abusive reads. ### dump() public
```
dump(string $key, array $data): bool
```
Converts the provided $data into a string of PHP code that can be used saved into a file and loaded later.
#### Parameters
`string` $key The identifier to write to. If the key has a . it will be treated as a plugin prefix.
`array` $data Data to dump.
#### Returns
`bool`
### read() public
```
read(string $key): array
```
Read a config file and return its contents.
Files with `.` in the name will be treated as values in plugins. Instead of reading from the initialized path, plugin keys will be located using Plugin::path().
#### Parameters
`string` $key The identifier to read from. If the key has a . it will be treated as a plugin prefix.
#### Returns
`array`
#### Throws
`Cake\Core\Exception\CakeException`
when files don't exist or they don't contain `$config`. Or when files contain '..' as this could lead to abusive reads. Property Detail
---------------
### $\_extension protected
File extension.
#### Type
`string`
### $\_path protected
The path this engine finds files on.
#### Type
`string`
cakephp Class Inflector Class Inflector
================
Pluralize and singularize English words.
Inflector pluralizes and singularizes English nouns. Used by CakePHP's naming conventions throughout the framework.
**Namespace:** [Cake\Utility](namespace-cake.utility)
**Link:** https://book.cakephp.org/4/en/core-libraries/inflector.html
Property Summary
----------------
* [$\_cache](#%24_cache) protected static `array<string, mixed>` Method cache array.
* [$\_initialState](#%24_initialState) protected static `array` The initial state of Inflector so reset() works.
* [$\_irregular](#%24_irregular) protected static `array<string, string>` Irregular rules
* [$\_plural](#%24_plural) protected static `array<string, string>` Plural inflector rules
* [$\_singular](#%24_singular) protected static `array<string, string>` Singular inflector rules
* [$\_uninflected](#%24_uninflected) protected static `array<string>` Words that should not be inflected
Method Summary
--------------
* ##### [\_cache()](#_cache()) protected static
Cache inflected values, and return if already available
* ##### [camelize()](#camelize()) public static
Returns the input lower\_case\_delimited\_string as a CamelCasedString.
* ##### [classify()](#classify()) public static
Returns Cake model class name ("Person" for the database table "people".) for given database table.
* ##### [dasherize()](#dasherize()) public static
Returns the input CamelCasedString as an dashed-string.
* ##### [delimit()](#delimit()) public static
Expects a CamelCasedInputString, and produces a lower\_case\_delimited\_string
* ##### [humanize()](#humanize()) public static
Returns the input lower\_case\_delimited\_string as 'A Human Readable String'. (Underscores are replaced by spaces and capitalized following words.)
* ##### [pluralize()](#pluralize()) public static
Return $word in plural form.
* ##### [reset()](#reset()) public static
Clears Inflectors inflected value caches. And resets the inflection rules to the initial values.
* ##### [rules()](#rules()) public static
Adds custom inflection $rules, of either 'plural', 'singular', 'uninflected' or 'irregular' $type.
* ##### [singularize()](#singularize()) public static
Return $word in singular form.
* ##### [tableize()](#tableize()) public static
Returns corresponding table name for given model $className. ("people" for the model class "Person").
* ##### [underscore()](#underscore()) public static
Returns the input CamelCasedString as an underscored\_string.
* ##### [variable()](#variable()) public static
Returns camelBacked version of an underscored string.
Method Detail
-------------
### \_cache() protected static
```
_cache(string $type, string $key, string|false $value = false): string|false
```
Cache inflected values, and return if already available
#### Parameters
`string` $type Inflection type
`string` $key Original value
`string|false` $value optional Inflected value
#### Returns
`string|false`
### camelize() public static
```
camelize(string $string, string $delimiter = '_'): string
```
Returns the input lower\_case\_delimited\_string as a CamelCasedString.
#### Parameters
`string` $string String to camelize
`string` $delimiter optional the delimiter in the input string
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/core-libraries/inflector.html#creating-camelcase-and-under-scored-forms
### classify() public static
```
classify(string $tableName): string
```
Returns Cake model class name ("Person" for the database table "people".) for given database table.
#### Parameters
`string` $tableName Name of database table to get class name for
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/core-libraries/inflector.html#creating-table-and-class-name-forms
### dasherize() public static
```
dasherize(string $string): string
```
Returns the input CamelCasedString as an dashed-string.
Also replaces underscores with dashes
#### Parameters
`string` $string The string to dasherize.
#### Returns
`string`
### delimit() public static
```
delimit(string $string, string $delimiter = '_'): string
```
Expects a CamelCasedInputString, and produces a lower\_case\_delimited\_string
#### Parameters
`string` $string String to delimit
`string` $delimiter optional the character to use as a delimiter
#### Returns
`string`
### humanize() public static
```
humanize(string $string, string $delimiter = '_'): string
```
Returns the input lower\_case\_delimited\_string as 'A Human Readable String'. (Underscores are replaced by spaces and capitalized following words.)
#### Parameters
`string` $string String to be humanized
`string` $delimiter optional the character to replace with a space
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/core-libraries/inflector.html#creating-human-readable-forms
### pluralize() public static
```
pluralize(string $word): string
```
Return $word in plural form.
#### Parameters
`string` $word Word in singular
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/core-libraries/inflector.html#creating-plural-singular-forms
### reset() public static
```
reset(): void
```
Clears Inflectors inflected value caches. And resets the inflection rules to the initial values.
#### Returns
`void`
### rules() public static
```
rules(string $type, array $rules, bool $reset = false): void
```
Adds custom inflection $rules, of either 'plural', 'singular', 'uninflected' or 'irregular' $type.
### Usage:
```
Inflector::rules('plural', ['/^(inflect)or$/i' => '\1ables']);
Inflector::rules('irregular', ['red' => 'redlings']);
Inflector::rules('uninflected', ['dontinflectme']);
```
#### Parameters
`string` $type The type of inflection, either 'plural', 'singular', or 'uninflected'.
`array` $rules Array of rules to be added.
`bool` $reset optional If true, will unset default inflections for all new rules that are being defined in $rules.
#### Returns
`void`
### singularize() public static
```
singularize(string $word): string
```
Return $word in singular form.
#### Parameters
`string` $word Word in plural
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/core-libraries/inflector.html#creating-plural-singular-forms
### tableize() public static
```
tableize(string $className): string
```
Returns corresponding table name for given model $className. ("people" for the model class "Person").
#### Parameters
`string` $className Name of class to get database table name for
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/core-libraries/inflector.html#creating-table-and-class-name-forms
### underscore() public static
```
underscore(string $string): string
```
Returns the input CamelCasedString as an underscored\_string.
Also replaces dashes with underscores
#### Parameters
`string` $string CamelCasedString to be "underscorized"
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/core-libraries/inflector.html#creating-camelcase-and-under-scored-forms
### variable() public static
```
variable(string $string): string
```
Returns camelBacked version of an underscored string.
#### Parameters
`string` $string String to convert.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/core-libraries/inflector.html#creating-variable-names
Property Detail
---------------
### $\_cache protected static
Method cache array.
#### Type
`array<string, mixed>`
### $\_initialState protected static
The initial state of Inflector so reset() works.
#### Type
`array`
### $\_irregular protected static
Irregular rules
#### Type
`array<string, string>`
### $\_plural protected static
Plural inflector rules
#### Type
`array<string, string>`
### $\_singular protected static
Singular inflector rules
#### Type
`array<string, string>`
### $\_uninflected protected static
Words that should not be inflected
#### Type
`array<string>`
| programming_docs |
cakephp Class SessionStorage Class SessionStorage
=====================
Session based persistent storage for authenticated user record.
**Namespace:** [Cake\Auth\Storage](namespace-cake.auth.storage)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default configuration for this class.
* [$\_session](#%24_session) protected `Cake\Http\Session` Session object.
* [$\_user](#%24_user) protected `ArrayAccess|array|false|null` User record.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [delete()](#delete()) public
Delete user record from session.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [read()](#read()) public
Read user record from session.
* ##### [redirectUrl()](#redirectUrl()) public
Get/set redirect URL.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [write()](#write()) public
Write user record to session.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Http\ServerRequest $request, Cake\Http\Response $response, array<string, mixed> $config = [])
```
Constructor.
#### Parameters
`Cake\Http\ServerRequest` $request Request instance.
`Cake\Http\Response` $response Response instance.
`array<string, mixed>` $config optional Configuration list.
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### delete() public
```
delete(): void
```
Delete user record from session.
The session id is also renewed to help mitigate issues with session replays.
#### Returns
`void`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### read() public
```
read(): ArrayAccess|array|null
```
Read user record from session.
#### Returns
`ArrayAccess|array|null`
### redirectUrl() public
```
redirectUrl(mixed $url = null): array|string|null
```
Get/set redirect URL.
#### Parameters
`mixed` $url optional #### Returns
`array|string|null`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### write() public
```
write(mixed $user): void
```
Write user record to session.
The session id is also renewed to help mitigate issues with session replays.
#### Parameters
`mixed` $user User record.
#### Returns
`void`
Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default configuration for this class.
Keys:
* `key` - Session key used to store user record.
* `redirect` - Session key used to store redirect URL.
#### Type
`array<string, mixed>`
### $\_session protected
Session object.
#### Type
`Cake\Http\Session`
### $\_user protected
User record.
Stores user record array if fetched from session or false if session does not have user record.
#### Type
`ArrayAccess|array|false|null`
cakephp Class FixtureManager Class FixtureManager
=====================
A factory class to manage the life cycle of test fixtures
**Namespace:** [Cake\TestSuite\Fixture](namespace-cake.testsuite.fixture)
Property Summary
----------------
* [$\_debug](#%24_debug) protected `bool` Is the test runner being run with `--debug` enabled. When true, fixture SQL will also be logged.
* [$\_fixtureMap](#%24_fixtureMap) protected `arrayCake\Datasource\FixtureInterface>` Holds the fixture classes that where instantiated indexed by class name
* [$\_initialized](#%24_initialized) protected `bool` Was this instance already initialized?
* [$\_insertionMap](#%24_insertionMap) protected `array<string, arrayCake\Datasource\FixtureInterface>>` A map of connection names and the fixture currently in it.
* [$\_loaded](#%24_loaded) protected `arrayCake\Datasource\FixtureInterface>` Holds the fixture classes that where instantiated
* [$\_processed](#%24_processed) protected `array<string, bool>` List of TestCase class name that have been processed
Method Summary
--------------
* ##### [\_aliasConnections()](#_aliasConnections()) protected
Add aliases for all non test prefixed connections.
* ##### [\_fixtureConnections()](#_fixtureConnections()) protected
Get the unique list of connections that a set of fixtures contains.
* ##### [\_initDb()](#_initDb()) protected
Initializes this class with a DataSource object to use as default for all fixtures
* ##### [\_loadFixtures()](#_loadFixtures()) protected
Looks for fixture files and instantiates the classes accordingly
* ##### [\_runOperation()](#_runOperation()) protected
Run a function on each connection and collection of fixtures.
* ##### [\_setupTable()](#_setupTable()) protected
Runs the drop and create commands on the fixtures if necessary.
* ##### [fixturize()](#fixturize()) public
* ##### [getInserted()](#getInserted()) public
* ##### [isFixtureSetup()](#isFixtureSetup()) public
Check whether a fixture has been inserted in a given connection name.
* ##### [load()](#load()) public
* ##### [loadSingle()](#loadSingle()) public
* ##### [loaded()](#loaded()) public
* ##### [setDebug()](#setDebug()) public
Modify the debug mode.
* ##### [shutDown()](#shutDown()) public
Drop all fixture tables loaded by this class
* ##### [unload()](#unload()) public
Truncates the fixtures tables
Method Detail
-------------
### \_aliasConnections() protected
```
_aliasConnections(): void
```
Add aliases for all non test prefixed connections.
This allows models to use the test connections without a pile of configuration work.
#### Returns
`void`
### \_fixtureConnections() protected
```
_fixtureConnections(array<string> $fixtures): array
```
Get the unique list of connections that a set of fixtures contains.
#### Parameters
`array<string>` $fixtures The array of fixtures a list of connections is needed from.
#### Returns
`array`
### \_initDb() protected
```
_initDb(): void
```
Initializes this class with a DataSource object to use as default for all fixtures
#### Returns
`void`
### \_loadFixtures() protected
```
_loadFixtures(Cake\TestSuite\TestCase $test): void
```
Looks for fixture files and instantiates the classes accordingly
#### Parameters
`Cake\TestSuite\TestCase` $test The test suite to load fixtures for.
#### Returns
`void`
#### Throws
`UnexpectedValueException`
when a referenced fixture does not exist. ### \_runOperation() protected
```
_runOperation(array<string> $fixtures, callable $operation): void
```
Run a function on each connection and collection of fixtures.
#### Parameters
`array<string>` $fixtures A list of fixtures to operate on.
`callable` $operation The operation to run on each connection + fixture set.
#### Returns
`void`
### \_setupTable() protected
```
_setupTable(Cake\Datasource\FixtureInterface $fixture, Cake\Datasource\ConnectionInterface $db, array<string> $sources, bool $drop = true): void
```
Runs the drop and create commands on the fixtures if necessary.
#### Parameters
`Cake\Datasource\FixtureInterface` $fixture the fixture object to create
`Cake\Datasource\ConnectionInterface` $db The Connection object instance to use
`array<string>` $sources The existing tables in the datasource.
`bool` $drop optional whether drop the fixture if it is already created or not
#### Returns
`void`
### fixturize() public
```
fixturize(Cake\TestSuite\TestCase $test): void
```
#### Parameters
`Cake\TestSuite\TestCase` $test Test case
#### Returns
`void`
### getInserted() public
```
getInserted(): array<string>
```
#### Returns
`array<string>`
### isFixtureSetup() public
```
isFixtureSetup(string $connection, Cake\Datasource\FixtureInterface $fixture): bool
```
Check whether a fixture has been inserted in a given connection name.
#### Parameters
`string` $connection The connection name.
`Cake\Datasource\FixtureInterface` $fixture The fixture to check.
#### Returns
`bool`
### load() public
```
load(Cake\TestSuite\TestCase $test): void
```
#### Parameters
`Cake\TestSuite\TestCase` $test Test case
#### Returns
`void`
#### Throws
`RuntimeException`
### loadSingle() public
```
loadSingle(string $name, Cake\Datasource\ConnectionInterface|null $connection = null, bool $dropTables = true): void
```
#### Parameters
`string` $name Name
`Cake\Datasource\ConnectionInterface|null` $connection optional Connection
`bool` $dropTables optional Drop all tables prior to loading schema files
#### Returns
`void`
#### Throws
`UnexpectedValueException`
### loaded() public
```
loaded(): Cake\Datasource\FixtureInterface[]
```
#### Returns
`Cake\Datasource\FixtureInterface[]`
### setDebug() public
```
setDebug(bool $debug): void
```
Modify the debug mode.
#### Parameters
`bool` $debug Whether fixture debug mode is enabled.
#### Returns
`void`
### shutDown() public
```
shutDown(): void
```
Drop all fixture tables loaded by this class
#### Returns
`void`
### unload() public
```
unload(Cake\TestSuite\TestCase $test): void
```
Truncates the fixtures tables
#### Parameters
`Cake\TestSuite\TestCase` $test The test to inspect for fixture unloading.
#### Returns
`void`
Property Detail
---------------
### $\_debug protected
Is the test runner being run with `--debug` enabled. When true, fixture SQL will also be logged.
#### Type
`bool`
### $\_fixtureMap protected
Holds the fixture classes that where instantiated indexed by class name
#### Type
`arrayCake\Datasource\FixtureInterface>`
### $\_initialized protected
Was this instance already initialized?
#### Type
`bool`
### $\_insertionMap protected
A map of connection names and the fixture currently in it.
#### Type
`array<string, arrayCake\Datasource\FixtureInterface>>`
### $\_loaded protected
Holds the fixture classes that where instantiated
#### Type
`arrayCake\Datasource\FixtureInterface>`
### $\_processed protected
List of TestCase class name that have been processed
#### Type
`array<string, bool>`
cakephp Namespace Form Namespace Form
==============
### Interfaces
* ##### [ContextInterface](interface-cake.view.form.contextinterface)
Interface for FormHelper context implementations.
### Classes
* ##### [ArrayContext](class-cake.view.form.arraycontext)
Provides a basic array based context provider for FormHelper.
* ##### [ContextFactory](class-cake.view.form.contextfactory)
Factory for getting form context instance based on provided data.
* ##### [EntityContext](class-cake.view.form.entitycontext)
Provides a form context around a single entity and its relations. It also can be used as context around an array or iterator of entities.
* ##### [FormContext](class-cake.view.form.formcontext)
Provides a context provider for {@link \Cake\Form\Form} instances.
* ##### [NullContext](class-cake.view.form.nullcontext)
Provides a context provider that does nothing.
cakephp Class AbstractPasswordHasher Class AbstractPasswordHasher
=============================
Abstract password hashing class
**Abstract**
**Namespace:** [Cake\Auth](namespace-cake.auth)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [check()](#check()) abstract public
Check hash. Generate hash from user provided password string or data array and check against existing hash.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [hash()](#hash()) abstract public
Generates password hash.
* ##### [needsRehash()](#needsRehash()) public
Returns true if the password need to be rehashed, due to the password being created with anything else than the passwords generated by this class.
* ##### [setConfig()](#setConfig()) public
Sets the config.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Constructor
#### Parameters
`array<string, mixed>` $config optional Array of config.
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### check() abstract public
```
check(string $password, string $hashedPassword): bool
```
Check hash. Generate hash from user provided password string or data array and check against existing hash.
#### Parameters
`string` $password Plain text password to hash.
`string` $hashedPassword Existing hashed password.
#### Returns
`bool`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### hash() abstract public
```
hash(string $password): string|false
```
Generates password hash.
#### Parameters
`string` $password Plain text password to hash.
#### Returns
`string|false`
### needsRehash() public
```
needsRehash(string $password): bool
```
Returns true if the password need to be rehashed, due to the password being created with anything else than the passwords generated by this class.
Returns true by default since the only implementation users should rely on is the one provided by default in php 5.5+ or any compatible library
#### Parameters
`string` $password The password to verify
#### Returns
`bool`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config
These are merged with user-provided config when the object is used.
#### Type
`array<string, mixed>`
| programming_docs |
cakephp Class FileSentAs Class FileSentAs
=================
FileSentAs
**Namespace:** [Cake\TestSuite\Constraint\Response](namespace-cake.testsuite.constraint.response)
Property Summary
----------------
* [$response](#%24response) protected `Cake\Http\Response`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_getBodyAsString()](#_getBodyAsString()) protected
Get the response body as string
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Checks assertion
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(Psr\Http\Message\ResponseInterface|null $response)
```
Constructor
#### Parameters
`Psr\Http\Message\ResponseInterface|null` $response Response
### \_getBodyAsString() protected
```
_getBodyAsString(): string
```
Get the response body as string
#### Returns
`string`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks assertion
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Expected type
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $response protected
#### Type
`Cake\Http\Response`
cakephp Class EventList Class EventList
================
The Event List
**Namespace:** [Cake\Event](namespace-cake.event)
Property Summary
----------------
* [$\_events](#%24_events) protected `arrayCake\Event\EventInterface>` Events list
Method Summary
--------------
* ##### [add()](#add()) public
Adds an event to the list when event listing is enabled.
* ##### [count()](#count()) public
Count elements of an object
* ##### [flush()](#flush()) public
Empties the list of dispatched events.
* ##### [hasEvent()](#hasEvent()) public
Checks if an event is in the list.
* ##### [offsetExists()](#offsetExists()) public
Whether a offset exists
* ##### [offsetGet()](#offsetGet()) public
Offset to retrieve
* ##### [offsetSet()](#offsetSet()) public
Offset to set
* ##### [offsetUnset()](#offsetUnset()) public
Offset to unset
Method Detail
-------------
### add() public
```
add(Cake\Event\EventInterface $event): void
```
Adds an event to the list when event listing is enabled.
#### Parameters
`Cake\Event\EventInterface` $event An event to the list of dispatched events.
#### Returns
`void`
### count() public
```
count(): int
```
Count elements of an object
#### Returns
`int`
#### Links
https://secure.php.net/manual/en/countable.count.php
### flush() public
```
flush(): void
```
Empties the list of dispatched events.
#### Returns
`void`
### hasEvent() public
```
hasEvent(string $name): bool
```
Checks if an event is in the list.
#### Parameters
`string` $name Event name.
#### Returns
`bool`
### offsetExists() public
```
offsetExists(mixed $offset): bool
```
Whether a offset exists
#### Parameters
`mixed` $offset An offset to check for.
#### Returns
`bool`
#### Links
https://secure.php.net/manual/en/arrayaccess.offsetexists.php
### offsetGet() public
```
offsetGet(mixed $offset): mixed
```
Offset to retrieve
#### Parameters
`mixed` $offset The offset to retrieve.
#### Returns
`mixed`
#### Links
https://secure.php.net/manual/en/arrayaccess.offsetget.php
### offsetSet() public
```
offsetSet(mixed $offset, mixed $value): void
```
Offset to set
#### Parameters
`mixed` $offset The offset to assign the value to.
`mixed` $value The value to set.
#### Returns
`void`
#### Links
https://secure.php.net/manual/en/arrayaccess.offsetset.php
### offsetUnset() public
```
offsetUnset(mixed $offset): void
```
Offset to unset
#### Parameters
`mixed` $offset The offset to unset.
#### Returns
`void`
#### Links
https://secure.php.net/manual/en/arrayaccess.offsetunset.php
Property Detail
---------------
### $\_events protected
Events list
#### Type
`arrayCake\Event\EventInterface>`
cakephp Namespace Component Namespace Component
===================
### Classes
* ##### [AuthComponent](class-cake.controller.component.authcomponent)
Authentication control component class.
* ##### [CheckHttpCacheComponent](class-cake.controller.component.checkhttpcachecomponent)
Use HTTP caching headers to see if rendering can be skipped.
* ##### [FlashComponent](class-cake.controller.component.flashcomponent)
The CakePHP FlashComponent provides a way for you to write a flash variable to the session from your controllers, to be rendered in a view with the FlashHelper.
* ##### [FormProtectionComponent](class-cake.controller.component.formprotectioncomponent)
Protects against form tampering. It ensures that:
* ##### [PaginatorComponent](class-cake.controller.component.paginatorcomponent)
This component is used to handle automatic model data pagination. The primary way to use this component is to call the paginate() method. There is a convenience wrapper on Controller as well.
* ##### [RequestHandlerComponent](class-cake.controller.component.requesthandlercomponent)
Request object handling for alternative HTTP requests.
* ##### [SecurityComponent](class-cake.controller.component.securitycomponent)
The Security Component creates an easy way to integrate tighter security in your application. It provides methods for these tasks:
cakephp Interface QueryInterface Interface QueryInterface
=========================
The basis for every query object
**Namespace:** [Cake\Datasource](namespace-cake.datasource)
Method Summary
--------------
* ##### [aliasField()](#aliasField()) public
Returns a key => value array representing a single aliased field that can be passed directly to the select() method. The key will contain the alias and the value the actual field name.
* ##### [aliasFields()](#aliasFields()) public
Runs `aliasField()` for each field in the provided list and returns the result under a single array.
* ##### [all()](#all()) public
Fetch the results for this query.
* ##### [andWhere()](#andWhere()) public @method
Connects any previously defined set of conditions to the provided list using the AND operator. {@see \Cake\Database\Query::andWhere()}
* ##### [applyOptions()](#applyOptions()) public
Populates or adds parts to current query clauses using an array. This is handy for passing all query clauses at once. The option array accepts:
* ##### [count()](#count()) public
Returns the total amount of results for the query.
* ##### [find()](#find()) public
Apply custom finds to against an existing query object.
* ##### [first()](#first()) public
Returns the first result out of executing this query, if the query has not been executed before, it will set the limit clause to 1 for performance reasons.
* ##### [firstOrFail()](#firstOrFail()) public @method
Get the first result from the executing query or raise an exception. {@see \Cake\Database\Query::firstOrFail()}
* ##### [getRepository()](#getRepository()) public
Returns the default repository object that will be used by this query, that is, the repository that will appear in the from clause.
* ##### [limit()](#limit()) public
Sets the number of records that should be retrieved from database, accepts an integer or an expression object that evaluates to an integer. In some databases, this operation might not be supported or will require the query to be transformed in order to limit the result set size.
* ##### [offset()](#offset()) public
Sets the number of records that should be skipped from the original result set This is commonly used for paginating large results. Accepts an integer or an expression object that evaluates to an integer.
* ##### [order()](#order()) public
Adds a single or multiple fields to be used in the ORDER clause for this query. Fields can be passed as an array of strings, array of expression objects, a single expression or a single string.
* ##### [page()](#page()) public
Set the page of results you want.
* ##### [repository()](#repository()) public
Set the default Table object that will be used by this query and form the `FROM` clause.
* ##### [select()](#select()) public
Adds fields to be selected from datasource.
* ##### [toArray()](#toArray()) public
Returns an array representation of the results after executing the query.
* ##### [where()](#where()) public
Adds a condition or set of conditions to be used in the WHERE clause for this query. Conditions can be expressed as an array of fields as keys with comparison operators in it, the values for the array will be used for comparing the field to such literal. Finally, conditions can be expressed as a single string or an array of strings.
Method Detail
-------------
### aliasField() public
```
aliasField(string $field, string|null $alias = null): array<string, string>
```
Returns a key => value array representing a single aliased field that can be passed directly to the select() method. The key will contain the alias and the value the actual field name.
If the field is already aliased, then it will not be changed. If no $alias is passed, the default table for this query will be used.
#### Parameters
`string` $field The field to alias
`string|null` $alias optional the alias used to prefix the field
#### Returns
`array<string, string>`
### aliasFields() public
```
aliasFields(array $fields, string|null $defaultAlias = null): array<string, string>
```
Runs `aliasField()` for each field in the provided list and returns the result under a single array.
#### Parameters
`array` $fields The fields to alias
`string|null` $defaultAlias optional The default alias
#### Returns
`array<string, string>`
### all() public
```
all(): Cake\Datasource\ResultSetInterface
```
Fetch the results for this query.
Will return either the results set through setResult(), or execute this query and return the ResultSetDecorator object ready for streaming of results.
ResultSetDecorator is a traversable object that implements the methods found on Cake\Collection\Collection.
#### Returns
`Cake\Datasource\ResultSetInterface`
### andWhere() public @method
```
andWhere(mixed $conditions, array $types = []): $this
```
Connects any previously defined set of conditions to the provided list using the AND operator. {@see \Cake\Database\Query::andWhere()}
#### Parameters
$conditions `array` $types optional #### Returns
`$this`
### applyOptions() public
```
applyOptions(array<string, mixed> $options): $this
```
Populates or adds parts to current query clauses using an array. This is handy for passing all query clauses at once. The option array accepts:
* fields: Maps to the select method
* conditions: Maps to the where method
* limit: Maps to the limit method
* order: Maps to the order method
* offset: Maps to the offset method
* group: Maps to the group method
* having: Maps to the having method
* contain: Maps to the contain options for eager loading
* join: Maps to the join method
* page: Maps to the page method
### Example:
```
$query->applyOptions([
'fields' => ['id', 'name'],
'conditions' => [
'created >=' => '2013-01-01'
],
'limit' => 10
]);
```
Is equivalent to:
```
$query
->select(['id', 'name'])
->where(['created >=' => '2013-01-01'])
->limit(10)
```
#### Parameters
`array<string, mixed>` $options list of query clauses to apply new parts to.
#### Returns
`$this`
### count() public
```
count(): int
```
Returns the total amount of results for the query.
#### Returns
`int`
### find() public
```
find(string $finder, array<string, mixed> $options = []): static
```
Apply custom finds to against an existing query object.
Allows custom find methods to be combined and applied to each other.
```
$repository->find('all')->find('recent');
```
The above is an example of stacking multiple finder methods onto a single query.
#### Parameters
`string` $finder The finder method to use.
`array<string, mixed>` $options optional The options for the finder.
#### Returns
`static`
### first() public
```
first(): Cake\Datasource\EntityInterface|array|null
```
Returns the first result out of executing this query, if the query has not been executed before, it will set the limit clause to 1 for performance reasons.
### Example:
```
$singleUser = $query->select(['id', 'username'])->first();
```
#### Returns
`Cake\Datasource\EntityInterface|array|null`
### firstOrFail() public @method
```
firstOrFail(): Cake\Datasource\EntityInterface|array
```
Get the first result from the executing query or raise an exception. {@see \Cake\Database\Query::firstOrFail()}
#### Returns
`Cake\Datasource\EntityInterface|array`
### getRepository() public
```
getRepository(): Cake\Datasource\RepositoryInterface|null
```
Returns the default repository object that will be used by this query, that is, the repository that will appear in the from clause.
#### Returns
`Cake\Datasource\RepositoryInterface|null`
### limit() public
```
limit(Cake\Database\ExpressionInterface|int|null $limit): $this
```
Sets the number of records that should be retrieved from database, accepts an integer or an expression object that evaluates to an integer. In some databases, this operation might not be supported or will require the query to be transformed in order to limit the result set size.
### Examples
```
$query->limit(10) // generates LIMIT 10
$query->limit($query->newExpr()->add(['1 + 1'])); // LIMIT (1 + 1)
```
#### Parameters
`Cake\Database\ExpressionInterface|int|null` $limit number of records to be returned
#### Returns
`$this`
### offset() public
```
offset(Cake\Database\ExpressionInterface|int|null $offset): $this
```
Sets the number of records that should be skipped from the original result set This is commonly used for paginating large results. Accepts an integer or an expression object that evaluates to an integer.
In some databases, this operation might not be supported or will require the query to be transformed in order to limit the result set size.
### Examples
```
$query->offset(10) // generates OFFSET 10
$query->offset($query->newExpr()->add(['1 + 1'])); // OFFSET (1 + 1)
```
#### Parameters
`Cake\Database\ExpressionInterface|int|null` $offset number of records to be skipped
#### Returns
`$this`
### order() public
```
order(Cake\Database\ExpressionInterfaceClosure|array|string $fields, bool $overwrite = false): $this
```
Adds a single or multiple fields to be used in the ORDER clause for this query. Fields can be passed as an array of strings, array of expression objects, a single expression or a single string.
If an array is passed, keys will be used as the field itself and the value will represent the order in which such field should be ordered. When called multiple times with the same fields as key, the last order definition will prevail over the others.
By default this function will append any passed argument to the list of fields to be selected, unless the second argument is set to true.
### Examples:
```
$query->order(['title' => 'DESC', 'author_id' => 'ASC']);
```
Produces:
`ORDER BY title DESC, author_id ASC`
```
$query
->order(['title' => $query->newExpr('DESC NULLS FIRST')])
->order('author_id');
```
Will generate:
`ORDER BY title DESC NULLS FIRST, author_id`
```
$expression = $query->newExpr()->add(['id % 2 = 0']);
$query->order($expression)->order(['title' => 'ASC']);
```
Will become:
`ORDER BY (id %2 = 0), title ASC`
If you need to set complex expressions as order conditions, you should use `orderAsc()` or `orderDesc()`.
#### Parameters
`Cake\Database\ExpressionInterfaceClosure|array|string` $fields fields to be added to the list
`bool` $overwrite optional whether to reset order with field list or not
#### Returns
`$this`
### page() public
```
page(int $num, int|null $limit = null): $this
```
Set the page of results you want.
This method provides an easier to use interface to set the limit + offset in the record set you want as results. If empty the limit will default to the existing limit clause, and if that too is empty, then `25` will be used.
Pages must start at 1.
#### Parameters
`int` $num The page number you want.
`int|null` $limit optional The number of rows you want in the page. If null the current limit clause will be used.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
If page number < 1. ### repository() public
```
repository(Cake\Datasource\RepositoryInterface $repository): $this
```
Set the default Table object that will be used by this query and form the `FROM` clause.
#### Parameters
`Cake\Datasource\RepositoryInterface` $repository The default repository object to use
#### Returns
`$this`
### select() public
```
select(Cake\Database\ExpressionInterfaceCake\ORM\AssociationCake\ORM\Table|callable|array|string $fields, bool $overwrite = false): $this
```
Adds fields to be selected from datasource.
Calling this function multiple times will append more fields to the list of fields to be selected.
If `true` is passed in the second argument, any previous selections will be overwritten with the list passed in the first argument.
#### Parameters
`Cake\Database\ExpressionInterfaceCake\ORM\AssociationCake\ORM\Table|callable|array|string` $fields Fields.
`bool` $overwrite optional whether to reset fields with passed list or not
#### Returns
`$this`
### toArray() public
```
toArray(): array
```
Returns an array representation of the results after executing the query.
#### Returns
`array`
### where() public
```
where(Closure|array|string|null $conditions = null, array<string, string> $types = [], bool $overwrite = false): $this
```
Adds a condition or set of conditions to be used in the WHERE clause for this query. Conditions can be expressed as an array of fields as keys with comparison operators in it, the values for the array will be used for comparing the field to such literal. Finally, conditions can be expressed as a single string or an array of strings.
When using arrays, each entry will be joined to the rest of the conditions using an AND operator. Consecutive calls to this function will also join the new conditions specified using the AND operator. Additionally, values can be expressed using expression objects which can include other query objects.
Any conditions created with this methods can be used with any SELECT, UPDATE and DELETE type of queries.
### Conditions using operators:
```
$query->where([
'posted >=' => new DateTime('3 days ago'),
'title LIKE' => 'Hello W%',
'author_id' => 1,
], ['posted' => 'datetime']);
```
The previous example produces:
`WHERE posted >= 2012-01-27 AND title LIKE 'Hello W%' AND author_id = 1`
Second parameter is used to specify what type is expected for each passed key. Valid types can be used from the mapped with Database\Type class.
### Nesting conditions with conjunctions:
```
$query->where([
'author_id !=' => 1,
'OR' => ['published' => true, 'posted <' => new DateTime('now')],
'NOT' => ['title' => 'Hello']
], ['published' => boolean, 'posted' => 'datetime']
```
The previous example produces:
`WHERE author_id = 1 AND (published = 1 OR posted < '2012-02-01') AND NOT (title = 'Hello')`
You can nest conditions using conjunctions as much as you like. Sometimes, you may want to define 2 different options for the same key, in that case, you can wrap each condition inside a new array:
`$query->where(['OR' => [['published' => false], ['published' => true]])`
Keep in mind that every time you call where() with the third param set to false (default), it will join the passed conditions to the previous stored list using the AND operator. Also, using the same array key twice in consecutive calls to this method will not override the previous value.
### Using expressions objects:
```
$exp = $query->newExpr()->add(['id !=' => 100, 'author_id' != 1])->tieWith('OR');
$query->where(['published' => true], ['published' => 'boolean'])->where($exp);
```
The previous example produces:
`WHERE (id != 100 OR author_id != 1) AND published = 1`
Other Query objects that be used as conditions for any field.
### Adding conditions in multiple steps:
You can use callable functions to construct complex expressions, functions receive as first argument a new QueryExpression object and this query instance as second argument. Functions must return an expression object, that will be added the list of conditions for the query using the AND operator.
```
$query
->where(['title !=' => 'Hello World'])
->where(function ($exp, $query) {
$or = $exp->or(['id' => 1]);
$and = $exp->and(['id >' => 2, 'id <' => 10]);
return $or->add($and);
});
```
* The previous example produces:
`WHERE title != 'Hello World' AND (id = 1 OR (id > 2 AND id < 10))`
### Conditions as strings:
```
$query->where(['articles.author_id = authors.id', 'modified IS NULL']);
```
The previous example produces:
`WHERE articles.author_id = authors.id AND modified IS NULL`
Please note that when using the array notation or the expression objects, all values will be correctly quoted and transformed to the correspondent database data type automatically for you, thus securing your application from SQL injections. If you use string conditions make sure that your values are correctly quoted. The safest thing you can do is to never use string conditions.
#### Parameters
`Closure|array|string|null` $conditions optional The conditions to filter on.
`array<string, string>` $types optional Associative array of type names used to bind values to query
`bool` $overwrite optional whether to reset conditions with passed list or not
#### Returns
`$this`
| programming_docs |
cakephp Class OpenSsl Class OpenSsl
==============
OpenSSL implementation of crypto features for Cake\Utility\Security
This class is not intended to be used directly and should only be used in the context of {@link \Cake\Utility\Security}.
**Namespace:** [Cake\Utility\Crypto](namespace-cake.utility.crypto)
Constants
---------
* `string` **METHOD\_AES\_256\_CBC**
```
'aes-256-cbc'
```
Method Summary
--------------
* ##### [decrypt()](#decrypt()) public static
Decrypt a value using AES-256.
* ##### [encrypt()](#encrypt()) public static
Encrypt a value using AES-256.
Method Detail
-------------
### decrypt() public static
```
decrypt(string $cipher, string $key): string
```
Decrypt a value using AES-256.
#### Parameters
`string` $cipher The ciphertext to decrypt.
`string` $key The 256 bit/32 byte key to use as a cipher key.
#### Returns
`string`
#### Throws
`InvalidArgumentException`
On invalid data or key. ### encrypt() public static
```
encrypt(string $plain, string $key): string
```
Encrypt a value using AES-256.
*Caveat* You cannot properly encrypt/decrypt data with trailing null bytes. Any trailing null bytes will be removed on decryption due to how PHP pads messages with nulls prior to encryption.
#### Parameters
`string` $plain The value to encrypt.
`string` $key The 256 bit/32 byte key to use as a cipher key.
#### Returns
`string`
#### Throws
`InvalidArgumentException`
On invalid data or key.
cakephp Namespace Exception Namespace Exception
===================
### Classes
* ##### [InvalidPrimaryKeyException](class-cake.datasource.exception.invalidprimarykeyexception)
Exception raised when the provided primary key does not match the table primary key
* ##### [MissingDatasourceConfigException](class-cake.datasource.exception.missingdatasourceconfigexception)
Exception class to be thrown when a datasource configuration is not found
* ##### [MissingDatasourceException](class-cake.datasource.exception.missingdatasourceexception)
Used when a datasource cannot be found.
* ##### [MissingModelException](class-cake.datasource.exception.missingmodelexception)
Used when a model cannot be found.
* ##### [RecordNotFoundException](class-cake.datasource.exception.recordnotfoundexception)
Exception raised when a particular record was not found
cakephp Class CacheRegistry Class CacheRegistry
====================
An object registry for cache engines.
Used by {@link \Cake\Cache\Cache} to load and manage cache engines.
**Namespace:** [Cake\Cache](namespace-cake.cache)
Property Summary
----------------
* [$\_loaded](#%24_loaded) protected `array<object>` Map of loaded objects.
Method Summary
--------------
* ##### [\_\_debugInfo()](#__debugInfo()) public
Debug friendly object properties.
* ##### [\_\_get()](#__get()) public
Provide public read access to the loaded objects
* ##### [\_\_isset()](#__isset()) public
Provide isset access to \_loaded
* ##### [\_\_set()](#__set()) public
Sets an object.
* ##### [\_\_unset()](#__unset()) public
Unsets an object.
* ##### [\_checkDuplicate()](#_checkDuplicate()) protected
Check for duplicate object loading.
* ##### [\_create()](#_create()) protected
Create the cache engine instance.
* ##### [\_resolveClassName()](#_resolveClassName()) protected
Resolve a cache engine classname.
* ##### [\_throwMissingClassError()](#_throwMissingClassError()) protected
Throws an exception when a cache engine is missing.
* ##### [count()](#count()) public
Returns the number of loaded objects.
* ##### [get()](#get()) public
Get loaded object instance.
* ##### [getIterator()](#getIterator()) public
Returns an array iterator.
* ##### [has()](#has()) public
Check whether a given object is loaded.
* ##### [load()](#load()) public
Loads/constructs an object instance.
* ##### [loaded()](#loaded()) public
Get the list of loaded objects.
* ##### [normalizeArray()](#normalizeArray()) public
Normalizes an object array, creates an array that makes lazy loading easier
* ##### [reset()](#reset()) public
Clear loaded instances in the registry.
* ##### [set()](#set()) public
Set an object directly into the registry by name.
* ##### [unload()](#unload()) public
Remove a single adapter from the registry.
Method Detail
-------------
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Debug friendly object properties.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): object|null
```
Provide public read access to the loaded objects
#### Parameters
`string` $name Name of property to read
#### Returns
`object|null`
### \_\_isset() public
```
__isset(string $name): bool
```
Provide isset access to \_loaded
#### Parameters
`string` $name Name of object being checked.
#### Returns
`bool`
### \_\_set() public
```
__set(string $name, object $object): void
```
Sets an object.
#### Parameters
`string` $name Name of a property to set.
`object` $object Object to set.
#### Returns
`void`
### \_\_unset() public
```
__unset(string $name): void
```
Unsets an object.
#### Parameters
`string` $name Name of a property to unset.
#### Returns
`void`
### \_checkDuplicate() protected
```
_checkDuplicate(string $name, array<string, mixed> $config): void
```
Check for duplicate object loading.
If a duplicate is being loaded and has different configuration, that is bad and an exception will be raised.
An exception is raised, as replacing the object will not update any references other objects may have. Additionally, simply updating the runtime configuration is not a good option as we may be missing important constructor logic dependent on the configuration.
#### Parameters
`string` $name The name of the alias in the registry.
`array<string, mixed>` $config The config data for the new instance.
#### Returns
`void`
#### Throws
`RuntimeException`
When a duplicate is found. ### \_create() protected
```
_create(object|string $class, string $alias, array<string, mixed> $config): Cake\Cache\CacheEngine
```
Create the cache engine instance.
Part of the template method for Cake\Core\ObjectRegistry::load()
#### Parameters
`object|string` $class The classname or object to make.
`string` $alias The alias of the object.
`array<string, mixed>` $config An array of settings to use for the cache engine.
#### Returns
`Cake\Cache\CacheEngine`
#### Throws
`RuntimeException`
when an object doesn't implement the correct interface. ### \_resolveClassName() protected
```
_resolveClassName(string $class): string|null
```
Resolve a cache engine classname.
Part of the template method for Cake\Core\ObjectRegistry::load()
#### Parameters
`string` $class Partial classname to resolve.
#### Returns
`string|null`
### \_throwMissingClassError() protected
```
_throwMissingClassError(string $class, string|null $plugin): void
```
Throws an exception when a cache engine is missing.
Part of the template method for Cake\Core\ObjectRegistry::load()
#### Parameters
`string` $class The classname that is missing.
`string|null` $plugin The plugin the cache is missing in.
#### Returns
`void`
#### Throws
`BadMethodCallException`
### count() public
```
count(): int
```
Returns the number of loaded objects.
#### Returns
`int`
### get() public
```
get(string $name): object
```
Get loaded object instance.
#### Parameters
`string` $name Name of object.
#### Returns
`object`
#### Throws
`RuntimeException`
If not loaded or found. ### getIterator() public
```
getIterator(): Traversable
```
Returns an array iterator.
#### Returns
`Traversable`
### has() public
```
has(string $name): bool
```
Check whether a given object is loaded.
#### Parameters
`string` $name The object name to check for.
#### Returns
`bool`
### load() public
```
load(string $name, array<string, mixed> $config = []): mixed
```
Loads/constructs an object instance.
Will return the instance in the registry if it already exists. If a subclass provides event support, you can use `$config['enabled'] = false` to exclude constructed objects from being registered for events.
Using {@link \Cake\Controller\Component::$components} as an example. You can alias an object by setting the 'className' key, i.e.,
```
protected $components = [
'Email' => [
'className' => 'App\Controller\Component\AliasedEmailComponent'
];
];
```
All calls to the `Email` component would use `AliasedEmail` instead.
#### Parameters
`string` $name The name/class of the object to load.
`array<string, mixed>` $config optional Additional settings to use when loading the object.
#### Returns
`mixed`
#### Throws
`Exception`
If the class cannot be found. ### loaded() public
```
loaded(): array<string>
```
Get the list of loaded objects.
#### Returns
`array<string>`
### normalizeArray() public
```
normalizeArray(array $objects): array<string, array>
```
Normalizes an object array, creates an array that makes lazy loading easier
#### Parameters
`array` $objects Array of child objects to normalize.
#### Returns
`array<string, array>`
### reset() public
```
reset(): $this
```
Clear loaded instances in the registry.
If the registry subclass has an event manager, the objects will be detached from events as well.
#### Returns
`$this`
### set() public
```
set(string $name, object $object): $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
#### Parameters
`string` $name The name of the object to set in the registry.
`object` $object instance to store in the registry
#### Returns
`$this`
### unload() public
```
unload(string $name): $this
```
Remove a single adapter from the registry.
If this registry has an event manager, the object will be detached from any events as well.
#### Parameters
`string` $name The adapter name.
#### Returns
`$this`
Property Detail
---------------
### $\_loaded protected
Map of loaded objects.
#### Type
`array<object>`
cakephp Class CommandRunner Class CommandRunner
====================
Run CLI commands for the provided application.
**Namespace:** [Cake\Console](namespace-cake.console)
Property Summary
----------------
* [$\_eventClass](#%24_eventClass) protected `string` Default class name for new event objects.
* [$\_eventManager](#%24_eventManager) protected `Cake\Event\EventManagerInterface|null` Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
* [$aliases](#%24aliases) protected `array<string>` Alias mappings.
* [$app](#%24app) protected `Cake\Core\ConsoleApplicationInterface` The application console commands are being run for.
* [$factory](#%24factory) protected `Cake\Console\CommandFactoryInterface|null` The application console commands are being run for.
* [$root](#%24root) protected `string` The root command name. Defaults to `cake`.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [bootstrap()](#bootstrap()) protected
Application bootstrap wrapper.
* ##### [createCommand()](#createCommand()) protected
The wrapper for creating shell instances.
* ##### [dispatchEvent()](#dispatchEvent()) public
Wrapper for creating and dispatching events.
* ##### [getCommand()](#getCommand()) protected
Get the shell instance for a given command name
* ##### [getEventManager()](#getEventManager()) public
Get the application's event manager or the global one.
* ##### [loadRoutes()](#loadRoutes()) protected
Ensure that the application's routes are loaded.
* ##### [longestCommandName()](#longestCommandName()) protected
Build the longest command name that exists in the collection
* ##### [resolveName()](#resolveName()) protected
Resolve the command name into a name that exists in the collection.
* ##### [run()](#run()) public
Run the command contained in $argv.
* ##### [runCommand()](#runCommand()) protected
Execute a Command class.
* ##### [runShell()](#runShell()) protected
Execute a Shell class.
* ##### [setAliases()](#setAliases()) public
Replace the entire alias map for a runner.
* ##### [setEventManager()](#setEventManager()) public
Get/set the application's event manager.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Core\ConsoleApplicationInterface $app, string $root = 'cake', Cake\Console\CommandFactoryInterface|null $factory = null)
```
Constructor
#### Parameters
`Cake\Core\ConsoleApplicationInterface` $app The application to run CLI commands for.
`string` $root optional The root command name to be removed from argv.
`Cake\Console\CommandFactoryInterface|null` $factory optional Command factory instance.
### bootstrap() protected
```
bootstrap(): void
```
Application bootstrap wrapper.
Calls the application's `bootstrap()` hook. After the application the plugins are bootstrapped.
#### Returns
`void`
### createCommand() protected
```
createCommand(string $className, Cake\Console\ConsoleIo $io): Cake\Console\CommandInterfaceCake\Console\Shell
```
The wrapper for creating shell instances.
#### Parameters
`string` $className Shell class name.
`Cake\Console\ConsoleIo` $io The IO wrapper for the created shell class.
#### Returns
`Cake\Console\CommandInterfaceCake\Console\Shell`
### dispatchEvent() public
```
dispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\EventInterface
```
Wrapper for creating and dispatching events.
Returns a dispatched event.
#### Parameters
`string` $name Name of the event.
`array|null` $data optional Any value you wish to be transported with this event to it can be read by listeners.
`object|null` $subject optional The object that this event applies to ($this by default).
#### Returns
`Cake\Event\EventInterface`
### getCommand() protected
```
getCommand(Cake\Console\ConsoleIo $io, Cake\Console\CommandCollection $commands, string $name): Cake\Console\CommandInterfaceCake\Console\Shell
```
Get the shell instance for a given command name
#### Parameters
`Cake\Console\ConsoleIo` $io The IO wrapper for the created shell class.
`Cake\Console\CommandCollection` $commands The command collection to find the shell in.
`string` $name The command name to find
#### Returns
`Cake\Console\CommandInterfaceCake\Console\Shell`
### getEventManager() public
```
getEventManager(): Cake\Event\EventManagerInterface
```
Get the application's event manager or the global one.
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.
#### Returns
`Cake\Event\EventManagerInterface`
### loadRoutes() protected
```
loadRoutes(): void
```
Ensure that the application's routes are loaded.
Console commands and shells often need to generate URLs.
#### Returns
`void`
### longestCommandName() protected
```
longestCommandName(Cake\Console\CommandCollection $commands, array $argv): array
```
Build the longest command name that exists in the collection
Build the longest command name that matches a defined command. This will traverse a maximum of 3 tokens.
#### Parameters
`Cake\Console\CommandCollection` $commands The command collection to check.
`array` $argv The CLI arguments.
#### Returns
`array`
### resolveName() protected
```
resolveName(Cake\Console\CommandCollection $commands, Cake\Console\ConsoleIo $io, string|null $name): string
```
Resolve the command name into a name that exists in the collection.
Apply backwards compatible inflections and aliases. Will step forward up to 3 tokens in $argv to generate a command name in the CommandCollection. More specific command names take precedence over less specific ones.
#### Parameters
`Cake\Console\CommandCollection` $commands The command collection to check.
`Cake\Console\ConsoleIo` $io ConsoleIo object for errors.
`string|null` $name The name from the CLI args.
#### Returns
`string`
#### Throws
`Cake\Console\Exception\MissingOptionException`
### run() public
```
run(array $argv, Cake\Console\ConsoleIo|null $io = null): int
```
Run the command contained in $argv.
Use the application to do the following:
* Bootstrap the application
* Create the CommandCollection using the console() hook on the application.
* Trigger the `Console.buildCommands` event of auto-wiring plugins.
* Run the requested command.
#### Parameters
`array` $argv The arguments from the CLI environment.
`Cake\Console\ConsoleIo|null` $io optional The ConsoleIo instance. Used primarily for testing.
#### Returns
`int`
#### Throws
`RuntimeException`
### runCommand() protected
```
runCommand(Cake\Console\CommandInterface $command, array $argv, Cake\Console\ConsoleIo $io): int|null
```
Execute a Command class.
#### Parameters
`Cake\Console\CommandInterface` $command The command to run.
`array` $argv The CLI arguments to invoke.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`int|null`
### runShell() protected
```
runShell(Cake\Console\Shell $shell, array $argv): int|bool|null
```
Execute a Shell class.
#### Parameters
`Cake\Console\Shell` $shell The shell to run.
`array` $argv The CLI arguments to invoke.
#### Returns
`int|bool|null`
### setAliases() public
```
setAliases(array<string> $aliases): $this
```
Replace the entire alias map for a runner.
Aliases allow you to define alternate names for commands in the collection. This can be useful to add top level switches like `--version` or `-h`
### Usage
```
$runner->setAliases(['--version' => 'version']);
```
#### Parameters
`array<string>` $aliases The map of aliases to replace.
#### Returns
`$this`
### setEventManager() public
```
setEventManager(Cake\Event\EventManagerInterface $eventManager): $this
```
Get/set the application's event manager.
If the application does not support events and this method is used as a setter, an exception will be raised.
#### Parameters
`Cake\Event\EventManagerInterface` $eventManager The event manager to set.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
Property Detail
---------------
### $\_eventClass protected
Default class name for new event objects.
#### Type
`string`
### $\_eventManager protected
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
#### Type
`Cake\Event\EventManagerInterface|null`
### $aliases protected
Alias mappings.
#### Type
`array<string>`
### $app protected
The application console commands are being run for.
#### Type
`Cake\Core\ConsoleApplicationInterface`
### $factory protected
The application console commands are being run for.
#### Type
`Cake\Console\CommandFactoryInterface|null`
### $root protected
The root command name. Defaults to `cake`.
#### Type
`string`
cakephp Class File Class File
===========
Convenience class for reading, writing and appending to files.
**Namespace:** [Cake\Filesystem](namespace-cake.filesystem)
**Deprecated:** 4.0.0 Will be removed in 5.0.
Property Summary
----------------
* [$Folder](#%24Folder) public `Cake\Filesystem\Folder` Folder object of the file
* [$handle](#%24handle) public `resource|null` Holds the file handler resource if the file is opened
* [$info](#%24info) public `array<string, mixed>` File info
* [$lock](#%24lock) public `bool|null` Enable locking for file reading and writing
* [$name](#%24name) public `string` File name
* [$path](#%24path) public `string|null` Path property
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_destruct()](#__destruct()) public
Closes the current file if it is opened
* ##### [\_basename()](#_basename()) protected static
Returns the file basename. simulate the php basename() for multibyte (mb\_basename).
* ##### [append()](#append()) public
Append given data string to this file.
* ##### [clearStatCache()](#clearStatCache()) public
Clear PHP's internal stat cache
* ##### [close()](#close()) public
Closes the current file if it is opened.
* ##### [copy()](#copy()) public
Copy the File to $dest
* ##### [create()](#create()) public
Creates the file.
* ##### [delete()](#delete()) public
Deletes the file.
* ##### [executable()](#executable()) public
Returns true if the File is executable.
* ##### [exists()](#exists()) public
Returns true if the file exists.
* ##### [ext()](#ext()) public
Returns the file extension.
* ##### [folder()](#folder()) public
Returns the current folder.
* ##### [group()](#group()) public
Returns the file's group.
* ##### [info()](#info()) public
Returns the file info as an array with the following keys:
* ##### [lastAccess()](#lastAccess()) public
Returns last access time.
* ##### [lastChange()](#lastChange()) public
Returns last modified time.
* ##### [md5()](#md5()) public
Get md5 Checksum of file with previous check of Filesize
* ##### [mime()](#mime()) public
Gets the mime type of the file. Uses the finfo extension if it's available, otherwise falls back to mime\_content\_type().
* ##### [name()](#name()) public
Returns the file name without extension.
* ##### [offset()](#offset()) public
Sets or gets the offset for the currently opened file.
* ##### [open()](#open()) public
Opens the current file with a given $mode
* ##### [owner()](#owner()) public
Returns the file's owner.
* ##### [perms()](#perms()) public
Returns the "chmod" (permissions) of the file.
* ##### [prepare()](#prepare()) public static
Prepares an ASCII string for writing. Converts line endings to the correct terminator for the current platform. If Windows, "\r\n" will be used, all other platforms will use "\n"
* ##### [pwd()](#pwd()) public
Returns the full path of the file.
* ##### [read()](#read()) public
Return the contents of this file as a string.
* ##### [readable()](#readable()) public
Returns true if the file is readable.
* ##### [replaceText()](#replaceText()) public
Searches for a given text and replaces the text if found.
* ##### [safe()](#safe()) public
Makes file name safe for saving
* ##### [size()](#size()) public
Returns the file size
* ##### [writable()](#writable()) public
Returns true if the file is writable.
* ##### [write()](#write()) public
Write given data to this file.
Method Detail
-------------
### \_\_construct() public
```
__construct(string $path, bool $create = false, int $mode = 0755)
```
Constructor
#### Parameters
`string` $path Path to file
`bool` $create optional Create file if it does not exist (if true)
`int` $mode optional Mode to apply to the folder holding the file
#### Links
https://book.cakephp.org/4/en/core-libraries/file-folder.html#file-api
### \_\_destruct() public
```
__destruct()
```
Closes the current file if it is opened
### \_basename() protected static
```
_basename(string $path, string|null $ext = null): string
```
Returns the file basename. simulate the php basename() for multibyte (mb\_basename).
#### Parameters
`string` $path Path to file
`string|null` $ext optional The name of the extension
#### Returns
`string`
### append() public
```
append(string $data, bool $force = false): bool
```
Append given data string to this file.
#### Parameters
`string` $data Data to write
`bool` $force optional Force the file to open
#### Returns
`bool`
### clearStatCache() public
```
clearStatCache(bool $all = false): void
```
Clear PHP's internal stat cache
#### Parameters
`bool` $all optional Clear all cache or not. Passing false will clear the stat cache for the current path only.
#### Returns
`void`
### close() public
```
close(): bool
```
Closes the current file if it is opened.
#### Returns
`bool`
### copy() public
```
copy(string $dest, bool $overwrite = true): bool
```
Copy the File to $dest
#### Parameters
`string` $dest Absolute path to copy the file to.
`bool` $overwrite optional Overwrite $dest if exists
#### Returns
`bool`
### create() public
```
create(): bool
```
Creates the file.
#### Returns
`bool`
### delete() public
```
delete(): bool
```
Deletes the file.
#### Returns
`bool`
### executable() public
```
executable(): bool
```
Returns true if the File is executable.
#### Returns
`bool`
### exists() public
```
exists(): bool
```
Returns true if the file exists.
#### Returns
`bool`
### ext() public
```
ext(): string|false
```
Returns the file extension.
#### Returns
`string|false`
### folder() public
```
folder(): Cake\Filesystem\Folder
```
Returns the current folder.
#### Returns
`Cake\Filesystem\Folder`
### group() public
```
group(): int|false
```
Returns the file's group.
#### Returns
`int|false`
### info() public
```
info(): array<string, mixed>
```
Returns the file info as an array with the following keys:
* dirname
* basename
* extension
* filename
* filesize
* mime
#### Returns
`array<string, mixed>`
### lastAccess() public
```
lastAccess(): int|false
```
Returns last access time.
#### Returns
`int|false`
### lastChange() public
```
lastChange(): int|false
```
Returns last modified time.
#### Returns
`int|false`
### md5() public
```
md5(int|true $maxsize = 5): string|false
```
Get md5 Checksum of file with previous check of Filesize
#### Parameters
`int|true` $maxsize optional in MB or true to force
#### Returns
`string|false`
### mime() public
```
mime(): string|false
```
Gets the mime type of the file. Uses the finfo extension if it's available, otherwise falls back to mime\_content\_type().
#### Returns
`string|false`
### name() public
```
name(): string|false
```
Returns the file name without extension.
#### Returns
`string|false`
### offset() public
```
offset(int|false $offset = false, int $seek = SEEK_SET): int|bool
```
Sets or gets the offset for the currently opened file.
#### Parameters
`int|false` $offset optional The $offset in bytes to seek. If set to false then the current offset is returned.
`int` $seek optional PHP Constant SEEK\_SET | SEEK\_CUR | SEEK\_END determining what the $offset is relative to
#### Returns
`int|bool`
### open() public
```
open(string $mode = 'r', bool $force = false): bool
```
Opens the current file with a given $mode
#### Parameters
`string` $mode optional A valid 'fopen' mode string (r|w|a ...)
`bool` $force optional If true then the file will be re-opened even if its already opened, otherwise it won't
#### Returns
`bool`
### owner() public
```
owner(): int|false
```
Returns the file's owner.
#### Returns
`int|false`
### perms() public
```
perms(): string|false
```
Returns the "chmod" (permissions) of the file.
#### Returns
`string|false`
### prepare() public static
```
prepare(string $data, bool $forceWindows = false): string
```
Prepares an ASCII string for writing. Converts line endings to the correct terminator for the current platform. If Windows, "\r\n" will be used, all other platforms will use "\n"
#### Parameters
`string` $data Data to prepare for writing.
`bool` $forceWindows optional If true forces Windows new line string.
#### Returns
`string`
### pwd() public
```
pwd(): string|null
```
Returns the full path of the file.
#### Returns
`string|null`
### read() public
```
read(string|false $bytes = false, string $mode = 'rb', bool $force = false): string|false
```
Return the contents of this file as a string.
#### Parameters
`string|false` $bytes optional where to start
`string` $mode optional A `fread` compatible mode.
`bool` $force optional If true then the file will be re-opened even if its already opened, otherwise it won't
#### Returns
`string|false`
### readable() public
```
readable(): bool
```
Returns true if the file is readable.
#### Returns
`bool`
### replaceText() public
```
replaceText(array<string>|string $search, array<string>|string $replace): bool
```
Searches for a given text and replaces the text if found.
#### Parameters
`array<string>|string` $search Text(s) to search for.
`array<string>|string` $replace Text(s) to replace with.
#### Returns
`bool`
### safe() public
```
safe(string|null $name = null, string|null $ext = null): string
```
Makes file name safe for saving
#### Parameters
`string|null` $name optional The name of the file to make safe if different from $this->name
`string|null` $ext optional The name of the extension to make safe if different from $this->ext
#### Returns
`string`
### size() public
```
size(): int|false
```
Returns the file size
#### Returns
`int|false`
### writable() public
```
writable(): bool
```
Returns true if the file is writable.
#### Returns
`bool`
### write() public
```
write(string $data, string $mode = 'w', bool $force = false): bool
```
Write given data to this file.
#### Parameters
`string` $data Data to write to this File.
`string` $mode optional Mode of writing. {@link <https://secure.php.net/fwrite> See fwrite()}.
`bool` $force optional Force the file to open
#### Returns
`bool`
Property Detail
---------------
### $Folder public
Folder object of the file
#### Type
`Cake\Filesystem\Folder`
### $handle public
Holds the file handler resource if the file is opened
#### Type
`resource|null`
### $info public
File info
#### Type
`array<string, mixed>`
### $lock public
Enable locking for file reading and writing
#### Type
`bool|null`
### $name public
File name
#### Type
`string`
### $path public
Path property
Current file's absolute path
#### Type
`string|null`
| programming_docs |
cakephp Class InvalidCsrfTokenException Class InvalidCsrfTokenException
================================
Represents an HTTP 403 error caused by an invalid CSRF token
**Namespace:** [Cake\Http\Exception](namespace-cake.http.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
* [$headers](#%24headers) protected `array<string, mixed>`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [getHeaders()](#getHeaders()) public
Returns array of response headers.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
* ##### [setHeader()](#setHeader()) public
Set a single HTTP response header.
* ##### [setHeaders()](#setHeaders()) public
Sets HTTP response headers.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $message = null, int|null $code = null, Throwable|null $previous = null)
```
Constructor
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`string|null` $message optional If no message is given 'Invalid CSRF Token' will be the message
`int|null` $code optional Status code, defaults to 403
`Throwable|null` $previous optional The previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### getHeaders() public
```
getHeaders(): array<string, mixed>
```
Returns array of response headers.
#### Returns
`array<string, mixed>`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
### setHeader() public
```
setHeader(string $header, array<string>|string|null $value = null): void
```
Set a single HTTP response header.
#### Parameters
`string` $header Header name
`array<string>|string|null` $value optional Header value
#### Returns
`void`
### setHeaders() public
```
setHeaders(array<string, mixed> $headers): void
```
Sets HTTP response headers.
#### Parameters
`array<string, mixed>` $headers Array of header name and value pairs.
#### Returns
`void`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
### $headers protected
#### Type
`array<string, mixed>`
cakephp Class PHPUnitExtension Class PHPUnitExtension
=======================
PHPUnit extension to integrate CakePHP's data-only fixtures.
**Namespace:** [Cake\TestSuite\Fixture](namespace-cake.testsuite.fixture)
Method Summary
--------------
* ##### [executeBeforeFirstTest()](#executeBeforeFirstTest()) public
Initializes before any tests are run.
Method Detail
-------------
### executeBeforeFirstTest() public
```
executeBeforeFirstTest(): void
```
Initializes before any tests are run.
#### Returns
`void`
cakephp Class TimeHelper Class TimeHelper
=================
Time Helper class for easy use of time data.
Manipulation of time data.
**Namespace:** [Cake\View\Helper](namespace-cake.view.helper)
**See:** \Cake\I18n\Time
**Link:** https://book.cakephp.org/4/en/views/helpers/time.html
Property Summary
----------------
* [$\_View](#%24_View) protected `Cake\View\View` The View instance this helper is attached to
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Config options
* [$\_helperMap](#%24_helperMap) protected `array<string, array>` A helper lookup table used to lazy load helper objects.
* [$\_templater](#%24_templater) protected `Cake\View\StringTemplate|null` StringTemplate instance.
* [$helpers](#%24helpers) protected `array` List of helpers used by this helper
Method Summary
--------------
* ##### [\_\_call()](#__call()) public
Provide non fatal errors on missing method calls.
* ##### [\_\_construct()](#__construct()) public
Default Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_get()](#__get()) public
Lazy loads helpers.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_confirm()](#_confirm()) protected
Returns a string to be used as onclick handler for confirm dialogs.
* ##### [\_getTimezone()](#_getTimezone()) protected
Get a timezone.
* ##### [addClass()](#addClass()) public
Adds the given class to the element options
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [format()](#format()) public
Returns a formatted date string, given either a Time instance, UNIX timestamp or a valid strtotime() date string.
* ##### [formatTemplate()](#formatTemplate()) public
Formats a template string with $data
* ##### [fromString()](#fromString()) public
Returns a UNIX timestamp, given either a UNIX timestamp or a valid strtotime() date string.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getTemplates()](#getTemplates()) public
Gets templates to use or a specific template.
* ##### [getView()](#getView()) public
Get the view instance this helper is bound to.
* ##### [gmt()](#gmt()) public
Returns gmt as a UNIX timestamp.
* ##### [i18nFormat()](#i18nFormat()) public
Returns a formatted date string, given either a Datetime instance, UNIX timestamp or a valid strtotime() date string.
* ##### [implementedEvents()](#implementedEvents()) public
Event listeners.
* ##### [initialize()](#initialize()) public
Constructor hook method.
* ##### [isFuture()](#isFuture()) public
Returns true, if the given datetime string is in the future.
* ##### [isPast()](#isPast()) public
Returns true, if the given datetime string is in the past.
* ##### [isThisMonth()](#isThisMonth()) public
Returns true if given datetime string is within this month
* ##### [isThisWeek()](#isThisWeek()) public
Returns true if given datetime string is within this week.
* ##### [isThisYear()](#isThisYear()) public
Returns true if given datetime string is within the current year.
* ##### [isToday()](#isToday()) public
Returns true, if the given datetime string is today.
* ##### [isTomorrow()](#isTomorrow()) public
Returns true if given datetime string is tomorrow.
* ##### [isWithinNext()](#isWithinNext()) public
Returns true if specified datetime is within the interval specified, else false.
* ##### [nice()](#nice()) public
Returns a nicely formatted date string for given Datetime string.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setTemplates()](#setTemplates()) public
Sets templates to use.
* ##### [templater()](#templater()) public
Returns the templater instance.
* ##### [timeAgoInWords()](#timeAgoInWords()) public
Formats a date into a phrase expressing the relative time.
* ##### [toAtom()](#toAtom()) public
Returns a date formatted for Atom RSS feeds.
* ##### [toQuarter()](#toQuarter()) public
Returns the quarter
* ##### [toRss()](#toRss()) public
Formats date for RSS feeds
* ##### [toUnix()](#toUnix()) public
Returns a UNIX timestamp from a textual datetime description.
* ##### [wasWithinLast()](#wasWithinLast()) public
Returns true if specified datetime was within the interval specified, else false.
* ##### [wasYesterday()](#wasYesterday()) public
Returns true if given datetime string was yesterday.
Method Detail
-------------
### \_\_call() public
```
__call(string $method, array $params): mixed|void
```
Provide non fatal errors on missing method calls.
#### Parameters
`string` $method Method to invoke
`array` $params Array of params for the method.
#### Returns
`mixed|void`
### \_\_construct() public
```
__construct(Cake\View\View $view, array<string, mixed> $config = [])
```
Default Constructor
#### Parameters
`Cake\View\View` $view The View this helper is being attached to.
`array<string, mixed>` $config optional Configuration settings for the helper.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): Cake\View\Helper|null|void
```
Lazy loads helpers.
#### Parameters
`string` $name Name of the property being accessed.
#### Returns
`Cake\View\Helper|null|void`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_confirm() protected
```
_confirm(string $okCode, string $cancelCode): string
```
Returns a string to be used as onclick handler for confirm dialogs.
#### Parameters
`string` $okCode Code to be executed after user chose 'OK'
`string` $cancelCode Code to be executed after user chose 'Cancel'
#### Returns
`string`
### \_getTimezone() protected
```
_getTimezone(DateTimeZone|string|null $timezone): DateTimeZone|string|null
```
Get a timezone.
Will use the provided timezone, or default output timezone if defined.
#### Parameters
`DateTimeZone|string|null` $timezone The override timezone if applicable.
#### Returns
`DateTimeZone|string|null`
### addClass() public
```
addClass(array<string, mixed> $options, string $class, string $key = 'class'): array<string, mixed>
```
Adds the given class to the element options
#### Parameters
`array<string, mixed>` $options Array options/attributes to add a class to
`string` $class The class name being added.
`string` $key optional the key to use for class. Defaults to `'class'`.
#### Returns
`array<string, mixed>`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### format() public
```
format(DateTimeInterface|string|int|null $date, string|int|null $format = null, string|false $invalid = false, DateTimeZone|string|null $timezone = null): string|int|false
```
Returns a formatted date string, given either a Time instance, UNIX timestamp or a valid strtotime() date string.
This method is an alias for TimeHelper::i18nFormat().
#### Parameters
`DateTimeInterface|string|int|null` $date UNIX timestamp, strtotime() valid string or DateTime object (or a date format string).
`string|int|null` $format optional date format string (or a UNIX timestamp, `strtotime()` valid string or DateTime object).
`string|false` $invalid optional Default value to display on invalid dates
`DateTimeZone|string|null` $timezone optional User's timezone string or DateTimeZone object
#### Returns
`string|int|false`
#### See Also
\Cake\I18n\Time::i18nFormat() ### formatTemplate() public
```
formatTemplate(string $name, array<string, mixed> $data): string
```
Formats a template string with $data
#### Parameters
`string` $name The template name.
`array<string, mixed>` $data The data to insert.
#### Returns
`string`
### fromString() public
```
fromString(DateTimeInterface|string|int $dateString, DateTimeZone|string|null $timezone = null): Cake\I18n\FrozenTime
```
Returns a UNIX timestamp, given either a UNIX timestamp or a valid strtotime() date string.
#### Parameters
`DateTimeInterface|string|int` $dateString UNIX timestamp, strtotime() valid string or DateTime object
`DateTimeZone|string|null` $timezone optional User's timezone string or DateTimeZone object
#### Returns
`Cake\I18n\FrozenTime`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getTemplates() public
```
getTemplates(string|null $template = null): array|string
```
Gets templates to use or a specific template.
#### Parameters
`string|null` $template optional String for reading a specific template, null for all.
#### Returns
`array|string`
### getView() public
```
getView(): Cake\View\View
```
Get the view instance this helper is bound to.
#### Returns
`Cake\View\View`
### gmt() public
```
gmt(DateTimeInterface|string|int|null $string = null): string
```
Returns gmt as a UNIX timestamp.
#### Parameters
`DateTimeInterface|string|int|null` $string optional UNIX timestamp, strtotime() valid string or DateTime object
#### Returns
`string`
#### See Also
\Cake\I18n\Time::gmt() ### i18nFormat() public
```
i18nFormat(DateTimeInterface|string|int|null $date, string|int|null $format = null, string|false $invalid = false, DateTimeZone|string|null $timezone = null): string|int|false
```
Returns a formatted date string, given either a Datetime instance, UNIX timestamp or a valid strtotime() date string.
#### Parameters
`DateTimeInterface|string|int|null` $date UNIX timestamp, strtotime() valid string or DateTime object
`string|int|null` $format optional Intl compatible format string.
`string|false` $invalid optional Default value to display on invalid dates
`DateTimeZone|string|null` $timezone optional User's timezone string or DateTimeZone object
#### Returns
`string|int|false`
#### Throws
`Exception`
When the date cannot be parsed #### See Also
\Cake\I18n\Time::i18nFormat() ### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Event listeners.
By defining one of the callback methods a helper is assumed to be interested in the related event.
Override this method if you need to add non-conventional event listeners. Or if you want helpers to listen to non-standard events.
#### Returns
`array<string, mixed>`
### initialize() public
```
initialize(array<string, mixed> $config): void
```
Constructor hook method.
Implement this method to avoid having to overwrite the constructor and call parent.
#### Parameters
`array<string, mixed>` $config The configuration settings provided to this helper.
#### Returns
`void`
### isFuture() public
```
isFuture(DateTimeInterface|string|int $dateString, DateTimeZone|string|null $timezone = null): bool
```
Returns true, if the given datetime string is in the future.
#### Parameters
`DateTimeInterface|string|int` $dateString UNIX timestamp, strtotime() valid string or DateTime object
`DateTimeZone|string|null` $timezone optional User's timezone string or DateTimeZone object
#### Returns
`bool`
### isPast() public
```
isPast(DateTimeInterface|string|int $dateString, DateTimeZone|string|null $timezone = null): bool
```
Returns true, if the given datetime string is in the past.
#### Parameters
`DateTimeInterface|string|int` $dateString UNIX timestamp, strtotime() valid string or DateTime object
`DateTimeZone|string|null` $timezone optional User's timezone string or DateTimeZone object
#### Returns
`bool`
### isThisMonth() public
```
isThisMonth(DateTimeInterface|string|int $dateString, DateTimeZone|string|null $timezone = null): bool
```
Returns true if given datetime string is within this month
#### Parameters
`DateTimeInterface|string|int` $dateString UNIX timestamp, strtotime() valid string or DateTime object
`DateTimeZone|string|null` $timezone optional User's timezone string or DateTimeZone object
#### Returns
`bool`
### isThisWeek() public
```
isThisWeek(DateTimeInterface|string|int $dateString, DateTimeZone|string|null $timezone = null): bool
```
Returns true if given datetime string is within this week.
#### Parameters
`DateTimeInterface|string|int` $dateString UNIX timestamp, strtotime() valid string or DateTime object
`DateTimeZone|string|null` $timezone optional User's timezone string or DateTimeZone object
#### Returns
`bool`
### isThisYear() public
```
isThisYear(DateTimeInterface|string|int $dateString, DateTimeZone|string|null $timezone = null): bool
```
Returns true if given datetime string is within the current year.
#### Parameters
`DateTimeInterface|string|int` $dateString UNIX timestamp, strtotime() valid string or DateTime object
`DateTimeZone|string|null` $timezone optional User's timezone string or DateTimeZone object
#### Returns
`bool`
### isToday() public
```
isToday(DateTimeInterface|string|int $dateString, DateTimeZone|string|null $timezone = null): bool
```
Returns true, if the given datetime string is today.
#### Parameters
`DateTimeInterface|string|int` $dateString UNIX timestamp, strtotime() valid string or DateTime object
`DateTimeZone|string|null` $timezone optional User's timezone string or DateTimeZone object
#### Returns
`bool`
### isTomorrow() public
```
isTomorrow(DateTimeInterface|string|int $dateString, DateTimeZone|string|null $timezone = null): bool
```
Returns true if given datetime string is tomorrow.
#### Parameters
`DateTimeInterface|string|int` $dateString UNIX timestamp, strtotime() valid string or DateTime object
`DateTimeZone|string|null` $timezone optional User's timezone string or DateTimeZone object
#### Returns
`bool`
### isWithinNext() public
```
isWithinNext(string $timeInterval, DateTimeInterface|string|int $dateString, DateTimeZone|string|null $timezone = null): bool
```
Returns true if specified datetime is within the interval specified, else false.
#### Parameters
`string` $timeInterval the numeric value with space then time type. Example of valid types: 6 hours, 2 days, 1 minute.
`DateTimeInterface|string|int` $dateString UNIX timestamp, strtotime() valid string or DateTime object
`DateTimeZone|string|null` $timezone optional User's timezone string or DateTimeZone object
#### Returns
`bool`
#### See Also
\Cake\I18n\Time::wasWithinLast() ### nice() public
```
nice(DateTimeInterface|string|int|null $dateString = null, DateTimeZone|string|null $timezone = null, string|null $locale = null): string
```
Returns a nicely formatted date string for given Datetime string.
#### Parameters
`DateTimeInterface|string|int|null` $dateString optional UNIX timestamp, strtotime() valid string or DateTime object
`DateTimeZone|string|null` $timezone optional User's timezone string or DateTimeZone object
`string|null` $locale optional Locale string.
#### Returns
`string`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setTemplates() public
```
setTemplates(array<string> $templates): $this
```
Sets templates to use.
#### Parameters
`array<string>` $templates Templates to be added.
#### Returns
`$this`
### templater() public
```
templater(): Cake\View\StringTemplate
```
Returns the templater instance.
#### Returns
`Cake\View\StringTemplate`
### timeAgoInWords() public
```
timeAgoInWords(DateTimeInterface|string|int $dateTime, array<string, mixed> $options = []): string
```
Formats a date into a phrase expressing the relative time.
### Additional options
* `element` - The element to wrap the formatted time in. Has a few additional options:
+ `tag` - The tag to use, defaults to 'span'.
+ `class` - The class name to use, defaults to `time-ago-in-words`.
+ `title` - Defaults to the $dateTime input.
#### Parameters
`DateTimeInterface|string|int` $dateTime UNIX timestamp, strtotime() valid string or DateTime object.
`array<string, mixed>` $options optional Default format if timestamp is used in $dateString
#### Returns
`string`
#### See Also
\Cake\I18n\Time::timeAgoInWords() ### toAtom() public
```
toAtom(DateTimeInterface|string|int $dateString, DateTimeZone|string|null $timezone = null): string
```
Returns a date formatted for Atom RSS feeds.
#### Parameters
`DateTimeInterface|string|int` $dateString UNIX timestamp, strtotime() valid string or DateTime object
`DateTimeZone|string|null` $timezone optional User's timezone string or DateTimeZone object
#### Returns
`string`
#### See Also
\Cake\I18n\Time::toAtom() ### toQuarter() public
```
toQuarter(DateTimeInterface|string|int $dateString, bool $range = false): array<string>|int
```
Returns the quarter
#### Parameters
`DateTimeInterface|string|int` $dateString UNIX timestamp, strtotime() valid string or DateTime object
`bool` $range optional if true returns a range in Y-m-d format
#### Returns
`array<string>|int`
#### See Also
\Cake\I18n\Time::toQuarter() ### toRss() public
```
toRss(DateTimeInterface|string|int $dateString, DateTimeZone|string|null $timezone = null): string
```
Formats date for RSS feeds
#### Parameters
`DateTimeInterface|string|int` $dateString UNIX timestamp, strtotime() valid string or DateTime object
`DateTimeZone|string|null` $timezone optional User's timezone string or DateTimeZone object
#### Returns
`string`
### toUnix() public
```
toUnix(DateTimeInterface|string|int $dateString, DateTimeZone|string|null $timezone = null): string
```
Returns a UNIX timestamp from a textual datetime description.
#### Parameters
`DateTimeInterface|string|int` $dateString UNIX timestamp, strtotime() valid string or DateTime object
`DateTimeZone|string|null` $timezone optional User's timezone string or DateTimeZone object
#### Returns
`string`
#### See Also
\Cake\I18n\Time::toUnix() ### wasWithinLast() public
```
wasWithinLast(string $timeInterval, DateTimeInterface|string|int $dateString, DateTimeZone|string|null $timezone = null): bool
```
Returns true if specified datetime was within the interval specified, else false.
#### Parameters
`string` $timeInterval the numeric value with space then time type. Example of valid types: 6 hours, 2 days, 1 minute.
`DateTimeInterface|string|int` $dateString UNIX timestamp, strtotime() valid string or DateTime object
`DateTimeZone|string|null` $timezone optional User's timezone string or DateTimeZone object
#### Returns
`bool`
#### See Also
\Cake\I18n\Time::wasWithinLast() ### wasYesterday() public
```
wasYesterday(DateTimeInterface|string|int $dateString, DateTimeZone|string|null $timezone = null): bool
```
Returns true if given datetime string was yesterday.
#### Parameters
`DateTimeInterface|string|int` $dateString UNIX timestamp, strtotime() valid string or DateTime object
`DateTimeZone|string|null` $timezone optional User's timezone string or DateTimeZone object
#### Returns
`bool`
Property Detail
---------------
### $\_View protected
The View instance this helper is attached to
#### Type
`Cake\View\View`
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Config options
#### Type
`array<string, mixed>`
### $\_helperMap protected
A helper lookup table used to lazy load helper objects.
#### Type
`array<string, array>`
### $\_templater protected
StringTemplate instance.
#### Type
`Cake\View\StringTemplate|null`
### $helpers protected
List of helpers used by this helper
#### Type
`array`
| programming_docs |
cakephp Class ValidCount Class ValidCount
=================
Validates the count of associated records.
**Namespace:** [Cake\ORM\Rule](namespace-cake.orm.rule)
Property Summary
----------------
* [$\_field](#%24_field) protected `string` The field to check
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_\_invoke()](#__invoke()) public
Performs the count check
Method Detail
-------------
### \_\_construct() public
```
__construct(string $field)
```
Constructor.
#### Parameters
`string` $field The field to check the count on.
### \_\_invoke() public
```
__invoke(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options): bool
```
Performs the count check
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity from where to extract the fields.
`array<string, mixed>` $options Options passed to the check.
#### Returns
`bool`
Property Detail
---------------
### $\_field protected
The field to check
#### Type
`string`
cakephp Namespace Auth Namespace Auth
==============
### Classes
* ##### [Basic](class-cake.http.client.auth.basic)
Basic authentication adapter for Cake\Http\Client
* ##### [Digest](class-cake.http.client.auth.digest)
Digest authentication adapter for Cake\Http\Client
* ##### [Oauth](class-cake.http.client.auth.oauth)
Oauth 1 authentication strategy for Cake\Http\Client
cakephp Class SessionCsrfProtectionMiddleware Class SessionCsrfProtectionMiddleware
======================================
Provides CSRF protection via session based tokens.
This middleware adds a CSRF token to the session. Each request must contain a token in request data, or the X-CSRF-Token header on each PATCH, POST, PUT, or DELETE request. This follows a 'synchronizer token' pattern.
If the request data is missing or does not match the session data, an InvalidCsrfTokenException will be raised.
This middleware integrates with the FormHelper automatically and when used together your forms will have CSRF tokens automatically added when `$this->Form->create(...)` is used in a view.
If you use this middleware *do not* also use CsrfProtectionMiddleware.
**Namespace:** [Cake\Http\Middleware](namespace-cake.http.middleware)
**See:** https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site\_Request\_Forgery\_Prevention\_Cheat\_Sheet.html#synchronizer-token-pattern
Constants
---------
* `int` **TOKEN\_VALUE\_LENGTH**
```
32
```
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Config for the CSRF handling.
* [$skipCheckCallback](#%24skipCheckCallback) protected `callable|null` Callback for deciding whether to skip the token check for particular request.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [createToken()](#createToken()) public
Create a new token to be used for CSRF protection
* ##### [process()](#process()) public
Checks and sets the CSRF token depending on the HTTP verb.
* ##### [saltToken()](#saltToken()) public
Apply entropy to a CSRF token
* ##### [skipCheckCallback()](#skipCheckCallback()) public
Set callback for allowing to skip token check for particular request.
* ##### [unsaltToken()](#unsaltToken()) protected
Remove the salt from a CSRF token.
* ##### [unsetTokenField()](#unsetTokenField()) protected
Remove CSRF protection token from request data.
* ##### [validateToken()](#validateToken()) protected
Validate the request data against the cookie token.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Constructor
#### Parameters
`array<string, mixed>` $config optional Config options. See $\_config for valid keys.
### createToken() public
```
createToken(): string
```
Create a new token to be used for CSRF protection
This token is a simple unique random value as the compare value is stored in the session where it cannot be tampered with.
#### Returns
`string`
### process() public
```
process(ServerRequestInterface $request, RequestHandlerInterface $handler): Psr\Http\Message\ResponseInterface
```
Checks and sets the CSRF token depending on the HTTP verb.
Processes an incoming server request in order to produce a response. If unable to produce the response itself, it may delegate to the provided request handler to do so.
#### Parameters
`ServerRequestInterface` $request The request.
`RequestHandlerInterface` $handler The request handler.
#### Returns
`Psr\Http\Message\ResponseInterface`
### saltToken() public
```
saltToken(string $token): string
```
Apply entropy to a CSRF token
To avoid BREACH apply a random salt value to a token When the token is compared to the session the token needs to be unsalted.
#### Parameters
`string` $token The token to salt.
#### Returns
`string`
### skipCheckCallback() public
```
skipCheckCallback(callable $callback): $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.
#### Parameters
`callable` $callback A callable.
#### Returns
`$this`
### unsaltToken() protected
```
unsaltToken(string $token): string
```
Remove the salt from a CSRF token.
If the token is not TOKEN\_VALUE\_LENGTH \* 2 it is an old unsalted value that is supported for backwards compatibility.
#### Parameters
`string` $token The token that could be salty.
#### Returns
`string`
### unsetTokenField() protected
```
unsetTokenField(Psr\Http\Message\ServerRequestInterface $request): Psr\Http\Message\ServerRequestInterface
```
Remove CSRF protection token from request data.
This ensures that the token does not cause failures during form tampering protection.
#### Parameters
`Psr\Http\Message\ServerRequestInterface` $request The request object.
#### Returns
`Psr\Http\Message\ServerRequestInterface`
### validateToken() protected
```
validateToken(Psr\Http\Message\ServerRequestInterface $request, Cake\Http\Session $session): void
```
Validate the request data against the cookie token.
#### Parameters
`Psr\Http\Message\ServerRequestInterface` $request The request to validate against.
`Cake\Http\Session` $session The session instance.
#### Returns
`void`
#### Throws
`Cake\Http\Exception\InvalidCsrfTokenException`
When the CSRF token is invalid or missing. Property Detail
---------------
### $\_config protected
Config for the CSRF handling.
* `key` The session key to use. Defaults to `csrfToken`
+ `field` The form field to check. Changing this will also require configuring FormHelper.
#### Type
`array<string, mixed>`
### $skipCheckCallback protected
Callback for deciding whether to skip the token check for particular request.
CSRF protection token check will be skipped if the callback returns `true`.
#### Type
`callable|null`
cakephp Class PropertyNode Class PropertyNode
===================
Dump node for object properties.
**Namespace:** [Cake\Error\Debug](namespace-cake.error.debug)
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getChildren()](#getChildren()) public
Get the child nodes of this node.
* ##### [getName()](#getName()) public
Get the property name
* ##### [getValue()](#getValue()) public
Get the value
* ##### [getVisibility()](#getVisibility()) public
Get the property visibility
Method Detail
-------------
### \_\_construct() public
```
__construct(string $name, string|null $visibility, Cake\Error\Debug\NodeInterface $value)
```
Constructor
#### Parameters
`string` $name The property name
`string|null` $visibility The visibility of the property.
`Cake\Error\Debug\NodeInterface` $value The property value node.
### getChildren() public
```
getChildren(): arrayCake\Error\Debug\NodeInterface>
```
Get the child nodes of this node.
#### Returns
`arrayCake\Error\Debug\NodeInterface>`
### getName() public
```
getName(): string
```
Get the property name
#### Returns
`string`
### getValue() public
```
getValue(): Cake\Error\Debug\NodeInterface
```
Get the value
#### Returns
`Cake\Error\Debug\NodeInterface`
### getVisibility() public
```
getVisibility(): string
```
Get the property visibility
#### Returns
`string`
cakephp Class ValueBinder Class ValueBinder
==================
Value binder class manages list of values bound to conditions.
**Namespace:** [Cake\Database](namespace-cake.database)
Property Summary
----------------
* [$\_bindings](#%24_bindings) protected `array` Array containing a list of bound values to the conditions on this object. Each array entry is another array structure containing the actual bound value, its type and the placeholder it is bound to.
* [$\_bindingsCount](#%24_bindingsCount) protected `int` A counter of the number of parameters bound in this expression object
Method Summary
--------------
* ##### [attachTo()](#attachTo()) public
Binds all the stored values in this object to the passed statement.
* ##### [bind()](#bind()) public
Associates a query placeholder to a value and a type
* ##### [bindings()](#bindings()) public
Returns all values bound to this expression object at this nesting level. Subexpression bound values will not be returned with this function.
* ##### [generateManyNamed()](#generateManyNamed()) public
Creates unique named placeholders for each of the passed values and binds them with the specified type.
* ##### [placeholder()](#placeholder()) public
Creates a unique placeholder name if the token provided does not start with ":" otherwise, it will return the same string and internally increment the number of placeholders generated by this object.
* ##### [reset()](#reset()) public
Clears any bindings that were previously registered
* ##### [resetCount()](#resetCount()) public
Resets the bindings count without clearing previously bound values
Method Detail
-------------
### attachTo() public
```
attachTo(Cake\Database\StatementInterface $statement): void
```
Binds all the stored values in this object to the passed statement.
#### Parameters
`Cake\Database\StatementInterface` $statement The statement to add parameters to.
#### Returns
`void`
### bind() public
```
bind(string|int $param, mixed $value, string|int|null $type = null): void
```
Associates a query placeholder to a value and a type
#### Parameters
`string|int` $param placeholder to be replaced with quoted version of $value
`mixed` $value The value to be bound
`string|int|null` $type optional the mapped type name, used for casting when sending to database
#### Returns
`void`
### bindings() public
```
bindings(): array
```
Returns all values bound to this expression object at this nesting level. Subexpression bound values will not be returned with this function.
#### Returns
`array`
### generateManyNamed() public
```
generateManyNamed(iterable $values, string|int|null $type = null): array
```
Creates unique named placeholders for each of the passed values and binds them with the specified type.
#### Parameters
`iterable` $values The list of values to be bound
`string|int|null` $type optional The type with which all values will be bound
#### Returns
`array`
### placeholder() public
```
placeholder(string $token): string
```
Creates a unique placeholder name if the token provided does not start with ":" otherwise, it will return the same string and internally increment the number of placeholders generated by this object.
#### Parameters
`string` $token string from which the placeholder will be derived from, if it starts with a colon, then the same string is returned
#### Returns
`string`
### reset() public
```
reset(): void
```
Clears any bindings that were previously registered
#### Returns
`void`
### resetCount() public
```
resetCount(): void
```
Resets the bindings count without clearing previously bound values
#### Returns
`void`
Property Detail
---------------
### $\_bindings protected
Array containing a list of bound values to the conditions on this object. Each array entry is another array structure containing the actual bound value, its type and the placeholder it is bound to.
#### Type
`array`
### $\_bindingsCount protected
A counter of the number of parameters bound in this expression object
#### Type
`int`
cakephp Class FormDataPart Class FormDataPart
===================
Contains the data and behavior for a single part in a Multipart FormData request body.
Added to Cake\Http\Client\FormData when sending data to a remote server.
**Namespace:** [Cake\Http\Client](namespace-cake.http.client)
Property Summary
----------------
* [$\_charset](#%24_charset) protected `string|null` The charset attribute for the Content-Disposition header fields
* [$\_contentId](#%24_contentId) protected `string|null` The contentId for the part
* [$\_disposition](#%24_disposition) protected `string` Disposition to send
* [$\_filename](#%24_filename) protected `string|null` Filename to send if using files.
* [$\_name](#%24_name) protected `string` Name of the value.
* [$\_transferEncoding](#%24_transferEncoding) protected `string|null` The encoding used in this part.
* [$\_type](#%24_type) protected `string|null` Content type to use
* [$\_value](#%24_value) protected `string` Value to send.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_toString()](#__toString()) public
Convert the part into a string.
* ##### [\_headerParameterToString()](#_headerParameterToString()) protected
Get the string for the header parameter.
* ##### [contentId()](#contentId()) public
Get/set the contentId for a part.
* ##### [disposition()](#disposition()) public
Get/set the disposition type
* ##### [filename()](#filename()) public
Get/set the filename.
* ##### [name()](#name()) public
Get the part name.
* ##### [transferEncoding()](#transferEncoding()) public
Set the transfer-encoding for multipart.
* ##### [type()](#type()) public
Get/set the content type.
* ##### [value()](#value()) public
Get the value.
Method Detail
-------------
### \_\_construct() public
```
__construct(string $name, string $value, string $disposition = 'form-data', string|null $charset = null)
```
Constructor
#### Parameters
`string` $name The name of the data.
`string` $value The value of the data.
`string` $disposition optional The type of disposition to use, defaults to form-data.
`string|null` $charset optional The charset of the data.
### \_\_toString() public
```
__toString(): string
```
Convert the part into a string.
Creates a string suitable for use in HTTP requests.
#### Returns
`string`
### \_headerParameterToString() protected
```
_headerParameterToString(string $name, string $value): string
```
Get the string for the header parameter.
If the value contains non-ASCII letters an additional header indicating the charset encoding will be set.
#### Parameters
`string` $name The name of the header parameter
`string` $value The value of the header parameter
#### Returns
`string`
### contentId() public
```
contentId(string|null $id = null): string|null
```
Get/set the contentId for a part.
#### Parameters
`string|null` $id optional The content id.
#### Returns
`string|null`
### disposition() public
```
disposition(string|null $disposition = null): string
```
Get/set the disposition type
By passing in `false` you can disable the disposition header from being added.
#### Parameters
`string|null` $disposition optional Use null to get/string to set.
#### Returns
`string`
### filename() public
```
filename(string|null $filename = null): string|null
```
Get/set the filename.
Setting the filename to `false` will exclude it from the generated output.
#### Parameters
`string|null` $filename optional Use null to get/string to set.
#### Returns
`string|null`
### name() public
```
name(): string
```
Get the part name.
#### Returns
`string`
### transferEncoding() public
```
transferEncoding(string|null $type): string|null
```
Set the transfer-encoding for multipart.
Useful when content bodies are in encodings like base64.
#### Parameters
`string|null` $type The type of encoding the value has.
#### Returns
`string|null`
### type() public
```
type(string|null $type): string|null
```
Get/set the content type.
#### Parameters
`string|null` $type Use null to get/string to set.
#### Returns
`string|null`
### value() public
```
value(): string
```
Get the value.
#### Returns
`string`
Property Detail
---------------
### $\_charset protected
The charset attribute for the Content-Disposition header fields
#### Type
`string|null`
### $\_contentId protected
The contentId for the part
#### Type
`string|null`
### $\_disposition protected
Disposition to send
#### Type
`string`
### $\_filename protected
Filename to send if using files.
#### Type
`string|null`
### $\_name protected
Name of the value.
#### Type
`string`
### $\_transferEncoding protected
The encoding used in this part.
#### Type
`string|null`
### $\_type protected
Content type to use
#### Type
`string|null`
### $\_value protected
Value to send.
#### Type
`string`
cakephp Class BelongsToMany Class BelongsToMany
====================
Represents an M - N relationship where there exists a junction - or join - table that contains the association fields between the source and the target table.
An example of a BelongsToMany association would be Article belongs to many Tags. In this example 'Article' is the source table and 'Tags' is the target table.
**Namespace:** [Cake\ORM\Association](namespace-cake.orm.association)
Constants
---------
* `string` **MANY\_TO\_MANY**
```
'manyToMany'
```
Association type for many to many associations.
* `string` **MANY\_TO\_ONE**
```
'manyToOne'
```
Association type for many to one associations.
* `string` **ONE\_TO\_MANY**
```
'oneToMany'
```
Association type for one to many associations.
* `string` **ONE\_TO\_ONE**
```
'oneToOne'
```
Association type for one to one associations.
* `string` **SAVE\_APPEND**
```
'append'
```
Saving strategy that will only append to the links set
* `string` **SAVE\_REPLACE**
```
'replace'
```
Saving strategy that will replace the links with the provided set
* `string` **STRATEGY\_JOIN**
```
'join'
```
Strategy name to use joins for fetching associated records
* `string` **STRATEGY\_SELECT**
```
'select'
```
Strategy name to use a select for fetching associated records
* `string` **STRATEGY\_SUBQUERY**
```
'subquery'
```
Strategy name to use a subquery for fetching associated records
Property Summary
----------------
* [$\_bindingKey](#%24_bindingKey) protected `array<string>|string|null` The field name in the owning side table that is used to match with the foreignKey
* [$\_cascadeCallbacks](#%24_cascadeCallbacks) protected `bool` Whether cascaded deletes should also fire callbacks.
* [$\_className](#%24_className) protected `string` The class name of the target table object
* [$\_conditions](#%24_conditions) protected `Closure|array` A list of conditions to be always included when fetching records from the target association
* [$\_dependent](#%24_dependent) protected `bool` Whether the records on the joint table should be removed when a record on the source table is deleted.
* [$\_finder](#%24_finder) protected `array|string` The default finder name to use for fetching rows from the target table With array value, finder name and default options are allowed.
* [$\_foreignKey](#%24_foreignKey) protected `array<string>|string` The name of the field representing the foreign key to the table to load
* [$\_joinType](#%24_joinType) protected `string` The type of join to be used when adding the association to a query
* [$\_junctionAssociationName](#%24_junctionAssociationName) protected `string` The name of the hasMany association from the target table to the junction table
* [$\_junctionConditions](#%24_junctionConditions) protected `array|null` Filtered conditions that reference the junction table.
* [$\_junctionProperty](#%24_junctionProperty) protected `string` The name of the property to be set containing data from the junction table once a record from the target table is hydrated
* [$\_junctionTable](#%24_junctionTable) protected `Cake\ORM\Table` Junction table instance
* [$\_junctionTableName](#%24_junctionTableName) protected `string` Junction table name
* [$\_name](#%24_name) protected `string` Name given to the association, it usually represents the alias assigned to the target associated table
* [$\_propertyName](#%24_propertyName) protected `string` The property name that should be filled with data from the target table in the source table record.
* [$\_saveStrategy](#%24_saveStrategy) protected `string` Saving strategy to be used by this association
* [$\_sort](#%24_sort) protected `mixed` Order in which target records should be returned
* [$\_sourceTable](#%24_sourceTable) protected `Cake\ORM\Table` Source table instance
* [$\_strategy](#%24_strategy) protected `string` The strategy name to be used to fetch associated records.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$\_targetConditions](#%24_targetConditions) protected `array|null` Filtered conditions that reference the target table.
* [$\_targetForeignKey](#%24_targetForeignKey) protected `array<string>|string|null` The name of the field representing the foreign key to the target table
* [$\_targetTable](#%24_targetTable) protected `Cake\ORM\Table` Target table instance
* [$\_through](#%24_through) protected `Cake\ORM\Table|string` The table instance for the junction relation.
* [$\_validStrategies](#%24_validStrategies) protected `array<string>` Valid strategies for this type of association
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
Method Summary
--------------
* ##### [\_\_call()](#__call()) public
Proxies method calls to the target table.
* ##### [\_\_construct()](#__construct()) public
Constructor. Subclasses can override \_options function to get the original list of passed options if expecting any other special key
* ##### [\_\_get()](#__get()) public
Proxies property retrieval to the target table. This is handy for getting this association's associations
* ##### [\_\_isset()](#__isset()) public
Proxies the isset call to the target table. This is handy to check if the target table has another association with the passed name
* ##### [\_appendFields()](#_appendFields()) protected
Helper function used to conditionally append fields to the select clause of a query from the fields found in another query object.
* ##### [\_appendJunctionJoin()](#_appendJunctionJoin()) protected
Append a join to the junction table.
* ##### [\_appendNotMatching()](#_appendNotMatching()) protected
Conditionally adds a condition to the passed Query that will make it find records where there is no match with this association.
* ##### [\_bindNewAssociations()](#_bindNewAssociations()) protected
Applies all attachable associations to `$query` out of the containments found in the `$surrogate` query.
* ##### [\_camelize()](#_camelize()) protected
Creates a camelized version of $name
* ##### [\_checkPersistenceStatus()](#_checkPersistenceStatus()) protected
Throws an exception should any of the passed entities is not persisted.
* ##### [\_collectJointEntities()](#_collectJointEntities()) protected
Returns the list of joint entities that exist between the source entity and each of the passed target entities
* ##### [\_diffLinks()](#_diffLinks()) protected
Helper method used to delete the difference between the links passed in `$existing` and `$jointEntities`. This method will return the values from `$targetEntities` that were not deleted from calculating the difference.
* ##### [\_dispatchBeforeFind()](#_dispatchBeforeFind()) protected
Triggers beforeFind on the target table for the query this association is attaching to
* ##### [\_entityName()](#_entityName()) protected
Creates the proper entity name (singular) for the specified name
* ##### [\_extractFinder()](#_extractFinder()) protected
Helper method to infer the requested finder and its options.
* ##### [\_fixtureName()](#_fixtureName()) protected
Creates a fixture name
* ##### [\_formatAssociationResults()](#_formatAssociationResults()) protected
Adds a formatter function to the passed `$query` if the `$surrogate` query declares any other formatter. Since the `$surrogate` query correspond to the associated target table, the resulting formatter will be the result of applying the surrogate formatters to only the property corresponding to such table.
* ##### [\_generateJunctionAssociations()](#_generateJunctionAssociations()) protected
Generate associations on the junction table as necessary
* ##### [\_generateSourceAssociations()](#_generateSourceAssociations()) protected
Generate additional source table associations as necessary.
* ##### [\_generateTargetAssociations()](#_generateTargetAssociations()) protected
Generate reciprocal associations as necessary.
* ##### [\_joinCondition()](#_joinCondition()) protected
Return false as join conditions are defined in the junction table
* ##### [\_junctionAssociationName()](#_junctionAssociationName()) protected
Returns the name of the association from the target table to the junction table, this name is used to generate alias in the query and to later on retrieve the results.
* ##### [\_junctionTableName()](#_junctionTableName()) protected
Sets the name of the junction table. If no arguments are passed the current configured name is returned. A default name based of the associated tables will be generated if none found.
* ##### [\_modelKey()](#_modelKey()) protected
Creates the proper underscored model key for associations
* ##### [\_modelNameFromKey()](#_modelNameFromKey()) protected
Creates the proper model name from a foreign key
* ##### [\_options()](#_options()) protected
Parse extra options passed in the constructor.
* ##### [\_pluginNamespace()](#_pluginNamespace()) protected
Return plugin's namespace
* ##### [\_pluginPath()](#_pluginPath()) protected
Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
* ##### [\_pluralHumanName()](#_pluralHumanName()) protected
Creates the plural human name used in views
* ##### [\_propertyName()](#_propertyName()) protected
Returns default property name based on association name.
* ##### [\_saveLinks()](#_saveLinks()) protected
Creates links between the source entity and each of the passed target entities
* ##### [\_saveTarget()](#_saveTarget()) protected
Persists each of the entities into the target table and creates links between the parent entity and each one of the saved target entities.
* ##### [\_singularHumanName()](#_singularHumanName()) protected
Creates the singular human name used in views
* ##### [\_singularName()](#_singularName()) protected
Creates the singular name for use in views.
* ##### [\_variableName()](#_variableName()) protected
Creates the plural variable name for views
* ##### [attachTo()](#attachTo()) public
Alters a Query object to include the associated target table data in the final result
* ##### [canBeJoined()](#canBeJoined()) public
Whether this association can be expressed directly in a query join
* ##### [cascadeDelete()](#cascadeDelete()) public
Clear out the data in the junction table for a given entity.
* ##### [defaultRowValue()](#defaultRowValue()) public
Returns a modified row after appending a property for this association with the default empty value according to whether the association was joined or fetched externally.
* ##### [deleteAll()](#deleteAll()) public
Proxies the delete operation to the target table's deleteAll method
* ##### [eagerLoader()](#eagerLoader()) public
Eager loads a list of records in the target table that are related to another set of records in the source table. Source records can be specified in two ways: first one is by passing a Query object setup to find on the source table and the other way is by explicitly passing an array of primary key values from the source table.
* ##### [exists()](#exists()) public
Proxies the operation to the target table's exists method after appending the default conditions for this association
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [find()](#find()) public
Proxies the finding operation to the target table's find method and modifies the query accordingly based of this association configuration.
* ##### [getBindingKey()](#getBindingKey()) public
Gets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
* ##### [getCascadeCallbacks()](#getCascadeCallbacks()) public
Gets whether cascaded deletes should also fire callbacks.
* ##### [getClassName()](#getClassName()) public
Gets the class name of the target table object.
* ##### [getConditions()](#getConditions()) public
Gets a list of conditions to be always included when fetching records from the target association.
* ##### [getDependent()](#getDependent()) public
Sets whether the records on the target table are dependent on the source table.
* ##### [getFinder()](#getFinder()) public
Gets the default finder to use for fetching rows from the target table.
* ##### [getForeignKey()](#getForeignKey()) public
Gets the name of the field representing the foreign key to the source table.
* ##### [getJoinType()](#getJoinType()) public
Gets the type of join to be used when adding the association to a query.
* ##### [getName()](#getName()) public
Gets the name for this association, usually the alias assigned to the target associated table
* ##### [getProperty()](#getProperty()) public
Gets the property name that should be filled with data from the target table in the source table record.
* ##### [getSaveStrategy()](#getSaveStrategy()) public
Gets the strategy that should be used for saving.
* ##### [getSort()](#getSort()) public
Gets the sort order in which target records should be returned.
* ##### [getSource()](#getSource()) public
Gets the table instance for the source side of the association.
* ##### [getStrategy()](#getStrategy()) public
Gets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [getTarget()](#getTarget()) public
Gets the table instance for the target side of the association.
* ##### [getTargetForeignKey()](#getTargetForeignKey()) public
Gets the name of the field representing the foreign key to the target table.
* ##### [getThrough()](#getThrough()) public
Gets the current join table, either the name of the Table instance or the instance itself.
* ##### [isOwningSide()](#isOwningSide()) public
Returns boolean true, as both of the tables 'own' rows in the other side of the association via the joint table.
* ##### [junction()](#junction()) public
Sets the table instance for the junction relation. If no arguments are passed, the current configured table instance is returned
* ##### [junctionConditions()](#junctionConditions()) protected
Returns filtered conditions that specifically reference the junction table.
* ##### [link()](#link()) public
Associates the source entity to each of the target entities provided by creating links in the junction table. Both the source entity and each of the target entities are assumed to be already persisted, if they are marked as new or their status is unknown then an exception will be thrown.
* ##### [replaceLinks()](#replaceLinks()) public
Replaces existing association links between the source entity and the target with the ones passed. This method does a smart cleanup, links that are already persisted and present in `$targetEntities` will not be deleted, new links will be created for the passed target entities that are not already in the database and the rest will be removed.
* ##### [requiresKeys()](#requiresKeys()) public
Returns true if the eager loading process will require a set of the owning table's binding keys in order to use them as a filter in the finder query.
* ##### [saveAssociated()](#saveAssociated()) public
Takes an entity from the source table and looks if there is a field matching the property name for this association. The found entity will be saved on the target table for this association by passing supplied `$options`
* ##### [setBindingKey()](#setBindingKey()) public
Sets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
* ##### [setCascadeCallbacks()](#setCascadeCallbacks()) public
Sets whether cascaded deletes should also fire callbacks.
* ##### [setClassName()](#setClassName()) public
Sets the class name of the target table object.
* ##### [setConditions()](#setConditions()) public
Sets a list of conditions to be always included when fetching records from the target association.
* ##### [setDependent()](#setDependent()) public
Sets whether the records on the target table are dependent on the source table.
* ##### [setFinder()](#setFinder()) public
Sets the default finder to use for fetching rows from the target table.
* ##### [setForeignKey()](#setForeignKey()) public
Sets the name of the field representing the foreign key to the target table.
* ##### [setJoinType()](#setJoinType()) public
Sets the type of join to be used when adding the association to a query.
* ##### [setName()](#setName()) public deprecated
Sets the name for this association, usually the alias assigned to the target associated table
* ##### [setProperty()](#setProperty()) public
Sets the property name that should be filled with data from the target table in the source table record.
* ##### [setSaveStrategy()](#setSaveStrategy()) public
Sets the strategy that should be used for saving.
* ##### [setSort()](#setSort()) public
Sets the sort order in which target records should be returned.
* ##### [setSource()](#setSource()) public
Sets the table instance for the source side of the association.
* ##### [setStrategy()](#setStrategy()) public
Sets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
* ##### [setTarget()](#setTarget()) public
Sets the table instance for the target side of the association.
* ##### [setTargetForeignKey()](#setTargetForeignKey()) public
Sets the name of the field representing the foreign key to the target table.
* ##### [setThrough()](#setThrough()) public
Sets the current join table, either the name of the Table instance or the instance itself.
* ##### [targetConditions()](#targetConditions()) protected
Returns filtered conditions that reference the target table.
* ##### [transformRow()](#transformRow()) public
Correctly nests a result row associated values into the correct array keys inside the source results.
* ##### [type()](#type()) public
Get the relationship type.
* ##### [unlink()](#unlink()) public
Removes all links between the passed source entity and each of the provided target entities. This method assumes that all passed objects are already persisted in the database and that each of them contain a primary key value.
* ##### [updateAll()](#updateAll()) public
Proxies the update operation to the target table's updateAll method
Method Detail
-------------
### \_\_call() public
```
__call(string $method, array $argument): mixed
```
Proxies method calls to the target table.
#### Parameters
`string` $method name of the method to be invoked
`array` $argument List of arguments passed to the function
#### Returns
`mixed`
#### Throws
`BadMethodCallException`
### \_\_construct() public
```
__construct(string $alias, array<string, mixed> $options = [])
```
Constructor. Subclasses can override \_options function to get the original list of passed options if expecting any other special key
#### Parameters
`string` $alias The name given to the association
`array<string, mixed>` $options optional A list of properties to be set on this object
### \_\_get() public
```
__get(string $property): Cake\ORM\Association
```
Proxies property retrieval to the target table. This is handy for getting this association's associations
#### Parameters
`string` $property the property name
#### Returns
`Cake\ORM\Association`
#### Throws
`RuntimeException`
if no association with such name exists ### \_\_isset() public
```
__isset(string $property): bool
```
Proxies the isset call to the target table. This is handy to check if the target table has another association with the passed name
#### Parameters
`string` $property the property name
#### Returns
`bool`
### \_appendFields() protected
```
_appendFields(Cake\ORM\Query $query, Cake\ORM\Query $surrogate, array<string, mixed> $options): void
```
Helper function used to conditionally append fields to the select clause of a query from the fields found in another query object.
#### Parameters
`Cake\ORM\Query` $query the query that will get the fields appended to
`Cake\ORM\Query` $surrogate the query having the fields to be copied from
`array<string, mixed>` $options options passed to the method `attachTo`
#### Returns
`void`
### \_appendJunctionJoin() protected
```
_appendJunctionJoin(Cake\ORM\Query $query, array|null $conditions = null): Cake\ORM\Query
```
Append a join to the junction table.
#### Parameters
`Cake\ORM\Query` $query The query to append.
`array|null` $conditions optional The query conditions to use.
#### Returns
`Cake\ORM\Query`
### \_appendNotMatching() protected
```
_appendNotMatching(Cake\ORM\Query $query, array<string, mixed> $options): void
```
Conditionally adds a condition to the passed Query that will make it find records where there is no match with this association.
#### Parameters
`Cake\ORM\Query` $query `array<string, mixed>` $options #### Returns
`void`
### \_bindNewAssociations() protected
```
_bindNewAssociations(Cake\ORM\Query $query, Cake\ORM\Query $surrogate, array<string, mixed> $options): void
```
Applies all attachable associations to `$query` out of the containments found in the `$surrogate` query.
Copies all contained associations from the `$surrogate` query into the passed `$query`. Containments are altered so that they respect the associations chain from which they originated.
#### Parameters
`Cake\ORM\Query` $query the query that will get the associations attached to
`Cake\ORM\Query` $surrogate the query having the containments to be attached
`array<string, mixed>` $options options passed to the method `attachTo`
#### Returns
`void`
### \_camelize() protected
```
_camelize(string $name): string
```
Creates a camelized version of $name
#### Parameters
`string` $name name
#### Returns
`string`
### \_checkPersistenceStatus() protected
```
_checkPersistenceStatus(Cake\Datasource\EntityInterface $sourceEntity, arrayCake\Datasource\EntityInterface> $targetEntities): bool
```
Throws an exception should any of the passed entities is not persisted.
#### Parameters
`Cake\Datasource\EntityInterface` $sourceEntity the row belonging to the `source` side of this association
`arrayCake\Datasource\EntityInterface>` $targetEntities list of entities belonging to the `target` side of this association
#### Returns
`bool`
#### Throws
`InvalidArgumentException`
### \_collectJointEntities() protected
```
_collectJointEntities(Cake\Datasource\EntityInterface $sourceEntity, array $targetEntities): arrayCake\Datasource\EntityInterface>
```
Returns the list of joint entities that exist between the source entity and each of the passed target entities
#### Parameters
`Cake\Datasource\EntityInterface` $sourceEntity The row belonging to the source side of this association.
`array` $targetEntities The rows belonging to the target side of this association.
#### Returns
`arrayCake\Datasource\EntityInterface>`
#### Throws
`InvalidArgumentException`
if any of the entities is lacking a primary key value ### \_diffLinks() protected
```
_diffLinks(Cake\ORM\Query $existing, arrayCake\Datasource\EntityInterface> $jointEntities, array $targetEntities, array<string, mixed> $options = []): array|false
```
Helper method used to delete the difference between the links passed in `$existing` and `$jointEntities`. This method will return the values from `$targetEntities` that were not deleted from calculating the difference.
#### Parameters
`Cake\ORM\Query` $existing a query for getting existing links
`arrayCake\Datasource\EntityInterface>` $jointEntities link entities that should be persisted
`array` $targetEntities entities in target table that are related to the `$jointEntities`
`array<string, mixed>` $options optional list of options accepted by `Table::delete()`
#### Returns
`array|false`
### \_dispatchBeforeFind() protected
```
_dispatchBeforeFind(Cake\ORM\Query $query): void
```
Triggers beforeFind on the target table for the query this association is attaching to
#### Parameters
`Cake\ORM\Query` $query the query this association is attaching itself to
#### Returns
`void`
### \_entityName() protected
```
_entityName(string $name): string
```
Creates the proper entity name (singular) for the specified name
#### Parameters
`string` $name Name
#### Returns
`string`
### \_extractFinder() protected
```
_extractFinder(array|string $finderData): array
```
Helper method to infer the requested finder and its options.
Returns the inferred options from the finder $type.
### Examples:
The following will call the finder 'translations' with the value of the finder as its options: $query->contain(['Comments' => ['finder' => ['translations']]]); $query->contain(['Comments' => ['finder' => ['translations' => []]]]); $query->contain(['Comments' => ['finder' => ['translations' => ['locales' => ['en\_US']]]]]);
#### Parameters
`array|string` $finderData The finder name or an array having the name as key and options as value.
#### Returns
`array`
### \_fixtureName() protected
```
_fixtureName(string $name): string
```
Creates a fixture name
#### Parameters
`string` $name Model class name
#### Returns
`string`
### \_formatAssociationResults() protected
```
_formatAssociationResults(Cake\ORM\Query $query, Cake\ORM\Query $surrogate, array<string, mixed> $options): void
```
Adds a formatter function to the passed `$query` if the `$surrogate` query declares any other formatter. Since the `$surrogate` query correspond to the associated target table, the resulting formatter will be the result of applying the surrogate formatters to only the property corresponding to such table.
#### Parameters
`Cake\ORM\Query` $query the query that will get the formatter applied to
`Cake\ORM\Query` $surrogate the query having formatters for the associated target table.
`array<string, mixed>` $options options passed to the method `attachTo`
#### Returns
`void`
### \_generateJunctionAssociations() protected
```
_generateJunctionAssociations(Cake\ORM\Table $junction, Cake\ORM\Table $source, Cake\ORM\Table $target): void
```
Generate associations on the junction table as necessary
Generates the following associations:
* junction belongsTo source e.g. ArticlesTags belongsTo Tags
* junction belongsTo target e.g. ArticlesTags belongsTo Articles
You can override these generated associations by defining associations with the correct aliases.
#### Parameters
`Cake\ORM\Table` $junction The junction table.
`Cake\ORM\Table` $source The source table.
`Cake\ORM\Table` $target The target table.
#### Returns
`void`
#### Throws
`InvalidArgumentException`
If the expected associations are incompatible with existing associations. ### \_generateSourceAssociations() protected
```
_generateSourceAssociations(Cake\ORM\Table $junction, Cake\ORM\Table $source): void
```
Generate additional source table associations as necessary.
Generates the following associations:
* source hasMany junction e.g. Tags hasMany ArticlesTags
You can override these generated associations by defining associations with the correct aliases.
#### Parameters
`Cake\ORM\Table` $junction The junction table.
`Cake\ORM\Table` $source The source table.
#### Returns
`void`
### \_generateTargetAssociations() protected
```
_generateTargetAssociations(Cake\ORM\Table $junction, Cake\ORM\Table $source, Cake\ORM\Table $target): void
```
Generate reciprocal associations as necessary.
Generates the following associations:
* target hasMany junction e.g. Articles hasMany ArticlesTags
* target belongsToMany source e.g Articles belongsToMany Tags.
You can override these generated associations by defining associations with the correct aliases.
#### Parameters
`Cake\ORM\Table` $junction The junction table.
`Cake\ORM\Table` $source The source table.
`Cake\ORM\Table` $target The target table.
#### Returns
`void`
### \_joinCondition() protected
```
_joinCondition(array<string, mixed> $options): array
```
Return false as join conditions are defined in the junction table
#### Parameters
`array<string, mixed>` $options list of options passed to attachTo method
#### Returns
`array`
### \_junctionAssociationName() protected
```
_junctionAssociationName(): string
```
Returns the name of the association from the target table to the junction table, this name is used to generate alias in the query and to later on retrieve the results.
#### Returns
`string`
### \_junctionTableName() protected
```
_junctionTableName(string|null $name = null): string
```
Sets the name of the junction table. If no arguments are passed the current configured name is returned. A default name based of the associated tables will be generated if none found.
#### Parameters
`string|null` $name optional The name of the junction table.
#### Returns
`string`
### \_modelKey() protected
```
_modelKey(string $name): string
```
Creates the proper underscored model key for associations
If the input contains a dot, assume that the right side is the real table name.
#### Parameters
`string` $name Model class name
#### Returns
`string`
### \_modelNameFromKey() protected
```
_modelNameFromKey(string $key): string
```
Creates the proper model name from a foreign key
#### Parameters
`string` $key Foreign key
#### Returns
`string`
### \_options() protected
```
_options(array<string, mixed> $options): void
```
Parse extra options passed in the constructor.
#### Parameters
`array<string, mixed>` $options original list of options passed in constructor
#### Returns
`void`
### \_pluginNamespace() protected
```
_pluginNamespace(string $pluginName): string
```
Return plugin's namespace
#### Parameters
`string` $pluginName Plugin name
#### Returns
`string`
### \_pluginPath() protected
```
_pluginPath(string $pluginName): string
```
Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
#### Parameters
`string` $pluginName Name of the plugin you want ie. DebugKit
#### Returns
`string`
### \_pluralHumanName() protected
```
_pluralHumanName(string $name): string
```
Creates the plural human name used in views
#### Parameters
`string` $name Controller name
#### Returns
`string`
### \_propertyName() protected
```
_propertyName(): string
```
Returns default property name based on association name.
#### Returns
`string`
### \_saveLinks() protected
```
_saveLinks(Cake\Datasource\EntityInterface $sourceEntity, arrayCake\Datasource\EntityInterface> $targetEntities, array<string, mixed> $options): bool
```
Creates links between the source entity and each of the passed target entities
#### Parameters
`Cake\Datasource\EntityInterface` $sourceEntity the entity from source table in this association
`arrayCake\Datasource\EntityInterface>` $targetEntities list of entities to link to link to the source entity using the junction table
`array<string, mixed>` $options list of options accepted by `Table::save()`
#### Returns
`bool`
### \_saveTarget() protected
```
_saveTarget(Cake\Datasource\EntityInterface $parentEntity, array $entities, array<string, mixed> $options): Cake\Datasource\EntityInterface|false
```
Persists each of the entities into the target table and creates links between the parent entity and each one of the saved target entities.
#### Parameters
`Cake\Datasource\EntityInterface` $parentEntity the source entity containing the target entities to be saved.
`array` $entities list of entities to persist in target table and to link to the parent entity
`array<string, mixed>` $options list of options accepted by `Table::save()`
#### Returns
`Cake\Datasource\EntityInterface|false`
#### Throws
`InvalidArgumentException`
if the property representing the association in the parent entity cannot be traversed ### \_singularHumanName() protected
```
_singularHumanName(string $name): string
```
Creates the singular human name used in views
#### Parameters
`string` $name Controller name
#### Returns
`string`
### \_singularName() protected
```
_singularName(string $name): string
```
Creates the singular name for use in views.
#### Parameters
`string` $name Name to use
#### Returns
`string`
### \_variableName() protected
```
_variableName(string $name): string
```
Creates the plural variable name for views
#### Parameters
`string` $name Name to use
#### Returns
`string`
### attachTo() public
```
attachTo(Cake\ORM\Query $query, array<string, mixed> $options = []): void
```
Alters a Query object to include the associated target table data in the final result
The options array accept the following keys:
* includeFields: Whether to include target model fields in the result or not
* foreignKey: The name of the field to use as foreign key, if false none will be used
* conditions: array with a list of conditions to filter the join with
* fields: a list of fields in the target table to include in the result
* type: The type of join to be used (e.g. INNER)
#### Parameters
`Cake\ORM\Query` $query the query to be altered to include the target table data
`array<string, mixed>` $options optional Any extra options or overrides to be taken in account
#### Returns
`void`
### canBeJoined() public
```
canBeJoined(array<string, mixed> $options = []): bool
```
Whether this association can be expressed directly in a query join
#### Parameters
`array<string, mixed>` $options optional custom options key that could alter the return value
#### Returns
`bool`
### cascadeDelete() public
```
cascadeDelete(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): bool
```
Clear out the data in the junction table for a given entity.
Each implementing class should handle the cascaded delete as required.
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity that started the cascading delete.
`array<string, mixed>` $options optional The options for the original delete.
#### Returns
`bool`
### defaultRowValue() public
```
defaultRowValue(array<string, mixed> $row, bool $joined): array<string, mixed>
```
Returns a modified row after appending a property for this association with the default empty value according to whether the association was joined or fetched externally.
#### Parameters
`array<string, mixed>` $row `bool` $joined #### Returns
`array<string, mixed>`
### deleteAll() public
```
deleteAll(Cake\Database\ExpressionInterfaceClosure|array|string|null $conditions): int
```
Proxies the delete operation to the target table's deleteAll method
#### Parameters
`Cake\Database\ExpressionInterfaceClosure|array|string|null` $conditions Conditions to be used, accepts anything Query::where() can take.
#### Returns
`int`
#### See Also
\Cake\ORM\Table::deleteAll() ### eagerLoader() public
```
eagerLoader(array<string, mixed> $options): Closure
```
Eager loads a list of records in the target table that are related to another set of records in the source table. Source records can be specified in two ways: first one is by passing a Query object setup to find on the source table and the other way is by explicitly passing an array of primary key values from the source table.
The required way of passing related source records is controlled by "strategy" When the subquery strategy is used it will require a query on the source table. When using the select strategy, the list of primary keys will be used.
Returns a closure that should be run for each record returned in a specific Query. This callable will be responsible for injecting the fields that are related to each specific passed row.
Options array accepts the following keys:
* query: Query object setup to find the source table records
* keys: List of primary key values from the source table
* foreignKey: The name of the field used to relate both tables
* conditions: List of conditions to be passed to the query where() method
* sort: The direction in which the records should be returned
* fields: List of fields to select from the target table
* contain: List of related tables to eager load associated to the target table
* strategy: The name of strategy to use for finding target table records
* nestKey: The array key under which results will be found when transforming the row
#### Parameters
`array<string, mixed>` $options #### Returns
`Closure`
### exists() public
```
exists(Cake\Database\ExpressionInterfaceClosure|array|string|null $conditions): bool
```
Proxies the operation to the target table's exists method after appending the default conditions for this association
#### Parameters
`Cake\Database\ExpressionInterfaceClosure|array|string|null` $conditions The conditions to use for checking if any record matches.
#### Returns
`bool`
#### See Also
\Cake\ORM\Table::exists() ### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### find() public
```
find(array<string, mixed>|string|null $type = null, array<string, mixed> $options = []): Cake\ORM\Query
```
Proxies the finding operation to the target table's find method and modifies the query accordingly based of this association configuration.
If your association includes conditions or a finder, the junction table will be included in the query's contained associations.
#### Parameters
`array<string, mixed>|string|null` $type optional the type of query to perform, if an array is passed, it will be interpreted as the `$options` parameter
`array<string, mixed>` $options optional The options to for the find
#### Returns
`Cake\ORM\Query`
#### See Also
\Cake\ORM\Table::find() ### getBindingKey() public
```
getBindingKey(): array<string>|string
```
Gets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
#### Returns
`array<string>|string`
### getCascadeCallbacks() public
```
getCascadeCallbacks(): bool
```
Gets whether cascaded deletes should also fire callbacks.
#### Returns
`bool`
### getClassName() public
```
getClassName(): string
```
Gets the class name of the target table object.
#### Returns
`string`
### getConditions() public
```
getConditions(): Closure|array
```
Gets a list of conditions to be always included when fetching records from the target association.
#### Returns
`Closure|array`
#### See Also
\Cake\Database\Query::where() for examples on the format of the array ### getDependent() public
```
getDependent(): bool
```
Sets whether the records on the target table are dependent on the source table.
This is primarily used to indicate that records should be removed if the owning record in the source table is deleted.
#### Returns
`bool`
### getFinder() public
```
getFinder(): array|string
```
Gets the default finder to use for fetching rows from the target table.
#### Returns
`array|string`
### getForeignKey() public
```
getForeignKey(): array<string>|string
```
Gets the name of the field representing the foreign key to the source table.
#### Returns
`array<string>|string`
### getJoinType() public
```
getJoinType(): string
```
Gets the type of join to be used when adding the association to a query.
#### Returns
`string`
### getName() public
```
getName(): string
```
Gets the name for this association, usually the alias assigned to the target associated table
#### Returns
`string`
### getProperty() public
```
getProperty(): string
```
Gets the property name that should be filled with data from the target table in the source table record.
#### Returns
`string`
### getSaveStrategy() public
```
getSaveStrategy(): string
```
Gets the strategy that should be used for saving.
#### Returns
`string`
### getSort() public
```
getSort(): mixed
```
Gets the sort order in which target records should be returned.
#### Returns
`mixed`
### getSource() public
```
getSource(): Cake\ORM\Table
```
Gets the table instance for the source side of the association.
#### Returns
`Cake\ORM\Table`
### getStrategy() public
```
getStrategy(): string
```
Gets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void.
#### Returns
`string`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### getTarget() public
```
getTarget(): Cake\ORM\Table
```
Gets the table instance for the target side of the association.
#### Returns
`Cake\ORM\Table`
### getTargetForeignKey() public
```
getTargetForeignKey(): array<string>|string
```
Gets the name of the field representing the foreign key to the target table.
#### Returns
`array<string>|string`
### getThrough() public
```
getThrough(): Cake\ORM\Table|string
```
Gets the current join table, either the name of the Table instance or the instance itself.
#### Returns
`Cake\ORM\Table|string`
### isOwningSide() public
```
isOwningSide(Cake\ORM\Table $side): bool
```
Returns boolean true, as both of the tables 'own' rows in the other side of the association via the joint table.
#### Parameters
`Cake\ORM\Table` $side The potential Table with ownership
#### Returns
`bool`
### junction() public
```
junction(Cake\ORM\Table|string|null $table = null): Cake\ORM\Table
```
Sets the table instance for the junction relation. If no arguments are passed, the current configured table instance is returned
#### Parameters
`Cake\ORM\Table|string|null` $table optional Name or instance for the join table
#### Returns
`Cake\ORM\Table`
#### Throws
`InvalidArgumentException`
If the expected associations are incompatible with existing associations. ### junctionConditions() protected
```
junctionConditions(): array
```
Returns filtered conditions that specifically reference the junction table.
#### Returns
`array`
### link() public
```
link(Cake\Datasource\EntityInterface $sourceEntity, arrayCake\Datasource\EntityInterface> $targetEntities, array<string, mixed> $options = []): bool
```
Associates the source entity to each of the target entities provided by creating links in the junction table. Both the source entity and each of the target entities are assumed to be already persisted, if they are marked as new or their status is unknown then an exception will be thrown.
When using this method, all entities in `$targetEntities` will be appended to the source entity's property corresponding to this association object.
This method does not check link uniqueness.
### Example:
```
$newTags = $tags->find('relevant')->toArray();
$articles->getAssociation('tags')->link($article, $newTags);
```
`$article->get('tags')` will contain all tags in `$newTags` after liking
#### Parameters
`Cake\Datasource\EntityInterface` $sourceEntity the row belonging to the `source` side of this association
`arrayCake\Datasource\EntityInterface>` $targetEntities list of entities belonging to the `target` side of this association
`array<string, mixed>` $options optional list of options to be passed to the internal `save` call
#### Returns
`bool`
#### Throws
`InvalidArgumentException`
when any of the values in $targetEntities is detected to not be already persisted ### replaceLinks() public
```
replaceLinks(Cake\Datasource\EntityInterface $sourceEntity, array $targetEntities, array<string, mixed> $options = []): bool
```
Replaces existing association links between the source entity and the target with the ones passed. This method does a smart cleanup, links that are already persisted and present in `$targetEntities` will not be deleted, new links will be created for the passed target entities that are not already in the database and the rest will be removed.
For example, if an article is linked to tags 'cake' and 'framework' and you pass to this method an array containing the entities for tags 'cake', 'php' and 'awesome', only the link for cake will be kept in database, the link for 'framework' will be deleted and the links for 'php' and 'awesome' will be created.
Existing links are not deleted and created again, they are either left untouched or updated so that potential extra information stored in the joint row is not lost. Updating the link row can be done by making sure the corresponding passed target entity contains the joint property with its primary key and any extra information to be stored.
On success, the passed `$sourceEntity` will contain `$targetEntities` as value in the corresponding property for this association.
This method assumes that links between both the source entity and each of the target entities are unique. That is, for any given row in the source table there can only be one link in the junction table pointing to any other given row in the target table.
Additional options for new links to be saved can be passed in the third argument, check `Table::save()` for information on the accepted options.
### Example:
```
$article->tags = [$tag1, $tag2, $tag3, $tag4];
$articles->save($article);
$tags = [$tag1, $tag3];
$articles->getAssociation('tags')->replaceLinks($article, $tags);
```
`$article->get('tags')` will contain only `[$tag1, $tag3]` at the end
#### Parameters
`Cake\Datasource\EntityInterface` $sourceEntity an entity persisted in the source table for this association
`array` $targetEntities list of entities from the target table to be linked
`array<string, mixed>` $options optional list of options to be passed to the internal `save`/`delete` calls when persisting/updating new links, or deleting existing ones
#### Returns
`bool`
#### Throws
`InvalidArgumentException`
if non persisted entities are passed or if any of them is lacking a primary key value ### requiresKeys() public
```
requiresKeys(array<string, mixed> $options = []): bool
```
Returns true if the eager loading process will require a set of the owning table's binding keys in order to use them as a filter in the finder query.
#### Parameters
`array<string, mixed>` $options optional The options containing the strategy to be used.
#### Returns
`bool`
### saveAssociated() public
```
saveAssociated(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): Cake\Datasource\EntityInterface|false
```
Takes an entity from the source table and looks if there is a field matching the property name for this association. The found entity will be saved on the target table for this association by passing supplied `$options`
When using the 'append' strategy, this function will only create new links between each side of this association. It will not destroy existing ones even though they may not be present in the array of entities to be saved.
When using the 'replace' strategy, existing links will be removed and new links will be created in the joint table. If there exists links in the database to some of the entities intended to be saved by this method, they will be updated, not deleted.
#### Parameters
`Cake\Datasource\EntityInterface` $entity an entity from the source table
`array<string, mixed>` $options optional options to be passed to the save method in the target table
#### Returns
`Cake\Datasource\EntityInterface|false`
#### Throws
`InvalidArgumentException`
if the property representing the association in the parent entity cannot be traversed #### See Also
\Cake\ORM\Table::save()
\Cake\ORM\Association\BelongsToMany::replaceLinks() ### setBindingKey() public
```
setBindingKey(array<string>|string $key): $this
```
Sets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
#### Parameters
`array<string>|string` $key the table field or fields to be used to link both tables together
#### Returns
`$this`
### setCascadeCallbacks() public
```
setCascadeCallbacks(bool $cascadeCallbacks): $this
```
Sets whether cascaded deletes should also fire callbacks.
#### Parameters
`bool` $cascadeCallbacks cascade callbacks switch value
#### Returns
`$this`
### setClassName() public
```
setClassName(string $className): $this
```
Sets the class name of the target table object.
#### Parameters
`string` $className Class name to set.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
In case the class name is set after the target table has been resolved, and it doesn't match the target table's class name. ### setConditions() public
```
setConditions(Closure|array $conditions): $this
```
Sets a list of conditions to be always included when fetching records from the target association.
#### Parameters
`Closure|array` $conditions #### Returns
`$this`
### setDependent() public
```
setDependent(bool $dependent): $this
```
Sets whether the records on the target table are dependent on the source table.
This is primarily used to indicate that records should be removed if the owning record in the source table is deleted.
If no parameters are passed the current setting is returned.
#### Parameters
`bool` $dependent Set the dependent mode. Use null to read the current state.
#### Returns
`$this`
### setFinder() public
```
setFinder(array|string $finder): $this
```
Sets the default finder to use for fetching rows from the target table.
#### Parameters
`array|string` $finder the finder name to use or array of finder name and option.
#### Returns
`$this`
### setForeignKey() public
```
setForeignKey(array<string>|string $key): $this
```
Sets the name of the field representing the foreign key to the target table.
#### Parameters
`array<string>|string` $key the key or keys to be used to link both tables together
#### Returns
`$this`
### setJoinType() public
```
setJoinType(string $type): $this
```
Sets the type of join to be used when adding the association to a query.
#### Parameters
`string` $type the join type to be used (e.g. INNER)
#### Returns
`$this`
### setName() public
```
setName(string $name): $this
```
Sets the name for this association, usually the alias assigned to the target associated table
#### Parameters
`string` $name Name to be assigned
#### Returns
`$this`
### setProperty() public
```
setProperty(string $name): $this
```
Sets the property name that should be filled with data from the target table in the source table record.
#### Parameters
`string` $name The name of the association property. Use null to read the current value.
#### Returns
`$this`
### setSaveStrategy() public
```
setSaveStrategy(string $strategy): $this
```
Sets the strategy that should be used for saving.
#### Parameters
`string` $strategy the strategy name to be used
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
if an invalid strategy name is passed ### setSort() public
```
setSort(mixed $sort): $this
```
Sets the sort order in which target records should be returned.
#### Parameters
`mixed` $sort A find() compatible order clause
#### Returns
`$this`
### setSource() public
```
setSource(Cake\ORM\Table $table): $this
```
Sets the table instance for the source side of the association.
#### Parameters
`Cake\ORM\Table` $table the instance to be assigned as source side
#### Returns
`$this`
### setStrategy() public
```
setStrategy(string $name): $this
```
Sets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void.
#### Parameters
`string` $name The strategy type. Use null to read the current value.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
When an invalid strategy is provided. ### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
### setTarget() public
```
setTarget(Cake\ORM\Table $table): $this
```
Sets the table instance for the target side of the association.
#### Parameters
`Cake\ORM\Table` $table the instance to be assigned as target side
#### Returns
`$this`
### setTargetForeignKey() public
```
setTargetForeignKey(array<string>|string $key): $this
```
Sets the name of the field representing the foreign key to the target table.
#### Parameters
`array<string>|string` $key the key to be used to link both tables together
#### Returns
`$this`
### setThrough() public
```
setThrough(Cake\ORM\Table|string $through): $this
```
Sets the current join table, either the name of the Table instance or the instance itself.
#### Parameters
`Cake\ORM\Table|string` $through Name of the Table instance or the instance itself
#### Returns
`$this`
### targetConditions() protected
```
targetConditions(): arrayClosure|null
```
Returns filtered conditions that reference the target table.
Any string expressions, or expression objects will also be returned in this list.
#### Returns
`arrayClosure|null`
### transformRow() public
```
transformRow(array $row, string $nestKey, bool $joined, string|null $targetProperty = null): array
```
Correctly nests a result row associated values into the correct array keys inside the source results.
#### Parameters
`array` $row The row to transform
`string` $nestKey The array key under which the results for this association should be found
`bool` $joined Whether the row is a result of a direct join with this association
`string|null` $targetProperty optional The property name in the source results where the association data shuld be nested in. Will use the default one if not provided.
#### Returns
`array`
### type() public
```
type(): string
```
Get the relationship type.
#### Returns
`string`
### unlink() public
```
unlink(Cake\Datasource\EntityInterface $sourceEntity, arrayCake\Datasource\EntityInterface> $targetEntities, array<string>|bool $options = []): bool
```
Removes all links between the passed source entity and each of the provided target entities. This method assumes that all passed objects are already persisted in the database and that each of them contain a primary key value.
### Options
Additionally to the default options accepted by `Table::delete()`, the following keys are supported:
* cleanProperty: Whether to remove all the objects in `$targetEntities` that are stored in `$sourceEntity` (default: true)
By default this method will unset each of the entity objects stored inside the source entity.
### Example:
```
$article->tags = [$tag1, $tag2, $tag3, $tag4];
$tags = [$tag1, $tag2, $tag3];
$articles->getAssociation('tags')->unlink($article, $tags);
```
`$article->get('tags')` will contain only `[$tag4]` after deleting in the database
#### Parameters
`Cake\Datasource\EntityInterface` $sourceEntity An entity persisted in the source table for this association.
`arrayCake\Datasource\EntityInterface>` $targetEntities List of entities persisted in the target table for this association.
`array<string>|bool` $options optional List of options to be passed to the internal `delete` call, or a `boolean` as `cleanProperty` key shortcut.
#### Returns
`bool`
#### Throws
`InvalidArgumentException`
If non persisted entities are passed or if any of them is lacking a primary key value. ### updateAll() public
```
updateAll(array $fields, Cake\Database\ExpressionInterfaceClosure|array|string|null $conditions): int
```
Proxies the update operation to the target table's updateAll method
#### Parameters
`array` $fields A hash of field => new value.
`Cake\Database\ExpressionInterfaceClosure|array|string|null` $conditions Conditions to be used, accepts anything Query::where() can take.
#### Returns
`int`
#### See Also
\Cake\ORM\Table::updateAll() Property Detail
---------------
### $\_bindingKey protected
The field name in the owning side table that is used to match with the foreignKey
#### Type
`array<string>|string|null`
### $\_cascadeCallbacks protected
Whether cascaded deletes should also fire callbacks.
#### Type
`bool`
### $\_className protected
The class name of the target table object
#### Type
`string`
### $\_conditions protected
A list of conditions to be always included when fetching records from the target association
#### Type
`Closure|array`
### $\_dependent protected
Whether the records on the joint table should be removed when a record on the source table is deleted.
Defaults to true for backwards compatibility.
#### Type
`bool`
### $\_finder protected
The default finder name to use for fetching rows from the target table With array value, finder name and default options are allowed.
#### Type
`array|string`
### $\_foreignKey protected
The name of the field representing the foreign key to the table to load
#### Type
`array<string>|string`
### $\_joinType protected
The type of join to be used when adding the association to a query
#### Type
`string`
### $\_junctionAssociationName protected
The name of the hasMany association from the target table to the junction table
#### Type
`string`
### $\_junctionConditions protected
Filtered conditions that reference the junction table.
#### Type
`array|null`
### $\_junctionProperty protected
The name of the property to be set containing data from the junction table once a record from the target table is hydrated
#### Type
`string`
### $\_junctionTable protected
Junction table instance
#### Type
`Cake\ORM\Table`
### $\_junctionTableName protected
Junction table name
#### Type
`string`
### $\_name protected
Name given to the association, it usually represents the alias assigned to the target associated table
#### Type
`string`
### $\_propertyName protected
The property name that should be filled with data from the target table in the source table record.
#### Type
`string`
### $\_saveStrategy protected
Saving strategy to be used by this association
#### Type
`string`
### $\_sort protected
Order in which target records should be returned
#### Type
`mixed`
### $\_sourceTable protected
Source table instance
#### Type
`Cake\ORM\Table`
### $\_strategy protected
The strategy name to be used to fetch associated records.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $\_targetConditions protected
Filtered conditions that reference the target table.
#### Type
`array|null`
### $\_targetForeignKey protected
The name of the field representing the foreign key to the target table
#### Type
`array<string>|string|null`
### $\_targetTable protected
Target table instance
#### Type
`Cake\ORM\Table`
### $\_through protected
The table instance for the junction relation.
#### Type
`Cake\ORM\Table|string`
### $\_validStrategies protected
Valid strategies for this type of association
#### Type
`array<string>`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
| programming_docs |
cakephp Class MissingActionException Class MissingActionException
=============================
Missing Action exception - used when a controller action cannot be found, or when the controller's isAction() method returns false.
**Namespace:** [Cake\Controller\Exception](namespace-cake.controller.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Class NestingLabelWidget Class NestingLabelWidget
=========================
Form 'widget' for creating labels that contain their input.
Generally this element is used by other widgets, and FormHelper itself.
**Namespace:** [Cake\View\Widget](namespace-cake.view.widget)
Property Summary
----------------
* [$\_labelTemplate](#%24_labelTemplate) protected `string` The template to use.
* [$\_templates](#%24_templates) protected `Cake\View\StringTemplate` Templates
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [render()](#render()) public
Render a label widget.
* ##### [secureFields()](#secureFields()) public
Returns a list of fields that need to be secured for this widget.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\View\StringTemplate $templates)
```
Constructor.
This class uses the following template:
* `label` Used to generate the label for a radio button. Can use the following variables `attrs`, `text` and `input`.
#### Parameters
`Cake\View\StringTemplate` $templates Templates list.
### render() public
```
render(array<string, mixed> $data, Cake\View\Form\ContextInterface $context): string
```
Render a label widget.
Accepts the following keys in $data:
* `text` The text for the label.
* `input` The input that can be formatted into the label if the template allows it.
* `escape` Set to false to disable HTML escaping.
All other attributes will be converted into HTML attributes.
#### Parameters
`array<string, mixed>` $data Data array.
`Cake\View\Form\ContextInterface` $context The current form context.
#### Returns
`string`
### secureFields() public
```
secureFields(array<string, mixed> $data): array<string>
```
Returns a list of fields that need to be secured for this widget.
#### Parameters
`array<string, mixed>` $data #### Returns
`array<string>`
Property Detail
---------------
### $\_labelTemplate protected
The template to use.
#### Type
`string`
### $\_templates protected
Templates
#### Type
`Cake\View\StringTemplate`
cakephp Class FilterIterator Class FilterIterator
=====================
Creates a filtered iterator from another iterator. The filtering is done by passing a callback function to each of the elements and taking them out if it does not return true.
**Namespace:** [Cake\Collection\Iterator](namespace-cake.collection.iterator)
Property Summary
----------------
* [$\_callback](#%24_callback) protected `callable` The callback used to filter the elements in this collection
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Creates a filtered iterator using the callback to determine which items are accepted or rejected.
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_serialize()](#__serialize()) public
Returns an array for serializing this of this object.
* ##### [\_\_unserialize()](#__unserialize()) public
Rebuilds the Collection instance.
* ##### [\_createMatcherFilter()](#_createMatcherFilter()) protected
Returns a callable that receives a value and will return whether it matches certain condition.
* ##### [\_extract()](#_extract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
* ##### [\_propertyExtractor()](#_propertyExtractor()) protected
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
* ##### [\_simpleExtract()](#_simpleExtract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path
* ##### [append()](#append()) public
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
* ##### [appendItem()](#appendItem()) public
Append a single item creating a new collection.
* ##### [avg()](#avg()) public
Returns the average of all the values extracted with $path or of this collection.
* ##### [buffered()](#buffered()) public
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
* ##### [cartesianProduct()](#cartesianProduct()) public
Create a new collection that is the cartesian product of the current collection
* ##### [chunk()](#chunk()) public
Breaks the collection into smaller arrays of the given size.
* ##### [chunkWithKeys()](#chunkWithKeys()) public
Breaks the collection into smaller arrays of the given size.
* ##### [combine()](#combine()) public
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
* ##### [compile()](#compile()) public
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
* ##### [contains()](#contains()) public
Returns true if $value is present in this collection. Comparisons are made both by value and type.
* ##### [count()](#count()) public
Returns the amount of elements in the collection.
* ##### [countBy()](#countBy()) public
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
* ##### [countKeys()](#countKeys()) public
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
* ##### [each()](#each()) public
Applies a callback to the elements in this collection.
* ##### [every()](#every()) public
Returns true if all values in this collection pass the truth test provided in the callback.
* ##### [extract()](#extract()) public
Returns a new collection containing the column or property value found in each of the elements.
* ##### [filter()](#filter()) public
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
* ##### [first()](#first()) public
Returns the first result in this collection
* ##### [firstMatch()](#firstMatch()) public
Returns the first result matching all the key-value pairs listed in conditions.
* ##### [groupBy()](#groupBy()) public
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
* ##### [indexBy()](#indexBy()) public
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
* ##### [insert()](#insert()) public
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
* ##### [isEmpty()](#isEmpty()) public
Returns whether there are elements in this collection
* ##### [jsonSerialize()](#jsonSerialize()) public
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
* ##### [last()](#last()) public
Returns the last result in this collection
* ##### [lazy()](#lazy()) public
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
* ##### [listNested()](#listNested()) public
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
* ##### [map()](#map()) public
Returns another collection after modifying each of the values in this one using the provided callable.
* ##### [match()](#match()) public
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
* ##### [max()](#max()) public
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [median()](#median()) public
Returns the median of all the values extracted with $path or of this collection.
* ##### [min()](#min()) public
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [nest()](#nest()) public
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
* ##### [newCollection()](#newCollection()) protected
Returns a new collection.
* ##### [optimizeUnwrap()](#optimizeUnwrap()) protected
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
* ##### [prepend()](#prepend()) public
Prepend a set of items to a collection creating a new collection
* ##### [prependItem()](#prependItem()) public
Prepend a single item creating a new collection.
* ##### [reduce()](#reduce()) public
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
* ##### [reject()](#reject()) public
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
* ##### [sample()](#sample()) public
Returns a new collection with maximum $size random elements from this collection
* ##### [serialize()](#serialize()) public
Returns a string representation of this object that can be used to reconstruct it
* ##### [shuffle()](#shuffle()) public
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
* ##### [skip()](#skip()) public
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
* ##### [some()](#some()) public
Returns true if any of the values in this collection pass the truth test provided in the callback.
* ##### [sortBy()](#sortBy()) public
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
* ##### [stopWhen()](#stopWhen()) public
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
* ##### [sumOf()](#sumOf()) public
Returns the total sum of all the values extracted with $matcher or of this collection.
* ##### [take()](#take()) public
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
* ##### [takeLast()](#takeLast()) public
Returns the last N elements of a collection
* ##### [through()](#through()) public
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
* ##### [toArray()](#toArray()) public
Returns an array representation of the results
* ##### [toList()](#toList()) public
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
* ##### [transpose()](#transpose()) public
Transpose rows and columns into columns and rows
* ##### [unfold()](#unfold()) public
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
* ##### [unserialize()](#unserialize()) public
Unserializes the passed string and rebuilds the Collection instance
* ##### [unwrap()](#unwrap()) public
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
* ##### [zip()](#zip()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
* ##### [zipWith()](#zipWith()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
Method Detail
-------------
### \_\_construct() public
```
__construct(Traversable|array $items, callable $callback)
```
Creates a filtered iterator using the callback to determine which items are accepted or rejected.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and the passed $items iterator as arguments, in that order.
#### Parameters
`Traversable|array` $items The items to be filtered.
`callable` $callback Callback.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_serialize() public
```
__serialize(): array
```
Returns an array for serializing this of this object.
#### Returns
`array`
### \_\_unserialize() public
```
__unserialize(array $data): void
```
Rebuilds the Collection instance.
#### Parameters
`array` $data Data array.
#### Returns
`void`
### \_createMatcherFilter() protected
```
_createMatcherFilter(array $conditions): Closure
```
Returns a callable that receives a value and will return whether it matches certain condition.
#### Parameters
`array` $conditions A key-value list of conditions to match where the key is the property path to get from the current item and the value is the value to be compared the item with.
#### Returns
`Closure`
### \_extract() protected
```
_extract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### \_propertyExtractor() protected
```
_propertyExtractor(callable|string $path): callable
```
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
#### Parameters
`callable|string` $path A dot separated path of column to follow so that the final one can be returned or a callable that will take care of doing that.
#### Returns
`callable`
### \_simpleExtract() protected
```
_simpleExtract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### append() public
```
append(iterable $items): self
```
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
#### Parameters
`iterable` $items #### Returns
`self`
### appendItem() public
```
appendItem(mixed $item, mixed $key = null): self
```
Append a single item creating a new collection.
#### Parameters
`mixed` $item `mixed` $key optional #### Returns
`self`
### avg() public
```
avg(callable|string|null $path = null): float|int|null
```
Returns the average of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->avg('invoice.total');
// Total: 150
$total = (new Collection([1, 2, 3]))->avg();
// Total: 2
```
The average of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int|null`
### buffered() public
```
buffered(): self
```
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
This can also be used to make any non-rewindable iterator rewindable.
#### Returns
`self`
### cartesianProduct() public
```
cartesianProduct(callable|null $operation = null, callable|null $filter = null): Cake\Collection\CollectionInterface
```
Create a new collection that is the cartesian product of the current collection
In order to create a carteisan product a collection must contain a single dimension of data.
### Example
```
$collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
$result = $collection->cartesianProduct()->toArray();
$expected = [
['A', 1],
['A', 2],
['A', 3],
['B', 1],
['B', 2],
['B', 3],
['C', 1],
['C', 2],
['C', 3],
];
```
#### Parameters
`callable|null` $operation optional A callable that allows you to customize the product result.
`callable|null` $filter optional A filtering callback that must return true for a result to be part of the final results.
#### Returns
`Cake\Collection\CollectionInterface`
#### Throws
`LogicException`
### chunk() public
```
chunk(int $chunkSize): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
$chunked = (new Collection($items))->chunk(3)->toList();
// Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
```
#### Parameters
`int` $chunkSize #### Returns
`self`
### chunkWithKeys() public
```
chunkWithKeys(int $chunkSize, bool $keepKeys = true): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
$chunked = (new Collection($items))->chunkWithKeys(3)->toList();
// Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
```
#### Parameters
`int` $chunkSize `bool` $keepKeys optional #### Returns
`self`
### combine() public
```
combine(callable|string $keyPath, callable|string $valuePath, callable|string|null $groupPath = null): self
```
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
### Examples:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent' => 'a'],
['id' => 2, 'name' => 'bar', 'parent' => 'b'],
['id' => 3, 'name' => 'baz', 'parent' => 'a'],
];
$combined = (new Collection($items))->combine('id', 'name');
// Result will look like this when converted to array
[
1 => 'foo',
2 => 'bar',
3 => 'baz',
];
$combined = (new Collection($items))->combine('id', 'name', 'parent');
// Result will look like this when converted to array
[
'a' => [1 => 'foo', 3 => 'baz'],
'b' => [2 => 'bar']
];
```
#### Parameters
`callable|string` $keyPath `callable|string` $valuePath `callable|string|null` $groupPath optional #### Returns
`self`
### compile() public
```
compile(bool $keepKeys = true): self
```
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
A common use case is to re-use the same variable for calculating different data. In those cases it may be helpful and more performant to first compile a collection and then apply more operations to it.
### Example:
```
$collection->map($mapper)->sortBy('age')->extract('name');
$compiled = $collection->compile();
$isJohnHere = $compiled->some($johnMatcher);
$allButJohn = $compiled->filter($johnMatcher);
```
In the above example, had the collection not been compiled before, the iterations for `map`, `sortBy` and `extract` would've been executed twice: once for getting `$isJohnHere` and once for `$allButJohn`
You can think of this method as a way to create save points for complex calculations in a collection.
#### Parameters
`bool` $keepKeys optional #### Returns
`self`
### contains() public
```
contains(mixed $value): bool
```
Returns true if $value is present in this collection. Comparisons are made both by value and type.
#### Parameters
`mixed` $value #### Returns
`bool`
### count() public
```
count(): int
```
Returns the amount of elements in the collection.
WARNINGS:
---------
### Will change the current position of the iterator:
Calling this method at the same time that you are iterating this collections, for example in a foreach, will result in undefined behavior. Avoid doing this.
### Consumes all elements for NoRewindIterator collections:
On certain type of collections, calling this method may render unusable afterwards. That is, you may not be able to get elements out of it, or to iterate on it anymore.
Specifically any collection wrapping a Generator (a function with a yield statement) or a unbuffered database cursor will not accept any other function calls after calling `count()` on it.
Create a new collection with `buffered()` method to overcome this problem.
### Can report more elements than unique keys:
Any collection constructed by appending collections together, or by having internal iterators returning duplicate keys, will report a larger amount of elements using this functions than the final amount of elements when converting the collections to a keyed array. This is because duplicate keys will be collapsed into a single one in the final array, whereas this count method is only concerned by the amount of elements after converting it to a plain list.
If you need the count of elements after taking the keys in consideration (the count of unique keys), you can call `countKeys()`
#### Returns
`int`
### countBy() public
```
countBy(callable|string $path): self
```
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->countBy('parent_id');
// Or
$group = (new Collection($items))->countBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => 2,
11 => 1
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### countKeys() public
```
countKeys(): int
```
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
This method comes with a number of caveats. Please refer to `CollectionInterface::count()` for details.
#### Returns
`int`
### each() public
```
each(callable $callback): $this
```
Applies a callback to the elements in this collection.
### Example:
```
$collection = (new Collection($items))->each(function ($value, $key) {
echo "Element $key: $value";
});
```
#### Parameters
`callable` $callback #### Returns
`$this`
### every() public
```
every(callable $callback): bool
```
Returns true if all values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$overTwentyOne = (new Collection([24, 45, 60, 15]))->every(function ($value, $key) {
return $value > 21;
});
```
Empty collections always return true.
#### Parameters
`callable` $callback #### Returns
`bool`
### extract() public
```
extract(callable|string $path): self
```
Returns a new collection containing the column or property value found in each of the elements.
The matcher can be a string with a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection, that position is filled with null.
### Example:
Extract the user name for all comments in the array:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->extract('comment.user.name');
// Result will look like this when converted to array
['Mark', 'Renan']
```
It is also possible to extract a flattened collection out of nested properties
```
$items = [
['comment' => ['votes' => [['value' => 1], ['value' => 2], ['value' => 3]]],
['comment' => ['votes' => [['value' => 4]]
];
$extracted = (new Collection($items))->extract('comment.votes.{*}.value');
// Result will contain
[1, 2, 3, 4]
```
#### Parameters
`callable|string` $path #### Returns
`self`
### filter() public
```
filter(callable|null $callback = null): self
```
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering odd numbers in an array, at the end only the value 2 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->filter(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable|null` $callback optional #### Returns
`self`
### first() public
```
first(): mixed
```
Returns the first result in this collection
#### Returns
`mixed`
### firstMatch() public
```
firstMatch(array $conditions): mixed
```
Returns the first result matching all the key-value pairs listed in conditions.
#### Parameters
`array` $conditions #### Returns
`mixed`
### groupBy() public
```
groupBy(callable|string $path): self
```
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->groupBy('parent_id');
// Or
$group = (new Collection($items))->groupBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
],
11 => [
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
]
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### indexBy() public
```
indexBy(callable|string $path): self
```
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo'],
['id' => 2, 'name' => 'bar'],
['id' => 3, 'name' => 'baz'],
];
$indexed = (new Collection($items))->indexBy('id');
// Or
$indexed = (new Collection($items))->indexBy(function ($e) {
return $e['id'];
});
// Result will look like this when converted to array
[
1 => ['id' => 1, 'name' => 'foo'],
3 => ['id' => 3, 'name' => 'baz'],
2 => ['id' => 2, 'name' => 'bar'],
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### insert() public
```
insert(string $path, mixed $values): self
```
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
The $path can be a string with a property name or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection as part of the path, the element will be kept unchanged.
### Example:
Insert ages into a collection containing users:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
];
$ages = [25, 28];
$inserted = (new Collection($items))->insert('comment.user.age', $ages);
// Result will look like this when converted to array
[
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
];
```
#### Parameters
`string` $path `mixed` $values #### Returns
`self`
### isEmpty() public
```
isEmpty(): bool
```
Returns whether there are elements in this collection
### Example:
```
$items [1, 2, 3];
(new Collection($items))->isEmpty(); // false
```
```
(new Collection([]))->isEmpty(); // true
```
#### Returns
`bool`
### jsonSerialize() public
```
jsonSerialize(): array
```
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
Part of JsonSerializable interface.
#### Returns
`array`
### last() public
```
last(): mixed
```
Returns the last result in this collection
#### Returns
`mixed`
### lazy() public
```
lazy(): self
```
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
A lazy collection can only be iterated once. A second attempt results in an error.
#### Returns
`self`
### listNested() public
```
listNested(string|int $order = 'desc', callable|string $nestingKey = 'children'): self
```
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
By default all elements in the tree following a Depth First Search will be returned, that is, elements from the top parent to the leaves for each branch.
It is possible to return all elements from bottom to top using a Breadth First Search approach by passing the '$dir' parameter with 'asc'. That is, it will return all elements for the same tree depth first and from bottom to top.
Finally, you can specify to only get a collection with the leaf nodes in the tree structure. You do so by passing 'leaves' in the first argument.
The possible values for the first argument are aliases for the following constants and it is valid to pass those instead of the alias:
* desc: RecursiveIteratorIterator::SELF\_FIRST
* asc: RecursiveIteratorIterator::CHILD\_FIRST
* leaves: RecursiveIteratorIterator::LEAVES\_ONLY
### Example:
```
$collection = new Collection([
['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
['id' => 4, 'children' => [['id' => 5]]]
]);
$flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
```
#### Parameters
`string|int` $order optional `callable|string` $nestingKey optional #### Returns
`self`
### map() public
```
map(callable $callback): self
```
Returns another collection after modifying each of the values in this one using the provided callable.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Getting a collection of booleans where true indicates if a person is female:
```
$collection = (new Collection($people))->map(function ($person, $key) {
return $person->gender === 'female';
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### match() public
```
match(array $conditions): self
```
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
### Example:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->match(['user.name' => 'Renan']);
// Result will look like this when converted to array
[
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
]
```
#### Parameters
`array` $conditions #### Returns
`self`
### max() public
```
max(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$max = $collection->max('age');
$max = $collection->max('user.salary');
$max = $collection->max(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $max->name;
```
#### Parameters
`callable|string` $path `int` $sort optional #### Returns
`mixed`
### median() public
```
median(callable|string|null $path = null): float|int|null
```
Returns the median of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 400]],
['invoice' => ['total' => 500]]
['invoice' => ['total' => 100]]
['invoice' => ['total' => 333]]
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->median('invoice.total');
// Total: 333
$total = (new Collection([1, 2, 3, 4]))->median();
// Total: 2.5
```
The median of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int|null`
### min() public
```
min(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$min = $collection->min('age');
$min = $collection->min('user.salary');
$min = $collection->min(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $min->name;
```
#### Parameters
`callable|string` $path `int` $sort optional #### Returns
`mixed`
### nest() public
```
nest(callable|string $idPath, callable|string $parentPath, string $nestingKey = 'children'): self
```
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
#### Parameters
`callable|string` $idPath `callable|string` $parentPath `string` $nestingKey optional #### Returns
`self`
### newCollection() protected
```
newCollection(mixed ...$args): Cake\Collection\CollectionInterface
```
Returns a new collection.
Allows classes which use this trait to determine their own type of returned collection interface
#### Parameters
`mixed` ...$args Constructor arguments.
#### Returns
`Cake\Collection\CollectionInterface`
### optimizeUnwrap() protected
```
optimizeUnwrap(): iterable
```
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
#### Returns
`iterable`
### prepend() public
```
prepend(mixed $items): self
```
Prepend a set of items to a collection creating a new collection
#### Parameters
`mixed` $items #### Returns
`self`
### prependItem() public
```
prependItem(mixed $item, mixed $key = null): self
```
Prepend a single item creating a new collection.
#### Parameters
`mixed` $item `mixed` $key optional #### Returns
`self`
### reduce() public
```
reduce(callable $callback, mixed $initial = null): mixed
```
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
#### Parameters
`callable` $callback `mixed` $initial optional #### Returns
`mixed`
### reject() public
```
reject(callable $callback): self
```
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering even numbers in an array, at the end only values 1 and 3 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->reject(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### sample() public
```
sample(int $length = 10): self
```
Returns a new collection with maximum $size random elements from this collection
#### Parameters
`int` $length optional #### Returns
`self`
### serialize() public
```
serialize(): string
```
Returns a string representation of this object that can be used to reconstruct it
#### Returns
`string`
### shuffle() public
```
shuffle(): self
```
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
#### Returns
`self`
### skip() public
```
skip(int $length): self
```
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
#### Parameters
`int` $length #### Returns
`self`
### some() public
```
some(callable $callback): bool
```
Returns true if any of the values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$hasYoungPeople = (new Collection([24, 45, 15]))->some(function ($value, $key) {
return $value < 21;
});
```
#### Parameters
`callable` $callback #### Returns
`bool`
### sortBy() public
```
sortBy(callable|string $path, int $order = \SORT_DESC, int $sort = \SORT_NUMERIC): self
```
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
The callback will receive as its first argument each of the elements in $items, the value returned by the callback will be used as the value for sorting such element. Please note that the callback function could be called more than once per element.
### Example:
```
$items = $collection->sortBy(function ($user) {
return $user->age;
});
// alternatively
$items = $collection->sortBy('age');
// or use a property path
$items = $collection->sortBy('department.name');
// output all user name order by their age in descending order
foreach ($items as $user) {
echo $user->name;
}
```
#### Parameters
`callable|string` $path `int` $order optional `int` $sort optional #### Returns
`self`
### stopWhen() public
```
stopWhen(callable|array $condition): self
```
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
This is handy for dealing with infinite iterators or any generator that could start returning invalid elements at a certain point. For example, when reading lines from a file stream you may want to stop the iteration after a certain value is reached.
### Example:
Get an array of lines in a CSV file until the timestamp column is less than a date
```
$lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
return (new DateTime($value))->format('Y') < 2012;
})
->toArray();
```
Get elements until the first unapproved message is found:
```
$comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
```
#### Parameters
`callable|array` $condition #### Returns
`self`
### sumOf() public
```
sumOf(callable|string|null $path = null): float|int
```
Returns the total sum of all the values extracted with $matcher or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->sumOf('invoice.total');
// Total: 300
$total = (new Collection([1, 2, 3]))->sumOf();
// Total: 6
```
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int`
### take() public
```
take(int $length = 1, int $offset = 0): self
```
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
#### Parameters
`int` $length optional `int` $offset optional #### Returns
`self`
### takeLast() public
```
takeLast(int $length): self
```
Returns the last N elements of a collection
### Example:
```
$items = [1, 2, 3, 4, 5];
$last = (new Collection($items))->takeLast(3);
// Result will look like this when converted to array
[3, 4, 5];
```
#### Parameters
`int` $length #### Returns
`self`
### through() public
```
through(callable $callback): self
```
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
### Example:
```
$items = [1, 2, 3];
$decorated = (new Collection($items))->through(function ($collection) {
return new MyCustomCollection($collection);
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### toArray() public
```
toArray(bool $keepKeys = true): array
```
Returns an array representation of the results
#### Parameters
`bool` $keepKeys optional #### Returns
`array`
### toList() public
```
toList(): array
```
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
#### Returns
`array`
### transpose() public
```
transpose(): Cake\Collection\CollectionInterface
```
Transpose rows and columns into columns and rows
### Example:
```
$items = [
['Products', '2012', '2013', '2014'],
['Product A', '200', '100', '50'],
['Product B', '300', '200', '100'],
['Product C', '400', '300', '200'],
]
$transpose = (new Collection($items))->transpose()->toList();
// Returns
// [
// ['Products', 'Product A', 'Product B', 'Product C'],
// ['2012', '200', '300', '400'],
// ['2013', '100', '200', '300'],
// ['2014', '50', '100', '200'],
// ]
```
#### Returns
`Cake\Collection\CollectionInterface`
#### Throws
`LogicException`
### unfold() public
```
unfold(callable|null $callback = null): self
```
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
The transformer function will receive the value and the key for each of the items in the collection, in that order, and it must return an array or a Traversable object that can be concatenated to the final result.
If no transformer function is passed, an "identity" function will be used. This is useful when each of the elements in the source collection are lists of items to be appended one after another.
### Example:
```
$items [[1, 2, 3], [4, 5]];
$unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
```
Using a transformer
```
$items [1, 2, 3];
$allItems = (new Collection($items))->unfold(function ($page) {
return $service->fetchPage($page)->toArray();
});
```
#### Parameters
`callable|null` $callback optional #### Returns
`self`
### unserialize() public
```
unserialize(string $collection): void
```
Unserializes the passed string and rebuilds the Collection instance
#### Parameters
`string` $collection The serialized collection
#### Returns
`void`
### unwrap() public
```
unwrap(): Traversable
```
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
#### Returns
`Traversable`
### zip() public
```
zip(iterable $items): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
### Example:
```
$collection = new Collection([1, 2]);
$collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
```
#### Parameters
`iterable` $items #### Returns
`self`
### zipWith() public
```
zipWith(iterable $items, callable $callback): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
The resulting element will be the return value of the $callable function.
### Example:
```
$collection = new Collection([1, 2]);
$zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
return array_sum($args);
});
$zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
```
#### Parameters
`iterable` $items `callable` $callback #### Returns
`self`
Property Detail
---------------
### $\_callback protected
The callback used to filter the elements in this collection
#### Type
`callable`
| programming_docs |
cakephp Namespace Validation Namespace Validation
====================
### Interfaces
* ##### [ValidatableInterface](interface-cake.validation.validatableinterface)
Describes objects that can be validated by passing a Validator object.
* ##### [ValidatorAwareInterface](interface-cake.validation.validatorawareinterface)
Provides methods for managing multiple validators.
### Classes
* ##### [RulesProvider](class-cake.validation.rulesprovider)
A Proxy class used to remove any extra arguments when the user intended to call a method in another class that is not aware of validation providers signature
* ##### [Validation](class-cake.validation.validation)
Validation Class. Used for validation of model data
* ##### [ValidationRule](class-cake.validation.validationrule)
ValidationRule object. Represents a validation method, error message and rules for applying such method to a field.
* ##### [ValidationSet](class-cake.validation.validationset)
ValidationSet object. Holds all validation rules for a field and exposes methods to dynamically add or remove validation rules
* ##### [Validator](class-cake.validation.validator)
Validator object encapsulates all methods related to data validations for a model It also provides an API to dynamically change validation rules for each model field.
### Traits
* ##### [ValidatorAwareTrait](trait-cake.validation.validatorawaretrait)
A trait that provides methods for building and interacting with Validators.
cakephp Namespace Middleware Namespace Middleware
====================
### Classes
* ##### [LocaleSelectorMiddleware](class-cake.i18n.middleware.localeselectormiddleware)
Sets the runtime default locale for the request based on the Accept-Language header. The default will only be set if it matches the list of passed valid locales.
cakephp Class TranslateBehavior Class TranslateBehavior
========================
This behavior provides a way to translate dynamic data by keeping translations in a separate table linked to the original record from another one. Translated fields can be configured to override those in the main table when fetched or put aside into another property for the same entity.
If you wish to override fields, you need to call the `locale` method in this behavior for setting the language you want to fetch from the translations table.
If you want to bring all or certain languages for each of the fetched records, you can use the custom `translations` finders that is exposed to the table.
**Namespace:** [Cake\ORM\Behavior](namespace-cake.orm.behavior)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config
* [$\_reflectionCache](#%24_reflectionCache) protected static `array<string, array>` Reflection method cache for behaviors.
* [$\_table](#%24_table) protected `Cake\ORM\Table` Table instance.
* [$defaultStrategyClass](#%24defaultStrategyClass) protected static `string` Default strategy class name.
* [$strategy](#%24strategy) protected `Cake\ORM\Behavior\Translate\TranslateStrategyInterface|null` Translation strategy instance.
Method Summary
--------------
* ##### [\_\_call()](#__call()) public
Proxy method calls to strategy class instance.
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_reflectionCache()](#_reflectionCache()) protected
Gets the methods implemented by this behavior
* ##### [\_resolveMethodAliases()](#_resolveMethodAliases()) protected
Removes aliased methods that would otherwise be duplicated by userland configuration.
* ##### [buildMarshalMap()](#buildMarshalMap()) public
Build a set of properties that should be included in the marshalling process.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [createStrategy()](#createStrategy()) protected
Create strategy instance.
* ##### [findTranslations()](#findTranslations()) public
Custom finder method used to retrieve all translations for the found records. Fetched translations can be filtered by locale by passing the `locales` key in the options array.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getDefaultStrategyClass()](#getDefaultStrategyClass()) public static
Get default strategy class name.
* ##### [getLocale()](#getLocale()) public
Returns the current locale.
* ##### [getStrategy()](#getStrategy()) public
Get strategy class instance.
* ##### [getTable()](#getTable()) public deprecated
Get the table instance this behavior is bound to.
* ##### [implementedEvents()](#implementedEvents()) public
Gets the Model callbacks this behavior is interested in.
* ##### [implementedFinders()](#implementedFinders()) public
implementedFinders
* ##### [implementedMethods()](#implementedMethods()) public
implementedMethods
* ##### [initialize()](#initialize()) public
Initialize hook
* ##### [referenceName()](#referenceName()) protected
Determine the reference name to use for a given table
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setDefaultStrategyClass()](#setDefaultStrategyClass()) public static
Set default strategy class name.
* ##### [setLocale()](#setLocale()) public
Sets the locale that should be used for all future find and save operations on the table where this behavior is attached to.
* ##### [setStrategy()](#setStrategy()) public
Set strategy class instance.
* ##### [table()](#table()) public
Get the table instance this behavior is bound to.
* ##### [translationField()](#translationField()) public
Returns a fully aliased field name for translated fields.
* ##### [verifyConfig()](#verifyConfig()) public
verifyConfig
Method Detail
-------------
### \_\_call() public
```
__call(string $method, array $args): mixed
```
Proxy method calls to strategy class instance.
#### Parameters
`string` $method Method name.
`array` $args Method arguments.
#### Returns
`mixed`
### \_\_construct() public
```
__construct(Cake\ORM\Table $table, array<string, mixed> $config = [])
```
Constructor
### Options
* `fields`: List of fields which need to be translated. Providing this fields list is mandatory when using `EavStrategy`. If the fields list is empty when using `ShadowTableStrategy` then the list will be auto generated based on shadow table schema.
* `defaultLocale`: The locale which is treated as default by the behavior. Fields values for defaut locale will be stored in the primary table itself and the rest in translation table. If not explicitly set the value of `I18n::getDefaultLocale()` will be used to get default locale. If you do not want any default locale and want translated fields for all locales to be stored in translation table then set this config to empty string `''`.
* `allowEmptyTranslations`: By default if a record has been translated and stored as an empty string the translate behavior will take and use this value to overwrite the original field value. If you don't want this behavior then set this option to `false`.
* `validator`: The validator that should be used when translation records are created/modified. Default `null`.
#### Parameters
`Cake\ORM\Table` $table The table this behavior is attached to.
`array<string, mixed>` $config optional The config for this behavior.
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_reflectionCache() protected
```
_reflectionCache(): array
```
Gets the methods implemented by this behavior
Uses the implementedEvents() method to exclude callback methods. Methods starting with `_` will be ignored, as will methods declared on Cake\ORM\Behavior
#### Returns
`array`
#### Throws
`ReflectionException`
### \_resolveMethodAliases() protected
```
_resolveMethodAliases(string $key, array<string, mixed> $defaults, array<string, mixed> $config): array
```
Removes aliased methods that would otherwise be duplicated by userland configuration.
#### Parameters
`string` $key The key to filter.
`array<string, mixed>` $defaults The default method mappings.
`array<string, mixed>` $config The customized method mappings.
#### Returns
`array`
### buildMarshalMap() public
```
buildMarshalMap(Cake\ORM\Marshaller $marshaller, array $map, array<string, mixed> $options): array
```
Build a set of properties that should be included in the marshalling process.
Add in `_translations` marshalling handlers. You can disable marshalling of translations by setting `'translations' => false` in the options provided to `Table::newEntity()` or `Table::patchEntity()`.
#### Parameters
`Cake\ORM\Marshaller` $marshaller The marhshaller of the table the behavior is attached to.
`array` $map The property map being built.
`array<string, mixed>` $options The options array used in the marshalling call.
#### Returns
`array`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### createStrategy() protected
```
createStrategy(): Cake\ORM\Behavior\Translate\TranslateStrategyInterface
```
Create strategy instance.
#### Returns
`Cake\ORM\Behavior\Translate\TranslateStrategyInterface`
### findTranslations() public
```
findTranslations(Cake\ORM\Query $query, array<string, mixed> $options): Cake\ORM\Query
```
Custom finder method used to retrieve all translations for the found records. Fetched translations can be filtered by locale by passing the `locales` key in the options array.
Translated values will be found for each entity under the property `_translations`, containing an array indexed by locale name.
### Example:
```
$article = $articles->find('translations', ['locales' => ['eng', 'deu'])->first();
$englishTranslatedFields = $article->get('_translations')['eng'];
```
If the `locales` array is not passed, it will bring all translations found for each record.
#### Parameters
`Cake\ORM\Query` $query The original query to modify
`array<string, mixed>` $options Options
#### Returns
`Cake\ORM\Query`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getDefaultStrategyClass() public static
```
getDefaultStrategyClass(): string
```
Get default strategy class name.
#### Returns
`string`
### getLocale() public
```
getLocale(): string
```
Returns the current locale.
If no locale has been explicitly set via `setLocale()`, this method will return the currently configured global locale.
#### Returns
`string`
#### See Also
\Cake\I18n\I18n::getLocale()
\Cake\ORM\Behavior\TranslateBehavior::setLocale() ### getStrategy() public
```
getStrategy(): Cake\ORM\Behavior\Translate\TranslateStrategyInterface
```
Get strategy class instance.
#### Returns
`Cake\ORM\Behavior\Translate\TranslateStrategyInterface`
### getTable() public
```
getTable(): Cake\ORM\Table
```
Get the table instance this behavior is bound to.
#### Returns
`Cake\ORM\Table`
### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Gets the Model callbacks this behavior is interested in.
By defining one of the callback methods a behavior is assumed to be interested in the related event.
Override this method if you need to add non-conventional event listeners. Or if you want your behavior to listen to non-standard events.
#### Returns
`array<string, mixed>`
### implementedFinders() public
```
implementedFinders(): array
```
implementedFinders
Provides an alias->methodname map of which finders a behavior implements. Example:
```
[
'this' => 'findThis',
'alias' => 'findMethodName'
]
```
With the above example, a call to `$table->find('this')` will call `$behavior->findThis()` and a call to `$table->find('alias')` will call `$behavior->findMethodName()`
It is recommended, though not required, to define implementedFinders in the config property of child classes such that it is not necessary to use reflections to derive the available method list. See core behaviors for examples
#### Returns
`array`
#### Throws
`ReflectionException`
### implementedMethods() public
```
implementedMethods(): array
```
implementedMethods
Provides an alias->methodname map of which methods a behavior implements. Example:
```
[
'method' => 'method',
'aliasedMethod' => 'somethingElse'
]
```
With the above example, a call to `$table->method()` will call `$behavior->method()` and a call to `$table->aliasedMethod()` will call `$behavior->somethingElse()`
It is recommended, though not required, to define implementedFinders in the config property of child classes such that it is not necessary to use reflections to derive the available method list. See core behaviors for examples
#### Returns
`array`
#### Throws
`ReflectionException`
### initialize() public
```
initialize(array<string, mixed> $config): void
```
Initialize hook
Implement this method to avoid having to overwrite the constructor and call parent.
#### Parameters
`array<string, mixed>` $config The config for this behavior.
#### Returns
`void`
### referenceName() protected
```
referenceName(Cake\ORM\Table $table): string
```
Determine the reference name to use for a given table
The reference name is usually derived from the class name of the table object (PostsTable -> Posts), however for autotable instances it is derived from the database table the object points at - or as a last resort, the alias of the autotable instance.
#### Parameters
`Cake\ORM\Table` $table The table class to get a reference name for.
#### Returns
`string`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setDefaultStrategyClass() public static
```
setDefaultStrategyClass(string $class): void
```
Set default strategy class name.
#### Parameters
`string` $class Class name.
#### Returns
`void`
### setLocale() public
```
setLocale(string|null $locale): $this
```
Sets the locale that should be used for all future find and save operations on the table where this behavior is attached to.
When fetching records, the behavior will include the content for the locale set via this method, and likewise when saving data, it will save the data in that locale.
Note that in case an entity has a `_locale` property set, that locale will win over the locale set via this method (and over the globally configured one for that matter)!
#### Parameters
`string|null` $locale The locale to use for fetching and saving records. Pass `null` in order to unset the current locale, and to make the behavior fall back to using the globally configured locale.
#### Returns
`$this`
#### See Also
\Cake\ORM\Behavior\TranslateBehavior::getLocale() #### Links
https://book.cakephp.org/4/en/orm/behaviors/translate.html#retrieving-one-language-without-using-i18n-locale
https://book.cakephp.org/4/en/orm/behaviors/translate.html#saving-in-another-language
### setStrategy() public
```
setStrategy(Cake\ORM\Behavior\Translate\TranslateStrategyInterface $strategy): $this
```
Set strategy class instance.
#### Parameters
`Cake\ORM\Behavior\Translate\TranslateStrategyInterface` $strategy Strategy class instance.
#### Returns
`$this`
### table() public
```
table(): Cake\ORM\Table
```
Get the table instance this behavior is bound to.
#### Returns
`Cake\ORM\Table`
### translationField() public
```
translationField(string $field): string
```
Returns a fully aliased field name for translated fields.
If the requested field is configured as a translation field, the `content` field with an alias of a corresponding association is returned. Table-aliased field name is returned for all other fields.
#### Parameters
`string` $field Field name to be aliased.
#### Returns
`string`
### verifyConfig() public
```
verifyConfig(): void
```
verifyConfig
Checks that implemented keys contain values pointing at callable.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if config are invalid Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config
These are merged with user-provided configuration when the behavior is used.
#### Type
`array<string, mixed>`
### $\_reflectionCache protected static
Reflection method cache for behaviors.
Stores the reflected method + finder methods per class. This prevents reflecting the same class multiple times in a single process.
#### Type
`array<string, array>`
### $\_table protected
Table instance.
#### Type
`Cake\ORM\Table`
### $defaultStrategyClass protected static
Default strategy class name.
#### Type
`string`
### $strategy protected
Translation strategy instance.
#### Type
`Cake\ORM\Behavior\Translate\TranslateStrategyInterface|null`
| programming_docs |
cakephp Namespace Error Namespace Error
===============
### Namespaces
* [Cake\Error\Debug](namespace-cake.error.debug)
* [Cake\Error\Middleware](namespace-cake.error.middleware)
* [Cake\Error\Renderer](namespace-cake.error.renderer)
### Interfaces
* ##### [ErrorLoggerInterface](interface-cake.error.errorloggerinterface)
Interface for error logging handlers.
* ##### [ErrorRendererInterface](interface-cake.error.errorrendererinterface)
Interface for PHP error rendering implementations
* ##### [ExceptionRendererInterface](interface-cake.error.exceptionrendererinterface)
Interface ExceptionRendererInterface
### Classes
* ##### [BaseErrorHandler](class-cake.error.baseerrorhandler)
Base error handler that provides logic common to the CLI + web error/exception handlers.
* ##### [ConsoleErrorHandler](class-cake.error.consoleerrorhandler)
Error Handler for Cake console. Does simple printing of the exception that occurred and the stack trace of the error.
* ##### [Debugger](class-cake.error.debugger)
Provide custom logging and error handling.
* ##### [ErrorHandler](class-cake.error.errorhandler)
Error Handler provides basic error and exception handling for your application. It captures and handles all unhandled exceptions and errors. Displays helpful framework errors when debug mode is on.
* ##### [ErrorLogger](class-cake.error.errorlogger)
Log errors and unhandled exceptions to `Cake\Log\Log`
* ##### [ErrorTrap](class-cake.error.errortrap)
Entry point to CakePHP's error handling.
* ##### [ExceptionRenderer](class-cake.error.exceptionrenderer)
Backwards compatible Exception Renderer.
* ##### [ExceptionTrap](class-cake.error.exceptiontrap)
Entry point to CakePHP's exception handling.
* ##### [FatalErrorException](class-cake.error.fatalerrorexception)
Represents a fatal error
* ##### [PhpError](class-cake.error.phperror)
Object wrapper around PHP errors that are emitted by `trigger_error()`
cakephp Class UnauthorizedException Class UnauthorizedException
============================
Represents an HTTP 401 error.
**Namespace:** [Cake\Http\Exception](namespace-cake.http.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
* [$headers](#%24headers) protected `array<string, mixed>`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [getHeaders()](#getHeaders()) public
Returns array of response headers.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
* ##### [setHeader()](#setHeader()) public
Set a single HTTP response header.
* ##### [setHeaders()](#setHeaders()) public
Sets HTTP response headers.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $message = null, int|null $code = null, Throwable|null $previous = null)
```
Constructor
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`string|null` $message optional If no message is given 'Unauthorized' will be the message
`int|null` $code optional Status code, defaults to 401
`Throwable|null` $previous optional The previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### getHeaders() public
```
getHeaders(): array<string, mixed>
```
Returns array of response headers.
#### Returns
`array<string, mixed>`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
### setHeader() public
```
setHeader(string $header, array<string>|string|null $value = null): void
```
Set a single HTTP response header.
#### Parameters
`string` $header Header name
`array<string>|string|null` $value optional Header value
#### Returns
`void`
### setHeaders() public
```
setHeaders(array<string, mixed> $headers): void
```
Sets HTTP response headers.
#### Parameters
`array<string, mixed>` $headers Array of header name and value pairs.
#### Returns
`void`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
### $headers protected
#### Type
`array<string, mixed>`
cakephp Class BodyNotEquals Class BodyNotEquals
====================
BodyNotEquals
**Namespace:** [Cake\TestSuite\Constraint\Response](namespace-cake.testsuite.constraint.response)
Property Summary
----------------
* [$response](#%24response) protected `Psr\Http\Message\ResponseInterface`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_getBodyAsString()](#_getBodyAsString()) protected
Get the response body as string
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Checks assertion
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(Psr\Http\Message\ResponseInterface|null $response)
```
Constructor
#### Parameters
`Psr\Http\Message\ResponseInterface|null` $response Response
### \_getBodyAsString() protected
```
_getBodyAsString(): string
```
Get the response body as string
#### Returns
`string`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks assertion
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Expected type
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $response protected
#### Type
`Psr\Http\Message\ResponseInterface`
cakephp Class MissingMailerException Class MissingMailerException
=============================
Used when a mailer cannot be found.
**Namespace:** [Cake\Mailer\Exception](namespace-cake.mailer.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Class FormData Class FormData
===============
Provides an interface for building multipart/form-encoded message bodies.
Used by Http\Client to upload POST/PUT data and files.
**Namespace:** [Cake\Http\Client](namespace-cake.http.client)
Property Summary
----------------
* [$\_boundary](#%24_boundary) protected `string` Boundary marker.
* [$\_hasComplexPart](#%24_hasComplexPart) protected `bool` Whether this formdata object has a complex part.
* [$\_hasFile](#%24_hasFile) protected `bool` Whether this formdata object has attached files.
* [$\_parts](#%24_parts) protected `arrayCake\Http\Client\FormDataPart>` The parts in the form data.
Method Summary
--------------
* ##### [\_\_toString()](#__toString()) public
Converts the FormData and its parts into a string suitable for use in an HTTP request.
* ##### [add()](#add()) public
Add a new part to the data.
* ##### [addFile()](#addFile()) public
Add either a file reference (string starting with @) or a file handle.
* ##### [addMany()](#addMany()) public
Add multiple parts at once.
* ##### [addRecursive()](#addRecursive()) public
Recursively add data.
* ##### [boundary()](#boundary()) public
Get the boundary marker
* ##### [contentType()](#contentType()) public
Get the content type for this payload.
* ##### [count()](#count()) public
Returns the count of parts inside this object.
* ##### [hasFile()](#hasFile()) public
Check whether the current payload has any files.
* ##### [isMultipart()](#isMultipart()) public
Check whether the current payload is multipart.
* ##### [newPart()](#newPart()) public
Method for creating new instances of Part
Method Detail
-------------
### \_\_toString() public
```
__toString(): string
```
Converts the FormData and its parts into a string suitable for use in an HTTP request.
#### Returns
`string`
### add() public
```
add(Cake\Http\Client\FormDataPart|string $name, mixed $value = null): $this
```
Add a new part to the data.
The value for a part can be a string, array, int, float, filehandle, or object implementing \_\_toString()
If the $value is an array, multiple parts will be added. Files will be read from their current position and saved in memory.
#### Parameters
`Cake\Http\Client\FormDataPart|string` $name The name of the part to add, or the part data object.
`mixed` $value optional The value for the part.
#### Returns
`$this`
### addFile() public
```
addFile(string $name, string|resourcePsr\Http\Message\UploadedFileInterface $value): Cake\Http\Client\FormDataPart
```
Add either a file reference (string starting with @) or a file handle.
#### Parameters
`string` $name The name to use.
`string|resourcePsr\Http\Message\UploadedFileInterface` $value Either a string filename, or a filehandle, or a UploadedFileInterface instance.
#### Returns
`Cake\Http\Client\FormDataPart`
### addMany() public
```
addMany(array $data): $this
```
Add multiple parts at once.
Iterates the parameter and adds all the key/values.
#### Parameters
`array` $data Array of data to add.
#### Returns
`$this`
### addRecursive() public
```
addRecursive(string $name, mixed $value): void
```
Recursively add data.
#### Parameters
`string` $name The name to use.
`mixed` $value The value to add.
#### Returns
`void`
### boundary() public
```
boundary(): string
```
Get the boundary marker
#### Returns
`string`
### contentType() public
```
contentType(): string
```
Get the content type for this payload.
If this object contains files, `multipart/form-data` will be used, otherwise `application/x-www-form-urlencoded` will be used.
#### Returns
`string`
### count() public
```
count(): int
```
Returns the count of parts inside this object.
#### Returns
`int`
### hasFile() public
```
hasFile(): bool
```
Check whether the current payload has any files.
#### Returns
`bool`
### isMultipart() public
```
isMultipart(): bool
```
Check whether the current payload is multipart.
A payload will become multipart when you add files or use add() with a Part instance.
#### Returns
`bool`
### newPart() public
```
newPart(string $name, string $value): Cake\Http\Client\FormDataPart
```
Method for creating new instances of Part
#### Parameters
`string` $name The name of the part.
`string` $value The value to add.
#### Returns
`Cake\Http\Client\FormDataPart`
Property Detail
---------------
### $\_boundary protected
Boundary marker.
#### Type
`string`
### $\_hasComplexPart protected
Whether this formdata object has a complex part.
#### Type
`bool`
### $\_hasFile protected
Whether this formdata object has attached files.
#### Type
`bool`
### $\_parts protected
The parts in the form data.
#### Type
`arrayCake\Http\Client\FormDataPart>`
| programming_docs |
cakephp Class PaginatorComponent Class PaginatorComponent
=========================
This component is used to handle automatic model data pagination. The primary way to use this component is to call the paginate() method. There is a convenience wrapper on Controller as well.
### Configuring pagination
You configure pagination when calling paginate(). See that method for more details.
**Namespace:** [Cake\Controller\Component](namespace-cake.controller.component)
**Deprecated:** 4.4.0 Use Cake\Datasource\Paging\Paginator directly.
**Link:** https://book.cakephp.org/4/en/controllers/components/pagination.html
Property Summary
----------------
* [$\_componentMap](#%24_componentMap) protected `array<string, array>` A component lookup table used to lazy load component objects.
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config
* [$\_paginator](#%24_paginator) protected `Cake\Datasource\Paging\NumericPaginator` Datasource paginator instance.
* [$\_registry](#%24_registry) protected `Cake\Controller\ComponentRegistry` Component registry class used to lazy load components.
* [$components](#%24components) protected `array` Other Components this component uses.
Method Summary
--------------
* ##### [\_\_call()](#__call()) public
Proxy method calls to Paginator.
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_get()](#__get()) public
Magic method for lazy loading $components.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_setPagingParams()](#_setPagingParams()) protected
Set paging params to request instance.
* ##### [configShallow()](#configShallow()) public
Proxy setting config options to Paginator.
* ##### [getConfig()](#getConfig()) public
Proxy getting config options to Paginator.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getController()](#getController()) public
Get the controller this component is bound to.
* ##### [getPaginator()](#getPaginator()) public
Get paginator instance.
* ##### [implementedEvents()](#implementedEvents()) public
Events supported by this component.
* ##### [initialize()](#initialize()) public
Constructor hook method.
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [mergeOptions()](#mergeOptions()) public
Merges the various options that Pagination uses. Pulls settings together from the following places:
* ##### [paginate()](#paginate()) public
Handles automatic pagination of model records.
* ##### [setConfig()](#setConfig()) public
Proxy setting config options to Paginator.
* ##### [setPaginator()](#setPaginator()) public
Set paginator instance.
Method Detail
-------------
### \_\_call() public
```
__call(string $method, array $args): mixed
```
Proxy method calls to Paginator.
#### Parameters
`string` $method Method name.
`array` $args Method arguments.
#### Returns
`mixed`
### \_\_construct() public
```
__construct(Cake\Controller\ComponentRegistry $registry, array<string, mixed> $config = [])
```
Constructor
#### Parameters
`Cake\Controller\ComponentRegistry` $registry `array<string, mixed>` $config optional ### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): Cake\Controller\Component|null
```
Magic method for lazy loading $components.
#### Parameters
`string` $name Name of component to get.
#### Returns
`Cake\Controller\Component|null`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_setPagingParams() protected
```
_setPagingParams(): void
```
Set paging params to request instance.
#### Returns
`void`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Proxy setting config options to Paginator.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Proxy getting config options to Paginator.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getController() public
```
getController(): Cake\Controller\Controller
```
Get the controller this component is bound to.
#### Returns
`Cake\Controller\Controller`
### getPaginator() public
```
getPaginator(): Cake\Datasource\Paging\NumericPaginator
```
Get paginator instance.
#### Returns
`Cake\Datasource\Paging\NumericPaginator`
### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Events supported by this component.
Uses Conventions to map controller events to standard component callback method names. By defining one of the callback methods a component is assumed to be interested in the related event.
Override this method if you need to add non-conventional event listeners. Or if you want components to listen to non-standard events.
#### Returns
`array<string, mixed>`
### initialize() public
```
initialize(array<string, mixed> $config): void
```
Constructor hook method.
Implement this method to avoid having to overwrite the constructor and call parent.
#### Parameters
`array<string, mixed>` $config The configuration settings provided to this component.
#### Returns
`void`
### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### mergeOptions() public
```
mergeOptions(string $alias, array<string, mixed> $settings): array<string, mixed>
```
Merges the various options that Pagination uses. Pulls settings together from the following places:
* General pagination settings
* Model specific settings.
* Request parameters
The result of this method is the aggregate of all the option sets combined together. You can change config value `allowedParameters` to modify which options/values can be set using request parameters.
#### Parameters
`string` $alias Model alias being paginated, if the general settings has a key with this value that key's settings will be used for pagination instead of the general ones.
`array<string, mixed>` $settings The settings to merge with the request data.
#### Returns
`array<string, mixed>`
### paginate() public
```
paginate(Cake\Datasource\RepositoryInterfaceCake\Datasource\QueryInterface $object, array<string, mixed> $settings = []): Cake\Datasource\ResultSetInterface
```
Handles automatic pagination of model records.
### Configuring pagination
When calling `paginate()` you can use the $settings parameter to pass in pagination settings. These settings are used to build the queries made and control other pagination settings.
If your settings contain a key with the current table's alias. The data inside that key will be used. Otherwise, the top level configuration will be used.
```
$settings = [
'limit' => 20,
'maxLimit' => 100
];
$results = $paginator->paginate($table, $settings);
```
The above settings will be used to paginate any Table. You can configure Table specific settings by keying the settings with the Table alias.
```
$settings = [
'Articles' => [
'limit' => 20,
'maxLimit' => 100
],
'Comments' => [ ... ]
];
$results = $paginator->paginate($table, $settings);
```
This would allow you to have different pagination settings for `Articles` and `Comments` tables.
### Controlling sort fields
By default CakePHP will automatically allow sorting on any column on the table object being paginated. Often times you will want to allow sorting on either associated columns or calculated fields. In these cases you will need to define an allowed list of fields you wish to allow sorting on. You can define the allowed fields in the `$settings` parameter:
```
$settings = [
'Articles' => [
'finder' => 'custom',
'sortableFields' => ['title', 'author_id', 'comment_count'],
]
];
```
Passing an empty array as allowed list disallows sorting altogether.
### Paginating with custom finders
You can paginate with any find type defined on your table using the `finder` option.
```
$settings = [
'Articles' => [
'finder' => 'popular'
]
];
$results = $paginator->paginate($table, $settings);
```
Would paginate using the `find('popular')` method.
You can also pass an already created instance of a query to this method:
```
$query = $this->Articles->find('popular')->matching('Tags', function ($q) {
return $q->where(['name' => 'CakePHP'])
});
$results = $paginator->paginate($query);
```
### Scoping Request parameters
By using request parameter scopes you can paginate multiple queries in the same controller action:
```
$articles = $paginator->paginate($articlesQuery, ['scope' => 'articles']);
$tags = $paginator->paginate($tagsQuery, ['scope' => 'tags']);
```
Each of the above queries will use different query string parameter sets for pagination data. An example URL paginating both results would be:
```
/dashboard?articles[page]=1&tags[page]=2
```
#### Parameters
`Cake\Datasource\RepositoryInterfaceCake\Datasource\QueryInterface` $object Table or query to paginate.
`array<string, mixed>` $settings optional The settings/configuration used for pagination.
#### Returns
`Cake\Datasource\ResultSetInterface`
#### Throws
`Cake\Http\Exception\NotFoundException`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Proxy setting config options to Paginator.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
### setPaginator() public
```
setPaginator(Cake\Datasource\Paging\NumericPaginator $paginator): $this
```
Set paginator instance.
#### Parameters
`Cake\Datasource\Paging\NumericPaginator` $paginator Paginator instance.
#### Returns
`$this`
Property Detail
---------------
### $\_componentMap protected
A component lookup table used to lazy load component objects.
#### Type
`array<string, array>`
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config
These are merged with user-provided config when the component is used.
#### Type
`array<string, mixed>`
### $\_paginator protected
Datasource paginator instance.
#### Type
`Cake\Datasource\Paging\NumericPaginator`
### $\_registry protected
Component registry class used to lazy load components.
#### Type
`Cake\Controller\ComponentRegistry`
### $components protected
Other Components this component uses.
#### Type
`array`
cakephp Trait CookieCryptTrait Trait CookieCryptTrait
=======================
Cookie Crypt Trait.
Provides the encrypt/decrypt logic for the CookieComponent.
**Namespace:** [Cake\Utility](namespace-cake.utility)
**Link:** https://book.cakephp.org/4/en/controllers/components/cookie.html
Property Summary
----------------
* [$\_validCiphers](#%24_validCiphers) protected `array<string>` Valid cipher names for encrypted cookies.
Method Summary
--------------
* ##### [\_checkCipher()](#_checkCipher()) protected
Helper method for validating encryption cipher names.
* ##### [\_decode()](#_decode()) protected
Decodes and decrypts a single value.
* ##### [\_decrypt()](#_decrypt()) protected
Decrypts $value using public $type method in Security class
* ##### [\_encrypt()](#_encrypt()) protected
Encrypts $value using public $type method in Security class
* ##### [\_explode()](#_explode()) protected
Explode method to return array from string set in CookieComponent::\_implode() Maintains reading backwards compatibility with 1.x CookieComponent::\_implode().
* ##### [\_getCookieEncryptionKey()](#_getCookieEncryptionKey()) abstract protected
Returns the encryption key to be used.
* ##### [\_implode()](#_implode()) protected
Implode method to keep keys are multidimensional arrays
Method Detail
-------------
### \_checkCipher() protected
```
_checkCipher(string $encrypt): void
```
Helper method for validating encryption cipher names.
#### Parameters
`string` $encrypt The cipher name.
#### Returns
`void`
#### Throws
`RuntimeException`
When an invalid cipher is provided. ### \_decode() protected
```
_decode(string $value, string|false $encrypt, string|null $key): array|string
```
Decodes and decrypts a single value.
#### Parameters
`string` $value The value to decode & decrypt.
`string|false` $encrypt The encryption cipher to use.
`string|null` $key Used as the security salt if specified.
#### Returns
`array|string`
### \_decrypt() protected
```
_decrypt(array<string>|string $values, string|false $mode, string|null $key = null): array|string
```
Decrypts $value using public $type method in Security class
#### Parameters
`array<string>|string` $values Values to decrypt
`string|false` $mode Encryption mode
`string|null` $key optional Used as the security salt if specified.
#### Returns
`array|string`
### \_encrypt() protected
```
_encrypt(array|string $value, string|false $encrypt, string|null $key = null): string
```
Encrypts $value using public $type method in Security class
#### Parameters
`array|string` $value Value to encrypt
`string|false` $encrypt Encryption mode to use. False disabled encryption.
`string|null` $key optional Used as the security salt if specified.
#### Returns
`string`
### \_explode() protected
```
_explode(string $string): array|string
```
Explode method to return array from string set in CookieComponent::\_implode() Maintains reading backwards compatibility with 1.x CookieComponent::\_implode().
#### Parameters
`string` $string A string containing JSON encoded data, or a bare string.
#### Returns
`array|string`
### \_getCookieEncryptionKey() abstract protected
```
_getCookieEncryptionKey(): string
```
Returns the encryption key to be used.
#### Returns
`string`
### \_implode() protected
```
_implode(array $array): string
```
Implode method to keep keys are multidimensional arrays
#### Parameters
`array` $array Map of key and values
#### Returns
`string`
Property Detail
---------------
### $\_validCiphers protected
Valid cipher names for encrypted cookies.
#### Type
`array<string>`
cakephp Class DefaultPasswordHasher Class DefaultPasswordHasher
============================
Default password hashing class.
**Namespace:** [Cake\Auth](namespace-cake.auth)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this object.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [check()](#check()) public
Check hash. Generate hash for user provided password and check against existing hash.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [hash()](#hash()) public
Generates password hash.
* ##### [needsRehash()](#needsRehash()) public
Returns true if the password need to be rehashed, due to the password being created with anything else than the passwords generated by this class.
* ##### [setConfig()](#setConfig()) public
Sets the config.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Constructor
#### Parameters
`array<string, mixed>` $config optional Array of config.
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### check() public
```
check(string $password, string $hashedPassword): bool
```
Check hash. Generate hash for user provided password and check against existing hash.
#### Parameters
`string` $password Plain text password to hash.
`string` $hashedPassword Existing hashed password.
#### Returns
`bool`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### hash() public
```
hash(string $password): string|false
```
Generates password hash.
#### Parameters
`string` $password Plain text password to hash.
#### Returns
`string|false`
#### Links
https://book.cakephp.org/4/en/controllers/components/authentication.html#hashing-passwords
### needsRehash() public
```
needsRehash(string $password): bool
```
Returns true if the password need to be rehashed, due to the password being created with anything else than the passwords generated by this class.
Returns true by default since the only implementation users should rely on is the one provided by default in php 5.5+ or any compatible library
#### Parameters
`string` $password The password to verify
#### Returns
`bool`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this object.
### Options
* `hashType` - Hashing algo to use. Valid values are those supported by `$algo` argument of `password_hash()`. Defaults to `PASSWORD_DEFAULT`
* `hashOptions` - Associative array of options. Check the PHP manual for supported options for each hash type. Defaults to empty array.
#### Type
`array<string, mixed>`
| programming_docs |
cakephp Namespace Paging Namespace Paging
================
### Namespaces
* [Cake\Datasource\Paging\Exception](namespace-cake.datasource.paging.exception)
### Interfaces
* ##### [PaginatorInterface](interface-cake.datasource.paging.paginatorinterface)
This interface describes the methods for paginator instance.
### Classes
* ##### [NumericPaginator](class-cake.datasource.paging.numericpaginator)
This class is used to handle automatic model data pagination.
* ##### [SimplePaginator](class-cake.datasource.paging.simplepaginator)
Simplified paginator which avoids potentially expensives queries to get the total count of records.
cakephp Class StringType Class StringType
=================
String type converter.
Use to convert string data between PHP and the database types.
**Namespace:** [Cake\Database\Type](namespace-cake.database.type)
Property Summary
----------------
* [$\_name](#%24_name) protected `string|null` Identifier name for this type
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getBaseType()](#getBaseType()) public
Returns the base type name that this class is inheriting.
* ##### [getName()](#getName()) public
Returns type identifier name for this object.
* ##### [marshal()](#marshal()) public
Marshals request data into PHP strings.
* ##### [newId()](#newId()) public
Generate a new primary key value for a given type.
* ##### [requiresToPhpCast()](#requiresToPhpCast()) public
Returns whether the cast to PHP is required to be invoked, since it is not a identity function.
* ##### [toDatabase()](#toDatabase()) public
Convert string data into the database format.
* ##### [toPHP()](#toPHP()) public
Convert string values to PHP strings.
* ##### [toStatement()](#toStatement()) public
Get the correct PDO binding type for string data.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $name = null)
```
Constructor
#### Parameters
`string|null` $name optional The name identifying this type
### getBaseType() public
```
getBaseType(): string|null
```
Returns the base type name that this class is inheriting.
This is useful when extending base type for adding extra functionality, but still want the rest of the framework to use the same assumptions it would do about the base type it inherits from.
#### Returns
`string|null`
### getName() public
```
getName(): string|null
```
Returns type identifier name for this object.
#### Returns
`string|null`
### marshal() public
```
marshal(mixed $value): string|null
```
Marshals request data into PHP strings.
Most useful for converting request data into PHP objects, that make sense for the rest of the ORM/Database layers.
#### Parameters
`mixed` $value The value to convert.
#### Returns
`string|null`
### newId() public
```
newId(): mixed
```
Generate a new primary key value for a given type.
This method can be used by types to create new primary key values when entities are inserted.
#### Returns
`mixed`
### requiresToPhpCast() public
```
requiresToPhpCast(): bool
```
Returns whether the cast to PHP is required to be invoked, since it is not a identity function.
#### Returns
`bool`
### toDatabase() public
```
toDatabase(mixed $value, Cake\Database\DriverInterface $driver): string|null
```
Convert string data into the database format.
#### Parameters
`mixed` $value The value to convert.
`Cake\Database\DriverInterface` $driver The driver instance to convert with.
#### Returns
`string|null`
### toPHP() public
```
toPHP(mixed $value, Cake\Database\DriverInterface $driver): string|null
```
Convert string values to PHP strings.
#### Parameters
`mixed` $value The value to convert.
`Cake\Database\DriverInterface` $driver The driver instance to convert with.
#### Returns
`string|null`
### toStatement() public
```
toStatement(mixed $value, Cake\Database\DriverInterface $driver): int
```
Get the correct PDO binding type for string data.
#### Parameters
`mixed` $value The value being bound.
`Cake\Database\DriverInterface` $driver The driver.
#### Returns
`int`
Property Detail
---------------
### $\_name protected
Identifier name for this type
#### Type
`string|null`
cakephp Namespace Email Namespace Email
===============
### Classes
* ##### [MailConstraintBase](class-cake.testsuite.constraint.email.mailconstraintbase)
Base class for all mail assertion constraints
* ##### [MailContains](class-cake.testsuite.constraint.email.mailcontains)
MailContains
* ##### [MailContainsAttachment](class-cake.testsuite.constraint.email.mailcontainsattachment)
MailContainsAttachment
* ##### [MailContainsHtml](class-cake.testsuite.constraint.email.mailcontainshtml)
MailContainsHtml
* ##### [MailContainsText](class-cake.testsuite.constraint.email.mailcontainstext)
MailContainsText
* ##### [MailCount](class-cake.testsuite.constraint.email.mailcount)
MailCount
* ##### [MailSentFrom](class-cake.testsuite.constraint.email.mailsentfrom)
MailSentFromConstraint
* ##### [MailSentTo](class-cake.testsuite.constraint.email.mailsentto)
MailSentTo
* ##### [MailSentWith](class-cake.testsuite.constraint.email.mailsentwith)
MailSentWith
* ##### [MailSubjectContains](class-cake.testsuite.constraint.email.mailsubjectcontains)
MailSubjectContains
* ##### [NoMailSent](class-cake.testsuite.constraint.email.nomailsent)
NoMailSent
cakephp Class Response Class Response
===============
Responses contain the response text, status and headers of a HTTP response.
There are external packages such as `fig/http-message-util` that provide HTTP status code constants. These can be used with any method that accepts or returns a status code integer. Keep in mind that these constants might include status codes that are now allowed which will throw an `\InvalidArgumentException`.
**Namespace:** [Cake\Http](namespace-cake.http)
Constants
---------
* `int` **STATUS\_CODE\_MAX**
```
599
```
* `int` **STATUS\_CODE\_MIN**
```
100
```
Property Summary
----------------
* [$\_cacheDirectives](#%24_cacheDirectives) protected `array<string, mixed>` Holds all the cache directives that will be converted into headers when sending the request
* [$\_charset](#%24_charset) protected `string` The charset the response body is encoded with
* [$\_cookies](#%24_cookies) protected `Cake\Http\Cookie\CookieCollection` Collection of cookies to send to the client
* [$\_file](#%24_file) protected `SplFileInfo|null` File object for file to be read out as response
* [$\_fileRange](#%24_fileRange) protected `array<int>` File range. Used for requesting ranges of files.
* [$\_mimeTypes](#%24_mimeTypes) protected `array<string, mixed>` Holds type key to mime type mappings for known mime types.
* [$\_reasonPhrase](#%24_reasonPhrase) protected `string` Reason Phrase
* [$\_status](#%24_status) protected `int` Status code to send to the client
* [$\_statusCodes](#%24_statusCodes) protected `array<int, string>` Allowed HTTP status codes and their default description.
* [$\_streamMode](#%24_streamMode) protected `string` Stream mode options.
* [$\_streamTarget](#%24_streamTarget) protected `resource|string` Stream target or resource object.
* [$headerNames](#%24headerNames) protected `array` Map of normalized header name to original name used to register header.
* [$headers](#%24headers) protected `array` List of all registered headers, as key => array of values.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_toString()](#__toString()) public
String conversion. Fetches the response body as a string. Does *not* send headers. If body is a callable, a blank string is returned.
* ##### [\_clearHeader()](#_clearHeader()) protected
Clear header
* ##### [\_createStream()](#_createStream()) protected
Creates the stream object.
* ##### [\_fileRange()](#_fileRange()) protected
Apply a file range to a file and set the end offset.
* ##### [\_getUTCDate()](#_getUTCDate()) protected
Returns a DateTime object initialized at the $time param and using UTC as timezone
* ##### [\_setCacheControl()](#_setCacheControl()) protected
Helper method to generate a valid Cache-Control header from the options set in other methods
* ##### [\_setContentType()](#_setContentType()) protected
Formats the Content-Type header based on the configured contentType and charset the charset will only be set in the header if the response is of type text/\*
* ##### [\_setHeader()](#_setHeader()) protected
Sets a header.
* ##### [\_setStatus()](#_setStatus()) protected
Modifier for response status
* ##### [checkNotModified()](#checkNotModified()) public deprecated
Checks whether a response has not been modified according to the 'If-None-Match' (Etags) and 'If-Modified-Since' (last modification date) request headers. If the response is detected to be not modified, it is marked as so accordingly so the client can be informed of that.
* ##### [compress()](#compress()) public
Sets the correct output buffering handler to send a compressed response. Responses will be compressed with zlib, if the extension is available.
* ##### [cors()](#cors()) public
Get a CorsBuilder instance for defining CORS headers.
* ##### [getBody()](#getBody()) public
Gets the body of the message.
* ##### [getCharset()](#getCharset()) public
Returns the current charset.
* ##### [getCookie()](#getCookie()) public
Read a single cookie from the response.
* ##### [getCookieCollection()](#getCookieCollection()) public
Get the CookieCollection from the response
* ##### [getCookies()](#getCookies()) public
Get all cookies in the response.
* ##### [getFile()](#getFile()) public
Get the current file if one exists.
* ##### [getHeader()](#getHeader()) public
Retrieves a message header value by the given case-insensitive name.
* ##### [getHeaderLine()](#getHeaderLine()) public
Retrieves a comma-separated string of the values for a single header.
* ##### [getHeaders()](#getHeaders()) public
Retrieves all message headers.
* ##### [getMimeType()](#getMimeType()) public
Returns the mime type definition for an alias
* ##### [getProtocolVersion()](#getProtocolVersion()) public
Retrieves the HTTP protocol version as a string.
* ##### [getReasonPhrase()](#getReasonPhrase()) public
Gets the response reason phrase associated with the status code.
* ##### [getStatusCode()](#getStatusCode()) public
Gets the response status code.
* ##### [getType()](#getType()) public
Returns the current content type.
* ##### [hasHeader()](#hasHeader()) public
Checks if a header exists by the given case-insensitive name.
* ##### [isNotModified()](#isNotModified()) public
Checks whether a response has not been modified according to the 'If-None-Match' (Etags) and 'If-Modified-Since' (last modification date) request headers.
* ##### [mapType()](#mapType()) public
Maps a content-type back to an alias
* ##### [notModified()](#notModified()) public deprecated
Sets the response as Not Modified by removing any body contents setting the status code to "304 Not Modified" and removing all conflicting headers
* ##### [outputCompressed()](#outputCompressed()) public
Returns whether the resulting output will be compressed by PHP
* ##### [resolveType()](#resolveType()) protected
Translate and validate content-types.
* ##### [setTypeMap()](#setTypeMap()) public
Sets a content type definition into the map.
* ##### [validateFile()](#validateFile()) protected
Validate a file path is a valid response body.
* ##### [withAddedHeader()](#withAddedHeader()) public
Return an instance with the specified header appended with the given value.
* ##### [withAddedLink()](#withAddedLink()) public
Create a new response with the Link header set.
* ##### [withBody()](#withBody()) public
Return an instance with the specified message body.
* ##### [withCache()](#withCache()) public
Create a new instance with the headers to enable client caching.
* ##### [withCharset()](#withCharset()) public
Get a new instance with an updated charset.
* ##### [withCookie()](#withCookie()) public
Create a new response with a cookie set.
* ##### [withCookieCollection()](#withCookieCollection()) public
Get a new instance with provided cookie collection.
* ##### [withDisabledCache()](#withDisabledCache()) public
Create a new instance with headers to instruct the client to not cache the response
* ##### [withDownload()](#withDownload()) public
Create a new instance with the Content-Disposition header set.
* ##### [withEtag()](#withEtag()) public
Create a new instance with the Etag header set.
* ##### [withExpiredCookie()](#withExpiredCookie()) public
Create a new response with an expired cookie set.
* ##### [withExpires()](#withExpires()) public
Create a new instance with the Expires header set.
* ##### [withFile()](#withFile()) public
Create a new instance that is based on a file.
* ##### [withHeader()](#withHeader()) public
Return an instance with the provided header, replacing any existing values of any headers with the same case-insensitive name.
* ##### [withLength()](#withLength()) public
Create a new response with the Content-Length header set.
* ##### [withLocation()](#withLocation()) public
Return an instance with an updated location header.
* ##### [withMaxAge()](#withMaxAge()) public
Create an instance with Cache-Control max-age directive set.
* ##### [withModified()](#withModified()) public
Create a new instance with the Last-Modified header set.
* ##### [withMustRevalidate()](#withMustRevalidate()) public
Create an instance with Cache-Control must-revalidate directive set.
* ##### [withNotModified()](#withNotModified()) public
Create a new instance as 'not modified'
* ##### [withProtocolVersion()](#withProtocolVersion()) public
Return an instance with the specified HTTP protocol version.
* ##### [withSharable()](#withSharable()) public
Create a new instace with the public/private Cache-Control directive set.
* ##### [withSharedMaxAge()](#withSharedMaxAge()) public
Create a new instance with the Cache-Control s-maxage directive.
* ##### [withStatus()](#withStatus()) public
Return an instance with the specified status code and, optionally, reason phrase.
* ##### [withStringBody()](#withStringBody()) public
Convenience method to set a string into the response body
* ##### [withType()](#withType()) public
Get an updated response with the content type set.
* ##### [withVary()](#withVary()) public
Create a new instance with the Vary header set.
* ##### [withoutHeader()](#withoutHeader()) public
Return an instance without the specified header.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $options = [])
```
Constructor
#### Parameters
`array<string, mixed>` $options optional list of parameters to setup the response. Possible values are:
#### Throws
`InvalidArgumentException`
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_toString() public
```
__toString(): string
```
String conversion. Fetches the response body as a string. Does *not* send headers. If body is a callable, a blank string is returned.
#### Returns
`string`
### \_clearHeader() protected
```
_clearHeader(string $header): void
```
Clear header
#### Parameters
`string` $header Header key.
#### Returns
`void`
### \_createStream() protected
```
_createStream(): void
```
Creates the stream object.
#### Returns
`void`
### \_fileRange() protected
```
_fileRange(SplFileInfo $file, string $httpRange): void
```
Apply a file range to a file and set the end offset.
If an invalid range is requested a 416 Status code will be used in the response.
#### Parameters
`SplFileInfo` $file The file to set a range on.
`string` $httpRange The range to use.
#### Returns
`void`
### \_getUTCDate() protected
```
_getUTCDate(DateTimeInterface|string|int|null $time = null): DateTimeInterface
```
Returns a DateTime object initialized at the $time param and using UTC as timezone
#### Parameters
`DateTimeInterface|string|int|null` $time optional Valid time string or \DateTimeInterface instance.
#### Returns
`DateTimeInterface`
### \_setCacheControl() protected
```
_setCacheControl(): void
```
Helper method to generate a valid Cache-Control header from the options set in other methods
#### Returns
`void`
### \_setContentType() protected
```
_setContentType(string $type): void
```
Formats the Content-Type header based on the configured contentType and charset the charset will only be set in the header if the response is of type text/\*
#### Parameters
`string` $type The type to set.
#### Returns
`void`
### \_setHeader() protected
```
_setHeader(string $header, string $value): void
```
Sets a header.
#### Parameters
`string` $header Header key.
`string` $value Header value.
#### Returns
`void`
### \_setStatus() protected
```
_setStatus(int $code, string $reasonPhrase = ''): void
```
Modifier for response status
#### Parameters
`int` $code The status code to set.
`string` $reasonPhrase optional The response reason phrase.
#### Returns
`void`
#### Throws
`InvalidArgumentException`
For invalid status code arguments. ### checkNotModified() public
```
checkNotModified(Cake\Http\ServerRequest $request): bool
```
Checks whether a response has not been modified according to the 'If-None-Match' (Etags) and 'If-Modified-Since' (last modification date) request headers. If the response is detected to be not modified, it is marked as so accordingly so the client can be informed of that.
In order to mark a response as not modified, you need to set at least the Last-Modified etag response header before calling this method. Otherwise a comparison will not be possible.
*Warning* This method mutates the response in-place and should be avoided.
#### Parameters
`Cake\Http\ServerRequest` $request Request object
#### Returns
`bool`
### compress() public
```
compress(): bool
```
Sets the correct output buffering handler to send a compressed response. Responses will be compressed with zlib, if the extension is available.
#### Returns
`bool`
### cors() public
```
cors(Cake\Http\ServerRequest $request): Cake\Http\CorsBuilder
```
Get a CorsBuilder instance for defining CORS headers.
#### Parameters
`Cake\Http\ServerRequest` $request Request object
#### Returns
`Cake\Http\CorsBuilder`
### getBody() public
```
getBody(): StreamInterface
```
Gets the body of the message.
#### Returns
`StreamInterface`
### getCharset() public
```
getCharset(): string
```
Returns the current charset.
#### Returns
`string`
### getCookie() public
```
getCookie(string $name): array|null
```
Read a single cookie from the response.
This method provides read access to pending cookies. It will not read the `Set-Cookie` header if set.
#### Parameters
`string` $name The cookie name you want to read.
#### Returns
`array|null`
### getCookieCollection() public
```
getCookieCollection(): Cake\Http\Cookie\CookieCollection
```
Get the CookieCollection from the response
#### Returns
`Cake\Http\Cookie\CookieCollection`
### getCookies() public
```
getCookies(): array<string, array>
```
Get all cookies in the response.
Returns an associative array of cookie name => cookie data.
#### Returns
`array<string, array>`
### getFile() public
```
getFile(): SplFileInfo|null
```
Get the current file if one exists.
#### Returns
`SplFileInfo|null`
### getHeader() public
```
getHeader(string $header): string[]
```
Retrieves a message header value by the given case-insensitive name.
This method returns an array of all the header values of the given case-insensitive header name.
If the header does not appear in the message, this method MUST return an empty array.
#### Parameters
`string` $header Case-insensitive header field name.
#### Returns
`string[]`
### getHeaderLine() public
```
getHeaderLine(string $name): string
```
Retrieves a comma-separated string of the values for a single header.
This method returns all of the header values of the given case-insensitive header name as a string concatenated together using a comma.
NOTE: Not all header values may be appropriately represented using comma concatenation. For such headers, use getHeader() instead and supply your own delimiter when concatenating.
If the header does not appear in the message, this method MUST return an empty string.
#### Parameters
`string` $name Case-insensitive header field name.
#### Returns
`string`
### getHeaders() public
```
getHeaders(): array
```
Retrieves all message headers.
The keys represent the header name as it will be sent over the wire, and each value is an array of strings associated with the header.
// Represent the headers as a string foreach ($message->getHeaders() as $name => $values) { echo $name . ": " . implode(", ", $values); }
// Emit headers iteratively: foreach ($message->getHeaders() as $name => $values) { foreach ($values as $value) { header(sprintf('%s: %s', $name, $value), false); } }
#### Returns
`array`
### getMimeType() public
```
getMimeType(string $alias): array|string|false
```
Returns the mime type definition for an alias
e.g `getMimeType('pdf'); // returns 'application/pdf'`
#### Parameters
`string` $alias the content type alias to map
#### Returns
`array|string|false`
### getProtocolVersion() public
```
getProtocolVersion(): string
```
Retrieves the HTTP protocol version as a string.
The string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
#### Returns
`string`
### getReasonPhrase() public
```
getReasonPhrase(): string
```
Gets the response reason phrase associated with the status code.
Because a reason phrase is not a required element in a response status line, the reason phrase value MAY be null. Implementations MAY choose to return the default RFC 7231 recommended reason phrase (or those listed in the IANA HTTP Status Code Registry) for the response's status code.
#### Returns
`string`
#### Links
https://tools.ietf.org/html/rfc7231#section-6
https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
### getStatusCode() public
```
getStatusCode(): int
```
Gets the response status code.
The status code is a 3-digit integer result code of the server's attempt to understand and satisfy the request.
#### Returns
`int`
### getType() public
```
getType(): string
```
Returns the current content type.
#### Returns
`string`
### hasHeader() public
```
hasHeader(string $header): bool
```
Checks if a header exists by the given case-insensitive name.
#### Parameters
`string` $header Case-insensitive header name.
#### Returns
`bool`
### isNotModified() public
```
isNotModified(Cake\Http\ServerRequest $request): bool
```
Checks whether a response has not been modified according to the 'If-None-Match' (Etags) and 'If-Modified-Since' (last modification date) request headers.
In order to interact with this method you must mark responses as not modified. You need to set at least one of the `Last-Modified` or `Etag` response headers before calling this method. Otherwise, a comparison will not be possible.
#### Parameters
`Cake\Http\ServerRequest` $request Request object
#### Returns
`bool`
### mapType() public
```
mapType(array|string $ctype): array|string|null
```
Maps a content-type back to an alias
e.g `mapType('application/pdf'); // returns 'pdf'`
#### Parameters
`array|string` $ctype Either a string content type to map, or an array of types.
#### Returns
`array|string|null`
### notModified() public
```
notModified(): void
```
Sets the response as Not Modified by removing any body contents setting the status code to "304 Not Modified" and removing all conflicting headers
*Warning* This method mutates the response in-place and should be avoided.
#### Returns
`void`
### outputCompressed() public
```
outputCompressed(): bool
```
Returns whether the resulting output will be compressed by PHP
#### Returns
`bool`
### resolveType() protected
```
resolveType(string $contentType): string
```
Translate and validate content-types.
#### Parameters
`string` $contentType The content-type or type alias.
#### Returns
`string`
#### Throws
`InvalidArgumentException`
When an invalid content-type or alias is used. ### setTypeMap() public
```
setTypeMap(string $type, array<string>|string $mimeType): void
```
Sets a content type definition into the map.
E.g.: setTypeMap('xhtml', ['application/xhtml+xml', 'application/xhtml'])
This is needed for RequestHandlerComponent and recognition of types.
#### Parameters
`string` $type Content type.
`array<string>|string` $mimeType Definition of the mime type.
#### Returns
`void`
### validateFile() protected
```
validateFile(string $path): SplFileInfo
```
Validate a file path is a valid response body.
#### Parameters
`string` $path The path to the file.
#### Returns
`SplFileInfo`
#### Throws
`Cake\Http\Exception\NotFoundException`
### withAddedHeader() public
```
withAddedHeader(string $name, string|string[] $value): static
```
Return an instance with the specified header appended with the given value.
Existing values for the specified header will be maintained. The new value(s) will be appended to the existing list. If the header did not exist previously, it will be added.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new header and/or value.
#### Parameters
`string` $name Case-insensitive header field name to add.
`string|string[]` $value Header value(s).
#### Returns
`static`
#### Throws
`Exception\InvalidArgumentException`
For invalid header names or values. ### withAddedLink() public
```
withAddedLink(string $url, array<string, mixed> $options = []): static
```
Create a new response with the Link header set.
### Examples
```
$response = $response->withAddedLink('http://example.com?page=1', ['rel' => 'prev'])
->withAddedLink('http://example.com?page=3', ['rel' => 'next']);
```
Will generate:
```
Link: <http://example.com?page=1>; rel="prev"
Link: <http://example.com?page=3>; rel="next"
```
#### Parameters
`string` $url The LinkHeader url.
`array<string, mixed>` $options optional The LinkHeader params.
#### Returns
`static`
### withBody() public
```
withBody(StreamInterface $body): static
```
Return an instance with the specified message body.
The body MUST be a StreamInterface object.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return a new instance that has the new body stream.
#### Parameters
`StreamInterface` $body Body.
#### Returns
`static`
#### Throws
`Exception\InvalidArgumentException`
When the body is not valid. ### withCache() public
```
withCache(string|int $since, string|int $time = '+1 day'): static
```
Create a new instance with the headers to enable client caching.
#### Parameters
`string|int` $since a valid time since the response text has not been modified
`string|int` $time optional a valid time for cache expiry
#### Returns
`static`
### withCharset() public
```
withCharset(string $charset): static
```
Get a new instance with an updated charset.
#### Parameters
`string` $charset Character set string.
#### Returns
`static`
### withCookie() public
```
withCookie(Cake\Http\Cookie\CookieInterface $cookie): static
```
Create a new response with a cookie set.
### Example
```
// add a cookie object
$response = $response->withCookie(new Cookie('remember_me', 1));
```
#### Parameters
`Cake\Http\Cookie\CookieInterface` $cookie cookie object
#### Returns
`static`
### withCookieCollection() public
```
withCookieCollection(Cake\Http\Cookie\CookieCollection $cookieCollection): static
```
Get a new instance with provided cookie collection.
#### Parameters
`Cake\Http\Cookie\CookieCollection` $cookieCollection Cookie collection to set.
#### Returns
`static`
### withDisabledCache() public
```
withDisabledCache(): static
```
Create a new instance with headers to instruct the client to not cache the response
#### Returns
`static`
### withDownload() public
```
withDownload(string $filename): static
```
Create a new instance with the Content-Disposition header set.
#### Parameters
`string` $filename The name of the file as the browser will download the response
#### Returns
`static`
### withEtag() public
```
withEtag(string $hash, bool $weak = false): static
```
Create a new instance with the Etag header set.
Etags are a strong indicative that a response can be cached by a HTTP client. A bad way of generating Etags is creating a hash of the response output, instead generate a unique hash of the unique components that identifies a request, such as a modification time, a resource Id, and anything else you consider it that makes the response unique.
The second parameter is used to inform clients that the content has changed, but semantically it is equivalent to existing cached values. Consider a page with a hit counter, two different page views are equivalent, but they differ by a few bytes. This permits the Client to decide whether they should use the cached data.
#### Parameters
`string` $hash The unique hash that identifies this response
`bool` $weak optional Whether the response is semantically the same as other with the same hash or not. Defaults to false
#### Returns
`static`
### withExpiredCookie() public
```
withExpiredCookie(Cake\Http\Cookie\CookieInterface $cookie): static
```
Create a new response with an expired cookie set.
### Example
```
// add a cookie object
$response = $response->withExpiredCookie(new Cookie('remember_me'));
```
#### Parameters
`Cake\Http\Cookie\CookieInterface` $cookie cookie object
#### Returns
`static`
### withExpires() public
```
withExpires(DateTimeInterface|string|int|null $time): static
```
Create a new instance with the Expires header set.
### Examples:
```
// Will Expire the response cache now
$response->withExpires('now')
// Will set the expiration in next 24 hours
$response->withExpires(new DateTime('+1 day'))
```
#### Parameters
`DateTimeInterface|string|int|null` $time Valid time string or \DateTime instance.
#### Returns
`static`
### withFile() public
```
withFile(string $path, array<string, mixed> $options = []): static
```
Create a new instance that is based on a file.
This method will augment both the body and a number of related headers.
If `$_SERVER['HTTP_RANGE']` is set, a slice of the file will be returned instead of the entire file.
### Options keys
* name: Alternate download name
* download: If `true` sets download header and forces file to be downloaded rather than displayed inline.
#### Parameters
`string` $path Absolute path to file.
`array<string, mixed>` $options optional Options See above.
#### Returns
`static`
#### Throws
`Cake\Http\Exception\NotFoundException`
### withHeader() public
```
withHeader(string $name, string|string[] $value): static
```
Return an instance with the provided header, replacing any existing values of any headers with the same case-insensitive name.
While header names are case-insensitive, the casing of the header will be preserved by this function, and returned from getHeaders().
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new and/or updated header and value.
#### Parameters
`string` $name Case-insensitive header field name.
`string|string[]` $value Header value(s).
#### Returns
`static`
#### Throws
`Exception\InvalidArgumentException`
For invalid header names or values. ### withLength() public
```
withLength(string|int $bytes): static
```
Create a new response with the Content-Length header set.
#### Parameters
`string|int` $bytes Number of bytes
#### Returns
`static`
### withLocation() public
```
withLocation(string $url): static
```
Return an instance with an updated location header.
If the current status code is 200, it will be replaced with 302.
#### Parameters
`string` $url The location to redirect to.
#### Returns
`static`
### withMaxAge() public
```
withMaxAge(int $seconds): static
```
Create an instance with Cache-Control max-age directive set.
The max-age is the number of seconds after which the response should no longer be considered a good candidate to be fetched from the local (client) cache.
#### Parameters
`int` $seconds The seconds a cached response can be considered valid
#### Returns
`static`
### withModified() public
```
withModified(DateTimeInterface|string|int $time): static
```
Create a new instance with the Last-Modified header set.
### Examples:
```
// Will Expire the response cache now
$response->withModified('now')
// Will set the expiration in next 24 hours
$response->withModified(new DateTime('+1 day'))
```
#### Parameters
`DateTimeInterface|string|int` $time Valid time string or \DateTime instance.
#### Returns
`static`
### withMustRevalidate() public
```
withMustRevalidate(bool $enable): static
```
Create an instance with Cache-Control must-revalidate directive set.
Sets the Cache-Control must-revalidate directive. must-revalidate indicates that the response should not be served stale by a cache under any circumstance without first revalidating with the origin.
#### Parameters
`bool` $enable If boolean sets or unsets the directive.
#### Returns
`static`
### withNotModified() public
```
withNotModified(): static
```
Create a new instance as 'not modified'
This will remove any body contents set the status code to "304" and removing headers that describe a response body.
#### Returns
`static`
### withProtocolVersion() public
```
withProtocolVersion(string $version): static
```
Return an instance with the specified HTTP protocol version.
The version string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the new protocol version.
#### Parameters
`string` $version HTTP protocol version
#### Returns
`static`
### withSharable() public
```
withSharable(bool $public, int|null $time = null): static
```
Create a new instace with the public/private Cache-Control directive set.
#### Parameters
`bool` $public If set to true, the Cache-Control header will be set as public if set to false, the response will be set to private.
`int|null` $time optional time in seconds after which the response should no longer be considered fresh.
#### Returns
`static`
### withSharedMaxAge() public
```
withSharedMaxAge(int $seconds): static
```
Create a new instance with the Cache-Control s-maxage directive.
The max-age is the number of seconds after which the response should no longer be considered a good candidate to be fetched from a shared cache (like in a proxy server).
#### Parameters
`int` $seconds The number of seconds for shared max-age
#### Returns
`static`
### withStatus() public
```
withStatus(int $code, string $reasonPhrase = ''): static
```
Return an instance with the specified status code and, optionally, reason phrase.
If no reason phrase is specified, implementations MAY choose to default to the RFC 7231 or IANA recommended reason phrase for the response's status code.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that has the updated status and reason phrase.
If the status code is 304 or 204, the existing Content-Type header will be cleared, as these response codes have no body.
There are external packages such as `fig/http-message-util` that provide HTTP status code constants. These can be used with any method that accepts or returns a status code integer. However, keep in mind that these constants might include status codes that are now allowed which will throw an `\InvalidArgumentException`.
#### Parameters
`int` $code The 3-digit integer status code to set.
`string` $reasonPhrase optional The reason phrase to use with the provided status code; if none is provided, implementations MAY use the defaults as suggested in the HTTP specification.
#### Returns
`static`
#### Throws
`InvalidArgumentException`
For invalid status code arguments. #### Links
https://tools.ietf.org/html/rfc7231#section-6
https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
### withStringBody() public
```
withStringBody(string|null $string): static
```
Convenience method to set a string into the response body
#### Parameters
`string|null` $string The string to be sent
#### Returns
`static`
### withType() public
```
withType(string $contentType): static
```
Get an updated response with the content type set.
If you attempt to set the type on a 304 or 204 status code response, the content type will not take effect as these status codes do not have content-types.
#### Parameters
`string` $contentType Either a file extension which will be mapped to a mime-type or a concrete mime-type.
#### Returns
`static`
### withVary() public
```
withVary(array<string>|string $cacheVariances): static
```
Create a new instance with the Vary header set.
If an array is passed values will be imploded into a comma separated string. If no parameters are passed, then an array with the current Vary header value is returned
#### Parameters
`array<string>|string` $cacheVariances A single Vary string or an array containing the list for variances.
#### Returns
`static`
### withoutHeader() public
```
withoutHeader(string $name): static
```
Return an instance without the specified header.
Header resolution MUST be done without case-sensitivity.
This method MUST be implemented in such a way as to retain the immutability of the message, and MUST return an instance that removes the named header.
#### Parameters
`string` $name Case-insensitive header field name to remove.
#### Returns
`static`
Property Detail
---------------
### $\_cacheDirectives protected
Holds all the cache directives that will be converted into headers when sending the request
#### Type
`array<string, mixed>`
### $\_charset protected
The charset the response body is encoded with
#### Type
`string`
### $\_cookies protected
Collection of cookies to send to the client
#### Type
`Cake\Http\Cookie\CookieCollection`
### $\_file protected
File object for file to be read out as response
#### Type
`SplFileInfo|null`
### $\_fileRange protected
File range. Used for requesting ranges of files.
#### Type
`array<int>`
### $\_mimeTypes protected
Holds type key to mime type mappings for known mime types.
#### Type
`array<string, mixed>`
### $\_reasonPhrase protected
Reason Phrase
#### Type
`string`
### $\_status protected
Status code to send to the client
#### Type
`int`
### $\_statusCodes protected
Allowed HTTP status codes and their default description.
#### Type
`array<int, string>`
### $\_streamMode protected
Stream mode options.
#### Type
`string`
### $\_streamTarget protected
Stream target or resource object.
#### Type
`resource|string`
### $headerNames protected
Map of normalized header name to original name used to register header.
#### Type
`array`
### $headers protected
List of all registered headers, as key => array of values.
#### Type
`array`
| programming_docs |
cakephp Class LoggingStatement Class LoggingStatement
=======================
Statement decorator used to
**Namespace:** [Cake\Database\Log](namespace-cake.database.log)
Constants
---------
* `string` **FETCH\_TYPE\_ASSOC**
```
'assoc'
```
Used to designate that an associated array be returned in a result when calling fetch methods
* `string` **FETCH\_TYPE\_NUM**
```
'num'
```
Used to designate that numeric indexes be returned in a result when calling fetch methods
* `string` **FETCH\_TYPE\_OBJ**
```
'obj'
```
Used to designate that a stdClass object be returned in a result when calling fetch methods
Property Summary
----------------
* [$\_compiledParams](#%24_compiledParams) protected `array<array>` Holds bound params
* [$\_driver](#%24_driver) protected `Cake\Database\DriverInterface` Reference to the driver object associated to this statement.
* [$\_hasExecuted](#%24_hasExecuted) protected `bool` Whether this statement has already been executed
* [$\_logger](#%24_logger) protected `Psr\Log\LoggerInterface` Logger instance responsible for actually doing the logging task
* [$\_statement](#%24_statement) protected `Cake\Database\StatementInterface` Statement instance implementation, such as PDOStatement or any other custom implementation.
* [$loggedQuery](#%24loggedQuery) protected `Cake\Database\Log\LoggedQuery|null` Logged query
* [$queryString](#%24queryString) public @property-read `string`
* [$startTime](#%24startTime) protected `float` Query execution start time.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_get()](#__get()) public
Magic getter to return $queryString as read-only.
* ##### [\_log()](#_log()) protected
Copies the logging data to the passed LoggedQuery and sends it to the logging system.
* ##### [bind()](#bind()) public
Binds a set of values to statement object with corresponding type.
* ##### [bindValue()](#bindValue()) public
Wrapper for bindValue function to gather each parameter to be later used in the logger function.
* ##### [cast()](#cast()) public
Converts a give value to a suitable database value based on type and return relevant internal statement type
* ##### [closeCursor()](#closeCursor()) public
Closes a cursor in the database, freeing up any resources and memory allocated to it. In most cases you don't need to call this method, as it is automatically called after fetching all results from the result set.
* ##### [columnCount()](#columnCount()) public
Returns the number of columns this statement's results will contain.
* ##### [count()](#count()) public
Statements can be passed as argument for count() to return the number for affected rows from last execution.
* ##### [errorCode()](#errorCode()) public
Returns the error code for the last error that occurred when executing this statement.
* ##### [errorInfo()](#errorInfo()) public
Returns the error information for the last error that occurred when executing this statement.
* ##### [execute()](#execute()) public
Wrapper for the execute function to calculate time spent and log the query afterwards.
* ##### [fetch()](#fetch()) public
Returns the next row for the result set after executing this statement. Rows can be fetched to contain columns as names or positions. If no rows are left in result set, this method will return false.
* ##### [fetchAll()](#fetchAll()) public
Returns an array with all rows resulting from executing this statement.
* ##### [fetchAssoc()](#fetchAssoc()) public
Returns the next row in a result set as an associative array. Calling this function is the same as calling $statement->fetch(StatementDecorator::FETCH\_TYPE\_ASSOC). If no results are found an empty array is returned.
* ##### [fetchColumn()](#fetchColumn()) public
Returns the value of the result at position.
* ##### [getInnerStatement()](#getInnerStatement()) public
Returns the statement object that was decorated by this class.
* ##### [getIterator()](#getIterator()) public
Statements are iterable as arrays, this method will return the iterator object for traversing all items in the result.
* ##### [getLogger()](#getLogger()) public
Gets the logger object
* ##### [lastInsertId()](#lastInsertId()) public
Returns the latest primary inserted using this statement.
* ##### [matchTypes()](#matchTypes()) public
Matches columns to corresponding types
* ##### [rowCount()](#rowCount()) public
Returns the number of rows affected by this SQL statement.
* ##### [setLogger()](#setLogger()) public
Sets a logger
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Database\StatementInterface $statement, Cake\Database\DriverInterface $driver)
```
Constructor
#### Parameters
`Cake\Database\StatementInterface` $statement Statement implementation such as PDOStatement.
`Cake\Database\DriverInterface` $driver Driver instance
### \_\_get() public
```
__get(string $property): string|null
```
Magic getter to return $queryString as read-only.
#### Parameters
`string` $property internal property to get
#### Returns
`string|null`
### \_log() protected
```
_log(): void
```
Copies the logging data to the passed LoggedQuery and sends it to the logging system.
#### Returns
`void`
### bind() public
```
bind(array $params, array $types): void
```
Binds a set of values to statement object with corresponding type.
#### Parameters
`array` $params list of values to be bound
`array` $types list of types to be used, keys should match those in $params
#### Returns
`void`
### bindValue() public
```
bindValue(string|int $column, mixed $value, string|int|null $type = 'string'): void
```
Wrapper for bindValue function to gather each parameter to be later used in the logger function.
It is not allowed to combine positional and named variables in the same statement.
### Examples:
```
$statement->bindValue(1, 'a title');
$statement->bindValue('active', true, 'boolean');
$statement->bindValue(5, new \DateTime(), 'date');
```
#### Parameters
`string|int` $column Name or param position to be bound
`mixed` $value The value to bind to variable in query
`string|int|null` $type optional PDO type or name of configured Type class
#### Returns
`void`
### cast() public
```
cast(mixed $value, Cake\Database\TypeInterface|string|int $type = 'string'): array
```
Converts a give value to a suitable database value based on type and return relevant internal statement type
#### Parameters
`mixed` $value The value to cast
`Cake\Database\TypeInterface|string|int` $type optional The type name or type instance to use.
#### Returns
`array`
### closeCursor() public
```
closeCursor(): void
```
Closes a cursor in the database, freeing up any resources and memory allocated to it. In most cases you don't need to call this method, as it is automatically called after fetching all results from the result set.
#### Returns
`void`
### columnCount() public
```
columnCount(): int
```
Returns the number of columns this statement's results will contain.
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
echo $statement->columnCount(); // outputs 2
```
#### Returns
`int`
### count() public
```
count(): int
```
Statements can be passed as argument for count() to return the number for affected rows from last execution.
#### Returns
`int`
### errorCode() public
```
errorCode(): string|int
```
Returns the error code for the last error that occurred when executing this statement.
#### Returns
`string|int`
### errorInfo() public
```
errorInfo(): array
```
Returns the error information for the last error that occurred when executing this statement.
#### Returns
`array`
### execute() public
```
execute(array|null $params = null): bool
```
Wrapper for the execute function to calculate time spent and log the query afterwards.
#### Parameters
`array|null` $params optional List of values to be bound to query
#### Returns
`bool`
#### Throws
`Exception`
Re-throws any exception raised during query execution. ### fetch() public
```
fetch(string|int $type = self::FETCH_TYPE_NUM): mixed
```
Returns the next row for the result set after executing this statement. Rows can be fetched to contain columns as names or positions. If no rows are left in result set, this method will return false.
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
print_r($statement->fetch('assoc')); // will show ['id' => 1, 'title' => 'a title']
```
#### Parameters
`string|int` $type optional #### Returns
`mixed`
### fetchAll() public
```
fetchAll(string|int $type = self::FETCH_TYPE_NUM): array|false
```
Returns an array with all rows resulting from executing this statement.
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
print_r($statement->fetchAll('assoc')); // will show [0 => ['id' => 1, 'title' => 'a title']]
```
#### Parameters
`string|int` $type optional #### Returns
`array|false`
### fetchAssoc() public
```
fetchAssoc(): array
```
Returns the next row in a result set as an associative array. Calling this function is the same as calling $statement->fetch(StatementDecorator::FETCH\_TYPE\_ASSOC). If no results are found an empty array is returned.
#### Returns
`array`
### fetchColumn() public
```
fetchColumn(int $position): mixed
```
Returns the value of the result at position.
#### Parameters
`int` $position The numeric position of the column to retrieve in the result
#### Returns
`mixed`
### getInnerStatement() public
```
getInnerStatement(): Cake\Database\StatementInterface
```
Returns the statement object that was decorated by this class.
#### Returns
`Cake\Database\StatementInterface`
### getIterator() public
```
getIterator(): Cake\Database\StatementInterface
```
Statements are iterable as arrays, this method will return the iterator object for traversing all items in the result.
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
foreach ($statement as $row) {
//do stuff
}
```
#### Returns
`Cake\Database\StatementInterface`
### getLogger() public
```
getLogger(): Psr\Log\LoggerInterface
```
Gets the logger object
#### Returns
`Psr\Log\LoggerInterface`
### lastInsertId() public
```
lastInsertId(string|null $table = null, string|null $column = null): string|int
```
Returns the latest primary inserted using this statement.
#### Parameters
`string|null` $table optional table name or sequence to get last insert value from
`string|null` $column optional the name of the column representing the primary key
#### Returns
`string|int`
### matchTypes() public
```
matchTypes(array $columns, array $types): array
```
Matches columns to corresponding types
Both $columns and $types should either be numeric based or string key based at the same time.
#### Parameters
`array` $columns list or associative array of columns and parameters to be bound with types
`array` $types list or associative array of types
#### Returns
`array`
### rowCount() public
```
rowCount(): int
```
Returns the number of rows affected by this SQL statement.
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
print_r($statement->rowCount()); // will show 1
```
#### Returns
`int`
### setLogger() public
```
setLogger(Psr\Log\LoggerInterface $logger): void
```
Sets a logger
#### Parameters
`Psr\Log\LoggerInterface` $logger Logger object
#### Returns
`void`
Property Detail
---------------
### $\_compiledParams protected
Holds bound params
#### Type
`array<array>`
### $\_driver protected
Reference to the driver object associated to this statement.
#### Type
`Cake\Database\DriverInterface`
### $\_hasExecuted protected
Whether this statement has already been executed
#### Type
`bool`
### $\_logger protected
Logger instance responsible for actually doing the logging task
#### Type
`Psr\Log\LoggerInterface`
### $\_statement protected
Statement instance implementation, such as PDOStatement or any other custom implementation.
#### Type
`Cake\Database\StatementInterface`
### $loggedQuery protected
Logged query
#### Type
`Cake\Database\Log\LoggedQuery|null`
### $queryString public @property-read
#### Type
`string`
### $startTime protected
Query execution start time.
#### Type
`float`
cakephp Class MissingDatasourceException Class MissingDatasourceException
=================================
Used when a datasource cannot be found.
**Namespace:** [Cake\Datasource\Exception](namespace-cake.datasource.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Class Text Class Text
===========
Text handling methods.
**Namespace:** [Cake\Utility](namespace-cake.utility)
Property Summary
----------------
* [$\_defaultHtmlNoCount](#%24_defaultHtmlNoCount) protected static `array<string>` Default HTML tags which must not be counted for truncating text.
* [$\_defaultTransliterator](#%24_defaultTransliterator) protected static `Transliterator|null` Default transliterator.
* [$\_defaultTransliteratorId](#%24_defaultTransliteratorId) protected static `string` Default transliterator id string.
Method Summary
--------------
* ##### [\_removeLastWord()](#_removeLastWord()) protected static
Removes the last word from the input text.
* ##### [\_strlen()](#_strlen()) protected static
Get string length.
* ##### [\_substr()](#_substr()) protected static
Return part of a string.
* ##### [\_wordWrap()](#_wordWrap()) protected static
Unicode aware version of wordwrap as helper method.
* ##### [ascii()](#ascii()) public static
Converts the decimal value of a multibyte character string to a string
* ##### [cleanInsert()](#cleanInsert()) public static
Cleans up a Text::insert() formatted string with given $options depending on the 'clean' key in $options. The default method used is text but html is also available. The goal of this function is to replace all whitespace and unneeded markup around placeholders that did not get replaced by Text::insert().
* ##### [excerpt()](#excerpt()) public static
Extracts an excerpt from the text surrounding the phrase with a number of characters on each side determined by radius.
* ##### [getTransliterator()](#getTransliterator()) public static
Get the default transliterator.
* ##### [getTransliteratorId()](#getTransliteratorId()) public static
Get default transliterator identifier string.
* ##### [highlight()](#highlight()) public static
Highlights a given phrase in a text. You can specify any expression in highlighter that may include the \1 expression to include the $phrase found.
* ##### [insert()](#insert()) public static
Replaces variable placeholders inside a $str with any given $data. Each key in the $data array corresponds to a variable placeholder name in $str. Example:
```
Text::insert(':name is :age years old.', ['name' => 'Bob', 'age' => '65']);
```
Returns: Bob is 65 years old.
* ##### [isMultibyte()](#isMultibyte()) public static
Check if the string contain multibyte characters
* ##### [parseFileSize()](#parseFileSize()) public static
Converts filesize from human readable string to bytes
* ##### [setTransliterator()](#setTransliterator()) public static
Set the default transliterator.
* ##### [setTransliteratorId()](#setTransliteratorId()) public static
Set default transliterator identifier string.
* ##### [slug()](#slug()) public static
Returns a string with all spaces converted to dashes (by default), characters transliterated to ASCII characters, and non word characters removed.
* ##### [tail()](#tail()) public static
Truncates text starting from the end.
* ##### [toList()](#toList()) public static
Creates a comma separated list where the last two items are joined with 'and', forming natural language.
* ##### [tokenize()](#tokenize()) public static
Tokenizes a string using $separator, ignoring any instance of $separator that appears between $leftBound and $rightBound.
* ##### [transliterate()](#transliterate()) public static
Transliterate string.
* ##### [truncate()](#truncate()) public static
Truncates text.
* ##### [truncateByWidth()](#truncateByWidth()) public static
Truncate text with specified width.
* ##### [utf8()](#utf8()) public static
Converts a multibyte character string to the decimal value of the character
* ##### [uuid()](#uuid()) public static
Generate a random UUID version 4
* ##### [wordWrap()](#wordWrap()) public static
Unicode and newline aware version of wordwrap.
* ##### [wrap()](#wrap()) public static
Wraps text to a specific width, can optionally wrap at word breaks.
* ##### [wrapBlock()](#wrapBlock()) public static
Wraps a complete block of text to a specific width, can optionally wrap at word breaks.
Method Detail
-------------
### \_removeLastWord() protected static
```
_removeLastWord(string $text): string
```
Removes the last word from the input text.
#### Parameters
`string` $text The input text
#### Returns
`string`
### \_strlen() protected static
```
_strlen(string $text, array<string, mixed> $options): int
```
Get string length.
### Options:
* `html` If true, HTML entities will be handled as decoded characters.
* `trimWidth` If true, the width will return.
#### Parameters
`string` $text The string being checked for length
`array<string, mixed>` $options An array of options.
#### Returns
`int`
### \_substr() protected static
```
_substr(string $text, int $start, int|null $length, array<string, mixed> $options): string
```
Return part of a string.
### Options:
* `html` If true, HTML entities will be handled as decoded characters.
* `trimWidth` If true, will be truncated with specified width.
#### Parameters
`string` $text The input string.
`int` $start The position to begin extracting.
`int|null` $length The desired length.
`array<string, mixed>` $options An array of options.
#### Returns
`string`
### \_wordWrap() protected static
```
_wordWrap(string $text, int $width = 72, string $break = "\n", bool $cut = false): string
```
Unicode aware version of wordwrap as helper method.
#### Parameters
`string` $text The text to format.
`int` $width optional The width to wrap to. Defaults to 72.
`string` $break optional The line is broken using the optional break parameter. Defaults to '\n'.
`bool` $cut optional If the cut is set to true, the string is always wrapped at the specified width.
#### Returns
`string`
### ascii() public static
```
ascii(array $array): string
```
Converts the decimal value of a multibyte character string to a string
#### Parameters
`array` $array Array
#### Returns
`string`
### cleanInsert() public static
```
cleanInsert(string $str, array<string, mixed> $options): string
```
Cleans up a Text::insert() formatted string with given $options depending on the 'clean' key in $options. The default method used is text but html is also available. The goal of this function is to replace all whitespace and unneeded markup around placeholders that did not get replaced by Text::insert().
#### Parameters
`string` $str String to clean.
`array<string, mixed>` $options Options list.
#### Returns
`string`
#### See Also
\Cake\Utility\Text::insert() ### excerpt() public static
```
excerpt(string $text, string $phrase, int $radius = 100, string $ellipsis = '...'): string
```
Extracts an excerpt from the text surrounding the phrase with a number of characters on each side determined by radius.
#### Parameters
`string` $text String to search the phrase in
`string` $phrase Phrase that will be searched for
`int` $radius optional The amount of characters that will be returned on each side of the founded phrase
`string` $ellipsis optional Ending that will be appended
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/core-libraries/text.html#extracting-an-excerpt
### getTransliterator() public static
```
getTransliterator(): Transliterator|null
```
Get the default transliterator.
#### Returns
`Transliterator|null`
### getTransliteratorId() public static
```
getTransliteratorId(): string
```
Get default transliterator identifier string.
#### Returns
`string`
### highlight() public static
```
highlight(string $text, array<string>|string $phrase, array<string, mixed> $options = []): string
```
Highlights a given phrase in a text. You can specify any expression in highlighter that may include the \1 expression to include the $phrase found.
### Options:
* `format` The piece of HTML with that the phrase will be highlighted
* `html` If true, will ignore any HTML tags, ensuring that only the correct text is highlighted
* `regex` A custom regex rule that is used to match words, default is '|$tag|iu'
* `limit` A limit, optional, defaults to -1 (none)
#### Parameters
`string` $text Text to search the phrase in.
`array<string>|string` $phrase The phrase or phrases that will be searched.
`array<string, mixed>` $options optional An array of HTML attributes and options.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/core-libraries/text.html#highlighting-substrings
### insert() public static
```
insert(string $str, array $data, array<string, mixed> $options = []): string
```
Replaces variable placeholders inside a $str with any given $data. Each key in the $data array corresponds to a variable placeholder name in $str. Example:
```
Text::insert(':name is :age years old.', ['name' => 'Bob', 'age' => '65']);
```
Returns: Bob is 65 years old.
Available $options are:
* before: The character or string in front of the name of the variable placeholder (Defaults to `:`)
* after: The character or string after the name of the variable placeholder (Defaults to null)
* escape: The character or string used to escape the before character / string (Defaults to `\`)
* format: A regex to use for matching variable placeholders. Default is: `/(?<!\\)\:%s/` (Overwrites before, after, breaks escape / clean)
* clean: A boolean or array with instructions for Text::cleanInsert
#### Parameters
`string` $str A string containing variable placeholders
`array` $data A key => val array where each key stands for a placeholder variable name to be replaced with val
`array<string, mixed>` $options optional An array of options, see description above
#### Returns
`string`
### isMultibyte() public static
```
isMultibyte(string $string): bool
```
Check if the string contain multibyte characters
#### Parameters
`string` $string value to test
#### Returns
`bool`
### parseFileSize() public static
```
parseFileSize(string $size, mixed $default = false): mixed
```
Converts filesize from human readable string to bytes
#### Parameters
`string` $size Size in human readable string like '5MB', '5M', '500B', '50kb' etc.
`mixed` $default optional Value to be returned when invalid size was used, for example 'Unknown type'
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
On invalid Unit type. #### Links
https://book.cakephp.org/4/en/core-libraries/text.html#Cake\Utility\Text::parseFileSize
### setTransliterator() public static
```
setTransliterator(Transliterator $transliterator): void
```
Set the default transliterator.
#### Parameters
`Transliterator` $transliterator A `Transliterator` instance.
#### Returns
`void`
### setTransliteratorId() public static
```
setTransliteratorId(string $transliteratorId): void
```
Set default transliterator identifier string.
#### Parameters
`string` $transliteratorId Transliterator identifier.
#### Returns
`void`
### slug() public static
```
slug(string $string, array<string, mixed>|string $options = []): string
```
Returns a string with all spaces converted to dashes (by default), characters transliterated to ASCII characters, and non word characters removed.
### Options:
* `replacement`: Replacement string. Default '-'.
* `transliteratorId`: A valid transliterator id string. If `null` (default) the transliterator (identifier) set via `setTransliteratorId()` or `setTransliterator()` will be used. If `false` no transliteration will be done, only non words will be removed.
* `preserve`: Specific non-word character to preserve. Default `null`. For e.g. this option can be set to '.' to generate clean file names.
#### Parameters
`string` $string the string you want to slug
`array<string, mixed>|string` $options optional If string it will be use as replacement character or an array of options.
#### Returns
`string`
#### See Also
setTransliterator()
setTransliteratorId() ### tail() public static
```
tail(string $text, int $length = 100, array<string, mixed> $options = []): string
```
Truncates text starting from the end.
Cuts a string to the length of $length and replaces the first characters with the ellipsis if the text is longer than length.
### Options:
* `ellipsis` Will be used as beginning and prepended to the trimmed string
* `exact` If false, $text will not be cut mid-word
#### Parameters
`string` $text String to truncate.
`int` $length optional Length of returned string, including ellipsis.
`array<string, mixed>` $options optional An array of options.
#### Returns
`string`
### toList() public static
```
toList(array<string> $list, string|null $and = null, string $separator = ', '): string
```
Creates a comma separated list where the last two items are joined with 'and', forming natural language.
#### Parameters
`array<string>` $list The list to be joined.
`string|null` $and optional The word used to join the last and second last items together with. Defaults to 'and'.
`string` $separator optional The separator used to join all the other items together. Defaults to ', '.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/core-libraries/text.html#converting-an-array-to-sentence-form
### tokenize() public static
```
tokenize(string $data, string $separator = ',', string $leftBound = '(', string $rightBound = ')'): array<string>
```
Tokenizes a string using $separator, ignoring any instance of $separator that appears between $leftBound and $rightBound.
#### Parameters
`string` $data The data to tokenize.
`string` $separator optional The token to split the data on.
`string` $leftBound optional The left boundary to ignore separators in.
`string` $rightBound optional The right boundary to ignore separators in.
#### Returns
`array<string>`
### transliterate() public static
```
transliterate(string $string, Transliterator|string|null $transliterator = null): string
```
Transliterate string.
#### Parameters
`string` $string String to transliterate.
`Transliterator|string|null` $transliterator optional Either a Transliterator instance, or a transliterator identifier string. If `null`, the default transliterator (identifier) set via `setTransliteratorId()` or `setTransliterator()` will be used.
#### Returns
`string`
#### See Also
https://secure.php.net/manual/en/transliterator.transliterate.php ### truncate() public static
```
truncate(string $text, int $length = 100, array<string, mixed> $options = []): string
```
Truncates text.
Cuts a string to the length of $length and replaces the last characters with the ellipsis if the text is longer than length.
### Options:
* `ellipsis` Will be used as ending and appended to the trimmed string
* `exact` If false, $text will not be cut mid-word
* `html` If true, HTML tags would be handled correctly
* `trimWidth` If true, $text will be truncated with the width
#### Parameters
`string` $text String to truncate.
`int` $length optional Length of returned string, including ellipsis.
`array<string, mixed>` $options optional An array of HTML attributes and options.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/core-libraries/text.html#truncating-text
### truncateByWidth() public static
```
truncateByWidth(string $text, int $length = 100, array<string, mixed> $options = []): string
```
Truncate text with specified width.
#### Parameters
`string` $text String to truncate.
`int` $length optional Length of returned string, including ellipsis.
`array<string, mixed>` $options optional An array of HTML attributes and options.
#### Returns
`string`
#### See Also
\Cake\Utility\Text::truncate() ### utf8() public static
```
utf8(string $string): array<int>
```
Converts a multibyte character string to the decimal value of the character
#### Parameters
`string` $string String to convert.
#### Returns
`array<int>`
### uuid() public static
```
uuid(): string
```
Generate a random UUID version 4
Warning: This method should not be used as a random seed for any cryptographic operations. Instead, you should use `Security::randomBytes()` or `Security::randomString()` instead.
It should also not be used to create identifiers that have security implications, such as 'unguessable' URL identifiers. Instead, you should use {@link \Cake\Utility\Security::randomBytes()}` for that.
#### Returns
`string`
#### See Also
https://www.ietf.org/rfc/rfc4122.txt ### wordWrap() public static
```
wordWrap(string $text, int $width = 72, string $break = "\n", bool $cut = false): string
```
Unicode and newline aware version of wordwrap.
#### Parameters
`string` $text The text to format.
`int` $width optional The width to wrap to. Defaults to 72.
`string` $break optional The line is broken using the optional break parameter. Defaults to '\n'.
`bool` $cut optional If the cut is set to true, the string is always wrapped at the specified width.
#### Returns
`string`
### wrap() public static
```
wrap(string $text, array<string, mixed>|int $options = []): string
```
Wraps text to a specific width, can optionally wrap at word breaks.
### Options
* `width` The width to wrap to. Defaults to 72.
* `wordWrap` Only wrap on words breaks (spaces) Defaults to true.
* `indent` String to indent with. Defaults to null.
* `indentAt` 0 based index to start indenting at. Defaults to 0.
#### Parameters
`string` $text The text to format.
`array<string, mixed>|int` $options optional Array of options to use, or an integer to wrap the text to.
#### Returns
`string`
### wrapBlock() public static
```
wrapBlock(string $text, array<string, mixed>|int $options = []): string
```
Wraps a complete block of text to a specific width, can optionally wrap at word breaks.
### Options
* `width` The width to wrap to. Defaults to 72.
* `wordWrap` Only wrap on words breaks (spaces) Defaults to true.
* `indent` String to indent with. Defaults to null.
* `indentAt` 0 based index to start indenting at. Defaults to 0.
#### Parameters
`string` $text The text to format.
`array<string, mixed>|int` $options optional Array of options to use, or an integer to wrap the text to.
#### Returns
`string`
Property Detail
---------------
### $\_defaultHtmlNoCount protected static
Default HTML tags which must not be counted for truncating text.
#### Type
`array<string>`
### $\_defaultTransliterator protected static
Default transliterator.
#### Type
`Transliterator|null`
### $\_defaultTransliteratorId protected static
Default transliterator id string.
#### Type
`string`
| programming_docs |
cakephp Class SqlserverCompiler Class SqlserverCompiler
========================
Responsible for compiling a Query object into its SQL representation for SQL Server
**Namespace:** [Cake\Database](namespace-cake.database)
Property Summary
----------------
* [$\_deleteParts](#%24_deleteParts) protected `array<string>` The list of query clauses to traverse for generating a DELETE statement
* [$\_insertParts](#%24_insertParts) protected `array<string>` The list of query clauses to traverse for generating an INSERT statement
* [$\_orderedUnion](#%24_orderedUnion) protected `bool` SQLserver does not support ORDER BY in UNION queries.
* [$\_quotedSelectAliases](#%24_quotedSelectAliases) protected `bool` Indicate whether aliases in SELECT clause need to be always quoted.
* [$\_selectParts](#%24_selectParts) protected `array<string>` The list of query clauses to traverse for generating a SELECT statement
* [$\_templates](#%24_templates) protected `array<string, string>` List of sprintf templates that will be used for compiling the SQL for this query. There are some clauses that can be built as just as the direct concatenation of the internal parts, those are listed here.
* [$\_updateParts](#%24_updateParts) protected `array<string>` The list of query clauses to traverse for generating an UPDATE statement
Method Summary
--------------
* ##### [\_buildFromPart()](#_buildFromPart()) protected
Helper function used to build the string representation of a FROM clause, it constructs the tables list taking care of aliasing and converting expression objects to string.
* ##### [\_buildHavingPart()](#_buildHavingPart()) protected
Helper function used to build the string representation of a HAVING clause, it constructs the field list taking care of aliasing and converting expression objects to string.
* ##### [\_buildInsertPart()](#_buildInsertPart()) protected
Generates the INSERT part of a SQL query
* ##### [\_buildJoinPart()](#_buildJoinPart()) protected
Helper function used to build the string representation of multiple JOIN clauses, it constructs the joins list taking care of aliasing and converting expression objects to string in both the table to be joined and the conditions to be used.
* ##### [\_buildLimitPart()](#_buildLimitPart()) protected
Generates the LIMIT part of a SQL query
* ##### [\_buildModifierPart()](#_buildModifierPart()) protected
Builds the SQL modifier fragment
* ##### [\_buildSelectPart()](#_buildSelectPart()) protected
Helper function used to build the string representation of a SELECT clause, it constructs the field list taking care of aliasing and converting expression objects to string. This function also constructs the DISTINCT clause for the query.
* ##### [\_buildSetPart()](#_buildSetPart()) protected
Helper function to generate SQL for SET expressions.
* ##### [\_buildUnionPart()](#_buildUnionPart()) protected
Builds the SQL string for all the UNION clauses in this query, when dealing with query objects it will also transform them using their configured SQL dialect.
* ##### [\_buildUpdatePart()](#_buildUpdatePart()) protected
Builds the SQL fragment for UPDATE.
* ##### [\_buildValuesPart()](#_buildValuesPart()) protected
Builds the SQL fragment for INSERT INTO.
* ##### [\_buildWindowPart()](#_buildWindowPart()) protected
Helper function to build the string representation of a window clause.
* ##### [\_buildWithPart()](#_buildWithPart()) protected
Helper function used to build the string representation of a `WITH` clause, it constructs the CTE definitions list without generating the `RECURSIVE` keyword that is neither required nor valid.
* ##### [\_sqlCompiler()](#_sqlCompiler()) protected
Returns a callable object that can be used to compile a SQL string representation of this query.
* ##### [\_stringifyExpressions()](#_stringifyExpressions()) protected
Helper function used to covert ExpressionInterface objects inside an array into their string representation.
* ##### [compile()](#compile()) public
Returns the SQL representation of the provided query after generating the placeholders for the bound values using the provided generator
Method Detail
-------------
### \_buildFromPart() protected
```
_buildFromPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Helper function used to build the string representation of a FROM clause, it constructs the tables list taking care of aliasing and converting expression objects to string.
#### Parameters
`array` $parts list of tables to be transformed to string
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildHavingPart() protected
```
_buildHavingPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Helper function used to build the string representation of a HAVING clause, it constructs the field list taking care of aliasing and converting expression objects to string.
#### Parameters
`array` $parts list of fields to be transformed to string
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildInsertPart() protected
```
_buildInsertPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Generates the INSERT part of a SQL query
To better handle concurrency and low transaction isolation levels, we also include an OUTPUT clause so we can ensure we get the inserted row's data back.
#### Parameters
`array` $parts The parts to build
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildJoinPart() protected
```
_buildJoinPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Helper function used to build the string representation of multiple JOIN clauses, it constructs the joins list taking care of aliasing and converting expression objects to string in both the table to be joined and the conditions to be used.
#### Parameters
`array` $parts list of joins to be transformed to string
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildLimitPart() protected
```
_buildLimitPart(int $limit, Cake\Database\Query $query): string
```
Generates the LIMIT part of a SQL query
#### Parameters
`int` $limit the limit clause
`Cake\Database\Query` $query The query that is being compiled
#### Returns
`string`
### \_buildModifierPart() protected
```
_buildModifierPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Builds the SQL modifier fragment
#### Parameters
`array` $parts The query modifier parts
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildSelectPart() protected
```
_buildSelectPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Helper function used to build the string representation of a SELECT clause, it constructs the field list taking care of aliasing and converting expression objects to string. This function also constructs the DISTINCT clause for the query.
#### Parameters
`array` $parts list of fields to be transformed to string
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildSetPart() protected
```
_buildSetPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Helper function to generate SQL for SET expressions.
#### Parameters
`array` $parts List of keys & values to set.
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildUnionPart() protected
```
_buildUnionPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Builds the SQL string for all the UNION clauses in this query, when dealing with query objects it will also transform them using their configured SQL dialect.
#### Parameters
`array` $parts list of queries to be operated with UNION
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildUpdatePart() protected
```
_buildUpdatePart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Builds the SQL fragment for UPDATE.
#### Parameters
`array` $parts The update parts.
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildValuesPart() protected
```
_buildValuesPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Builds the SQL fragment for INSERT INTO.
#### Parameters
`array` $parts The values parts.
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildWindowPart() protected
```
_buildWindowPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Helper function to build the string representation of a window clause.
#### Parameters
`array` $parts List of windows to be transformed to string
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildWithPart() protected
```
_buildWithPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Helper function used to build the string representation of a `WITH` clause, it constructs the CTE definitions list without generating the `RECURSIVE` keyword that is neither required nor valid.
#### Parameters
`array` $parts List of CTEs to be transformed to string
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_sqlCompiler() protected
```
_sqlCompiler(string $sql, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): Closure
```
Returns a callable object that can be used to compile a SQL string representation of this query.
#### Parameters
`string` $sql initial sql string to append to
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`Closure`
### \_stringifyExpressions() protected
```
_stringifyExpressions(array $expressions, Cake\Database\ValueBinder $binder, bool $wrap = true): array
```
Helper function used to covert ExpressionInterface objects inside an array into their string representation.
#### Parameters
`array` $expressions list of strings and ExpressionInterface objects
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
`bool` $wrap optional Whether to wrap each expression object with parenthesis
#### Returns
`array`
### compile() public
```
compile(Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Returns the SQL representation of the provided query after generating the placeholders for the bound values using the provided generator
#### Parameters
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholders
#### Returns
`string`
Property Detail
---------------
### $\_deleteParts protected
The list of query clauses to traverse for generating a DELETE statement
#### Type
`array<string>`
### $\_insertParts protected
The list of query clauses to traverse for generating an INSERT statement
#### Type
`array<string>`
### $\_orderedUnion protected
SQLserver does not support ORDER BY in UNION queries.
Overridden in subclasses.
#### Type
`bool`
### $\_quotedSelectAliases protected
Indicate whether aliases in SELECT clause need to be always quoted.
#### Type
`bool`
### $\_selectParts protected
The list of query clauses to traverse for generating a SELECT statement
#### Type
`array<string>`
### $\_templates protected
List of sprintf templates that will be used for compiling the SQL for this query. There are some clauses that can be built as just as the direct concatenation of the internal parts, those are listed here.
#### Type
`array<string, string>`
### $\_updateParts protected
The list of query clauses to traverse for generating an UPDATE statement
#### Type
`array<string>`
cakephp Class MailCount Class MailCount
================
MailCount
**Namespace:** [Cake\TestSuite\Constraint\Email](namespace-cake.testsuite.constraint.email)
Property Summary
----------------
* [$at](#%24at) protected `int|null`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [getMessages()](#getMessages()) public
Gets the email or emails to check
* ##### [matches()](#matches()) public
Checks constraint
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message string
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(int|null $at = null): void
```
Constructor
#### Parameters
`int|null` $at optional At
#### Returns
`void`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### getMessages() public
```
getMessages(): arrayCake\Mailer\Message>
```
Gets the email or emails to check
#### Returns
`arrayCake\Mailer\Message>`
### matches() public
```
matches(mixed $other): bool
```
Checks constraint
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Constraint check
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message string
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $at protected
#### Type
`int|null`
| programming_docs |
cakephp Class TestSession Class TestSession
==================
Read only access to the session during testing.
**Namespace:** [Cake\TestSuite](namespace-cake.testsuite)
Property Summary
----------------
* [$session](#%24session) protected `array|null`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
* ##### [check()](#check()) public
Returns true if given variable name is set in session.
* ##### [read()](#read()) public
Returns given session variable, or all of them, if no parameters given.
Method Detail
-------------
### \_\_construct() public
```
__construct(array|null $session)
```
#### Parameters
`array|null` $session Session data.
### check() public
```
check(string|null $name = null): bool
```
Returns true if given variable name is set in session.
#### Parameters
`string|null` $name optional Variable name to check for
#### Returns
`bool`
### read() public
```
read(string|null $name = null): mixed
```
Returns given session variable, or all of them, if no parameters given.
#### Parameters
`string|null` $name optional The name of the session variable (or a path as sent to Hash.extract)
#### Returns
`mixed`
Property Detail
---------------
### $session protected
#### Type
`array|null`
cakephp Class ShadowTableStrategy Class ShadowTableStrategy
==========================
This class provides a way to translate dynamic data by keeping translations in a separate shadow table where each row corresponds to a row of primary table.
**Namespace:** [Cake\ORM\Behavior\Translate](namespace-cake.orm.behavior.translate)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
* [$locale](#%24locale) protected `string|null` The locale name that will be used to override fields in the bound table from the translations table
* [$table](#%24table) protected `Cake\ORM\Table` Table instance
* [$translationTable](#%24translationTable) protected `Cake\ORM\Table` Instance of Table responsible for translating
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [addFieldsToQuery()](#addFieldsToQuery()) protected
Add translation fields to query.
* ##### [afterSave()](#afterSave()) public
Unsets the temporary `_i18n` property after the entity has been saved
* ##### [beforeFind()](#beforeFind()) public
Callback method that listens to the `beforeFind` event in the bound table. It modifies the passed query by eager loading the translated fields and adding a formatter to copy the values into the main table records.
* ##### [beforeSave()](#beforeSave()) public
Modifies the entity before it is saved so that translated fields are persisted in the database too.
* ##### [buildMarshalMap()](#buildMarshalMap()) public
Build a set of properties that should be included in the marshalling process.
* ##### [bundleTranslatedFields()](#bundleTranslatedFields()) protected
Helper method used to generated multiple translated field entities out of the data found in the `_translations` property in the passed entity. The result will be put into its `_i18n` property.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getLocale()](#getLocale()) public
Returns the current locale.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [getTranslationTable()](#getTranslationTable()) public
Return translation table instance.
* ##### [groupTranslations()](#groupTranslations()) public
Modifies the results from a table find in order to merge full translation records into each entity under the `_translations` key.
* ##### [iterateClause()](#iterateClause()) protected
Iterate over a clause to alias fields.
* ##### [mainFields()](#mainFields()) protected
Lazy define and return the main table fields.
* ##### [rowMapper()](#rowMapper()) protected
Modifies the results from a table find in order to merge the translated fields into each entity for a given locale.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setLocale()](#setLocale()) public
Sets the locale to be used.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
* ##### [setupAssociations()](#setupAssociations()) protected
Create a hasMany association for all records.
* ##### [setupHasOneAssociation()](#setupHasOneAssociation()) protected
Create a hasOne association for record with required locale.
* ##### [translatedFields()](#translatedFields()) protected
Lazy define and return the translation table fields.
* ##### [translationField()](#translationField()) public
Returns a fully aliased field name for translated fields.
* ##### [traverseClause()](#traverseClause()) protected
Traverse over a clause to alias fields.
* ##### [unsetEmptyFields()](#unsetEmptyFields()) protected
Unset empty translations to avoid persistence.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\ORM\Table $table, array<string, mixed> $config = [])
```
Constructor
#### Parameters
`Cake\ORM\Table` $table Table instance.
`array<string, mixed>` $config optional Configuration.
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### addFieldsToQuery() protected
```
addFieldsToQuery(Cake\ORM\Query $query, array<string, mixed> $config): bool
```
Add translation fields to query.
If the query is using autofields (directly or implicitly) add the main table's fields to the query first.
Only add translations for fields that are in the main table, always add the locale field though.
#### Parameters
`Cake\ORM\Query` $query The query to check.
`array<string, mixed>` $config The config to use for adding fields.
#### Returns
`bool`
### afterSave() public
```
afterSave(Cake\Event\EventInterface $event, Cake\Datasource\EntityInterface $entity): void
```
Unsets the temporary `_i18n` property after the entity has been saved
#### Parameters
`Cake\Event\EventInterface` $event The beforeSave event that was fired
`Cake\Datasource\EntityInterface` $entity The entity that is going to be saved
#### Returns
`void`
### beforeFind() public
```
beforeFind(Cake\Event\EventInterface $event, Cake\ORM\Query $query, ArrayObject $options): void
```
Callback method that listens to the `beforeFind` event in the bound table. It modifies the passed query by eager loading the translated fields and adding a formatter to copy the values into the main table records.
#### Parameters
`Cake\Event\EventInterface` $event The beforeFind event that was fired.
`Cake\ORM\Query` $query Query.
`ArrayObject` $options The options for the query.
#### Returns
`void`
### beforeSave() public
```
beforeSave(Cake\Event\EventInterface $event, Cake\Datasource\EntityInterface $entity, ArrayObject $options): void
```
Modifies the entity before it is saved so that translated fields are persisted in the database too.
#### Parameters
`Cake\Event\EventInterface` $event The beforeSave event that was fired.
`Cake\Datasource\EntityInterface` $entity The entity that is going to be saved.
`ArrayObject` $options the options passed to the save method.
#### Returns
`void`
### buildMarshalMap() public
```
buildMarshalMap(Cake\ORM\Marshaller $marshaller, array $map, array<string, mixed> $options): array
```
Build a set of properties that should be included in the marshalling process.
Add in `_translations` marshalling handlers. You can disable marshalling of translations by setting `'translations' => false` in the options provided to `Table::newEntity()` or `Table::patchEntity()`.
#### Parameters
`Cake\ORM\Marshaller` $marshaller `array` $map `array<string, mixed>` $options #### Returns
`array`
### bundleTranslatedFields() protected
```
bundleTranslatedFields(Cake\Datasource\EntityInterface $entity): void
```
Helper method used to generated multiple translated field entities out of the data found in the `_translations` property in the passed entity. The result will be put into its `_i18n` property.
#### Parameters
`Cake\Datasource\EntityInterface` $entity Entity.
#### Returns
`void`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getLocale() public
```
getLocale(): string
```
Returns the current locale.
If no locale has been explicitly set via `setLocale()`, this method will return the currently configured global locale.
#### Returns
`string`
#### See Also
\Cake\I18n\I18n::getLocale()
\Cake\ORM\Behavior\TranslateBehavior::setLocale() ### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### getTranslationTable() public
```
getTranslationTable(): Cake\ORM\Table
```
Return translation table instance.
#### Returns
`Cake\ORM\Table`
### groupTranslations() public
```
groupTranslations(Cake\Datasource\ResultSetInterface $results): Cake\Collection\CollectionInterface
```
Modifies the results from a table find in order to merge full translation records into each entity under the `_translations` key.
#### Parameters
`Cake\Datasource\ResultSetInterface` $results Results to modify.
#### Returns
`Cake\Collection\CollectionInterface`
### iterateClause() protected
```
iterateClause(Cake\ORM\Query $query, string $name = '', array<string, mixed> $config = []): bool
```
Iterate over a clause to alias fields.
The objective here is to transparently prevent ambiguous field errors by prefixing fields with the appropriate table alias. This method currently expects to receive an order clause only.
#### Parameters
`Cake\ORM\Query` $query the query to check.
`string` $name optional The clause name.
`array<string, mixed>` $config optional The config to use for adding fields.
#### Returns
`bool`
### mainFields() protected
```
mainFields(): array<string>
```
Lazy define and return the main table fields.
#### Returns
`array<string>`
### rowMapper() protected
```
rowMapper(Cake\Datasource\ResultSetInterface $results, string $locale): Cake\Collection\CollectionInterface
```
Modifies the results from a table find in order to merge the translated fields into each entity for a given locale.
#### Parameters
`Cake\Datasource\ResultSetInterface` $results Results to map.
`string` $locale Locale string
#### Returns
`Cake\Collection\CollectionInterface`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setLocale() public
```
setLocale(string|null $locale): $this
```
Sets the locale to be used.
When fetching records, the content for the locale set via this method, and likewise when saving data, it will save the data in that locale.
Note that in case an entity has a `_locale` property set, that locale will win over the locale set via this method (and over the globally configured one for that matter)!
#### Parameters
`string|null` $locale The locale to use for fetching and saving records. Pass `null` in order to unset the current locale, and to make the behavior fall back to using the globally configured locale.
#### Returns
`$this`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
### setupAssociations() protected
```
setupAssociations(): void
```
Create a hasMany association for all records.
Don't create a hasOne association here as the join conditions are modified in before find - so create/modify it there.
#### Returns
`void`
### setupHasOneAssociation() protected
```
setupHasOneAssociation(string $locale, ArrayObject $options): void
```
Create a hasOne association for record with required locale.
#### Parameters
`string` $locale Locale
`ArrayObject` $options Find options
#### Returns
`void`
### translatedFields() protected
```
translatedFields(): array<string>
```
Lazy define and return the translation table fields.
#### Returns
`array<string>`
### translationField() public
```
translationField(string $field): string
```
Returns a fully aliased field name for translated fields.
If the requested field is configured as a translation field, field with an alias of a corresponding association is returned. Table-aliased field name is returned for all other fields.
#### Parameters
`string` $field Field name to be aliased.
#### Returns
`string`
### traverseClause() protected
```
traverseClause(Cake\ORM\Query $query, string $name = '', array<string, mixed> $config = []): bool
```
Traverse over a clause to alias fields.
The objective here is to transparently prevent ambiguous field errors by prefixing fields with the appropriate table alias. This method currently expects to receive a where clause only.
#### Parameters
`Cake\ORM\Query` $query the query to check.
`string` $name optional The clause name.
`array<string, mixed>` $config optional The config to use for adding fields.
#### Returns
`bool`
### unsetEmptyFields() protected
```
unsetEmptyFields(Cake\Datasource\EntityInterface $entity): void
```
Unset empty translations to avoid persistence.
Should only be called if $this->\_config['allowEmptyTranslations'] is false.
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity to check for empty translations fields inside.
#### Returns
`void`
Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config
These are merged with user-provided configuration.
#### Type
`array<string, mixed>`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
### $locale protected
The locale name that will be used to override fields in the bound table from the translations table
#### Type
`string|null`
### $table protected
Table instance
#### Type
`Cake\ORM\Table`
### $translationTable protected
Instance of Table responsible for translating
#### Type
`Cake\ORM\Table`
| programming_docs |
cakephp Class JsonFormatter Class JsonFormatter
====================
**Namespace:** [Cake\Log\Formatter](namespace-cake.log.formatter)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this class
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [format()](#format()) public
Formats message.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [setConfig()](#setConfig()) public
Sets the config.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
#### Parameters
`array<string, mixed>` $config optional Formatter config
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### format() public
```
format(mixed $level, string $message, array $context = []): string
```
Formats message.
#### Parameters
`mixed` $level `string` $message `array` $context optional #### Returns
`string`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this class
#### Type
`array<string, mixed>`
cakephp Class RoutesGenerateCommand Class RoutesGenerateCommand
============================
Provides interactive CLI tools for URL generation
**Namespace:** [Cake\Command](namespace-cake.command)
Constants
---------
* `int` **CODE\_ERROR**
```
1
```
Default error code
* `int` **CODE\_SUCCESS**
```
0
```
Default success code
Property Summary
----------------
* [$\_modelFactories](#%24_modelFactories) protected `array<callableCake\Datasource\Locator\LocatorInterface>` A list of overridden model factory functions.
* [$\_modelType](#%24_modelType) protected `string` The model type to use.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
* [$modelClass](#%24modelClass) protected deprecated `string|null` This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
* [$name](#%24name) protected `string` The name of this command.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_setModelClass()](#_setModelClass()) protected
Set the modelClass property based on conventions.
* ##### [\_splitArgs()](#_splitArgs()) protected
Split the CLI arguments into a hash.
* ##### [abort()](#abort()) public
Halt the the current process with a StopException.
* ##### [buildOptionParser()](#buildOptionParser()) public
Get the option parser.
* ##### [defaultName()](#defaultName()) public static
Get the command name.
* ##### [displayHelp()](#displayHelp()) protected
Output help content
* ##### [execute()](#execute()) public
Display all routes in an application
* ##### [executeCommand()](#executeCommand()) public
Execute another command with the provided set of arguments.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getDescription()](#getDescription()) public static
Get the command description.
* ##### [getModelType()](#getModelType()) public
Get the model type to be used by this class
* ##### [getName()](#getName()) public
Get the command name.
* ##### [getOptionParser()](#getOptionParser()) public
Get the option parser.
* ##### [getRootName()](#getRootName()) public
Get the root command name.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [initialize()](#initialize()) public
Hook method invoked by CakePHP when a command is about to be executed.
* ##### [loadModel()](#loadModel()) public deprecated
Loads and constructs repository objects required by this object
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [modelFactory()](#modelFactory()) public
Override a existing callable to generate repositories of a given type.
* ##### [run()](#run()) public
Run the command.
* ##### [setModelType()](#setModelType()) public
Set the model type to be used by this class
* ##### [setName()](#setName()) public
Set the name this command uses in the collection.
* ##### [setOutputLevel()](#setOutputLevel()) protected
Set the output level based on the Arguments.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
Method Detail
-------------
### \_\_construct() public
```
__construct()
```
Constructor
By default CakePHP will construct command objects when building the CommandCollection for your application.
### \_setModelClass() protected
```
_setModelClass(string $name): void
```
Set the modelClass property based on conventions.
If the property is already set it will not be overwritten
#### Parameters
`string` $name Class name.
#### Returns
`void`
### \_splitArgs() protected
```
_splitArgs(array<string> $args): array<string|bool>
```
Split the CLI arguments into a hash.
#### Parameters
`array<string>` $args The arguments to split.
#### Returns
`array<string|bool>`
### abort() public
```
abort(int $code = self::CODE_ERROR): void
```
Halt the the current process with a StopException.
#### Parameters
`int` $code optional The exit code to use.
#### Returns
`void`
#### Throws
`Cake\Console\Exception\StopException`
### buildOptionParser() public
```
buildOptionParser(Cake\Console\ConsoleOptionParser $parser): Cake\Console\ConsoleOptionParser
```
Get the option parser.
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser to update
#### Returns
`Cake\Console\ConsoleOptionParser`
### defaultName() public static
```
defaultName(): string
```
Get the command name.
Returns the command name based on class name. For e.g. for a command with class name `UpdateTableCommand` the default name returned would be `'update_table'`.
#### Returns
`string`
### displayHelp() protected
```
displayHelp(Cake\Console\ConsoleOptionParser $parser, Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Output help content
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser.
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### execute() public
```
execute(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): int|null
```
Display all routes in an application
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`int|null`
### executeCommand() public
```
executeCommand(Cake\Console\CommandInterface|string $command, array $args = [], Cake\Console\ConsoleIo|null $io = null): int|null
```
Execute another command with the provided set of arguments.
If you are using a string command name, that command's dependencies will not be resolved with the application container. Instead you will need to pass the command as an object with all of its dependencies.
#### Parameters
`Cake\Console\CommandInterface|string` $command The command class name or command instance.
`array` $args optional The arguments to invoke the command with.
`Cake\Console\ConsoleIo|null` $io optional The ConsoleIo instance to use for the executed command.
#### Returns
`int|null`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getDescription() public static
```
getDescription(): string
```
Get the command description.
#### Returns
`string`
### getModelType() public
```
getModelType(): string
```
Get the model type to be used by this class
#### Returns
`string`
### getName() public
```
getName(): string
```
Get the command name.
#### Returns
`string`
### getOptionParser() public
```
getOptionParser(): Cake\Console\ConsoleOptionParser
```
Get the option parser.
You can override buildOptionParser() to define your options & arguments.
#### Returns
`Cake\Console\ConsoleOptionParser`
#### Throws
`RuntimeException`
When the parser is invalid ### getRootName() public
```
getRootName(): string
```
Get the root command name.
#### Returns
`string`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### initialize() public
```
initialize(): void
```
Hook method invoked by CakePHP when a command is about to be executed.
Override this method and implement expensive/important setup steps that should not run on every command run. This method will be called *before* the options and arguments are validated and processed.
#### Returns
`void`
### loadModel() public
```
loadModel(string|null $modelClass = null, string|null $modelType = null): Cake\Datasource\RepositoryInterface
```
Loads and constructs repository objects required by this object
Typically used to load ORM Table objects as required. Can also be used to load other types of repository objects your application uses.
If a repository provider does not return an object a MissingModelException will be thrown.
#### Parameters
`string|null` $modelClass optional Name of model class to load. Defaults to $this->modelClass. The name can be an alias like `'Post'` or FQCN like `App\Model\Table\PostsTable::class`.
`string|null` $modelType optional The type of repository to load. Defaults to the getModelType() value.
#### Returns
`Cake\Datasource\RepositoryInterface`
#### Throws
`Cake\Datasource\Exception\MissingModelException`
If the model class cannot be found.
`UnexpectedValueException`
If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty. ### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### modelFactory() public
```
modelFactory(string $type, Cake\Datasource\Locator\LocatorInterface|callable $factory): void
```
Override a existing callable to generate repositories of a given type.
#### Parameters
`string` $type The name of the repository type the factory function is for.
`Cake\Datasource\Locator\LocatorInterface|callable` $factory The factory function used to create instances.
#### Returns
`void`
### run() public
```
run(array $argv, Cake\Console\ConsoleIo $io): int|null
```
Run the command.
#### Parameters
`array` $argv `Cake\Console\ConsoleIo` $io #### Returns
`int|null`
### setModelType() public
```
setModelType(string $modelType): $this
```
Set the model type to be used by this class
#### Parameters
`string` $modelType The model type
#### Returns
`$this`
### setName() public
```
setName(string $name): $this
```
Set the name this command uses in the collection.
Generally invoked by the CommandCollection when the command is added. Required to have at least one space in the name so that the root command can be calculated.
#### Parameters
`string` $name #### Returns
`$this`
### setOutputLevel() protected
```
setOutputLevel(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Set the output level based on the Arguments.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
Property Detail
---------------
### $\_modelFactories protected
A list of overridden model factory functions.
#### Type
`array<callableCake\Datasource\Locator\LocatorInterface>`
### $\_modelType protected
The model type to use.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
### $modelClass protected deprecated
This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
Example: For an object named 'Comments', the modelClass would be 'Comments'. Plugin classes should use `Plugin.Comments` style names to correctly load models from the correct plugin.
Use empty string to not use auto-loading on this object. Null auto-detects based on controller name.
#### Type
`string|null`
### $name protected
The name of this command.
#### Type
`string`
cakephp Trait CaseExpressionTrait Trait CaseExpressionTrait
==========================
Trait that holds shared functionality for case related expressions.
**Namespace:** [Cake\Database\Expression](namespace-cake.database.expression)
Property Summary
----------------
* [$\_typeMap](#%24_typeMap) public @property `Cake\Database\TypeMap` The type map to use when using an array of conditions for the `WHEN` value.
Method Summary
--------------
* ##### [compileNullableValue()](#compileNullableValue()) protected
Compiles a nullable value to SQL.
* ##### [inferType()](#inferType()) protected
Infers the abstract type for the given value.
Method Detail
-------------
### compileNullableValue() protected
```
compileNullableValue(Cake\Database\ValueBinder $binder, Cake\Database\ExpressionInterface|object|scalar|null $value, string|null $type = null): string
```
Compiles a nullable value to SQL.
#### Parameters
`Cake\Database\ValueBinder` $binder The value binder to use.
`Cake\Database\ExpressionInterface|object|scalar|null` $value The value to compile.
`string|null` $type optional The value type.
#### Returns
`string`
### inferType() protected
```
inferType(mixed $value): string|null
```
Infers the abstract type for the given value.
#### Parameters
`mixed` $value The value for which to infer the type.
#### Returns
`string|null`
Property Detail
---------------
### $\_typeMap public @property
The type map to use when using an array of conditions for the `WHEN` value.
#### Type
`Cake\Database\TypeMap`
| programming_docs |
cakephp Namespace ORM Namespace ORM
=============
### Namespaces
* [Cake\ORM\Association](namespace-cake.orm.association)
* [Cake\ORM\Behavior](namespace-cake.orm.behavior)
* [Cake\ORM\Exception](namespace-cake.orm.exception)
* [Cake\ORM\Locator](namespace-cake.orm.locator)
* [Cake\ORM\Rule](namespace-cake.orm.rule)
### Interfaces
* ##### [PropertyMarshalInterface](interface-cake.orm.propertymarshalinterface)
Behaviors implementing this interface can participate in entity marshalling.
### Classes
* ##### [Association](class-cake.orm.association)
An Association is a relationship established between two tables and is used to configure and customize the way interconnected records are retrieved.
* ##### [AssociationCollection](class-cake.orm.associationcollection)
A container/collection for association classes.
* ##### [Behavior](class-cake.orm.behavior)
Base class for behaviors.
* ##### [BehaviorRegistry](class-cake.orm.behaviorregistry)
BehaviorRegistry is used as a registry for loaded behaviors and handles loading and constructing behavior objects.
* ##### [EagerLoadable](class-cake.orm.eagerloadable)
Represents a single level in the associations tree to be eagerly loaded for a specific query. This contains all the information required to fetch the results from the database from an associations and all its children levels.
* ##### [EagerLoader](class-cake.orm.eagerloader)
Exposes the methods for storing the associations that should be eager loaded for a table once a query is provided and delegates the job of creating the required joins and decorating the results so that those associations can be part of the result set.
* ##### [Entity](class-cake.orm.entity)
An entity represents a single result row from a repository. It exposes the methods for retrieving and storing properties associated in this row.
* ##### [LazyEagerLoader](class-cake.orm.lazyeagerloader)
Contains methods that are capable of injecting eagerly loaded associations into entities or lists of entities by using the same syntax as the EagerLoader.
* ##### [Marshaller](class-cake.orm.marshaller)
Contains logic to convert array data into entities.
* ##### [Query](class-cake.orm.query)
Extends the base Query class to provide new methods related to association loading, automatic fields selection, automatic type casting and to wrap results into a specific iterator that will be responsible for hydrating results if required.
* ##### [ResultSet](class-cake.orm.resultset)
Represents the results obtained after executing a query for a specific table This object is responsible for correctly nesting result keys reported from the query, casting each field to the correct type and executing the extra queries required for eager loading external associations.
* ##### [RulesChecker](class-cake.orm.ruleschecker)
ORM flavoured rules checker.
* ##### [SaveOptionsBuilder](class-cake.orm.saveoptionsbuilder)
OOP style Save Option Builder.
* ##### [Table](class-cake.orm.table)
Represents a single database table.
* ##### [TableRegistry](class-cake.orm.tableregistry)
Provides a registry/factory for Table objects.
### Traits
* ##### [AssociationsNormalizerTrait](trait-cake.orm.associationsnormalizertrait)
Contains methods for parsing the associated tables array that is typically passed to a save operation
cakephp Class FlashMessage Class FlashMessage
===================
The FlashMessage class provides a way for you to write a flash variable to the session, to be rendered in a view with the FlashHelper.
**Namespace:** [Cake\Http](namespace-cake.http)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default configuration
* [$session](#%24session) protected `Cake\Http\Session`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [consume()](#consume()) public
Get the messages for given key and remove from session.
* ##### [error()](#error()) public
Set an success message.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [info()](#info()) public
Set an info message.
* ##### [set()](#set()) public
Store flash messages that can be output in the view.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setExceptionMessage()](#setExceptionMessage()) public
Set an exception's message as flash message.
* ##### [success()](#success()) public
Set a success message.
* ##### [warning()](#warning()) public
Set a warning message.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Http\Session $session, array<string, mixed> $config = [])
```
Constructor
#### Parameters
`Cake\Http\Session` $session Session instance.
`array<string, mixed>` $config optional Config array.
#### See Also
FlashMessage::set() For list of valid config keys. ### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### consume() public
```
consume(string $key): array|null
```
Get the messages for given key and remove from session.
#### Parameters
`string` $key The key for get messages for.
#### Returns
`array|null`
### error() public
```
error(string $message, array<string, mixed> $options = []): void
```
Set an success message.
The `'element'` option will be set to `'error'`.
#### Parameters
`string` $message Message to flash.
`array<string, mixed>` $options optional An array of options.
#### Returns
`void`
#### See Also
FlashMessage::set() For list of valid options ### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### info() public
```
info(string $message, array<string, mixed> $options = []): void
```
Set an info message.
The `'element'` option will be set to `'info'`.
#### Parameters
`string` $message Message to flash.
`array<string, mixed>` $options optional An array of options.
#### Returns
`void`
#### See Also
FlashMessage::set() For list of valid options ### set() public
```
set(string $message, array<string, mixed> $options = []): void
```
Store flash messages that can be output in the view.
If you make consecutive calls to this method, the messages will stack (if they are set with the same flash key)
### Options:
* `key` The key to set under the session's Flash key.
* `element` The element used to render the flash message. You can use `'SomePlugin.name'` style value for flash elements from a plugin.
* `plugin` Plugin name to use element from.
* `params` An array of variables to be made available to the element.
* `clear` A bool stating if the current stack should be cleared to start a new one.
* `escape` Set to false to allow templates to print out HTML content.
#### Parameters
`string` $message Message to be flashed.
`array<string, mixed>` $options optional An array of options
#### Returns
`void`
#### See Also
FlashMessage::$\_defaultConfig For default values for the options. ### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setExceptionMessage() public
```
setExceptionMessage(Throwable $exception, array<string, mixed> $options = []): void
```
Set an exception's message as flash message.
The following options will be set by default if unset:
```
'element' => 'error',
`params' => ['code' => $exception->getCode()]
```
#### Parameters
`Throwable` $exception Exception instance.
`array<string, mixed>` $options optional An array of options.
#### Returns
`void`
#### See Also
FlashMessage::set() For list of valid options ### success() public
```
success(string $message, array<string, mixed> $options = []): void
```
Set a success message.
The `'element'` option will be set to `'success'`.
#### Parameters
`string` $message Message to flash.
`array<string, mixed>` $options optional An array of options.
#### Returns
`void`
#### See Also
FlashMessage::set() For list of valid options ### warning() public
```
warning(string $message, array<string, mixed> $options = []): void
```
Set a warning message.
The `'element'` option will be set to `'warning'`.
#### Parameters
`string` $message Message to flash.
`array<string, mixed>` $options optional An array of options.
#### Returns
`void`
#### See Also
FlashMessage::set() For list of valid options Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default configuration
#### Type
`array<string, mixed>`
### $session protected
#### Type
`Cake\Http\Session`
cakephp Class Configure Class Configure
================
Configuration class. Used for managing runtime configuration information.
Provides features for reading and writing to the runtime configuration, as well as methods for loading additional configuration files or storing runtime configuration for future use.
**Namespace:** [Cake\Core](namespace-cake.core)
**Link:** https://book.cakephp.org/4/en/development/configuration.html
Property Summary
----------------
* [$\_engines](#%24_engines) protected static `arrayCake\Core\Configure\ConfigEngineInterface>` Configured engine classes, used to load config files from resources
* [$\_hasIniSet](#%24_hasIniSet) protected static `bool|null` Flag to track whether ini\_set exists.
* [$\_values](#%24_values) protected static `array<string, mixed>` Array of values currently stored in Configure.
Method Summary
--------------
* ##### [\_getEngine()](#_getEngine()) protected static
Get the configured engine. Internally used by `Configure::load()` and `Configure::dump()` Will create new PhpConfig for default if not configured yet.
* ##### [check()](#check()) public static
Returns true if given variable is set in Configure.
* ##### [clear()](#clear()) public static
Clear all values stored in Configure.
* ##### [config()](#config()) public static
Add a new engine to Configure. Engines allow you to read configuration files in various formats/storage locations. CakePHP comes with two built-in engines PhpConfig and IniConfig. You can also implement your own engine classes in your application.
* ##### [configured()](#configured()) public static
Gets the names of the configured Engine objects.
* ##### [consume()](#consume()) public static
Used to read and delete a variable from Configure.
* ##### [consumeOrFail()](#consumeOrFail()) public static
Used to consume information stored in Configure. It's not possible to store `null` values in Configure.
* ##### [delete()](#delete()) public static
Used to delete a variable from Configure.
* ##### [drop()](#drop()) public static
Remove a configured engine. This will unset the engine and make any future attempts to use it cause an Exception.
* ##### [dump()](#dump()) public static
Dump data currently in Configure into $key. The serialization format is decided by the config engine attached as $config. For example, if the 'default' adapter is a PhpConfig, the generated file will be a PHP configuration file loadable by the PhpConfig.
* ##### [isConfigured()](#isConfigured()) public static
Returns true if the Engine objects is configured.
* ##### [load()](#load()) public static
Loads stored configuration information from a resource. You can add config file resource engines with `Configure::config()`.
* ##### [read()](#read()) public static
Used to read information stored in Configure. It's not possible to store `null` values in Configure.
* ##### [readOrFail()](#readOrFail()) public static
Used to get information stored in Configure. It's not possible to store `null` values in Configure.
* ##### [restore()](#restore()) public static
Restores configuration data stored in the Cache into configure. Restored values will overwrite existing ones.
* ##### [store()](#store()) public static
Used to write runtime configuration into Cache. Stored runtime configuration can be restored using `Configure::restore()`. These methods can be used to enable configuration managers frontends, or other GUI type interfaces for configuration.
* ##### [version()](#version()) public static
Used to determine the current version of CakePHP.
* ##### [write()](#write()) public static
Used to store a dynamic variable in Configure.
Method Detail
-------------
### \_getEngine() protected static
```
_getEngine(string $config): Cake\Core\Configure\ConfigEngineInterface|null
```
Get the configured engine. Internally used by `Configure::load()` and `Configure::dump()` Will create new PhpConfig for default if not configured yet.
#### Parameters
`string` $config The name of the configured adapter
#### Returns
`Cake\Core\Configure\ConfigEngineInterface|null`
### check() public static
```
check(string $var): bool
```
Returns true if given variable is set in Configure.
#### Parameters
`string` $var Variable name to check for
#### Returns
`bool`
### clear() public static
```
clear(): void
```
Clear all values stored in Configure.
#### Returns
`void`
### config() public static
```
config(string $name, Cake\Core\Configure\ConfigEngineInterface $engine): void
```
Add a new engine to Configure. Engines allow you to read configuration files in various formats/storage locations. CakePHP comes with two built-in engines PhpConfig and IniConfig. You can also implement your own engine classes in your application.
To add a new engine to Configure:
```
Configure::config('ini', new IniConfig());
```
#### Parameters
`string` $name The name of the engine being configured. This alias is used later to read values from a specific engine.
`Cake\Core\Configure\ConfigEngineInterface` $engine The engine to append.
#### Returns
`void`
### configured() public static
```
configured(): array<string>
```
Gets the names of the configured Engine objects.
#### Returns
`array<string>`
### consume() public static
```
consume(string $var): array|string|null
```
Used to read and delete a variable from Configure.
This is primarily used during bootstrapping to move configuration data out of configure into the various other classes in CakePHP.
#### Parameters
`string` $var The key to read and remove.
#### Returns
`array|string|null`
### consumeOrFail() public static
```
consumeOrFail(string $var): mixed
```
Used to consume information stored in Configure. It's not possible to store `null` values in Configure.
Acts as a wrapper around Configure::consume() and Configure::check(). The configure key/value pair consumed via this method is expected to exist. In case it does not an exception will be thrown.
#### Parameters
`string` $var Variable to consume. Use '.' to access array elements.
#### Returns
`mixed`
#### Throws
`RuntimeException`
if the requested configuration is not set. ### delete() public static
```
delete(string $var): void
```
Used to delete a variable from Configure.
Usage:
```
Configure::delete('Name'); will delete the entire Configure::Name
Configure::delete('Name.key'); will delete only the Configure::Name[key]
```
#### Parameters
`string` $var the var to be deleted
#### Returns
`void`
#### Links
https://book.cakephp.org/4/en/development/configuration.html#deleting-configuration-data
### drop() public static
```
drop(string $name): bool
```
Remove a configured engine. This will unset the engine and make any future attempts to use it cause an Exception.
#### Parameters
`string` $name Name of the engine to drop.
#### Returns
`bool`
### dump() public static
```
dump(string $key, string $config = 'default', array<string> $keys = []): bool
```
Dump data currently in Configure into $key. The serialization format is decided by the config engine attached as $config. For example, if the 'default' adapter is a PhpConfig, the generated file will be a PHP configuration file loadable by the PhpConfig.
### Usage
Given that the 'default' engine is an instance of PhpConfig. Save all data in Configure to the file `my_config.php`:
```
Configure::dump('my_config', 'default');
```
Save only the error handling configuration:
```
Configure::dump('error', 'default', ['Error', 'Exception'];
```
#### Parameters
`string` $key The identifier to create in the config adapter. This could be a filename or a cache key depending on the adapter being used.
`string` $config optional The name of the configured adapter to dump data with.
`array<string>` $keys optional The name of the top-level keys you want to dump. This allows you save only some data stored in Configure.
#### Returns
`bool`
#### Throws
`Cake\Core\Exception\CakeException`
if the adapter does not implement a `dump` method. ### isConfigured() public static
```
isConfigured(string $name): bool
```
Returns true if the Engine objects is configured.
#### Parameters
`string` $name Engine name.
#### Returns
`bool`
### load() public static
```
load(string $key, string $config = 'default', bool $merge = true): bool
```
Loads stored configuration information from a resource. You can add config file resource engines with `Configure::config()`.
Loaded configuration information will be merged with the current runtime configuration. You can load configuration files from plugins by preceding the filename with the plugin name.
`Configure::load('Users.user', 'default')`
Would load the 'user' config file using the default config engine. You can load app config files by giving the name of the resource you want loaded.
```
Configure::load('setup', 'default');
```
If using `default` config and no engine has been configured for it yet, one will be automatically created using PhpConfig
#### Parameters
`string` $key name of configuration resource to load.
`string` $config optional Name of the configured engine to use to read the resource identified by $key.
`bool` $merge optional if config files should be merged instead of simply overridden
#### Returns
`bool`
#### Throws
`Cake\Core\Exception\CakeException`
if the $config engine is not found #### Links
https://book.cakephp.org/4/en/development/configuration.html#reading-and-writing-configuration-files
### read() public static
```
read(string|null $var = null, mixed $default = null): mixed
```
Used to read information stored in Configure. It's not possible to store `null` values in Configure.
Usage:
```
Configure::read('Name'); will return all values for Name
Configure::read('Name.key'); will return only the value of Configure::Name[key]
```
#### Parameters
`string|null` $var optional Variable to obtain. Use '.' to access array elements.
`mixed` $default optional The return value when the configure does not exist
#### Returns
`mixed`
#### Links
https://book.cakephp.org/4/en/development/configuration.html#reading-configuration-data
### readOrFail() public static
```
readOrFail(string $var): mixed
```
Used to get information stored in Configure. It's not possible to store `null` values in Configure.
Acts as a wrapper around Configure::read() and Configure::check(). The configure key/value pair fetched via this method is expected to exist. In case it does not an exception will be thrown.
Usage:
```
Configure::readOrFail('Name'); will return all values for Name
Configure::readOrFail('Name.key'); will return only the value of Configure::Name[key]
```
#### Parameters
`string` $var Variable to obtain. Use '.' to access array elements.
#### Returns
`mixed`
#### Throws
`RuntimeException`
if the requested configuration is not set. #### Links
https://book.cakephp.org/4/en/development/configuration.html#reading-configuration-data
### restore() public static
```
restore(string $name, string $cacheConfig = 'default'): bool
```
Restores configuration data stored in the Cache into configure. Restored values will overwrite existing ones.
#### Parameters
`string` $name Name of the stored config file to load.
`string` $cacheConfig optional Name of the Cache configuration to read from.
#### Returns
`bool`
#### Throws
`RuntimeException`
### store() public static
```
store(string $name, string $cacheConfig = 'default', array|null $data = null): bool
```
Used to write runtime configuration into Cache. Stored runtime configuration can be restored using `Configure::restore()`. These methods can be used to enable configuration managers frontends, or other GUI type interfaces for configuration.
#### Parameters
`string` $name The storage name for the saved configuration.
`string` $cacheConfig optional The cache configuration to save into. Defaults to 'default'
`array|null` $data optional Either an array of data to store, or leave empty to store all values.
#### Returns
`bool`
#### Throws
`RuntimeException`
### version() public static
```
version(): string
```
Used to determine the current version of CakePHP.
Usage
```
Configure::version();
```
#### Returns
`string`
### write() public static
```
write(array<string, mixed>|string $config, mixed $value = null): void
```
Used to store a dynamic variable in Configure.
Usage:
```
Configure::write('One.key1', 'value of the Configure::One[key1]');
Configure::write(['One.key1' => 'value of the Configure::One[key1]']);
Configure::write('One', [
'key1' => 'value of the Configure::One[key1]',
'key2' => 'value of the Configure::One[key2]'
]);
Configure::write([
'One.key1' => 'value of the Configure::One[key1]',
'One.key2' => 'value of the Configure::One[key2]'
]);
```
#### Parameters
`array<string, mixed>|string` $config The key to write, can be a dot notation value. Alternatively can be an array containing key(s) and value(s).
`mixed` $value optional Value to set for var
#### Returns
`void`
#### Links
https://book.cakephp.org/4/en/development/configuration.html#writing-configuration-data
Property Detail
---------------
### $\_engines protected static
Configured engine classes, used to load config files from resources
#### Type
`arrayCake\Core\Configure\ConfigEngineInterface>`
### $\_hasIniSet protected static
Flag to track whether ini\_set exists.
#### Type
`bool|null`
### $\_values protected static
Array of values currently stored in Configure.
#### Type
`array<string, mixed>`
| programming_docs |
cakephp Class StatusCode Class StatusCode
=================
StatusCode
**Namespace:** [Cake\TestSuite\Constraint\Response](namespace-cake.testsuite.constraint.response)
Property Summary
----------------
* [$code](#%24code) protected `array<int, int>|int`
* [$response](#%24response) protected `Psr\Http\Message\ResponseInterface`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_getBodyAsString()](#_getBodyAsString()) protected
Get the response body as string
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) public
Failure description
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Check assertion
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [statusCodeBetween()](#statusCodeBetween()) protected
Helper for checking status codes
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(Psr\Http\Message\ResponseInterface|null $response)
```
Constructor
#### Parameters
`Psr\Http\Message\ResponseInterface|null` $response Response
### \_getBodyAsString() protected
```
_getBodyAsString(): string
```
Get the response body as string
#### Returns
`string`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() public
```
failureDescription(mixed $other): string
```
Failure description
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other Expected code
#### Returns
`string`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Check assertion
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Array of min/max status codes, or a single code
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### statusCodeBetween() protected
```
statusCodeBetween(int $min, int $max): bool
```
Helper for checking status codes
#### Parameters
`int` $min Min status code (inclusive)
`int` $max Max status code (inclusive)
#### Returns
`bool`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $code protected
#### Type
`array<int, int>|int`
### $response protected
#### Type
`Psr\Http\Message\ResponseInterface`
cakephp Class WindowExpression Class WindowExpression
=======================
This represents a SQL window expression used by aggregate and window functions.
**Namespace:** [Cake\Database\Expression](namespace-cake.database.expression)
Constants
---------
* `string` **FOLLOWING**
```
'FOLLOWING'
```
* `string` **GROUPS**
```
'GROUPS'
```
* `string` **PRECEDING**
```
'PRECEDING'
```
* `string` **RANGE**
```
'RANGE'
```
* `string` **ROWS**
```
'ROWS'
```
Property Summary
----------------
* [$exclusion](#%24exclusion) protected `string|null`
* [$frame](#%24frame) protected `array|null`
* [$name](#%24name) protected `Cake\Database\Expression\IdentifierExpression`
* [$order](#%24order) protected `Cake\Database\Expression\OrderByExpression|null`
* [$partitions](#%24partitions) protected `arrayCake\Database\ExpressionInterface>`
Method Summary
--------------
* ##### [\_\_clone()](#__clone()) public
Clone this object and its subtree of expressions.
* ##### [\_\_construct()](#__construct()) public
* ##### [buildOffsetSql()](#buildOffsetSql()) protected
Builds frame offset sql.
* ##### [excludeCurrent()](#excludeCurrent()) public
Adds current row frame exclusion.
* ##### [excludeGroup()](#excludeGroup()) public
Adds group frame exclusion.
* ##### [excludeTies()](#excludeTies()) public
Adds ties frame exclusion.
* ##### [frame()](#frame()) public
Adds a frame to the window.
* ##### [groups()](#groups()) public
Adds a simple groups frame to the window.
* ##### [isNamedOnly()](#isNamedOnly()) public
Return whether is only a named window expression.
* ##### [name()](#name()) public
Sets the window name.
* ##### [order()](#order()) public
Adds one or more order clauses to the window.
* ##### [partition()](#partition()) public
Adds one or more partition expressions to the window.
* ##### [range()](#range()) public
Adds a simple range frame to the window.
* ##### [rows()](#rows()) public
Adds a simple rows frame to the window.
* ##### [sql()](#sql()) public
Converts the Node into a SQL string fragment.
* ##### [traverse()](#traverse()) public
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
Method Detail
-------------
### \_\_clone() public
```
__clone(): void
```
Clone this object and its subtree of expressions.
#### Returns
`void`
### \_\_construct() public
```
__construct(string $name = '')
```
#### Parameters
`string` $name optional Window name
### buildOffsetSql() protected
```
buildOffsetSql(Cake\Database\ValueBinder $binder, Cake\Database\ExpressionInterface|string|int|null $offset, string $direction): string
```
Builds frame offset sql.
#### Parameters
`Cake\Database\ValueBinder` $binder Value binder
`Cake\Database\ExpressionInterface|string|int|null` $offset Frame offset
`string` $direction Frame offset direction
#### Returns
`string`
### excludeCurrent() public
```
excludeCurrent(): $this
```
Adds current row frame exclusion.
#### Returns
`$this`
### excludeGroup() public
```
excludeGroup(): $this
```
Adds group frame exclusion.
#### Returns
`$this`
### excludeTies() public
```
excludeTies(): $this
```
Adds ties frame exclusion.
#### Returns
`$this`
### frame() public
```
frame(string $type, Cake\Database\ExpressionInterface|string|int|null $startOffset, string $startDirection, Cake\Database\ExpressionInterface|string|int|null $endOffset, string $endDirection): $this
```
Adds a frame to the window.
Use the `range()`, `rows()` or `groups()` helpers if you need simple 'BETWEEN offset PRECEDING and offset FOLLOWING' frames.
You can specify any direction for both frame start and frame end.
With both `$startOffset` and `$endOffset`:
* `0` - 'CURRENT ROW'
* `null` - 'UNBOUNDED'
#### Parameters
`string` $type `Cake\Database\ExpressionInterface|string|int|null` $startOffset `string` $startDirection `Cake\Database\ExpressionInterface|string|int|null` $endOffset `string` $endDirection #### Returns
`$this`
### groups() public
```
groups(int|null $start, int|null $end = 0): $this
```
Adds a simple groups frame to the window.
See `range()` for details.
#### Parameters
`int|null` $start `int|null` $end optional #### Returns
`$this`
### isNamedOnly() public
```
isNamedOnly(): bool
```
Return whether is only a named window expression.
These window expressions only specify a named window and do not specify their own partitions, frame or order.
#### Returns
`bool`
### name() public
```
name(string $name): $this
```
Sets the window name.
#### Parameters
`string` $name Window name
#### Returns
`$this`
### order() public
```
order(Cake\Database\ExpressionInterfaceClosure|arrayCake\Database\ExpressionInterface|string>|string $fields): $this
```
Adds one or more order clauses to the window.
#### Parameters
`Cake\Database\ExpressionInterfaceClosure|arrayCake\Database\ExpressionInterface|string>|string` $fields #### Returns
`$this`
### partition() public
```
partition(Cake\Database\ExpressionInterfaceClosure|arrayCake\Database\ExpressionInterface|string>|string $partitions): $this
```
Adds one or more partition expressions to the window.
#### Parameters
`Cake\Database\ExpressionInterfaceClosure|arrayCake\Database\ExpressionInterface|string>|string` $partitions #### Returns
`$this`
### range() public
```
range(Cake\Database\ExpressionInterface|string|int|null $start, Cake\Database\ExpressionInterface|string|int|null $end = 0): $this
```
Adds a simple range frame to the window.
`$start`:
* `0` - 'CURRENT ROW'
* `null` - 'UNBOUNDED PRECEDING'
* offset - 'offset PRECEDING'
`$end`:
* `0` - 'CURRENT ROW'
* `null` - 'UNBOUNDED FOLLOWING'
* offset - 'offset FOLLOWING'
If you need to use 'FOLLOWING' with frame start or 'PRECEDING' with frame end, use `frame()` instead.
#### Parameters
`Cake\Database\ExpressionInterface|string|int|null` $start `Cake\Database\ExpressionInterface|string|int|null` $end optional #### Returns
`$this`
### rows() public
```
rows(int|null $start, int|null $end = 0): $this
```
Adds a simple rows frame to the window.
See `range()` for details.
#### Parameters
`int|null` $start `int|null` $end optional #### Returns
`$this`
### sql() public
```
sql(Cake\Database\ValueBinder $binder): string
```
Converts the Node into a SQL string fragment.
#### Parameters
`Cake\Database\ValueBinder` $binder #### Returns
`string`
### traverse() public
```
traverse(Closure $callback): $this
```
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
#### Parameters
`Closure` $callback #### Returns
`$this`
Property Detail
---------------
### $exclusion protected
#### Type
`string|null`
### $frame protected
#### Type
`array|null`
### $name protected
#### Type
`Cake\Database\Expression\IdentifierExpression`
### $order protected
#### Type
`Cake\Database\Expression\OrderByExpression|null`
### $partitions protected
#### Type
`arrayCake\Database\ExpressionInterface>`
cakephp Class FrozenTime Class FrozenTime
=================
Extends the built-in DateTime class to provide handy methods and locale-aware formatting helpers
This object provides an immutable variant of {@link \Cake\I18n\Time}
**Namespace:** [Cake\I18n](namespace-cake.i18n)
Constants
---------
* `int` **DAYS\_PER\_WEEK**
```
7
```
* `string` **DEFAULT\_TO\_STRING\_FORMAT**
```
'Y-m-d H:i:s'
```
Default format to use for \_\_toString method when type juggling occurs.
* `int` **FRIDAY**
```
5
```
* `int` **HOURS\_PER\_DAY**
```
24
```
* `int` **MINUTES\_PER\_HOUR**
```
60
```
* `int` **MONDAY**
```
1
```
* `int` **MONTHS\_PER\_QUARTER**
```
3
```
* `int` **MONTHS\_PER\_YEAR**
```
12
```
* `int` **SATURDAY**
```
6
```
* `int` **SECONDS\_PER\_MINUTE**
```
60
```
* `int` **SUNDAY**
```
7
```
* `int` **THURSDAY**
```
4
```
* `int` **TUESDAY**
```
2
```
* `string` **UNIX\_TIMESTAMP\_FORMAT**
```
'unixTimestampFormat'
```
serialise the value as a Unix Timestamp
* `int` **WEDNESDAY**
```
3
```
* `int` **WEEKS\_PER\_YEAR**
```
52
```
* `int` **YEARS\_PER\_CENTURY**
```
100
```
* `int` **YEARS\_PER\_DECADE**
```
10
```
Property Summary
----------------
* [$\_formatters](#%24_formatters) protected static `arrayIntlDateFormatter>` In-memory cache of date formatters
* [$\_jsonEncodeFormat](#%24_jsonEncodeFormat) protected static `Closure|array<int>|string|int` The format to use when converting this object to JSON.
* [$\_lastErrors](#%24_lastErrors) protected static `array` Holds the last error generated by createFromFormat
* [$\_toStringFormat](#%24_toStringFormat) protected static `array<int>|string|int` The format to use when formatting a time using `Cake\I18n\FrozenTime::i18nFormat()` and `__toString`. This format is also used by `parseDateTime()`.
* [$age](#%24age) public @property-read `int` does a diffInYears() with default parameters
* [$day](#%24day) public @property-read `int`
* [$dayOfWeek](#%24dayOfWeek) public @property-read `int` 1 (for Monday) through 7 (for Sunday)
* [$dayOfWeekName](#%24dayOfWeekName) public @property-read `string`
* [$dayOfYear](#%24dayOfYear) public @property-read `int` 0 through 365
* [$days](#%24days) protected static `array` Names of days of the week.
* [$daysInMonth](#%24daysInMonth) public @property-read `int` number of days in the given month
* [$defaultLocale](#%24defaultLocale) protected static `string|null` The default locale to be used for displaying formatted date strings.
* [$diffFormatter](#%24diffFormatter) protected static `Cake\Chronos\DifferenceFormatterInterface` Instance of the diff formatting object.
* [$dst](#%24dst) public @property-read `bool` daylight savings time indicator, true if DST, false otherwise
* [$hour](#%24hour) public @property-read `int`
* [$lenientParsing](#%24lenientParsing) protected static `bool` Whether lenient parsing is enabled for IntlDateFormatter.
* [$local](#%24local) public @property-read `bool` checks if the timezone is local, true if local, false otherwise
* [$micro](#%24micro) public @property-read `int`
* [$microsecond](#%24microsecond) public @property-read `int`
* [$minute](#%24minute) public @property-read `int`
* [$month](#%24month) public @property-read `int`
* [$niceFormat](#%24niceFormat) public static `array<int>|string|int` The format to use when formatting a time using `Cake\I18n\FrozenTime::nice()`
* [$offset](#%24offset) public @property-read `int` the timezone offset in seconds from UTC
* [$offsetHours](#%24offsetHours) public @property-read `int` the timezone offset in hours from UTC
* [$quarter](#%24quarter) public @property-read `int` the quarter of this instance, 1 - 4
* [$relativePattern](#%24relativePattern) protected static `string` Regex for relative period.
* [$second](#%24second) public @property-read `int`
* [$testNow](#%24testNow) protected static `Cake\Chronos\ChronosInterface|null` A test ChronosInterface instance to be returned when now instances are created
* [$timestamp](#%24timestamp) public @property-read `int` seconds since the Unix Epoch
* [$timezone](#%24timezone) public @property-read `DateTimeZone` the current timezone
* [$timezoneName](#%24timezoneName) public @property-read `string`
* [$toStringFormat](#%24toStringFormat) protected static `string` Format to use for \_\_toString method when type juggling occurs.
* [$tz](#%24tz) public @property-read `DateTimeZone` alias of timezone
* [$tzName](#%24tzName) public @property-read `string`
* [$utc](#%24utc) public @property-read `bool` checks if the timezone is UTC, true if UTC, false otherwise
* [$weekEndsAt](#%24weekEndsAt) protected static `int` Last day of week
* [$weekOfMonth](#%24weekOfMonth) public @property-read `int` 1 through 5
* [$weekOfYear](#%24weekOfYear) public @property-read `int` ISO-8601 week number of year, weeks starting on Monday
* [$weekStartsAt](#%24weekStartsAt) protected static `int` First day of week
* [$weekendDays](#%24weekendDays) protected static `array` Days of weekend
* [$wordAccuracy](#%24wordAccuracy) public static `array<string>` The format to use when formatting a time using `Time::timeAgoInWords()` and the difference is less than `Time::$wordEnd`
* [$wordEnd](#%24wordEnd) public static `string` The end of relative time telling
* [$wordFormat](#%24wordFormat) public static `array<int>|string|int` The format to use when formatting a time using `Cake\I18n\FrozenTime::timeAgoInWords()` and the difference is more than `Cake\I18n\FrozenTime::$wordEnd`
* [$year](#%24year) public @property-read `int`
* [$yearIso](#%24yearIso) public @property-read `int`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Create a new immutable time instance.
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns the data that should be displayed when debugging this object
* ##### [\_\_get()](#__get()) public
Get a part of the ChronosInterface object
* ##### [\_\_isset()](#__isset()) public
Check if an attribute exists on the object
* ##### [\_\_toString()](#__toString()) public
Format the instance as a string using the set format
* ##### [\_formatObject()](#_formatObject()) protected
Returns a translated and localized date string. Implements what IntlDateFormatter::formatObject() is in PHP 5.5+
* ##### [addDay()](#addDay()) public
Add a day to the instance
* ##### [addDays()](#addDays()) public
Add days to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addHour()](#addHour()) public
Add an hour to the instance
* ##### [addHours()](#addHours()) public
Add hours to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addMinute()](#addMinute()) public
Add a minute to the instance
* ##### [addMinutes()](#addMinutes()) public
Add minutes to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addMonth()](#addMonth()) public
Add a month to the instance.
* ##### [addMonthWithOverflow()](#addMonthWithOverflow()) public
Add a month with overflow to the instance.
* ##### [addMonths()](#addMonths()) public
Add months to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addMonthsWithOverflow()](#addMonthsWithOverflow()) public
Add months with overflowing to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addSecond()](#addSecond()) public
Add a second to the instance
* ##### [addSeconds()](#addSeconds()) public
Add seconds to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addWeek()](#addWeek()) public
Add a week to the instance
* ##### [addWeekday()](#addWeekday()) public
Add a weekday to the instance
* ##### [addWeekdays()](#addWeekdays()) public
Add weekdays to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addWeeks()](#addWeeks()) public
Add weeks to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addYear()](#addYear()) public
Add a year to the instance
* ##### [addYearWithOverflow()](#addYearWithOverflow()) public
Add a year with overflow to the instance
* ##### [addYears()](#addYears()) public
Add years to the instance. Positive $value travel forward while negative $value travel into the past.
* ##### [addYearsWithOverflow()](#addYearsWithOverflow()) public
Add years with overflowing to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [average()](#average()) public
Modify the current instance to the average of a given instance (default now) and the current instance.
* ##### [between()](#between()) public
Determines if the instance is between two others
* ##### [closest()](#closest()) public
Get the closest date from the instance.
* ##### [copy()](#copy()) public
Get a copy of the instance
* ##### [create()](#create()) public static
Create a new ChronosInterface instance from a specific date and time.
* ##### [createFromArray()](#createFromArray()) public static
Creates a ChronosInterface instance from an array of date and time values.
* ##### [createFromDate()](#createFromDate()) public static
Create a ChronosInterface instance from just a date. The time portion is set to now.
* ##### [createFromFormat()](#createFromFormat()) public static
Create a ChronosInterface instance from a specific format
* ##### [createFromTime()](#createFromTime()) public static
Create a ChronosInterface instance from just a time. The date portion is set to today.
* ##### [createFromTimestamp()](#createFromTimestamp()) public static
Create a ChronosInterface instance from a timestamp
* ##### [createFromTimestampUTC()](#createFromTimestampUTC()) public static
Create a ChronosInterface instance from an UTC timestamp
* ##### [day()](#day()) public
Set the instance's day
* ##### [diffFiltered()](#diffFiltered()) public
Get the difference by the given interval using a filter callable
* ##### [diffForHumans()](#diffForHumans()) public
Get the difference in a human readable format.
* ##### [diffFormatter()](#diffFormatter()) public static
Get the difference formatter instance or overwrite the current one.
* ##### [diffInDays()](#diffInDays()) public
Get the difference in days
* ##### [diffInDaysFiltered()](#diffInDaysFiltered()) public
Get the difference in days using a filter callable
* ##### [diffInHours()](#diffInHours()) public
Get the difference in hours
* ##### [diffInHoursFiltered()](#diffInHoursFiltered()) public
Get the difference in hours using a filter callable
* ##### [diffInMinutes()](#diffInMinutes()) public
Get the difference in minutes
* ##### [diffInMonths()](#diffInMonths()) public
Get the difference in months
* ##### [diffInMonthsIgnoreTimezone()](#diffInMonthsIgnoreTimezone()) public
Get the difference in months ignoring the timezone. This means the months are calculated in the specified timezone without converting to UTC first. This prevents the day from changing which can change the month.
* ##### [diffInSeconds()](#diffInSeconds()) public
Get the difference in seconds
* ##### [diffInWeekdays()](#diffInWeekdays()) public
Get the difference in weekdays
* ##### [diffInWeekendDays()](#diffInWeekendDays()) public
Get the difference in weekend days using a filter
* ##### [diffInWeeks()](#diffInWeeks()) public
Get the difference in weeks
* ##### [diffInYears()](#diffInYears()) public
Get the difference in years
* ##### [disableLenientParsing()](#disableLenientParsing()) public static
Enables lenient parsing for locale formats.
* ##### [enableLenientParsing()](#enableLenientParsing()) public static
Enables lenient parsing for locale formats.
* ##### [endOfCentury()](#endOfCentury()) public
Resets the date to end of the century and time to 23:59:59
* ##### [endOfDay()](#endOfDay()) public
Resets the time to 23:59:59
* ##### [endOfDecade()](#endOfDecade()) public
Resets the date to end of the decade and time to 23:59:59
* ##### [endOfMonth()](#endOfMonth()) public
Resets the date to end of the month and time to 23:59:59
* ##### [endOfWeek()](#endOfWeek()) public
Resets the date to end of week (defined in $weekEndsAt) and time to 23:59:59
* ##### [endOfYear()](#endOfYear()) public
Resets the date to end of the year and time to 23:59:59
* ##### [eq()](#eq()) public
Determines if the instance is equal to another
* ##### [equals()](#equals()) public
Determines if the instance is equal to another
* ##### [farthest()](#farthest()) public
Get the farthest date from the instance.
* ##### [firstOfMonth()](#firstOfMonth()) public
Modify to the first occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the first day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [firstOfQuarter()](#firstOfQuarter()) public
Modify to the first occurrence of a given day of the week in the current quarter. If no dayOfWeek is provided, modify to the first day of the current quarter. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [firstOfYear()](#firstOfYear()) public
Modify to the first occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the first day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [fromNow()](#fromNow()) public static
Convenience method for getting the remaining time from a given time.
* ##### [getDefaultLocale()](#getDefaultLocale()) public static
Gets the default locale.
* ##### [getDiffFormatter()](#getDiffFormatter()) public static
Get the difference formatter instance.
* ##### [getLastErrors()](#getLastErrors()) public static
Returns any errors or warnings that were found during the parsing of the last object created by this class.
* ##### [getTestNow()](#getTestNow()) public static
Get the ChronosInterface instance (real or mock) to be returned when a "now" instance is created.
* ##### [getWeekEndsAt()](#getWeekEndsAt()) public static
Get the last day of week
* ##### [getWeekStartsAt()](#getWeekStartsAt()) public static
Get the first day of week
* ##### [getWeekendDays()](#getWeekendDays()) public static
Get weekend days
* ##### [greaterThan()](#greaterThan()) public
Determines if the instance is greater (after) than another
* ##### [greaterThanOrEquals()](#greaterThanOrEquals()) public
Determines if the instance is greater (after) than or equal to another
* ##### [gt()](#gt()) public
Determines if the instance is greater (after) than another
* ##### [gte()](#gte()) public
Determines if the instance is greater (after) than or equal to another
* ##### [hasRelativeKeywords()](#hasRelativeKeywords()) public static
Determine if there is a relative keyword in the time string, this is to create dates relative to now for test instances. e.g.: next tuesday
* ##### [hasTestNow()](#hasTestNow()) public static
Determine if there is a valid test instance set. A valid test instance is anything that is not null.
* ##### [hour()](#hour()) public
Set the instance's hour
* ##### [i18nFormat()](#i18nFormat()) public
Returns a formatted string for this time object using the preferred format and language for the specified locale.
* ##### [instance()](#instance()) public static
Create a ChronosInterface instance from a DateTimeInterface one
* ##### [isBirthday()](#isBirthday()) public
Check if its the birthday. Compares the date/month values of the two dates.
* ##### [isFriday()](#isFriday()) public
Checks if this day is a Friday.
* ##### [isFuture()](#isFuture()) public
Determines if the instance is in the future, ie. greater (after) than now
* ##### [isLastMonth()](#isLastMonth()) public
Determines if the instance is within the last month
* ##### [isLastWeek()](#isLastWeek()) public
Determines if the instance is within the last week
* ##### [isLastYear()](#isLastYear()) public
Determines if the instance is within the last year
* ##### [isLeapYear()](#isLeapYear()) public
Determines if the instance is a leap year
* ##### [isMonday()](#isMonday()) public
Checks if this day is a Monday.
* ##### [isMutable()](#isMutable()) public
Check if instance of ChronosInterface is mutable.
* ##### [isNextMonth()](#isNextMonth()) public
Determines if the instance is within the next month
* ##### [isNextWeek()](#isNextWeek()) public
Determines if the instance is within the next week
* ##### [isNextYear()](#isNextYear()) public
Determines if the instance is within the next year
* ##### [isPast()](#isPast()) public
Determines if the instance is in the past, ie. less (before) than now
* ##### [isSameDay()](#isSameDay()) public
Checks if the passed in date is the same day as the instance current day.
* ##### [isSaturday()](#isSaturday()) public
Checks if this day is a Saturday.
* ##### [isSunday()](#isSunday()) public
Checks if this day is a Sunday.
* ##### [isThisMonth()](#isThisMonth()) public
Returns true if this object represents a date within the current month
* ##### [isThisWeek()](#isThisWeek()) public
Returns true if this object represents a date within the current week
* ##### [isThisYear()](#isThisYear()) public
Returns true if this object represents a date within the current year
* ##### [isThursday()](#isThursday()) public
Checks if this day is a Thursday.
* ##### [isToday()](#isToday()) public
Determines if the instance is today
* ##### [isTomorrow()](#isTomorrow()) public
Determines if the instance is tomorrow
* ##### [isTuesday()](#isTuesday()) public
Checks if this day is a Tuesday.
* ##### [isWednesday()](#isWednesday()) public
Checks if this day is a Wednesday.
* ##### [isWeekday()](#isWeekday()) public
Determines if the instance is a weekday
* ##### [isWeekend()](#isWeekend()) public
Determines if the instance is a weekend day
* ##### [isWithinNext()](#isWithinNext()) public
Returns true this instance will happen within the specified interval
* ##### [isYesterday()](#isYesterday()) public
Determines if the instance is yesterday
* ##### [jsonSerialize()](#jsonSerialize()) public
Returns a string that should be serialized when converting this object to JSON
* ##### [lastOfMonth()](#lastOfMonth()) public
Modify to the last occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the last day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [lastOfQuarter()](#lastOfQuarter()) public
Modify to the last occurrence of a given day of the week in the current quarter. If no dayOfWeek is provided, modify to the last day of the current quarter. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [lastOfYear()](#lastOfYear()) public
Modify to the last occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the last day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [lenientParsingEnabled()](#lenientParsingEnabled()) public static
Gets whether locale format parsing is set to lenient.
* ##### [lessThan()](#lessThan()) public
Determines if the instance is less (before) than another
* ##### [lessThanOrEquals()](#lessThanOrEquals()) public
Determines if the instance is less (before) or equal to another
* ##### [listTimezones()](#listTimezones()) public static
Get list of timezone identifiers
* ##### [lt()](#lt()) public
Determines if the instance is less (before) than another
* ##### [lte()](#lte()) public
Determines if the instance is less (before) or equal to another
* ##### [max()](#max()) public
Get the maximum instance between a given instance (default now) and the current instance.
* ##### [maxValue()](#maxValue()) public static
Create a ChronosInterface instance for the greatest supported date.
* ##### [microsecond()](#microsecond()) public
Set the instance's microsecond
* ##### [min()](#min()) public
Get the minimum instance between a given instance (default now) and the current instance.
* ##### [minValue()](#minValue()) public static
Create a ChronosInterface instance for the lowest supported date.
* ##### [minute()](#minute()) public
Set the instance's minute
* ##### [modify()](#modify()) public @method
* ##### [month()](#month()) public
Set the instance's month
* ##### [ne()](#ne()) public
Determines if the instance is not equal to another
* ##### [next()](#next()) public
Modify to the next occurrence of a given day of the week. If no dayOfWeek is provided, modify to the next occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [nice()](#nice()) public
Returns a nicely formatted date string for this object.
* ##### [notEquals()](#notEquals()) public
Determines if the instance is not equal to another
* ##### [now()](#now()) public static
Get a ChronosInterface instance for the current date and time
* ##### [nthOfMonth()](#nthOfMonth()) public
Modify to the given occurrence of a given day of the week in the current month. If the calculated occurrence is outside the scope of the current month, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [nthOfQuarter()](#nthOfQuarter()) public
Modify to the given occurrence of a given day of the week in the current quarter. If the calculated occurrence is outside the scope of the current quarter, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [nthOfYear()](#nthOfYear()) public
Modify to the given occurrence of a given day of the week in the current year. If the calculated occurrence is outside the scope of the current year, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [parse()](#parse()) public static
Create a ChronosInterface instance from a string. This is an alias for the constructor that allows better fluent syntax as it allows you to do ChronosInterface::parse('Monday next week')->fn() rather than (new Chronos('Monday next week'))->fn()
* ##### [parseDate()](#parseDate()) public static
Returns a new Time object after parsing the provided $date string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
* ##### [parseDateTime()](#parseDateTime()) public static
Returns a new Time object after parsing the provided time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
* ##### [parseTime()](#parseTime()) public static
Returns a new Time object after parsing the provided $time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
* ##### [previous()](#previous()) public
Modify to the previous occurrence of a given day of the week. If no dayOfWeek is provided, modify to the previous occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [resetToStringFormat()](#resetToStringFormat()) public static
Resets the format used to the default when converting an instance of this type to a string
* ##### [safeCreateDateTimeZone()](#safeCreateDateTimeZone()) protected static
Creates a DateTimeZone from a string or a DateTimeZone
* ##### [second()](#second()) public
Set the instance's second
* ##### [secondsSinceMidnight()](#secondsSinceMidnight()) public
The number of seconds since midnight.
* ##### [secondsUntilEndOfDay()](#secondsUntilEndOfDay()) public
The number of seconds until 23:59:59.
* ##### [setDate()](#setDate()) public
Set the date to a different date.
* ##### [setDateTime()](#setDateTime()) public
Set the date and time all together
* ##### [setDefaultLocale()](#setDefaultLocale()) public static
Sets the default locale.
* ##### [setDiffFormatter()](#setDiffFormatter()) public static
Set the difference formatter instance.
* ##### [setJsonEncodeFormat()](#setJsonEncodeFormat()) public static
Sets the default format used when converting this object to JSON
* ##### [setTestNow()](#setTestNow()) public static
Set a ChronosInterface instance (real or mock) to be returned when a "now" instance is created. The provided instance will be returned specifically under the following conditions:
+ A call to the static now() method, ex. ChronosInterface::now()
+ When a null (or blank string) is passed to the constructor or parse(), ex. new Chronos(null)
+ When the string "now" is passed to the constructor or parse(), ex. new Chronos('now')
+ When a string containing the desired time is passed to ChronosInterface::parse()
* ##### [setTimeFromTimeString()](#setTimeFromTimeString()) public
Set the time by time string
* ##### [setTimezone()](#setTimezone()) public
Set the instance's timezone from a string or object
* ##### [setToStringFormat()](#setToStringFormat()) public static
Sets the default format used when type converting instances of this type to string
* ##### [setWeekEndsAt()](#setWeekEndsAt()) public static
Set the last day of week
* ##### [setWeekStartsAt()](#setWeekStartsAt()) public static
Set the first day of week
* ##### [setWeekendDays()](#setWeekendDays()) public static
Set weekend days
* ##### [startOfCentury()](#startOfCentury()) public
Resets the date to the first day of the century and the time to 00:00:00
* ##### [startOfDay()](#startOfDay()) public
Resets the time to 00:00:00
* ##### [startOfDecade()](#startOfDecade()) public
Resets the date to the first day of the decade and the time to 00:00:00
* ##### [startOfMonth()](#startOfMonth()) public
Resets the date to the first day of the month and the time to 00:00:00
* ##### [startOfWeek()](#startOfWeek()) public
Resets the date to the first day of week (defined in $weekStartsAt) and the time to 00:00:00
* ##### [startOfYear()](#startOfYear()) public
Resets the date to the first day of the year and the time to 00:00:00
* ##### [subDay()](#subDay()) public
Remove a day from the instance
* ##### [subDays()](#subDays()) public
Remove days from the instance
* ##### [subHour()](#subHour()) public
Remove an hour from the instance
* ##### [subHours()](#subHours()) public
Remove hours from the instance
* ##### [subMinute()](#subMinute()) public
Remove a minute from the instance
* ##### [subMinutes()](#subMinutes()) public
Remove minutes from the instance
* ##### [subMonth()](#subMonth()) public
Remove a month from the instance
* ##### [subMonthWithOverflow()](#subMonthWithOverflow()) public
Remove a month with overflow from the instance.
* ##### [subMonths()](#subMonths()) public
Remove months from the instance.
* ##### [subMonthsWithOverflow()](#subMonthsWithOverflow()) public
Remove months with overflow from the instance.
* ##### [subSecond()](#subSecond()) public
Remove a second from the instance
* ##### [subSeconds()](#subSeconds()) public
Remove seconds from the instance
* ##### [subWeek()](#subWeek()) public
Remove a week from the instance
* ##### [subWeekday()](#subWeekday()) public
Remove a weekday from the instance
* ##### [subWeekdays()](#subWeekdays()) public
Remove weekdays from the instance
* ##### [subWeeks()](#subWeeks()) public
Remove weeks to the instance
* ##### [subYear()](#subYear()) public
Remove a year from the instance.
* ##### [subYearWithOverflow()](#subYearWithOverflow()) public
Remove a year with overflow from the instance
* ##### [subYears()](#subYears()) public
Remove years from the instance.
* ##### [subYearsWithOverflow()](#subYearsWithOverflow()) public
Remove years with overflow from the instance
* ##### [timeAgoInWords()](#timeAgoInWords()) public
Returns either a relative or a formatted absolute date depending on the difference between the current time and this object.
* ##### [timestamp()](#timestamp()) public
Set the instance's timestamp
* ##### [timezone()](#timezone()) public
Alias for setTimezone()
* ##### [toAtomString()](#toAtomString()) public
Format the instance as ATOM
* ##### [toCookieString()](#toCookieString()) public
Format the instance as COOKIE
* ##### [toDateString()](#toDateString()) public
Format the instance as date
* ##### [toDateTimeString()](#toDateTimeString()) public
Format the instance as date and time
* ##### [toDayDateTimeString()](#toDayDateTimeString()) public
Format the instance with day, date and time
* ##### [toFormattedDateString()](#toFormattedDateString()) public
Format the instance as a readable date
* ##### [toIso8601String()](#toIso8601String()) public
Format the instance as ISO8601
* ##### [toMutable()](#toMutable()) public
Create a new mutable instance from current immutable instance.
* ##### [toQuarter()](#toQuarter()) public
Returns the quarter
* ##### [toRfc1036String()](#toRfc1036String()) public
Format the instance as RFC1036
* ##### [toRfc1123String()](#toRfc1123String()) public
Format the instance as RFC1123
* ##### [toRfc2822String()](#toRfc2822String()) public
Format the instance as RFC2822
* ##### [toRfc3339String()](#toRfc3339String()) public
Format the instance as RFC3339
* ##### [toRfc822String()](#toRfc822String()) public
Format the instance as RFC822
* ##### [toRfc850String()](#toRfc850String()) public
Format the instance as RFC850
* ##### [toRssString()](#toRssString()) public
Format the instance as RSS
* ##### [toTimeString()](#toTimeString()) public
Format the instance as time
* ##### [toUnixString()](#toUnixString()) public
Returns a UNIX timestamp.
* ##### [toW3cString()](#toW3cString()) public
Format the instance as W3C
* ##### [toWeek()](#toWeek()) public
* ##### [today()](#today()) public static
Create a ChronosInterface instance for today
* ##### [tomorrow()](#tomorrow()) public static
Create a ChronosInterface instance for tomorrow
* ##### [tz()](#tz()) public
Alias for setTimezone()
* ##### [wasWithinLast()](#wasWithinLast()) public
Returns true this instance happened within the specified interval
* ##### [year()](#year()) public
Set the instance's year
* ##### [yesterday()](#yesterday()) public static
Create a ChronosInterface instance for yesterday
Method Detail
-------------
### \_\_construct() public
```
__construct(DateTimeInterface|string|int|null $time = null, DateTimeZone|string|null $tz = null)
```
Create a new immutable time instance.
Please see the testing aids section (specifically static::setTestNow()) for more on the possibility of this constructor returning a test instance.
#### Parameters
`DateTimeInterface|string|int|null` $time optional Fixed or relative time
`DateTimeZone|string|null` $tz optional The timezone for the instance
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns the data that should be displayed when debugging this object
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): string|int|boolDateTimeZone
```
Get a part of the ChronosInterface object
#### Parameters
`string` $name The property name to read.
#### Returns
`string|int|boolDateTimeZone`
#### Throws
`InvalidArgumentException`
### \_\_isset() public
```
__isset(string $name): bool
```
Check if an attribute exists on the object
#### Parameters
`string` $name The property name to check.
#### Returns
`bool`
### \_\_toString() public
```
__toString(): string
```
Format the instance as a string using the set format
#### Returns
`string`
### \_formatObject() protected
```
_formatObject(DateTimeDateTimeImmutable $date, array<int>|string|int $format, string|null $locale): string
```
Returns a translated and localized date string. Implements what IntlDateFormatter::formatObject() is in PHP 5.5+
#### Parameters
`DateTimeDateTimeImmutable` $date Date.
`array<int>|string|int` $format Format.
`string|null` $locale The locale name in which the date should be displayed.
#### Returns
`string`
### addDay() public
```
addDay(int $value = 1): static
```
Add a day to the instance
#### Parameters
`int` $value optional The number of days to add.
#### Returns
`static`
### addDays() public
```
addDays(int $value): static
```
Add days to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of days to add.
#### Returns
`static`
### addHour() public
```
addHour(int $value = 1): static
```
Add an hour to the instance
#### Parameters
`int` $value optional The number of hours to add.
#### Returns
`static`
### addHours() public
```
addHours(int $value): static
```
Add hours to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of hours to add.
#### Returns
`static`
### addMinute() public
```
addMinute(int $value = 1): static
```
Add a minute to the instance
#### Parameters
`int` $value optional The number of minutes to add.
#### Returns
`static`
### addMinutes() public
```
addMinutes(int $value): static
```
Add minutes to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of minutes to add.
#### Returns
`static`
### addMonth() public
```
addMonth(int $value = 1): static
```
Add a month to the instance.
Has the same behavior as `addMonths()`.
#### Parameters
`int` $value optional The number of months to add.
#### Returns
`static`
### addMonthWithOverflow() public
```
addMonthWithOverflow(int $value = 1): static
```
Add a month with overflow to the instance.
Has the same behavior as `addMonthsWithOverflow()`.
#### Parameters
`int` $value optional The number of months to add.
#### Returns
`static`
### addMonths() public
```
addMonths(int $value): static
```
Add months to the instance. Positive $value travels forward while negative $value travels into the past.
If the new date does not exist, the last day of the month is used instead instead of overflowing into the next month.
### Example:
```
(new Chronos('2015-01-03'))->addMonths(1); // Results in 2015-02-03
(new Chronos('2015-01-31'))->addMonths(1); // Results in 2015-02-28
```
#### Parameters
`int` $value The number of months to add.
#### Returns
`static`
### addMonthsWithOverflow() public
```
addMonthsWithOverflow(int $value): static
```
Add months with overflowing to the instance. Positive $value travels forward while negative $value travels into the past.
If the new date does not exist, the days overflow into the next month.
### Example:
```
(new Chronos('2012-01-30'))->addMonthsWithOverflow(1); // Results in 2013-03-01
```
#### Parameters
`int` $value The number of months to add.
#### Returns
`static`
### addSecond() public
```
addSecond(int $value = 1): static
```
Add a second to the instance
#### Parameters
`int` $value optional The number of seconds to add.
#### Returns
`static`
### addSeconds() public
```
addSeconds(int $value): static
```
Add seconds to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of seconds to add.
#### Returns
`static`
### addWeek() public
```
addWeek(int $value = 1): static
```
Add a week to the instance
#### Parameters
`int` $value optional The number of weeks to add.
#### Returns
`static`
### addWeekday() public
```
addWeekday(int $value = 1): static
```
Add a weekday to the instance
#### Parameters
`int` $value optional The number of weekdays to add.
#### Returns
`static`
### addWeekdays() public
```
addWeekdays(int $value): static
```
Add weekdays to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of weekdays to add.
#### Returns
`static`
### addWeeks() public
```
addWeeks(int $value): static
```
Add weeks to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of weeks to add.
#### Returns
`static`
### addYear() public
```
addYear(int $value = 1): static
```
Add a year to the instance
Has the same behavior as `addYears()`.
#### Parameters
`int` $value optional The number of years to add.
#### Returns
`static`
### addYearWithOverflow() public
```
addYearWithOverflow(int $value = 1): static
```
Add a year with overflow to the instance
Has the same behavior as `addYearsWithOverflow()`.
#### Parameters
`int` $value optional The number of years to add.
#### Returns
`static`
### addYears() public
```
addYears(int $value): static
```
Add years to the instance. Positive $value travel forward while negative $value travel into the past.
If the new date does not exist, the last day of the month is used instead instead of overflowing into the next month.
### Example:
```
(new Chronos('2015-01-03'))->addYears(1); // Results in 2016-01-03
(new Chronos('2012-02-29'))->addYears(1); // Results in 2013-02-28
```
#### Parameters
`int` $value The number of years to add.
#### Returns
`static`
### addYearsWithOverflow() public
```
addYearsWithOverflow(int $value): static
```
Add years with overflowing to the instance. Positive $value travels forward while negative $value travels into the past.
If the new date does not exist, the days overflow into the next month.
### Example:
```
(new Chronos('2012-02-29'))->addYearsWithOverflow(1); // Results in 2013-03-01
```
#### Parameters
`int` $value The number of years to add.
#### Returns
`static`
### average() public
```
average(Cake\Chronos\ChronosInterface $dt = null): static
```
Modify the current instance to the average of a given instance (default now) and the current instance.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt optional The instance to compare with.
#### Returns
`static`
### between() public
```
between(Cake\Chronos\ChronosInterface $dt1, Cake\Chronos\ChronosInterface $dt2, bool $equal = true): bool
```
Determines if the instance is between two others
#### Parameters
`Cake\Chronos\ChronosInterface` $dt1 The instance to compare with.
`Cake\Chronos\ChronosInterface` $dt2 The instance to compare with.
`bool` $equal optional Indicates if a > and < comparison should be used or <= or >=
#### Returns
`bool`
### closest() public
```
closest(Cake\Chronos\ChronosInterface $dt1, Cake\Chronos\ChronosInterface $dt2): static
```
Get the closest date from the instance.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt1 The instance to compare with.
`Cake\Chronos\ChronosInterface` $dt2 The instance to compare with.
#### Returns
`static`
### copy() public
```
copy(): static
```
Get a copy of the instance
#### Returns
`static`
### create() public static
```
create(int|null $year = null, int|null $month = null, int|null $day = null, int|null $hour = null, int|null $minute = null, int|null $second = null, int|null $microsecond = null, DateTimeZone|string|null $tz = null): static
```
Create a new ChronosInterface instance from a specific date and time.
If any of $year, $month or $day are set to null their now() values will be used.
If $hour is null it will be set to its now() value and the default values for $minute, $second and $microsecond will be their now() values. If $hour is not null then the default values for $minute, $second and $microsecond will be 0.
#### Parameters
`int|null` $year optional The year to create an instance with.
`int|null` $month optional The month to create an instance with.
`int|null` $day optional The day to create an instance with.
`int|null` $hour optional The hour to create an instance with.
`int|null` $minute optional The minute to create an instance with.
`int|null` $second optional The second to create an instance with.
`int|null` $microsecond optional The microsecond to create an instance with.
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
### createFromArray() public static
```
createFromArray((int|string)[] $values): static
```
Creates a ChronosInterface instance from an array of date and time values.
The 'year', 'month' and 'day' values must all be set for a date. The time values all default to 0.
The 'timezone' value can be any format supported by `\DateTimeZone`.
Allowed values:
* year
* month
* day
* hour
* minute
* second
* microsecond
* meridian ('am' or 'pm')
* timezone
#### Parameters
`(int|string)[]` $values Array of date and time values.
#### Returns
`static`
### createFromDate() public static
```
createFromDate(int|null $year = null, int|null $month = null, int|null $day = null, DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance from just a date. The time portion is set to now.
#### Parameters
`int|null` $year optional The year to create an instance with.
`int|null` $month optional The month to create an instance with.
`int|null` $day optional The day to create an instance with.
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
### createFromFormat() public static
```
createFromFormat(string $format, string $time, DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance from a specific format
#### Parameters
`string` $format The date() compatible format string.
`string` $time The formatted date string to interpret.
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
#### Throws
`InvalidArgumentException`
### createFromTime() public static
```
createFromTime(int|null $hour = null, int|null $minute = null, int|null $second = null, int|null $microsecond = null, DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance from just a time. The date portion is set to today.
#### Parameters
`int|null` $hour optional The hour to create an instance with.
`int|null` $minute optional The minute to create an instance with.
`int|null` $second optional The second to create an instance with.
`int|null` $microsecond optional The microsecond to create an instance with.
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
### createFromTimestamp() public static
```
createFromTimestamp(int $timestamp, DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance from a timestamp
#### Parameters
`int` $timestamp The timestamp to create an instance from.
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
### createFromTimestampUTC() public static
```
createFromTimestampUTC(int $timestamp): static
```
Create a ChronosInterface instance from an UTC timestamp
#### Parameters
`int` $timestamp The UTC timestamp to create an instance from.
#### Returns
`static`
### day() public
```
day(int $value): static
```
Set the instance's day
#### Parameters
`int` $value The day value.
#### Returns
`static`
### diffFiltered() public
```
diffFiltered(Cake\Chronos\ChronosInterval $ci, callable $callback, Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference by the given interval using a filter callable
#### Parameters
`Cake\Chronos\ChronosInterval` $ci An interval to traverse by
`callable` $callback The callback to use for filtering.
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffForHumans() public
```
diffForHumans(Cake\Chronos\ChronosInterface|null $other = null, bool $absolute = false): string
```
Get the difference in a human readable format.
When comparing a value in the past to default now: 1 hour ago 5 months ago
When comparing a value in the future to default now: 1 hour from now 5 months from now
When comparing a value in the past to another value: 1 hour before 5 months before
When comparing a value in the future to another value: 1 hour after 5 months after
#### Parameters
`Cake\Chronos\ChronosInterface|null` $other optional The datetime to compare with.
`bool` $absolute optional removes time difference modifiers ago, after, etc
#### Returns
`string`
### diffFormatter() public static
```
diffFormatter(Cake\Chronos\DifferenceFormatterInterface|null $formatter = null): Cake\Chronos\DifferenceFormatterInterface
```
Get the difference formatter instance or overwrite the current one.
#### Parameters
`Cake\Chronos\DifferenceFormatterInterface|null` $formatter optional The formatter instance when setting.
#### Returns
`Cake\Chronos\DifferenceFormatterInterface`
### diffInDays() public
```
diffInDays(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in days
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInDaysFiltered() public
```
diffInDaysFiltered(callable $callback, Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in days using a filter callable
#### Parameters
`callable` $callback The callback to use for filtering.
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInHours() public
```
diffInHours(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in hours
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInHoursFiltered() public
```
diffInHoursFiltered(callable $callback, Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in hours using a filter callable
#### Parameters
`callable` $callback The callback to use for filtering.
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInMinutes() public
```
diffInMinutes(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in minutes
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInMonths() public
```
diffInMonths(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in months
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInMonthsIgnoreTimezone() public
```
diffInMonthsIgnoreTimezone(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in months ignoring the timezone. This means the months are calculated in the specified timezone without converting to UTC first. This prevents the day from changing which can change the month.
For example, if comparing `2019-06-01 Asia/Tokyo` and `2019-10-01 Asia/Tokyo`, the result would be 4 months instead of 3 when using normal `DateTime::diff()`.
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInSeconds() public
```
diffInSeconds(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in seconds
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInWeekdays() public
```
diffInWeekdays(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in weekdays
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInWeekendDays() public
```
diffInWeekendDays(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in weekend days using a filter
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInWeeks() public
```
diffInWeeks(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in weeks
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInYears() public
```
diffInYears(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in years
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### disableLenientParsing() public static
```
disableLenientParsing(): void
```
Enables lenient parsing for locale formats.
#### Returns
`void`
### enableLenientParsing() public static
```
enableLenientParsing(): void
```
Enables lenient parsing for locale formats.
#### Returns
`void`
### endOfCentury() public
```
endOfCentury(): static
```
Resets the date to end of the century and time to 23:59:59
#### Returns
`static`
### endOfDay() public
```
endOfDay(): static
```
Resets the time to 23:59:59
#### Returns
`static`
### endOfDecade() public
```
endOfDecade(): static
```
Resets the date to end of the decade and time to 23:59:59
#### Returns
`static`
### endOfMonth() public
```
endOfMonth(): static
```
Resets the date to end of the month and time to 23:59:59
#### Returns
`static`
### endOfWeek() public
```
endOfWeek(): static
```
Resets the date to end of week (defined in $weekEndsAt) and time to 23:59:59
#### Returns
`static`
### endOfYear() public
```
endOfYear(): static
```
Resets the date to end of the year and time to 23:59:59
#### Returns
`static`
### eq() public
```
eq(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
equals ### equals() public
```
equals(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### farthest() public
```
farthest(Cake\Chronos\ChronosInterface $dt1, Cake\Chronos\ChronosInterface $dt2): static
```
Get the farthest date from the instance.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt1 The instance to compare with.
`Cake\Chronos\ChronosInterface` $dt2 The instance to compare with.
#### Returns
`static`
### firstOfMonth() public
```
firstOfMonth(int|null $dayOfWeek = null): mixed
```
Modify to the first occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the first day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### firstOfQuarter() public
```
firstOfQuarter(int|null $dayOfWeek = null): mixed
```
Modify to the first occurrence of a given day of the week in the current quarter. If no dayOfWeek is provided, modify to the first day of the current quarter. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### firstOfYear() public
```
firstOfYear(int|null $dayOfWeek = null): mixed
```
Modify to the first occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the first day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### fromNow() public static
```
fromNow(DateTimeDateTimeImmutable $datetime): DateInterval|bool
```
Convenience method for getting the remaining time from a given time.
#### Parameters
`DateTimeDateTimeImmutable` $datetime The date to get the remaining time from.
#### Returns
`DateInterval|bool`
### getDefaultLocale() public static
```
getDefaultLocale(): string|null
```
Gets the default locale.
#### Returns
`string|null`
### getDiffFormatter() public static
```
getDiffFormatter(): Cake\Chronos\DifferenceFormatterInterface
```
Get the difference formatter instance.
#### Returns
`Cake\Chronos\DifferenceFormatterInterface`
### getLastErrors() public static
```
getLastErrors(): array
```
Returns any errors or warnings that were found during the parsing of the last object created by this class.
#### Returns
`array`
### getTestNow() public static
```
getTestNow(): Cake\Chronos\ChronosInterface|null
```
Get the ChronosInterface instance (real or mock) to be returned when a "now" instance is created.
#### Returns
`Cake\Chronos\ChronosInterface|null`
### getWeekEndsAt() public static
```
getWeekEndsAt(): int
```
Get the last day of week
#### Returns
`int`
### getWeekStartsAt() public static
```
getWeekStartsAt(): int
```
Get the first day of week
#### Returns
`int`
### getWeekendDays() public static
```
getWeekendDays(): array
```
Get weekend days
#### Returns
`array`
### greaterThan() public
```
greaterThan(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is greater (after) than another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### greaterThanOrEquals() public
```
greaterThanOrEquals(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is greater (after) than or equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### gt() public
```
gt(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is greater (after) than another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
greaterThan ### gte() public
```
gte(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is greater (after) than or equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
greaterThanOrEquals ### hasRelativeKeywords() public static
```
hasRelativeKeywords(string|null $time): bool
```
Determine if there is a relative keyword in the time string, this is to create dates relative to now for test instances. e.g.: next tuesday
#### Parameters
`string|null` $time The time string to check.
#### Returns
`bool`
### hasTestNow() public static
```
hasTestNow(): bool
```
Determine if there is a valid test instance set. A valid test instance is anything that is not null.
#### Returns
`bool`
### hour() public
```
hour(int $value): static
```
Set the instance's hour
#### Parameters
`int` $value The hour value.
#### Returns
`static`
### i18nFormat() public
```
i18nFormat(string|int|null $format = null, DateTimeZone|string|null $timezone = null, string|null $locale = null): string|int
```
Returns a formatted string for this time object using the preferred format and language for the specified locale.
It is possible to specify the desired format for the string to be displayed. You can either pass `IntlDateFormatter` constants as the first argument of this function, or pass a full ICU date formatting string as specified in the following resource: <https://unicode-org.github.io/icu/userguide/format_parse/datetime/#datetime-format-syntax>.
Additional to `IntlDateFormatter` constants and date formatting string you can use Time::UNIX\_TIMESTAMP\_FORMAT to get a unix timestamp
### Examples
```
$time = new Time('2014-04-20 22:10');
$time->i18nFormat(); // outputs '4/20/14, 10:10 PM' for the en-US locale
$time->i18nFormat(\IntlDateFormatter::FULL); // Use the full date and time format
$time->i18nFormat([\IntlDateFormatter::FULL, \IntlDateFormatter::SHORT]); // Use full date but short time format
$time->i18nFormat('yyyy-MM-dd HH:mm:ss'); // outputs '2014-04-20 22:10'
$time->i18nFormat(Time::UNIX_TIMESTAMP_FORMAT); // outputs '1398031800'
```
You can control the default format used through `Time::setToStringFormat()`.
You can read about the available IntlDateFormatter constants at <https://secure.php.net/manual/en/class.intldateformatter.php>
If you need to display the date in a different timezone than the one being used for this Time object without altering its internal state, you can pass a timezone string or object as the second parameter.
Finally, should you need to use a different locale for displaying this time object, pass a locale string as the third parameter to this function.
### Examples
```
$time = new Time('2014-04-20 22:10');
$time->i18nFormat(null, null, 'de-DE');
$time->i18nFormat(\IntlDateFormatter::FULL, 'Europe/Berlin', 'de-DE');
```
You can control the default locale used through `Time::setDefaultLocale()`. If empty, the default will be taken from the `intl.default_locale` ini config.
#### Parameters
`string|int|null` $format optional Format string.
`DateTimeZone|string|null` $timezone optional Timezone string or DateTimeZone object in which the date will be displayed. The timezone stored for this object will not be changed.
`string|null` $locale optional The locale name in which the date should be displayed (e.g. pt-BR)
#### Returns
`string|int`
### instance() public static
```
instance(DateTimeInterface $dt): static
```
Create a ChronosInterface instance from a DateTimeInterface one
#### Parameters
`DateTimeInterface` $dt The datetime instance to convert.
#### Returns
`static`
### isBirthday() public
```
isBirthday(Cake\Chronos\ChronosInterface $dt): bool
```
Check if its the birthday. Compares the date/month values of the two dates.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### isFriday() public
```
isFriday(): bool
```
Checks if this day is a Friday.
#### Returns
`bool`
### isFuture() public
```
isFuture(): bool
```
Determines if the instance is in the future, ie. greater (after) than now
#### Returns
`bool`
### isLastMonth() public
```
isLastMonth(): bool
```
Determines if the instance is within the last month
#### Returns
`bool`
### isLastWeek() public
```
isLastWeek(): bool
```
Determines if the instance is within the last week
#### Returns
`bool`
### isLastYear() public
```
isLastYear(): bool
```
Determines if the instance is within the last year
#### Returns
`bool`
### isLeapYear() public
```
isLeapYear(): bool
```
Determines if the instance is a leap year
#### Returns
`bool`
### isMonday() public
```
isMonday(): bool
```
Checks if this day is a Monday.
#### Returns
`bool`
### isMutable() public
```
isMutable(): bool
```
Check if instance of ChronosInterface is mutable.
#### Returns
`bool`
### isNextMonth() public
```
isNextMonth(): bool
```
Determines if the instance is within the next month
#### Returns
`bool`
### isNextWeek() public
```
isNextWeek(): bool
```
Determines if the instance is within the next week
#### Returns
`bool`
### isNextYear() public
```
isNextYear(): bool
```
Determines if the instance is within the next year
#### Returns
`bool`
### isPast() public
```
isPast(): bool
```
Determines if the instance is in the past, ie. less (before) than now
#### Returns
`bool`
### isSameDay() public
```
isSameDay(Cake\Chronos\ChronosInterface $dt): bool
```
Checks if the passed in date is the same day as the instance current day.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to check against.
#### Returns
`bool`
### isSaturday() public
```
isSaturday(): bool
```
Checks if this day is a Saturday.
#### Returns
`bool`
### isSunday() public
```
isSunday(): bool
```
Checks if this day is a Sunday.
#### Returns
`bool`
### isThisMonth() public
```
isThisMonth(): bool
```
Returns true if this object represents a date within the current month
#### Returns
`bool`
### isThisWeek() public
```
isThisWeek(): bool
```
Returns true if this object represents a date within the current week
#### Returns
`bool`
### isThisYear() public
```
isThisYear(): bool
```
Returns true if this object represents a date within the current year
#### Returns
`bool`
### isThursday() public
```
isThursday(): bool
```
Checks if this day is a Thursday.
#### Returns
`bool`
### isToday() public
```
isToday(): bool
```
Determines if the instance is today
#### Returns
`bool`
### isTomorrow() public
```
isTomorrow(): bool
```
Determines if the instance is tomorrow
#### Returns
`bool`
### isTuesday() public
```
isTuesday(): bool
```
Checks if this day is a Tuesday.
#### Returns
`bool`
### isWednesday() public
```
isWednesday(): bool
```
Checks if this day is a Wednesday.
#### Returns
`bool`
### isWeekday() public
```
isWeekday(): bool
```
Determines if the instance is a weekday
#### Returns
`bool`
### isWeekend() public
```
isWeekend(): bool
```
Determines if the instance is a weekend day
#### Returns
`bool`
### isWithinNext() public
```
isWithinNext(string|int $timeInterval): bool
```
Returns true this instance will happen within the specified interval
#### Parameters
`string|int` $timeInterval the numeric value with space then time type. Example of valid types: 6 hours, 2 days, 1 minute.
#### Returns
`bool`
### isYesterday() public
```
isYesterday(): bool
```
Determines if the instance is yesterday
#### Returns
`bool`
### jsonSerialize() public
```
jsonSerialize(): string|int
```
Returns a string that should be serialized when converting this object to JSON
#### Returns
`string|int`
### lastOfMonth() public
```
lastOfMonth(int|null $dayOfWeek = null): mixed
```
Modify to the last occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the last day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### lastOfQuarter() public
```
lastOfQuarter(int|null $dayOfWeek = null): mixed
```
Modify to the last occurrence of a given day of the week in the current quarter. If no dayOfWeek is provided, modify to the last day of the current quarter. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### lastOfYear() public
```
lastOfYear(int|null $dayOfWeek = null): mixed
```
Modify to the last occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the last day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### lenientParsingEnabled() public static
```
lenientParsingEnabled(): bool
```
Gets whether locale format parsing is set to lenient.
#### Returns
`bool`
### lessThan() public
```
lessThan(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is less (before) than another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### lessThanOrEquals() public
```
lessThanOrEquals(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is less (before) or equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### listTimezones() public static
```
listTimezones(string|int|null $filter = null, string|null $country = null, array<string, mixed>|bool $options = []): array
```
Get list of timezone identifiers
#### Parameters
`string|int|null` $filter optional A regex to filter identifier Or one of DateTimeZone class constants
`string|null` $country optional A two-letter ISO 3166-1 compatible country code. This option is only used when $filter is set to DateTimeZone::PER\_COUNTRY
`array<string, mixed>|bool` $options optional If true (default value) groups the identifiers list by primary region. Otherwise, an array containing `group`, `abbr`, `before`, and `after` keys. Setting `group` and `abbr` to true will group results and append timezone abbreviation in the display value. Set `before` and `after` to customize the abbreviation wrapper.
#### Returns
`array`
### lt() public
```
lt(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is less (before) than another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
lessThan ### lte() public
```
lte(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is less (before) or equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
lessThanOrEquals ### max() public
```
max(Cake\Chronos\ChronosInterface|null $dt = null): static
```
Get the maximum instance between a given instance (default now) and the current instance.
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to compare with.
#### Returns
`static`
### maxValue() public static
```
maxValue(): Cake\Chronos\ChronosInterface
```
Create a ChronosInterface instance for the greatest supported date.
#### Returns
`Cake\Chronos\ChronosInterface`
### microsecond() public
```
microsecond(int $value): static
```
Set the instance's microsecond
#### Parameters
`int` $value The microsecond value.
#### Returns
`static`
### min() public
```
min(Cake\Chronos\ChronosInterface|null $dt = null): static
```
Get the minimum instance between a given instance (default now) and the current instance.
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to compare with.
#### Returns
`static`
### minValue() public static
```
minValue(): Cake\Chronos\ChronosInterface
```
Create a ChronosInterface instance for the lowest supported date.
#### Returns
`Cake\Chronos\ChronosInterface`
### minute() public
```
minute(int $value): static
```
Set the instance's minute
#### Parameters
`int` $value The minute value.
#### Returns
`static`
### modify() public @method
```
modify(string $relative): Cake\Chronos\ChronosInterface
```
#### Parameters
`string` $relative #### Returns
`Cake\Chronos\ChronosInterface`
### month() public
```
month(int $value): static
```
Set the instance's month
#### Parameters
`int` $value The month value.
#### Returns
`static`
### ne() public
```
ne(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is not equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
notEquals ### next() public
```
next(int|null $dayOfWeek = null): mixed
```
Modify to the next occurrence of a given day of the week. If no dayOfWeek is provided, modify to the next occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### nice() public
```
nice(DateTimeZone|string|null $timezone = null, string|null $locale = null): string
```
Returns a nicely formatted date string for this object.
The format to be used is stored in the static property `Time::niceFormat`.
#### Parameters
`DateTimeZone|string|null` $timezone optional Timezone string or DateTimeZone object in which the date will be displayed. The timezone stored for this object will not be changed.
`string|null` $locale optional The locale name in which the date should be displayed (e.g. pt-BR)
#### Returns
`string`
### notEquals() public
```
notEquals(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is not equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### now() public static
```
now(DateTimeZone|string|null $tz): static
```
Get a ChronosInterface instance for the current date and time
#### Parameters
`DateTimeZone|string|null` $tz The DateTimeZone object or timezone name.
#### Returns
`static`
### nthOfMonth() public
```
nthOfMonth(int $nth, int $dayOfWeek): mixed
```
Modify to the given occurrence of a given day of the week in the current month. If the calculated occurrence is outside the scope of the current month, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int` $nth The offset to use.
`int` $dayOfWeek The day of the week to move to.
#### Returns
`mixed`
### nthOfQuarter() public
```
nthOfQuarter(int $nth, int $dayOfWeek): mixed
```
Modify to the given occurrence of a given day of the week in the current quarter. If the calculated occurrence is outside the scope of the current quarter, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int` $nth The offset to use.
`int` $dayOfWeek The day of the week to move to.
#### Returns
`mixed`
### nthOfYear() public
```
nthOfYear(int $nth, int $dayOfWeek): mixed
```
Modify to the given occurrence of a given day of the week in the current year. If the calculated occurrence is outside the scope of the current year, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int` $nth The offset to use.
`int` $dayOfWeek The day of the week to move to.
#### Returns
`mixed`
### parse() public static
```
parse(DateTimeInterface|string|int $time = 'now', DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance from a string. This is an alias for the constructor that allows better fluent syntax as it allows you to do ChronosInterface::parse('Monday next week')->fn() rather than (new Chronos('Monday next week'))->fn()
#### Parameters
`DateTimeInterface|string|int` $time optional The strtotime compatible string to parse
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name.
#### Returns
`static`
### parseDate() public static
```
parseDate(string $date, array|string|int|null $format = null): static|null
```
Returns a new Time object after parsing the provided $date string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
When no $format is provided, the `wordFormat` format will be used.
If it was impossible to parse the provided time, null will be returned.
Example:
```
$time = Time::parseDate('10/13/2013');
$time = Time::parseDate('13 Oct, 2013', 'dd MMM, y');
$time = Time::parseDate('13 Oct, 2013', IntlDateFormatter::SHORT);
```
#### Parameters
`string` $date The date string to parse.
`array|string|int|null` $format optional Any format accepted by IntlDateFormatter.
#### Returns
`static|null`
### parseDateTime() public static
```
parseDateTime(string $time, array<int>|string|null $format = null, DateTimeZone|string|null $tz = null): static|null
```
Returns a new Time object after parsing the provided time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
When no $format is provided, the `toString` format will be used.
Unlike DateTime, the time zone of the returned instance is always converted to `$tz` (default time zone if null) even if the `$time` string specified a time zone. This is a limitation of IntlDateFormatter.
If it was impossible to parse the provided time, null will be returned.
Example:
```
$time = Time::parseDateTime('10/13/2013 12:54am');
$time = Time::parseDateTime('13 Oct, 2013 13:54', 'dd MMM, y H:mm');
$time = Time::parseDateTime('10/10/2015', [IntlDateFormatter::SHORT, IntlDateFormatter::NONE]);
```
#### Parameters
`string` $time The time string to parse.
`array<int>|string|null` $format optional Any format accepted by IntlDateFormatter.
`DateTimeZone|string|null` $tz optional The timezone for the instance
#### Returns
`static|null`
### parseTime() public static
```
parseTime(string $time, string|int|null $format = null): static|null
```
Returns a new Time object after parsing the provided $time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
When no $format is provided, the IntlDateFormatter::SHORT format will be used.
If it was impossible to parse the provided time, null will be returned.
Example:
```
$time = Time::parseTime('11:23pm');
```
#### Parameters
`string` $time The time string to parse.
`string|int|null` $format optional Any format accepted by IntlDateFormatter.
#### Returns
`static|null`
### previous() public
```
previous(int|null $dayOfWeek = null): mixed
```
Modify to the previous occurrence of a given day of the week. If no dayOfWeek is provided, modify to the previous occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### resetToStringFormat() public static
```
resetToStringFormat(): void
```
Resets the format used to the default when converting an instance of this type to a string
#### Returns
`void`
### safeCreateDateTimeZone() protected static
```
safeCreateDateTimeZone(DateTimeZone|string|null $object): DateTimeZone
```
Creates a DateTimeZone from a string or a DateTimeZone
#### Parameters
`DateTimeZone|string|null` $object The value to convert.
#### Returns
`DateTimeZone`
#### Throws
`InvalidArgumentException`
### second() public
```
second(int $value): static
```
Set the instance's second
#### Parameters
`int` $value The seconds value.
#### Returns
`static`
### secondsSinceMidnight() public
```
secondsSinceMidnight(): int
```
The number of seconds since midnight.
#### Returns
`int`
### secondsUntilEndOfDay() public
```
secondsUntilEndOfDay(): int
```
The number of seconds until 23:59:59.
#### Returns
`int`
### setDate() public
```
setDate(int $year, int $month, int $day): static
```
Set the date to a different date.
Workaround for a PHP bug related to the first day of a month
#### Parameters
`int` $year The year to set.
`int` $month The month to set.
`int` $day The day to set.
#### Returns
`static`
### setDateTime() public
```
setDateTime(int $year, int $month, int $day, int $hour, int $minute, int $second = 0): static
```
Set the date and time all together
#### Parameters
`int` $year The year to set.
`int` $month The month to set.
`int` $day The day to set.
`int` $hour The hour to set.
`int` $minute The minute to set.
`int` $second optional The second to set.
#### Returns
`static`
### setDefaultLocale() public static
```
setDefaultLocale(string|null $locale = null): void
```
Sets the default locale.
Set to null to use IntlDateFormatter default.
#### Parameters
`string|null` $locale optional The default locale string to be used.
#### Returns
`void`
### setDiffFormatter() public static
```
setDiffFormatter(Cake\Chronos\DifferenceFormatterInterface $formatter): void
```
Set the difference formatter instance.
#### Parameters
`Cake\Chronos\DifferenceFormatterInterface` $formatter The formatter instance when setting.
#### Returns
`void`
### setJsonEncodeFormat() public static
```
setJsonEncodeFormat(Closure|array|string|int $format): void
```
Sets the default format used when converting this object to JSON
The format should be either the formatting constants from IntlDateFormatter as described in (<https://secure.php.net/manual/en/class.intldateformatter.php>) or a pattern as specified in (<https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details>)
It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.
Alternatively, the format can provide a callback. In this case, the callback can receive this datetime object and return a formatted string.
#### Parameters
`Closure|array|string|int` $format #### Returns
`void`
### setTestNow() public static
```
setTestNow(Cake\Chronos\ChronosInterface|string|null $testNow = null): void
```
Set a ChronosInterface instance (real or mock) to be returned when a "now" instance is created. The provided instance will be returned specifically under the following conditions:
* A call to the static now() method, ex. ChronosInterface::now()
* When a null (or blank string) is passed to the constructor or parse(), ex. new Chronos(null)
* When the string "now" is passed to the constructor or parse(), ex. new Chronos('now')
* When a string containing the desired time is passed to ChronosInterface::parse()
Note the timezone parameter was left out of the examples above and has no affect as the mock value will be returned regardless of its value.
To clear the test instance call this method using the default parameter of null.
#### Parameters
`Cake\Chronos\ChronosInterface|string|null` $testNow optional The instance to use for all future instances.
#### Returns
`void`
### setTimeFromTimeString() public
```
setTimeFromTimeString(string $time): static
```
Set the time by time string
#### Parameters
`string` $time Time as string.
#### Returns
`static`
### setTimezone() public
```
setTimezone(DateTimeZone|string $value): static
```
Set the instance's timezone from a string or object
#### Parameters
`DateTimeZone|string` $value The DateTimeZone object or timezone name to use.
#### Returns
`static`
### setToStringFormat() public static
```
setToStringFormat(string $format): void
```
Sets the default format used when type converting instances of this type to string
The format should be either the formatting constants from IntlDateFormatter as described in (<https://secure.php.net/manual/en/class.intldateformatter.php>) or a pattern as specified in (<https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details>)
It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.
#### Parameters
`string` $format Format.
#### Returns
`void`
### setWeekEndsAt() public static
```
setWeekEndsAt(int $day): void
```
Set the last day of week
#### Parameters
`int` $day The day the week ends with.
#### Returns
`void`
### setWeekStartsAt() public static
```
setWeekStartsAt(int $day): void
```
Set the first day of week
#### Parameters
`int` $day The day the week starts with.
#### Returns
`void`
### setWeekendDays() public static
```
setWeekendDays(array $days): void
```
Set weekend days
#### Parameters
`array` $days Which days are 'weekends'.
#### Returns
`void`
### startOfCentury() public
```
startOfCentury(): static
```
Resets the date to the first day of the century and the time to 00:00:00
#### Returns
`static`
### startOfDay() public
```
startOfDay(): static
```
Resets the time to 00:00:00
#### Returns
`static`
### startOfDecade() public
```
startOfDecade(): static
```
Resets the date to the first day of the decade and the time to 00:00:00
#### Returns
`static`
### startOfMonth() public
```
startOfMonth(): static
```
Resets the date to the first day of the month and the time to 00:00:00
#### Returns
`static`
### startOfWeek() public
```
startOfWeek(): static
```
Resets the date to the first day of week (defined in $weekStartsAt) and the time to 00:00:00
#### Returns
`static`
### startOfYear() public
```
startOfYear(): static
```
Resets the date to the first day of the year and the time to 00:00:00
#### Returns
`static`
### subDay() public
```
subDay(int $value = 1): static
```
Remove a day from the instance
#### Parameters
`int` $value optional The number of days to remove.
#### Returns
`static`
### subDays() public
```
subDays(int $value): static
```
Remove days from the instance
#### Parameters
`int` $value The number of days to remove.
#### Returns
`static`
### subHour() public
```
subHour(int $value = 1): static
```
Remove an hour from the instance
#### Parameters
`int` $value optional The number of hours to remove.
#### Returns
`static`
### subHours() public
```
subHours(int $value): static
```
Remove hours from the instance
#### Parameters
`int` $value The number of hours to remove.
#### Returns
`static`
### subMinute() public
```
subMinute(int $value = 1): static
```
Remove a minute from the instance
#### Parameters
`int` $value optional The number of minutes to remove.
#### Returns
`static`
### subMinutes() public
```
subMinutes(int $value): static
```
Remove minutes from the instance
#### Parameters
`int` $value The number of minutes to remove.
#### Returns
`static`
### subMonth() public
```
subMonth(int $value = 1): static
```
Remove a month from the instance
Has the same behavior as `addMonths()`.
#### Parameters
`int` $value optional The number of months to remove.
#### Returns
`static`
### subMonthWithOverflow() public
```
subMonthWithOverflow(int $value = 1): static
```
Remove a month with overflow from the instance.
Has the same behavior as `addMonthsWithOverflow()`.
#### Parameters
`int` $value optional The number of months to remove.
#### Returns
`static`
### subMonths() public
```
subMonths(int $value): static
```
Remove months from the instance.
Has the same behavior as `addMonths()`.
#### Parameters
`int` $value The number of months to remove.
#### Returns
`static`
### subMonthsWithOverflow() public
```
subMonthsWithOverflow(int $value): static
```
Remove months with overflow from the instance.
Has the same behavior as `addMonthsWithOverflow()`.
#### Parameters
`int` $value The number of months to remove.
#### Returns
`static`
### subSecond() public
```
subSecond(int $value = 1): static
```
Remove a second from the instance
#### Parameters
`int` $value optional The number of seconds to remove.
#### Returns
`static`
### subSeconds() public
```
subSeconds(int $value): static
```
Remove seconds from the instance
#### Parameters
`int` $value The number of seconds to remove.
#### Returns
`static`
### subWeek() public
```
subWeek(int $value = 1): static
```
Remove a week from the instance
#### Parameters
`int` $value optional The number of weeks to remove.
#### Returns
`static`
### subWeekday() public
```
subWeekday(int $value = 1): static
```
Remove a weekday from the instance
#### Parameters
`int` $value optional The number of weekdays to remove.
#### Returns
`static`
### subWeekdays() public
```
subWeekdays(int $value): static
```
Remove weekdays from the instance
#### Parameters
`int` $value The number of weekdays to remove.
#### Returns
`static`
### subWeeks() public
```
subWeeks(int $value): static
```
Remove weeks to the instance
#### Parameters
`int` $value The number of weeks to remove.
#### Returns
`static`
### subYear() public
```
subYear(int $value = 1): static
```
Remove a year from the instance.
Has the same behavior as `addYears()`.
#### Parameters
`int` $value optional The number of years to remove.
#### Returns
`static`
### subYearWithOverflow() public
```
subYearWithOverflow(int $value = 1): static
```
Remove a year with overflow from the instance
Has the same behavior as `addYearsWithOverflow()`.
#### Parameters
`int` $value optional The number of years to remove.
#### Returns
`static`
### subYears() public
```
subYears(int $value): static
```
Remove years from the instance.
Has the same behavior as `addYears()`.
#### Parameters
`int` $value The number of years to remove.
#### Returns
`static`
### subYearsWithOverflow() public
```
subYearsWithOverflow(int $value): static
```
Remove years with overflow from the instance
Has the same behavior as `addYearsWithOverflow()`.
#### Parameters
`int` $value The number of years to remove.
#### Returns
`static`
### timeAgoInWords() public
```
timeAgoInWords(array<string, mixed> $options = []): string
```
Returns either a relative or a formatted absolute date depending on the difference between the current time and this object.
### Options:
* `from` => another Time object representing the "now" time
* `format` => a fall back format if the relative time is longer than the duration specified by end
* `accuracy` => Specifies how accurate the date should be described (array)
+ year => The format if years > 0 (default "day")
+ month => The format if months > 0 (default "day")
+ week => The format if weeks > 0 (default "day")
+ day => The format if weeks > 0 (default "hour")
+ hour => The format if hours > 0 (default "minute")
+ minute => The format if minutes > 0 (default "minute")
+ second => The format if seconds > 0 (default "second")
* `end` => The end of relative time telling
* `relativeString` => The printf compatible string when outputting relative time
* `absoluteString` => The printf compatible string when outputting absolute time
* `timezone` => The user timezone the timestamp should be formatted in.
Relative dates look something like this:
* 3 weeks, 4 days ago
* 15 seconds ago
Default date formatting is d/M/YY e.g: on 18/2/09. Formatting is done internally using `i18nFormat`, see the method for the valid formatting strings
The returned string includes 'ago' or 'on' and assumes you'll properly add a word like 'Posted ' before the function output.
NOTE: If the difference is one week or more, the lowest level of accuracy is day
#### Parameters
`array<string, mixed>` $options optional Array of options.
#### Returns
`string`
### timestamp() public
```
timestamp(int $value): static
```
Set the instance's timestamp
#### Parameters
`int` $value The timestamp value to set.
#### Returns
`static`
### timezone() public
```
timezone(DateTimeZone|string $value): static
```
Alias for setTimezone()
#### Parameters
`DateTimeZone|string` $value The DateTimeZone object or timezone name to use.
#### Returns
`static`
### toAtomString() public
```
toAtomString(): string
```
Format the instance as ATOM
#### Returns
`string`
### toCookieString() public
```
toCookieString(): string
```
Format the instance as COOKIE
#### Returns
`string`
### toDateString() public
```
toDateString(): string
```
Format the instance as date
#### Returns
`string`
### toDateTimeString() public
```
toDateTimeString(): string
```
Format the instance as date and time
#### Returns
`string`
### toDayDateTimeString() public
```
toDayDateTimeString(): string
```
Format the instance with day, date and time
#### Returns
`string`
### toFormattedDateString() public
```
toFormattedDateString(): string
```
Format the instance as a readable date
#### Returns
`string`
### toIso8601String() public
```
toIso8601String(): string
```
Format the instance as ISO8601
#### Returns
`string`
### toMutable() public
```
toMutable(): Cake\Chronos\MutableDateTime
```
Create a new mutable instance from current immutable instance.
#### Returns
`Cake\Chronos\MutableDateTime`
### toQuarter() public
```
toQuarter(bool $range = false): int|array
```
Returns the quarter
#### Parameters
`bool` $range optional Range.
#### Returns
`int|array`
### toRfc1036String() public
```
toRfc1036String(): string
```
Format the instance as RFC1036
#### Returns
`string`
### toRfc1123String() public
```
toRfc1123String(): string
```
Format the instance as RFC1123
#### Returns
`string`
### toRfc2822String() public
```
toRfc2822String(): string
```
Format the instance as RFC2822
#### Returns
`string`
### toRfc3339String() public
```
toRfc3339String(): string
```
Format the instance as RFC3339
#### Returns
`string`
### toRfc822String() public
```
toRfc822String(): string
```
Format the instance as RFC822
#### Returns
`string`
### toRfc850String() public
```
toRfc850String(): string
```
Format the instance as RFC850
#### Returns
`string`
### toRssString() public
```
toRssString(): string
```
Format the instance as RSS
#### Returns
`string`
### toTimeString() public
```
toTimeString(): string
```
Format the instance as time
#### Returns
`string`
### toUnixString() public
```
toUnixString(): string
```
Returns a UNIX timestamp.
#### Returns
`string`
### toW3cString() public
```
toW3cString(): string
```
Format the instance as W3C
#### Returns
`string`
### toWeek() public
```
toWeek(): int
```
#### Returns
`int`
### today() public static
```
today(DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance for today
#### Parameters
`DateTimeZone|string|null` $tz optional The timezone to use.
#### Returns
`static`
### tomorrow() public static
```
tomorrow(DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance for tomorrow
#### Parameters
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
### tz() public
```
tz(DateTimeZone|string $value): static
```
Alias for setTimezone()
#### Parameters
`DateTimeZone|string` $value The DateTimeZone object or timezone name to use.
#### Returns
`static`
### wasWithinLast() public
```
wasWithinLast(string|int $timeInterval): bool
```
Returns true this instance happened within the specified interval
#### Parameters
`string|int` $timeInterval the numeric value with space then time type. Example of valid types: 6 hours, 2 days, 1 minute.
#### Returns
`bool`
### year() public
```
year(int $value): static
```
Set the instance's year
#### Parameters
`int` $value The year value.
#### Returns
`static`
### yesterday() public static
```
yesterday(DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance for yesterday
#### Parameters
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
Property Detail
---------------
### $\_formatters protected static
In-memory cache of date formatters
#### Type
`arrayIntlDateFormatter>`
### $\_jsonEncodeFormat protected static
The format to use when converting this object to JSON.
The format should be either the formatting constants from IntlDateFormatter as described in (<https://secure.php.net/manual/en/class.intldateformatter.php>) or a pattern as specified in (<https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details>)
It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.
#### Type
`Closure|array<int>|string|int`
### $\_lastErrors protected static
Holds the last error generated by createFromFormat
#### Type
`array`
### $\_toStringFormat protected static
The format to use when formatting a time using `Cake\I18n\FrozenTime::i18nFormat()` and `__toString`. This format is also used by `parseDateTime()`.
The format should be either the formatting constants from IntlDateFormatter as described in (<https://secure.php.net/manual/en/class.intldateformatter.php>) or a pattern as specified in (<https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details>)
It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.
#### Type
`array<int>|string|int`
### $age public @property-read
does a diffInYears() with default parameters
#### Type
`int`
### $day public @property-read
#### Type
`int`
### $dayOfWeek public @property-read
1 (for Monday) through 7 (for Sunday)
#### Type
`int`
### $dayOfWeekName public @property-read
#### Type
`string`
### $dayOfYear public @property-read
0 through 365
#### Type
`int`
### $days protected static
Names of days of the week.
#### Type
`array`
### $daysInMonth public @property-read
number of days in the given month
#### Type
`int`
### $defaultLocale protected static
The default locale to be used for displaying formatted date strings.
Use static::setDefaultLocale() and static::getDefaultLocale() instead.
#### Type
`string|null`
### $diffFormatter protected static
Instance of the diff formatting object.
#### Type
`Cake\Chronos\DifferenceFormatterInterface`
### $dst public @property-read
daylight savings time indicator, true if DST, false otherwise
#### Type
`bool`
### $hour public @property-read
#### Type
`int`
### $lenientParsing protected static
Whether lenient parsing is enabled for IntlDateFormatter.
Defaults to true which is the default for IntlDateFormatter.
#### Type
`bool`
### $local public @property-read
checks if the timezone is local, true if local, false otherwise
#### Type
`bool`
### $micro public @property-read
#### Type
`int`
### $microsecond public @property-read
#### Type
`int`
### $minute public @property-read
#### Type
`int`
### $month public @property-read
#### Type
`int`
### $niceFormat public static
The format to use when formatting a time using `Cake\I18n\FrozenTime::nice()`
The format should be either the formatting constants from IntlDateFormatter as described in (<https://secure.php.net/manual/en/class.intldateformatter.php>) or a pattern as specified in (<https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details>)
It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.
#### Type
`array<int>|string|int`
### $offset public @property-read
the timezone offset in seconds from UTC
#### Type
`int`
### $offsetHours public @property-read
the timezone offset in hours from UTC
#### Type
`int`
### $quarter public @property-read
the quarter of this instance, 1 - 4
#### Type
`int`
### $relativePattern protected static
Regex for relative period.
#### Type
`string`
### $second public @property-read
#### Type
`int`
### $testNow protected static
A test ChronosInterface instance to be returned when now instances are created
There is a single test now for all date/time classes provided by Chronos. This aims to emulate stubbing out 'now' which is a single global fact.
#### Type
`Cake\Chronos\ChronosInterface|null`
### $timestamp public @property-read
seconds since the Unix Epoch
#### Type
`int`
### $timezone public @property-read
the current timezone
#### Type
`DateTimeZone`
### $timezoneName public @property-read
#### Type
`string`
### $toStringFormat protected static
Format to use for \_\_toString method when type juggling occurs.
#### Type
`string`
### $tz public @property-read
alias of timezone
#### Type
`DateTimeZone`
### $tzName public @property-read
#### Type
`string`
### $utc public @property-read
checks if the timezone is UTC, true if UTC, false otherwise
#### Type
`bool`
### $weekEndsAt protected static
Last day of week
#### Type
`int`
### $weekOfMonth public @property-read
1 through 5
#### Type
`int`
### $weekOfYear public @property-read
ISO-8601 week number of year, weeks starting on Monday
#### Type
`int`
### $weekStartsAt protected static
First day of week
#### Type
`int`
### $weekendDays protected static
Days of weekend
#### Type
`array`
### $wordAccuracy public static
The format to use when formatting a time using `Time::timeAgoInWords()` and the difference is less than `Time::$wordEnd`
#### Type
`array<string>`
### $wordEnd public static
The end of relative time telling
#### Type
`string`
### $wordFormat public static
The format to use when formatting a time using `Cake\I18n\FrozenTime::timeAgoInWords()` and the difference is more than `Cake\I18n\FrozenTime::$wordEnd`
#### Type
`array<int>|string|int`
### $year public @property-read
#### Type
`int`
### $yearIso public @property-read
#### Type
`int`
| programming_docs |
cakephp Class ResponseEmitter Class ResponseEmitter
======================
Emits a Response to the PHP Server API.
This emitter offers a few changes from the emitters offered by diactoros:
* It logs headers sent using CakePHP's logging tools.
* Cookies are emitted using setcookie() to not conflict with ext/session
**Namespace:** [Cake\Http](namespace-cake.http)
Property Summary
----------------
* [$maxBufferLength](#%24maxBufferLength) protected `int` Maximum output buffering size for each iteration.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [emit()](#emit()) public
Emit a response.
* ##### [emitBody()](#emitBody()) protected
Emit the message body.
* ##### [emitBodyRange()](#emitBodyRange()) protected
Emit a range of the message body.
* ##### [emitCookies()](#emitCookies()) protected
Emit cookies using setcookie()
* ##### [emitHeaders()](#emitHeaders()) protected
Emit response headers.
* ##### [emitStatusLine()](#emitStatusLine()) protected
Emit the status line.
* ##### [flush()](#flush()) protected
Loops through the output buffer, flushing each, before emitting the response.
* ##### [parseContentRange()](#parseContentRange()) protected
Parse content-range header <https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.16>
* ##### [setCookie()](#setCookie()) protected
Helper methods to set cookie.
Method Detail
-------------
### \_\_construct() public
```
__construct(int $maxBufferLength = 8192)
```
Constructor
#### Parameters
`int` $maxBufferLength optional Maximum output buffering size for each iteration.
### emit() public
```
emit(ResponseInterface $response): bool
```
Emit a response.
Emits a response, including status line, headers, and the message body, according to the environment.
#### Parameters
`ResponseInterface` $response The response to emit.
#### Returns
`bool`
### emitBody() protected
```
emitBody(Psr\Http\Message\ResponseInterface $response): void
```
Emit the message body.
#### Parameters
`Psr\Http\Message\ResponseInterface` $response The response to emit
#### Returns
`void`
### emitBodyRange() protected
```
emitBodyRange(array $range, Psr\Http\Message\ResponseInterface $response): void
```
Emit a range of the message body.
#### Parameters
`array` $range The range data to emit
`Psr\Http\Message\ResponseInterface` $response The response to emit
#### Returns
`void`
### emitCookies() protected
```
emitCookies(arrayCake\Http\Cookie\CookieInterface|string> $cookies): void
```
Emit cookies using setcookie()
#### Parameters
`arrayCake\Http\Cookie\CookieInterface|string>` $cookies An array of cookies.
#### Returns
`void`
### emitHeaders() protected
```
emitHeaders(Psr\Http\Message\ResponseInterface $response): void
```
Emit response headers.
Loops through each header, emitting each; if the header value is an array with multiple values, ensures that each is sent in such a way as to create aggregate headers (instead of replace the previous).
#### Parameters
`Psr\Http\Message\ResponseInterface` $response The response to emit
#### Returns
`void`
### emitStatusLine() protected
```
emitStatusLine(Psr\Http\Message\ResponseInterface $response): void
```
Emit the status line.
Emits the status line using the protocol version and status code from the response; if a reason phrase is available, it, too, is emitted.
#### Parameters
`Psr\Http\Message\ResponseInterface` $response The response to emit
#### Returns
`void`
### flush() protected
```
flush(int|null $maxBufferLevel = null): void
```
Loops through the output buffer, flushing each, before emitting the response.
#### Parameters
`int|null` $maxBufferLevel optional Flush up to this buffer level.
#### Returns
`void`
### parseContentRange() protected
```
parseContentRange(string $header): array|false
```
Parse content-range header <https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.16>
#### Parameters
`string` $header The Content-Range header to parse.
#### Returns
`array|false`
### setCookie() protected
```
setCookie(Cake\Http\Cookie\CookieInterface|string $cookie): bool
```
Helper methods to set cookie.
#### Parameters
`Cake\Http\Cookie\CookieInterface|string` $cookie Cookie.
#### Returns
`bool`
Property Detail
---------------
### $maxBufferLength protected
Maximum output buffering size for each iteration.
#### Type
`int`
cakephp Class Socket Class Socket
=============
CakePHP network socket connection class.
Core base class for network communication.
**Namespace:** [Cake\Network](namespace-cake.network)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_connectionErrors](#%24_connectionErrors) protected `array<string>` Used to capture connection warnings which can happen when there are SSL errors for example.
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default configuration settings for the socket connection
* [$\_encryptMethods](#%24_encryptMethods) protected `array<string, int>` Contains all the encryption methods available
* [$connected](#%24connected) protected `bool` This boolean contains the current state of the Socket class
* [$connection](#%24connection) protected `resource|null` Reference to socket connection resource
* [$encrypted](#%24encrypted) protected `bool` True if the socket stream is encrypted after a {@link \Cake\Network\Socket::enableCrypto()} call
* [$lastError](#%24lastError) protected `array<string, mixed>` This variable contains an array with the last error number (num) and string (str)
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_\_destruct()](#__destruct()) public
Destructor, used to disconnect from current connection.
* ##### [\_\_get()](#__get()) public
Temporary magic method to allow accessing protected properties.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_connectionErrorHandler()](#_connectionErrorHandler()) protected
socket\_stream\_client() does not populate errNum, or $errStr when there are connection errors, as in the case of SSL verification failure.
* ##### [\_getStreamSocketClient()](#_getStreamSocketClient()) protected
Create a stream socket client. Mock utility.
* ##### [\_setSslContext()](#_setSslContext()) protected
Configure the SSL context options.
* ##### [address()](#address()) public
Get the IP address of the current connection.
* ##### [addresses()](#addresses()) public
Get all IP addresses associated with the current connection.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [connect()](#connect()) public
Connect the socket to the given host and port.
* ##### [context()](#context()) public
Get the connection context.
* ##### [disconnect()](#disconnect()) public
Disconnect the socket from the current connection.
* ##### [enableCrypto()](#enableCrypto()) public
Encrypts current stream socket, using one of the defined encryption methods
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [host()](#host()) public
Get the host name of the current connection.
* ##### [isConnected()](#isConnected()) public
Check the connection status after calling `connect()`.
* ##### [isEncrypted()](#isEncrypted()) public
Check the encryption status after calling `enableCrypto()`.
* ##### [lastError()](#lastError()) public
Get the last error as a string.
* ##### [read()](#read()) public
Read data from the socket. Returns null if no data is available or no connection could be established.
* ##### [reset()](#reset()) public
Resets the state of this Socket instance to it's initial state (before Object::\_\_construct got executed)
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setLastError()](#setLastError()) public
Set the last error.
* ##### [write()](#write()) public
Write data to the socket.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Constructor.
#### Parameters
`array<string, mixed>` $config optional Socket configuration, which will be merged with the base configuration
#### See Also
\Cake\Network\Socket::$\_defaultConfig ### \_\_destruct() public
```
__destruct()
```
Destructor, used to disconnect from current connection.
### \_\_get() public
```
__get(string $name): mixed
```
Temporary magic method to allow accessing protected properties.
Will be removed in 5.0.
#### Parameters
`string` $name Property name.
#### Returns
`mixed`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_connectionErrorHandler() protected
```
_connectionErrorHandler(int $code, string $message): void
```
socket\_stream\_client() does not populate errNum, or $errStr when there are connection errors, as in the case of SSL verification failure.
Instead we need to handle those errors manually.
#### Parameters
`int` $code Code number.
`string` $message Message.
#### Returns
`void`
### \_getStreamSocketClient() protected
```
_getStreamSocketClient(string $remoteSocketTarget, int $errNum, string $errStr, int $timeout, int $connectAs, resource $context): resource|null
```
Create a stream socket client. Mock utility.
#### Parameters
`string` $remoteSocketTarget remote socket
`int` $errNum error number
`string` $errStr error string
`int` $timeout timeout
`int` $connectAs flags
`resource` $context context
#### Returns
`resource|null`
### \_setSslContext() protected
```
_setSslContext(string $host): void
```
Configure the SSL context options.
#### Parameters
`string` $host The host name being connected to.
#### Returns
`void`
### address() public
```
address(): string
```
Get the IP address of the current connection.
#### Returns
`string`
### addresses() public
```
addresses(): array
```
Get all IP addresses associated with the current connection.
#### Returns
`array`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### connect() public
```
connect(): bool
```
Connect the socket to the given host and port.
#### Returns
`bool`
#### Throws
`Cake\Network\Exception\SocketException`
### context() public
```
context(): array|null
```
Get the connection context.
#### Returns
`array|null`
### disconnect() public
```
disconnect(): bool
```
Disconnect the socket from the current connection.
#### Returns
`bool`
### enableCrypto() public
```
enableCrypto(string $type, string $clientOrServer = 'client', bool $enable = true): void
```
Encrypts current stream socket, using one of the defined encryption methods
#### Parameters
`string` $type can be one of 'ssl2', 'ssl3', 'ssl23' or 'tls'
`string` $clientOrServer optional can be one of 'client', 'server'. Default is 'client'
`bool` $enable optional enable or disable encryption. Default is true (enable)
#### Returns
`void`
#### Throws
`InvalidArgumentException`
When an invalid encryption scheme is chosen.
`Cake\Network\Exception\SocketException`
When attempting to enable SSL/TLS fails #### See Also
stream\_socket\_enable\_crypto ### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### host() public
```
host(): string
```
Get the host name of the current connection.
#### Returns
`string`
### isConnected() public
```
isConnected(): bool
```
Check the connection status after calling `connect()`.
#### Returns
`bool`
### isEncrypted() public
```
isEncrypted(): bool
```
Check the encryption status after calling `enableCrypto()`.
#### Returns
`bool`
### lastError() public
```
lastError(): string|null
```
Get the last error as a string.
#### Returns
`string|null`
### read() public
```
read(int $length = 1024): string|null
```
Read data from the socket. Returns null if no data is available or no connection could be established.
#### Parameters
`int` $length optional Optional buffer length to read; defaults to 1024
#### Returns
`string|null`
### reset() public
```
reset(array|null $state = null): void
```
Resets the state of this Socket instance to it's initial state (before Object::\_\_construct got executed)
#### Parameters
`array|null` $state optional Array with key and values to reset
#### Returns
`void`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setLastError() public
```
setLastError(int|null $errNum, string $errStr): void
```
Set the last error.
#### Parameters
`int|null` $errNum Error code
`string` $errStr Error string
#### Returns
`void`
### write() public
```
write(string $data): int
```
Write data to the socket.
#### Parameters
`string` $data The data to write to the socket.
#### Returns
`int`
Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_connectionErrors protected
Used to capture connection warnings which can happen when there are SSL errors for example.
#### Type
`array<string>`
### $\_defaultConfig protected
Default configuration settings for the socket connection
#### Type
`array<string, mixed>`
### $\_encryptMethods protected
Contains all the encryption methods available
#### Type
`array<string, int>`
### $connected protected
This boolean contains the current state of the Socket class
#### Type
`bool`
### $connection protected
Reference to socket connection resource
#### Type
`resource|null`
### $encrypted protected
True if the socket stream is encrypted after a {@link \Cake\Network\Socket::enableCrypto()} call
#### Type
`bool`
### $lastError protected
This variable contains an array with the last error number (num) and string (str)
#### Type
`array<string, mixed>`
cakephp Trait ConsoleIntegrationTestTrait Trait ConsoleIntegrationTestTrait
==================================
A bundle of methods that makes testing commands and shell classes easier.
Enables you to call commands/shells with a full application context.
**Namespace:** [Cake\Console\TestSuite](namespace-cake.console.testsuite)
Property Summary
----------------
* [$\_appArgs](#%24_appArgs) protected `array|null` The customized application constructor arguments.
* [$\_appClass](#%24_appClass) protected `string|null` The customized application class name.
* [$\_err](#%24_err) protected `Cake\Console\TestSuite\StubConsoleOutput` Console error output stub
* [$\_exitCode](#%24_exitCode) protected `int|null` Last exit code
* [$\_in](#%24_in) protected `Cake\Console\TestSuite\StubConsoleInput` Console input mock
* [$\_out](#%24_out) protected `Cake\Console\TestSuite\StubConsoleOutput` Console output stub
* [$\_useCommandRunner](#%24_useCommandRunner) protected `bool` Whether to use the CommandRunner
Method Summary
--------------
* ##### [assertErrorContains()](#assertErrorContains()) public
Asserts `stderr` contains expected output
* ##### [assertErrorEmpty()](#assertErrorEmpty()) public
Asserts that `stderr` is empty
* ##### [assertErrorRegExp()](#assertErrorRegExp()) public
Asserts `stderr` contains expected regexp
* ##### [assertExitCode()](#assertExitCode()) public
Asserts shell exited with the expected code
* ##### [assertExitError()](#assertExitError()) public
Asserts shell exited with Command::CODE\_ERROR
* ##### [assertExitSuccess()](#assertExitSuccess()) public
Asserts shell exited with the Command::CODE\_SUCCESS
* ##### [assertOutputContains()](#assertOutputContains()) public
Asserts `stdout` contains expected output
* ##### [assertOutputContainsRow()](#assertOutputContainsRow()) protected
Check that a row of cells exists in the output.
* ##### [assertOutputEmpty()](#assertOutputEmpty()) public
Asserts that `stdout` is empty
* ##### [assertOutputNotContains()](#assertOutputNotContains()) public
Asserts `stdout` does not contain expected output
* ##### [assertOutputRegExp()](#assertOutputRegExp()) public
Asserts `stdout` contains expected regexp
* ##### [cleanupConsoleTrait()](#cleanupConsoleTrait()) public
Cleans state to get ready for the next test
* ##### [cleanupContainer()](#cleanupContainer()) public
Clears any mocks that were defined and cleans up application class configuration.
* ##### [commandStringToArgs()](#commandStringToArgs()) protected
Creates an $argv array from a command string
* ##### [configApplication()](#configApplication()) public
Configure the application class to use in integration tests.
* ##### [createApp()](#createApp()) protected
Create an application instance.
* ##### [exec()](#exec()) public
Runs CLI integration test
* ##### [makeRunner()](#makeRunner()) protected
Builds the appropriate command dispatcher
* ##### [mockService()](#mockService()) public
Add a mocked service to the container.
* ##### [modifyContainer()](#modifyContainer()) public
Wrap the application's container with one containing mocks.
* ##### [removeMockService()](#removeMockService()) public
Remove a mocked service to the container.
* ##### [useCommandRunner()](#useCommandRunner()) public
Set this test case to use the CommandRunner rather than the legacy ShellDispatcher
Method Detail
-------------
### assertErrorContains() public
```
assertErrorContains(string $expected, string $message = ''): void
```
Asserts `stderr` contains expected output
#### Parameters
`string` $expected Expected output
`string` $message optional Failure message
#### Returns
`void`
### assertErrorEmpty() public
```
assertErrorEmpty(string $message = ''): void
```
Asserts that `stderr` is empty
#### Parameters
`string` $message optional The message to output when the assertion fails.
#### Returns
`void`
### assertErrorRegExp() public
```
assertErrorRegExp(string $pattern, string $message = ''): void
```
Asserts `stderr` contains expected regexp
#### Parameters
`string` $pattern Expected pattern
`string` $message optional Failure message
#### Returns
`void`
### assertExitCode() public
```
assertExitCode(int $expected, string $message = ''): void
```
Asserts shell exited with the expected code
#### Parameters
`int` $expected Expected exit code
`string` $message optional Failure message
#### Returns
`void`
### assertExitError() public
```
assertExitError(string $message = ''): void
```
Asserts shell exited with Command::CODE\_ERROR
#### Parameters
`string` $message optional Failure message
#### Returns
`void`
### assertExitSuccess() public
```
assertExitSuccess(string $message = ''): void
```
Asserts shell exited with the Command::CODE\_SUCCESS
#### Parameters
`string` $message optional Failure message
#### Returns
`void`
### assertOutputContains() public
```
assertOutputContains(string $expected, string $message = ''): void
```
Asserts `stdout` contains expected output
#### Parameters
`string` $expected Expected output
`string` $message optional Failure message
#### Returns
`void`
### assertOutputContainsRow() protected
```
assertOutputContainsRow(array $row, string $message = ''): void
```
Check that a row of cells exists in the output.
#### Parameters
`array` $row Row of cells to ensure exist in the output.
`string` $message optional Failure message.
#### Returns
`void`
### assertOutputEmpty() public
```
assertOutputEmpty(string $message = ''): void
```
Asserts that `stdout` is empty
#### Parameters
`string` $message optional The message to output when the assertion fails.
#### Returns
`void`
### assertOutputNotContains() public
```
assertOutputNotContains(string $expected, string $message = ''): void
```
Asserts `stdout` does not contain expected output
#### Parameters
`string` $expected Expected output
`string` $message optional Failure message
#### Returns
`void`
### assertOutputRegExp() public
```
assertOutputRegExp(string $pattern, string $message = ''): void
```
Asserts `stdout` contains expected regexp
#### Parameters
`string` $pattern Expected pattern
`string` $message optional Failure message
#### Returns
`void`
### cleanupConsoleTrait() public
```
cleanupConsoleTrait(): void
```
Cleans state to get ready for the next test
#### Returns
`void`
### cleanupContainer() public
```
cleanupContainer(): void
```
Clears any mocks that were defined and cleans up application class configuration.
#### Returns
`void`
### commandStringToArgs() protected
```
commandStringToArgs(string $command): array<string>
```
Creates an $argv array from a command string
#### Parameters
`string` $command Command string
#### Returns
`array<string>`
### configApplication() public
```
configApplication(string $class, array|null $constructorArgs): void
```
Configure the application class to use in integration tests.
#### Parameters
`string` $class The application class name.
`array|null` $constructorArgs The constructor arguments for your application class.
#### Returns
`void`
### createApp() protected
```
createApp(): Cake\Core\HttpApplicationInterfaceCake\Core\ConsoleApplicationInterface
```
Create an application instance.
Uses the configuration set in `configApplication()`.
#### Returns
`Cake\Core\HttpApplicationInterfaceCake\Core\ConsoleApplicationInterface`
### exec() public
```
exec(string $command, array $input = []): void
```
Runs CLI integration test
#### Parameters
`string` $command Command to run
`array` $input optional Input values to pass to an interactive shell
#### Returns
`void`
#### Throws
`Cake\Console\TestSuite\MissingConsoleInputException`
`RuntimeException`
### makeRunner() protected
```
makeRunner(): Cake\Console\CommandRunnerCake\Console\TestSuite\LegacyCommandRunner
```
Builds the appropriate command dispatcher
#### Returns
`Cake\Console\CommandRunnerCake\Console\TestSuite\LegacyCommandRunner`
### mockService() public
```
mockService(string $class, Closure $factory): $this
```
Add a mocked service to the container.
When the container is created the provided classname will be mapped to the factory function. The factory function will be used to create mocked services.
#### Parameters
`string` $class The class or interface you want to define.
`Closure` $factory The factory function for mocked services.
#### Returns
`$this`
### modifyContainer() public
```
modifyContainer(Cake\Event\EventInterface $event, Cake\Core\ContainerInterface $container): Cake\Core\ContainerInterface|null
```
Wrap the application's container with one containing mocks.
If any mocked services are defined, the application's container will be replaced with one containing mocks. The original container will be set as a delegate to the mock container.
#### Parameters
`Cake\Event\EventInterface` $event The event
`Cake\Core\ContainerInterface` $container The container to wrap.
#### Returns
`Cake\Core\ContainerInterface|null`
### removeMockService() public
```
removeMockService(string $class): $this
```
Remove a mocked service to the container.
#### Parameters
`string` $class The class or interface you want to remove.
#### Returns
`$this`
### useCommandRunner() public
```
useCommandRunner(): void
```
Set this test case to use the CommandRunner rather than the legacy ShellDispatcher
#### Returns
`void`
Property Detail
---------------
### $\_appArgs protected
The customized application constructor arguments.
#### Type
`array|null`
### $\_appClass protected
The customized application class name.
#### Type
`string|null`
### $\_err protected
Console error output stub
#### Type
`Cake\Console\TestSuite\StubConsoleOutput`
### $\_exitCode protected
Last exit code
#### Type
`int|null`
### $\_in protected
Console input mock
#### Type
`Cake\Console\TestSuite\StubConsoleInput`
### $\_out protected
Console output stub
#### Type
`Cake\Console\TestSuite\StubConsoleOutput`
### $\_useCommandRunner protected
Whether to use the CommandRunner
#### Type
`bool`
| programming_docs |
cakephp Class NotAcceptableException Class NotAcceptableException
=============================
Represents an HTTP 406 error.
**Namespace:** [Cake\Http\Exception](namespace-cake.http.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
* [$headers](#%24headers) protected `array<string, mixed>`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [getHeaders()](#getHeaders()) public
Returns array of response headers.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
* ##### [setHeader()](#setHeader()) public
Set a single HTTP response header.
* ##### [setHeaders()](#setHeaders()) public
Sets HTTP response headers.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $message = null, int|null $code = null, Throwable|null $previous = null)
```
Constructor
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`string|null` $message optional If no message is given 'Not Acceptable' will be the message
`int|null` $code optional Status code, defaults to 406
`Throwable|null` $previous optional The previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### getHeaders() public
```
getHeaders(): array<string, mixed>
```
Returns array of response headers.
#### Returns
`array<string, mixed>`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
### setHeader() public
```
setHeader(string $header, array<string>|string|null $value = null): void
```
Set a single HTTP response header.
#### Parameters
`string` $header Header name
`array<string>|string|null` $value optional Header value
#### Returns
`void`
### setHeaders() public
```
setHeaders(array<string, mixed> $headers): void
```
Sets HTTP response headers.
#### Parameters
`array<string, mixed>` $headers Array of header name and value pairs.
#### Returns
`void`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
### $headers protected
#### Type
`array<string, mixed>`
cakephp Class BodyContains Class BodyContains
===================
BodyContains
**Namespace:** [Cake\TestSuite\Constraint\Response](namespace-cake.testsuite.constraint.response)
Property Summary
----------------
* [$ignoreCase](#%24ignoreCase) protected `bool`
* [$response](#%24response) protected `Psr\Http\Message\ResponseInterface`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_getBodyAsString()](#_getBodyAsString()) protected
Get the response body as string
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Checks assertion
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(Psr\Http\Message\ResponseInterface $response, bool $ignoreCase = false)
```
Constructor.
#### Parameters
`Psr\Http\Message\ResponseInterface` $response A response instance.
`bool` $ignoreCase optional Ignore case
### \_getBodyAsString() protected
```
_getBodyAsString(): string
```
Get the response body as string
#### Returns
`string`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks assertion
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Expected type
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $ignoreCase protected
#### Type
`bool`
### $response protected
#### Type
`Psr\Http\Message\ResponseInterface`
cakephp Class PostgresSchemaDialect Class PostgresSchemaDialect
============================
Schema management/reflection features for Postgres.
**Namespace:** [Cake\Database\Schema](namespace-cake.database.schema)
Property Summary
----------------
* [$\_driver](#%24_driver) protected `Cake\Database\DriverInterface` The driver instance being used.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_applyTypeSpecificColumnConversion()](#_applyTypeSpecificColumnConversion()) protected
Tries to use a matching database type to convert a SQL column definition to an abstract type definition.
* ##### [\_convertColumn()](#_convertColumn()) protected
Convert a column definition to the abstract types.
* ##### [\_convertConstraint()](#_convertConstraint()) protected
Add/update a constraint into the schema object.
* ##### [\_convertConstraintColumns()](#_convertConstraintColumns()) protected
Convert foreign key constraints references to a valid stringified list
* ##### [\_convertOnClause()](#_convertOnClause()) protected
Convert string on clauses to the abstract ones.
* ##### [\_defaultValue()](#_defaultValue()) protected
Manipulate the default value.
* ##### [\_foreignOnClause()](#_foreignOnClause()) protected
Generate an ON clause for a foreign key.
* ##### [\_getTypeSpecificColumnSql()](#_getTypeSpecificColumnSql()) protected
Tries to use a matching database type to generate the SQL fragment for a single column in a table.
* ##### [\_keySql()](#_keySql()) protected
Helper method for generating key SQL snippets.
* ##### [addConstraintSql()](#addConstraintSql()) public
Generate the SQL queries needed to add foreign key constraints to the table
* ##### [columnSql()](#columnSql()) public
Generate the SQL fragment for a single column in a table.
* ##### [constraintSql()](#constraintSql()) public
Generate the SQL fragments for defining table constraints.
* ##### [convertColumnDescription()](#convertColumnDescription()) public
Convert field description results into abstract schema fields.
* ##### [convertForeignKeyDescription()](#convertForeignKeyDescription()) public
Convert a foreign key description into constraints on the Table object.
* ##### [convertIndexDescription()](#convertIndexDescription()) public
Convert an index description results into abstract schema indexes or constraints.
* ##### [convertOptionsDescription()](#convertOptionsDescription()) public
Convert options data into table options.
* ##### [createTableSql()](#createTableSql()) public
Generate the SQL to create a table.
* ##### [describeColumnSql()](#describeColumnSql()) public
Generate the SQL to describe a table.
* ##### [describeForeignKeySql()](#describeForeignKeySql()) public
Generate the SQL to describe the foreign keys in a table.
* ##### [describeIndexSql()](#describeIndexSql()) public
Generate the SQL to describe the indexes in a table.
* ##### [describeOptionsSql()](#describeOptionsSql()) public
Generate the SQL to describe table options
* ##### [dropConstraintSql()](#dropConstraintSql()) public
Generate the SQL queries needed to drop foreign key constraints from the table
* ##### [dropTableSql()](#dropTableSql()) public
Generate the SQL to drop a table.
* ##### [indexSql()](#indexSql()) public
Generate the SQL fragment for a single index in a table.
* ##### [listTablesSql()](#listTablesSql()) public
Generate the SQL to list the tables and views.
* ##### [listTablesWithoutViewsSql()](#listTablesWithoutViewsSql()) public
Generate the SQL to list the tables, excluding all views.
* ##### [truncateTableSql()](#truncateTableSql()) public
Generate the SQL to truncate a table.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Database\DriverInterface $driver)
```
Constructor
This constructor will connect the driver so that methods like columnSql() and others will fail when the driver has not been connected.
#### Parameters
`Cake\Database\DriverInterface` $driver The driver to use.
### \_applyTypeSpecificColumnConversion() protected
```
_applyTypeSpecificColumnConversion(string $columnType, array $definition): array|null
```
Tries to use a matching database type to convert a SQL column definition to an abstract type definition.
#### Parameters
`string` $columnType The column type.
`array` $definition The column definition.
#### Returns
`array|null`
### \_convertColumn() protected
```
_convertColumn(string $column): array<string, mixed>
```
Convert a column definition to the abstract types.
The returned type will be a type that Cake\Database\TypeFactory can handle.
#### Parameters
`string` $column The column type + length
#### Returns
`array<string, mixed>`
#### Throws
`Cake\Database\Exception\DatabaseException`
when column cannot be parsed. ### \_convertConstraint() protected
```
_convertConstraint(Cake\Database\Schema\TableSchema $schema, string $name, string $type, array $row): void
```
Add/update a constraint into the schema object.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema The table to update.
`string` $name The index name.
`string` $type The index type.
`array` $row The metadata record to update with.
#### Returns
`void`
### \_convertConstraintColumns() protected
```
_convertConstraintColumns(array<string>|string $references): string
```
Convert foreign key constraints references to a valid stringified list
#### Parameters
`array<string>|string` $references The referenced columns of a foreign key constraint statement
#### Returns
`string`
### \_convertOnClause() protected
```
_convertOnClause(string $clause): string
```
Convert string on clauses to the abstract ones.
#### Parameters
`string` $clause #### Returns
`string`
### \_defaultValue() protected
```
_defaultValue(string|int|null $default): string|int|null
```
Manipulate the default value.
Postgres includes sequence data and casting information in default values. We need to remove those.
#### Parameters
`string|int|null` $default The default value.
#### Returns
`string|int|null`
### \_foreignOnClause() protected
```
_foreignOnClause(string $on): string
```
Generate an ON clause for a foreign key.
#### Parameters
`string` $on The on clause
#### Returns
`string`
### \_getTypeSpecificColumnSql() protected
```
_getTypeSpecificColumnSql(string $columnType, Cake\Database\Schema\TableSchemaInterface $schema, string $column): string|null
```
Tries to use a matching database type to generate the SQL fragment for a single column in a table.
#### Parameters
`string` $columnType The column type.
`Cake\Database\Schema\TableSchemaInterface` $schema The table schema instance the column is in.
`string` $column The name of the column.
#### Returns
`string|null`
### \_keySql() protected
```
_keySql(string $prefix, array<string, mixed> $data): string
```
Helper method for generating key SQL snippets.
#### Parameters
`string` $prefix The key prefix
`array<string, mixed>` $data Key data.
#### Returns
`string`
### addConstraintSql() public
```
addConstraintSql(Cake\Database\Schema\TableSchema $schema): array
```
Generate the SQL queries needed to add foreign key constraints to the table
#### Parameters
`Cake\Database\Schema\TableSchema` $schema #### Returns
`array`
### columnSql() public
```
columnSql(Cake\Database\Schema\TableSchema $schema, string $name): string
```
Generate the SQL fragment for a single column in a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `string` $name #### Returns
`string`
### constraintSql() public
```
constraintSql(Cake\Database\Schema\TableSchema $schema, string $name): string
```
Generate the SQL fragments for defining table constraints.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `string` $name #### Returns
`string`
### convertColumnDescription() public
```
convertColumnDescription(Cake\Database\Schema\TableSchema $schema, array $row): void
```
Convert field description results into abstract schema fields.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `array` $row #### Returns
`void`
### convertForeignKeyDescription() public
```
convertForeignKeyDescription(Cake\Database\Schema\TableSchema $schema, array $row): void
```
Convert a foreign key description into constraints on the Table object.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `array` $row #### Returns
`void`
### convertIndexDescription() public
```
convertIndexDescription(Cake\Database\Schema\TableSchema $schema, array $row): void
```
Convert an index description results into abstract schema indexes or constraints.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `array` $row #### Returns
`void`
### convertOptionsDescription() public
```
convertOptionsDescription(Cake\Database\Schema\TableSchema $schema, array $row): void
```
Convert options data into table options.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema Table instance.
`array` $row The row of data.
#### Returns
`void`
### createTableSql() public
```
createTableSql(Cake\Database\Schema\TableSchema $schema, array<string> $columns, array<string> $constraints, array<string> $indexes): array<string>
```
Generate the SQL to create a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `array<string>` $columns `array<string>` $constraints `array<string>` $indexes #### Returns
`array<string>`
### describeColumnSql() public
```
describeColumnSql(string $tableName, array<string, mixed> $config): array
```
Generate the SQL to describe a table.
#### Parameters
`string` $tableName `array<string, mixed>` $config #### Returns
`array`
### describeForeignKeySql() public
```
describeForeignKeySql(string $tableName, array<string, mixed> $config): array
```
Generate the SQL to describe the foreign keys in a table.
#### Parameters
`string` $tableName `array<string, mixed>` $config #### Returns
`array`
### describeIndexSql() public
```
describeIndexSql(string $tableName, array<string, mixed> $config): array
```
Generate the SQL to describe the indexes in a table.
#### Parameters
`string` $tableName `array<string, mixed>` $config #### Returns
`array`
### describeOptionsSql() public
```
describeOptionsSql(string $tableName, array<string, mixed> $config): array
```
Generate the SQL to describe table options
#### Parameters
`string` $tableName Table name.
`array<string, mixed>` $config The connection configuration.
#### Returns
`array`
### dropConstraintSql() public
```
dropConstraintSql(Cake\Database\Schema\TableSchema $schema): array
```
Generate the SQL queries needed to drop foreign key constraints from the table
#### Parameters
`Cake\Database\Schema\TableSchema` $schema #### Returns
`array`
### dropTableSql() public
```
dropTableSql(Cake\Database\Schema\TableSchema $schema): array
```
Generate the SQL to drop a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema Table instance
#### Returns
`array`
### indexSql() public
```
indexSql(Cake\Database\Schema\TableSchema $schema, string $name): string
```
Generate the SQL fragment for a single index in a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `string` $name #### Returns
`string`
### listTablesSql() public
```
listTablesSql(array<string, mixed> $config): array
```
Generate the SQL to list the tables and views.
#### Parameters
`array<string, mixed>` $config The connection configuration to use for getting tables from.
#### Returns
`array`
### listTablesWithoutViewsSql() public
```
listTablesWithoutViewsSql(array<string, mixed> $config): array<mixed>
```
Generate the SQL to list the tables, excluding all views.
#### Parameters
`array<string, mixed>` $config The connection configuration to use for getting tables from.
#### Returns
`array<mixed>`
### truncateTableSql() public
```
truncateTableSql(Cake\Database\Schema\TableSchema $schema): array
```
Generate the SQL to truncate a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema #### Returns
`array`
Property Detail
---------------
### $\_driver protected
The driver instance being used.
#### Type
`Cake\Database\DriverInterface`
| programming_docs |
cakephp Class TransportFactory Class TransportFactory
=======================
Factory class for generating email transport instances.
**Namespace:** [Cake\Mailer](namespace-cake.mailer)
Property Summary
----------------
* [$\_config](#%24_config) protected static `array<string, mixed>` Configuration sets.
* [$\_dsnClassMap](#%24_dsnClassMap) protected static `array<string, string>` An array mapping url schemes to fully qualified Transport class names
* [$\_registry](#%24_registry) protected static `Cake\Mailer\TransportRegistry|null` Transport Registry used for creating and using transport instances.
Method Summary
--------------
* ##### [\_buildTransport()](#_buildTransport()) protected static
Finds and builds the instance of the required tranport class.
* ##### [configured()](#configured()) public static
Returns an array containing the named configurations
* ##### [drop()](#drop()) public static
Drops a constructed adapter.
* ##### [get()](#get()) public static
Get transport instance.
* ##### [getConfig()](#getConfig()) public static
Reads existing configuration.
* ##### [getConfigOrFail()](#getConfigOrFail()) public static
Reads existing configuration for a specific key.
* ##### [getDsnClassMap()](#getDsnClassMap()) public static
Returns the DSN class map for this class.
* ##### [getRegistry()](#getRegistry()) public static
Returns the Transport Registry used for creating and using transport instances.
* ##### [parseDsn()](#parseDsn()) public static
Parses a DSN into a valid connection configuration
* ##### [setConfig()](#setConfig()) public static
This method can be used to define configuration adapters for an application.
* ##### [setDsnClassMap()](#setDsnClassMap()) public static
Updates the DSN class map for this class.
* ##### [setRegistry()](#setRegistry()) public static
Sets the Transport Registry instance used for creating and using transport instances.
Method Detail
-------------
### \_buildTransport() protected static
```
_buildTransport(string $name): void
```
Finds and builds the instance of the required tranport class.
#### Parameters
`string` $name Name of the config array that needs a tranport instance built
#### Returns
`void`
#### Throws
`InvalidArgumentException`
When a tranport cannot be created. ### configured() public static
```
configured(): array<string>
```
Returns an array containing the named configurations
#### Returns
`array<string>`
### drop() public static
```
drop(string $config): bool
```
Drops a constructed adapter.
If you wish to modify an existing configuration, you should drop it, change configuration and then re-add it.
If the implementing objects supports a `$_registry` object the named configuration will also be unloaded from the registry.
#### Parameters
`string` $config An existing configuration you wish to remove.
#### Returns
`bool`
### get() public static
```
get(string $name): Cake\Mailer\AbstractTransport
```
Get transport instance.
#### Parameters
`string` $name Config name.
#### Returns
`Cake\Mailer\AbstractTransport`
### getConfig() public static
```
getConfig(string $key): mixed|null
```
Reads existing configuration.
#### Parameters
`string` $key The name of the configuration.
#### Returns
`mixed|null`
### getConfigOrFail() public static
```
getConfigOrFail(string $key): mixed
```
Reads existing configuration for a specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The name of the configuration.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
If value does not exist. ### getDsnClassMap() public static
```
getDsnClassMap(): array<string, string>
```
Returns the DSN class map for this class.
#### Returns
`array<string, string>`
### getRegistry() public static
```
getRegistry(): Cake\Mailer\TransportRegistry
```
Returns the Transport Registry used for creating and using transport instances.
#### Returns
`Cake\Mailer\TransportRegistry`
### parseDsn() public static
```
parseDsn(string $dsn): array<string, mixed>
```
Parses a DSN into a valid connection configuration
This method allows setting a DSN using formatting similar to that used by PEAR::DB. The following is an example of its usage:
```
$dsn = 'mysql://user:pass@localhost/database?';
$config = ConnectionManager::parseDsn($dsn);
$dsn = 'Cake\Log\Engine\FileLog://?types=notice,info,debug&file=debug&path=LOGS';
$config = Log::parseDsn($dsn);
$dsn = 'smtp://user:secret@localhost:25?timeout=30&client=null&tls=null';
$config = Email::parseDsn($dsn);
$dsn = 'file:///?className=\My\Cache\Engine\FileEngine';
$config = Cache::parseDsn($dsn);
$dsn = 'File://?prefix=myapp_cake_core_&serialize=true&duration=+2 minutes&path=/tmp/persistent/';
$config = Cache::parseDsn($dsn);
```
For all classes, the value of `scheme` is set as the value of both the `className` unless they have been otherwise specified.
Note that querystring arguments are also parsed and set as values in the returned configuration.
#### Parameters
`string` $dsn The DSN string to convert to a configuration array
#### Returns
`array<string, mixed>`
#### Throws
`InvalidArgumentException`
If not passed a string, or passed an invalid string ### setConfig() public static
```
setConfig(array<string, mixed>|string $key, object|array<string, mixed>|null $config = null): void
```
This method can be used to define configuration adapters for an application.
To change an adapter's configuration at runtime, first drop the adapter and then reconfigure it.
Adapters will not be constructed until the first operation is done.
### Usage
Assuming that the class' name is `Cache` the following scenarios are supported:
Setting a cache engine up.
```
Cache::setConfig('default', $settings);
```
Injecting a constructed adapter in:
```
Cache::setConfig('default', $instance);
```
Configure multiple adapters at once:
```
Cache::setConfig($arrayOfConfig);
```
#### Parameters
`array<string, mixed>|string` $key The name of the configuration, or an array of multiple configs.
`object|array<string, mixed>|null` $config optional An array of name => configuration data for adapter.
#### Returns
`void`
#### Throws
`BadMethodCallException`
When trying to modify an existing config.
`LogicException`
When trying to store an invalid structured config array. ### setDsnClassMap() public static
```
setDsnClassMap(array<string, string> $map): void
```
Updates the DSN class map for this class.
#### Parameters
`array<string, string>` $map Additions/edits to the class map to apply.
#### Returns
`void`
### setRegistry() public static
```
setRegistry(Cake\Mailer\TransportRegistry $registry): void
```
Sets the Transport Registry instance used for creating and using transport instances.
Also allows for injecting of a new registry instance.
#### Parameters
`Cake\Mailer\TransportRegistry` $registry Injectable registry object.
#### Returns
`void`
Property Detail
---------------
### $\_config protected static
Configuration sets.
#### Type
`array<string, mixed>`
### $\_dsnClassMap protected static
An array mapping url schemes to fully qualified Transport class names
#### Type
`array<string, string>`
### $\_registry protected static
Transport Registry used for creating and using transport instances.
#### Type
`Cake\Mailer\TransportRegistry|null`
cakephp Class CacheClearallCommand Class CacheClearallCommand
===========================
CacheClearall command.
**Namespace:** [Cake\Command](namespace-cake.command)
Constants
---------
* `int` **CODE\_ERROR**
```
1
```
Default error code
* `int` **CODE\_SUCCESS**
```
0
```
Default success code
Property Summary
----------------
* [$\_modelFactories](#%24_modelFactories) protected `array<callableCake\Datasource\Locator\LocatorInterface>` A list of overridden model factory functions.
* [$\_modelType](#%24_modelType) protected `string` The model type to use.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
* [$modelClass](#%24modelClass) protected deprecated `string|null` This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
* [$name](#%24name) protected `string` The name of this command.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_setModelClass()](#_setModelClass()) protected
Set the modelClass property based on conventions.
* ##### [abort()](#abort()) public
Halt the the current process with a StopException.
* ##### [buildOptionParser()](#buildOptionParser()) public
Hook method for defining this command's option parser.
* ##### [defaultName()](#defaultName()) public static
Get the command name.
* ##### [displayHelp()](#displayHelp()) protected
Output help content
* ##### [execute()](#execute()) public
Implement this method with your command's logic.
* ##### [executeCommand()](#executeCommand()) public
Execute another command with the provided set of arguments.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getDescription()](#getDescription()) public static
Get the command description.
* ##### [getModelType()](#getModelType()) public
Get the model type to be used by this class
* ##### [getName()](#getName()) public
Get the command name.
* ##### [getOptionParser()](#getOptionParser()) public
Get the option parser.
* ##### [getRootName()](#getRootName()) public
Get the root command name.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [initialize()](#initialize()) public
Hook method invoked by CakePHP when a command is about to be executed.
* ##### [loadModel()](#loadModel()) public deprecated
Loads and constructs repository objects required by this object
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [modelFactory()](#modelFactory()) public
Override a existing callable to generate repositories of a given type.
* ##### [run()](#run()) public
Run the command.
* ##### [setModelType()](#setModelType()) public
Set the model type to be used by this class
* ##### [setName()](#setName()) public
Set the name this command uses in the collection.
* ##### [setOutputLevel()](#setOutputLevel()) protected
Set the output level based on the Arguments.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
Method Detail
-------------
### \_\_construct() public
```
__construct()
```
Constructor
By default CakePHP will construct command objects when building the CommandCollection for your application.
### \_setModelClass() protected
```
_setModelClass(string $name): void
```
Set the modelClass property based on conventions.
If the property is already set it will not be overwritten
#### Parameters
`string` $name Class name.
#### Returns
`void`
### abort() public
```
abort(int $code = self::CODE_ERROR): void
```
Halt the the current process with a StopException.
#### Parameters
`int` $code optional The exit code to use.
#### Returns
`void`
#### Throws
`Cake\Console\Exception\StopException`
### buildOptionParser() public
```
buildOptionParser(Cake\Console\ConsoleOptionParser $parser): Cake\Console\ConsoleOptionParser
```
Hook method for defining this command's option parser.
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The parser to be defined
#### Returns
`Cake\Console\ConsoleOptionParser`
#### See Also
https://book.cakephp.org/4/en/console-commands/option-parsers.html ### defaultName() public static
```
defaultName(): string
```
Get the command name.
Returns the command name based on class name. For e.g. for a command with class name `UpdateTableCommand` the default name returned would be `'update_table'`.
#### Returns
`string`
### displayHelp() protected
```
displayHelp(Cake\Console\ConsoleOptionParser $parser, Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Output help content
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser.
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### execute() public
```
execute(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): int|null
```
Implement this method with your command's logic.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`int|null`
### executeCommand() public
```
executeCommand(Cake\Console\CommandInterface|string $command, array $args = [], Cake\Console\ConsoleIo|null $io = null): int|null
```
Execute another command with the provided set of arguments.
If you are using a string command name, that command's dependencies will not be resolved with the application container. Instead you will need to pass the command as an object with all of its dependencies.
#### Parameters
`Cake\Console\CommandInterface|string` $command The command class name or command instance.
`array` $args optional The arguments to invoke the command with.
`Cake\Console\ConsoleIo|null` $io optional The ConsoleIo instance to use for the executed command.
#### Returns
`int|null`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getDescription() public static
```
getDescription(): string
```
Get the command description.
#### Returns
`string`
### getModelType() public
```
getModelType(): string
```
Get the model type to be used by this class
#### Returns
`string`
### getName() public
```
getName(): string
```
Get the command name.
#### Returns
`string`
### getOptionParser() public
```
getOptionParser(): Cake\Console\ConsoleOptionParser
```
Get the option parser.
You can override buildOptionParser() to define your options & arguments.
#### Returns
`Cake\Console\ConsoleOptionParser`
#### Throws
`RuntimeException`
When the parser is invalid ### getRootName() public
```
getRootName(): string
```
Get the root command name.
#### Returns
`string`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### initialize() public
```
initialize(): void
```
Hook method invoked by CakePHP when a command is about to be executed.
Override this method and implement expensive/important setup steps that should not run on every command run. This method will be called *before* the options and arguments are validated and processed.
#### Returns
`void`
### loadModel() public
```
loadModel(string|null $modelClass = null, string|null $modelType = null): Cake\Datasource\RepositoryInterface
```
Loads and constructs repository objects required by this object
Typically used to load ORM Table objects as required. Can also be used to load other types of repository objects your application uses.
If a repository provider does not return an object a MissingModelException will be thrown.
#### Parameters
`string|null` $modelClass optional Name of model class to load. Defaults to $this->modelClass. The name can be an alias like `'Post'` or FQCN like `App\Model\Table\PostsTable::class`.
`string|null` $modelType optional The type of repository to load. Defaults to the getModelType() value.
#### Returns
`Cake\Datasource\RepositoryInterface`
#### Throws
`Cake\Datasource\Exception\MissingModelException`
If the model class cannot be found.
`UnexpectedValueException`
If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty. ### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### modelFactory() public
```
modelFactory(string $type, Cake\Datasource\Locator\LocatorInterface|callable $factory): void
```
Override a existing callable to generate repositories of a given type.
#### Parameters
`string` $type The name of the repository type the factory function is for.
`Cake\Datasource\Locator\LocatorInterface|callable` $factory The factory function used to create instances.
#### Returns
`void`
### run() public
```
run(array $argv, Cake\Console\ConsoleIo $io): int|null
```
Run the command.
#### Parameters
`array` $argv `Cake\Console\ConsoleIo` $io #### Returns
`int|null`
### setModelType() public
```
setModelType(string $modelType): $this
```
Set the model type to be used by this class
#### Parameters
`string` $modelType The model type
#### Returns
`$this`
### setName() public
```
setName(string $name): $this
```
Set the name this command uses in the collection.
Generally invoked by the CommandCollection when the command is added. Required to have at least one space in the name so that the root command can be calculated.
#### Parameters
`string` $name #### Returns
`$this`
### setOutputLevel() protected
```
setOutputLevel(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Set the output level based on the Arguments.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
Property Detail
---------------
### $\_modelFactories protected
A list of overridden model factory functions.
#### Type
`array<callableCake\Datasource\Locator\LocatorInterface>`
### $\_modelType protected
The model type to use.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
### $modelClass protected deprecated
This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
Example: For an object named 'Comments', the modelClass would be 'Comments'. Plugin classes should use `Plugin.Comments` style names to correctly load models from the correct plugin.
Use empty string to not use auto-loading on this object. Null auto-detects based on controller name.
#### Type
`string|null`
### $name protected
The name of this command.
#### Type
`string`
| programming_docs |
cakephp Class I18n Class I18n
===========
I18n handles translation of Text and time format strings.
**Namespace:** [Cake\I18n](namespace-cake.i18n)
Constants
---------
* `string` **DEFAULT\_LOCALE**
```
'en_US'
```
Default locale
Property Summary
----------------
* [$\_collection](#%24_collection) protected static `Cake\I18n\TranslatorRegistry|null` The translators collection
* [$\_defaultLocale](#%24_defaultLocale) protected static `string|null` The environment default locale
Method Summary
--------------
* ##### [clear()](#clear()) public static
Destroys all translator instances and creates a new empty translations collection.
* ##### [config()](#config()) public static
Registers a callable object that can be used for creating new translator instances for the same translations domain. Loaders will be invoked whenever a translator object is requested for a domain that has not been configured or loaded already.
* ##### [getDefaultFormatter()](#getDefaultFormatter()) public static
Returns the currently configured default formatter.
* ##### [getDefaultLocale()](#getDefaultLocale()) public static
Returns the default locale.
* ##### [getLocale()](#getLocale()) public static
Will return the currently configure locale as stored in the `intl.default_locale` PHP setting.
* ##### [getTranslator()](#getTranslator()) public static
Returns an instance of a translator that was configured for the name and locale.
* ##### [setDefaultFormatter()](#setDefaultFormatter()) public static
Sets the name of the default messages formatter to use for future translator instances. By default, the `default` and `sprintf` formatters are available.
* ##### [setLocale()](#setLocale()) public static
Sets the default locale to use for future translator instances. This also affects the `intl.default_locale` PHP setting.
* ##### [setTranslator()](#setTranslator()) public static
Sets a translator.
* ##### [translators()](#translators()) public static
Returns the translators collection instance. It can be used for getting specific translators based of their name and locale or to configure some aspect of future translations that are not yet constructed.
* ##### [useFallback()](#useFallback()) public static
Set if the domain fallback is used.
Method Detail
-------------
### clear() public static
```
clear(): void
```
Destroys all translator instances and creates a new empty translations collection.
#### Returns
`void`
### config() public static
```
config(string $name, callable $loader): void
```
Registers a callable object that can be used for creating new translator instances for the same translations domain. Loaders will be invoked whenever a translator object is requested for a domain that has not been configured or loaded already.
Registering loaders is useful when you need to lazily use translations in multiple different locales for the same domain, and don't want to use the built-in translation service based of `gettext` files.
Loader objects will receive two arguments: The domain name that needs to be built, and the locale that is requested. These objects can assemble the messages from any source, but must return an `Cake\I18n\Package` object.
### Example:
```
use Cake\I18n\MessagesFileLoader;
I18n::config('my_domain', function ($name, $locale) {
// Load resources/locales/$locale/filename.po
$fileLoader = new MessagesFileLoader('filename', $locale, 'po');
return $fileLoader();
});
```
You can also assemble the package object yourself:
```
use Cake\I18n\Package;
I18n::config('my_domain', function ($name, $locale) {
$package = new Package('default');
$messages = (...); // Fetch messages for locale from external service.
$package->setMessages($message);
$package->setFallback('default');
return $package;
});
```
#### Parameters
`string` $name The name of the translator to create a loader for
`callable` $loader A callable object that should return a Package instance to be used for assembling a new translator.
#### Returns
`void`
### getDefaultFormatter() public static
```
getDefaultFormatter(): string
```
Returns the currently configured default formatter.
#### Returns
`string`
### getDefaultLocale() public static
```
getDefaultLocale(): string
```
Returns the default locale.
This returns the default locale before any modifications, i.e. the value as stored in the `intl.default_locale` PHP setting before any manipulation by this class.
#### Returns
`string`
### getLocale() public static
```
getLocale(): string
```
Will return the currently configure locale as stored in the `intl.default_locale` PHP setting.
#### Returns
`string`
### getTranslator() public static
```
getTranslator(string $name = 'default', string|null $locale = null): Cake\I18n\Translator
```
Returns an instance of a translator that was configured for the name and locale.
If no locale is passed then it takes the value returned by the `getLocale()` method.
#### Parameters
`string` $name optional The domain of the translation messages.
`string|null` $locale optional The locale for the translator.
#### Returns
`Cake\I18n\Translator`
#### Throws
`Cake\I18n\Exception\I18nException`
### setDefaultFormatter() public static
```
setDefaultFormatter(string $name): void
```
Sets the name of the default messages formatter to use for future translator instances. By default, the `default` and `sprintf` formatters are available.
#### Parameters
`string` $name The name of the formatter to use.
#### Returns
`void`
### setLocale() public static
```
setLocale(string $locale): void
```
Sets the default locale to use for future translator instances. This also affects the `intl.default_locale` PHP setting.
#### Parameters
`string` $locale The name of the locale to set as default.
#### Returns
`void`
### setTranslator() public static
```
setTranslator(string $name, callable $loader, string|null $locale = null): void
```
Sets a translator.
Configures future translators, this is achieved by passing a callable as the last argument of this function.
### Example:
```
I18n::setTranslator('default', function () {
$package = new \Cake\I18n\Package();
$package->setMessages([
'Cake' => 'Gâteau'
]);
return $package;
}, 'fr_FR');
$translator = I18n::getTranslator('default', 'fr_FR');
echo $translator->translate('Cake');
```
You can also use the `Cake\I18n\MessagesFileLoader` class to load a specific file from a folder. For example for loading a `my_translations.po` file from the `resources/locales/custom` folder, you would do:
```
I18n::setTranslator(
'default',
new MessagesFileLoader('my_translations', 'custom', 'po'),
'fr_FR'
);
```
#### Parameters
`string` $name The domain of the translation messages.
`callable` $loader A callback function or callable class responsible for constructing a translations package instance.
`string|null` $locale optional The locale for the translator.
#### Returns
`void`
### translators() public static
```
translators(): Cake\I18n\TranslatorRegistry
```
Returns the translators collection instance. It can be used for getting specific translators based of their name and locale or to configure some aspect of future translations that are not yet constructed.
#### Returns
`Cake\I18n\TranslatorRegistry`
### useFallback() public static
```
useFallback(bool $enable = true): void
```
Set if the domain fallback is used.
#### Parameters
`bool` $enable optional flag to enable or disable fallback
#### Returns
`void`
Property Detail
---------------
### $\_collection protected static
The translators collection
#### Type
`Cake\I18n\TranslatorRegistry|null`
### $\_defaultLocale protected static
The environment default locale
#### Type
`string|null`
cakephp Namespace Cookie Namespace Cookie
================
### Interfaces
* ##### [CookieInterface](interface-cake.http.cookie.cookieinterface)
Cookie Interface
### Classes
* ##### [Cookie](class-cake.http.cookie.cookie)
Cookie object to build a cookie and turn it into a header value
* ##### [CookieCollection](class-cake.http.cookie.cookiecollection)
Cookie Collection
cakephp Interface ExpressionTypeInterface Interface ExpressionTypeInterface
==================================
An interface used by Type objects to signal whether the value should be converted to an ExpressionInterface instead of a string when sent to the database.
**Namespace:** [Cake\Database\Type](namespace-cake.database.type)
Method Summary
--------------
* ##### [toExpression()](#toExpression()) public
Returns an ExpressionInterface object for the given value that can be used in queries.
Method Detail
-------------
### toExpression() public
```
toExpression(mixed $value): Cake\Database\ExpressionInterface
```
Returns an ExpressionInterface object for the given value that can be used in queries.
#### Parameters
`mixed` $value The value to be converted to an expression
#### Returns
`Cake\Database\ExpressionInterface`
cakephp Class FloatType Class FloatType
================
Float type converter.
Use to convert float/decimal data between PHP and the database types.
**Namespace:** [Cake\Database\Type](namespace-cake.database.type)
Property Summary
----------------
* [$\_name](#%24_name) protected `string|null` Identifier name for this type
* [$\_useLocaleParser](#%24_useLocaleParser) protected `bool` Whether numbers should be parsed using a locale aware parser when marshalling string inputs.
* [$numberClass](#%24numberClass) public static `string` The class to use for representing number objects
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_parseValue()](#_parseValue()) protected
Converts a string into a float point after parsing it using the locale aware parser.
* ##### [getBaseType()](#getBaseType()) public
Returns the base type name that this class is inheriting.
* ##### [getName()](#getName()) public
Returns type identifier name for this object.
* ##### [manyToPHP()](#manyToPHP()) public
Returns an array of the values converted to the PHP representation of this type.
* ##### [marshal()](#marshal()) public
Marshals request data into PHP floats.
* ##### [newId()](#newId()) public
Generate a new primary key value for a given type.
* ##### [toDatabase()](#toDatabase()) public
Convert integer data into the database format.
* ##### [toPHP()](#toPHP()) public
Casts given value from a database type to a PHP equivalent.
* ##### [toStatement()](#toStatement()) public
Get the correct PDO binding type for float data.
* ##### [useLocaleParser()](#useLocaleParser()) public
Sets whether to parse numbers passed to the marshal() function by using a locale aware parser.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $name = null)
```
Constructor
#### Parameters
`string|null` $name optional The name identifying this type
### \_parseValue() protected
```
_parseValue(string $value): float
```
Converts a string into a float point after parsing it using the locale aware parser.
#### Parameters
`string` $value The value to parse and convert to an float.
#### Returns
`float`
### getBaseType() public
```
getBaseType(): string|null
```
Returns the base type name that this class is inheriting.
This is useful when extending base type for adding extra functionality, but still want the rest of the framework to use the same assumptions it would do about the base type it inherits from.
#### Returns
`string|null`
### getName() public
```
getName(): string|null
```
Returns type identifier name for this object.
#### Returns
`string|null`
### manyToPHP() public
```
manyToPHP(array $values, array<string> $fields, Cake\Database\DriverInterface $driver): array<string, mixed>
```
Returns an array of the values converted to the PHP representation of this type.
#### Parameters
`array` $values `array<string>` $fields `Cake\Database\DriverInterface` $driver #### Returns
`array<string, mixed>`
### marshal() public
```
marshal(mixed $value): string|float|null
```
Marshals request data into PHP floats.
Most useful for converting request data into PHP objects, that make sense for the rest of the ORM/Database layers.
#### Parameters
`mixed` $value The value to convert.
#### Returns
`string|float|null`
### newId() public
```
newId(): mixed
```
Generate a new primary key value for a given type.
This method can be used by types to create new primary key values when entities are inserted.
#### Returns
`mixed`
### toDatabase() public
```
toDatabase(mixed $value, Cake\Database\DriverInterface $driver): float|null
```
Convert integer data into the database format.
#### Parameters
`mixed` $value The value to convert.
`Cake\Database\DriverInterface` $driver The driver instance to convert with.
#### Returns
`float|null`
### toPHP() public
```
toPHP(mixed $value, Cake\Database\DriverInterface $driver): float|null
```
Casts given value from a database type to a PHP equivalent.
#### Parameters
`mixed` $value The value to convert.
`Cake\Database\DriverInterface` $driver The driver instance to convert with.
#### Returns
`float|null`
#### Throws
`Cake\Core\Exception\CakeException`
### toStatement() public
```
toStatement(mixed $value, Cake\Database\DriverInterface $driver): int
```
Get the correct PDO binding type for float data.
#### Parameters
`mixed` $value The value being bound.
`Cake\Database\DriverInterface` $driver The driver.
#### Returns
`int`
### useLocaleParser() public
```
useLocaleParser(bool $enable = true): $this
```
Sets whether to parse numbers passed to the marshal() function by using a locale aware parser.
#### Parameters
`bool` $enable optional Whether to enable
#### Returns
`$this`
Property Detail
---------------
### $\_name protected
Identifier name for this type
#### Type
`string|null`
### $\_useLocaleParser protected
Whether numbers should be parsed using a locale aware parser when marshalling string inputs.
#### Type
`bool`
### $numberClass public static
The class to use for representing number objects
#### Type
`string`
cakephp Class Connection Class Connection
=================
Represents a connection with a database server.
**Namespace:** [Cake\Database](namespace-cake.database)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Contains the configuration params for this connection.
* [$\_driver](#%24_driver) protected `Cake\Database\DriverInterface` Driver object, responsible for creating the real connection and provide specific SQL dialect.
* [$\_logQueries](#%24_logQueries) protected `bool` Whether to log queries generated during this connection.
* [$\_logger](#%24_logger) protected `Psr\Log\LoggerInterface|null` Logger object instance.
* [$\_schemaCollection](#%24_schemaCollection) protected `Cake\Database\Schema\CollectionInterface|null` The schema collection object
* [$\_transactionLevel](#%24_transactionLevel) protected `int` Contains how many nested transactions have been started.
* [$\_transactionStarted](#%24_transactionStarted) protected `bool` Whether a transaction is active in this connection.
* [$\_useSavePoints](#%24_useSavePoints) protected `bool` Whether this connection can and should use savepoints for nested transactions.
* [$cacher](#%24cacher) protected `Psr\SimpleCache\CacheInterface|null` Cacher object instance.
* [$nestedTransactionRollbackException](#%24nestedTransactionRollbackException) protected `Cake\Database\Exception\NestedTransactionRollbackException|null` NestedTransactionRollbackException object instance, will be stored if the rollback method is called in some nested transaction.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_destruct()](#__destruct()) public
Destructor
* ##### [\_newLogger()](#_newLogger()) protected
Returns a new statement object that will log the activity for the passed original statement instance.
* ##### [begin()](#begin()) public
Starts a new transaction.
* ##### [cacheMetadata()](#cacheMetadata()) public
Enables or disables metadata caching for this connection
* ##### [cast()](#cast()) public
Converts a give value to a suitable database value based on type and return relevant internal statement type
* ##### [commit()](#commit()) public
Commits current transaction.
* ##### [compileQuery()](#compileQuery()) public
Compiles a Query object into a SQL string according to the dialect for this connection's driver
* ##### [config()](#config()) public
Get the configuration data used to create the connection.
* ##### [configName()](#configName()) public
Get the configuration name for this connection.
* ##### [connect()](#connect()) public
Connects to the configured database.
* ##### [createDriver()](#createDriver()) protected
Creates driver from name, class name or instance.
* ##### [createSavePoint()](#createSavePoint()) public
Creates a new save point for nested transactions.
* ##### [delete()](#delete()) public
Executes a DELETE statement on the specified table.
* ##### [disableConstraints()](#disableConstraints()) public
Run an operation with constraints disabled.
* ##### [disableForeignKeys()](#disableForeignKeys()) public
Run driver specific SQL to disable foreign key checks.
* ##### [disableQueryLogging()](#disableQueryLogging()) public
Disable query logging
* ##### [disableSavePoints()](#disableSavePoints()) public
Disables the usage of savepoints.
* ##### [disconnect()](#disconnect()) public
Disconnects from database server.
* ##### [enableForeignKeys()](#enableForeignKeys()) public
Run driver specific SQL to enable foreign key checks.
* ##### [enableQueryLogging()](#enableQueryLogging()) public
Enable/disable query logging
* ##### [enableSavePoints()](#enableSavePoints()) public
Enables/disables the usage of savepoints, enables only if driver the allows it.
* ##### [execute()](#execute()) public
Executes a query using $params for interpolating values and $types as a hint for each those params.
* ##### [getCacher()](#getCacher()) public
Get a cacher.
* ##### [getDisconnectRetry()](#getDisconnectRetry()) public
Get the retry wrapper object that is allows recovery from server disconnects while performing certain database actions, such as executing a query.
* ##### [getDriver()](#getDriver()) public
Gets the driver instance.
* ##### [getLogger()](#getLogger()) public
Gets the logger object
* ##### [getSchemaCollection()](#getSchemaCollection()) public
Gets a Schema\Collection object for this connection.
* ##### [inTransaction()](#inTransaction()) public
Checks if a transaction is running.
* ##### [insert()](#insert()) public
Executes an INSERT query on the specified table.
* ##### [isConnected()](#isConnected()) public
Returns whether connection to database server was already established.
* ##### [isQueryLoggingEnabled()](#isQueryLoggingEnabled()) public
Check if query logging is enabled.
* ##### [isSavePointsEnabled()](#isSavePointsEnabled()) public
Returns whether this connection is using savepoints for nested transactions
* ##### [log()](#log()) public
Logs a Query string using the configured logger object.
* ##### [matchTypes()](#matchTypes()) public
Matches columns to corresponding types
* ##### [newQuery()](#newQuery()) public
Create a new Query instance for this connection.
* ##### [prepare()](#prepare()) public
Prepares a SQL statement to be executed.
* ##### [query()](#query()) public
Executes a SQL statement and returns the Statement object as result.
* ##### [quote()](#quote()) public
Quotes value to be used safely in database query.
* ##### [quoteIdentifier()](#quoteIdentifier()) public
Quotes a database identifier (a column name, table name, etc..) to be used safely in queries without the risk of using reserved words.
* ##### [releaseSavePoint()](#releaseSavePoint()) public
Releases a save point by its name.
* ##### [rollback()](#rollback()) public
Rollback current transaction.
* ##### [rollbackSavepoint()](#rollbackSavepoint()) public
Rollback a save point by its name.
* ##### [run()](#run()) public
Executes the provided query after compiling it for the specific driver dialect and returns the executed Statement object.
* ##### [setCacher()](#setCacher()) public
Set a cacher.
* ##### [setDriver()](#setDriver()) public deprecated
Sets the driver instance. If a string is passed it will be treated as a class name and will be instantiated.
* ##### [setLogger()](#setLogger()) public
Sets a logger
* ##### [setSchemaCollection()](#setSchemaCollection()) public
Sets a Schema\Collection object for this connection.
* ##### [supportsDynamicConstraints()](#supportsDynamicConstraints()) public deprecated
Returns whether the driver supports adding or dropping constraints to already created tables.
* ##### [supportsQuoting()](#supportsQuoting()) public
Checks if using `quote()` is supported.
* ##### [transactional()](#transactional()) public
Executes a callable function inside a transaction, if any exception occurs while executing the passed callable, the transaction will be rolled back If the result of the callable function is `false`, the transaction will also be rolled back. Otherwise, the transaction is committed after executing the callback.
* ##### [update()](#update()) public
Executes an UPDATE statement on the specified table.
* ##### [wasNestedTransactionRolledback()](#wasNestedTransactionRolledback()) protected
Returns whether some nested transaction has been already rolled back.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config)
```
Constructor.
### Available options:
* `driver` Sort name or FCQN for driver.
* `log` Boolean indicating whether to use query logging.
* `name` Connection name.
* `cacheMetaData` Boolean indicating whether metadata (datasource schemas) should be cached. If set to a string it will be used as the name of cache config to use.
* `cacheKeyPrefix` Custom prefix to use when generation cache keys. Defaults to connection name.
#### Parameters
`array<string, mixed>` $config Configuration array.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_destruct() public
```
__destruct()
```
Destructor
Disconnects the driver to release the connection.
### \_newLogger() protected
```
_newLogger(Cake\Database\StatementInterface $statement): Cake\Database\Log\LoggingStatement
```
Returns a new statement object that will log the activity for the passed original statement instance.
#### Parameters
`Cake\Database\StatementInterface` $statement the instance to be decorated
#### Returns
`Cake\Database\Log\LoggingStatement`
### begin() public
```
begin(): void
```
Starts a new transaction.
#### Returns
`void`
### cacheMetadata() public
```
cacheMetadata(string|bool $cache): void
```
Enables or disables metadata caching for this connection
Changing this setting will not modify existing schema collections objects.
#### Parameters
`string|bool` $cache Either boolean false to disable metadata caching, or true to use `_cake_model_` or the name of the cache config to use.
#### Returns
`void`
### cast() public
```
cast(mixed $value, Cake\Database\TypeInterface|string|int $type = 'string'): array
```
Converts a give value to a suitable database value based on type and return relevant internal statement type
#### Parameters
`mixed` $value The value to cast
`Cake\Database\TypeInterface|string|int` $type optional The type name or type instance to use.
#### Returns
`array`
### commit() public
```
commit(): bool
```
Commits current transaction.
#### Returns
`bool`
### compileQuery() public
```
compileQuery(Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Compiles a Query object into a SQL string according to the dialect for this connection's driver
#### Parameters
`Cake\Database\Query` $query The query to be compiled
`Cake\Database\ValueBinder` $binder Value binder
#### Returns
`string`
### config() public
```
config(): array<string, mixed>
```
Get the configuration data used to create the connection.
#### Returns
`array<string, mixed>`
### configName() public
```
configName(): string
```
Get the configuration name for this connection.
#### Returns
`string`
### connect() public
```
connect(): bool
```
Connects to the configured database.
#### Returns
`bool`
#### Throws
`Cake\Database\Exception\MissingConnectionException`
If database connection could not be established. ### createDriver() protected
```
createDriver(Cake\Database\DriverInterface|string $name, array $config): Cake\Database\DriverInterface
```
Creates driver from name, class name or instance.
#### Parameters
`Cake\Database\DriverInterface|string` $name Driver name, class name or instance.
`array` $config Driver config if $name is not an instance.
#### Returns
`Cake\Database\DriverInterface`
#### Throws
`Cake\Database\Exception\MissingDriverException`
When a driver class is missing.
`Cake\Database\Exception\MissingExtensionException`
When a driver's PHP extension is missing. ### createSavePoint() public
```
createSavePoint(string|int $name): void
```
Creates a new save point for nested transactions.
#### Parameters
`string|int` $name Save point name or id
#### Returns
`void`
### delete() public
```
delete(string $table, array $conditions = [], array<string> $types = []): Cake\Database\StatementInterface
```
Executes a DELETE statement on the specified table.
#### Parameters
`string` $table the table to delete rows from
`array` $conditions optional conditions to be set for delete statement
`array<string>` $types optional list of associative array containing the types to be used for casting
#### Returns
`Cake\Database\StatementInterface`
### disableConstraints() public
```
disableConstraints(callable $callback): mixed
```
Run an operation with constraints disabled.
Constraints should be re-enabled after the callback succeeds/fails.
### Example:
```
$connection->disableConstraints(function ($connection) {
$connection->newQuery()->delete('users')->execute();
});
```
#### Parameters
`callable` $callback #### Returns
`mixed`
### disableForeignKeys() public
```
disableForeignKeys(): void
```
Run driver specific SQL to disable foreign key checks.
#### Returns
`void`
### disableQueryLogging() public
```
disableQueryLogging(): $this
```
Disable query logging
#### Returns
`$this`
### disableSavePoints() public
```
disableSavePoints(): $this
```
Disables the usage of savepoints.
#### Returns
`$this`
### disconnect() public
```
disconnect(): void
```
Disconnects from database server.
#### Returns
`void`
### enableForeignKeys() public
```
enableForeignKeys(): void
```
Run driver specific SQL to enable foreign key checks.
#### Returns
`void`
### enableQueryLogging() public
```
enableQueryLogging(bool $enable = true): $this
```
Enable/disable query logging
#### Parameters
`bool` $enable optional Enable/disable query logging
#### Returns
`$this`
### enableSavePoints() public
```
enableSavePoints(bool $enable = true): $this
```
Enables/disables the usage of savepoints, enables only if driver the allows it.
If you are trying to enable this feature, make sure you check `isSavePointsEnabled()` to verify that savepoints were enabled successfully.
#### Parameters
`bool` $enable optional Whether save points should be used.
#### Returns
`$this`
### execute() public
```
execute(string $sql, array $params = [], array $types = []): Cake\Database\StatementInterface
```
Executes a query using $params for interpolating values and $types as a hint for each those params.
#### Parameters
`string` $sql SQL to be executed and interpolated with $params
`array` $params optional list or associative array of params to be interpolated in $sql as values
`array` $types optional list or associative array of types to be used for casting values in query
#### Returns
`Cake\Database\StatementInterface`
### getCacher() public
```
getCacher(): Psr\SimpleCache\CacheInterface
```
Get a cacher.
#### Returns
`Psr\SimpleCache\CacheInterface`
### getDisconnectRetry() public
```
getDisconnectRetry(): Cake\Core\Retry\CommandRetry
```
Get the retry wrapper object that is allows recovery from server disconnects while performing certain database actions, such as executing a query.
#### Returns
`Cake\Core\Retry\CommandRetry`
### getDriver() public
```
getDriver(): Cake\Database\DriverInterface
```
Gets the driver instance.
#### Returns
`Cake\Database\DriverInterface`
### getLogger() public
```
getLogger(): Psr\Log\LoggerInterface
```
Gets the logger object
#### Returns
`Psr\Log\LoggerInterface`
### getSchemaCollection() public
```
getSchemaCollection(): Cake\Database\Schema\CollectionInterface
```
Gets a Schema\Collection object for this connection.
#### Returns
`Cake\Database\Schema\CollectionInterface`
### inTransaction() public
```
inTransaction(): bool
```
Checks if a transaction is running.
#### Returns
`bool`
### insert() public
```
insert(string $table, array $values, array<int|string, string> $types = []): Cake\Database\StatementInterface
```
Executes an INSERT query on the specified table.
#### Parameters
`string` $table the table to insert values in
`array` $values values to be inserted
`array<int|string, string>` $types optional Array containing the types to be used for casting
#### Returns
`Cake\Database\StatementInterface`
### isConnected() public
```
isConnected(): bool
```
Returns whether connection to database server was already established.
#### Returns
`bool`
### isQueryLoggingEnabled() public
```
isQueryLoggingEnabled(): bool
```
Check if query logging is enabled.
#### Returns
`bool`
### isSavePointsEnabled() public
```
isSavePointsEnabled(): bool
```
Returns whether this connection is using savepoints for nested transactions
#### Returns
`bool`
### log() public
```
log(string $sql): void
```
Logs a Query string using the configured logger object.
#### Parameters
`string` $sql string to be logged
#### Returns
`void`
### matchTypes() public
```
matchTypes(array $columns, array $types): array
```
Matches columns to corresponding types
Both $columns and $types should either be numeric based or string key based at the same time.
#### Parameters
`array` $columns list or associative array of columns and parameters to be bound with types
`array` $types list or associative array of types
#### Returns
`array`
### newQuery() public
```
newQuery(): Cake\Database\Query
```
Create a new Query instance for this connection.
#### Returns
`Cake\Database\Query`
### prepare() public
```
prepare(Cake\Database\Query|string $query): Cake\Database\StatementInterface
```
Prepares a SQL statement to be executed.
#### Parameters
`Cake\Database\Query|string` $query The SQL to convert into a prepared statement.
#### Returns
`Cake\Database\StatementInterface`
### query() public
```
query(string $sql): Cake\Database\StatementInterface
```
Executes a SQL statement and returns the Statement object as result.
#### Parameters
`string` $sql The SQL query to execute.
#### Returns
`Cake\Database\StatementInterface`
### quote() public
```
quote(mixed $value, Cake\Database\TypeInterface|string|int $type = 'string'): string
```
Quotes value to be used safely in database query.
This uses `PDO::quote()` and requires `supportsQuoting()` to work.
#### Parameters
`mixed` $value The value to quote.
`Cake\Database\TypeInterface|string|int` $type optional Type to be used for determining kind of quoting to perform
#### Returns
`string`
### quoteIdentifier() public
```
quoteIdentifier(string $identifier): string
```
Quotes a database identifier (a column name, table name, etc..) to be used safely in queries without the risk of using reserved words.
This does not require `supportsQuoting()` to work.
#### Parameters
`string` $identifier The identifier to quote.
#### Returns
`string`
### releaseSavePoint() public
```
releaseSavePoint(string|int $name): void
```
Releases a save point by its name.
#### Parameters
`string|int` $name Save point name or id
#### Returns
`void`
### rollback() public
```
rollback(bool|null $toBeginning = null): bool
```
Rollback current transaction.
#### Parameters
`bool|null` $toBeginning optional Whether the transaction should be rolled back to the beginning of it. Defaults to false if using savepoints, or true if not.
#### Returns
`bool`
### rollbackSavepoint() public
```
rollbackSavepoint(string|int $name): void
```
Rollback a save point by its name.
#### Parameters
`string|int` $name Save point name or id
#### Returns
`void`
### run() public
```
run(Cake\Database\Query $query): Cake\Database\StatementInterface
```
Executes the provided query after compiling it for the specific driver dialect and returns the executed Statement object.
#### Parameters
`Cake\Database\Query` $query The query to be executed
#### Returns
`Cake\Database\StatementInterface`
### setCacher() public
```
setCacher(Psr\SimpleCache\CacheInterface $cacher): $this
```
Set a cacher.
#### Parameters
`Psr\SimpleCache\CacheInterface` $cacher #### Returns
`$this`
### setDriver() public
```
setDriver(Cake\Database\DriverInterface|string $driver, array<string, mixed> $config = []): $this
```
Sets the driver instance. If a string is passed it will be treated as a class name and will be instantiated.
#### Parameters
`Cake\Database\DriverInterface|string` $driver The driver instance to use.
`array<string, mixed>` $config optional Config for a new driver.
#### Returns
`$this`
#### Throws
`Cake\Database\Exception\MissingDriverException`
When a driver class is missing.
`Cake\Database\Exception\MissingExtensionException`
When a driver's PHP extension is missing. ### setLogger() public
```
setLogger(Psr\Log\LoggerInterface $logger): $this
```
Sets a logger
#### Parameters
`Psr\Log\LoggerInterface` $logger Logger object
#### Returns
`$this`
### setSchemaCollection() public
```
setSchemaCollection(Cake\Database\Schema\CollectionInterface $collection): $this
```
Sets a Schema\Collection object for this connection.
#### Parameters
`Cake\Database\Schema\CollectionInterface` $collection The schema collection object
#### Returns
`$this`
### supportsDynamicConstraints() public
```
supportsDynamicConstraints(): bool
```
Returns whether the driver supports adding or dropping constraints to already created tables.
#### Returns
`bool`
### supportsQuoting() public
```
supportsQuoting(): bool
```
Checks if using `quote()` is supported.
This is not required to use `quoteIdentifier()`.
#### Returns
`bool`
### transactional() public
```
transactional(callable $callback): mixed
```
Executes a callable function inside a transaction, if any exception occurs while executing the passed callable, the transaction will be rolled back If the result of the callable function is `false`, the transaction will also be rolled back. Otherwise, the transaction is committed after executing the callback.
The callback will receive the connection instance as its first argument.
### Example:
```
$connection->transactional(function ($connection) {
$connection->newQuery()->delete('users')->execute();
});
```
#### Parameters
`callable` $callback #### Returns
`mixed`
### update() public
```
update(string $table, array $values, array $conditions = [], array<string> $types = []): Cake\Database\StatementInterface
```
Executes an UPDATE statement on the specified table.
#### Parameters
`string` $table the table to update rows from
`array` $values values to be updated
`array` $conditions optional conditions to be set for update statement
`array<string>` $types optional list of associative array containing the types to be used for casting
#### Returns
`Cake\Database\StatementInterface`
### wasNestedTransactionRolledback() protected
```
wasNestedTransactionRolledback(): bool
```
Returns whether some nested transaction has been already rolled back.
#### Returns
`bool`
Property Detail
---------------
### $\_config protected
Contains the configuration params for this connection.
#### Type
`array<string, mixed>`
### $\_driver protected
Driver object, responsible for creating the real connection and provide specific SQL dialect.
#### Type
`Cake\Database\DriverInterface`
### $\_logQueries protected
Whether to log queries generated during this connection.
#### Type
`bool`
### $\_logger protected
Logger object instance.
#### Type
`Psr\Log\LoggerInterface|null`
### $\_schemaCollection protected
The schema collection object
#### Type
`Cake\Database\Schema\CollectionInterface|null`
### $\_transactionLevel protected
Contains how many nested transactions have been started.
#### Type
`int`
### $\_transactionStarted protected
Whether a transaction is active in this connection.
#### Type
`bool`
### $\_useSavePoints protected
Whether this connection can and should use savepoints for nested transactions.
#### Type
`bool`
### $cacher protected
Cacher object instance.
#### Type
`Psr\SimpleCache\CacheInterface|null`
### $nestedTransactionRollbackException protected
NestedTransactionRollbackException object instance, will be stored if the rollback method is called in some nested transaction.
#### Type
`Cake\Database\Exception\NestedTransactionRollbackException|null`
| programming_docs |
cakephp Class SessionHasKey Class SessionHasKey
====================
SessionHasKey
**Namespace:** [Cake\TestSuite\Constraint\Session](namespace-cake.testsuite.constraint.session)
Property Summary
----------------
* [$path](#%24path) protected `string`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Compare session value
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(string $path)
```
Constructor
#### Parameters
`string` $path Session Path
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Compare session value
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Value to compare with
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $path protected
#### Type
`string`
cakephp Class NestIterator Class NestIterator
===================
A type of collection that is aware of nested items and exposes methods to check or retrieve them
**Namespace:** [Cake\Collection\Iterator](namespace-cake.collection.iterator)
Property Summary
----------------
* [$\_nestKey](#%24_nestKey) protected `callable|string` The name of the property that contains the nested items for each element
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_serialize()](#__serialize()) public
Returns an array for serializing this of this object.
* ##### [\_\_unserialize()](#__unserialize()) public
Rebuilds the Collection instance.
* ##### [\_createMatcherFilter()](#_createMatcherFilter()) protected
Returns a callable that receives a value and will return whether it matches certain condition.
* ##### [\_extract()](#_extract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
* ##### [\_propertyExtractor()](#_propertyExtractor()) protected
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
* ##### [\_simpleExtract()](#_simpleExtract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path
* ##### [append()](#append()) public
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
* ##### [appendItem()](#appendItem()) public
Append a single item creating a new collection.
* ##### [avg()](#avg()) public
Returns the average of all the values extracted with $path or of this collection.
* ##### [buffered()](#buffered()) public
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
* ##### [cartesianProduct()](#cartesianProduct()) public
Create a new collection that is the cartesian product of the current collection
* ##### [chunk()](#chunk()) public
Breaks the collection into smaller arrays of the given size.
* ##### [chunkWithKeys()](#chunkWithKeys()) public
Breaks the collection into smaller arrays of the given size.
* ##### [combine()](#combine()) public
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
* ##### [compile()](#compile()) public
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
* ##### [contains()](#contains()) public
Returns true if $value is present in this collection. Comparisons are made both by value and type.
* ##### [count()](#count()) public
Returns the amount of elements in the collection.
* ##### [countBy()](#countBy()) public
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
* ##### [countKeys()](#countKeys()) public
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
* ##### [each()](#each()) public
Applies a callback to the elements in this collection.
* ##### [every()](#every()) public
Returns true if all values in this collection pass the truth test provided in the callback.
* ##### [extract()](#extract()) public
Returns a new collection containing the column or property value found in each of the elements.
* ##### [filter()](#filter()) public
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
* ##### [first()](#first()) public
Returns the first result in this collection
* ##### [firstMatch()](#firstMatch()) public
Returns the first result matching all the key-value pairs listed in conditions.
* ##### [getChildren()](#getChildren()) public
Returns a traversable containing the children for the current item
* ##### [groupBy()](#groupBy()) public
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
* ##### [hasChildren()](#hasChildren()) public
Returns true if there is an array or a traversable object stored under the configured nestKey for the current item
* ##### [indexBy()](#indexBy()) public
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
* ##### [insert()](#insert()) public
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
* ##### [isEmpty()](#isEmpty()) public
Returns whether there are elements in this collection
* ##### [jsonSerialize()](#jsonSerialize()) public
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
* ##### [last()](#last()) public
Returns the last result in this collection
* ##### [lazy()](#lazy()) public
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
* ##### [listNested()](#listNested()) public
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
* ##### [map()](#map()) public
Returns another collection after modifying each of the values in this one using the provided callable.
* ##### [match()](#match()) public
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
* ##### [max()](#max()) public
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [median()](#median()) public
Returns the median of all the values extracted with $path or of this collection.
* ##### [min()](#min()) public
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [nest()](#nest()) public
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
* ##### [newCollection()](#newCollection()) protected
Returns a new collection.
* ##### [optimizeUnwrap()](#optimizeUnwrap()) protected
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
* ##### [prepend()](#prepend()) public
Prepend a set of items to a collection creating a new collection
* ##### [prependItem()](#prependItem()) public
Prepend a single item creating a new collection.
* ##### [reduce()](#reduce()) public
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
* ##### [reject()](#reject()) public
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
* ##### [sample()](#sample()) public
Returns a new collection with maximum $size random elements from this collection
* ##### [serialize()](#serialize()) public
Returns a string representation of this object that can be used to reconstruct it
* ##### [shuffle()](#shuffle()) public
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
* ##### [skip()](#skip()) public
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
* ##### [some()](#some()) public
Returns true if any of the values in this collection pass the truth test provided in the callback.
* ##### [sortBy()](#sortBy()) public
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
* ##### [stopWhen()](#stopWhen()) public
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
* ##### [sumOf()](#sumOf()) public
Returns the total sum of all the values extracted with $matcher or of this collection.
* ##### [take()](#take()) public
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
* ##### [takeLast()](#takeLast()) public
Returns the last N elements of a collection
* ##### [through()](#through()) public
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
* ##### [toArray()](#toArray()) public
Returns an array representation of the results
* ##### [toList()](#toList()) public
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
* ##### [transpose()](#transpose()) public
Transpose rows and columns into columns and rows
* ##### [unfold()](#unfold()) public
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
* ##### [unserialize()](#unserialize()) public
Unserializes the passed string and rebuilds the Collection instance
* ##### [unwrap()](#unwrap()) public
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
* ##### [zip()](#zip()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
* ##### [zipWith()](#zipWith()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
Method Detail
-------------
### \_\_construct() public
```
__construct(iterable $items, callable|string $nestKey)
```
Constructor
#### Parameters
`iterable` $items Collection items.
`callable|string` $nestKey the property that contains the nested items If a callable is passed, it should return the childrens for the passed item
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_serialize() public
```
__serialize(): array
```
Returns an array for serializing this of this object.
#### Returns
`array`
### \_\_unserialize() public
```
__unserialize(array $data): void
```
Rebuilds the Collection instance.
#### Parameters
`array` $data Data array.
#### Returns
`void`
### \_createMatcherFilter() protected
```
_createMatcherFilter(array $conditions): Closure
```
Returns a callable that receives a value and will return whether it matches certain condition.
#### Parameters
`array` $conditions A key-value list of conditions to match where the key is the property path to get from the current item and the value is the value to be compared the item with.
#### Returns
`Closure`
### \_extract() protected
```
_extract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### \_propertyExtractor() protected
```
_propertyExtractor(callable|string $path): callable
```
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
#### Parameters
`callable|string` $path A dot separated path of column to follow so that the final one can be returned or a callable that will take care of doing that.
#### Returns
`callable`
### \_simpleExtract() protected
```
_simpleExtract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### append() public
```
append(iterable $items): self
```
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
#### Parameters
`iterable` $items #### Returns
`self`
### appendItem() public
```
appendItem(mixed $item, mixed $key = null): self
```
Append a single item creating a new collection.
#### Parameters
`mixed` $item `mixed` $key optional #### Returns
`self`
### avg() public
```
avg(callable|string|null $path = null): float|int|null
```
Returns the average of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->avg('invoice.total');
// Total: 150
$total = (new Collection([1, 2, 3]))->avg();
// Total: 2
```
The average of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int|null`
### buffered() public
```
buffered(): self
```
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
This can also be used to make any non-rewindable iterator rewindable.
#### Returns
`self`
### cartesianProduct() public
```
cartesianProduct(callable|null $operation = null, callable|null $filter = null): Cake\Collection\CollectionInterface
```
Create a new collection that is the cartesian product of the current collection
In order to create a carteisan product a collection must contain a single dimension of data.
### Example
```
$collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
$result = $collection->cartesianProduct()->toArray();
$expected = [
['A', 1],
['A', 2],
['A', 3],
['B', 1],
['B', 2],
['B', 3],
['C', 1],
['C', 2],
['C', 3],
];
```
#### Parameters
`callable|null` $operation optional A callable that allows you to customize the product result.
`callable|null` $filter optional A filtering callback that must return true for a result to be part of the final results.
#### Returns
`Cake\Collection\CollectionInterface`
#### Throws
`LogicException`
### chunk() public
```
chunk(int $chunkSize): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
$chunked = (new Collection($items))->chunk(3)->toList();
// Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
```
#### Parameters
`int` $chunkSize #### Returns
`self`
### chunkWithKeys() public
```
chunkWithKeys(int $chunkSize, bool $keepKeys = true): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
$chunked = (new Collection($items))->chunkWithKeys(3)->toList();
// Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
```
#### Parameters
`int` $chunkSize `bool` $keepKeys optional #### Returns
`self`
### combine() public
```
combine(callable|string $keyPath, callable|string $valuePath, callable|string|null $groupPath = null): self
```
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
### Examples:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent' => 'a'],
['id' => 2, 'name' => 'bar', 'parent' => 'b'],
['id' => 3, 'name' => 'baz', 'parent' => 'a'],
];
$combined = (new Collection($items))->combine('id', 'name');
// Result will look like this when converted to array
[
1 => 'foo',
2 => 'bar',
3 => 'baz',
];
$combined = (new Collection($items))->combine('id', 'name', 'parent');
// Result will look like this when converted to array
[
'a' => [1 => 'foo', 3 => 'baz'],
'b' => [2 => 'bar']
];
```
#### Parameters
`callable|string` $keyPath `callable|string` $valuePath `callable|string|null` $groupPath optional #### Returns
`self`
### compile() public
```
compile(bool $keepKeys = true): self
```
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
A common use case is to re-use the same variable for calculating different data. In those cases it may be helpful and more performant to first compile a collection and then apply more operations to it.
### Example:
```
$collection->map($mapper)->sortBy('age')->extract('name');
$compiled = $collection->compile();
$isJohnHere = $compiled->some($johnMatcher);
$allButJohn = $compiled->filter($johnMatcher);
```
In the above example, had the collection not been compiled before, the iterations for `map`, `sortBy` and `extract` would've been executed twice: once for getting `$isJohnHere` and once for `$allButJohn`
You can think of this method as a way to create save points for complex calculations in a collection.
#### Parameters
`bool` $keepKeys optional #### Returns
`self`
### contains() public
```
contains(mixed $value): bool
```
Returns true if $value is present in this collection. Comparisons are made both by value and type.
#### Parameters
`mixed` $value #### Returns
`bool`
### count() public
```
count(): int
```
Returns the amount of elements in the collection.
WARNINGS:
---------
### Will change the current position of the iterator:
Calling this method at the same time that you are iterating this collections, for example in a foreach, will result in undefined behavior. Avoid doing this.
### Consumes all elements for NoRewindIterator collections:
On certain type of collections, calling this method may render unusable afterwards. That is, you may not be able to get elements out of it, or to iterate on it anymore.
Specifically any collection wrapping a Generator (a function with a yield statement) or a unbuffered database cursor will not accept any other function calls after calling `count()` on it.
Create a new collection with `buffered()` method to overcome this problem.
### Can report more elements than unique keys:
Any collection constructed by appending collections together, or by having internal iterators returning duplicate keys, will report a larger amount of elements using this functions than the final amount of elements when converting the collections to a keyed array. This is because duplicate keys will be collapsed into a single one in the final array, whereas this count method is only concerned by the amount of elements after converting it to a plain list.
If you need the count of elements after taking the keys in consideration (the count of unique keys), you can call `countKeys()`
#### Returns
`int`
### countBy() public
```
countBy(callable|string $path): self
```
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->countBy('parent_id');
// Or
$group = (new Collection($items))->countBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => 2,
11 => 1
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### countKeys() public
```
countKeys(): int
```
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
This method comes with a number of caveats. Please refer to `CollectionInterface::count()` for details.
#### Returns
`int`
### each() public
```
each(callable $callback): $this
```
Applies a callback to the elements in this collection.
### Example:
```
$collection = (new Collection($items))->each(function ($value, $key) {
echo "Element $key: $value";
});
```
#### Parameters
`callable` $callback #### Returns
`$this`
### every() public
```
every(callable $callback): bool
```
Returns true if all values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$overTwentyOne = (new Collection([24, 45, 60, 15]))->every(function ($value, $key) {
return $value > 21;
});
```
Empty collections always return true.
#### Parameters
`callable` $callback #### Returns
`bool`
### extract() public
```
extract(callable|string $path): self
```
Returns a new collection containing the column or property value found in each of the elements.
The matcher can be a string with a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection, that position is filled with null.
### Example:
Extract the user name for all comments in the array:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->extract('comment.user.name');
// Result will look like this when converted to array
['Mark', 'Renan']
```
It is also possible to extract a flattened collection out of nested properties
```
$items = [
['comment' => ['votes' => [['value' => 1], ['value' => 2], ['value' => 3]]],
['comment' => ['votes' => [['value' => 4]]
];
$extracted = (new Collection($items))->extract('comment.votes.{*}.value');
// Result will contain
[1, 2, 3, 4]
```
#### Parameters
`callable|string` $path #### Returns
`self`
### filter() public
```
filter(callable|null $callback = null): self
```
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering odd numbers in an array, at the end only the value 2 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->filter(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable|null` $callback optional #### Returns
`self`
### first() public
```
first(): mixed
```
Returns the first result in this collection
#### Returns
`mixed`
### firstMatch() public
```
firstMatch(array $conditions): mixed
```
Returns the first result matching all the key-value pairs listed in conditions.
#### Parameters
`array` $conditions #### Returns
`mixed`
### getChildren() public
```
getChildren(): RecursiveIterator
```
Returns a traversable containing the children for the current item
#### Returns
`RecursiveIterator`
### groupBy() public
```
groupBy(callable|string $path): self
```
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->groupBy('parent_id');
// Or
$group = (new Collection($items))->groupBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
],
11 => [
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
]
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### hasChildren() public
```
hasChildren(): bool
```
Returns true if there is an array or a traversable object stored under the configured nestKey for the current item
#### Returns
`bool`
### indexBy() public
```
indexBy(callable|string $path): self
```
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo'],
['id' => 2, 'name' => 'bar'],
['id' => 3, 'name' => 'baz'],
];
$indexed = (new Collection($items))->indexBy('id');
// Or
$indexed = (new Collection($items))->indexBy(function ($e) {
return $e['id'];
});
// Result will look like this when converted to array
[
1 => ['id' => 1, 'name' => 'foo'],
3 => ['id' => 3, 'name' => 'baz'],
2 => ['id' => 2, 'name' => 'bar'],
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### insert() public
```
insert(string $path, mixed $values): self
```
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
The $path can be a string with a property name or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection as part of the path, the element will be kept unchanged.
### Example:
Insert ages into a collection containing users:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
];
$ages = [25, 28];
$inserted = (new Collection($items))->insert('comment.user.age', $ages);
// Result will look like this when converted to array
[
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
];
```
#### Parameters
`string` $path `mixed` $values #### Returns
`self`
### isEmpty() public
```
isEmpty(): bool
```
Returns whether there are elements in this collection
### Example:
```
$items [1, 2, 3];
(new Collection($items))->isEmpty(); // false
```
```
(new Collection([]))->isEmpty(); // true
```
#### Returns
`bool`
### jsonSerialize() public
```
jsonSerialize(): array
```
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
Part of JsonSerializable interface.
#### Returns
`array`
### last() public
```
last(): mixed
```
Returns the last result in this collection
#### Returns
`mixed`
### lazy() public
```
lazy(): self
```
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
A lazy collection can only be iterated once. A second attempt results in an error.
#### Returns
`self`
### listNested() public
```
listNested(string|int $order = 'desc', callable|string $nestingKey = 'children'): self
```
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
By default all elements in the tree following a Depth First Search will be returned, that is, elements from the top parent to the leaves for each branch.
It is possible to return all elements from bottom to top using a Breadth First Search approach by passing the '$dir' parameter with 'asc'. That is, it will return all elements for the same tree depth first and from bottom to top.
Finally, you can specify to only get a collection with the leaf nodes in the tree structure. You do so by passing 'leaves' in the first argument.
The possible values for the first argument are aliases for the following constants and it is valid to pass those instead of the alias:
* desc: RecursiveIteratorIterator::SELF\_FIRST
* asc: RecursiveIteratorIterator::CHILD\_FIRST
* leaves: RecursiveIteratorIterator::LEAVES\_ONLY
### Example:
```
$collection = new Collection([
['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
['id' => 4, 'children' => [['id' => 5]]]
]);
$flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
```
#### Parameters
`string|int` $order optional `callable|string` $nestingKey optional #### Returns
`self`
### map() public
```
map(callable $callback): self
```
Returns another collection after modifying each of the values in this one using the provided callable.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Getting a collection of booleans where true indicates if a person is female:
```
$collection = (new Collection($people))->map(function ($person, $key) {
return $person->gender === 'female';
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### match() public
```
match(array $conditions): self
```
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
### Example:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->match(['user.name' => 'Renan']);
// Result will look like this when converted to array
[
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
]
```
#### Parameters
`array` $conditions #### Returns
`self`
### max() public
```
max(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$max = $collection->max('age');
$max = $collection->max('user.salary');
$max = $collection->max(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $max->name;
```
#### Parameters
`callable|string` $path `int` $sort optional #### Returns
`mixed`
### median() public
```
median(callable|string|null $path = null): float|int|null
```
Returns the median of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 400]],
['invoice' => ['total' => 500]]
['invoice' => ['total' => 100]]
['invoice' => ['total' => 333]]
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->median('invoice.total');
// Total: 333
$total = (new Collection([1, 2, 3, 4]))->median();
// Total: 2.5
```
The median of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int|null`
### min() public
```
min(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$min = $collection->min('age');
$min = $collection->min('user.salary');
$min = $collection->min(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $min->name;
```
#### Parameters
`callable|string` $path `int` $sort optional #### Returns
`mixed`
### nest() public
```
nest(callable|string $idPath, callable|string $parentPath, string $nestingKey = 'children'): self
```
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
#### Parameters
`callable|string` $idPath `callable|string` $parentPath `string` $nestingKey optional #### Returns
`self`
### newCollection() protected
```
newCollection(mixed ...$args): Cake\Collection\CollectionInterface
```
Returns a new collection.
Allows classes which use this trait to determine their own type of returned collection interface
#### Parameters
`mixed` ...$args Constructor arguments.
#### Returns
`Cake\Collection\CollectionInterface`
### optimizeUnwrap() protected
```
optimizeUnwrap(): iterable
```
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
#### Returns
`iterable`
### prepend() public
```
prepend(mixed $items): self
```
Prepend a set of items to a collection creating a new collection
#### Parameters
`mixed` $items #### Returns
`self`
### prependItem() public
```
prependItem(mixed $item, mixed $key = null): self
```
Prepend a single item creating a new collection.
#### Parameters
`mixed` $item `mixed` $key optional #### Returns
`self`
### reduce() public
```
reduce(callable $callback, mixed $initial = null): mixed
```
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
#### Parameters
`callable` $callback `mixed` $initial optional #### Returns
`mixed`
### reject() public
```
reject(callable $callback): self
```
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering even numbers in an array, at the end only values 1 and 3 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->reject(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### sample() public
```
sample(int $length = 10): self
```
Returns a new collection with maximum $size random elements from this collection
#### Parameters
`int` $length optional #### Returns
`self`
### serialize() public
```
serialize(): string
```
Returns a string representation of this object that can be used to reconstruct it
#### Returns
`string`
### shuffle() public
```
shuffle(): self
```
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
#### Returns
`self`
### skip() public
```
skip(int $length): self
```
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
#### Parameters
`int` $length #### Returns
`self`
### some() public
```
some(callable $callback): bool
```
Returns true if any of the values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$hasYoungPeople = (new Collection([24, 45, 15]))->some(function ($value, $key) {
return $value < 21;
});
```
#### Parameters
`callable` $callback #### Returns
`bool`
### sortBy() public
```
sortBy(callable|string $path, int $order = \SORT_DESC, int $sort = \SORT_NUMERIC): self
```
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
The callback will receive as its first argument each of the elements in $items, the value returned by the callback will be used as the value for sorting such element. Please note that the callback function could be called more than once per element.
### Example:
```
$items = $collection->sortBy(function ($user) {
return $user->age;
});
// alternatively
$items = $collection->sortBy('age');
// or use a property path
$items = $collection->sortBy('department.name');
// output all user name order by their age in descending order
foreach ($items as $user) {
echo $user->name;
}
```
#### Parameters
`callable|string` $path `int` $order optional `int` $sort optional #### Returns
`self`
### stopWhen() public
```
stopWhen(callable|array $condition): self
```
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
This is handy for dealing with infinite iterators or any generator that could start returning invalid elements at a certain point. For example, when reading lines from a file stream you may want to stop the iteration after a certain value is reached.
### Example:
Get an array of lines in a CSV file until the timestamp column is less than a date
```
$lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
return (new DateTime($value))->format('Y') < 2012;
})
->toArray();
```
Get elements until the first unapproved message is found:
```
$comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
```
#### Parameters
`callable|array` $condition #### Returns
`self`
### sumOf() public
```
sumOf(callable|string|null $path = null): float|int
```
Returns the total sum of all the values extracted with $matcher or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->sumOf('invoice.total');
// Total: 300
$total = (new Collection([1, 2, 3]))->sumOf();
// Total: 6
```
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int`
### take() public
```
take(int $length = 1, int $offset = 0): self
```
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
#### Parameters
`int` $length optional `int` $offset optional #### Returns
`self`
### takeLast() public
```
takeLast(int $length): self
```
Returns the last N elements of a collection
### Example:
```
$items = [1, 2, 3, 4, 5];
$last = (new Collection($items))->takeLast(3);
// Result will look like this when converted to array
[3, 4, 5];
```
#### Parameters
`int` $length #### Returns
`self`
### through() public
```
through(callable $callback): self
```
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
### Example:
```
$items = [1, 2, 3];
$decorated = (new Collection($items))->through(function ($collection) {
return new MyCustomCollection($collection);
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### toArray() public
```
toArray(bool $keepKeys = true): array
```
Returns an array representation of the results
#### Parameters
`bool` $keepKeys optional #### Returns
`array`
### toList() public
```
toList(): array
```
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
#### Returns
`array`
### transpose() public
```
transpose(): Cake\Collection\CollectionInterface
```
Transpose rows and columns into columns and rows
### Example:
```
$items = [
['Products', '2012', '2013', '2014'],
['Product A', '200', '100', '50'],
['Product B', '300', '200', '100'],
['Product C', '400', '300', '200'],
]
$transpose = (new Collection($items))->transpose()->toList();
// Returns
// [
// ['Products', 'Product A', 'Product B', 'Product C'],
// ['2012', '200', '300', '400'],
// ['2013', '100', '200', '300'],
// ['2014', '50', '100', '200'],
// ]
```
#### Returns
`Cake\Collection\CollectionInterface`
#### Throws
`LogicException`
### unfold() public
```
unfold(callable|null $callback = null): self
```
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
The transformer function will receive the value and the key for each of the items in the collection, in that order, and it must return an array or a Traversable object that can be concatenated to the final result.
If no transformer function is passed, an "identity" function will be used. This is useful when each of the elements in the source collection are lists of items to be appended one after another.
### Example:
```
$items [[1, 2, 3], [4, 5]];
$unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
```
Using a transformer
```
$items [1, 2, 3];
$allItems = (new Collection($items))->unfold(function ($page) {
return $service->fetchPage($page)->toArray();
});
```
#### Parameters
`callable|null` $callback optional #### Returns
`self`
### unserialize() public
```
unserialize(string $collection): void
```
Unserializes the passed string and rebuilds the Collection instance
#### Parameters
`string` $collection The serialized collection
#### Returns
`void`
### unwrap() public
```
unwrap(): Traversable
```
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
#### Returns
`Traversable`
### zip() public
```
zip(iterable $items): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
### Example:
```
$collection = new Collection([1, 2]);
$collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
```
#### Parameters
`iterable` $items #### Returns
`self`
### zipWith() public
```
zipWith(iterable $items, callable $callback): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
The resulting element will be the return value of the $callable function.
### Example:
```
$collection = new Collection([1, 2]);
$zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
return array_sum($args);
});
$zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
```
#### Parameters
`iterable` $items `callable` $callback #### Returns
`self`
Property Detail
---------------
### $\_nestKey protected
The name of the property that contains the nested items for each element
#### Type
`callable|string`
| programming_docs |
cakephp Class MissingLayoutException Class MissingLayoutException
=============================
Used when a layout file cannot be found.
**Namespace:** [Cake\View\Exception](namespace-cake.view.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
* [$filename](#%24filename) protected `string`
* [$paths](#%24paths) protected `array<string>`
* [$templateName](#%24templateName) protected `string|null`
* [$type](#%24type) protected `string`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [formatMessage()](#formatMessage()) public
Get the formatted exception message.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string>|string $file, array<string> $paths = [], int|null $code = null, Throwable|null $previous = null)
```
Constructor
#### Parameters
`array<string>|string` $file Either the file name as a string, or in an array for backwards compatibility.
`array<string>` $paths optional The path list that template could not be found in.
`int|null` $code optional The code of the error.
`Throwable|null` $previous optional the previous exception.
### formatMessage() public
```
formatMessage(): string
```
Get the formatted exception message.
#### Returns
`string`
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
### $filename protected
#### Type
`string`
### $paths protected
#### Type
`array<string>`
### $templateName protected
#### Type
`string|null`
### $type protected
#### Type
`string`
cakephp Class ReconnectStrategy Class ReconnectStrategy
========================
Makes sure the connection to the database is alive before authorizing the retry of an action.
**Namespace:** [Cake\Database\Retry](namespace-cake.database.retry)
Property Summary
----------------
* [$causes](#%24causes) protected static `array<string>` The list of error strings to match when looking for a disconnection error.
* [$connection](#%24connection) protected `Cake\Database\Connection` The connection to check for validity
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Creates the ReconnectStrategy object by storing a reference to the passed connection. This reference will be used to automatically reconnect to the server in case of failure.
* ##### [reconnect()](#reconnect()) protected
Tries to re-establish the connection to the server, if it is safe to do so
* ##### [shouldRetry()](#shouldRetry()) public
Returns true if the action can be retried, false otherwise.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Database\Connection $connection)
```
Creates the ReconnectStrategy object by storing a reference to the passed connection. This reference will be used to automatically reconnect to the server in case of failure.
#### Parameters
`Cake\Database\Connection` $connection The connection to check
### reconnect() protected
```
reconnect(): bool
```
Tries to re-establish the connection to the server, if it is safe to do so
#### Returns
`bool`
### shouldRetry() public
```
shouldRetry(Exception $exception, int $retryCount): bool
```
Returns true if the action can be retried, false otherwise.
Checks whether the exception was caused by a lost connection, and returns true if it was able to successfully reconnect.
#### Parameters
`Exception` $exception `int` $retryCount #### Returns
`bool`
Property Detail
---------------
### $causes protected static
The list of error strings to match when looking for a disconnection error.
This is a static variable to enable opcache to inline the values.
#### Type
`array<string>`
### $connection protected
The connection to check for validity
#### Type
`Cake\Database\Connection`
cakephp Class ForbiddenException Class ForbiddenException
=========================
Represents an HTTP 403 error.
**Namespace:** [Cake\Http\Exception](namespace-cake.http.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
* [$headers](#%24headers) protected `array<string, mixed>`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [getHeaders()](#getHeaders()) public
Returns array of response headers.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
* ##### [setHeader()](#setHeader()) public
Set a single HTTP response header.
* ##### [setHeaders()](#setHeaders()) public
Sets HTTP response headers.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $message = null, int|null $code = null, Throwable|null $previous = null)
```
Constructor
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`string|null` $message optional If no message is given 'Forbidden' will be the message
`int|null` $code optional Status code, defaults to 403
`Throwable|null` $previous optional The previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### getHeaders() public
```
getHeaders(): array<string, mixed>
```
Returns array of response headers.
#### Returns
`array<string, mixed>`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
### setHeader() public
```
setHeader(string $header, array<string>|string|null $value = null): void
```
Set a single HTTP response header.
#### Parameters
`string` $header Header name
`array<string>|string|null` $value optional Header value
#### Returns
`void`
### setHeaders() public
```
setHeaders(array<string, mixed> $headers): void
```
Sets HTTP response headers.
#### Parameters
`array<string, mixed>` $headers Array of header name and value pairs.
#### Returns
`void`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
### $headers protected
#### Type
`array<string, mixed>`
cakephp Interface PaginatorInterface Interface PaginatorInterface
=============================
This interface describes the methods for paginator instance.
**Namespace:** [Cake\Datasource\Paging](namespace-cake.datasource.paging)
Method Summary
--------------
* ##### [getPagingParams()](#getPagingParams()) public
Get paging params after pagination operation.
* ##### [paginate()](#paginate()) public
Handles pagination of datasource records.
Method Detail
-------------
### getPagingParams() public
```
getPagingParams(): array
```
Get paging params after pagination operation.
#### Returns
`array`
### paginate() public
```
paginate(Cake\Datasource\RepositoryInterfaceCake\Datasource\QueryInterface $object, array $params = [], array $settings = []): Cake\Datasource\ResultSetInterface
```
Handles pagination of datasource records.
#### Parameters
`Cake\Datasource\RepositoryInterfaceCake\Datasource\QueryInterface` $object The repository or query to paginate.
`array` $params optional Request params
`array` $settings optional The settings/configuration used for pagination.
#### Returns
`Cake\Datasource\ResultSetInterface`
cakephp Class I18nInitCommand Class I18nInitCommand
======================
Command for interactive I18N management.
**Namespace:** [Cake\Command](namespace-cake.command)
Constants
---------
* `int` **CODE\_ERROR**
```
1
```
Default error code
* `int` **CODE\_SUCCESS**
```
0
```
Default success code
Property Summary
----------------
* [$\_modelFactories](#%24_modelFactories) protected `array<callableCake\Datasource\Locator\LocatorInterface>` A list of overridden model factory functions.
* [$\_modelType](#%24_modelType) protected `string` The model type to use.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
* [$modelClass](#%24modelClass) protected deprecated `string|null` This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
* [$name](#%24name) protected `string` The name of this command.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_setModelClass()](#_setModelClass()) protected
Set the modelClass property based on conventions.
* ##### [abort()](#abort()) public
Halt the the current process with a StopException.
* ##### [buildOptionParser()](#buildOptionParser()) public
Gets the option parser instance and configures it.
* ##### [defaultName()](#defaultName()) public static
Get the command name.
* ##### [displayHelp()](#displayHelp()) protected
Output help content
* ##### [execute()](#execute()) public
Execute the command
* ##### [executeCommand()](#executeCommand()) public
Execute another command with the provided set of arguments.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getDescription()](#getDescription()) public static
Get the command description.
* ##### [getModelType()](#getModelType()) public
Get the model type to be used by this class
* ##### [getName()](#getName()) public
Get the command name.
* ##### [getOptionParser()](#getOptionParser()) public
Get the option parser.
* ##### [getRootName()](#getRootName()) public
Get the root command name.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [initialize()](#initialize()) public
Hook method invoked by CakePHP when a command is about to be executed.
* ##### [loadModel()](#loadModel()) public deprecated
Loads and constructs repository objects required by this object
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [modelFactory()](#modelFactory()) public
Override a existing callable to generate repositories of a given type.
* ##### [run()](#run()) public
Run the command.
* ##### [setModelType()](#setModelType()) public
Set the model type to be used by this class
* ##### [setName()](#setName()) public
Set the name this command uses in the collection.
* ##### [setOutputLevel()](#setOutputLevel()) protected
Set the output level based on the Arguments.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
Method Detail
-------------
### \_\_construct() public
```
__construct()
```
Constructor
By default CakePHP will construct command objects when building the CommandCollection for your application.
### \_setModelClass() protected
```
_setModelClass(string $name): void
```
Set the modelClass property based on conventions.
If the property is already set it will not be overwritten
#### Parameters
`string` $name Class name.
#### Returns
`void`
### abort() public
```
abort(int $code = self::CODE_ERROR): void
```
Halt the the current process with a StopException.
#### Parameters
`int` $code optional The exit code to use.
#### Returns
`void`
#### Throws
`Cake\Console\Exception\StopException`
### buildOptionParser() public
```
buildOptionParser(Cake\Console\ConsoleOptionParser $parser): Cake\Console\ConsoleOptionParser
```
Gets the option parser instance and configures it.
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The parser to update
#### Returns
`Cake\Console\ConsoleOptionParser`
### defaultName() public static
```
defaultName(): string
```
Get the command name.
Returns the command name based on class name. For e.g. for a command with class name `UpdateTableCommand` the default name returned would be `'update_table'`.
#### Returns
`string`
### displayHelp() protected
```
displayHelp(Cake\Console\ConsoleOptionParser $parser, Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Output help content
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser.
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### execute() public
```
execute(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): int|null
```
Execute the command
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`int|null`
### executeCommand() public
```
executeCommand(Cake\Console\CommandInterface|string $command, array $args = [], Cake\Console\ConsoleIo|null $io = null): int|null
```
Execute another command with the provided set of arguments.
If you are using a string command name, that command's dependencies will not be resolved with the application container. Instead you will need to pass the command as an object with all of its dependencies.
#### Parameters
`Cake\Console\CommandInterface|string` $command The command class name or command instance.
`array` $args optional The arguments to invoke the command with.
`Cake\Console\ConsoleIo|null` $io optional The ConsoleIo instance to use for the executed command.
#### Returns
`int|null`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getDescription() public static
```
getDescription(): string
```
Get the command description.
#### Returns
`string`
### getModelType() public
```
getModelType(): string
```
Get the model type to be used by this class
#### Returns
`string`
### getName() public
```
getName(): string
```
Get the command name.
#### Returns
`string`
### getOptionParser() public
```
getOptionParser(): Cake\Console\ConsoleOptionParser
```
Get the option parser.
You can override buildOptionParser() to define your options & arguments.
#### Returns
`Cake\Console\ConsoleOptionParser`
#### Throws
`RuntimeException`
When the parser is invalid ### getRootName() public
```
getRootName(): string
```
Get the root command name.
#### Returns
`string`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### initialize() public
```
initialize(): void
```
Hook method invoked by CakePHP when a command is about to be executed.
Override this method and implement expensive/important setup steps that should not run on every command run. This method will be called *before* the options and arguments are validated and processed.
#### Returns
`void`
### loadModel() public
```
loadModel(string|null $modelClass = null, string|null $modelType = null): Cake\Datasource\RepositoryInterface
```
Loads and constructs repository objects required by this object
Typically used to load ORM Table objects as required. Can also be used to load other types of repository objects your application uses.
If a repository provider does not return an object a MissingModelException will be thrown.
#### Parameters
`string|null` $modelClass optional Name of model class to load. Defaults to $this->modelClass. The name can be an alias like `'Post'` or FQCN like `App\Model\Table\PostsTable::class`.
`string|null` $modelType optional The type of repository to load. Defaults to the getModelType() value.
#### Returns
`Cake\Datasource\RepositoryInterface`
#### Throws
`Cake\Datasource\Exception\MissingModelException`
If the model class cannot be found.
`UnexpectedValueException`
If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty. ### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### modelFactory() public
```
modelFactory(string $type, Cake\Datasource\Locator\LocatorInterface|callable $factory): void
```
Override a existing callable to generate repositories of a given type.
#### Parameters
`string` $type The name of the repository type the factory function is for.
`Cake\Datasource\Locator\LocatorInterface|callable` $factory The factory function used to create instances.
#### Returns
`void`
### run() public
```
run(array $argv, Cake\Console\ConsoleIo $io): int|null
```
Run the command.
#### Parameters
`array` $argv `Cake\Console\ConsoleIo` $io #### Returns
`int|null`
### setModelType() public
```
setModelType(string $modelType): $this
```
Set the model type to be used by this class
#### Parameters
`string` $modelType The model type
#### Returns
`$this`
### setName() public
```
setName(string $name): $this
```
Set the name this command uses in the collection.
Generally invoked by the CommandCollection when the command is added. Required to have at least one space in the name so that the root command can be calculated.
#### Parameters
`string` $name #### Returns
`$this`
### setOutputLevel() protected
```
setOutputLevel(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Set the output level based on the Arguments.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
Property Detail
---------------
### $\_modelFactories protected
A list of overridden model factory functions.
#### Type
`array<callableCake\Datasource\Locator\LocatorInterface>`
### $\_modelType protected
The model type to use.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
### $modelClass protected deprecated
This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
Example: For an object named 'Comments', the modelClass would be 'Comments'. Plugin classes should use `Plugin.Comments` style names to correctly load models from the correct plugin.
Use empty string to not use auto-loading on this object. Null auto-detects based on controller name.
#### Type
`string|null`
### $name protected
The name of this command.
#### Type
`string`
| programming_docs |
cakephp Namespace Route Namespace Route
===============
### Classes
* ##### [DashedRoute](class-cake.routing.route.dashedroute)
This route class will transparently inflect the controller, action and plugin routing parameters, so that requesting `/my-plugin/my-controller/my-action` is parsed as `['plugin' => 'MyPlugin', 'controller' => 'MyController', 'action' => 'myAction']`
* ##### [EntityRoute](class-cake.routing.route.entityroute)
Matches entities to routes
* ##### [InflectedRoute](class-cake.routing.route.inflectedroute)
This route class will transparently inflect the controller and plugin routing parameters, so that requesting `/my_controller` is parsed as `['controller' => 'MyController']`
* ##### [PluginShortRoute](class-cake.routing.route.pluginshortroute)
Plugin short route, that copies the plugin param to the controller parameters It is used for supporting /{plugin} routes.
* ##### [RedirectRoute](class-cake.routing.route.redirectroute)
Redirect route will perform an immediate redirect. Redirect routes are useful when you want to have Routing layer redirects occur in your application, for when URLs move.
* ##### [Route](class-cake.routing.route.route)
A single Route used by the Router to connect requests to parameter maps.
cakephp Trait LocatorAwareTrait Trait LocatorAwareTrait
========================
Contains method for setting and accessing LocatorInterface instance
**Namespace:** [Cake\ORM\Locator](namespace-cake.orm.locator)
Property Summary
----------------
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
Method Summary
--------------
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
Method Detail
-------------
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
Property Detail
---------------
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
cakephp Class PackageLocator Class PackageLocator
=====================
A ServiceLocator implementation for loading and retaining package objects.
**Namespace:** [Cake\I18n](namespace-cake.i18n)
Property Summary
----------------
* [$converted](#%24converted) protected `array<string, array<string, bool>>` Tracks whether a registry entry has been converted from a callable to a Package object.
* [$registry](#%24registry) protected `array<string, array<string,Cake\I18n\Package|callable>>` A registry of packages.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [get()](#get()) public
Gets a Package object.
* ##### [has()](#has()) public
Check if a Package object for given name and locale exists in registry.
* ##### [set()](#set()) public
Sets a Package loader.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, array<string,Cake\I18n\Package|callable>> $registry = [])
```
Constructor.
#### Parameters
`array<string, array<string,Cake\I18n\Package|callable>>` $registry optional A registry of packages.
#### See Also
PackageLocator::$registry ### get() public
```
get(string $name, string $locale): Cake\I18n\Package
```
Gets a Package object.
#### Parameters
`string` $name The package name.
`string` $locale The locale for the package.
#### Returns
`Cake\I18n\Package`
### has() public
```
has(string $name, string $locale): bool
```
Check if a Package object for given name and locale exists in registry.
#### Parameters
`string` $name The package name.
`string` $locale The locale for the package.
#### Returns
`bool`
### set() public
```
set(string $name, string $locale, Cake\I18n\Package|callable $spec): void
```
Sets a Package loader.
#### Parameters
`string` $name The package name.
`string` $locale The locale for the package.
`Cake\I18n\Package|callable` $spec A callable that returns a package or Package instance.
#### Returns
`void`
Property Detail
---------------
### $converted protected
Tracks whether a registry entry has been converted from a callable to a Package object.
#### Type
`array<string, array<string, bool>>`
### $registry protected
A registry of packages.
Unlike many other registries, this one is two layers deep. The first key is a package name, the second key is a locale code, and the value is a callable that returns a Package object for that name and locale.
#### Type
`array<string, array<string,Cake\I18n\Package|callable>>`
cakephp Class ErrorCodeWaitStrategy Class ErrorCodeWaitStrategy
============================
Implements retry strategy based on db error codes and wait interval.
**Namespace:** [Cake\Database\Retry](namespace-cake.database.retry)
Property Summary
----------------
* [$errorCodes](#%24errorCodes) protected `array<int>`
* [$retryInterval](#%24retryInterval) protected `int`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
* ##### [shouldRetry()](#shouldRetry()) public
Returns true if the action can be retried, false otherwise.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<int> $errorCodes, int $retryInterval)
```
#### Parameters
`array<int>` $errorCodes DB-specific error codes that allow retrying
`int` $retryInterval Seconds to wait before allowing next retry, 0 for no wait.
### shouldRetry() public
```
shouldRetry(Exception $exception, int $retryCount): bool
```
Returns true if the action can be retried, false otherwise.
#### Parameters
`Exception` $exception `int` $retryCount #### Returns
`bool`
Property Detail
---------------
### $errorCodes protected
#### Type
`array<int>`
### $retryInterval protected
#### Type
`int`
cakephp Class ApcuEngine Class ApcuEngine
=================
APCu storage engine for cache
**Namespace:** [Cake\Cache\Engine](namespace-cake.cache.engine)
Constants
---------
* `string` **CHECK\_KEY**
```
'key'
```
* `string` **CHECK\_VALUE**
```
'value'
```
Property Summary
----------------
* [$\_compiledGroupNames](#%24_compiledGroupNames) protected `array<string>` Contains the compiled group names (prefixed with the global configuration prefix)
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` The default cache configuration is overridden in most cache adapters. These are the keys that are common to all adapters. If overridden, this property is not used.
* [$\_groupPrefix](#%24_groupPrefix) protected `string` Contains the compiled string with all group prefixes to be prepended to every key in this cache engine
Method Summary
--------------
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_key()](#_key()) protected
Generates a key for cache backend usage.
* ##### [add()](#add()) public
Write data for key into cache if it doesn't exist already. If it already exists, it fails and returns false.
* ##### [clear()](#clear()) public
Delete all keys from the cache. This will clear every cache config using APC.
* ##### [clearGroup()](#clearGroup()) public
Increments the group value to simulate deletion of all keys under a group old values will remain in storage until they expire.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [decrement()](#decrement()) public
Decrements the value of an integer cached key
* ##### [delete()](#delete()) public
Delete a key from the cache
* ##### [deleteMultiple()](#deleteMultiple()) public
Deletes multiple cache items as a list
* ##### [duration()](#duration()) protected
Convert the various expressions of a TTL value into duration in seconds
* ##### [ensureValidKey()](#ensureValidKey()) protected
Ensure the validity of the given cache key.
* ##### [ensureValidType()](#ensureValidType()) protected
Ensure the validity of the argument type and cache keys.
* ##### [get()](#get()) public
Read a key from the cache
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getMultiple()](#getMultiple()) public
Obtains multiple cache items by their unique keys.
* ##### [groups()](#groups()) public
Returns the `group value` for each of the configured groups If the group initial value was not found, then it initializes the group accordingly.
* ##### [has()](#has()) public
Determines whether an item is present in the cache.
* ##### [increment()](#increment()) public
Increments the value of an integer cached key
* ##### [init()](#init()) public
Initialize the Cache Engine
* ##### [set()](#set()) public
Write data for key into cache
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setMultiple()](#setMultiple()) public
Persists a set of key => value pairs in the cache, with an optional TTL.
* ##### [warning()](#warning()) protected
Cache Engines may trigger warnings if they encounter failures during operation, if option warnOnWriteFailures is set to true.
Method Detail
-------------
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_key() protected
```
_key(string $key): string
```
Generates a key for cache backend usage.
If the requested key is valid, the group prefix value and engine prefix are applied. Whitespace in keys will be replaced.
#### Parameters
`string` $key the key passed over
#### Returns
`string`
#### Throws
`Cake\Cache\InvalidArgumentException`
If key's value is invalid. ### add() public
```
add(string $key, mixed $value): bool
```
Write data for key into cache if it doesn't exist already. If it already exists, it fails and returns false.
Defaults to a non-atomic implementation. Subclasses should prefer atomic implementations.
#### Parameters
`string` $key Identifier for the data.
`mixed` $value Data to be cached.
#### Returns
`bool`
#### Links
https://secure.php.net/manual/en/function.apcu-add.php
### clear() public
```
clear(): bool
```
Delete all keys from the cache. This will clear every cache config using APC.
#### Returns
`bool`
#### Links
https://secure.php.net/manual/en/function.apcu-cache-info.php
https://secure.php.net/manual/en/function.apcu-delete.php
### clearGroup() public
```
clearGroup(string $group): bool
```
Increments the group value to simulate deletion of all keys under a group old values will remain in storage until they expire.
Each implementation needs to decide whether actually delete the keys or just augment a group generation value to achieve the same result.
#### Parameters
`string` $group The group to clear.
#### Returns
`bool`
#### Links
https://secure.php.net/manual/en/function.apcu-inc.php
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### decrement() public
```
decrement(string $key, int $offset = 1): int|false
```
Decrements the value of an integer cached key
#### Parameters
`string` $key Identifier for the data
`int` $offset optional How much to subtract
#### Returns
`int|false`
#### Links
https://secure.php.net/manual/en/function.apcu-dec.php
### delete() public
```
delete(string $key): bool
```
Delete a key from the cache
#### Parameters
`string` $key Identifier for the data
#### Returns
`bool`
#### Links
https://secure.php.net/manual/en/function.apcu-delete.php
### deleteMultiple() public
```
deleteMultiple(iterable $keys): bool
```
Deletes multiple cache items as a list
This is a best effort attempt. If deleting an item would create an error it will be ignored, and all items will be attempted.
#### Parameters
`iterable` $keys A list of string-based keys to be deleted.
#### Returns
`bool`
#### Throws
`Cake\Cache\InvalidArgumentException`
If $keys is neither an array nor a Traversable, or if any of the $keys are not a legal value. ### duration() protected
```
duration(DateInterval|int|null $ttl): int
```
Convert the various expressions of a TTL value into duration in seconds
#### Parameters
`DateInterval|int|null` $ttl The TTL value of this item. If null is sent, the driver's default duration will be used.
#### Returns
`int`
### ensureValidKey() protected
```
ensureValidKey(string $key): void
```
Ensure the validity of the given cache key.
#### Parameters
`string` $key Key to check.
#### Returns
`void`
#### Throws
`Cake\Cache\InvalidArgumentException`
When the key is not valid. ### ensureValidType() protected
```
ensureValidType(iterable $iterable, string $check = self::CHECK_VALUE): void
```
Ensure the validity of the argument type and cache keys.
#### Parameters
`iterable` $iterable The iterable to check.
`string` $check optional Whether to check keys or values.
#### Returns
`void`
#### Throws
`Cake\Cache\InvalidArgumentException`
### get() public
```
get(string $key, mixed $default = null): mixed
```
Read a key from the cache
#### Parameters
`string` $key Identifier for the data
`mixed` $default optional Default value in case the cache misses.
#### Returns
`mixed`
#### Links
https://secure.php.net/manual/en/function.apcu-fetch.php
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getMultiple() public
```
getMultiple(iterable $keys, mixed $default = null): iterable
```
Obtains multiple cache items by their unique keys.
#### Parameters
`iterable` $keys A list of keys that can obtained in a single operation.
`mixed` $default optional Default value to return for keys that do not exist.
#### Returns
`iterable`
#### Throws
`Cake\Cache\InvalidArgumentException`
If $keys is neither an array nor a Traversable, or if any of the $keys are not a legal value. ### groups() public
```
groups(): array<string>
```
Returns the `group value` for each of the configured groups If the group initial value was not found, then it initializes the group accordingly.
#### Returns
`array<string>`
#### Links
https://secure.php.net/manual/en/function.apcu-fetch.php
https://secure.php.net/manual/en/function.apcu-store.php
### has() public
```
has(string $key): bool
```
Determines whether an item is present in the cache.
NOTE: It is recommended that has() is only to be used for cache warming type purposes and not to be used within your live applications operations for get/set, as this method is subject to a race condition where your has() will return true and immediately after, another script can remove it making the state of your app out of date.
#### Parameters
`string` $key The cache item key.
#### Returns
`bool`
#### Throws
`Cake\Cache\InvalidArgumentException`
If the $key string is not a legal value. ### increment() public
```
increment(string $key, int $offset = 1): int|false
```
Increments the value of an integer cached key
#### Parameters
`string` $key Identifier for the data
`int` $offset optional How much to increment
#### Returns
`int|false`
#### Links
https://secure.php.net/manual/en/function.apcu-inc.php
### init() public
```
init(array<string, mixed> $config = []): bool
```
Initialize the Cache Engine
Called automatically by the cache frontend
#### Parameters
`array<string, mixed>` $config optional array of setting for the engine
#### Returns
`bool`
### set() public
```
set(string $key, mixed $value, null|intDateInterval $ttl = null): bool
```
Write data for key into cache
#### Parameters
`string` $key Identifier for the data
`mixed` $value Data to be cached
`null|intDateInterval` $ttl optional Optional. The TTL value of this item. If no value is sent and the driver supports TTL then the library may set a default value for it or let the driver take care of that.
#### Returns
`bool`
#### Links
https://secure.php.net/manual/en/function.apcu-store.php
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setMultiple() public
```
setMultiple(iterable $values, null|intDateInterval $ttl = null): bool
```
Persists a set of key => value pairs in the cache, with an optional TTL.
#### Parameters
`iterable` $values A list of key => value pairs for a multiple-set operation.
`null|intDateInterval` $ttl optional Optional. The TTL value of this item. If no value is sent and the driver supports TTL then the library may set a default value for it or let the driver take care of that.
#### Returns
`bool`
#### Throws
`Cake\Cache\InvalidArgumentException`
If $values is neither an array nor a Traversable, or if any of the $values are not a legal value. ### warning() protected
```
warning(string $message): void
```
Cache Engines may trigger warnings if they encounter failures during operation, if option warnOnWriteFailures is set to true.
#### Parameters
`string` $message The warning message.
#### Returns
`void`
Property Detail
---------------
### $\_compiledGroupNames protected
Contains the compiled group names (prefixed with the global configuration prefix)
#### Type
`array<string>`
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
The default cache configuration is overridden in most cache adapters. These are the keys that are common to all adapters. If overridden, this property is not used.
* `duration` Specify how long items in this cache configuration last.
* `groups` List of groups or 'tags' associated to every key stored in this config. handy for deleting a complete group from cache.
* `prefix` Prefix appended to all entries. Good for when you need to share a keyspace with either another cache config or another application.
* `warnOnWriteFailures` Some engines, such as ApcuEngine, may raise warnings on write failures.
#### Type
`array<string, mixed>`
### $\_groupPrefix protected
Contains the compiled string with all group prefixes to be prepended to every key in this cache engine
#### Type
`string`
| programming_docs |
cakephp Namespace Collection Namespace Collection
====================
### Namespaces
* [Cake\Collection\Iterator](namespace-cake.collection.iterator)
### Interfaces
* ##### [CollectionInterface](interface-cake.collection.collectioninterface)
Describes the methods a Collection should implement. A collection is an immutable list of elements exposing a number of traversing and extracting method for generating other collections.
### Classes
* ##### [Collection](class-cake.collection.collection)
A collection is an immutable list of elements with a handful of functions to iterate, group, transform and extract information from it.
cakephp Class IdentifierExpression Class IdentifierExpression
===========================
Represents a single identifier name in the database.
Identifier values are unsafe with user supplied data. Values will be quoted when identifier quoting is enabled.
**Namespace:** [Cake\Database\Expression](namespace-cake.database.expression)
**See:** \Cake\Database\Query::identifier()
Property Summary
----------------
* [$\_identifier](#%24_identifier) protected `string` Holds the identifier string
* [$collation](#%24collation) protected `string|null`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getCollation()](#getCollation()) public
Returns the collation.
* ##### [getIdentifier()](#getIdentifier()) public
Returns the identifier this expression represents
* ##### [setCollation()](#setCollation()) public
Sets the collation.
* ##### [setIdentifier()](#setIdentifier()) public
Sets the identifier this expression represents
* ##### [sql()](#sql()) public
Converts the Node into a SQL string fragment.
* ##### [traverse()](#traverse()) public
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
Method Detail
-------------
### \_\_construct() public
```
__construct(string $identifier, string|null $collation = null)
```
Constructor
#### Parameters
`string` $identifier The identifier this expression represents
`string|null` $collation optional The identifier collation
### getCollation() public
```
getCollation(): string|null
```
Returns the collation.
#### Returns
`string|null`
### getIdentifier() public
```
getIdentifier(): string
```
Returns the identifier this expression represents
#### Returns
`string`
### setCollation() public
```
setCollation(string $collation): void
```
Sets the collation.
#### Parameters
`string` $collation Identifier collation
#### Returns
`void`
### setIdentifier() public
```
setIdentifier(string $identifier): void
```
Sets the identifier this expression represents
#### Parameters
`string` $identifier The identifier
#### Returns
`void`
### sql() public
```
sql(Cake\Database\ValueBinder $binder): string
```
Converts the Node into a SQL string fragment.
#### Parameters
`Cake\Database\ValueBinder` $binder #### Returns
`string`
### traverse() public
```
traverse(Closure $callback): $this
```
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
#### Parameters
`Closure` $callback #### Returns
`$this`
Property Detail
---------------
### $\_identifier protected
Holds the identifier string
#### Type
`string`
### $collation protected
#### Type
`string|null`
cakephp Class ConsoleInputArgument Class ConsoleInputArgument
===========================
An object to represent a single argument used in the command line. ConsoleOptionParser creates these when you use addArgument()
**Namespace:** [Cake\Console](namespace-cake.console)
**See:** \Cake\Console\ConsoleOptionParser::addArgument()
Property Summary
----------------
* [$\_choices](#%24_choices) protected `array<string>` An array of valid choices for this argument.
* [$\_help](#%24_help) protected `string` Help string
* [$\_name](#%24_name) protected `string` Name of the argument.
* [$\_required](#%24_required) protected `bool` Is this option required?
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Make a new Input Argument
* ##### [help()](#help()) public
Generate the help for this argument.
* ##### [isEqualTo()](#isEqualTo()) public
Checks if this argument is equal to another argument.
* ##### [isRequired()](#isRequired()) public
Check if this argument is a required argument
* ##### [name()](#name()) public
Get the value of the name attribute.
* ##### [usage()](#usage()) public
Get the usage value for this argument
* ##### [validChoice()](#validChoice()) public
Check that $value is a valid choice for this argument.
* ##### [xml()](#xml()) public
Append this arguments XML representation to the passed in SimpleXml object.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed>|string $name, string $help = '', bool $required = false, array<string> $choices = [])
```
Make a new Input Argument
#### Parameters
`array<string, mixed>|string` $name The long name of the option, or an array with all the properties.
`string` $help optional The help text for this option
`bool` $required optional Whether this argument is required. Missing required args will trigger exceptions
`array<string>` $choices optional Valid choices for this option.
### help() public
```
help(int $width = 0): string
```
Generate the help for this argument.
#### Parameters
`int` $width optional The width to make the name of the option.
#### Returns
`string`
### isEqualTo() public
```
isEqualTo(Cake\Console\ConsoleInputArgument $argument): bool
```
Checks if this argument is equal to another argument.
#### Parameters
`Cake\Console\ConsoleInputArgument` $argument ConsoleInputArgument to compare to.
#### Returns
`bool`
### isRequired() public
```
isRequired(): bool
```
Check if this argument is a required argument
#### Returns
`bool`
### name() public
```
name(): string
```
Get the value of the name attribute.
#### Returns
`string`
### usage() public
```
usage(): string
```
Get the usage value for this argument
#### Returns
`string`
### validChoice() public
```
validChoice(string $value): true
```
Check that $value is a valid choice for this argument.
#### Parameters
`string` $value The choice to validate.
#### Returns
`true`
#### Throws
`Cake\Console\Exception\ConsoleException`
### xml() public
```
xml(SimpleXMLElement $parent): SimpleXMLElement
```
Append this arguments XML representation to the passed in SimpleXml object.
#### Parameters
`SimpleXMLElement` $parent The parent element.
#### Returns
`SimpleXMLElement`
Property Detail
---------------
### $\_choices protected
An array of valid choices for this argument.
#### Type
`array<string>`
### $\_help protected
Help string
#### Type
`string`
### $\_name protected
Name of the argument.
#### Type
`string`
### $\_required protected
Is this option required?
#### Type
`bool`
cakephp Class TypeFactory Class TypeFactory
==================
Factory for building database type classes.
**Namespace:** [Cake\Database](namespace-cake.database)
Property Summary
----------------
* [$\_builtTypes](#%24_builtTypes) protected static `arrayCake\Database\TypeInterface>` Contains a map of type object instances to be reused if needed.
* [$\_types](#%24_types) protected static `array<string, string>` List of supported database types. A human readable identifier is used as key and a complete namespaced class name as value representing the class that will do actual type conversions.
Method Summary
--------------
* ##### [build()](#build()) public static
Returns a Type object capable of converting a type identified by name.
* ##### [buildAll()](#buildAll()) public static
Returns an arrays with all the mapped type objects, indexed by name.
* ##### [clear()](#clear()) public static
Clears out all created instances and mapped types classes, useful for testing
* ##### [getMap()](#getMap()) public static
Get mapped class name for given type or map array.
* ##### [map()](#map()) public static
Registers a new type identifier and maps it to a fully namespaced classname.
* ##### [set()](#set()) public static
Set TypeInterface instance capable of converting a type identified by $name
* ##### [setMap()](#setMap()) public static
Set type to classname mapping.
Method Detail
-------------
### build() public static
```
build(string $name): Cake\Database\TypeInterface
```
Returns a Type object capable of converting a type identified by name.
#### Parameters
`string` $name type identifier
#### Returns
`Cake\Database\TypeInterface`
#### Throws
`InvalidArgumentException`
If type identifier is unknown ### buildAll() public static
```
buildAll(): arrayCake\Database\TypeInterface>
```
Returns an arrays with all the mapped type objects, indexed by name.
#### Returns
`arrayCake\Database\TypeInterface>`
### clear() public static
```
clear(): void
```
Clears out all created instances and mapped types classes, useful for testing
#### Returns
`void`
### getMap() public static
```
getMap(string|null $type = null): array<string>|string|null
```
Get mapped class name for given type or map array.
#### Parameters
`string|null` $type optional Type name to get mapped class for or null to get map array.
#### Returns
`array<string>|string|null`
### map() public static
```
map(string $type, string $className): void
```
Registers a new type identifier and maps it to a fully namespaced classname.
#### Parameters
`string` $type Name of type to map.
`string` $className The classname to register.
#### Returns
`void`
### set() public static
```
set(string $name, Cake\Database\TypeInterface $instance): void
```
Set TypeInterface instance capable of converting a type identified by $name
#### Parameters
`string` $name The type identifier you want to set.
`Cake\Database\TypeInterface` $instance The type instance you want to set.
#### Returns
`void`
### setMap() public static
```
setMap(array<string> $map): void
```
Set type to classname mapping.
#### Parameters
`array<string>` $map List of types to be mapped.
#### Returns
`void`
Property Detail
---------------
### $\_builtTypes protected static
Contains a map of type object instances to be reused if needed.
#### Type
`arrayCake\Database\TypeInterface>`
### $\_types protected static
List of supported database types. A human readable identifier is used as key and a complete namespaced class name as value representing the class that will do actual type conversions.
#### Type
`array<string, string>`
cakephp Class ArrayEngine Class ArrayEngine
==================
Array storage engine for cache.
Not actually a persistent cache engine. All data is only stored in memory for the duration of a single process. While not useful in production settings this engine can be useful in tests or console tools where you don't want the overhead of interacting with a cache servers, but want the work saving properties a cache provides.
**Namespace:** [Cake\Cache\Engine](namespace-cake.cache.engine)
Constants
---------
* `string` **CHECK\_KEY**
```
'key'
```
* `string` **CHECK\_VALUE**
```
'value'
```
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` The default cache configuration is overridden in most cache adapters. These are the keys that are common to all adapters. If overridden, this property is not used.
* [$\_groupPrefix](#%24_groupPrefix) protected `string` Contains the compiled string with all group prefixes to be prepended to every key in this cache engine
* [$data](#%24data) protected `array<string, array>` Cached data.
Method Summary
--------------
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_key()](#_key()) protected
Generates a key for cache backend usage.
* ##### [add()](#add()) public
Add a key to the cache if it does not already exist.
* ##### [clear()](#clear()) public
Delete all keys from the cache. This will clear every cache config using APC.
* ##### [clearGroup()](#clearGroup()) public
Increments the group value to simulate deletion of all keys under a group old values will remain in storage until they expire.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [decrement()](#decrement()) public
Decrements the value of an integer cached key
* ##### [delete()](#delete()) public
Delete a key from the cache
* ##### [deleteMultiple()](#deleteMultiple()) public
Deletes multiple cache items as a list
* ##### [duration()](#duration()) protected
Convert the various expressions of a TTL value into duration in seconds
* ##### [ensureValidKey()](#ensureValidKey()) protected
Ensure the validity of the given cache key.
* ##### [ensureValidType()](#ensureValidType()) protected
Ensure the validity of the argument type and cache keys.
* ##### [get()](#get()) public
Read a key from the cache
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getMultiple()](#getMultiple()) public
Obtains multiple cache items by their unique keys.
* ##### [groups()](#groups()) public
Returns the `group value` for each of the configured groups If the group initial value was not found, then it initializes the group accordingly.
* ##### [has()](#has()) public
Determines whether an item is present in the cache.
* ##### [increment()](#increment()) public
Increments the value of an integer cached key
* ##### [init()](#init()) public
Initialize the cache engine
* ##### [set()](#set()) public
Write data for key into cache
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setMultiple()](#setMultiple()) public
Persists a set of key => value pairs in the cache, with an optional TTL.
* ##### [warning()](#warning()) protected
Cache Engines may trigger warnings if they encounter failures during operation, if option warnOnWriteFailures is set to true.
Method Detail
-------------
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_key() protected
```
_key(string $key): string
```
Generates a key for cache backend usage.
If the requested key is valid, the group prefix value and engine prefix are applied. Whitespace in keys will be replaced.
#### Parameters
`string` $key the key passed over
#### Returns
`string`
#### Throws
`Cake\Cache\InvalidArgumentException`
If key's value is invalid. ### add() public
```
add(string $key, mixed $value): bool
```
Add a key to the cache if it does not already exist.
Defaults to a non-atomic implementation. Subclasses should prefer atomic implementations.
#### Parameters
`string` $key Identifier for the data.
`mixed` $value Data to be cached.
#### Returns
`bool`
### clear() public
```
clear(): bool
```
Delete all keys from the cache. This will clear every cache config using APC.
#### Returns
`bool`
### clearGroup() public
```
clearGroup(string $group): bool
```
Increments the group value to simulate deletion of all keys under a group old values will remain in storage until they expire.
Each implementation needs to decide whether actually delete the keys or just augment a group generation value to achieve the same result.
#### Parameters
`string` $group The group to clear.
#### Returns
`bool`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### decrement() public
```
decrement(string $key, int $offset = 1): int|false
```
Decrements the value of an integer cached key
#### Parameters
`string` $key Identifier for the data
`int` $offset optional How much to subtract
#### Returns
`int|false`
### delete() public
```
delete(string $key): bool
```
Delete a key from the cache
#### Parameters
`string` $key Identifier for the data
#### Returns
`bool`
### deleteMultiple() public
```
deleteMultiple(iterable $keys): bool
```
Deletes multiple cache items as a list
This is a best effort attempt. If deleting an item would create an error it will be ignored, and all items will be attempted.
#### Parameters
`iterable` $keys A list of string-based keys to be deleted.
#### Returns
`bool`
#### Throws
`Cake\Cache\InvalidArgumentException`
If $keys is neither an array nor a Traversable, or if any of the $keys are not a legal value. ### duration() protected
```
duration(DateInterval|int|null $ttl): int
```
Convert the various expressions of a TTL value into duration in seconds
#### Parameters
`DateInterval|int|null` $ttl The TTL value of this item. If null is sent, the driver's default duration will be used.
#### Returns
`int`
### ensureValidKey() protected
```
ensureValidKey(string $key): void
```
Ensure the validity of the given cache key.
#### Parameters
`string` $key Key to check.
#### Returns
`void`
#### Throws
`Cake\Cache\InvalidArgumentException`
When the key is not valid. ### ensureValidType() protected
```
ensureValidType(iterable $iterable, string $check = self::CHECK_VALUE): void
```
Ensure the validity of the argument type and cache keys.
#### Parameters
`iterable` $iterable The iterable to check.
`string` $check optional Whether to check keys or values.
#### Returns
`void`
#### Throws
`Cake\Cache\InvalidArgumentException`
### get() public
```
get(string $key, mixed $default = null): mixed
```
Read a key from the cache
#### Parameters
`string` $key Identifier for the data
`mixed` $default optional Default value to return if the key does not exist.
#### Returns
`mixed`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getMultiple() public
```
getMultiple(iterable $keys, mixed $default = null): iterable
```
Obtains multiple cache items by their unique keys.
#### Parameters
`iterable` $keys A list of keys that can obtained in a single operation.
`mixed` $default optional Default value to return for keys that do not exist.
#### Returns
`iterable`
#### Throws
`Cake\Cache\InvalidArgumentException`
If $keys is neither an array nor a Traversable, or if any of the $keys are not a legal value. ### groups() public
```
groups(): array<string>
```
Returns the `group value` for each of the configured groups If the group initial value was not found, then it initializes the group accordingly.
#### Returns
`array<string>`
### has() public
```
has(string $key): bool
```
Determines whether an item is present in the cache.
NOTE: It is recommended that has() is only to be used for cache warming type purposes and not to be used within your live applications operations for get/set, as this method is subject to a race condition where your has() will return true and immediately after, another script can remove it making the state of your app out of date.
#### Parameters
`string` $key The cache item key.
#### Returns
`bool`
#### Throws
`Cake\Cache\InvalidArgumentException`
If the $key string is not a legal value. ### increment() public
```
increment(string $key, int $offset = 1): int|false
```
Increments the value of an integer cached key
#### Parameters
`string` $key Identifier for the data
`int` $offset optional How much to increment
#### Returns
`int|false`
### init() public
```
init(array<string, mixed> $config = []): bool
```
Initialize the cache engine
Called automatically by the cache frontend. Merge the runtime config with the defaults before use.
#### Parameters
`array<string, mixed>` $config optional Associative array of parameters for the engine
#### Returns
`bool`
### set() public
```
set(string $key, mixed $value, null|intDateInterval $ttl = null): bool
```
Write data for key into cache
#### Parameters
`string` $key Identifier for the data
`mixed` $value Data to be cached
`null|intDateInterval` $ttl optional Optional. The TTL value of this item. If no value is sent and the driver supports TTL then the library may set a default value for it or let the driver take care of that.
#### Returns
`bool`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setMultiple() public
```
setMultiple(iterable $values, null|intDateInterval $ttl = null): bool
```
Persists a set of key => value pairs in the cache, with an optional TTL.
#### Parameters
`iterable` $values A list of key => value pairs for a multiple-set operation.
`null|intDateInterval` $ttl optional Optional. The TTL value of this item. If no value is sent and the driver supports TTL then the library may set a default value for it or let the driver take care of that.
#### Returns
`bool`
#### Throws
`Cake\Cache\InvalidArgumentException`
If $values is neither an array nor a Traversable, or if any of the $values are not a legal value. ### warning() protected
```
warning(string $message): void
```
Cache Engines may trigger warnings if they encounter failures during operation, if option warnOnWriteFailures is set to true.
#### Parameters
`string` $message The warning message.
#### Returns
`void`
Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
The default cache configuration is overridden in most cache adapters. These are the keys that are common to all adapters. If overridden, this property is not used.
* `duration` Specify how long items in this cache configuration last.
* `groups` List of groups or 'tags' associated to every key stored in this config. handy for deleting a complete group from cache.
* `prefix` Prefix appended to all entries. Good for when you need to share a keyspace with either another cache config or another application.
* `warnOnWriteFailures` Some engines, such as ApcuEngine, may raise warnings on write failures.
#### Type
`array<string, mixed>`
### $\_groupPrefix protected
Contains the compiled string with all group prefixes to be prepended to every key in this cache engine
#### Type
`string`
### $data protected
Cached data.
Structured as [key => [exp => expiration, val => value]]
#### Type
`array<string, array>`
| programming_docs |
cakephp Class PluginAssetsCopyCommand Class PluginAssetsCopyCommand
==============================
Command for copying plugin assets to app's webroot.
**Namespace:** [Cake\Command](namespace-cake.command)
Constants
---------
* `int` **CODE\_ERROR**
```
1
```
Default error code
* `int` **CODE\_SUCCESS**
```
0
```
Default success code
Property Summary
----------------
* [$\_modelFactories](#%24_modelFactories) protected `array<callableCake\Datasource\Locator\LocatorInterface>` A list of overridden model factory functions.
* [$\_modelType](#%24_modelType) protected `string` The model type to use.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$args](#%24args) protected `Cake\Console\Arguments` Arguments
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
* [$io](#%24io) protected `Cake\Console\ConsoleIo` Console IO
* [$modelClass](#%24modelClass) protected deprecated `string|null` This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
* [$name](#%24name) protected `string` The name of this command.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_copyDirectory()](#_copyDirectory()) protected
Copy directory
* ##### [\_createDirectory()](#_createDirectory()) protected
Create directory
* ##### [\_createSymlink()](#_createSymlink()) protected
Create symlink
* ##### [\_list()](#_list()) protected
Get list of plugins to process. Plugins without a webroot directory are skipped.
* ##### [\_process()](#_process()) protected
Process plugins
* ##### [\_remove()](#_remove()) protected
Remove folder/symlink.
* ##### [\_setModelClass()](#_setModelClass()) protected
Set the modelClass property based on conventions.
* ##### [abort()](#abort()) public
Halt the the current process with a StopException.
* ##### [buildOptionParser()](#buildOptionParser()) public
Get the option parser.
* ##### [defaultName()](#defaultName()) public static
Get the command name.
* ##### [displayHelp()](#displayHelp()) protected
Output help content
* ##### [execute()](#execute()) public
Execute the command
* ##### [executeCommand()](#executeCommand()) public
Execute another command with the provided set of arguments.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getDescription()](#getDescription()) public static
Get the command description.
* ##### [getModelType()](#getModelType()) public
Get the model type to be used by this class
* ##### [getName()](#getName()) public
Get the command name.
* ##### [getOptionParser()](#getOptionParser()) public
Get the option parser.
* ##### [getRootName()](#getRootName()) public
Get the root command name.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [initialize()](#initialize()) public
Hook method invoked by CakePHP when a command is about to be executed.
* ##### [loadModel()](#loadModel()) public deprecated
Loads and constructs repository objects required by this object
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [modelFactory()](#modelFactory()) public
Override a existing callable to generate repositories of a given type.
* ##### [run()](#run()) public
Run the command.
* ##### [setModelType()](#setModelType()) public
Set the model type to be used by this class
* ##### [setName()](#setName()) public
Set the name this command uses in the collection.
* ##### [setOutputLevel()](#setOutputLevel()) protected
Set the output level based on the Arguments.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
Method Detail
-------------
### \_\_construct() public
```
__construct()
```
Constructor
By default CakePHP will construct command objects when building the CommandCollection for your application.
### \_copyDirectory() protected
```
_copyDirectory(string $source, string $destination): bool
```
Copy directory
#### Parameters
`string` $source Source directory
`string` $destination Destination directory
#### Returns
`bool`
### \_createDirectory() protected
```
_createDirectory(string $dir): bool
```
Create directory
#### Parameters
`string` $dir Directory name
#### Returns
`bool`
### \_createSymlink() protected
```
_createSymlink(string $target, string $link): bool
```
Create symlink
#### Parameters
`string` $target Target directory
`string` $link Link name
#### Returns
`bool`
### \_list() protected
```
_list(string|null $name = null): array<string, mixed>
```
Get list of plugins to process. Plugins without a webroot directory are skipped.
#### Parameters
`string|null` $name optional Name of plugin for which to symlink assets. If null all plugins will be processed.
#### Returns
`array<string, mixed>`
### \_process() protected
```
_process(array<string, mixed> $plugins, bool $copy = false, bool $overwrite = false): void
```
Process plugins
#### Parameters
`array<string, mixed>` $plugins List of plugins to process
`bool` $copy optional Force copy mode. Default false.
`bool` $overwrite optional Overwrite existing files.
#### Returns
`void`
### \_remove() protected
```
_remove(array<string, mixed> $config): bool
```
Remove folder/symlink.
#### Parameters
`array<string, mixed>` $config Plugin config.
#### Returns
`bool`
### \_setModelClass() protected
```
_setModelClass(string $name): void
```
Set the modelClass property based on conventions.
If the property is already set it will not be overwritten
#### Parameters
`string` $name Class name.
#### Returns
`void`
### abort() public
```
abort(int $code = self::CODE_ERROR): void
```
Halt the the current process with a StopException.
#### Parameters
`int` $code optional The exit code to use.
#### Returns
`void`
#### Throws
`Cake\Console\Exception\StopException`
### buildOptionParser() public
```
buildOptionParser(Cake\Console\ConsoleOptionParser $parser): Cake\Console\ConsoleOptionParser
```
Get the option parser.
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser to update
#### Returns
`Cake\Console\ConsoleOptionParser`
### defaultName() public static
```
defaultName(): string
```
Get the command name.
Returns the command name based on class name. For e.g. for a command with class name `UpdateTableCommand` the default name returned would be `'update_table'`.
#### Returns
`string`
### displayHelp() protected
```
displayHelp(Cake\Console\ConsoleOptionParser $parser, Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Output help content
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser.
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### execute() public
```
execute(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): int|null
```
Execute the command
Copying plugin assets to app's webroot. For vendor namespaced plugin, parent folder for vendor name are created if required.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`int|null`
### executeCommand() public
```
executeCommand(Cake\Console\CommandInterface|string $command, array $args = [], Cake\Console\ConsoleIo|null $io = null): int|null
```
Execute another command with the provided set of arguments.
If you are using a string command name, that command's dependencies will not be resolved with the application container. Instead you will need to pass the command as an object with all of its dependencies.
#### Parameters
`Cake\Console\CommandInterface|string` $command The command class name or command instance.
`array` $args optional The arguments to invoke the command with.
`Cake\Console\ConsoleIo|null` $io optional The ConsoleIo instance to use for the executed command.
#### Returns
`int|null`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getDescription() public static
```
getDescription(): string
```
Get the command description.
#### Returns
`string`
### getModelType() public
```
getModelType(): string
```
Get the model type to be used by this class
#### Returns
`string`
### getName() public
```
getName(): string
```
Get the command name.
#### Returns
`string`
### getOptionParser() public
```
getOptionParser(): Cake\Console\ConsoleOptionParser
```
Get the option parser.
You can override buildOptionParser() to define your options & arguments.
#### Returns
`Cake\Console\ConsoleOptionParser`
#### Throws
`RuntimeException`
When the parser is invalid ### getRootName() public
```
getRootName(): string
```
Get the root command name.
#### Returns
`string`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### initialize() public
```
initialize(): void
```
Hook method invoked by CakePHP when a command is about to be executed.
Override this method and implement expensive/important setup steps that should not run on every command run. This method will be called *before* the options and arguments are validated and processed.
#### Returns
`void`
### loadModel() public
```
loadModel(string|null $modelClass = null, string|null $modelType = null): Cake\Datasource\RepositoryInterface
```
Loads and constructs repository objects required by this object
Typically used to load ORM Table objects as required. Can also be used to load other types of repository objects your application uses.
If a repository provider does not return an object a MissingModelException will be thrown.
#### Parameters
`string|null` $modelClass optional Name of model class to load. Defaults to $this->modelClass. The name can be an alias like `'Post'` or FQCN like `App\Model\Table\PostsTable::class`.
`string|null` $modelType optional The type of repository to load. Defaults to the getModelType() value.
#### Returns
`Cake\Datasource\RepositoryInterface`
#### Throws
`Cake\Datasource\Exception\MissingModelException`
If the model class cannot be found.
`UnexpectedValueException`
If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty. ### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### modelFactory() public
```
modelFactory(string $type, Cake\Datasource\Locator\LocatorInterface|callable $factory): void
```
Override a existing callable to generate repositories of a given type.
#### Parameters
`string` $type The name of the repository type the factory function is for.
`Cake\Datasource\Locator\LocatorInterface|callable` $factory The factory function used to create instances.
#### Returns
`void`
### run() public
```
run(array $argv, Cake\Console\ConsoleIo $io): int|null
```
Run the command.
#### Parameters
`array` $argv `Cake\Console\ConsoleIo` $io #### Returns
`int|null`
### setModelType() public
```
setModelType(string $modelType): $this
```
Set the model type to be used by this class
#### Parameters
`string` $modelType The model type
#### Returns
`$this`
### setName() public
```
setName(string $name): $this
```
Set the name this command uses in the collection.
Generally invoked by the CommandCollection when the command is added. Required to have at least one space in the name so that the root command can be calculated.
#### Parameters
`string` $name #### Returns
`$this`
### setOutputLevel() protected
```
setOutputLevel(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Set the output level based on the Arguments.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
Property Detail
---------------
### $\_modelFactories protected
A list of overridden model factory functions.
#### Type
`array<callableCake\Datasource\Locator\LocatorInterface>`
### $\_modelType protected
The model type to use.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $args protected
Arguments
#### Type
`Cake\Console\Arguments`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
### $io protected
Console IO
#### Type
`Cake\Console\ConsoleIo`
### $modelClass protected deprecated
This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
Example: For an object named 'Comments', the modelClass would be 'Comments'. Plugin classes should use `Plugin.Comments` style names to correctly load models from the correct plugin.
Use empty string to not use auto-loading on this object. Null auto-detects based on controller name.
#### Type
`string|null`
### $name protected
The name of this command.
#### Type
`string`
cakephp Class DateTimeFractionalType Class DateTimeFractionalType
=============================
Extends DateTimeType with support for fractional seconds up to microseconds.
**Namespace:** [Cake\Database\Type](namespace-cake.database.type)
Property Summary
----------------
* [$\_className](#%24_className) protected `string` The classname to use when creating objects.
* [$\_format](#%24_format) protected `string` The DateTime format used when converting to string.
* [$\_localeMarshalFormat](#%24_localeMarshalFormat) protected `array|string|int` The locale-aware format `marshal()` uses when `_useLocaleParser` is true.
* [$\_marshalFormats](#%24_marshalFormats) protected `array<string>` The DateTime formats allowed by `marshal()`.
* [$\_name](#%24_name) protected `string|null` Identifier name for this type
* [$\_useLocaleMarshal](#%24_useLocaleMarshal) protected `bool` Whether `marshal()` should use locale-aware parser with `_localeMarshalFormat`.
* [$dbTimezone](#%24dbTimezone) protected `DateTimeZone|null` Database time zone.
* [$defaultTimezone](#%24defaultTimezone) protected `DateTimeZone` Default time zone.
* [$keepDatabaseTimezone](#%24keepDatabaseTimezone) protected `bool` Whether database time zone is kept when converting
* [$setToDateStart](#%24setToDateStart) protected `bool` Whether we want to override the time of the converted Time objects so it points to the start of the day.
* [$userTimezone](#%24userTimezone) protected `DateTimeZone|null` User time zone.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_parseLocaleValue()](#_parseLocaleValue()) protected
Converts a string into a DateTime object after parsing it using the locale aware parser with the format set by `setLocaleFormat()`.
* ##### [\_parseValue()](#_parseValue()) protected
Converts a string into a DateTime object after parsing it using the formats in `_marshalFormats`.
* ##### [\_setClassName()](#_setClassName()) protected
Set the classname to use when building objects.
* ##### [getBaseType()](#getBaseType()) public
Returns the base type name that this class is inheriting.
* ##### [getDateTimeClassName()](#getDateTimeClassName()) public
Get the classname used for building objects.
* ##### [getName()](#getName()) public
Returns type identifier name for this object.
* ##### [manyToPHP()](#manyToPHP()) public
Returns an array of the values converted to the PHP representation of this type.
* ##### [marshal()](#marshal()) public
Convert request data into a datetime object.
* ##### [newId()](#newId()) public
Generate a new primary key value for a given type.
* ##### [setDatabaseTimezone()](#setDatabaseTimezone()) public
Set database timezone.
* ##### [setKeepDatabaseTimezone()](#setKeepDatabaseTimezone()) public
Set whether DateTime object created from database string is converted to default time zone.
* ##### [setLocaleFormat()](#setLocaleFormat()) public
Sets the locale-aware format used by `marshal()` when parsing strings.
* ##### [setTimezone()](#setTimezone()) public deprecated
Alias for `setDatabaseTimezone()`.
* ##### [setUserTimezone()](#setUserTimezone()) public
Set user timezone.
* ##### [toDatabase()](#toDatabase()) public
Convert DateTime instance into strings.
* ##### [toPHP()](#toPHP()) public
Casts given value from a database type to a PHP equivalent.
* ##### [toStatement()](#toStatement()) public
Casts given value to Statement equivalent
* ##### [useImmutable()](#useImmutable()) public deprecated
Change the preferred class name to the FrozenTime implementation.
* ##### [useLocaleParser()](#useLocaleParser()) public
Sets whether to parse strings passed to `marshal()` using the locale-aware format set by `setLocaleFormat()`.
* ##### [useMutable()](#useMutable()) public deprecated
Change the preferred class name to the mutable Time implementation.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $name = null)
```
Constructor
#### Parameters
`string|null` $name optional The name identifying this type
### \_parseLocaleValue() protected
```
_parseLocaleValue(string $value): Cake\I18n\I18nDateTimeInterface|null
```
Converts a string into a DateTime object after parsing it using the locale aware parser with the format set by `setLocaleFormat()`.
#### Parameters
`string` $value The value to parse and convert to an object.
#### Returns
`Cake\I18n\I18nDateTimeInterface|null`
### \_parseValue() protected
```
_parseValue(string $value): DateTimeInterface|null
```
Converts a string into a DateTime object after parsing it using the formats in `_marshalFormats`.
#### Parameters
`string` $value The value to parse and convert to an object.
#### Returns
`DateTimeInterface|null`
### \_setClassName() protected
```
_setClassName(string $class, string $fallback): void
```
Set the classname to use when building objects.
#### Parameters
`string` $class The classname to use.
`string` $fallback The classname to use when the preferred class does not exist.
#### Returns
`void`
### getBaseType() public
```
getBaseType(): string|null
```
Returns the base type name that this class is inheriting.
This is useful when extending base type for adding extra functionality, but still want the rest of the framework to use the same assumptions it would do about the base type it inherits from.
#### Returns
`string|null`
### getDateTimeClassName() public
```
getDateTimeClassName(): string
```
Get the classname used for building objects.
#### Returns
`string`
### getName() public
```
getName(): string|null
```
Returns type identifier name for this object.
#### Returns
`string|null`
### manyToPHP() public
```
manyToPHP(array $values, array<string> $fields, Cake\Database\DriverInterface $driver): array<string, mixed>
```
Returns an array of the values converted to the PHP representation of this type.
#### Parameters
`array` $values `array<string>` $fields `Cake\Database\DriverInterface` $driver #### Returns
`array<string, mixed>`
### marshal() public
```
marshal(mixed $value): DateTimeInterface|null
```
Convert request data into a datetime object.
Most useful for converting request data into PHP objects, that make sense for the rest of the ORM/Database layers.
#### Parameters
`mixed` $value Request data
#### Returns
`DateTimeInterface|null`
### newId() public
```
newId(): mixed
```
Generate a new primary key value for a given type.
This method can be used by types to create new primary key values when entities are inserted.
#### Returns
`mixed`
### setDatabaseTimezone() public
```
setDatabaseTimezone(DateTimeZone|string|null $timezone): $this
```
Set database timezone.
This is the time zone used when converting database strings to DateTime instances and converting DateTime instances to database strings.
#### Parameters
`DateTimeZone|string|null` $timezone Database timezone.
#### Returns
`$this`
#### See Also
DateTimeType::setKeepDatabaseTimezone ### setKeepDatabaseTimezone() public
```
setKeepDatabaseTimezone(bool $keep): $this
```
Set whether DateTime object created from database string is converted to default time zone.
If your database date times are in a specific time zone that you want to keep in the DateTime instance then set this to true.
When false, datetime timezones are converted to default time zone. This is default behavior.
#### Parameters
`bool` $keep If true, database time zone is kept when converting to DateTime instances.
#### Returns
`$this`
### setLocaleFormat() public
```
setLocaleFormat(array|string $format): $this
```
Sets the locale-aware format used by `marshal()` when parsing strings.
See `Cake\I18n\Time::parseDateTime()` for accepted formats.
#### Parameters
`array|string` $format The locale-aware format
#### Returns
`$this`
#### See Also
\Cake\I18n\Time::parseDateTime() ### setTimezone() public
```
setTimezone(DateTimeZone|string|null $timezone): $this
```
Alias for `setDatabaseTimezone()`.
#### Parameters
`DateTimeZone|string|null` $timezone Database timezone.
#### Returns
`$this`
### setUserTimezone() public
```
setUserTimezone(DateTimeZone|string|null $timezone): $this
```
Set user timezone.
This is the time zone used when marshalling strings to DateTime instances.
#### Parameters
`DateTimeZone|string|null` $timezone User timezone.
#### Returns
`$this`
### toDatabase() public
```
toDatabase(mixed $value, Cake\Database\DriverInterface $driver): string|null
```
Convert DateTime instance into strings.
#### Parameters
`mixed` $value The value to convert.
`Cake\Database\DriverInterface` $driver The driver instance to convert with.
#### Returns
`string|null`
### toPHP() public
```
toPHP(mixed $value, Cake\Database\DriverInterface $driver): DateTimeInterface|null
```
Casts given value from a database type to a PHP equivalent.
#### Parameters
`mixed` $value Value to be converted to PHP equivalent
`Cake\Database\DriverInterface` $driver Object from which database preferences and configuration will be extracted
#### Returns
`DateTimeInterface|null`
### toStatement() public
```
toStatement(mixed $value, Cake\Database\DriverInterface $driver): mixed
```
Casts given value to Statement equivalent
#### Parameters
`mixed` $value value to be converted to PDO statement
`Cake\Database\DriverInterface` $driver object from which database preferences and configuration will be extracted
#### Returns
`mixed`
### useImmutable() public
```
useImmutable(): $this
```
Change the preferred class name to the FrozenTime implementation.
#### Returns
`$this`
### useLocaleParser() public
```
useLocaleParser(bool $enable = true): $this
```
Sets whether to parse strings passed to `marshal()` using the locale-aware format set by `setLocaleFormat()`.
#### Parameters
`bool` $enable optional Whether to enable
#### Returns
`$this`
### useMutable() public
```
useMutable(): $this
```
Change the preferred class name to the mutable Time implementation.
#### Returns
`$this`
Property Detail
---------------
### $\_className protected
The classname to use when creating objects.
#### Type
`string`
### $\_format protected
The DateTime format used when converting to string.
#### Type
`string`
### $\_localeMarshalFormat protected
The locale-aware format `marshal()` uses when `_useLocaleParser` is true.
See `Cake\I18n\Time::parseDateTime()` for accepted formats.
#### Type
`array|string|int`
### $\_marshalFormats protected
The DateTime formats allowed by `marshal()`.
#### Type
`array<string>`
### $\_name protected
Identifier name for this type
#### Type
`string|null`
### $\_useLocaleMarshal protected
Whether `marshal()` should use locale-aware parser with `_localeMarshalFormat`.
#### Type
`bool`
### $dbTimezone protected
Database time zone.
#### Type
`DateTimeZone|null`
### $defaultTimezone protected
Default time zone.
#### Type
`DateTimeZone`
### $keepDatabaseTimezone protected
Whether database time zone is kept when converting
#### Type
`bool`
### $setToDateStart protected
Whether we want to override the time of the converted Time objects so it points to the start of the day.
This is primarily to avoid subclasses needing to re-implement the same functionality.
#### Type
`bool`
### $userTimezone protected
User time zone.
#### Type
`DateTimeZone|null`
| programming_docs |
cakephp Class RoutesCheckCommand Class RoutesCheckCommand
=========================
Provides interactive CLI tool for testing routes.
**Namespace:** [Cake\Command](namespace-cake.command)
Constants
---------
* `int` **CODE\_ERROR**
```
1
```
Default error code
* `int` **CODE\_SUCCESS**
```
0
```
Default success code
Property Summary
----------------
* [$\_modelFactories](#%24_modelFactories) protected `array<callableCake\Datasource\Locator\LocatorInterface>` A list of overridden model factory functions.
* [$\_modelType](#%24_modelType) protected `string` The model type to use.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
* [$modelClass](#%24modelClass) protected deprecated `string|null` This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
* [$name](#%24name) protected `string` The name of this command.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_setModelClass()](#_setModelClass()) protected
Set the modelClass property based on conventions.
* ##### [abort()](#abort()) public
Halt the the current process with a StopException.
* ##### [buildOptionParser()](#buildOptionParser()) public
Get the option parser.
* ##### [defaultName()](#defaultName()) public static
Get the command name.
* ##### [displayHelp()](#displayHelp()) protected
Output help content
* ##### [execute()](#execute()) public
Display all routes in an application
* ##### [executeCommand()](#executeCommand()) public
Execute another command with the provided set of arguments.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getDescription()](#getDescription()) public static
Get the command description.
* ##### [getModelType()](#getModelType()) public
Get the model type to be used by this class
* ##### [getName()](#getName()) public
Get the command name.
* ##### [getOptionParser()](#getOptionParser()) public
Get the option parser.
* ##### [getRootName()](#getRootName()) public
Get the root command name.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [initialize()](#initialize()) public
Hook method invoked by CakePHP when a command is about to be executed.
* ##### [loadModel()](#loadModel()) public deprecated
Loads and constructs repository objects required by this object
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [modelFactory()](#modelFactory()) public
Override a existing callable to generate repositories of a given type.
* ##### [run()](#run()) public
Run the command.
* ##### [setModelType()](#setModelType()) public
Set the model type to be used by this class
* ##### [setName()](#setName()) public
Set the name this command uses in the collection.
* ##### [setOutputLevel()](#setOutputLevel()) protected
Set the output level based on the Arguments.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
Method Detail
-------------
### \_\_construct() public
```
__construct()
```
Constructor
By default CakePHP will construct command objects when building the CommandCollection for your application.
### \_setModelClass() protected
```
_setModelClass(string $name): void
```
Set the modelClass property based on conventions.
If the property is already set it will not be overwritten
#### Parameters
`string` $name Class name.
#### Returns
`void`
### abort() public
```
abort(int $code = self::CODE_ERROR): void
```
Halt the the current process with a StopException.
#### Parameters
`int` $code optional The exit code to use.
#### Returns
`void`
#### Throws
`Cake\Console\Exception\StopException`
### buildOptionParser() public
```
buildOptionParser(Cake\Console\ConsoleOptionParser $parser): Cake\Console\ConsoleOptionParser
```
Get the option parser.
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser to update
#### Returns
`Cake\Console\ConsoleOptionParser`
### defaultName() public static
```
defaultName(): string
```
Get the command name.
Returns the command name based on class name. For e.g. for a command with class name `UpdateTableCommand` the default name returned would be `'update_table'`.
#### Returns
`string`
### displayHelp() protected
```
displayHelp(Cake\Console\ConsoleOptionParser $parser, Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Output help content
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser.
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### execute() public
```
execute(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): int|null
```
Display all routes in an application
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`int|null`
### executeCommand() public
```
executeCommand(Cake\Console\CommandInterface|string $command, array $args = [], Cake\Console\ConsoleIo|null $io = null): int|null
```
Execute another command with the provided set of arguments.
If you are using a string command name, that command's dependencies will not be resolved with the application container. Instead you will need to pass the command as an object with all of its dependencies.
#### Parameters
`Cake\Console\CommandInterface|string` $command The command class name or command instance.
`array` $args optional The arguments to invoke the command with.
`Cake\Console\ConsoleIo|null` $io optional The ConsoleIo instance to use for the executed command.
#### Returns
`int|null`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getDescription() public static
```
getDescription(): string
```
Get the command description.
#### Returns
`string`
### getModelType() public
```
getModelType(): string
```
Get the model type to be used by this class
#### Returns
`string`
### getName() public
```
getName(): string
```
Get the command name.
#### Returns
`string`
### getOptionParser() public
```
getOptionParser(): Cake\Console\ConsoleOptionParser
```
Get the option parser.
You can override buildOptionParser() to define your options & arguments.
#### Returns
`Cake\Console\ConsoleOptionParser`
#### Throws
`RuntimeException`
When the parser is invalid ### getRootName() public
```
getRootName(): string
```
Get the root command name.
#### Returns
`string`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### initialize() public
```
initialize(): void
```
Hook method invoked by CakePHP when a command is about to be executed.
Override this method and implement expensive/important setup steps that should not run on every command run. This method will be called *before* the options and arguments are validated and processed.
#### Returns
`void`
### loadModel() public
```
loadModel(string|null $modelClass = null, string|null $modelType = null): Cake\Datasource\RepositoryInterface
```
Loads and constructs repository objects required by this object
Typically used to load ORM Table objects as required. Can also be used to load other types of repository objects your application uses.
If a repository provider does not return an object a MissingModelException will be thrown.
#### Parameters
`string|null` $modelClass optional Name of model class to load. Defaults to $this->modelClass. The name can be an alias like `'Post'` or FQCN like `App\Model\Table\PostsTable::class`.
`string|null` $modelType optional The type of repository to load. Defaults to the getModelType() value.
#### Returns
`Cake\Datasource\RepositoryInterface`
#### Throws
`Cake\Datasource\Exception\MissingModelException`
If the model class cannot be found.
`UnexpectedValueException`
If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty. ### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### modelFactory() public
```
modelFactory(string $type, Cake\Datasource\Locator\LocatorInterface|callable $factory): void
```
Override a existing callable to generate repositories of a given type.
#### Parameters
`string` $type The name of the repository type the factory function is for.
`Cake\Datasource\Locator\LocatorInterface|callable` $factory The factory function used to create instances.
#### Returns
`void`
### run() public
```
run(array $argv, Cake\Console\ConsoleIo $io): int|null
```
Run the command.
#### Parameters
`array` $argv `Cake\Console\ConsoleIo` $io #### Returns
`int|null`
### setModelType() public
```
setModelType(string $modelType): $this
```
Set the model type to be used by this class
#### Parameters
`string` $modelType The model type
#### Returns
`$this`
### setName() public
```
setName(string $name): $this
```
Set the name this command uses in the collection.
Generally invoked by the CommandCollection when the command is added. Required to have at least one space in the name so that the root command can be calculated.
#### Parameters
`string` $name #### Returns
`$this`
### setOutputLevel() protected
```
setOutputLevel(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Set the output level based on the Arguments.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
Property Detail
---------------
### $\_modelFactories protected
A list of overridden model factory functions.
#### Type
`array<callableCake\Datasource\Locator\LocatorInterface>`
### $\_modelType protected
The model type to use.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
### $modelClass protected deprecated
This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
Example: For an object named 'Comments', the modelClass would be 'Comments'. Plugin classes should use `Plugin.Comments` style names to correctly load models from the correct plugin.
Use empty string to not use auto-loading on this object. Null auto-detects based on controller name.
#### Type
`string|null`
### $name protected
The name of this command.
#### Type
`string`
cakephp Namespace Fixture Namespace Fixture
=================
### Interfaces
* ##### [FixtureStrategyInterface](interface-cake.testsuite.fixture.fixturestrategyinterface)
Base interface for strategies used to manage fixtures for TestCase.
### Classes
* ##### [FixtureHelper](class-cake.testsuite.fixture.fixturehelper)
Helper for managing fixtures.
* ##### [FixtureInjector](class-cake.testsuite.fixture.fixtureinjector)
Test listener used to inject a fixture manager in all tests that are composed inside a Test Suite
* ##### [FixtureManager](class-cake.testsuite.fixture.fixturemanager)
A factory class to manage the life cycle of test fixtures
* ##### [PHPUnitExtension](class-cake.testsuite.fixture.phpunitextension)
PHPUnit extension to integrate CakePHP's data-only fixtures.
* ##### [SchemaLoader](class-cake.testsuite.fixture.schemaloader)
Create test database schema from one or more SQL dump files.
* ##### [TestFixture](class-cake.testsuite.fixture.testfixture)
Cake TestFixture is responsible for building and destroying tables to be used during testing.
* ##### [TransactionStrategy](class-cake.testsuite.fixture.transactionstrategy)
Fixture strategy that wraps fixtures in a transaction that is rolled back after each test.
* ##### [TruncateStrategy](class-cake.testsuite.fixture.truncatestrategy)
Fixture strategy that truncates all fixture ables at the end of test.
cakephp Class HeaderNotSet Class HeaderNotSet
===================
HeaderSet
**Namespace:** [Cake\TestSuite\Constraint\Response](namespace-cake.testsuite.constraint.response)
Property Summary
----------------
* [$headerName](#%24headerName) protected `string`
* [$response](#%24response) protected `Psr\Http\Message\ResponseInterface`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_getBodyAsString()](#_getBodyAsString()) protected
Get the response body as string
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Overwrites the descriptions so we can remove the automatic "expected" message
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Checks assertion
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(Psr\Http\Message\ResponseInterface|null $response, string $headerName)
```
Constructor.
#### Parameters
`Psr\Http\Message\ResponseInterface|null` $response A response instance.
`string` $headerName Header name
### \_getBodyAsString() protected
```
_getBodyAsString(): string
```
Get the response body as string
#### Returns
`string`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Overwrites the descriptions so we can remove the automatic "expected" message
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other Value
#### Returns
`string`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks assertion
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Expected content
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $headerName protected
#### Type
`string`
### $response protected
#### Type
`Psr\Http\Message\ResponseInterface`
| programming_docs |
cakephp Namespace Adapter Namespace Adapter
=================
### Classes
* ##### [Curl](class-cake.http.client.adapter.curl)
Implements sending Cake\Http\Client\Request via ext/curl.
* ##### [Mock](class-cake.http.client.adapter.mock)
Implements sending requests to an array of stubbed responses
* ##### [Stream](class-cake.http.client.adapter.stream)
Implements sending Cake\Http\Client\Request via php's stream API.
cakephp Class SecurityException Class SecurityException
========================
Security exception - used when SecurityComponent detects any issue with the current request
**Namespace:** [Cake\Controller\Exception](namespace-cake.controller.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_reason](#%24_reason) protected `string|null` Reason for request blackhole
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
* [$\_type](#%24_type) protected `string` Security Exception type
* [$headers](#%24headers) protected `array<string, mixed>`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [getHeaders()](#getHeaders()) public
Returns array of response headers.
* ##### [getReason()](#getReason()) public
Get Reason
* ##### [getType()](#getType()) public
Getter for type
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
* ##### [setHeader()](#setHeader()) public
Set a single HTTP response header.
* ##### [setHeaders()](#setHeaders()) public
Sets HTTP response headers.
* ##### [setMessage()](#setMessage()) public
Set Message
* ##### [setReason()](#setReason()) public
Set Reason
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $message = null, int|null $code = null, Throwable|null $previous = null)
```
Constructor
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`string|null` $message optional If no message is given 'Bad Request' will be the message
`int|null` $code optional Status code, defaults to 400
`Throwable|null` $previous optional The previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### getHeaders() public
```
getHeaders(): array<string, mixed>
```
Returns array of response headers.
#### Returns
`array<string, mixed>`
### getReason() public
```
getReason(): string|null
```
Get Reason
#### Returns
`string|null`
### getType() public
```
getType(): string
```
Getter for type
#### Returns
`string`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
### setHeader() public
```
setHeader(string $header, array<string>|string|null $value = null): void
```
Set a single HTTP response header.
#### Parameters
`string` $header Header name
`array<string>|string|null` $value optional Header value
#### Returns
`void`
### setHeaders() public
```
setHeaders(array<string, mixed> $headers): void
```
Sets HTTP response headers.
#### Parameters
`array<string, mixed>` $headers Array of header name and value pairs.
#### Returns
`void`
### setMessage() public
```
setMessage(string $message): void
```
Set Message
#### Parameters
`string` $message Exception message
#### Returns
`void`
### setReason() public
```
setReason(string|null $reason = null): $this
```
Set Reason
#### Parameters
`string|null` $reason optional Reason details
#### Returns
`$this`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_reason protected
Reason for request blackhole
#### Type
`string|null`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
### $\_type protected
Security Exception type
#### Type
`string`
### $headers protected
#### Type
`array<string, mixed>`
cakephp Class Route Class Route
============
A single Route used by the Router to connect requests to parameter maps.
Not normally created as a standalone. Use Router::connect() to create Routes for your application.
**Namespace:** [Cake\Routing\Route](namespace-cake.routing.route)
Constants
---------
* `string` **PLACEHOLDER\_REGEX**
```
'#\\{([a-z][a-z0-9-_]*)\\}#i'
```
Regex for matching braced placholders in route template.
* `array<string>` **VALID\_METHODS**
```
['GET', 'PUT', 'POST', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD']
```
Valid HTTP methods.
Property Summary
----------------
* [$\_compiledRoute](#%24_compiledRoute) protected `string|null` The compiled route regular expression
* [$\_extensions](#%24_extensions) protected `array<string>` List of connected extensions for this route.
* [$\_greedy](#%24_greedy) protected `bool` Is this route a greedy route? Greedy routes have a `/*` in their template
* [$\_name](#%24_name) protected `string|null` The name for a route. Fetch with Route::getName();
* [$braceKeys](#%24braceKeys) protected `bool` Track whether brace keys `{var}` were used.
* [$defaults](#%24defaults) public `array` Default parameters for a Route
* [$keys](#%24keys) public `array` An array of named segments in a Route. `/{controller}/{action}/{id}` has 3 key elements
* [$middleware](#%24middleware) protected `array` List of middleware that should be applied.
* [$options](#%24options) public `array` An array of additional parameters for the Route.
* [$template](#%24template) public `string` The routes template string.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor for a Route
* ##### [\_\_set\_state()](#__set_state()) public static
Set state magic method to support var\_export
* ##### [\_matchMethod()](#_matchMethod()) protected
Check whether the URL's HTTP method matches.
* ##### [\_parseArgs()](#_parseArgs()) protected
Parse passed parameters into a list of passed args.
* ##### [\_parseExtension()](#_parseExtension()) protected
Removes the extension from $url if it contains a registered extension. If no registered extension is found, no extension is returned and the URL is returned unmodified.
* ##### [\_persistParams()](#_persistParams()) protected
Apply persistent parameters to a URL array. Persistent parameters are a special key used during route creation to force route parameters to persist when omitted from a URL array.
* ##### [\_writeRoute()](#_writeRoute()) protected
Builds a route regular expression.
* ##### [\_writeUrl()](#_writeUrl()) protected
Converts a matching route array into a URL string.
* ##### [compile()](#compile()) public
Compiles the route's regular expression.
* ##### [compiled()](#compiled()) public
Check if a Route has been compiled into a regular expression.
* ##### [getExtensions()](#getExtensions()) public
Get the supported extensions for this route.
* ##### [getMiddleware()](#getMiddleware()) public
Get the names of the middleware that should be applied to this route.
* ##### [getName()](#getName()) public
Get the standardized plugin.controller:action name for a route.
* ##### [hostMatches()](#hostMatches()) public
Check to see if the host matches the route requirements
* ##### [match()](#match()) public
Check if a URL array matches this route instance.
* ##### [normalizeAndValidateMethods()](#normalizeAndValidateMethods()) protected
Normalize method names to upper case and validate that they are valid HTTP methods.
* ##### [parse()](#parse()) public
Checks to see if the given URL can be parsed by this route.
* ##### [parseRequest()](#parseRequest()) public
Checks to see if the given URL can be parsed by this route.
* ##### [setExtensions()](#setExtensions()) public
Set the supported extensions for this route.
* ##### [setHost()](#setHost()) public
Set host requirement
* ##### [setMethods()](#setMethods()) public
Set the accepted HTTP methods for this route.
* ##### [setMiddleware()](#setMiddleware()) public
Set the names of the middleware that should be applied to this route.
* ##### [setPass()](#setPass()) public
Set the names of parameters that will be converted into passed parameters
* ##### [setPatterns()](#setPatterns()) public
Set regexp patterns for routing parameters
* ##### [setPersist()](#setPersist()) public
Set the names of parameters that will persisted automatically
* ##### [staticPath()](#staticPath()) public
Get the static path portion for this route.
Method Detail
-------------
### \_\_construct() public
```
__construct(string $template, array $defaults = [], array<string, mixed> $options = [])
```
Constructor for a Route
### Options
* `_ext` - Defines the extensions used for this route.
* `_middleware` - Define the middleware names for this route.
* `pass` - Copies the listed parameters into params['pass'].
* `_method` - Defines the HTTP method(s) the route applies to. It can be a string or array of valid HTTP method name.
* `_host` - Define the host name pattern if you want this route to only match specific host names. You can use `.*` and to create wildcard subdomains/hosts e.g. `*.example.com` matches all subdomains on `example.com`.
* '\_port` - Define the port if you want this route to only match specific port number.
* '\_urldecode' - Set to `false` to disable URL decoding before route parsing.
#### Parameters
`string` $template Template string with parameter placeholders
`array` $defaults optional Defaults for the route.
`array<string, mixed>` $options optional Array of additional options for the Route
#### Throws
`InvalidArgumentException`
When `$options['\_method']` are not in `VALID\_METHODS` list. ### \_\_set\_state() public static
```
__set_state(array<string, mixed> $fields): static
```
Set state magic method to support var\_export
This method helps for applications that want to implement router caching.
#### Parameters
`array<string, mixed>` $fields Key/Value of object attributes
#### Returns
`static`
### \_matchMethod() protected
```
_matchMethod(array $url): bool
```
Check whether the URL's HTTP method matches.
#### Parameters
`array` $url The array for the URL being generated.
#### Returns
`bool`
### \_parseArgs() protected
```
_parseArgs(string $args, array $context): array<string>
```
Parse passed parameters into a list of passed args.
Return true if a given named $param's $val matches a given $rule depending on $context. Currently implemented rule types are controller, action and match that can be combined with each other.
#### Parameters
`string` $args A string with the passed params. eg. /1/foo
`array` $context The current route context, which should contain controller/action keys.
#### Returns
`array<string>`
### \_parseExtension() protected
```
_parseExtension(string $url): array
```
Removes the extension from $url if it contains a registered extension. If no registered extension is found, no extension is returned and the URL is returned unmodified.
#### Parameters
`string` $url The url to parse.
#### Returns
`array`
### \_persistParams() protected
```
_persistParams(array $url, array $params): array
```
Apply persistent parameters to a URL array. Persistent parameters are a special key used during route creation to force route parameters to persist when omitted from a URL array.
#### Parameters
`array` $url The array to apply persistent parameters to.
`array` $params An array of persistent values to replace persistent ones.
#### Returns
`array`
### \_writeRoute() protected
```
_writeRoute(): void
```
Builds a route regular expression.
Uses the template, defaults and options properties to compile a regular expression that can be used to parse request strings.
#### Returns
`void`
### \_writeUrl() protected
```
_writeUrl(array $params, array $pass = [], array $query = []): string
```
Converts a matching route array into a URL string.
Composes the string URL using the template used to create the route.
#### Parameters
`array` $params The params to convert to a string url
`array` $pass optional The additional passed arguments
`array` $query optional An array of parameters
#### Returns
`string`
### compile() public
```
compile(): string
```
Compiles the route's regular expression.
Modifies defaults property so all necessary keys are set and populates $this->names with the named routing elements.
#### Returns
`string`
### compiled() public
```
compiled(): bool
```
Check if a Route has been compiled into a regular expression.
#### Returns
`bool`
### getExtensions() public
```
getExtensions(): array<string>
```
Get the supported extensions for this route.
#### Returns
`array<string>`
### getMiddleware() public
```
getMiddleware(): array
```
Get the names of the middleware that should be applied to this route.
#### Returns
`array`
### getName() public
```
getName(): string
```
Get the standardized plugin.controller:action name for a route.
#### Returns
`string`
### hostMatches() public
```
hostMatches(string $host): bool
```
Check to see if the host matches the route requirements
#### Parameters
`string` $host The request's host name
#### Returns
`bool`
### match() public
```
match(array $url, array $context = []): string|null
```
Check if a URL array matches this route instance.
If the URL matches the route parameters and settings, then return a generated string URL. If the URL doesn't match the route parameters, false will be returned. This method handles the reverse routing or conversion of URL arrays into string URLs.
#### Parameters
`array` $url An array of parameters to check matching with.
`array` $context optional An array of the current request context. Contains information such as the current host, scheme, port, base directory and other url params.
#### Returns
`string|null`
### normalizeAndValidateMethods() protected
```
normalizeAndValidateMethods(array<string>|string $methods): array<string>|string
```
Normalize method names to upper case and validate that they are valid HTTP methods.
#### Parameters
`array<string>|string` $methods Methods.
#### Returns
`array<string>|string`
#### Throws
`InvalidArgumentException`
When methods are not in `VALID\_METHODS` list. ### parse() public
```
parse(string $url, string $method): array|null
```
Checks to see if the given URL can be parsed by this route.
If the route can be parsed an array of parameters will be returned; if not `null` will be returned. String URLs are parsed if they match a routes regular expression.
#### Parameters
`string` $url The URL to attempt to parse.
`string` $method The HTTP method of the request being parsed.
#### Returns
`array|null`
#### Throws
`Cake\Http\Exception\BadRequestException`
When method is not an empty string and not in `VALID\_METHODS` list. ### parseRequest() public
```
parseRequest(Psr\Http\Message\ServerRequestInterface $request): array|null
```
Checks to see if the given URL can be parsed by this route.
If the route can be parsed an array of parameters will be returned; if not `null` will be returned.
#### Parameters
`Psr\Http\Message\ServerRequestInterface` $request The URL to attempt to parse.
#### Returns
`array|null`
### setExtensions() public
```
setExtensions(array<string> $extensions): $this
```
Set the supported extensions for this route.
#### Parameters
`array<string>` $extensions The extensions to set.
#### Returns
`$this`
### setHost() public
```
setHost(string $host): $this
```
Set host requirement
#### Parameters
`string` $host The host name this route is bound to
#### Returns
`$this`
### setMethods() public
```
setMethods(array<string> $methods): $this
```
Set the accepted HTTP methods for this route.
#### Parameters
`array<string>` $methods The HTTP methods to accept.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
When methods are not in `VALID\_METHODS` list. ### setMiddleware() public
```
setMiddleware(array $middleware): $this
```
Set the names of the middleware that should be applied to this route.
#### Parameters
`array` $middleware The list of middleware names to apply to this route. Middleware names will not be checked until the route is matched.
#### Returns
`$this`
### setPass() public
```
setPass(array<string> $names): $this
```
Set the names of parameters that will be converted into passed parameters
#### Parameters
`array<string>` $names The names of the parameters that should be passed.
#### Returns
`$this`
### setPatterns() public
```
setPatterns(array<string> $patterns): $this
```
Set regexp patterns for routing parameters
If any of your patterns contain multibyte values, the `multibytePattern` mode will be enabled.
#### Parameters
`array<string>` $patterns The patterns to apply to routing elements
#### Returns
`$this`
### setPersist() public
```
setPersist(array $names): $this
```
Set the names of parameters that will persisted automatically
Persistent parameters allow you to define which route parameters should be automatically included when generating new URLs. You can override persistent parameters by redefining them in a URL or remove them by setting the persistent parameter to `false`.
```
// remove a persistent 'date' parameter
Router::url(['date' => false', ...]);
```
#### Parameters
`array` $names The names of the parameters that should be passed.
#### Returns
`$this`
### staticPath() public
```
staticPath(): string
```
Get the static path portion for this route.
#### Returns
`string`
Property Detail
---------------
### $\_compiledRoute protected
The compiled route regular expression
#### Type
`string|null`
### $\_extensions protected
List of connected extensions for this route.
#### Type
`array<string>`
### $\_greedy protected
Is this route a greedy route? Greedy routes have a `/*` in their template
#### Type
`bool`
### $\_name protected
The name for a route. Fetch with Route::getName();
#### Type
`string|null`
### $braceKeys protected
Track whether brace keys `{var}` were used.
#### Type
`bool`
### $defaults public
Default parameters for a Route
#### Type
`array`
### $keys public
An array of named segments in a Route. `/{controller}/{action}/{id}` has 3 key elements
#### Type
`array`
### $middleware protected
List of middleware that should be applied.
#### Type
`array`
### $options public
An array of additional parameters for the Route.
#### Type
`array`
### $template public
The routes template string.
#### Type
`string`
| programming_docs |
cakephp Class RulesChecker Class RulesChecker
===================
ORM flavoured rules checker.
Adds ORM related features to the RulesChecker class.
**Namespace:** [Cake\ORM](namespace-cake.orm)
**See:** \Cake\Datasource\RulesChecker
Constants
---------
* `string` **CREATE**
```
'create'
```
Indicates that the checking rules to apply are those used for creating entities
* `string` **DELETE**
```
'delete'
```
Indicates that the checking rules to apply are those used for deleting entities
* `string` **UPDATE**
```
'update'
```
Indicates that the checking rules to apply are those used for updating entities
Property Summary
----------------
* [$\_createRules](#%24_createRules) protected `arrayCake\Datasource\RuleInvoker>` The list of rules to check during create operations
* [$\_deleteRules](#%24_deleteRules) protected `arrayCake\Datasource\RuleInvoker>` The list of rules to check during delete operations
* [$\_options](#%24_options) protected `array` List of options to pass to every callable rule
* [$\_rules](#%24_rules) protected `arrayCake\Datasource\RuleInvoker>` The list of rules to be checked on both create and update operations
* [$\_updateRules](#%24_updateRules) protected `arrayCake\Datasource\RuleInvoker>` The list of rules to check during update operations
* [$\_useI18n](#%24_useI18n) protected `bool` Whether to use I18n functions for translating default error messages
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor. Takes the options to be passed to all rules.
* ##### [\_addError()](#_addError()) protected
Utility method for decorating any callable so that if it returns false, the correct property in the entity is marked as invalid.
* ##### [\_addLinkConstraintRule()](#_addLinkConstraintRule()) protected
Adds a link constraint rule.
* ##### [\_checkRules()](#_checkRules()) protected
Used by top level functions checkDelete, checkCreate and checkUpdate, this function iterates an array containing the rules to be checked and checks them all.
* ##### [add()](#add()) public
Adds a rule that will be applied to the entity both on create and update operations.
* ##### [addCreate()](#addCreate()) public
Adds a rule that will be applied to the entity on create operations.
* ##### [addDelete()](#addDelete()) public
Adds a rule that will be applied to the entity on delete operations.
* ##### [addUpdate()](#addUpdate()) public
Adds a rule that will be applied to the entity on update operations.
* ##### [check()](#check()) public
Runs each of the rules by passing the provided entity and returns true if all of them pass. The rules to be applied are depended on the $mode parameter which can only be RulesChecker::CREATE, RulesChecker::UPDATE or RulesChecker::DELETE
* ##### [checkCreate()](#checkCreate()) public
Runs each of the rules by passing the provided entity and returns true if all of them pass. The rules selected will be only those specified to be run on 'create'
* ##### [checkDelete()](#checkDelete()) public
Runs each of the rules by passing the provided entity and returns true if all of them pass. The rules selected will be only those specified to be run on 'delete'
* ##### [checkUpdate()](#checkUpdate()) public
Runs each of the rules by passing the provided entity and returns true if all of them pass. The rules selected will be only those specified to be run on 'update'
* ##### [existsIn()](#existsIn()) public
Returns a callable that can be used as a rule for checking that the values extracted from the entity to check exist as the primary key in another table.
* ##### [isLinkedTo()](#isLinkedTo()) public
Validates whether links to the given association exist.
* ##### [isNotLinkedTo()](#isNotLinkedTo()) public
Validates whether links to the given association do not exist.
* ##### [isUnique()](#isUnique()) public
Returns a callable that can be used as a rule for checking the uniqueness of a value in the table.
* ##### [validCount()](#validCount()) public
Validates the count of associated records.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $options = [])
```
Constructor. Takes the options to be passed to all rules.
#### Parameters
`array<string, mixed>` $options optional The options to pass to every rule
### \_addError() protected
```
_addError(callableCake\Datasource\RuleInvoker $rule, array|string|null $name = null, array<string, mixed> $options = []): Cake\Datasource\RuleInvoker
```
Utility method for decorating any callable so that if it returns false, the correct property in the entity is marked as invalid.
#### Parameters
`callableCake\Datasource\RuleInvoker` $rule The rule to decorate
`array|string|null` $name optional The alias for a rule or an array of options
`array<string, mixed>` $options optional The options containing the error message and field.
#### Returns
`Cake\Datasource\RuleInvoker`
### \_addLinkConstraintRule() protected
```
_addLinkConstraintRule(Cake\ORM\Association|string $association, string|null $errorField, string|null $message, string $linkStatus, string $ruleName): Cake\Datasource\RuleInvoker
```
Adds a link constraint rule.
#### Parameters
`Cake\ORM\Association|string` $association The association to check for links.
`string|null` $errorField The name of the property to use for setting possible errors. When absent, the name is inferred from `$association`.
`string|null` $message The error message to show in case the rule does not pass.
`string` $linkStatus The ink status required for the check to pass.
`string` $ruleName The alias/name of the rule.
#### Returns
`Cake\Datasource\RuleInvoker`
#### Throws
`InvalidArgumentException`
In case the `$association` argument is of an invalid type. #### See Also
\Cake\ORM\RulesChecker::isLinkedTo()
\Cake\ORM\RulesChecker::isNotLinkedTo()
\Cake\ORM\Rule\LinkConstraint::STATUS\_LINKED
\Cake\ORM\Rule\LinkConstraint::STATUS\_NOT\_LINKED ### \_checkRules() protected
```
_checkRules(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = [], arrayCake\Datasource\RuleInvoker> $rules = []): bool
```
Used by top level functions checkDelete, checkCreate and checkUpdate, this function iterates an array containing the rules to be checked and checks them all.
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity to check for validity.
`array<string, mixed>` $options optional Extra options to pass to checker functions.
`arrayCake\Datasource\RuleInvoker>` $rules optional The list of rules that must be checked.
#### Returns
`bool`
### add() public
```
add(callable $rule, array|string|null $name = null, array<string, mixed> $options = []): $this
```
Adds a rule that will be applied to the entity both on create and 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.
#### Parameters
`callable` $rule A callable function or object that will return whether the entity is valid or not.
`array|string|null` $name optional The alias for a rule, or an array of options.
`array<string, mixed>` $options optional List of extra options to pass to the rule callable as second argument.
#### Returns
`$this`
### addCreate() public
```
addCreate(callable $rule, array|string|null $name = null, array<string, mixed> $options = []): $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.
#### Parameters
`callable` $rule A callable function or object that will return whether the entity is valid or not.
`array|string|null` $name optional The alias for a rule or an array of options.
`array<string, mixed>` $options optional List of extra options to pass to the rule callable as second argument.
#### Returns
`$this`
### addDelete() public
```
addDelete(callable $rule, array|string|null $name = null, array<string, mixed> $options = []): $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.
#### Parameters
`callable` $rule A callable function or object that will return whether the entity is valid or not.
`array|string|null` $name optional The alias for a rule, or an array of options.
`array<string, mixed>` $options optional List of extra options to pass to the rule callable as second argument.
#### Returns
`$this`
### addUpdate() public
```
addUpdate(callable $rule, array|string|null $name = null, array<string, mixed> $options = []): $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.
#### Parameters
`callable` $rule A callable function or object that will return whether the entity is valid or not.
`array|string|null` $name optional The alias for a rule, or an array of options.
`array<string, mixed>` $options optional List of extra options to pass to the rule callable as second argument.
#### Returns
`$this`
### check() public
```
check(Cake\Datasource\EntityInterface $entity, string $mode, array<string, mixed> $options = []): bool
```
Runs each of the rules by passing the provided entity and returns true if all of them pass. The rules to be applied are depended on the $mode parameter which can only be RulesChecker::CREATE, RulesChecker::UPDATE or RulesChecker::DELETE
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity to check for validity.
`string` $mode Either 'create, 'update' or 'delete'.
`array<string, mixed>` $options optional Extra options to pass to checker functions.
#### Returns
`bool`
#### Throws
`InvalidArgumentException`
if an invalid mode is passed. ### checkCreate() public
```
checkCreate(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): bool
```
Runs each of the rules by passing the provided entity and returns true if all of them pass. The rules selected will be only those specified to be run on 'create'
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity to check for validity.
`array<string, mixed>` $options optional Extra options to pass to checker functions.
#### Returns
`bool`
### checkDelete() public
```
checkDelete(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): bool
```
Runs each of the rules by passing the provided entity and returns true if all of them pass. The rules selected will be only those specified to be run on 'delete'
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity to check for validity.
`array<string, mixed>` $options optional Extra options to pass to checker functions.
#### Returns
`bool`
### checkUpdate() public
```
checkUpdate(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): bool
```
Runs each of the rules by passing the provided entity and returns true if all of them pass. The rules selected will be only those specified to be run on 'update'
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity to check for validity.
`array<string, mixed>` $options optional Extra options to pass to checker functions.
#### Returns
`bool`
### existsIn() public
```
existsIn(array<string>|string $field, Cake\ORM\TableCake\ORM\Association|string $table, array<string, mixed>|string|null $message = null): Cake\Datasource\RuleInvoker
```
Returns a callable that can be used as a rule for checking that the values extracted from the entity to check exist as the primary key in another table.
This is useful for enforcing foreign key integrity checks.
### Example:
```
$rules->add($rules->existsIn('author_id', 'Authors', 'Invalid Author'));
$rules->add($rules->existsIn('site_id', new SitesTable(), 'Invalid Site'));
```
Available $options are error 'message' and 'allowNullableNulls' flag. 'message' sets a custom error message. Set 'allowNullableNulls' to true to accept composite foreign keys where one or more nullable columns are null.
#### Parameters
`array<string>|string` $field The field or list of fields to check for existence by primary key lookup in the other table.
`Cake\ORM\TableCake\ORM\Association|string` $table The table name where the fields existence will be checked.
`array<string, mixed>|string|null` $message optional The error message to show in case the rule does not pass. Can also be an array of options. When an array, the 'message' key can be used to provide a message.
#### Returns
`Cake\Datasource\RuleInvoker`
### isLinkedTo() public
```
isLinkedTo(Cake\ORM\Association|string $association, string|null $field = null, string|null $message = null): Cake\Datasource\RuleInvoker
```
Validates whether links to the given association exist.
### Example:
```
$rules->addUpdate($rules->isLinkedTo('Articles', 'article'));
```
On a `Comments` table that has a `belongsTo Articles` association, this check would ensure that comments can only be edited as long as they are associated to an existing article.
#### Parameters
`Cake\ORM\Association|string` $association The association to check for links.
`string|null` $field optional The name of the association property. When supplied, this is the name used to set possible errors. When absent, the name is inferred from `$association`.
`string|null` $message optional The error message to show in case the rule does not pass.
#### Returns
`Cake\Datasource\RuleInvoker`
### isNotLinkedTo() public
```
isNotLinkedTo(Cake\ORM\Association|string $association, string|null $field = null, string|null $message = null): Cake\Datasource\RuleInvoker
```
Validates whether links to the given association do not exist.
### Example:
```
$rules->addDelete($rules->isNotLinkedTo('Comments', 'comments'));
```
On a `Articles` table that has a `hasMany Comments` association, this check would ensure that articles can only be deleted when no associated comments exist.
#### Parameters
`Cake\ORM\Association|string` $association The association to check for links.
`string|null` $field optional The name of the association property. When supplied, this is the name used to set possible errors. When absent, the name is inferred from `$association`.
`string|null` $message optional The error message to show in case the rule does not pass.
#### Returns
`Cake\Datasource\RuleInvoker`
### isUnique() public
```
isUnique(array<string> $fields, array<string, mixed>|string|null $message = null): Cake\Datasource\RuleInvoker
```
Returns a callable that can be used as a rule for checking the uniqueness of a value in the table.
### Example
```
$rules->add($rules->isUnique(['email'], 'The email should be unique'));
```
### Options
* `allowMultipleNulls` Allows any field to have multiple null values. Defaults to false.
#### Parameters
`array<string>` $fields The list of fields to check for uniqueness.
`array<string, mixed>|string|null` $message optional The error message to show in case the rule does not pass. Can also be an array of options. When an array, the 'message' key can be used to provide a message.
#### Returns
`Cake\Datasource\RuleInvoker`
### validCount() public
```
validCount(string $field, int $count = 0, string $operator = '>', string|null $message = null): Cake\Datasource\RuleInvoker
```
Validates the count of associated records.
#### Parameters
`string` $field The field to check the count on.
`int` $count optional The expected count.
`string` $operator optional The operator for the count comparison.
`string|null` $message optional The error message to show in case the rule does not pass.
#### Returns
`Cake\Datasource\RuleInvoker`
Property Detail
---------------
### $\_createRules protected
The list of rules to check during create operations
#### Type
`arrayCake\Datasource\RuleInvoker>`
### $\_deleteRules protected
The list of rules to check during delete operations
#### Type
`arrayCake\Datasource\RuleInvoker>`
### $\_options protected
List of options to pass to every callable rule
#### Type
`array`
### $\_rules protected
The list of rules to be checked on both create and update operations
#### Type
`arrayCake\Datasource\RuleInvoker>`
### $\_updateRules protected
The list of rules to check during update operations
#### Type
`arrayCake\Datasource\RuleInvoker>`
### $\_useI18n protected
Whether to use I18n functions for translating default error messages
#### Type
`bool`
cakephp Class SqlserverSchemaDialect Class SqlserverSchemaDialect
=============================
Schema management/reflection features for SQLServer.
**Namespace:** [Cake\Database\Schema](namespace-cake.database.schema)
Constants
---------
* `string` **DEFAULT\_SCHEMA\_NAME**
```
'dbo'
```
Property Summary
----------------
* [$\_driver](#%24_driver) protected `Cake\Database\DriverInterface` The driver instance being used.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_applyTypeSpecificColumnConversion()](#_applyTypeSpecificColumnConversion()) protected
Tries to use a matching database type to convert a SQL column definition to an abstract type definition.
* ##### [\_convertColumn()](#_convertColumn()) protected
Convert a column definition to the abstract types.
* ##### [\_convertConstraintColumns()](#_convertConstraintColumns()) protected
Convert foreign key constraints references to a valid stringified list
* ##### [\_convertOnClause()](#_convertOnClause()) protected
Convert string on clauses to the abstract ones.
* ##### [\_defaultValue()](#_defaultValue()) protected
Manipulate the default value.
* ##### [\_foreignOnClause()](#_foreignOnClause()) protected
Generate an ON clause for a foreign key.
* ##### [\_getTypeSpecificColumnSql()](#_getTypeSpecificColumnSql()) protected
Tries to use a matching database type to generate the SQL fragment for a single column in a table.
* ##### [\_keySql()](#_keySql()) protected
Helper method for generating key SQL snippets.
* ##### [addConstraintSql()](#addConstraintSql()) public
Generate the SQL queries needed to add foreign key constraints to the table
* ##### [columnSql()](#columnSql()) public
Generate the SQL fragment for a single column in a table.
* ##### [constraintSql()](#constraintSql()) public
Generate the SQL fragments for defining table constraints.
* ##### [convertColumnDescription()](#convertColumnDescription()) public
Convert field description results into abstract schema fields.
* ##### [convertForeignKeyDescription()](#convertForeignKeyDescription()) public
Convert a foreign key description into constraints on the Table object.
* ##### [convertIndexDescription()](#convertIndexDescription()) public
Convert an index description results into abstract schema indexes or constraints.
* ##### [convertOptionsDescription()](#convertOptionsDescription()) public
Convert options data into table options.
* ##### [createTableSql()](#createTableSql()) public
Generate the SQL to create a table.
* ##### [describeColumnSql()](#describeColumnSql()) public
Generate the SQL to describe a table.
* ##### [describeForeignKeySql()](#describeForeignKeySql()) public
Generate the SQL to describe the foreign keys in a table.
* ##### [describeIndexSql()](#describeIndexSql()) public
Generate the SQL to describe the indexes in a table.
* ##### [describeOptionsSql()](#describeOptionsSql()) public
Generate the SQL to describe table options
* ##### [dropConstraintSql()](#dropConstraintSql()) public
Generate the SQL queries needed to drop foreign key constraints from the table
* ##### [dropTableSql()](#dropTableSql()) public
Generate the SQL to drop a table.
* ##### [indexSql()](#indexSql()) public
Generate the SQL fragment for a single index in a table.
* ##### [listTablesSql()](#listTablesSql()) public
Generate the SQL to list the tables and views.
* ##### [listTablesWithoutViewsSql()](#listTablesWithoutViewsSql()) public
Generate the SQL to list the tables, excluding all views.
* ##### [truncateTableSql()](#truncateTableSql()) public
Generate the SQL to truncate a table.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Database\DriverInterface $driver)
```
Constructor
This constructor will connect the driver so that methods like columnSql() and others will fail when the driver has not been connected.
#### Parameters
`Cake\Database\DriverInterface` $driver The driver to use.
### \_applyTypeSpecificColumnConversion() protected
```
_applyTypeSpecificColumnConversion(string $columnType, array $definition): array|null
```
Tries to use a matching database type to convert a SQL column definition to an abstract type definition.
#### Parameters
`string` $columnType The column type.
`array` $definition The column definition.
#### Returns
`array|null`
### \_convertColumn() protected
```
_convertColumn(string $col, int|null $length = null, int|null $precision = null, int|null $scale = null): array<string, mixed>
```
Convert a column definition to the abstract types.
The returned type will be a type that Cake\Database\TypeFactory can handle.
#### Parameters
`string` $col The column type
`int|null` $length optional the column length
`int|null` $precision optional The column precision
`int|null` $scale optional The column scale
#### Returns
`array<string, mixed>`
#### Links
https://technet.microsoft.com/en-us/library/ms187752.aspx
### \_convertConstraintColumns() protected
```
_convertConstraintColumns(array<string>|string $references): string
```
Convert foreign key constraints references to a valid stringified list
#### Parameters
`array<string>|string` $references The referenced columns of a foreign key constraint statement
#### Returns
`string`
### \_convertOnClause() protected
```
_convertOnClause(string $clause): string
```
Convert string on clauses to the abstract ones.
#### Parameters
`string` $clause #### Returns
`string`
### \_defaultValue() protected
```
_defaultValue(string $type, string|null $default): string|int|null
```
Manipulate the default value.
Removes () wrapping default values, extracts strings from N'' wrappers and collation text and converts NULL strings.
#### Parameters
`string` $type The schema type
`string|null` $default The default value.
#### Returns
`string|int|null`
### \_foreignOnClause() protected
```
_foreignOnClause(string $on): string
```
Generate an ON clause for a foreign key.
#### Parameters
`string` $on #### Returns
`string`
### \_getTypeSpecificColumnSql() protected
```
_getTypeSpecificColumnSql(string $columnType, Cake\Database\Schema\TableSchemaInterface $schema, string $column): string|null
```
Tries to use a matching database type to generate the SQL fragment for a single column in a table.
#### Parameters
`string` $columnType The column type.
`Cake\Database\Schema\TableSchemaInterface` $schema The table schema instance the column is in.
`string` $column The name of the column.
#### Returns
`string|null`
### \_keySql() protected
```
_keySql(string $prefix, array $data): string
```
Helper method for generating key SQL snippets.
#### Parameters
`string` $prefix The key prefix
`array` $data Key data.
#### Returns
`string`
### addConstraintSql() public
```
addConstraintSql(Cake\Database\Schema\TableSchema $schema): array
```
Generate the SQL queries needed to add foreign key constraints to the table
#### Parameters
`Cake\Database\Schema\TableSchema` $schema #### Returns
`array`
### columnSql() public
```
columnSql(Cake\Database\Schema\TableSchema $schema, string $name): string
```
Generate the SQL fragment for a single column in a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `string` $name #### Returns
`string`
### constraintSql() public
```
constraintSql(Cake\Database\Schema\TableSchema $schema, string $name): string
```
Generate the SQL fragments for defining table constraints.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `string` $name #### Returns
`string`
### convertColumnDescription() public
```
convertColumnDescription(Cake\Database\Schema\TableSchema $schema, array $row): void
```
Convert field description results into abstract schema fields.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `array` $row #### Returns
`void`
### convertForeignKeyDescription() public
```
convertForeignKeyDescription(Cake\Database\Schema\TableSchema $schema, array $row): void
```
Convert a foreign key description into constraints on the Table object.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `array` $row #### Returns
`void`
### convertIndexDescription() public
```
convertIndexDescription(Cake\Database\Schema\TableSchema $schema, array $row): void
```
Convert an index description results into abstract schema indexes or constraints.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `array` $row #### Returns
`void`
### convertOptionsDescription() public
```
convertOptionsDescription(Cake\Database\Schema\TableSchema $schema, array $row): void
```
Convert options data into table options.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema Table instance.
`array` $row The row of data.
#### Returns
`void`
### createTableSql() public
```
createTableSql(Cake\Database\Schema\TableSchema $schema, array<string> $columns, array<string> $constraints, array<string> $indexes): array<string>
```
Generate the SQL to create a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `array<string>` $columns `array<string>` $constraints `array<string>` $indexes #### Returns
`array<string>`
### describeColumnSql() public
```
describeColumnSql(string $tableName, array<string, mixed> $config): array
```
Generate the SQL to describe a table.
#### Parameters
`string` $tableName `array<string, mixed>` $config #### Returns
`array`
### describeForeignKeySql() public
```
describeForeignKeySql(string $tableName, array<string, mixed> $config): array
```
Generate the SQL to describe the foreign keys in a table.
#### Parameters
`string` $tableName `array<string, mixed>` $config #### Returns
`array`
### describeIndexSql() public
```
describeIndexSql(string $tableName, array<string, mixed> $config): array
```
Generate the SQL to describe the indexes in a table.
#### Parameters
`string` $tableName `array<string, mixed>` $config #### Returns
`array`
### describeOptionsSql() public
```
describeOptionsSql(string $tableName, array<string, mixed> $config): array
```
Generate the SQL to describe table options
#### Parameters
`string` $tableName Table name.
`array<string, mixed>` $config The connection configuration.
#### Returns
`array`
### dropConstraintSql() public
```
dropConstraintSql(Cake\Database\Schema\TableSchema $schema): array
```
Generate the SQL queries needed to drop foreign key constraints from the table
#### Parameters
`Cake\Database\Schema\TableSchema` $schema #### Returns
`array`
### dropTableSql() public
```
dropTableSql(Cake\Database\Schema\TableSchema $schema): array
```
Generate the SQL to drop a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema Schema instance
#### Returns
`array`
### indexSql() public
```
indexSql(Cake\Database\Schema\TableSchema $schema, string $name): string
```
Generate the SQL fragment for a single index in a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema `string` $name #### Returns
`string`
### listTablesSql() public
```
listTablesSql(array<string, mixed> $config): array
```
Generate the SQL to list the tables and views.
#### Parameters
`array<string, mixed>` $config The connection configuration to use for getting tables from.
#### Returns
`array`
### listTablesWithoutViewsSql() public
```
listTablesWithoutViewsSql(array<string, mixed> $config): array<mixed>
```
Generate the SQL to list the tables, excluding all views.
#### Parameters
`array<string, mixed>` $config The connection configuration to use for getting tables from.
#### Returns
`array<mixed>`
### truncateTableSql() public
```
truncateTableSql(Cake\Database\Schema\TableSchema $schema): array
```
Generate the SQL to truncate a table.
#### Parameters
`Cake\Database\Schema\TableSchema` $schema #### Returns
`array`
Property Detail
---------------
### $\_driver protected
The driver instance being used.
#### Type
`Cake\Database\DriverInterface`
| programming_docs |
cakephp Class ArrayLog Class ArrayLog
===============
Array logger.
Collects log messages in memory. Intended primarily for usage in testing where using mocks would be complicated. But can also be used in scenarios where you need to capture logs in application code.
**Namespace:** [Cake\Log\Engine](namespace-cake.log.engine)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this class
* [$content](#%24content) protected `array<string>` Captured messages
* [$formatter](#%24formatter) protected `Cake\Log\Formatter\AbstractFormatter`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
\_\_construct method
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_format()](#_format()) protected deprecated
Formats the message to be logged.
* ##### [alert()](#alert()) public
Action must be taken immediately.
* ##### [clear()](#clear()) public
Reset internal storage.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [critical()](#critical()) public
Critical conditions.
* ##### [debug()](#debug()) public
Detailed debug information.
* ##### [emergency()](#emergency()) public
System is unusable.
* ##### [error()](#error()) public
Runtime errors that do not require immediate action but should typically be logged and monitored.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [info()](#info()) public
Interesting events.
* ##### [interpolate()](#interpolate()) protected
Replaces placeholders in message string with context values.
* ##### [levels()](#levels()) public
Get the levels this logger is interested in.
* ##### [log()](#log()) public
Implements writing to the internal storage.
* ##### [notice()](#notice()) public
Normal but significant events.
* ##### [read()](#read()) public
Read the internal storage
* ##### [scopes()](#scopes()) public
Get the scopes this logger is interested in.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [warning()](#warning()) public
Exceptional occurrences that are not errors.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
\_\_construct method
#### Parameters
`array<string, mixed>` $config optional Configuration array
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_format() protected
```
_format(string $message, array $context = []): string
```
Formats the message to be logged.
The context can optionally be used by log engines to interpolate variables or add additional info to the logged message.
#### Parameters
`string` $message The message to be formatted.
`array` $context optional Additional logging information for the message.
#### Returns
`string`
### alert() public
```
alert(string $message, mixed[] $context = array()): void
```
Action must be taken immediately.
Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### clear() public
```
clear(): void
```
Reset internal storage.
#### Returns
`void`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### critical() public
```
critical(string $message, mixed[] $context = array()): void
```
Critical conditions.
Example: Application component unavailable, unexpected exception.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### debug() public
```
debug(string $message, mixed[] $context = array()): void
```
Detailed debug information.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### emergency() public
```
emergency(string $message, mixed[] $context = array()): void
```
System is unusable.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### error() public
```
error(string $message, mixed[] $context = array()): void
```
Runtime errors that do not require immediate action but should typically be logged and monitored.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### info() public
```
info(string $message, mixed[] $context = array()): void
```
Interesting events.
Example: User logs in, SQL logs.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### interpolate() protected
```
interpolate(string $message, array $context = []): string
```
Replaces placeholders in message string with context values.
#### Parameters
`string` $message Formatted string
`array` $context optional Context for placeholder values.
#### Returns
`string`
### levels() public
```
levels(): array<string>
```
Get the levels this logger is interested in.
#### Returns
`array<string>`
### log() public
```
log(mixed $level, string $message, mixed[] $context = []): void
```
Implements writing to the internal storage.
#### Parameters
`mixed` $level The severity level of log you are making.
`string` $message The message you want to log.
`mixed[]` $context optional Additional information about the logged message
#### Returns
`void`
#### See Also
\Cake\Log\Log::$\_levels ### notice() public
```
notice(string $message, mixed[] $context = array()): void
```
Normal but significant events.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### read() public
```
read(): array<string>
```
Read the internal storage
#### Returns
`array<string>`
### scopes() public
```
scopes(): array<string>|false
```
Get the scopes this logger is interested in.
#### Returns
`array<string>|false`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### warning() public
```
warning(string $message, mixed[] $context = array()): void
```
Exceptional occurrences that are not errors.
Example: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this class
#### Type
`array<string, mixed>`
### $content protected
Captured messages
#### Type
`array<string>`
### $formatter protected
#### Type
`Cake\Log\Formatter\AbstractFormatter`
cakephp Class ErrorHandler Class ErrorHandler
===================
Error Handler provides basic error and exception handling for your application. It captures and handles all unhandled exceptions and errors. Displays helpful framework errors when debug mode is on.
### Uncaught exceptions
When debug mode is off a ExceptionRenderer will render 404 or 500 errors. If an uncaught exception is thrown and it is a type that ExceptionRenderer does not know about it will be treated as a 500 error.
### Implementing application specific exception handling
You can implement application specific exception handling in one of a few ways. Each approach gives you different amounts of control over the exception handling process.
* Modify config/error.php and setup custom exception handling.
* Use the `exceptionRenderer` option to inject an Exception renderer. This will let you keep the existing handling logic but override the rendering logic.
#### Create your own Exception handler
This gives you full control over the exception handling process. The class you choose should be loaded in your config/error.php and registered as the default exception handler.
#### Using a custom renderer with `exceptionRenderer`
If you don't want to take control of the exception handling, but want to change how exceptions are rendered you can use `exceptionRenderer` option to choose a class to render exception pages. By default `Cake\Error\ExceptionRenderer` is used. Your custom exception renderer class should be placed in src/Error.
Your custom renderer should expect an exception in its constructor, and implement a render method. Failing to do so will cause additional errors.
#### Logging exceptions
Using the built-in exception handling, you can log all the exceptions that are dealt with by ErrorHandler by setting `log` option to true in your config/error.php. Enabling this will log every exception to Log and the configured loggers.
### PHP errors
Error handler also provides the built in features for handling php errors (trigger\_error). While in debug mode, errors will be output to the screen using debugger. While in production mode, errors will be logged to Log. You can control which errors are logged by setting `errorLevel` option in config/error.php.
#### Logging errors
When ErrorHandler is used for handling errors, you can enable error logging by setting the `log` option to true. This will log all errors to the configured log handlers.
#### Controlling what errors are logged/displayed
You can control which errors are logged / displayed by ErrorHandler by setting `errorLevel`. Setting this to one or a combination of a few of the E\_\* constants will only enable the specified errors:
```
$options['errorLevel'] = E_ALL & ~E_NOTICE;
```
Would enable handling for all non Notice errors.
**Namespace:** [Cake\Error](namespace-cake.error)
**See:** \Cake\Error\ExceptionRenderer for more information on how to customize exception rendering.
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Options to use for the Error handling.
* [$\_handled](#%24_handled) protected `bool`
* [$logger](#%24logger) protected `Cake\Error\ErrorLoggerInterface|null` Exception logger instance.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_displayError()](#_displayError()) protected
Display an error.
* ##### [\_displayException()](#_displayException()) protected
Displays an exception response body.
* ##### [\_logError()](#_logError()) protected
Log an error.
* ##### [\_logInternalError()](#_logInternalError()) protected
Log internal errors.
* ##### [\_sendResponse()](#_sendResponse()) protected
Method that can be easily stubbed in testing.
* ##### [\_stop()](#_stop()) protected
Stop the process.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getLogger()](#getLogger()) public
Get exception logger.
* ##### [getRenderer()](#getRenderer()) public
Get a renderer instance.
* ##### [handleError()](#handleError()) public
Set as the default error handler by CakePHP.
* ##### [handleException()](#handleException()) public
Handle uncaught exceptions.
* ##### [handleFatalError()](#handleFatalError()) public
Display/Log a fatal error.
* ##### [increaseMemoryLimit()](#increaseMemoryLimit()) public
Increases the PHP "memory\_limit" ini setting by the specified amount in kilobytes
* ##### [logException()](#logException()) public
Log an error for the exception if applicable.
* ##### [mapErrorCode()](#mapErrorCode()) public static
Map an error code into an Error word, and log location.
* ##### [register()](#register()) public
Register the error and exception handlers.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [wrapAndHandleException()](#wrapAndHandleException()) public deprecated
Checks the passed exception type. If it is an instance of `Error` then, it wraps the passed object inside another Exception object for backwards compatibility purposes.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Constructor
#### Parameters
`array<string, mixed>` $config optional The options for error handling.
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_displayError() protected
```
_displayError(array $error, bool $debug): void
```
Display an error.
Template method of BaseErrorHandler.
#### Parameters
`array` $error An array of error data.
`bool` $debug Whether the app is in debug mode.
#### Returns
`void`
### \_displayException() protected
```
_displayException(Throwable $exception): void
```
Displays an exception response body.
Subclasses should implement this method to display an uncaught exception as desired for the runtime they operate in.
#### Parameters
`Throwable` $exception The exception to display.
#### Returns
`void`
#### Throws
`Exception`
When the chosen exception renderer is invalid. ### \_logError() protected
```
_logError(string|int $level, array $data): bool
```
Log an error.
#### Parameters
`string|int` $level The level name of the log.
`array` $data Array of error data.
#### Returns
`bool`
### \_logInternalError() protected
```
_logInternalError(Throwable $exception): void
```
Log internal errors.
#### Parameters
`Throwable` $exception Exception.
#### Returns
`void`
### \_sendResponse() protected
```
_sendResponse(Psr\Http\Message\ResponseInterface|string $response): void
```
Method that can be easily stubbed in testing.
#### Parameters
`Psr\Http\Message\ResponseInterface|string` $response Either the message or response object.
#### Returns
`void`
### \_stop() protected
```
_stop(int $code): void
```
Stop the process.
Implemented in subclasses that need it.
#### Parameters
`int` $code Exit code.
#### Returns
`void`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getLogger() public
```
getLogger(): Cake\Error\ErrorLoggerInterface
```
Get exception logger.
#### Returns
`Cake\Error\ErrorLoggerInterface`
### getRenderer() public
```
getRenderer(Throwable $exception, Psr\Http\Message\ServerRequestInterface|null $request = null): Cake\Error\ExceptionRendererInterface
```
Get a renderer instance.
#### Parameters
`Throwable` $exception The exception being rendered.
`Psr\Http\Message\ServerRequestInterface|null` $request optional The request.
#### Returns
`Cake\Error\ExceptionRendererInterface`
#### Throws
`RuntimeException`
When the renderer class cannot be found. ### handleError() public
```
handleError(int $code, string $description, string|null $file = null, int|null $line = null, array<string, mixed>|null $context = null): bool
```
Set as the default error handler by CakePHP.
Use config/error.php to customize or replace this error handler. This function will use Debugger to display errors when debug mode is on. And will log errors to Log, when debug mode is off.
You can use the 'errorLevel' option to set what type of errors will be handled. Stack traces for errors can be enabled with the 'trace' option.
#### Parameters
`int` $code Code of error
`string` $description Error description
`string|null` $file optional File on which error occurred
`int|null` $line optional Line that triggered the error
`array<string, mixed>|null` $context optional Context
#### Returns
`bool`
### handleException() public
```
handleException(Throwable $exception): void
```
Handle uncaught exceptions.
Uses a template method provided by subclasses to display errors in an environment appropriate way.
#### Parameters
`Throwable` $exception Exception instance.
#### Returns
`void`
#### Throws
`Exception`
When renderer class not found #### See Also
https://secure.php.net/manual/en/function.set-exception-handler.php ### handleFatalError() public
```
handleFatalError(int $code, string $description, string $file, int $line): bool
```
Display/Log a fatal error.
#### Parameters
`int` $code Code of error
`string` $description Error description
`string` $file File on which error occurred
`int` $line Line that triggered the error
#### Returns
`bool`
### increaseMemoryLimit() public
```
increaseMemoryLimit(int $additionalKb): void
```
Increases the PHP "memory\_limit" ini setting by the specified amount in kilobytes
#### Parameters
`int` $additionalKb Number in kilobytes
#### Returns
`void`
### logException() public
```
logException(Throwable $exception, Psr\Http\Message\ServerRequestInterface|null $request = null): bool
```
Log an error for the exception if applicable.
#### Parameters
`Throwable` $exception The exception to log a message for.
`Psr\Http\Message\ServerRequestInterface|null` $request optional The current request.
#### Returns
`bool`
### mapErrorCode() public static
```
mapErrorCode(int $code): array
```
Map an error code into an Error word, and log location.
#### Parameters
`int` $code Error code to map
#### Returns
`array`
### register() public
```
register(): void
```
Register the error and exception handlers.
#### Returns
`void`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### wrapAndHandleException() public
```
wrapAndHandleException(Throwable $exception): void
```
Checks the passed exception type. If it is an instance of `Error` then, it wraps the passed object inside another Exception object for backwards compatibility purposes.
#### Parameters
`Throwable` $exception The exception to handle
#### Returns
`void`
Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Options to use for the Error handling.
#### Type
`array<string, mixed>`
### $\_handled protected
#### Type
`bool`
### $logger protected
Exception logger instance.
#### Type
`Cake\Error\ErrorLoggerInterface|null`
| programming_docs |
cakephp Class EventManager Class EventManager
===================
The event manager is responsible for keeping track of event listeners, passing the correct data to them, and firing them in the correct order, when associated events are triggered. You can create multiple instances of this object to manage local events or keep a single instance and pass it around to manage all events in your app.
**Namespace:** [Cake\Event](namespace-cake.event)
Property Summary
----------------
* [$\_eventList](#%24_eventList) protected `Cake\Event\EventList|null` The event list object.
* [$\_generalManager](#%24_generalManager) protected static `Cake\Event\EventManager|null` The globally available instance, used for dispatching events attached from any scope
* [$\_isGlobal](#%24_isGlobal) protected `bool` Internal flag to distinguish a common manager from the singleton
* [$\_listeners](#%24_listeners) protected `array` List of listener callbacks associated to
* [$\_trackEvents](#%24_trackEvents) protected `bool` Enables automatic adding of events to the event list object if it is present.
* [$defaultPriority](#%24defaultPriority) public static `int` The default priority queue value for new, attached listeners
Method Summary
--------------
* ##### [\_\_debugInfo()](#__debugInfo()) public
Debug friendly object properties.
* ##### [\_attachSubscriber()](#_attachSubscriber()) protected
Auxiliary function to attach all implemented callbacks of a Cake\Event\EventListenerInterface class instance as individual methods on this manager
* ##### [\_callListener()](#_callListener()) protected
Calls a listener.
* ##### [\_detachSubscriber()](#_detachSubscriber()) protected
Auxiliary function to help detach all listeners provided by an object implementing EventListenerInterface
* ##### [\_extractCallable()](#_extractCallable()) protected
Auxiliary function to extract and return a PHP callback type out of the callable definition from the return value of the `implementedEvents()` method on a {@link \Cake\Event\EventListenerInterface}
* ##### [addEventToList()](#addEventToList()) public
Adds an event to the list if the event list object is present.
* ##### [dispatch()](#dispatch()) public
Dispatches a new event to all configured listeners
* ##### [getEventList()](#getEventList()) public
Returns the event list.
* ##### [instance()](#instance()) public static
Returns the globally available instance of a Cake\Event\EventManager this is used for dispatching events attached from outside the scope other managers were created. Usually for creating hook systems or inter-class communication
* ##### [isTrackingEvents()](#isTrackingEvents()) public
Returns whether this manager is set up to track events
* ##### [listeners()](#listeners()) public
Returns a list of all listeners for an eventKey in the order they should be called
* ##### [matchingListeners()](#matchingListeners()) public
Returns the listeners matching a specified pattern
* ##### [off()](#off()) public
Remove a listener from the active listeners.
* ##### [on()](#on()) public
Adds a new listener to an event.
* ##### [prioritisedListeners()](#prioritisedListeners()) public
Returns the listeners for the specified event key indexed by priority
* ##### [setEventList()](#setEventList()) public
Enables the listing of dispatched events.
* ##### [trackEvents()](#trackEvents()) public
Enables / disables event tracking at runtime.
* ##### [unsetEventList()](#unsetEventList()) public
Disables the listing of dispatched events.
Method Detail
-------------
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Debug friendly object properties.
#### Returns
`array<string, mixed>`
### \_attachSubscriber() protected
```
_attachSubscriber(Cake\Event\EventListenerInterface $subscriber): void
```
Auxiliary function to attach all implemented callbacks of a Cake\Event\EventListenerInterface class instance as individual methods on this manager
#### Parameters
`Cake\Event\EventListenerInterface` $subscriber Event listener.
#### Returns
`void`
### \_callListener() protected
```
_callListener(callable $listener, Cake\Event\EventInterface $event): mixed
```
Calls a listener.
#### Parameters
`callable` $listener The listener to trigger.
`Cake\Event\EventInterface` $event Event instance.
#### Returns
`mixed`
### \_detachSubscriber() protected
```
_detachSubscriber(Cake\Event\EventListenerInterface $subscriber, string|null $eventKey = null): void
```
Auxiliary function to help detach all listeners provided by an object implementing EventListenerInterface
#### Parameters
`Cake\Event\EventListenerInterface` $subscriber the subscriber to be detached
`string|null` $eventKey optional optional event key name to unsubscribe the listener from
#### Returns
`void`
### \_extractCallable() protected
```
_extractCallable(array $function, Cake\Event\EventListenerInterface $object): array
```
Auxiliary function to extract and return a PHP callback type out of the callable definition from the return value of the `implementedEvents()` method on a {@link \Cake\Event\EventListenerInterface}
#### Parameters
`array` $function the array taken from a handler definition for an event
`Cake\Event\EventListenerInterface` $object The handler object
#### Returns
`array`
### addEventToList() public
```
addEventToList(Cake\Event\EventInterface $event): $this
```
Adds an event to the list if the event list object is present.
#### Parameters
`Cake\Event\EventInterface` $event An event to add to the list.
#### Returns
`$this`
### dispatch() public
```
dispatch(Cake\Event\EventInterface|string $event): Cake\Event\EventInterface
```
Dispatches a new event to all configured listeners
#### Parameters
`Cake\Event\EventInterface|string` $event #### Returns
`Cake\Event\EventInterface`
### getEventList() public
```
getEventList(): Cake\Event\EventList|null
```
Returns the event list.
#### Returns
`Cake\Event\EventList|null`
### instance() public static
```
instance(Cake\Event\EventManager|null $manager = null): Cake\Event\EventManager
```
Returns the globally available instance of a Cake\Event\EventManager this is used for dispatching events attached from outside the scope other managers were created. Usually for creating hook systems or inter-class communication
If called with the first parameter, it will be set as the globally available instance
#### Parameters
`Cake\Event\EventManager|null` $manager optional Event manager instance.
#### Returns
`Cake\Event\EventManager`
### isTrackingEvents() public
```
isTrackingEvents(): bool
```
Returns whether this manager is set up to track events
#### Returns
`bool`
### listeners() public
```
listeners(string $eventKey): array
```
Returns a list of all listeners for an eventKey in the order they should be called
#### Parameters
`string` $eventKey #### Returns
`array`
### matchingListeners() public
```
matchingListeners(string $eventKeyPattern): array
```
Returns the listeners matching a specified pattern
#### Parameters
`string` $eventKeyPattern Pattern to match.
#### Returns
`array`
### off() public
```
off(Cake\Event\EventListenerInterface|callable|string $eventKey, Cake\Event\EventListenerInterface|callable|null $callable = null): $this
```
Remove a listener from the active listeners.
Remove a EventListenerInterface entirely:
```
$manager->off($listener);
```
Remove all listeners for a given event:
```
$manager->off('My.event');
```
Remove a specific listener:
```
$manager->off('My.event', $callback);
```
Remove a callback from all events:
```
$manager->off($callback);
```
#### Parameters
`Cake\Event\EventListenerInterface|callable|string` $eventKey `Cake\Event\EventListenerInterface|callable|null` $callable optional #### Returns
`$this`
### on() public
```
on(Cake\Event\EventListenerInterface|string $eventKey, callable|array $options = [], callable|null $callable = null): $this
```
Adds a new listener to an event.
A variadic interface to add listeners that emulates jQuery.on().
Binding an EventListenerInterface:
```
$eventManager->on($listener);
```
Binding with no options:
```
$eventManager->on('Model.beforeSave', $callable);
```
Binding with options:
```
$eventManager->on('Model.beforeSave', ['priority' => 90], $callable);
```
#### Parameters
`Cake\Event\EventListenerInterface|string` $eventKey `callable|array` $options optional `callable|null` $callable optional #### Returns
`$this`
### prioritisedListeners() public
```
prioritisedListeners(string $eventKey): array
```
Returns the listeners for the specified event key indexed by priority
#### Parameters
`string` $eventKey Event key.
#### Returns
`array`
### setEventList() public
```
setEventList(Cake\Event\EventList $eventList): $this
```
Enables the listing of dispatched events.
#### Parameters
`Cake\Event\EventList` $eventList The event list object to use.
#### Returns
`$this`
### trackEvents() public
```
trackEvents(bool $enabled): $this
```
Enables / disables event tracking at runtime.
#### Parameters
`bool` $enabled True or false to enable / disable it.
#### Returns
`$this`
### unsetEventList() public
```
unsetEventList(): $this
```
Disables the listing of dispatched events.
#### Returns
`$this`
Property Detail
---------------
### $\_eventList protected
The event list object.
#### Type
`Cake\Event\EventList|null`
### $\_generalManager protected static
The globally available instance, used for dispatching events attached from any scope
#### Type
`Cake\Event\EventManager|null`
### $\_isGlobal protected
Internal flag to distinguish a common manager from the singleton
#### Type
`bool`
### $\_listeners protected
List of listener callbacks associated to
#### Type
`array`
### $\_trackEvents protected
Enables automatic adding of events to the event list object if it is present.
#### Type
`bool`
### $defaultPriority public static
The default priority queue value for new, attached listeners
#### Type
`int`
cakephp Class PluginAssetsSymlinkCommand Class PluginAssetsSymlinkCommand
=================================
Command for symlinking / copying plugin assets to app's webroot.
**Namespace:** [Cake\Command](namespace-cake.command)
Constants
---------
* `int` **CODE\_ERROR**
```
1
```
Default error code
* `int` **CODE\_SUCCESS**
```
0
```
Default success code
Property Summary
----------------
* [$\_modelFactories](#%24_modelFactories) protected `array<callableCake\Datasource\Locator\LocatorInterface>` A list of overridden model factory functions.
* [$\_modelType](#%24_modelType) protected `string` The model type to use.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$args](#%24args) protected `Cake\Console\Arguments` Arguments
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
* [$io](#%24io) protected `Cake\Console\ConsoleIo` Console IO
* [$modelClass](#%24modelClass) protected deprecated `string|null` This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
* [$name](#%24name) protected `string` The name of this command.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_copyDirectory()](#_copyDirectory()) protected
Copy directory
* ##### [\_createDirectory()](#_createDirectory()) protected
Create directory
* ##### [\_createSymlink()](#_createSymlink()) protected
Create symlink
* ##### [\_list()](#_list()) protected
Get list of plugins to process. Plugins without a webroot directory are skipped.
* ##### [\_process()](#_process()) protected
Process plugins
* ##### [\_remove()](#_remove()) protected
Remove folder/symlink.
* ##### [\_setModelClass()](#_setModelClass()) protected
Set the modelClass property based on conventions.
* ##### [abort()](#abort()) public
Halt the the current process with a StopException.
* ##### [buildOptionParser()](#buildOptionParser()) public
Get the option parser.
* ##### [defaultName()](#defaultName()) public static
Get the command name.
* ##### [displayHelp()](#displayHelp()) protected
Output help content
* ##### [execute()](#execute()) public
Execute the command
* ##### [executeCommand()](#executeCommand()) public
Execute another command with the provided set of arguments.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getDescription()](#getDescription()) public static
Get the command description.
* ##### [getModelType()](#getModelType()) public
Get the model type to be used by this class
* ##### [getName()](#getName()) public
Get the command name.
* ##### [getOptionParser()](#getOptionParser()) public
Get the option parser.
* ##### [getRootName()](#getRootName()) public
Get the root command name.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [initialize()](#initialize()) public
Hook method invoked by CakePHP when a command is about to be executed.
* ##### [loadModel()](#loadModel()) public deprecated
Loads and constructs repository objects required by this object
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [modelFactory()](#modelFactory()) public
Override a existing callable to generate repositories of a given type.
* ##### [run()](#run()) public
Run the command.
* ##### [setModelType()](#setModelType()) public
Set the model type to be used by this class
* ##### [setName()](#setName()) public
Set the name this command uses in the collection.
* ##### [setOutputLevel()](#setOutputLevel()) protected
Set the output level based on the Arguments.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
Method Detail
-------------
### \_\_construct() public
```
__construct()
```
Constructor
By default CakePHP will construct command objects when building the CommandCollection for your application.
### \_copyDirectory() protected
```
_copyDirectory(string $source, string $destination): bool
```
Copy directory
#### Parameters
`string` $source Source directory
`string` $destination Destination directory
#### Returns
`bool`
### \_createDirectory() protected
```
_createDirectory(string $dir): bool
```
Create directory
#### Parameters
`string` $dir Directory name
#### Returns
`bool`
### \_createSymlink() protected
```
_createSymlink(string $target, string $link): bool
```
Create symlink
#### Parameters
`string` $target Target directory
`string` $link Link name
#### Returns
`bool`
### \_list() protected
```
_list(string|null $name = null): array<string, mixed>
```
Get list of plugins to process. Plugins without a webroot directory are skipped.
#### Parameters
`string|null` $name optional Name of plugin for which to symlink assets. If null all plugins will be processed.
#### Returns
`array<string, mixed>`
### \_process() protected
```
_process(array<string, mixed> $plugins, bool $copy = false, bool $overwrite = false): void
```
Process plugins
#### Parameters
`array<string, mixed>` $plugins List of plugins to process
`bool` $copy optional Force copy mode. Default false.
`bool` $overwrite optional Overwrite existing files.
#### Returns
`void`
### \_remove() protected
```
_remove(array<string, mixed> $config): bool
```
Remove folder/symlink.
#### Parameters
`array<string, mixed>` $config Plugin config.
#### Returns
`bool`
### \_setModelClass() protected
```
_setModelClass(string $name): void
```
Set the modelClass property based on conventions.
If the property is already set it will not be overwritten
#### Parameters
`string` $name Class name.
#### Returns
`void`
### abort() public
```
abort(int $code = self::CODE_ERROR): void
```
Halt the the current process with a StopException.
#### Parameters
`int` $code optional The exit code to use.
#### Returns
`void`
#### Throws
`Cake\Console\Exception\StopException`
### buildOptionParser() public
```
buildOptionParser(Cake\Console\ConsoleOptionParser $parser): Cake\Console\ConsoleOptionParser
```
Get the option parser.
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser to update
#### Returns
`Cake\Console\ConsoleOptionParser`
### defaultName() public static
```
defaultName(): string
```
Get the command name.
Returns the command name based on class name. For e.g. for a command with class name `UpdateTableCommand` the default name returned would be `'update_table'`.
#### Returns
`string`
### displayHelp() protected
```
displayHelp(Cake\Console\ConsoleOptionParser $parser, Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Output help content
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser.
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### execute() public
```
execute(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): int|null
```
Execute the command
Attempt to symlink plugin assets to app's webroot. If symlinking fails it fallbacks to copying the assets. For vendor namespaced plugin, parent folder for vendor name are created if required.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`int|null`
### executeCommand() public
```
executeCommand(Cake\Console\CommandInterface|string $command, array $args = [], Cake\Console\ConsoleIo|null $io = null): int|null
```
Execute another command with the provided set of arguments.
If you are using a string command name, that command's dependencies will not be resolved with the application container. Instead you will need to pass the command as an object with all of its dependencies.
#### Parameters
`Cake\Console\CommandInterface|string` $command The command class name or command instance.
`array` $args optional The arguments to invoke the command with.
`Cake\Console\ConsoleIo|null` $io optional The ConsoleIo instance to use for the executed command.
#### Returns
`int|null`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getDescription() public static
```
getDescription(): string
```
Get the command description.
#### Returns
`string`
### getModelType() public
```
getModelType(): string
```
Get the model type to be used by this class
#### Returns
`string`
### getName() public
```
getName(): string
```
Get the command name.
#### Returns
`string`
### getOptionParser() public
```
getOptionParser(): Cake\Console\ConsoleOptionParser
```
Get the option parser.
You can override buildOptionParser() to define your options & arguments.
#### Returns
`Cake\Console\ConsoleOptionParser`
#### Throws
`RuntimeException`
When the parser is invalid ### getRootName() public
```
getRootName(): string
```
Get the root command name.
#### Returns
`string`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### initialize() public
```
initialize(): void
```
Hook method invoked by CakePHP when a command is about to be executed.
Override this method and implement expensive/important setup steps that should not run on every command run. This method will be called *before* the options and arguments are validated and processed.
#### Returns
`void`
### loadModel() public
```
loadModel(string|null $modelClass = null, string|null $modelType = null): Cake\Datasource\RepositoryInterface
```
Loads and constructs repository objects required by this object
Typically used to load ORM Table objects as required. Can also be used to load other types of repository objects your application uses.
If a repository provider does not return an object a MissingModelException will be thrown.
#### Parameters
`string|null` $modelClass optional Name of model class to load. Defaults to $this->modelClass. The name can be an alias like `'Post'` or FQCN like `App\Model\Table\PostsTable::class`.
`string|null` $modelType optional The type of repository to load. Defaults to the getModelType() value.
#### Returns
`Cake\Datasource\RepositoryInterface`
#### Throws
`Cake\Datasource\Exception\MissingModelException`
If the model class cannot be found.
`UnexpectedValueException`
If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty. ### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### modelFactory() public
```
modelFactory(string $type, Cake\Datasource\Locator\LocatorInterface|callable $factory): void
```
Override a existing callable to generate repositories of a given type.
#### Parameters
`string` $type The name of the repository type the factory function is for.
`Cake\Datasource\Locator\LocatorInterface|callable` $factory The factory function used to create instances.
#### Returns
`void`
### run() public
```
run(array $argv, Cake\Console\ConsoleIo $io): int|null
```
Run the command.
#### Parameters
`array` $argv `Cake\Console\ConsoleIo` $io #### Returns
`int|null`
### setModelType() public
```
setModelType(string $modelType): $this
```
Set the model type to be used by this class
#### Parameters
`string` $modelType The model type
#### Returns
`$this`
### setName() public
```
setName(string $name): $this
```
Set the name this command uses in the collection.
Generally invoked by the CommandCollection when the command is added. Required to have at least one space in the name so that the root command can be calculated.
#### Parameters
`string` $name #### Returns
`$this`
### setOutputLevel() protected
```
setOutputLevel(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Set the output level based on the Arguments.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
Property Detail
---------------
### $\_modelFactories protected
A list of overridden model factory functions.
#### Type
`array<callableCake\Datasource\Locator\LocatorInterface>`
### $\_modelType protected
The model type to use.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $args protected
Arguments
#### Type
`Cake\Console\Arguments`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
### $io protected
Console IO
#### Type
`Cake\Console\ConsoleIo`
### $modelClass protected deprecated
This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
Example: For an object named 'Comments', the modelClass would be 'Comments'. Plugin classes should use `Plugin.Comments` style names to correctly load models from the correct plugin.
Use empty string to not use auto-loading on this object. Null auto-detects based on controller name.
#### Type
`string|null`
### $name protected
The name of this command.
#### Type
`string`
| programming_docs |
cakephp Class MissingDatasourceConfigException Class MissingDatasourceConfigException
=======================================
Exception class to be thrown when a datasource configuration is not found
**Namespace:** [Cake\Datasource\Exception](namespace-cake.datasource.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Interface ResultSetInterface Interface ResultSetInterface
=============================
Describes how a collection of datasource results should look like
**Namespace:** [Cake\Datasource](namespace-cake.datasource)
Method Summary
--------------
* ##### [append()](#append()) public
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
* ##### [appendItem()](#appendItem()) public
Append a single item creating a new collection.
* ##### [avg()](#avg()) public
Returns the average of all the values extracted with $path or of this collection.
* ##### [buffered()](#buffered()) public
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
* ##### [cartesianProduct()](#cartesianProduct()) public
Create a new collection that is the cartesian product of the current collection
* ##### [chunk()](#chunk()) public
Breaks the collection into smaller arrays of the given size.
* ##### [chunkWithKeys()](#chunkWithKeys()) public
Breaks the collection into smaller arrays of the given size.
* ##### [combine()](#combine()) public
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
* ##### [compile()](#compile()) public
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
* ##### [contains()](#contains()) public
Returns true if $value is present in this collection. Comparisons are made both by value and type.
* ##### [count()](#count()) public
Returns the amount of elements in the collection.
* ##### [countBy()](#countBy()) public
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
* ##### [countKeys()](#countKeys()) public
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
* ##### [each()](#each()) public
Applies a callback to the elements in this collection.
* ##### [every()](#every()) public
Returns true if all values in this collection pass the truth test provided in the callback.
* ##### [extract()](#extract()) public
Returns a new collection containing the column or property value found in each of the elements.
* ##### [filter()](#filter()) public
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
* ##### [first()](#first()) public
Returns the first result in this collection
* ##### [firstMatch()](#firstMatch()) public
Returns the first result matching all the key-value pairs listed in conditions.
* ##### [groupBy()](#groupBy()) public
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
* ##### [indexBy()](#indexBy()) public
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
* ##### [insert()](#insert()) public
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
* ##### [isEmpty()](#isEmpty()) public
Returns whether there are elements in this collection
* ##### [jsonSerialize()](#jsonSerialize()) public
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
* ##### [last()](#last()) public
Returns the last result in this collection
* ##### [lazy()](#lazy()) public
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
* ##### [listNested()](#listNested()) public
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
* ##### [map()](#map()) public
Returns another collection after modifying each of the values in this one using the provided callable.
* ##### [match()](#match()) public
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
* ##### [max()](#max()) public
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [median()](#median()) public
Returns the median of all the values extracted with $path or of this collection.
* ##### [min()](#min()) public
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [nest()](#nest()) public
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
* ##### [prepend()](#prepend()) public
Prepend a set of items to a collection creating a new collection
* ##### [prependItem()](#prependItem()) public
Prepend a single item creating a new collection.
* ##### [reduce()](#reduce()) public
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
* ##### [reject()](#reject()) public
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
* ##### [sample()](#sample()) public
Returns a new collection with maximum $size random elements from this collection
* ##### [shuffle()](#shuffle()) public
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
* ##### [skip()](#skip()) public
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
* ##### [some()](#some()) public
Returns true if any of the values in this collection pass the truth test provided in the callback.
* ##### [sortBy()](#sortBy()) public
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
* ##### [stopWhen()](#stopWhen()) public
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
* ##### [sumOf()](#sumOf()) public
Returns the total sum of all the values extracted with $matcher or of this collection.
* ##### [take()](#take()) public
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
* ##### [takeLast()](#takeLast()) public
Returns the last N elements of a collection
* ##### [through()](#through()) public
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
* ##### [toArray()](#toArray()) public
Returns an array representation of the results
* ##### [toList()](#toList()) public
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
* ##### [transpose()](#transpose()) public
Transpose rows and columns into columns and rows
* ##### [unfold()](#unfold()) public
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
* ##### [unwrap()](#unwrap()) public
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
* ##### [zip()](#zip()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
* ##### [zipWith()](#zipWith()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
Method Detail
-------------
### append() public
```
append(iterable $items): self
```
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
#### Parameters
`iterable` $items Items list.
#### Returns
`self`
### appendItem() public
```
appendItem(mixed $item, mixed $key = null): self
```
Append a single item creating a new collection.
#### Parameters
`mixed` $item The item to append.
`mixed` $key optional The key to append the item with. If null a key will be generated.
#### Returns
`self`
### avg() public
```
avg(callable|string|null $path = null): float|int|null
```
Returns the average of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->avg('invoice.total');
// Total: 150
$total = (new Collection([1, 2, 3]))->avg();
// Total: 2
```
The average of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional The property name to sum or a function If no value is passed, an identity function will be used. that will return the value of the property to sum.
#### Returns
`float|int|null`
### buffered() public
```
buffered(): self
```
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
This can also be used to make any non-rewindable iterator rewindable.
#### Returns
`self`
### cartesianProduct() public
```
cartesianProduct(callable|null $operation = null, callable|null $filter = null): self
```
Create a new collection that is the cartesian product of the current collection
In order to create a carteisan product a collection must contain a single dimension of data.
### Example
```
$collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
$result = $collection->cartesianProduct()->toArray();
$expected = [
['A', 1],
['A', 2],
['A', 3],
['B', 1],
['B', 2],
['B', 3],
['C', 1],
['C', 2],
['C', 3],
];
```
#### Parameters
`callable|null` $operation optional A callable that allows you to customize the product result.
`callable|null` $filter optional A filtering callback that must return true for a result to be part of the final results.
#### Returns
`self`
### chunk() public
```
chunk(int $chunkSize): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
$chunked = (new Collection($items))->chunk(3)->toList();
// Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
```
#### Parameters
`int` $chunkSize The maximum size for each chunk
#### Returns
`self`
### chunkWithKeys() public
```
chunkWithKeys(int $chunkSize, bool $keepKeys = true): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
$chunked = (new Collection($items))->chunkWithKeys(3)->toList();
// Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
```
#### Parameters
`int` $chunkSize The maximum size for each chunk
`bool` $keepKeys optional If the keys of the array should be kept
#### Returns
`self`
### combine() public
```
combine(callable|string $keyPath, callable|string $valuePath, callable|string|null $groupPath = null): self
```
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
### Examples:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent' => 'a'],
['id' => 2, 'name' => 'bar', 'parent' => 'b'],
['id' => 3, 'name' => 'baz', 'parent' => 'a'],
];
$combined = (new Collection($items))->combine('id', 'name');
// Result will look like this when converted to array
[
1 => 'foo',
2 => 'bar',
3 => 'baz',
];
$combined = (new Collection($items))->combine('id', 'name', 'parent');
// Result will look like this when converted to array
[
'a' => [1 => 'foo', 3 => 'baz'],
'b' => [2 => 'bar']
];
```
#### Parameters
`callable|string` $keyPath the column name path to use for indexing or a function returning the indexing key out of the provided element
`callable|string` $valuePath the column name path to use as the array value or a function returning the value out of the provided element
`callable|string|null` $groupPath optional the column name path to use as the parent grouping key or a function returning the key out of the provided element
#### Returns
`self`
### compile() public
```
compile(bool $keepKeys = true): self
```
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
A common use case is to re-use the same variable for calculating different data. In those cases it may be helpful and more performant to first compile a collection and then apply more operations to it.
### Example:
```
$collection->map($mapper)->sortBy('age')->extract('name');
$compiled = $collection->compile();
$isJohnHere = $compiled->some($johnMatcher);
$allButJohn = $compiled->filter($johnMatcher);
```
In the above example, had the collection not been compiled before, the iterations for `map`, `sortBy` and `extract` would've been executed twice: once for getting `$isJohnHere` and once for `$allButJohn`
You can think of this method as a way to create save points for complex calculations in a collection.
#### Parameters
`bool` $keepKeys optional Whether to use the keys returned by this collection as the array keys. Keep in mind that it is valid for iterators to return the same key for different elements, setting this value to false can help getting all items if keys are not important in the result.
#### Returns
`self`
### contains() public
```
contains(mixed $value): bool
```
Returns true if $value is present in this collection. Comparisons are made both by value and type.
#### Parameters
`mixed` $value The value to check for
#### Returns
`bool`
### count() public
```
count(): int
```
Returns the amount of elements in the collection.
WARNINGS:
---------
### Will change the current position of the iterator:
Calling this method at the same time that you are iterating this collections, for example in a foreach, will result in undefined behavior. Avoid doing this.
### Consumes all elements for NoRewindIterator collections:
On certain type of collections, calling this method may render unusable afterwards. That is, you may not be able to get elements out of it, or to iterate on it anymore.
Specifically any collection wrapping a Generator (a function with a yield statement) or a unbuffered database cursor will not accept any other function calls after calling `count()` on it.
Create a new collection with `buffered()` method to overcome this problem.
### Can report more elements than unique keys:
Any collection constructed by appending collections together, or by having internal iterators returning duplicate keys, will report a larger amount of elements using this functions than the final amount of elements when converting the collections to a keyed array. This is because duplicate keys will be collapsed into a single one in the final array, whereas this count method is only concerned by the amount of elements after converting it to a plain list.
If you need the count of elements after taking the keys in consideration (the count of unique keys), you can call `countKeys()`
#### Returns
`int`
### countBy() public
```
countBy(callable|string $path): self
```
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->countBy('parent_id');
// Or
$group = (new Collection($items))->countBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => 2,
11 => 1
];
```
#### Parameters
`callable|string` $path The column name to use for indexing or callback that returns the value. or a function returning the indexing key out of the provided element
#### Returns
`self`
### countKeys() public
```
countKeys(): int
```
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
This method comes with a number of caveats. Please refer to `CollectionInterface::count()` for details.
#### Returns
`int`
#### See Also
\Cake\Collection\CollectionInterface::count() ### each() public
```
each(callable $callback): $this
```
Applies a callback to the elements in this collection.
### Example:
```
$collection = (new Collection($items))->each(function ($value, $key) {
echo "Element $key: $value";
});
```
#### Parameters
`callable` $callback Callback to run for each element in collection.
#### Returns
`$this`
### every() public
```
every(callable $callback): bool
```
Returns true if all values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$overTwentyOne = (new Collection([24, 45, 60, 15]))->every(function ($value, $key) {
return $value > 21;
});
```
Empty collections always return true.
#### Parameters
`callable` $callback a callback function
#### Returns
`bool`
### extract() public
```
extract(callable|string $path): self
```
Returns a new collection containing the column or property value found in each of the elements.
The matcher can be a string with a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection, that position is filled with null.
### Example:
Extract the user name for all comments in the array:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->extract('comment.user.name');
// Result will look like this when converted to array
['Mark', 'Renan']
```
It is also possible to extract a flattened collection out of nested properties
```
$items = [
['comment' => ['votes' => [['value' => 1], ['value' => 2], ['value' => 3]]],
['comment' => ['votes' => [['value' => 4]]
];
$extracted = (new Collection($items))->extract('comment.votes.{*}.value');
// Result will contain
[1, 2, 3, 4]
```
#### Parameters
`callable|string` $path A dot separated path of column to follow so that the final one can be returned or a callable that will take care of doing that.
#### Returns
`self`
### filter() public
```
filter(callable|null $callback = null): self
```
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering odd numbers in an array, at the end only the value 2 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->filter(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable|null` $callback optional the method that will receive each of the elements and returns true whether they should be in the resulting collection. If left null, a callback that filters out falsey values will be used.
#### Returns
`self`
### first() public
```
first(): mixed
```
Returns the first result in this collection
#### Returns
`mixed`
### firstMatch() public
```
firstMatch(array $conditions): mixed
```
Returns the first result matching all the key-value pairs listed in conditions.
#### Parameters
`array` $conditions a key-value list of conditions where the key is a property path as accepted by `Collection::extract`, and the value the condition against with each element will be matched
#### Returns
`mixed`
#### See Also
\Cake\Collection\CollectionInterface::match() ### groupBy() public
```
groupBy(callable|string $path): self
```
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->groupBy('parent_id');
// Or
$group = (new Collection($items))->groupBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
],
11 => [
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
]
];
```
#### Parameters
`callable|string` $path The column name to use for grouping or callback that returns the value. or a function returning the grouping key out of the provided element
#### Returns
`self`
### indexBy() public
```
indexBy(callable|string $path): self
```
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo'],
['id' => 2, 'name' => 'bar'],
['id' => 3, 'name' => 'baz'],
];
$indexed = (new Collection($items))->indexBy('id');
// Or
$indexed = (new Collection($items))->indexBy(function ($e) {
return $e['id'];
});
// Result will look like this when converted to array
[
1 => ['id' => 1, 'name' => 'foo'],
3 => ['id' => 3, 'name' => 'baz'],
2 => ['id' => 2, 'name' => 'bar'],
];
```
#### Parameters
`callable|string` $path The column name to use for indexing or callback that returns the value. or a function returning the indexing key out of the provided element
#### Returns
`self`
### insert() public
```
insert(string $path, mixed $values): self
```
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
The $path can be a string with a property name or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection as part of the path, the element will be kept unchanged.
### Example:
Insert ages into a collection containing users:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
];
$ages = [25, 28];
$inserted = (new Collection($items))->insert('comment.user.age', $ages);
// Result will look like this when converted to array
[
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
];
```
#### Parameters
`string` $path a dot separated string symbolizing the path to follow inside the hierarchy of each value so that the value can be inserted
`mixed` $values The values to be inserted at the specified path, values are matched with the elements in this collection by its positional index.
#### Returns
`self`
### isEmpty() public
```
isEmpty(): bool
```
Returns whether there are elements in this collection
### Example:
```
$items [1, 2, 3];
(new Collection($items))->isEmpty(); // false
```
```
(new Collection([]))->isEmpty(); // true
```
#### Returns
`bool`
### jsonSerialize() public
```
jsonSerialize(): array
```
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
Part of JsonSerializable interface.
#### Returns
`array`
### last() public
```
last(): mixed
```
Returns the last result in this collection
#### Returns
`mixed`
### lazy() public
```
lazy(): self
```
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
A lazy collection can only be iterated once. A second attempt results in an error.
#### Returns
`self`
### listNested() public
```
listNested(string|int $order = 'desc', callable|string $nestingKey = 'children'): self
```
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
By default all elements in the tree following a Depth First Search will be returned, that is, elements from the top parent to the leaves for each branch.
It is possible to return all elements from bottom to top using a Breadth First Search approach by passing the '$dir' parameter with 'asc'. That is, it will return all elements for the same tree depth first and from bottom to top.
Finally, you can specify to only get a collection with the leaf nodes in the tree structure. You do so by passing 'leaves' in the first argument.
The possible values for the first argument are aliases for the following constants and it is valid to pass those instead of the alias:
* desc: RecursiveIteratorIterator::SELF\_FIRST
* asc: RecursiveIteratorIterator::CHILD\_FIRST
* leaves: RecursiveIteratorIterator::LEAVES\_ONLY
### Example:
```
$collection = new Collection([
['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
['id' => 4, 'children' => [['id' => 5]]]
]);
$flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
```
#### Parameters
`string|int` $order optional The order in which to return the elements
`callable|string` $nestingKey optional The key name under which children are nested or a callable function that will return the children list
#### Returns
`self`
### map() public
```
map(callable $callback): self
```
Returns another collection after modifying each of the values in this one using the provided callable.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Getting a collection of booleans where true indicates if a person is female:
```
$collection = (new Collection($people))->map(function ($person, $key) {
return $person->gender === 'female';
});
```
#### Parameters
`callable` $callback the method that will receive each of the elements and returns the new value for the key that is being iterated
#### Returns
`self`
### match() public
```
match(array $conditions): self
```
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
### Example:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->match(['user.name' => 'Renan']);
// Result will look like this when converted to array
[
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
]
```
#### Parameters
`array` $conditions a key-value list of conditions where the key is a property path as accepted by `Collection::extract, and the value the condition against with each element will be matched
#### Returns
`self`
### max() public
```
max(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$max = $collection->max('age');
$max = $collection->max('user.salary');
$max = $collection->max(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $max->name;
```
#### Parameters
`callable|string` $path The column name to use for sorting or callback that returns the value.
`int` $sort optional The sort type, one of SORT\_STRING SORT\_NUMERIC or SORT\_NATURAL
#### Returns
`mixed`
#### See Also
\Cake\Collection\CollectionInterface::sortBy() ### median() public
```
median(callable|string|null $path = null): float|int|null
```
Returns the median of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 400]],
['invoice' => ['total' => 500]]
['invoice' => ['total' => 100]]
['invoice' => ['total' => 333]]
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->median('invoice.total');
// Total: 333
$total = (new Collection([1, 2, 3, 4]))->median();
// Total: 2.5
```
The median of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional The property name to sum or a function If no value is passed, an identity function will be used. that will return the value of the property to sum.
#### Returns
`float|int|null`
### min() public
```
min(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$min = $collection->min('age');
$min = $collection->min('user.salary');
$min = $collection->min(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $min->name;
```
#### Parameters
`callable|string` $path The column name to use for sorting or callback that returns the value.
`int` $sort optional The sort type, one of SORT\_STRING SORT\_NUMERIC or SORT\_NATURAL
#### Returns
`mixed`
#### See Also
\Cake\Collection\CollectionInterface::sortBy() ### nest() public
```
nest(callable|string $idPath, callable|string $parentPath, string $nestingKey = 'children'): self
```
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
#### Parameters
`callable|string` $idPath the column name path to use for determining whether an element is parent of another
`callable|string` $parentPath the column name path to use for determining whether an element is child of another
`string` $nestingKey optional The key name under which children are nested
#### Returns
`self`
### prepend() public
```
prepend(mixed $items): self
```
Prepend a set of items to a collection creating a new collection
#### Parameters
`mixed` $items The items to prepend.
#### Returns
`self`
### prependItem() public
```
prependItem(mixed $item, mixed $key = null): self
```
Prepend a single item creating a new collection.
#### Parameters
`mixed` $item The item to prepend.
`mixed` $key optional The key to prepend the item with. If null a key will be generated.
#### Returns
`self`
### reduce() public
```
reduce(callable $callback, mixed $initial = null): mixed
```
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
#### Parameters
`callable` $callback The callback function to be called
`mixed` $initial optional The state of reduction
#### Returns
`mixed`
### reject() public
```
reject(callable $callback): self
```
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering even numbers in an array, at the end only values 1 and 3 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->reject(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable` $callback the method that will receive each of the elements and returns true whether they should be out of the resulting collection.
#### Returns
`self`
### sample() public
```
sample(int $length = 10): self
```
Returns a new collection with maximum $size random elements from this collection
#### Parameters
`int` $length optional the maximum number of elements to randomly take from this collection
#### Returns
`self`
### shuffle() public
```
shuffle(): self
```
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
#### Returns
`self`
### skip() public
```
skip(int $length): self
```
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
#### Parameters
`int` $length The number of elements to skip.
#### Returns
`self`
### some() public
```
some(callable $callback): bool
```
Returns true if any of the values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$hasYoungPeople = (new Collection([24, 45, 15]))->some(function ($value, $key) {
return $value < 21;
});
```
#### Parameters
`callable` $callback a callback function
#### Returns
`bool`
### sortBy() public
```
sortBy(callable|string $path, int $order = SORT_DESC, int $sort = \SORT_NUMERIC): self
```
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
The callback will receive as its first argument each of the elements in $items, the value returned by the callback will be used as the value for sorting such element. Please note that the callback function could be called more than once per element.
### Example:
```
$items = $collection->sortBy(function ($user) {
return $user->age;
});
// alternatively
$items = $collection->sortBy('age');
// or use a property path
$items = $collection->sortBy('department.name');
// output all user name order by their age in descending order
foreach ($items as $user) {
echo $user->name;
}
```
#### Parameters
`callable|string` $path The column name to use for sorting or callback that returns the value.
`int` $order optional The sort order, either SORT\_DESC or SORT\_ASC
`int` $sort optional The sort type, one of SORT\_STRING SORT\_NUMERIC or SORT\_NATURAL
#### Returns
`self`
### stopWhen() public
```
stopWhen(callable|array $condition): self
```
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
This is handy for dealing with infinite iterators or any generator that could start returning invalid elements at a certain point. For example, when reading lines from a file stream you may want to stop the iteration after a certain value is reached.
### Example:
Get an array of lines in a CSV file until the timestamp column is less than a date
```
$lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
return (new DateTime($value))->format('Y') < 2012;
})
->toArray();
```
Get elements until the first unapproved message is found:
```
$comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
```
#### Parameters
`callable|array` $condition the method that will receive each of the elements and returns true when the iteration should be stopped. If an array, it will be interpreted as a key-value list of conditions where the key is a property path as accepted by `Collection::extract`, and the value the condition against with each element will be matched.
#### Returns
`self`
### sumOf() public
```
sumOf(callable|string|null $path = null): float|int
```
Returns the total sum of all the values extracted with $matcher or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->sumOf('invoice.total');
// Total: 300
$total = (new Collection([1, 2, 3]))->sumOf();
// Total: 6
```
#### Parameters
`callable|string|null` $path optional The property name to sum or a function If no value is passed, an identity function will be used. that will return the value of the property to sum.
#### Returns
`float|int`
### take() public
```
take(int $length = 1, int $offset = 0): self
```
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
#### Parameters
`int` $length optional the maximum number of elements to take from this collection
`int` $offset optional A positional offset from where to take the elements
#### Returns
`self`
### takeLast() public
```
takeLast(int $length): self
```
Returns the last N elements of a collection
### Example:
```
$items = [1, 2, 3, 4, 5];
$last = (new Collection($items))->takeLast(3);
// Result will look like this when converted to array
[3, 4, 5];
```
#### Parameters
`int` $length The number of elements at the end of the collection
#### Returns
`self`
### through() public
```
through(callable $callback): self
```
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
### Example:
```
$items = [1, 2, 3];
$decorated = (new Collection($items))->through(function ($collection) {
return new MyCustomCollection($collection);
});
```
#### Parameters
`callable` $callback A callable function that will receive this collection as first argument.
#### Returns
`self`
### toArray() public
```
toArray(bool $keepKeys = true): array
```
Returns an array representation of the results
#### Parameters
`bool` $keepKeys optional Whether to use the keys returned by this collection as the array keys. Keep in mind that it is valid for iterators to return the same key for different elements, setting this value to false can help getting all items if keys are not important in the result.
#### Returns
`array`
### toList() public
```
toList(): array
```
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
#### Returns
`array`
### transpose() public
```
transpose(): self
```
Transpose rows and columns into columns and rows
### Example:
```
$items = [
['Products', '2012', '2013', '2014'],
['Product A', '200', '100', '50'],
['Product B', '300', '200', '100'],
['Product C', '400', '300', '200'],
]
$transpose = (new Collection($items))->transpose()->toList();
// Returns
// [
// ['Products', 'Product A', 'Product B', 'Product C'],
// ['2012', '200', '300', '400'],
// ['2013', '100', '200', '300'],
// ['2014', '50', '100', '200'],
// ]
```
#### Returns
`self`
### unfold() public
```
unfold(callable|null $callback = null): self
```
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
The transformer function will receive the value and the key for each of the items in the collection, in that order, and it must return an array or a Traversable object that can be concatenated to the final result.
If no transformer function is passed, an "identity" function will be used. This is useful when each of the elements in the source collection are lists of items to be appended one after another.
### Example:
```
$items [[1, 2, 3], [4, 5]];
$unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
```
Using a transformer
```
$items [1, 2, 3];
$allItems = (new Collection($items))->unfold(function ($page) {
return $service->fetchPage($page)->toArray();
});
```
#### Parameters
`callable|null` $callback optional A callable function that will receive each of the items in the collection and should return an array or Traversable object
#### Returns
`self`
### unwrap() public
```
unwrap(): Traversable
```
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
#### Returns
`Traversable`
### zip() public
```
zip(iterable $items): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
### Example:
```
$collection = new Collection([1, 2]);
$collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
```
#### Parameters
`iterable` $items The collections to zip.
#### Returns
`self`
### zipWith() public
```
zipWith(iterable $items, callable $callback): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
The resulting element will be the return value of the $callable function.
### Example:
```
$collection = new Collection([1, 2]);
$zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
return array_sum($args);
});
$zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
```
#### Parameters
`iterable` $items The collections to zip.
`callable` $callback The function to use for zipping the elements together.
#### Returns
`self`
| programming_docs |
cakephp Class HelperRegistry Class HelperRegistry
=====================
HelperRegistry is used as a registry for loaded helpers and handles loading and constructing helper class objects.
**Namespace:** [Cake\View](namespace-cake.view)
Property Summary
----------------
* [$\_View](#%24_View) protected `Cake\View\View` View object to use when making helpers.
* [$\_eventClass](#%24_eventClass) protected `string` Default class name for new event objects.
* [$\_eventManager](#%24_eventManager) protected `Cake\Event\EventManagerInterface|null` Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
* [$\_loaded](#%24_loaded) protected `array<object>` Map of loaded objects.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Debug friendly object properties.
* ##### [\_\_get()](#__get()) public
Provide public read access to the loaded objects
* ##### [\_\_isset()](#__isset()) public
Tries to lazy load a helper based on its name, if it cannot be found in the application folder, then it tries looking under the current plugin if any
* ##### [\_\_set()](#__set()) public
Sets an object.
* ##### [\_\_unset()](#__unset()) public
Unsets an object.
* ##### [\_checkDuplicate()](#_checkDuplicate()) protected
Check for duplicate object loading.
* ##### [\_create()](#_create()) protected
Create the helper instance.
* ##### [\_resolveClassName()](#_resolveClassName()) protected
Resolve a helper classname.
* ##### [\_throwMissingClassError()](#_throwMissingClassError()) protected
Throws an exception when a helper is missing.
* ##### [count()](#count()) public
Returns the number of loaded objects.
* ##### [dispatchEvent()](#dispatchEvent()) public
Wrapper for creating and dispatching events.
* ##### [get()](#get()) public
Get loaded object instance.
* ##### [getEventManager()](#getEventManager()) public
Returns the Cake\Event\EventManager manager instance for this object.
* ##### [getIterator()](#getIterator()) public
Returns an array iterator.
* ##### [has()](#has()) public
Check whether a given object is loaded.
* ##### [load()](#load()) public
Loads/constructs an object instance.
* ##### [loaded()](#loaded()) public
Get the list of loaded objects.
* ##### [normalizeArray()](#normalizeArray()) public
Normalizes an object array, creates an array that makes lazy loading easier
* ##### [reset()](#reset()) public
Clear loaded instances in the registry.
* ##### [set()](#set()) public
Set an object directly into the registry by name.
* ##### [setEventManager()](#setEventManager()) public
Returns the Cake\Event\EventManagerInterface instance for this object.
* ##### [unload()](#unload()) public
Remove an object from the registry.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\View\View $view)
```
Constructor
#### Parameters
`Cake\View\View` $view View object.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Debug friendly object properties.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): Cake\View\Helper|null
```
Provide public read access to the loaded objects
#### Parameters
`string` $name Name of property to read
#### Returns
`Cake\View\Helper|null`
### \_\_isset() public
```
__isset(string $helper): bool
```
Tries to lazy load a helper based on its name, if it cannot be found in the application folder, then it tries looking under the current plugin if any
#### Parameters
`string` $helper The helper name to be loaded
#### Returns
`bool`
#### Throws
`Cake\View\Exception\MissingHelperException`
When a helper could not be found. App helpers are searched, and then plugin helpers. ### \_\_set() public
```
__set(string $name, object $object): void
```
Sets an object.
#### Parameters
`string` $name Name of a property to set.
`object` $object Object to set.
#### Returns
`void`
### \_\_unset() public
```
__unset(string $name): void
```
Unsets an object.
#### Parameters
`string` $name Name of a property to unset.
#### Returns
`void`
### \_checkDuplicate() protected
```
_checkDuplicate(string $name, array<string, mixed> $config): void
```
Check for duplicate object loading.
If a duplicate is being loaded and has different configuration, that is bad and an exception will be raised.
An exception is raised, as replacing the object will not update any references other objects may have. Additionally, simply updating the runtime configuration is not a good option as we may be missing important constructor logic dependent on the configuration.
#### Parameters
`string` $name The name of the alias in the registry.
`array<string, mixed>` $config The config data for the new instance.
#### Returns
`void`
#### Throws
`RuntimeException`
When a duplicate is found. ### \_create() protected
```
_create(object|string $class, string $alias, array<string, mixed> $config): Cake\View\Helper
```
Create the helper instance.
Part of the template method for Cake\Core\ObjectRegistry::load() Enabled helpers will be registered with the event manager.
#### Parameters
`object|string` $class The class to create.
`string` $alias The alias of the loaded helper.
`array<string, mixed>` $config An array of settings to use for the helper.
#### Returns
`Cake\View\Helper`
### \_resolveClassName() protected
```
_resolveClassName(string $class): string|null
```
Resolve a helper classname.
Part of the template method for Cake\Core\ObjectRegistry::load()
#### Parameters
`string` $class Partial classname to resolve.
#### Returns
`string|null`
### \_throwMissingClassError() protected
```
_throwMissingClassError(string $class, string|null $plugin): void
```
Throws an exception when a helper is missing.
Part of the template method for Cake\Core\ObjectRegistry::load() and Cake\Core\ObjectRegistry::unload()
#### Parameters
`string` $class The classname that is missing.
`string|null` $plugin The plugin the helper is missing in.
#### Returns
`void`
#### Throws
`Cake\View\Exception\MissingHelperException`
### count() public
```
count(): int
```
Returns the number of loaded objects.
#### Returns
`int`
### dispatchEvent() public
```
dispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\EventInterface
```
Wrapper for creating and dispatching events.
Returns a dispatched event.
#### Parameters
`string` $name Name of the event.
`array|null` $data optional Any value you wish to be transported with this event to it can be read by listeners.
`object|null` $subject optional The object that this event applies to ($this by default).
#### Returns
`Cake\Event\EventInterface`
### get() public
```
get(string $name): object
```
Get loaded object instance.
#### Parameters
`string` $name Name of object.
#### Returns
`object`
#### Throws
`RuntimeException`
If not loaded or found. ### getEventManager() public
```
getEventManager(): Cake\Event\EventManagerInterface
```
Returns the Cake\Event\EventManager manager 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.
#### Returns
`Cake\Event\EventManagerInterface`
### getIterator() public
```
getIterator(): Traversable
```
Returns an array iterator.
#### Returns
`Traversable`
### has() public
```
has(string $name): bool
```
Check whether a given object is loaded.
#### Parameters
`string` $name The object name to check for.
#### Returns
`bool`
### load() public
```
load(string $name, array<string, mixed> $config = []): mixed
```
Loads/constructs an object instance.
Will return the instance in the registry if it already exists. If a subclass provides event support, you can use `$config['enabled'] = false` to exclude constructed objects from being registered for events.
Using {@link \Cake\Controller\Component::$components} as an example. You can alias an object by setting the 'className' key, i.e.,
```
protected $components = [
'Email' => [
'className' => 'App\Controller\Component\AliasedEmailComponent'
];
];
```
All calls to the `Email` component would use `AliasedEmail` instead.
#### Parameters
`string` $name The name/class of the object to load.
`array<string, mixed>` $config optional Additional settings to use when loading the object.
#### Returns
`mixed`
#### Throws
`Exception`
If the class cannot be found. ### loaded() public
```
loaded(): array<string>
```
Get the list of loaded objects.
#### Returns
`array<string>`
### normalizeArray() public
```
normalizeArray(array $objects): array<string, array>
```
Normalizes an object array, creates an array that makes lazy loading easier
#### Parameters
`array` $objects Array of child objects to normalize.
#### Returns
`array<string, array>`
### reset() public
```
reset(): $this
```
Clear loaded instances in the registry.
If the registry subclass has an event manager, the objects will be detached from events as well.
#### Returns
`$this`
### set() public
```
set(string $name, object $object): $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
#### Parameters
`string` $name The name of the object to set in the registry.
`object` $object instance to store in the registry
#### Returns
`$this`
### setEventManager() public
```
setEventManager(Cake\Event\EventManagerInterface $eventManager): $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.
#### Parameters
`Cake\Event\EventManagerInterface` $eventManager the eventManager to set
#### Returns
`$this`
### unload() public
```
unload(string $name): $this
```
Remove an object from the registry.
If this registry has an event manager, the object will be detached from any events as well.
#### Parameters
`string` $name The name of the object to remove from the registry.
#### Returns
`$this`
Property Detail
---------------
### $\_View protected
View object to use when making helpers.
#### Type
`Cake\View\View`
### $\_eventClass protected
Default class name for new event objects.
#### Type
`string`
### $\_eventManager protected
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
#### Type
`Cake\Event\EventManagerInterface|null`
### $\_loaded protected
Map of loaded objects.
#### Type
`array<object>`
cakephp Interface LocatorInterface Interface LocatorInterface
===========================
Registries for Table objects should implement this interface.
**Namespace:** [Cake\ORM\Locator](namespace-cake.orm.locator)
Method Summary
--------------
* ##### [clear()](#clear()) public
Clears the registry of configuration and instances.
* ##### [exists()](#exists()) public
Check to see if an instance exists in the registry.
* ##### [get()](#get()) public
Get a table instance from the registry.
* ##### [getConfig()](#getConfig()) public
Returns configuration for an alias or the full configuration array for all aliases.
* ##### [remove()](#remove()) public
Removes an repository instance from the registry.
* ##### [set()](#set()) public
Set a table instance.
* ##### [setConfig()](#setConfig()) public
Stores a list of options to be used when instantiating an object with a matching alias.
Method Detail
-------------
### clear() public
```
clear(): void
```
Clears the registry of configuration and instances.
#### Returns
`void`
### exists() public
```
exists(string $alias): bool
```
Check to see if an instance exists in the registry.
#### Parameters
`string` $alias The alias to check for.
#### Returns
`bool`
### get() public
```
get(string $alias, array<string, mixed> $options = []): Cake\ORM\Table
```
Get a table instance from the registry.
#### Parameters
`string` $alias The alias name you want to get.
`array<string, mixed>` $options optional The options you want to build the table with.
#### Returns
`Cake\ORM\Table`
### getConfig() public
```
getConfig(string|null $alias = null): array
```
Returns configuration for an alias or the full configuration array for all aliases.
#### Parameters
`string|null` $alias optional Alias to get config for, null for complete config.
#### Returns
`array`
### remove() public
```
remove(string $alias): void
```
Removes an repository instance from the registry.
#### Parameters
`string` $alias The alias to remove.
#### Returns
`void`
### set() public
```
set(string $alias, Cake\Datasource\RepositoryInterface $repository): Cake\ORM\Table
```
Set a table instance.
#### Parameters
`string` $alias The alias to set.
`Cake\Datasource\RepositoryInterface` $repository The table to set.
#### Returns
`Cake\ORM\Table`
### setConfig() public
```
setConfig(array<string, mixed>|string $alias, array<string, mixed>|null $options = null): $this
```
Stores a list of options to be used when instantiating an object with a matching alias.
#### Parameters
`array<string, mixed>|string` $alias Name of the alias or array to completely overwrite current config.
`array<string, mixed>|null` $options optional list of options for the alias
#### Returns
`$this`
#### Throws
`RuntimeException`
When you attempt to configure an existing table instance.
cakephp Class CallbackStream Class CallbackStream
=====================
Implementation of PSR HTTP streams.
This differs from Laminas\Diactoros\Callback stream in that it allows the use of `echo` inside the callback, and gracefully handles the callback not returning a string.
Ideally we can amend/update diactoros, but we need to figure that out with the diactoros project. Until then we'll use this shim to provide backwards compatibility with existing CakePHP apps.
**Namespace:** [Cake\Http](namespace-cake.http)
Property Summary
----------------
* [$callback](#%24callback) protected `callable|null`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
* ##### [\_\_toString()](#__toString()) public
Reads all data from the stream into a string, from the beginning to end.
* ##### [attach()](#attach()) public
Attach a new callback to the instance.
* ##### [close()](#close()) public
Closes the stream and any underlying resources.
* ##### [detach()](#detach()) public
Separates any underlying resources from the stream.
* ##### [eof()](#eof()) public
Returns true if the stream is at the end of the stream.
* ##### [getContents()](#getContents()) public
Returns the remaining contents in a string
* ##### [getMetadata()](#getMetadata()) public
Get stream metadata as an associative array or retrieve a specific key.
* ##### [getSize()](#getSize()) public
Get the size of the stream if known.
* ##### [isReadable()](#isReadable()) public
Returns whether or not the stream is readable.
* ##### [isSeekable()](#isSeekable()) public
Returns whether or not the stream is seekable.
* ##### [isWritable()](#isWritable()) public
Returns whether or not the stream is writable.
* ##### [read()](#read()) public
Read data from the stream.
* ##### [rewind()](#rewind()) public
Seek to the beginning of the stream.
* ##### [seek()](#seek()) public
Seek to a position in the stream.
* ##### [tell()](#tell()) public
Returns the current position of the file read/write pointer
* ##### [write()](#write()) public
Write data to the stream.
Method Detail
-------------
### \_\_construct() public
```
__construct(callable $callback)
```
#### Parameters
`callable` $callback #### Throws
`Exception\InvalidArgumentException`
### \_\_toString() public
```
__toString(): string
```
Reads all data from the stream into a string, from the beginning to end.
This method MUST attempt to seek to the beginning of the stream before reading data and read the stream until the end is reached.
Warning: This could attempt to load a large amount of data into memory.
This method MUST NOT raise an exception in order to conform with PHP's string casting operations.
#### Returns
`string`
### attach() public
```
attach(callable $callback): void
```
Attach a new callback to the instance.
#### Parameters
`callable` $callback #### Returns
`void`
### close() public
```
close(): void
```
Closes the stream and any underlying resources.
#### Returns
`void`
### detach() public
```
detach(): null|callable
```
Separates any underlying resources from the stream.
After the stream has been detached, the stream is in an unusable state.
#### Returns
`null|callable`
### eof() public
```
eof(): bool
```
Returns true if the stream is at the end of the stream.
#### Returns
`bool`
### getContents() public
```
getContents(): string
```
Returns the remaining contents in a string
#### Returns
`string`
### getMetadata() public
```
getMetadata(string $key = null): array|mixed|null
```
Get stream metadata as an associative array or retrieve a specific key.
The keys returned are identical to the keys returned from PHP's stream\_get\_meta\_data() function.
#### Parameters
`string` $key optional #### Returns
`array|mixed|null`
### getSize() public
```
getSize(): ?int
```
Get the size of the stream if known.
#### Returns
`?int`
### isReadable() public
```
isReadable(): bool
```
Returns whether or not the stream is readable.
#### Returns
`bool`
### isSeekable() public
```
isSeekable(): bool
```
Returns whether or not the stream is seekable.
#### Returns
`bool`
### isWritable() public
```
isWritable(): bool
```
Returns whether or not the stream is writable.
#### Returns
`bool`
### read() public
```
read(int $length): string
```
Read data from the stream.
#### Parameters
`int` $length #### Returns
`string`
### rewind() public
```
rewind(): void
```
Seek to the beginning of the stream.
If the stream is not seekable, this method will raise an exception; otherwise, it will perform a seek(0).
#### Returns
`void`
### seek() public
```
seek(int $offset, int $whence = SEEK_SET): void
```
Seek to a position in the stream.
#### Parameters
`int` $offset `int` $whence optional #### Returns
`void`
### tell() public
```
tell(): int
```
Returns the current position of the file read/write pointer
#### Returns
`int`
### write() public
```
write(string $string): void
```
Write data to the stream.
#### Parameters
`string` $string #### Returns
`void`
Property Detail
---------------
### $callback protected
#### Type
`callable|null`
cakephp Namespace Crypto Namespace Crypto
================
### Classes
* ##### [OpenSsl](class-cake.utility.crypto.openssl)
OpenSSL implementation of crypto features for Cake\Utility\Security
| programming_docs |
cakephp Class TableSchema Class TableSchema
==================
Represents a single table in a database schema.
Can either be populated using the reflection API's or by incrementally building an instance using methods.
Once created TableSchema instances can be added to Schema\Collection objects. They can also be converted into SQL using the createSql(), dropSql() and truncateSql() methods.
**Namespace:** [Cake\Database\Schema](namespace-cake.database.schema)
Constants
---------
* `string` **ACTION\_CASCADE**
```
'cascade'
```
Foreign key cascade action
* `string` **ACTION\_NO\_ACTION**
```
'noAction'
```
Foreign key no action
* `string` **ACTION\_RESTRICT**
```
'restrict'
```
Foreign key restrict action
* `string` **ACTION\_SET\_DEFAULT**
```
'setDefault'
```
Foreign key restrict default
* `string` **ACTION\_SET\_NULL**
```
'setNull'
```
Foreign key set null action
* `string` **CONSTRAINT\_FOREIGN**
```
'foreign'
```
Foreign constraint type
* `string` **CONSTRAINT\_PRIMARY**
```
'primary'
```
Primary constraint type
* `string` **CONSTRAINT\_UNIQUE**
```
'unique'
```
Unique constraint type
* `string` **INDEX\_FULLTEXT**
```
'fulltext'
```
Fulltext index type
* `string` **INDEX\_INDEX**
```
'index'
```
Index - index type
* `int` **LENGTH\_LONG**
```
4294967295
```
Column length when using a `long` column type
* `int` **LENGTH\_MEDIUM**
```
16777215
```
Column length when using a `medium` column type
* `int` **LENGTH\_TINY**
```
255
```
Column length when using a `tiny` column type
* `string` **TYPE\_BIGINTEGER**
```
'biginteger'
```
Big Integer column type
* `string` **TYPE\_BINARY**
```
'binary'
```
Binary column type
* `string` **TYPE\_BINARY\_UUID**
```
'binaryuuid'
```
Binary UUID column type
* `string` **TYPE\_BOOLEAN**
```
'boolean'
```
Boolean column type
* `string` **TYPE\_CHAR**
```
'char'
```
Char column type
* `string` **TYPE\_DATE**
```
'date'
```
Date column type
* `string` **TYPE\_DATETIME**
```
'datetime'
```
Datetime column type
* `string` **TYPE\_DATETIME\_FRACTIONAL**
```
'datetimefractional'
```
Datetime with fractional seconds column type
* `string` **TYPE\_DECIMAL**
```
'decimal'
```
Decimal column type
* `string` **TYPE\_FLOAT**
```
'float'
```
Float column type
* `string` **TYPE\_INTEGER**
```
'integer'
```
Integer column type
* `string` **TYPE\_JSON**
```
'json'
```
JSON column type
* `string` **TYPE\_SMALLINTEGER**
```
'smallinteger'
```
Small Integer column type
* `string` **TYPE\_STRING**
```
'string'
```
String column type
* `string` **TYPE\_TEXT**
```
'text'
```
Text column type
* `string` **TYPE\_TIME**
```
'time'
```
Time column type
* `string` **TYPE\_TIMESTAMP**
```
'timestamp'
```
Timestamp column type
* `string` **TYPE\_TIMESTAMP\_FRACTIONAL**
```
'timestampfractional'
```
Timestamp with fractional seconds column type
* `string` **TYPE\_TIMESTAMP\_TIMEZONE**
```
'timestamptimezone'
```
Timestamp with time zone column type
* `string` **TYPE\_TINYINTEGER**
```
'tinyinteger'
```
Tiny Integer column type
* `string` **TYPE\_UUID**
```
'uuid'
```
UUID column type
Property Summary
----------------
* [$\_columnExtras](#%24_columnExtras) protected static `array<string, array<string, mixed>>` Additional type specific properties.
* [$\_columnKeys](#%24_columnKeys) protected static `array<string, mixed>` The valid keys that can be used in a column definition.
* [$\_columns](#%24_columns) protected `array<string, array>` Columns in the table.
* [$\_constraints](#%24_constraints) protected `array<string, array<string, mixed>>` Constraints in the table.
* [$\_indexKeys](#%24_indexKeys) protected static `array<string, mixed>` The valid keys that can be used in an index definition.
* [$\_indexes](#%24_indexes) protected `array<string, array>` Indexes in the table.
* [$\_options](#%24_options) protected `array<string, mixed>` Options for the table.
* [$\_table](#%24_table) protected `string` The name of the table
* [$\_temporary](#%24_temporary) protected `bool` Whether the table is temporary
* [$\_typeMap](#%24_typeMap) protected `array<string, string>` A map with columns to types
* [$\_validConstraintTypes](#%24_validConstraintTypes) protected static `array<string>` Names of the valid constraint types.
* [$\_validForeignKeyActions](#%24_validForeignKeyActions) protected static `array<string>` Names of the valid foreign key actions.
* [$\_validIndexTypes](#%24_validIndexTypes) protected static `array<string>` Names of the valid index types.
* [$columnLengths](#%24columnLengths) public static `array<string, int>` Valid column length that can be used with text type columns
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array of the table schema.
* ##### [\_checkForeignKey()](#_checkForeignKey()) protected
Helper method to check/validate foreign keys.
* ##### [addColumn()](#addColumn()) public
Add a column to the table.
* ##### [addConstraint()](#addConstraint()) public
Add a constraint.
* ##### [addConstraintSql()](#addConstraintSql()) public
Generate the SQL statements to add the constraints to the table
* ##### [addIndex()](#addIndex()) public
Add an index.
* ##### [baseColumnType()](#baseColumnType()) public
Returns the base type name for the provided column. This represent the database type a more complex class is based upon.
* ##### [columns()](#columns()) public
Get the column names in the table.
* ##### [constraints()](#constraints()) public
Get the names of all the constraints in the table.
* ##### [createSql()](#createSql()) public
Generate the SQL to create the Table.
* ##### [defaultValues()](#defaultValues()) public
Get a hash of columns and their default values.
* ##### [dropConstraint()](#dropConstraint()) public
Remove a constraint.
* ##### [dropConstraintSql()](#dropConstraintSql()) public
Generate the SQL statements to drop the constraints to the table
* ##### [dropSql()](#dropSql()) public
Generate the SQL to drop a table.
* ##### [getColumn()](#getColumn()) public
Get column data in the table.
* ##### [getColumnType()](#getColumnType()) public
Returns column type or null if a column does not exist.
* ##### [getConstraint()](#getConstraint()) public
Read information about a constraint based on name.
* ##### [getIndex()](#getIndex()) public
Read information about an index based on name.
* ##### [getOptions()](#getOptions()) public
Gets the options for a table.
* ##### [getPrimaryKey()](#getPrimaryKey()) public
Get the column(s) used for the primary key.
* ##### [hasAutoincrement()](#hasAutoincrement()) public
Check whether a table has an autoIncrement column defined.
* ##### [hasColumn()](#hasColumn()) public
Returns true if a column exists in the schema.
* ##### [indexes()](#indexes()) public
Get the names of all the indexes in the table.
* ##### [isNullable()](#isNullable()) public
Check whether a field is nullable
* ##### [isTemporary()](#isTemporary()) public
Gets whether the table is temporary in the database.
* ##### [name()](#name()) public
Get the name of the table.
* ##### [primaryKey()](#primaryKey()) public deprecated
Get the column(s) used for the primary key.
* ##### [removeColumn()](#removeColumn()) public
Remove a column from the table schema.
* ##### [setColumnType()](#setColumnType()) public
Sets the type of a column.
* ##### [setOptions()](#setOptions()) public
Sets the options for a table.
* ##### [setTemporary()](#setTemporary()) public
Sets whether the table is temporary in the database.
* ##### [truncateSql()](#truncateSql()) public
Generate the SQL statements to truncate a table
* ##### [typeMap()](#typeMap()) public
Returns an array where the keys are the column names in the schema and the values the database type they have.
Method Detail
-------------
### \_\_construct() public
```
__construct(string $table, array<string, array|string> $columns = [])
```
Constructor.
#### Parameters
`string` $table The table name.
`array<string, array|string>` $columns optional The list of columns for the schema.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array of the table schema.
#### Returns
`array<string, mixed>`
### \_checkForeignKey() protected
```
_checkForeignKey(array<string, mixed> $attrs): array<string, mixed>
```
Helper method to check/validate foreign keys.
#### Parameters
`array<string, mixed>` $attrs Attributes to set.
#### Returns
`array<string, mixed>`
#### Throws
`Cake\Database\Exception\DatabaseException`
When foreign key definition is not valid. ### addColumn() public
```
addColumn(string $name, array<string, mixed>|string $attrs): $this
```
Add a column to the table.
### Attributes
Columns can have several attributes:
* `type` The type of the column. This should be one of CakePHP's abstract types.
* `length` The length of the column.
* `precision` The number of decimal places to store for float and decimal types.
* `default` The default value of the column.
* `null` Whether the column can hold nulls.
* `fixed` Whether the column is a fixed length column. This is only present/valid with string columns.
* `unsigned` Whether the column is an unsigned column. This is only present/valid for integer, decimal, float columns.
In addition to the above keys, the following keys are implemented in some database dialects, but not all:
* `comment` The comment for the column.
#### Parameters
`string` $name `array<string, mixed>|string` $attrs #### Returns
`$this`
### addConstraint() public
```
addConstraint(string $name, array<string, mixed>|string $attrs): $this
```
Add a constraint.
Used to add constraints to a table. For example primary keys, unique keys and foreign keys.
### Attributes
* `type` The type of constraint being added.
* `columns` The columns in the index.
* `references` The table, column a foreign key references.
* `update` The behavior on update. Options are 'restrict', 'setNull', 'cascade', 'noAction'.
* `delete` The behavior on delete. Options are 'restrict', 'setNull', 'cascade', 'noAction'.
The default for 'update' & 'delete' is 'cascade'.
#### Parameters
`string` $name `array<string, mixed>|string` $attrs #### Returns
`$this`
### addConstraintSql() public
```
addConstraintSql(Cake\Database\Connection $connection): array
```
Generate the SQL statements to add the constraints to the table
#### Parameters
`Cake\Database\Connection` $connection #### Returns
`array`
### addIndex() public
```
addIndex(string $name, array<string, mixed>|string $attrs): $this
```
Add an index.
Used to add indexes, and full text indexes in platforms that support them.
### Attributes
* `type` The type of index being added.
* `columns` The columns in the index.
#### Parameters
`string` $name `array<string, mixed>|string` $attrs #### Returns
`$this`
### baseColumnType() public
```
baseColumnType(string $column): string|null
```
Returns the base type name for the provided column. This represent the database type a more complex class is based upon.
#### Parameters
`string` $column #### Returns
`string|null`
### columns() public
```
columns(): array<string>
```
Get the column names in the table.
#### Returns
`array<string>`
### constraints() public
```
constraints(): array<string>
```
Get the names of all the constraints in the table.
#### Returns
`array<string>`
### createSql() public
```
createSql(Cake\Database\Connection $connection): array
```
Generate the SQL to create the Table.
Uses the connection to access the schema dialect to generate platform specific SQL.
#### Parameters
`Cake\Database\Connection` $connection #### Returns
`array`
### defaultValues() public
```
defaultValues(): array<string, mixed>
```
Get a hash of columns and their default values.
#### Returns
`array<string, mixed>`
### dropConstraint() public
```
dropConstraint(string $name): $this
```
Remove a constraint.
#### Parameters
`string` $name #### Returns
`$this`
### dropConstraintSql() public
```
dropConstraintSql(Cake\Database\Connection $connection): array
```
Generate the SQL statements to drop the constraints to the table
#### Parameters
`Cake\Database\Connection` $connection #### Returns
`array`
### dropSql() public
```
dropSql(Cake\Database\Connection $connection): array
```
Generate the SQL to drop a table.
Uses the connection to access the schema dialect to generate platform specific SQL.
#### Parameters
`Cake\Database\Connection` $connection #### Returns
`array`
### getColumn() public
```
getColumn(string $name): array<string, mixed>|null
```
Get column data in the table.
#### Parameters
`string` $name #### Returns
`array<string, mixed>|null`
### getColumnType() public
```
getColumnType(string $name): string|null
```
Returns column type or null if a column does not exist.
#### Parameters
`string` $name #### Returns
`string|null`
### getConstraint() public
```
getConstraint(string $name): array<string, mixed>|null
```
Read information about a constraint based on name.
#### Parameters
`string` $name #### Returns
`array<string, mixed>|null`
### getIndex() public
```
getIndex(string $name): array<string, mixed>|null
```
Read information about an index based on name.
#### Parameters
`string` $name #### Returns
`array<string, mixed>|null`
### getOptions() public
```
getOptions(): array<string, mixed>
```
Gets the options for a table.
Table options allow you to set platform specific table level options. For example the engine type in MySQL.
#### Returns
`array<string, mixed>`
### getPrimaryKey() public
```
getPrimaryKey(): array<string>
```
Get the column(s) used for the primary key.
#### Returns
`array<string>`
### hasAutoincrement() public
```
hasAutoincrement(): bool
```
Check whether a table has an autoIncrement column defined.
#### Returns
`bool`
### hasColumn() public
```
hasColumn(string $name): bool
```
Returns true if a column exists in the schema.
#### Parameters
`string` $name #### Returns
`bool`
### indexes() public
```
indexes(): array<string>
```
Get the names of all the indexes in the table.
#### Returns
`array<string>`
### isNullable() public
```
isNullable(string $name): bool
```
Check whether a field is nullable
Missing columns are nullable.
#### Parameters
`string` $name #### Returns
`bool`
### isTemporary() public
```
isTemporary(): bool
```
Gets whether the table is temporary in the database.
#### Returns
`bool`
### name() public
```
name(): string
```
Get the name of the table.
#### Returns
`string`
### primaryKey() public
```
primaryKey(): array
```
Get the column(s) used for the primary key.
#### Returns
`array`
### removeColumn() public
```
removeColumn(string $name): $this
```
Remove a column from the table schema.
If the column is not defined in the table, no error will be raised.
#### Parameters
`string` $name #### Returns
`$this`
### setColumnType() public
```
setColumnType(string $name, string $type): $this
```
Sets the type of a column.
#### Parameters
`string` $name `string` $type #### Returns
`$this`
### setOptions() public
```
setOptions(array<string, mixed> $options): $this
```
Sets the options for a table.
Table options allow you to set platform specific table level options. For example the engine type in MySQL.
#### Parameters
`array<string, mixed>` $options #### Returns
`$this`
### setTemporary() public
```
setTemporary(bool $temporary): $this
```
Sets whether the table is temporary in the database.
#### Parameters
`bool` $temporary #### Returns
`$this`
### truncateSql() public
```
truncateSql(Cake\Database\Connection $connection): array
```
Generate the SQL statements to truncate a table
#### Parameters
`Cake\Database\Connection` $connection #### Returns
`array`
### typeMap() public
```
typeMap(): array<string, string>
```
Returns an array where the keys are the column names in the schema and the values the database type they have.
#### Returns
`array<string, string>`
Property Detail
---------------
### $\_columnExtras protected static
Additional type specific properties.
#### Type
`array<string, array<string, mixed>>`
### $\_columnKeys protected static
The valid keys that can be used in a column definition.
#### Type
`array<string, mixed>`
### $\_columns protected
Columns in the table.
#### Type
`array<string, array>`
### $\_constraints protected
Constraints in the table.
#### Type
`array<string, array<string, mixed>>`
### $\_indexKeys protected static
The valid keys that can be used in an index definition.
#### Type
`array<string, mixed>`
### $\_indexes protected
Indexes in the table.
#### Type
`array<string, array>`
### $\_options protected
Options for the table.
#### Type
`array<string, mixed>`
### $\_table protected
The name of the table
#### Type
`string`
### $\_temporary protected
Whether the table is temporary
#### Type
`bool`
### $\_typeMap protected
A map with columns to types
#### Type
`array<string, string>`
### $\_validConstraintTypes protected static
Names of the valid constraint types.
#### Type
`array<string>`
### $\_validForeignKeyActions protected static
Names of the valid foreign key actions.
#### Type
`array<string>`
### $\_validIndexTypes protected static
Names of the valid index types.
#### Type
`array<string>`
### $columnLengths public static
Valid column length that can be used with text type columns
#### Type
`array<string, int>`
cakephp Class MiddlewareDispatcher Class MiddlewareDispatcher
===========================
Dispatches a request capturing the response for integration testing purposes into the Cake\Http stack.
**Namespace:** [Cake\TestSuite](namespace-cake.testsuite)
Property Summary
----------------
* [$app](#%24app) protected `Cake\Core\HttpApplicationInterface` The application that is being dispatched.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_createRequest()](#_createRequest()) protected
Create a PSR7 request from the request spec.
* ##### [execute()](#execute()) public
Run a request and get the response.
* ##### [resolveRoute()](#resolveRoute()) protected
Convert a URL array into a string URL via routing.
* ##### [resolveUrl()](#resolveUrl()) public
Resolve the provided URL into a string.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Core\HttpApplicationInterface $app)
```
Constructor
#### Parameters
`Cake\Core\HttpApplicationInterface` $app The test case to run.
### \_createRequest() protected
```
_createRequest(array<string, mixed> $spec): Cake\Http\ServerRequest
```
Create a PSR7 request from the request spec.
#### Parameters
`array<string, mixed>` $spec The request spec.
#### Returns
`Cake\Http\ServerRequest`
### execute() public
```
execute(array<string, mixed> $requestSpec): Psr\Http\Message\ResponseInterface
```
Run a request and get the response.
#### Parameters
`array<string, mixed>` $requestSpec The request spec to execute.
#### Returns
`Psr\Http\Message\ResponseInterface`
#### Throws
`LogicException`
### resolveRoute() protected
```
resolveRoute(array $url): string
```
Convert a URL array into a string URL via routing.
#### Parameters
`array` $url The url to resolve
#### Returns
`string`
### resolveUrl() public
```
resolveUrl(array|string $url): string
```
Resolve the provided URL into a string.
#### Parameters
`array|string` $url The URL array/string to resolve.
#### Returns
`string`
Property Detail
---------------
### $app protected
The application that is being dispatched.
#### Type
`Cake\Core\HttpApplicationInterface`
| programming_docs |
cakephp Class MailContains Class MailContains
===================
MailContains
**Namespace:** [Cake\TestSuite\Constraint\Email](namespace-cake.testsuite.constraint.email)
Property Summary
----------------
* [$at](#%24at) protected `int|null`
* [$type](#%24type) protected `string|null` Mail type to check contents of
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [getAssertedMessages()](#getAssertedMessages()) protected
Returns the type-dependent strings of all messages respects $this->at
* ##### [getMessages()](#getMessages()) public
Gets the email or emails to check
* ##### [getTypeMethod()](#getTypeMethod()) protected
* ##### [matches()](#matches()) public
Checks constraint
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message string
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(int|null $at = null): void
```
Constructor
#### Parameters
`int|null` $at optional At
#### Returns
`void`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### getAssertedMessages() protected
```
getAssertedMessages(): string
```
Returns the type-dependent strings of all messages respects $this->at
#### Returns
`string`
### getMessages() public
```
getMessages(): arrayCake\Mailer\Message>
```
Gets the email or emails to check
#### Returns
`arrayCake\Mailer\Message>`
### getTypeMethod() protected
```
getTypeMethod(): string
```
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks constraint
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Constraint check
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message string
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $at protected
#### Type
`int|null`
### $type protected
Mail type to check contents of
#### Type
`string|null`
cakephp Class InvalidArgumentException Class InvalidArgumentException
===============================
Exception raised when cache keys are invalid.
**Namespace:** [Cake\Cache](namespace-cake.cache)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Namespace Association Namespace Association
=====================
### Namespaces
* [Cake\ORM\Association\Loader](namespace-cake.orm.association.loader)
### Classes
* ##### [BelongsTo](class-cake.orm.association.belongsto)
Represents an 1 - N relationship where the source side of the relation is related to only one record in the target table.
* ##### [BelongsToMany](class-cake.orm.association.belongstomany)
Represents an M - N relationship where there exists a junction - or join - table that contains the association fields between the source and the target table.
* ##### [DependentDeleteHelper](class-cake.orm.association.dependentdeletehelper)
Helper class for cascading deletes in associations.
* ##### [HasMany](class-cake.orm.association.hasmany)
Represents an N - 1 relationship where the target side of the relationship will have one or multiple records per each one in the source side.
* ##### [HasOne](class-cake.orm.association.hasone)
Represents an 1 - 1 relationship where the source side of the relation is related to only one record in the target table and vice versa.
cakephp Class CaseStatementExpression Class CaseStatementExpression
==============================
Represents a SQL case statement with a fluid API
**Namespace:** [Cake\Database\Expression](namespace-cake.database.expression)
Property Summary
----------------
* [$\_typeMap](#%24_typeMap) public @property `Cake\Database\TypeMap` The type map to use when using an array of conditions for the `WHEN` value.
* [$else](#%24else) protected `Cake\Database\ExpressionInterface|object|scalar|null` The else part result value.
* [$elseType](#%24elseType) protected `string|null` The else part result type.
* [$isSimpleVariant](#%24isSimpleVariant) protected `bool` Whether this is a simple case expression.
* [$returnType](#%24returnType) protected `string|null` The return type.
* [$validClauseNames](#%24validClauseNames) protected `array<string>` The names of the clauses that are valid for use with the `clause()` method.
* [$value](#%24value) protected `Cake\Database\ExpressionInterface|object|scalar|null` The case value.
* [$valueType](#%24valueType) protected `string|null` The case value type.
* [$when](#%24when) protected `arrayCake\Database\Expression\WhenThenExpression>` The `WHEN ... THEN ...` expressions.
* [$whenBuffer](#%24whenBuffer) protected `array|null` Buffer that holds values and types for use with `then()`.
Method Summary
--------------
* ##### [\_\_clone()](#__clone()) public
Clones the inner expression objects.
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_castToExpression()](#_castToExpression()) protected
Conditionally converts the passed value to an ExpressionInterface object if the type class implements the ExpressionTypeInterface. Otherwise, returns the value unmodified.
* ##### [\_requiresToExpressionCasting()](#_requiresToExpressionCasting()) protected
Returns an array with the types that require values to be casted to expressions, out of the list of type names passed as parameter.
* ##### [clause()](#clause()) public
Returns the available data for the given clause.
* ##### [compileNullableValue()](#compileNullableValue()) protected
Compiles a nullable value to SQL.
* ##### [else()](#else()) public
Sets the `ELSE` result value.
* ##### [getDefaultTypes()](#getDefaultTypes()) public
Gets default types of current type map.
* ##### [getReturnType()](#getReturnType()) public
Returns the abstract type that this expression will return.
* ##### [getTypeMap()](#getTypeMap()) public
Returns the existing type map.
* ##### [inferType()](#inferType()) protected
Infers the abstract type for the given value.
* ##### [setDefaultTypes()](#setDefaultTypes()) public
Overwrite the default type mappings for fields in the implementing object.
* ##### [setReturnType()](#setReturnType()) public
Sets the abstract type that this expression will return.
* ##### [setTypeMap()](#setTypeMap()) public
Creates a new TypeMap if $typeMap is an array, otherwise exchanges it for the given one.
* ##### [sql()](#sql()) public
Converts the Node into a SQL string fragment.
* ##### [then()](#then()) public
Sets the `THEN` result value for the last `WHEN ... THEN ...` statement that was opened using `when()`.
* ##### [traverse()](#traverse()) public
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
* ##### [when()](#when()) public
Sets the `WHEN` value for a `WHEN ... THEN ...` expression, or a self-contained expression that holds both the value for `WHEN` and the value for `THEN`.
Method Detail
-------------
### \_\_clone() public
```
__clone(): void
```
Clones the inner expression objects.
#### Returns
`void`
### \_\_construct() public
```
__construct(Cake\Database\ExpressionInterface|object|scalar|null $value = null, string|null $type = null)
```
Constructor.
When a value is set, the syntax generated is `CASE case_value WHEN when_value ... END` (simple case), where the `when_value`'s are compared against the `case_value`.
When no value is set, the syntax generated is `CASE WHEN when_conditions ... END` (searched case), where the conditions hold the comparisons.
Note that `null` is a valid case value, and thus should only be passed if you actually want to create the simple case expression variant!
#### Parameters
`Cake\Database\ExpressionInterface|object|scalar|null` $value optional The case value.
`string|null` $type optional The case value type. If no type is provided, the type will be tried to be inferred from the value.
### \_castToExpression() protected
```
_castToExpression(mixed $value, string|null $type = null): mixed
```
Conditionally converts the passed value to an ExpressionInterface object if the type class implements the ExpressionTypeInterface. Otherwise, returns the value unmodified.
#### Parameters
`mixed` $value The value to convert to ExpressionInterface
`string|null` $type optional The type name
#### Returns
`mixed`
### \_requiresToExpressionCasting() protected
```
_requiresToExpressionCasting(array $types): array
```
Returns an array with the types that require values to be casted to expressions, out of the list of type names passed as parameter.
#### Parameters
`array` $types List of type names
#### Returns
`array`
### clause() public
```
clause(string $clause): Cake\Database\ExpressionInterface|object|arrayCake\Database\Expression\WhenThenExpression>|scalar|null
```
Returns the available data for the given clause.
### Available clauses
The following clause names are available:
* `value`: The case value for a `CASE case_value WHEN ...` expression.
* `when`: An array of `WHEN ... THEN ...` expressions.
* `else`: The `ELSE` result value.
#### Parameters
`string` $clause The name of the clause to obtain.
#### Returns
`Cake\Database\ExpressionInterface|object|arrayCake\Database\Expression\WhenThenExpression>|scalar|null`
#### Throws
`InvalidArgumentException`
In case the given clause name is invalid. ### compileNullableValue() protected
```
compileNullableValue(Cake\Database\ValueBinder $binder, Cake\Database\ExpressionInterface|object|scalar|null $value, string|null $type = null): string
```
Compiles a nullable value to SQL.
#### Parameters
`Cake\Database\ValueBinder` $binder The value binder to use.
`Cake\Database\ExpressionInterface|object|scalar|null` $value The value to compile.
`string|null` $type optional The value type.
#### Returns
`string`
### else() public
```
else(Cake\Database\ExpressionInterface|object|scalar|null $result, string|null $type = null): $this
```
Sets the `ELSE` result value.
#### Parameters
`Cake\Database\ExpressionInterface|object|scalar|null` $result The result value.
`string|null` $type optional The result type. If no type is provided, the type will be tried to be inferred from the value.
#### Returns
`$this`
#### Throws
`LogicException`
In case a closing `then()` call is required before calling this method.
`InvalidArgumentException`
In case the `$result` argument is neither a scalar value, nor an object, an instance of `\Cake\Database\ExpressionInterface`, or `null`. ### getDefaultTypes() public
```
getDefaultTypes(): array<int|string, string>
```
Gets default types of current type map.
#### Returns
`array<int|string, string>`
### getReturnType() public
```
getReturnType(): string
```
Returns the abstract type that this expression will return.
If no type has been explicitly set via `setReturnType()`, this method will try to obtain the type from the result types of the `then()` and `else()`calls. All types must be identical in order for this to work, otherwise the type will default to `string`.
#### Returns
`string`
#### See Also
CaseStatementExpression::then() ### getTypeMap() public
```
getTypeMap(): Cake\Database\TypeMap
```
Returns the existing type map.
#### Returns
`Cake\Database\TypeMap`
### inferType() protected
```
inferType(mixed $value): string|null
```
Infers the abstract type for the given value.
#### Parameters
`mixed` $value The value for which to infer the type.
#### Returns
`string|null`
### setDefaultTypes() public
```
setDefaultTypes(array<int|string, string> $types): $this
```
Overwrite the default type mappings for fields in the implementing object.
This method is useful if you need to set type mappings that are shared across multiple functions/expressions in a query.
To add a default without overwriting existing ones use `getTypeMap()->addDefaults()`
#### Parameters
`array<int|string, string>` $types The array of types to set.
#### Returns
`$this`
#### See Also
\Cake\Database\TypeMap::setDefaults() ### setReturnType() public
```
setReturnType(string $type): $this
```
Sets the abstract type that this expression will return.
If no type is being explicitly set via this method, then the `getReturnType()` method will try to infer the type from the result types of the `then()` and `else()`calls.
#### Parameters
`string` $type The type name to use.
#### Returns
`$this`
### setTypeMap() public
```
setTypeMap(Cake\Database\TypeMap|array $typeMap): $this
```
Creates a new TypeMap if $typeMap is an array, otherwise exchanges it for the given one.
#### Parameters
`Cake\Database\TypeMap|array` $typeMap Creates a TypeMap if array, otherwise sets the given TypeMap
#### Returns
`$this`
### sql() public
```
sql(Cake\Database\ValueBinder $binder): string
```
Converts the Node into a SQL string fragment.
#### Parameters
`Cake\Database\ValueBinder` $binder #### Returns
`string`
### then() public
```
then(Cake\Database\ExpressionInterface|object|scalar|null $result, string|null $type = null): $this
```
Sets the `THEN` result value for the last `WHEN ... THEN ...` statement that was opened using `when()`.
### Order based syntax
This method can only be invoked in case `when()` was previously used with a value other than a closure or an instance of `\Cake\Database\Expression\WhenThenExpression`:
```
$case
->when(['Table.column' => true])
->then('Yes')
->when(['Table.column' => false])
->then('No')
->else('Maybe');
```
The following would all fail with an exception:
```
$case
->when(['Table.column' => true])
->when(['Table.column' => false])
// ...
```
```
$case
->when(['Table.column' => true])
->else('Maybe')
// ...
```
```
$case
->then('Yes')
// ...
```
```
$case
->when(['Table.column' => true])
->then('Yes')
->then('No')
// ...
```
#### Parameters
`Cake\Database\ExpressionInterface|object|scalar|null` $result The result value.
`string|null` $type optional The result type. If no type is provided, the type will be tried to be inferred from the value.
#### Returns
`$this`
#### Throws
`LogicException`
In case `when()` wasn't previously called with a value other than a closure or an instance of `\Cake\Database\Expression\WhenThenExpression`. ### traverse() public
```
traverse(Closure $callback): $this
```
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
#### Parameters
`Closure` $callback #### Returns
`$this`
### when() public
```
when(Cake\Database\ExpressionInterfaceClosure|object|array|scalar $when, array<string, string>|string|null $type = null): $this
```
Sets the `WHEN` value for a `WHEN ... THEN ...` expression, or a self-contained expression that holds both the value for `WHEN` and the value for `THEN`.
### Order based syntax
When passing a value other than a self-contained `\Cake\Database\Expression\WhenThenExpression`, instance, the `WHEN ... THEN ...` statement must be closed off with a call to `then()` before invoking `when()` again or `else()`:
```
$queryExpression
->case($query->identifier('Table.column'))
->when(true)
->then('Yes')
->when(false)
->then('No')
->else('Maybe');
```
### Self-contained expressions
When passing an instance of `\Cake\Database\Expression\WhenThenExpression`, being it directly, or via a callable, then there is no need to close using `then()` on this object, instead the statement will be closed on the `\Cake\Database\Expression\WhenThenExpression` object using `\Cake\Database\Expression\WhenThenExpression::then()`.
Callables will receive an instance of `\Cake\Database\Expression\WhenThenExpression`, and must return one, being it the same object, or a custom one:
```
$queryExpression
->case()
->when(function (\Cake\Database\Expression\WhenThenExpression $whenThen) {
return $whenThen
->when(['Table.column' => true])
->then('Yes');
})
->when(function (\Cake\Database\Expression\WhenThenExpression $whenThen) {
return $whenThen
->when(['Table.column' => false])
->then('No');
})
->else('Maybe');
```
### Type handling
The types provided via the `$type` argument will be merged with the type map set for this expression. When using callables for `$when`, the `\Cake\Database\Expression\WhenThenExpression` instance received by the callables will inherit that type map, however the types passed here will *not* be merged in case of using callables, instead the types must be passed in `\Cake\Database\Expression\WhenThenExpression::when()`:
```
$queryExpression
->case()
->when(function (\Cake\Database\Expression\WhenThenExpression $whenThen) {
return $whenThen
->when(['unmapped_column' => true], ['unmapped_column' => 'bool'])
->then('Yes');
})
->when(function (\Cake\Database\Expression\WhenThenExpression $whenThen) {
return $whenThen
->when(['unmapped_column' => false], ['unmapped_column' => 'bool'])
->then('No');
})
->else('Maybe');
```
### User data safety
When passing user data, be aware that allowing a user defined array to be passed, is a potential SQL injection vulnerability, as it allows for raw SQL to slip in!
The following is *unsafe* usage that must be avoided:
```
$case
->when($userData)
```
A safe variant for the above would be to define a single type for the value:
```
$case
->when($userData, 'integer')
```
This way an exception would be triggered when an array is passed for the value, thus preventing raw SQL from slipping in, and all other types of values would be forced to be bound as an integer.
Another way to safely pass user data is when using a conditions array, and passing user data only on the value side of the array entries, which will cause them to be bound:
```
$case
->when([
'Table.column' => $userData,
])
```
Lastly, data can also be bound manually:
```
$query
->select([
'val' => $query->newExpr()
->case()
->when($query->newExpr(':userData'))
->then(123)
])
->bind(':userData', $userData, 'integer')
```
#### Parameters
`Cake\Database\ExpressionInterfaceClosure|object|array|scalar` $when The `WHEN` value. When using an array of conditions, it must be compatible with `\Cake\Database\Query::where()`. Note that this argument is *not* completely safe for use with user data, as a user supplied array would allow for raw SQL to slip in! If you plan to use user data, either pass a single type for the `$type` argument (which forces the `$when` value to be a non-array, and then always binds the data), use a conditions array where the user data is only passed on the value side of the array entries, or custom bindings!
`array<string, string>|string|null` $type optional The when value type. Either an associative array when using array style conditions, or else a string. If no type is provided, the type will be tried to be inferred from the value.
#### Returns
`$this`
#### Throws
`LogicException`
In case this a closing `then()` call is required before calling this method.
`LogicException`
In case the callable doesn't return an instance of `\Cake\Database\Expression\WhenThenExpression`. Property Detail
---------------
### $\_typeMap public @property
The type map to use when using an array of conditions for the `WHEN` value.
#### Type
`Cake\Database\TypeMap`
### $else protected
The else part result value.
#### Type
`Cake\Database\ExpressionInterface|object|scalar|null`
### $elseType protected
The else part result type.
#### Type
`string|null`
### $isSimpleVariant protected
Whether this is a simple case expression.
#### Type
`bool`
### $returnType protected
The return type.
#### Type
`string|null`
### $validClauseNames protected
The names of the clauses that are valid for use with the `clause()` method.
#### Type
`array<string>`
### $value protected
The case value.
#### Type
`Cake\Database\ExpressionInterface|object|scalar|null`
### $valueType protected
The case value type.
#### Type
`string|null`
### $when protected
The `WHEN ... THEN ...` expressions.
#### Type
`arrayCake\Database\Expression\WhenThenExpression>`
### $whenBuffer protected
Buffer that holds values and types for use with `then()`.
#### Type
`array|null`
| programming_docs |
cakephp Class TimestampBehavior Class TimestampBehavior
========================
Class TimestampBehavior
**Namespace:** [Cake\ORM\Behavior](namespace-cake.orm.behavior)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config
* [$\_reflectionCache](#%24_reflectionCache) protected static `array<string, array>` Reflection method cache for behaviors.
* [$\_table](#%24_table) protected `Cake\ORM\Table` Table instance.
* [$\_ts](#%24_ts) protected `Cake\I18n\FrozenTime|null` Current timestamp
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_reflectionCache()](#_reflectionCache()) protected
Gets the methods implemented by this behavior
* ##### [\_resolveMethodAliases()](#_resolveMethodAliases()) protected
Removes aliased methods that would otherwise be duplicated by userland configuration.
* ##### [\_updateField()](#_updateField()) protected
Update a field, if it hasn't been updated already
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getTable()](#getTable()) public deprecated
Get the table instance this behavior is bound to.
* ##### [handleEvent()](#handleEvent()) public
There is only one event handler, it can be configured to be called for any event
* ##### [implementedEvents()](#implementedEvents()) public
implementedEvents
* ##### [implementedFinders()](#implementedFinders()) public
implementedFinders
* ##### [implementedMethods()](#implementedMethods()) public
implementedMethods
* ##### [initialize()](#initialize()) public
Initialize hook
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [table()](#table()) public
Get the table instance this behavior is bound to.
* ##### [timestamp()](#timestamp()) public
Get or set the timestamp to be used
* ##### [touch()](#touch()) public
Touch an entity
* ##### [verifyConfig()](#verifyConfig()) public
verifyConfig
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\ORM\Table $table, array<string, mixed> $config = [])
```
Constructor
Merges config with the default and store in the config property
#### Parameters
`Cake\ORM\Table` $table The table this behavior is attached to.
`array<string, mixed>` $config optional The config for this behavior.
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_reflectionCache() protected
```
_reflectionCache(): array
```
Gets the methods implemented by this behavior
Uses the implementedEvents() method to exclude callback methods. Methods starting with `_` will be ignored, as will methods declared on Cake\ORM\Behavior
#### Returns
`array`
#### Throws
`ReflectionException`
### \_resolveMethodAliases() protected
```
_resolveMethodAliases(string $key, array<string, mixed> $defaults, array<string, mixed> $config): array
```
Removes aliased methods that would otherwise be duplicated by userland configuration.
#### Parameters
`string` $key The key to filter.
`array<string, mixed>` $defaults The default method mappings.
`array<string, mixed>` $config The customized method mappings.
#### Returns
`array`
### \_updateField() protected
```
_updateField(Cake\Datasource\EntityInterface $entity, string $field, bool $refreshTimestamp): void
```
Update a field, if it hasn't been updated already
#### Parameters
`Cake\Datasource\EntityInterface` $entity Entity instance.
`string` $field Field name
`bool` $refreshTimestamp Whether to refresh timestamp.
#### Returns
`void`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getTable() public
```
getTable(): Cake\ORM\Table
```
Get the table instance this behavior is bound to.
#### Returns
`Cake\ORM\Table`
### handleEvent() public
```
handleEvent(Cake\Event\EventInterface $event, Cake\Datasource\EntityInterface $entity): true
```
There is only one event handler, it can be configured to be called for any event
#### Parameters
`Cake\Event\EventInterface` $event Event instance.
`Cake\Datasource\EntityInterface` $entity Entity instance.
#### Returns
`true`
#### Throws
`UnexpectedValueException`
if a field's when value is misdefined
`UnexpectedValueException`
When the value for an event is not 'always', 'new' or 'existing' ### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
implementedEvents
The implemented events of this behavior depend on configuration
#### Returns
`array<string, mixed>`
### implementedFinders() public
```
implementedFinders(): array
```
implementedFinders
Provides an alias->methodname map of which finders a behavior implements. Example:
```
[
'this' => 'findThis',
'alias' => 'findMethodName'
]
```
With the above example, a call to `$table->find('this')` will call `$behavior->findThis()` and a call to `$table->find('alias')` will call `$behavior->findMethodName()`
It is recommended, though not required, to define implementedFinders in the config property of child classes such that it is not necessary to use reflections to derive the available method list. See core behaviors for examples
#### Returns
`array`
#### Throws
`ReflectionException`
### implementedMethods() public
```
implementedMethods(): array
```
implementedMethods
Provides an alias->methodname map of which methods a behavior implements. Example:
```
[
'method' => 'method',
'aliasedMethod' => 'somethingElse'
]
```
With the above example, a call to `$table->method()` will call `$behavior->method()` and a call to `$table->aliasedMethod()` will call `$behavior->somethingElse()`
It is recommended, though not required, to define implementedFinders in the config property of child classes such that it is not necessary to use reflections to derive the available method list. See core behaviors for examples
#### Returns
`array`
#### Throws
`ReflectionException`
### initialize() public
```
initialize(array<string, mixed> $config): void
```
Initialize hook
If events are specified - do *not* merge them with existing events, overwrite the events to listen on
#### Parameters
`array<string, mixed>` $config The config for this behavior.
#### Returns
`void`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### table() public
```
table(): Cake\ORM\Table
```
Get the table instance this behavior is bound to.
#### Returns
`Cake\ORM\Table`
### timestamp() public
```
timestamp(DateTimeInterface|null $ts = null, bool $refreshTimestamp = false): Cake\I18n\FrozenTime
```
Get or set the timestamp to be used
Set the timestamp to the given DateTime object, or if not passed a new DateTime object If an explicit date time is passed, the config option `refreshTimestamp` is automatically set to false.
#### Parameters
`DateTimeInterface|null` $ts optional Timestamp
`bool` $refreshTimestamp optional If true timestamp is refreshed.
#### Returns
`Cake\I18n\FrozenTime`
### touch() public
```
touch(Cake\Datasource\EntityInterface $entity, string $eventName = 'Model.beforeSave'): bool
```
Touch an entity
Bumps timestamp fields for an entity. For any fields configured to be updated "always" or "existing", update the timestamp value. This method will overwrite any pre-existing value.
#### Parameters
`Cake\Datasource\EntityInterface` $entity Entity instance.
`string` $eventName optional Event name.
#### Returns
`bool`
### verifyConfig() public
```
verifyConfig(): void
```
verifyConfig
Checks that implemented keys contain values pointing at callable.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if config are invalid Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config
These are merged with user-provided config when the behavior is used.
events - an event-name keyed array of which fields to update, and when, for a given event possible values for when a field will be updated are "always", "new" or "existing", to set the field value always, only when a new record or only when an existing record.
refreshTimestamp - if true (the default) the timestamp used will be the current time when the code is executed, to set to an explicit date time value - set refreshTimetamp to false and call setTimestamp() on the behavior class before use.
#### Type
`array<string, mixed>`
### $\_reflectionCache protected static
Reflection method cache for behaviors.
Stores the reflected method + finder methods per class. This prevents reflecting the same class multiple times in a single process.
#### Type
`array<string, array>`
### $\_table protected
Table instance.
#### Type
`Cake\ORM\Table`
### $\_ts protected
Current timestamp
#### Type
`Cake\I18n\FrozenTime|null`
cakephp Class TableHelper Class TableHelper
==================
Create a visually pleasing ASCII art table from 2 dimensional array data.
**Namespace:** [Cake\Shell\Helper](namespace-cake.shell.helper)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this helper.
* [$\_io](#%24_io) protected `Cake\Console\ConsoleIo` ConsoleIo instance.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_addStyle()](#_addStyle()) protected
Add style tags
* ##### [\_calculateWidths()](#_calculateWidths()) protected
Calculate the column widths
* ##### [\_cellWidth()](#_cellWidth()) protected
Get the width of a cell exclusive of style tags.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_render()](#_render()) protected
Output a row.
* ##### [\_rowSeparator()](#_rowSeparator()) protected
Output a row separator.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [output()](#output()) public
Output a table.
* ##### [setConfig()](#setConfig()) public
Sets the config.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Console\ConsoleIo $io, array<string, mixed> $config = [])
```
Constructor.
#### Parameters
`Cake\Console\ConsoleIo` $io The ConsoleIo instance to use.
`array<string, mixed>` $config optional The settings for this helper.
### \_addStyle() protected
```
_addStyle(string $text, string $style): string
```
Add style tags
#### Parameters
`string` $text The text to be surrounded
`string` $style The style to be applied
#### Returns
`string`
### \_calculateWidths() protected
```
_calculateWidths(array $rows): array<int>
```
Calculate the column widths
#### Parameters
`array` $rows The rows on which the columns width will be calculated on.
#### Returns
`array<int>`
### \_cellWidth() protected
```
_cellWidth(string $text): int
```
Get the width of a cell exclusive of style tags.
#### Parameters
`string` $text The text to calculate a width for.
#### Returns
`int`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_render() protected
```
_render(array $row, array<int> $widths, array<string, mixed> $options = []): void
```
Output a row.
#### Parameters
`array` $row The row to output.
`array<int>` $widths The widths of each column to output.
`array<string, mixed>` $options optional Options to be passed.
#### Returns
`void`
### \_rowSeparator() protected
```
_rowSeparator(array<int> $widths): void
```
Output a row separator.
#### Parameters
`array<int>` $widths The widths of each column to output.
#### Returns
`void`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### output() public
```
output(array $args): void
```
Output a table.
Data will be output based on the order of the values in the array. The keys will not be used to align data.
#### Parameters
`array` $args The data to render out.
#### Returns
`void`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this helper.
#### Type
`array<string, mixed>`
### $\_io protected
ConsoleIo instance.
#### Type
`Cake\Console\ConsoleIo`
| programming_docs |
cakephp Namespace Network Namespace Network
=================
### Namespaces
* [Cake\Network\Exception](namespace-cake.network.exception)
### Classes
* ##### [Socket](class-cake.network.socket)
CakePHP network socket connection class.
cakephp Class StatusCodeBase Class StatusCodeBase
=====================
StatusCodeBase
**Abstract**
**Namespace:** [Cake\TestSuite\Constraint\Response](namespace-cake.testsuite.constraint.response)
Property Summary
----------------
* [$code](#%24code) protected `array<int, int>|int`
* [$response](#%24response) protected `Psr\Http\Message\ResponseInterface`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_getBodyAsString()](#_getBodyAsString()) protected
Get the response body as string
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Overwrites the descriptions so we can remove the automatic "expected" message
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Check assertion
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [statusCodeBetween()](#statusCodeBetween()) protected
Helper for checking status codes
* ##### [toString()](#toString()) public
Returns a string representation of the object.
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(Psr\Http\Message\ResponseInterface|null $response)
```
Constructor
#### Parameters
`Psr\Http\Message\ResponseInterface|null` $response Response
### \_getBodyAsString() protected
```
_getBodyAsString(): string
```
Get the response body as string
#### Returns
`string`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Overwrites the descriptions so we can remove the automatic "expected" message
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other Value
#### Returns
`string`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Check assertion
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Array of min/max status codes, or a single code
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### statusCodeBetween() protected
```
statusCodeBetween(int $min, int $max): bool
```
Helper for checking status codes
#### Parameters
`int` $min Min status code (inclusive)
`int` $max Max status code (inclusive)
#### Returns
`bool`
### toString() public
```
toString(): string
```
Returns a string representation of the object.
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $code protected
#### Type
`array<int, int>|int`
### $response protected
#### Type
`Psr\Http\Message\ResponseInterface`
cakephp Class ViewBlock Class ViewBlock
================
ViewBlock implements the concept of Blocks or Slots in the View layer. Slots or blocks are combined with extending views and layouts to afford slots of content that are present in a layout or parent view, but are defined by the child view or elements used in the view.
**Namespace:** [Cake\View](namespace-cake.view)
Constants
---------
* `string` **APPEND**
```
'append'
```
Append content
* `string` **OVERRIDE**
```
'override'
```
Override content
* `string` **PREPEND**
```
'prepend'
```
Prepend content
Property Summary
----------------
* [$\_active](#%24_active) protected `array<string>` The active blocks being captured.
* [$\_blocks](#%24_blocks) protected `array<string>` Block content. An array of blocks indexed by name.
* [$\_discardActiveBufferOnEnd](#%24_discardActiveBufferOnEnd) protected `bool` Should the currently captured content be discarded on ViewBlock::end()
Method Summary
--------------
* ##### [active()](#active()) public
Get the name of the currently open block.
* ##### [concat()](#concat()) public
Concat content to an existing or new block. Concating to a new block will create the block.
* ##### [end()](#end()) public
End a capturing block. The compliment to ViewBlock::start()
* ##### [exists()](#exists()) public
Check if a block exists
* ##### [get()](#get()) public
Get the content for a block.
* ##### [keys()](#keys()) public
Get the names of all the existing blocks.
* ##### [set()](#set()) public
Set the content for a block. This will overwrite any existing content.
* ##### [start()](#start()) public
Start capturing output for a 'block'
* ##### [unclosed()](#unclosed()) public
Get the unclosed/active blocks. Key is name, value is mode.
Method Detail
-------------
### active() public
```
active(): string|null
```
Get the name of the currently open block.
#### Returns
`string|null`
### concat() public
```
concat(string $name, mixed $value = null, string $mode = ViewBlock::APPEND): void
```
Concat content to an existing or new block. Concating to a new block will create the block.
Calling concat() without a value will create a new capturing block that needs to be finished with View::end(). The content of the new capturing context will be added to the existing block context.
#### Parameters
`string` $name Name of the block
`mixed` $value optional The content for the block. Value will be type cast to string.
`string` $mode optional If ViewBlock::APPEND content will be appended to existing content. If ViewBlock::PREPEND it will be prepended.
#### Returns
`void`
### end() public
```
end(): void
```
End a capturing block. The compliment to ViewBlock::start()
#### Returns
`void`
#### See Also
\Cake\View\ViewBlock::start() ### exists() public
```
exists(string $name): bool
```
Check if a block exists
#### Parameters
`string` $name Name of the block
#### Returns
`bool`
### get() public
```
get(string $name, string $default = ''): string
```
Get the content for a block.
#### Parameters
`string` $name Name of the block
`string` $default optional Default string
#### Returns
`string`
### keys() public
```
keys(): array<string>
```
Get the names of all the existing blocks.
#### Returns
`array<string>`
### set() public
```
set(string $name, mixed $value): void
```
Set the content for a block. This will overwrite any existing content.
#### Parameters
`string` $name Name of the block
`mixed` $value The content for the block. Value will be type cast to string.
#### Returns
`void`
### start() public
```
start(string $name, string $mode = ViewBlock::OVERRIDE): void
```
Start capturing output for a 'block'
Blocks allow you to create slots or blocks of dynamic content in the layout. view files can implement some or all of a layout's slots.
You can end capturing blocks using View::end(). Blocks can be output using View::get();
#### Parameters
`string` $name The name of the block to capture for.
`string` $mode optional If ViewBlock::OVERRIDE existing content will be overridden by new content. If ViewBlock::APPEND content will be appended to existing content. If ViewBlock::PREPEND it will be prepended.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
When starting a block twice ### unclosed() public
```
unclosed(): array<string>
```
Get the unclosed/active blocks. Key is name, value is mode.
#### Returns
`array<string>`
Property Detail
---------------
### $\_active protected
The active blocks being captured.
#### Type
`array<string>`
### $\_blocks protected
Block content. An array of blocks indexed by name.
#### Type
`array<string>`
### $\_discardActiveBufferOnEnd protected
Should the currently captured content be discarded on ViewBlock::end()
#### Type
`bool`
cakephp Class MissingTaskException Class MissingTaskException
===========================
Used when a Task cannot be found.
**Namespace:** [Cake\Console\Exception](namespace-cake.console.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Class MissingShellException Class MissingShellException
============================
Used when a shell cannot be found.
**Namespace:** [Cake\Console\Exception](namespace-cake.console.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
| programming_docs |
cakephp Namespace Log Namespace Log
=============
### Classes
* ##### [LoggedQuery](class-cake.database.log.loggedquery)
Contains a query string, the params used to executed it, time taken to do it and the number of rows found or affected by its execution.
* ##### [LoggingStatement](class-cake.database.log.loggingstatement)
Statement decorator used to
* ##### [QueryLogger](class-cake.database.log.querylogger)
This class is a bridge used to write LoggedQuery objects into a real log. by default this class use the built-in CakePHP Log class to accomplish this
cakephp Class IntegrationTestCase Class IntegrationTestCase
==========================
A test case class intended to make integration tests of your controllers easier.
This test class provides a number of helper methods and features that make dispatching requests and checking their responses simpler. It favours full integration tests over mock objects as you can test more of your code easily and avoid some of the maintenance pitfalls that mock objects create.
**Abstract**
**Namespace:** [Cake\TestSuite](namespace-cake.testsuite)
**Deprecated:** 3.7.0 Will be removed in 5.0.0. Use {@link \Cake\TestSuite\IntegrationTestTrait} instead.
Property Summary
----------------
* [$\_appArgs](#%24_appArgs) protected `array|null` The customized application constructor arguments.
* [$\_appClass](#%24_appClass) protected `string|null` The customized application class name.
* [$\_configure](#%24_configure) protected `array` Configure values to restore at end of test.
* [$\_controller](#%24_controller) protected `Cake\Controller\Controller|null` The controller used in the last request.
* [$\_cookie](#%24_cookie) protected `array` Cookie data to use in the next request.
* [$\_cookieEncryptionKey](#%24_cookieEncryptionKey) protected `string|null`
* [$\_csrfKeyName](#%24_csrfKeyName) protected `string` The name that will be used when retrieving the csrf token.
* [$\_csrfToken](#%24_csrfToken) protected `bool` Boolean flag for whether the request should have a CSRF token added.
* [$\_exception](#%24_exception) protected `Throwable|null` The exception being thrown if the case.
* [$\_flashMessages](#%24_flashMessages) protected `array` Stored flash messages before render
* [$\_layoutName](#%24_layoutName) protected `string` The last rendered layout
* [$\_request](#%24_request) protected `array` The data used to build the next request.
* [$\_requestSession](#%24_requestSession) protected `Cake\Http\Session` The session instance from the last request
* [$\_response](#%24_response) protected `Psr\Http\Message\ResponseInterface|null` The response for the most recent request.
* [$\_retainFlashMessages](#%24_retainFlashMessages) protected `bool` Boolean flag for whether the request should re-store flash messages
* [$\_securityToken](#%24_securityToken) protected `bool` Boolean flag for whether the request should have a SecurityComponent token added.
* [$\_session](#%24_session) protected `array` Session data to use in the next request.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$\_unlockedFields](#%24_unlockedFields) protected `array<string>` List of fields that are excluded from field validation.
* [$\_validCiphers](#%24_validCiphers) protected `array<string>` Valid cipher names for encrypted cookies.
* [$\_viewName](#%24_viewName) protected `string` The last rendered view
* [$autoFixtures](#%24autoFixtures) public deprecated `bool` By default, all fixtures attached to this class will be truncated and reloaded after each test. Set this to false to handle manually
* [$backupGlobals](#%24backupGlobals) protected `?bool`
* [$backupGlobalsBlacklist](#%24backupGlobalsBlacklist) protected deprecated `string[]`
* [$backupGlobalsExcludeList](#%24backupGlobalsExcludeList) protected `string[]`
* [$backupStaticAttributes](#%24backupStaticAttributes) protected `bool`
* [$backupStaticAttributesBlacklist](#%24backupStaticAttributesBlacklist) protected deprecated `array<string, array<int, string>>`
* [$backupStaticAttributesExcludeList](#%24backupStaticAttributesExcludeList) protected `array<string, array<int, string>>`
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
* [$dropTables](#%24dropTables) public deprecated `bool` Control table create/drops on each test method.
* [$fixtureManager](#%24fixtureManager) public static `Cake\TestSuite\Fixture\FixtureManager|null` The class responsible for managing the creation, loading and removing of fixtures
* [$fixtureStrategy](#%24fixtureStrategy) protected `Cake\TestSuite\Fixture\FixtureStrategyInterface|null`
* [$fixtures](#%24fixtures) protected `array<string>` Fixtures used by this test case.
* [$preserveGlobalState](#%24preserveGlobalState) protected `bool`
* [$providedTests](#%24providedTests) protected `list<ExecutionOrderDependency>`
* [$runTestInSeparateProcess](#%24runTestInSeparateProcess) protected `bool`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
* ##### [\_addTokens()](#_addTokens()) protected
Add the CSRF and Security Component tokens if necessary.
* ##### [\_assertAttributes()](#_assertAttributes()) protected
Check the attributes as part of an assertTags() check.
* ##### [\_buildRequest()](#_buildRequest()) protected
Creates a request object with the configured options and parameters.
* ##### [\_castToString()](#_castToString()) protected
Recursively casts all data to string as that is how data would be POSTed in the real world
* ##### [\_checkCipher()](#_checkCipher()) protected
Helper method for validating encryption cipher names.
* ##### [\_decode()](#_decode()) protected
Decodes and decrypts a single value.
* ##### [\_decrypt()](#_decrypt()) protected
Decrypts $value using public $type method in Security class
* ##### [\_encrypt()](#_encrypt()) protected
Encrypts $value using public $type method in Security class
* ##### [\_explode()](#_explode()) protected
Explode method to return array from string set in CookieComponent::\_implode() Maintains reading backwards compatibility with 1.x CookieComponent::\_implode().
* ##### [\_getBodyAsString()](#_getBodyAsString()) protected
Get the response body as string
* ##### [\_getCookieEncryptionKey()](#_getCookieEncryptionKey()) protected
Returns the encryption key to be used.
* ##### [\_getTableClassName()](#_getTableClassName()) protected
Gets the class name for the table.
* ##### [\_handleError()](#_handleError()) protected
Attempts to render an error response for a given exception.
* ##### [\_implode()](#_implode()) protected
Implode method to keep keys are multidimensional arrays
* ##### [\_makeDispatcher()](#_makeDispatcher()) protected
Get the correct dispatcher instance.
* ##### [\_normalizePath()](#_normalizePath()) protected
Normalize a path for comparison.
* ##### [\_sendRequest()](#_sendRequest()) protected
Creates and send the request into a Dispatcher instance.
* ##### [\_url()](#_url()) protected
Creates a valid request url and parameter array more like Request::\_url()
* ##### [addFixture()](#addFixture()) protected
Adds a fixture to this test case.
* ##### [addToAssertionCount()](#addToAssertionCount()) public
* ##### [addWarning()](#addWarning()) public
* ##### [any()](#any()) public static
Returns a matcher that matches when the method is executed zero or more times.
* ##### [anything()](#anything()) public static
* ##### [arrayHasKey()](#arrayHasKey()) public static
* ##### [assertArrayHasKey()](#assertArrayHasKey()) public static
Asserts that an array has a specified key.
* ##### [assertArrayNotHasKey()](#assertArrayNotHasKey()) public static
Asserts that an array does not have a specified key.
* ##### [assertClassHasAttribute()](#assertClassHasAttribute()) public static
Asserts that a class has a specified attribute.
* ##### [assertClassHasStaticAttribute()](#assertClassHasStaticAttribute()) public static
Asserts that a class has a specified static attribute.
* ##### [assertClassNotHasAttribute()](#assertClassNotHasAttribute()) public static
Asserts that a class does not have a specified attribute.
* ##### [assertClassNotHasStaticAttribute()](#assertClassNotHasStaticAttribute()) public static
Asserts that a class does not have a specified static attribute.
* ##### [assertContains()](#assertContains()) public static
Asserts that a haystack contains a needle.
* ##### [assertContainsEquals()](#assertContainsEquals()) public static
* ##### [assertContainsOnly()](#assertContainsOnly()) public static
Asserts that a haystack contains only values of a given type.
* ##### [assertContainsOnlyInstancesOf()](#assertContainsOnlyInstancesOf()) public static
Asserts that a haystack contains only instances of a given class name.
* ##### [assertContentType()](#assertContentType()) public
Asserts content type
* ##### [assertCookie()](#assertCookie()) public
Asserts cookie values
* ##### [assertCookieEncrypted()](#assertCookieEncrypted()) public
Asserts cookie values which are encrypted by the CookieComponent.
* ##### [assertCookieNotSet()](#assertCookieNotSet()) public
Asserts a cookie has not been set in the response
* ##### [assertCount()](#assertCount()) public static
Asserts the number of elements of an array, Countable or Traversable.
* ##### [assertDirectoryDoesNotExist()](#assertDirectoryDoesNotExist()) public static
Asserts that a directory does not exist.
* ##### [assertDirectoryExists()](#assertDirectoryExists()) public static
Asserts that a directory exists.
* ##### [assertDirectoryIsNotReadable()](#assertDirectoryIsNotReadable()) public static
Asserts that a directory exists and is not readable.
* ##### [assertDirectoryIsNotWritable()](#assertDirectoryIsNotWritable()) public static
Asserts that a directory exists and is not writable.
* ##### [assertDirectoryIsReadable()](#assertDirectoryIsReadable()) public static
Asserts that a directory exists and is readable.
* ##### [assertDirectoryIsWritable()](#assertDirectoryIsWritable()) public static
Asserts that a directory exists and is writable.
* ##### [assertDirectoryNotExists()](#assertDirectoryNotExists()) public static deprecated
Asserts that a directory does not exist.
* ##### [assertDirectoryNotIsReadable()](#assertDirectoryNotIsReadable()) public static deprecated
Asserts that a directory exists and is not readable.
* ##### [assertDirectoryNotIsWritable()](#assertDirectoryNotIsWritable()) public static deprecated
Asserts that a directory exists and is not writable.
* ##### [assertDoesNotMatchRegularExpression()](#assertDoesNotMatchRegularExpression()) public static
Asserts that a string does not match a given regular expression.
* ##### [assertEmpty()](#assertEmpty()) public static
Asserts that a variable is empty.
* ##### [assertEqualXMLStructure()](#assertEqualXMLStructure()) public static deprecated
Asserts that a hierarchy of DOMElements matches.
* ##### [assertEquals()](#assertEquals()) public static
Asserts that two variables are equal.
* ##### [assertEqualsCanonicalizing()](#assertEqualsCanonicalizing()) public static
Asserts that two variables are equal (canonicalizing).
* ##### [assertEqualsIgnoringCase()](#assertEqualsIgnoringCase()) public static
Asserts that two variables are equal (ignoring case).
* ##### [assertEqualsSql()](#assertEqualsSql()) public
Assert that a string matches SQL with db-specific characters like quotes removed.
* ##### [assertEqualsWithDelta()](#assertEqualsWithDelta()) public static
Asserts that two variables are equal (with delta).
* ##### [assertEventFired()](#assertEventFired()) public
Asserts that a global event was fired. You must track events in your event manager for this assertion to work
* ##### [assertEventFiredWith()](#assertEventFiredWith()) public
Asserts an event was fired with data
* ##### [assertFalse()](#assertFalse()) public static
Asserts that a condition is false.
* ##### [assertFileDoesNotExist()](#assertFileDoesNotExist()) public static
Asserts that a file does not exist.
* ##### [assertFileEquals()](#assertFileEquals()) public static
Asserts that the contents of one file is equal to the contents of another file.
* ##### [assertFileEqualsCanonicalizing()](#assertFileEqualsCanonicalizing()) public static
Asserts that the contents of one file is equal to the contents of another file (canonicalizing).
* ##### [assertFileEqualsIgnoringCase()](#assertFileEqualsIgnoringCase()) public static
Asserts that the contents of one file is equal to the contents of another file (ignoring case).
* ##### [assertFileExists()](#assertFileExists()) public static
Asserts that a file exists.
* ##### [assertFileIsNotReadable()](#assertFileIsNotReadable()) public static
Asserts that a file exists and is not readable.
* ##### [assertFileIsNotWritable()](#assertFileIsNotWritable()) public static
Asserts that a file exists and is not writable.
* ##### [assertFileIsReadable()](#assertFileIsReadable()) public static
Asserts that a file exists and is readable.
* ##### [assertFileIsWritable()](#assertFileIsWritable()) public static
Asserts that a file exists and is writable.
* ##### [assertFileNotEquals()](#assertFileNotEquals()) public static
Asserts that the contents of one file is not equal to the contents of another file.
* ##### [assertFileNotEqualsCanonicalizing()](#assertFileNotEqualsCanonicalizing()) public static
Asserts that the contents of one file is not equal to the contents of another file (canonicalizing).
* ##### [assertFileNotEqualsIgnoringCase()](#assertFileNotEqualsIgnoringCase()) public static
Asserts that the contents of one file is not equal to the contents of another file (ignoring case).
* ##### [assertFileNotExists()](#assertFileNotExists()) public static deprecated
Asserts that a file does not exist.
* ##### [assertFileNotIsReadable()](#assertFileNotIsReadable()) public static deprecated
Asserts that a file exists and is not readable.
* ##### [assertFileNotIsWritable()](#assertFileNotIsWritable()) public static deprecated
Asserts that a file exists and is not writable.
* ##### [assertFileResponse()](#assertFileResponse()) public
Asserts that a file with the given name was sent in the response
* ##### [assertFinite()](#assertFinite()) public static
Asserts that a variable is finite.
* ##### [assertFlashElement()](#assertFlashElement()) public
Asserts a flash element was set
* ##### [assertFlashElementAt()](#assertFlashElementAt()) public
Asserts a flash element was set at a certain index
* ##### [assertFlashMessage()](#assertFlashMessage()) public
Asserts a flash message was set
* ##### [assertFlashMessageAt()](#assertFlashMessageAt()) public
Asserts a flash message was set at a certain index
* ##### [assertGreaterThan()](#assertGreaterThan()) public static
Asserts that a value is greater than another value.
* ##### [assertGreaterThanOrEqual()](#assertGreaterThanOrEqual()) public static
Asserts that a value is greater than or equal to another value.
* ##### [assertHeader()](#assertHeader()) public
Asserts response headers
* ##### [assertHeaderContains()](#assertHeaderContains()) public
Asserts response header contains a string
* ##### [assertHeaderNotContains()](#assertHeaderNotContains()) public
Asserts response header does not contain a string
* ##### [assertHtml()](#assertHtml()) public
Asserts HTML tags.
* ##### [assertInfinite()](#assertInfinite()) public static
Asserts that a variable is infinite.
* ##### [assertInstanceOf()](#assertInstanceOf()) public static
Asserts that a variable is of a given type.
* ##### [assertIsArray()](#assertIsArray()) public static
Asserts that a variable is of type array.
* ##### [assertIsBool()](#assertIsBool()) public static
Asserts that a variable is of type bool.
* ##### [assertIsCallable()](#assertIsCallable()) public static
Asserts that a variable is of type callable.
* ##### [assertIsClosedResource()](#assertIsClosedResource()) public static
Asserts that a variable is of type resource and is closed.
* ##### [assertIsFloat()](#assertIsFloat()) public static
Asserts that a variable is of type float.
* ##### [assertIsInt()](#assertIsInt()) public static
Asserts that a variable is of type int.
* ##### [assertIsIterable()](#assertIsIterable()) public static
Asserts that a variable is of type iterable.
* ##### [assertIsNotArray()](#assertIsNotArray()) public static
Asserts that a variable is not of type array.
* ##### [assertIsNotBool()](#assertIsNotBool()) public static
Asserts that a variable is not of type bool.
* ##### [assertIsNotCallable()](#assertIsNotCallable()) public static
Asserts that a variable is not of type callable.
* ##### [assertIsNotClosedResource()](#assertIsNotClosedResource()) public static
Asserts that a variable is not of type resource.
* ##### [assertIsNotFloat()](#assertIsNotFloat()) public static
Asserts that a variable is not of type float.
* ##### [assertIsNotInt()](#assertIsNotInt()) public static
Asserts that a variable is not of type int.
* ##### [assertIsNotIterable()](#assertIsNotIterable()) public static
Asserts that a variable is not of type iterable.
* ##### [assertIsNotNumeric()](#assertIsNotNumeric()) public static
Asserts that a variable is not of type numeric.
* ##### [assertIsNotObject()](#assertIsNotObject()) public static
Asserts that a variable is not of type object.
* ##### [assertIsNotReadable()](#assertIsNotReadable()) public static
Asserts that a file/dir exists and is not readable.
* ##### [assertIsNotResource()](#assertIsNotResource()) public static
Asserts that a variable is not of type resource.
* ##### [assertIsNotScalar()](#assertIsNotScalar()) public static
Asserts that a variable is not of type scalar.
* ##### [assertIsNotString()](#assertIsNotString()) public static
Asserts that a variable is not of type string.
* ##### [assertIsNotWritable()](#assertIsNotWritable()) public static
Asserts that a file/dir exists and is not writable.
* ##### [assertIsNumeric()](#assertIsNumeric()) public static
Asserts that a variable is of type numeric.
* ##### [assertIsObject()](#assertIsObject()) public static
Asserts that a variable is of type object.
* ##### [assertIsReadable()](#assertIsReadable()) public static
Asserts that a file/dir is readable.
* ##### [assertIsResource()](#assertIsResource()) public static
Asserts that a variable is of type resource.
* ##### [assertIsScalar()](#assertIsScalar()) public static
Asserts that a variable is of type scalar.
* ##### [assertIsString()](#assertIsString()) public static
Asserts that a variable is of type string.
* ##### [assertIsWritable()](#assertIsWritable()) public static
Asserts that a file/dir exists and is writable.
* ##### [assertJson()](#assertJson()) public static
Asserts that a string is a valid JSON string.
* ##### [assertJsonFileEqualsJsonFile()](#assertJsonFileEqualsJsonFile()) public static
Asserts that two JSON files are equal.
* ##### [assertJsonFileNotEqualsJsonFile()](#assertJsonFileNotEqualsJsonFile()) public static
Asserts that two JSON files are not equal.
* ##### [assertJsonStringEqualsJsonFile()](#assertJsonStringEqualsJsonFile()) public static
Asserts that the generated JSON encoded object and the content of the given file are equal.
* ##### [assertJsonStringEqualsJsonString()](#assertJsonStringEqualsJsonString()) public static
Asserts that two given JSON encoded objects or arrays are equal.
* ##### [assertJsonStringNotEqualsJsonFile()](#assertJsonStringNotEqualsJsonFile()) public static
Asserts that the generated JSON encoded object and the content of the given file are not equal.
* ##### [assertJsonStringNotEqualsJsonString()](#assertJsonStringNotEqualsJsonString()) public static
Asserts that two given JSON encoded objects or arrays are not equal.
* ##### [assertLayout()](#assertLayout()) public
Asserts that the search string was in the layout name.
* ##### [assertLessThan()](#assertLessThan()) public static
Asserts that a value is smaller than another value.
* ##### [assertLessThanOrEqual()](#assertLessThanOrEqual()) public static
Asserts that a value is smaller than or equal to another value.
* ##### [assertMatchesRegularExpression()](#assertMatchesRegularExpression()) public static
Asserts that a string matches a given regular expression.
* ##### [assertNan()](#assertNan()) public static
Asserts that a variable is nan.
* ##### [assertNoRedirect()](#assertNoRedirect()) public
Asserts that the Location header is not set.
* ##### [assertNotContains()](#assertNotContains()) public static
Asserts that a haystack does not contain a needle.
* ##### [assertNotContainsEquals()](#assertNotContainsEquals()) public static
* ##### [assertNotContainsOnly()](#assertNotContainsOnly()) public static
Asserts that a haystack does not contain only values of a given type.
* ##### [assertNotCount()](#assertNotCount()) public static
Asserts the number of elements of an array, Countable or Traversable.
* ##### [assertNotEmpty()](#assertNotEmpty()) public static
Asserts that a variable is not empty.
* ##### [assertNotEquals()](#assertNotEquals()) public static
Asserts that two variables are not equal.
* ##### [assertNotEqualsCanonicalizing()](#assertNotEqualsCanonicalizing()) public static
Asserts that two variables are not equal (canonicalizing).
* ##### [assertNotEqualsIgnoringCase()](#assertNotEqualsIgnoringCase()) public static
Asserts that two variables are not equal (ignoring case).
* ##### [assertNotEqualsWithDelta()](#assertNotEqualsWithDelta()) public static
Asserts that two variables are not equal (with delta).
* ##### [assertNotFalse()](#assertNotFalse()) public static
Asserts that a condition is not false.
* ##### [assertNotInstanceOf()](#assertNotInstanceOf()) public static
Asserts that a variable is not of a given type.
* ##### [assertNotIsReadable()](#assertNotIsReadable()) public static deprecated
Asserts that a file/dir exists and is not readable.
* ##### [assertNotIsWritable()](#assertNotIsWritable()) public static deprecated
Asserts that a file/dir exists and is not writable.
* ##### [assertNotNull()](#assertNotNull()) public static
Asserts that a variable is not null.
* ##### [assertNotRegExp()](#assertNotRegExp()) public static deprecated
Asserts that a string does not match a given regular expression.
* ##### [assertNotSame()](#assertNotSame()) public static
Asserts that two variables do not have the same type and value. Used on objects, it asserts that two variables do not reference the same object.
* ##### [assertNotSameSize()](#assertNotSameSize()) public static
Assert that the size of two arrays (or `Countable` or `Traversable` objects) is not the same.
* ##### [assertNotTrue()](#assertNotTrue()) public static
Asserts that a condition is not true.
* ##### [assertNotWithinRange()](#assertNotWithinRange()) protected static
Compatibility function to test if a value is not between an acceptable range.
* ##### [assertNull()](#assertNull()) public static
Asserts that a variable is null.
* ##### [assertObjectEquals()](#assertObjectEquals()) public static
* ##### [assertObjectHasAttribute()](#assertObjectHasAttribute()) public static
Asserts that an object has a specified attribute.
* ##### [assertObjectNotHasAttribute()](#assertObjectNotHasAttribute()) public static
Asserts that an object does not have a specified attribute.
* ##### [assertPathEquals()](#assertPathEquals()) protected static
Compatibility function to test paths.
* ##### [assertPostConditions()](#assertPostConditions()) protected
Performs assertions shared by all tests of a test case.
* ##### [assertPreConditions()](#assertPreConditions()) protected
Performs assertions shared by all tests of a test case.
* ##### [assertRedirect()](#assertRedirect()) public
Asserts that the Location header is correct. Comparison is made against a full URL.
* ##### [assertRedirectContains()](#assertRedirectContains()) public
Asserts that the Location header contains a substring
* ##### [assertRedirectEquals()](#assertRedirectEquals()) public
Asserts that the Location header is correct. Comparison is made against exactly the URL provided.
* ##### [assertRedirectNotContains()](#assertRedirectNotContains()) public
Asserts that the Location header does not contain a substring
* ##### [assertRegExp()](#assertRegExp()) public static deprecated
Asserts that a string matches a given regular expression.
* ##### [assertRegExpSql()](#assertRegExpSql()) public
Assertion for comparing a regex pattern against a query having its identifiers quoted. It accepts queries quoted with the characters `<` and `>`. If the third parameter is set to true, it will alter the pattern to both accept quoted and unquoted queries
* ##### [assertResponseCode()](#assertResponseCode()) public
Asserts a specific response status code.
* ##### [assertResponseContains()](#assertResponseContains()) public
Asserts content exists in the response body.
* ##### [assertResponseEmpty()](#assertResponseEmpty()) public
Assert response content is empty.
* ##### [assertResponseEquals()](#assertResponseEquals()) public
Asserts content in the response body equals.
* ##### [assertResponseError()](#assertResponseError()) public
Asserts that the response status code is in the 4xx range.
* ##### [assertResponseFailure()](#assertResponseFailure()) public
Asserts that the response status code is in the 5xx range.
* ##### [assertResponseNotContains()](#assertResponseNotContains()) public
Asserts content does not exist in the response body.
* ##### [assertResponseNotEmpty()](#assertResponseNotEmpty()) public
Assert response content is not empty.
* ##### [assertResponseNotEquals()](#assertResponseNotEquals()) public
Asserts content in the response body not equals.
* ##### [assertResponseNotRegExp()](#assertResponseNotRegExp()) public
Asserts that the response body does not match a given regular expression.
* ##### [assertResponseOk()](#assertResponseOk()) public
Asserts that the response status code is in the 2xx range.
* ##### [assertResponseRegExp()](#assertResponseRegExp()) public
Asserts that the response body matches a given regular expression.
* ##### [assertResponseSuccess()](#assertResponseSuccess()) public
Asserts that the response status code is in the 2xx/3xx range.
* ##### [assertSame()](#assertSame()) public static
Asserts that two variables have the same type and value. Used on objects, it asserts that two variables reference the same object.
* ##### [assertSameSize()](#assertSameSize()) public static
Assert that the size of two arrays (or `Countable` or `Traversable` objects) is the same.
* ##### [assertSession()](#assertSession()) public
Asserts session contents
* ##### [assertSessionHasKey()](#assertSessionHasKey()) public
Asserts session key exists.
* ##### [assertSessionNotHasKey()](#assertSessionNotHasKey()) public
Asserts a session key does not exist.
* ##### [assertStringContainsString()](#assertStringContainsString()) public static
* ##### [assertStringContainsStringIgnoringCase()](#assertStringContainsStringIgnoringCase()) public static
* ##### [assertStringEndsNotWith()](#assertStringEndsNotWith()) public static
Asserts that a string ends not with a given suffix.
* ##### [assertStringEndsWith()](#assertStringEndsWith()) public static
Asserts that a string ends with a given suffix.
* ##### [assertStringEqualsFile()](#assertStringEqualsFile()) public static
Asserts that the contents of a string is equal to the contents of a file.
* ##### [assertStringEqualsFileCanonicalizing()](#assertStringEqualsFileCanonicalizing()) public static
Asserts that the contents of a string is equal to the contents of a file (canonicalizing).
* ##### [assertStringEqualsFileIgnoringCase()](#assertStringEqualsFileIgnoringCase()) public static
Asserts that the contents of a string is equal to the contents of a file (ignoring case).
* ##### [assertStringMatchesFormat()](#assertStringMatchesFormat()) public static
Asserts that a string matches a given format string.
* ##### [assertStringMatchesFormatFile()](#assertStringMatchesFormatFile()) public static
Asserts that a string matches a given format file.
* ##### [assertStringNotContainsString()](#assertStringNotContainsString()) public static
* ##### [assertStringNotContainsStringIgnoringCase()](#assertStringNotContainsStringIgnoringCase()) public static
* ##### [assertStringNotEqualsFile()](#assertStringNotEqualsFile()) public static
Asserts that the contents of a string is not equal to the contents of a file.
* ##### [assertStringNotEqualsFileCanonicalizing()](#assertStringNotEqualsFileCanonicalizing()) public static
Asserts that the contents of a string is not equal to the contents of a file (canonicalizing).
* ##### [assertStringNotEqualsFileIgnoringCase()](#assertStringNotEqualsFileIgnoringCase()) public static
Asserts that the contents of a string is not equal to the contents of a file (ignoring case).
* ##### [assertStringNotMatchesFormat()](#assertStringNotMatchesFormat()) public static
Asserts that a string does not match a given format string.
* ##### [assertStringNotMatchesFormatFile()](#assertStringNotMatchesFormatFile()) public static
Asserts that a string does not match a given format string.
* ##### [assertStringStartsNotWith()](#assertStringStartsNotWith()) public static
Asserts that a string starts not with a given prefix.
* ##### [assertStringStartsWith()](#assertStringStartsWith()) public static
Asserts that a string starts with a given prefix.
* ##### [assertTemplate()](#assertTemplate()) public
Asserts that the search string was in the template name.
* ##### [assertTextContains()](#assertTextContains()) public
Assert that a string contains another string, ignoring differences in newlines. Helpful for doing cross platform tests of blocks of text.
* ##### [assertTextEndsNotWith()](#assertTextEndsNotWith()) public
Asserts that a string ends not with a given prefix, ignoring differences in newlines. Helpful for doing cross platform tests of blocks of text.
* ##### [assertTextEndsWith()](#assertTextEndsWith()) public
Asserts that a string ends with a given prefix, ignoring differences in newlines. Helpful for doing cross platform tests of blocks of text.
* ##### [assertTextEquals()](#assertTextEquals()) public
Assert text equality, ignoring differences in newlines. Helpful for doing cross platform tests of blocks of text.
* ##### [assertTextNotContains()](#assertTextNotContains()) public
Assert that a text doesn't contain another text, ignoring differences in newlines. Helpful for doing cross platform tests of blocks of text.
* ##### [assertTextNotEquals()](#assertTextNotEquals()) public
Assert text equality, ignoring differences in newlines. Helpful for doing cross platform tests of blocks of text.
* ##### [assertTextStartsNotWith()](#assertTextStartsNotWith()) public
Asserts that a string starts not with a given prefix, ignoring differences in newlines. Helpful for doing cross platform tests of blocks of text.
* ##### [assertTextStartsWith()](#assertTextStartsWith()) public
Asserts that a string starts with a given prefix, ignoring differences in newlines. Helpful for doing cross platform tests of blocks of text.
* ##### [assertThat()](#assertThat()) public static
Evaluates a PHPUnit\Framework\Constraint matcher object.
* ##### [assertTrue()](#assertTrue()) public static
Asserts that a condition is true.
* ##### [assertWithinRange()](#assertWithinRange()) protected static
Compatibility function to test if a value is between an acceptable range.
* ##### [assertXmlFileEqualsXmlFile()](#assertXmlFileEqualsXmlFile()) public static
Asserts that two XML files are equal.
* ##### [assertXmlFileNotEqualsXmlFile()](#assertXmlFileNotEqualsXmlFile()) public static
Asserts that two XML files are not equal.
* ##### [assertXmlStringEqualsXmlFile()](#assertXmlStringEqualsXmlFile()) public static
Asserts that two XML documents are equal.
* ##### [assertXmlStringEqualsXmlString()](#assertXmlStringEqualsXmlString()) public static
Asserts that two XML documents are equal.
* ##### [assertXmlStringNotEqualsXmlFile()](#assertXmlStringNotEqualsXmlFile()) public static
Asserts that two XML documents are not equal.
* ##### [assertXmlStringNotEqualsXmlString()](#assertXmlStringNotEqualsXmlString()) public static
Asserts that two XML documents are not equal.
* ##### [at()](#at()) public static deprecated
Returns a matcher that matches when the method is executed at the given index.
* ##### [atLeast()](#atLeast()) public static
Returns a matcher that matches when the method is executed at least N times.
* ##### [atLeastOnce()](#atLeastOnce()) public static
Returns a matcher that matches when the method is executed at least once.
* ##### [atMost()](#atMost()) public static
Returns a matcher that matches when the method is executed at most N times.
* ##### [callback()](#callback()) public static
* ##### [classHasAttribute()](#classHasAttribute()) public static
* ##### [classHasStaticAttribute()](#classHasStaticAttribute()) public static
* ##### [cleanup()](#cleanup()) public
Clears the state used for requests.
* ##### [cleanupContainer()](#cleanupContainer()) public
Clears any mocks that were defined and cleans up application class configuration.
* ##### [clearPlugins()](#clearPlugins()) public
Clear all plugins from the global plugin collection.
* ##### [configApplication()](#configApplication()) public
Configure the application class to use in integration tests.
* ##### [configRequest()](#configRequest()) public
Configures the data for the *next* request.
* ##### [containsEqual()](#containsEqual()) public static
* ##### [containsIdentical()](#containsIdentical()) public static
* ##### [containsOnly()](#containsOnly()) public static
* ##### [containsOnlyInstancesOf()](#containsOnlyInstancesOf()) public static
* ##### [controllerSpy()](#controllerSpy()) public
Adds additional event spies to the controller/view event manager.
* ##### [cookie()](#cookie()) public
Sets a request cookie for future requests.
* ##### [cookieEncrypted()](#cookieEncrypted()) public
Sets a encrypted request cookie for future requests.
* ##### [count()](#count()) public
* ##### [countOf()](#countOf()) public static
* ##### [createApp()](#createApp()) protected
Create an application instance.
* ##### [createConfiguredMock()](#createConfiguredMock()) protected
Returns a configured mock object for the specified class.
* ##### [createMock()](#createMock()) protected
Returns a mock object for the specified class.
* ##### [createPartialMock()](#createPartialMock()) protected
Returns a partial mock object for the specified class.
* ##### [createResult()](#createResult()) protected
Creates a default TestResult object.
* ##### [createStub()](#createStub()) protected
Makes configurable stub for the specified class.
* ##### [createTestProxy()](#createTestProxy()) protected
Returns a test proxy for the specified class.
* ##### [dataName()](#dataName()) public
* ##### [delete()](#delete()) public
Performs a DELETE request using the current request data.
* ##### [deprecated()](#deprecated()) public
Helper method for check deprecation methods
* ##### [directoryExists()](#directoryExists()) public static
* ##### [disableErrorHandlerMiddleware()](#disableErrorHandlerMiddleware()) public
Disable the error handler middleware.
* ##### [doesNotPerformAssertions()](#doesNotPerformAssertions()) public
* ##### [doubledTypes()](#doubledTypes()) public
* ##### [enableCsrfToken()](#enableCsrfToken()) public
Calling this method will add a CSRF token to the request.
* ##### [enableRetainFlashMessages()](#enableRetainFlashMessages()) public
Calling this method will re-store flash messages into the test session after being removed by the FlashHelper
* ##### [enableSecurityToken()](#enableSecurityToken()) public
Calling this method will enable a SecurityComponent compatible token to be added to request data. This lets you easily test actions protected by SecurityComponent.
* ##### [equalTo()](#equalTo()) public static
* ##### [equalToCanonicalizing()](#equalToCanonicalizing()) public static
* ##### [equalToIgnoringCase()](#equalToIgnoringCase()) public static
* ##### [equalToWithDelta()](#equalToWithDelta()) public static
* ##### [exactly()](#exactly()) public static
Returns a matcher that matches when the method is executed exactly $count times.
* ##### [expectDeprecation()](#expectDeprecation()) public
* ##### [expectDeprecationMessage()](#expectDeprecationMessage()) public
* ##### [expectDeprecationMessageMatches()](#expectDeprecationMessageMatches()) public
* ##### [expectError()](#expectError()) public
* ##### [expectErrorMessage()](#expectErrorMessage()) public
* ##### [expectErrorMessageMatches()](#expectErrorMessageMatches()) public
* ##### [expectException()](#expectException()) public
* ##### [expectExceptionCode()](#expectExceptionCode()) public
* ##### [expectExceptionMessage()](#expectExceptionMessage()) public
* ##### [expectExceptionMessageMatches()](#expectExceptionMessageMatches()) public
* ##### [expectExceptionObject()](#expectExceptionObject()) public
Sets up an expectation for an exception to be raised by the code under test. Information for expected exception class, expected exception message, and expected exception code are retrieved from a given Exception object.
* ##### [expectNotToPerformAssertions()](#expectNotToPerformAssertions()) public
* ##### [expectNotice()](#expectNotice()) public
* ##### [expectNoticeMessage()](#expectNoticeMessage()) public
* ##### [expectNoticeMessageMatches()](#expectNoticeMessageMatches()) public
* ##### [expectOutputRegex()](#expectOutputRegex()) public
* ##### [expectOutputString()](#expectOutputString()) public
* ##### [expectWarning()](#expectWarning()) public
* ##### [expectWarningMessage()](#expectWarningMessage()) public
* ##### [expectWarningMessageMatches()](#expectWarningMessageMatches()) public
* ##### [extractExceptionMessage()](#extractExceptionMessage()) protected
Extract verbose message for existing exception
* ##### [extractVerboseMessage()](#extractVerboseMessage()) protected
Inspect controller to extract possible causes of the failed assertion
* ##### [fail()](#fail()) public static
Fails a test with the given message.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [fileExists()](#fileExists()) public static
* ##### [get()](#get()) public
Performs a GET request using the current request data.
* ##### [getActualOutput()](#getActualOutput()) public
* ##### [getActualOutputForAssertion()](#getActualOutputForAssertion()) public
* ##### [getCount()](#getCount()) public static
Return the current assertion count.
* ##### [getDataSetAsString()](#getDataSetAsString()) public
* ##### [getExpectedException()](#getExpectedException()) public
* ##### [getExpectedExceptionCode()](#getExpectedExceptionCode()) public
* ##### [getExpectedExceptionMessage()](#getExpectedExceptionMessage()) public
* ##### [getExpectedExceptionMessageRegExp()](#getExpectedExceptionMessageRegExp()) public
* ##### [getFixtureStrategy()](#getFixtureStrategy()) protected
Returns fixture strategy used by these tests.
* ##### [getFixtures()](#getFixtures()) public
Get the fixtures this test should use.
* ##### [getGroups()](#getGroups()) public
* ##### [getMockBuilder()](#getMockBuilder()) public
Returns a builder object to create mock objects using a fluent interface.
* ##### [getMockClass()](#getMockClass()) protected
Mocks the specified class and returns the name of the mocked class.
* ##### [getMockForAbstractClass()](#getMockForAbstractClass()) protected
Returns a mock object for the specified abstract class with all abstract methods of the class mocked. Concrete methods are not mocked by default. To mock concrete methods, use the 7th parameter ($mockedMethods).
* ##### [getMockForModel()](#getMockForModel()) public
Mock a model, maintain fixtures and table association
* ##### [getMockForTrait()](#getMockForTrait()) protected
Returns a mock object for the specified trait with all abstract methods of the trait mocked. Concrete methods to mock can be specified with the `$mockedMethods` parameter.
* ##### [getMockFromWsdl()](#getMockFromWsdl()) protected
Returns a mock object based on the given WSDL file.
* ##### [getName()](#getName()) public
* ##### [getNumAssertions()](#getNumAssertions()) public
Returns the number of assertions performed by this test.
* ##### [getObjectForTrait()](#getObjectForTrait()) protected
Returns an object for the specified trait.
* ##### [getProvidedData()](#getProvidedData()) public
Gets the data set of a TestCase.
* ##### [getResult()](#getResult()) public
* ##### [getSession()](#getSession()) protected
* ##### [getSize()](#getSize()) public
Returns the size of the test.
* ##### [getStatus()](#getStatus()) public
* ##### [getStatusMessage()](#getStatusMessage()) public
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [getTestResultObject()](#getTestResultObject()) public
* ##### [greaterThan()](#greaterThan()) public static
* ##### [greaterThanOrEqual()](#greaterThanOrEqual()) public static
* ##### [hasExpectationOnOutput()](#hasExpectationOnOutput()) public
* ##### [hasFailed()](#hasFailed()) public
* ##### [hasOutput()](#hasOutput()) public
* ##### [hasSize()](#hasSize()) public
* ##### [head()](#head()) public
Performs a HEAD request using the current request data.
* ##### [identicalTo()](#identicalTo()) public static
* ##### [iniSet()](#iniSet()) protected
This method is a wrapper for the ini\_set() function that automatically resets the modified php.ini setting to its original value after the test is run.
* ##### [isEmpty()](#isEmpty()) public static
* ##### [isFalse()](#isFalse()) public static
* ##### [isFinite()](#isFinite()) public static
* ##### [isInIsolation()](#isInIsolation()) public
* ##### [isInfinite()](#isInfinite()) public static
* ##### [isInstanceOf()](#isInstanceOf()) public static
* ##### [isJson()](#isJson()) public static
* ##### [isLarge()](#isLarge()) public
* ##### [isMedium()](#isMedium()) public
* ##### [isNan()](#isNan()) public static
* ##### [isNull()](#isNull()) public static
* ##### [isReadable()](#isReadable()) public static
* ##### [isSmall()](#isSmall()) public
* ##### [isTrue()](#isTrue()) public static
* ##### [isType()](#isType()) public static
* ##### [isWritable()](#isWritable()) public static
* ##### [lessThan()](#lessThan()) public static
* ##### [lessThanOrEqual()](#lessThanOrEqual()) public static
* ##### [loadFixtures()](#loadFixtures()) public deprecated
Chooses which fixtures to load for a given test
* ##### [loadPlugins()](#loadPlugins()) public
Load plugins into a simulated application.
* ##### [loadRoutes()](#loadRoutes()) public
Load routes for the application.
* ##### [logicalAnd()](#logicalAnd()) public static
* ##### [logicalNot()](#logicalNot()) public static
* ##### [logicalOr()](#logicalOr()) public static
* ##### [logicalXor()](#logicalXor()) public static
* ##### [markAsRisky()](#markAsRisky()) public
* ##### [markTestIncomplete()](#markTestIncomplete()) public static
Mark the test as incomplete.
* ##### [markTestSkipped()](#markTestSkipped()) public static
Mark the test as skipped.
* ##### [matches()](#matches()) public static
* ##### [matchesRegularExpression()](#matchesRegularExpression()) public static
* ##### [mockService()](#mockService()) public
Add a mocked service to the container.
* ##### [modifyContainer()](#modifyContainer()) public
Wrap the application's container with one containing mocks.
* ##### [never()](#never()) public static
Returns a matcher that matches when the method is never executed.
* ##### [objectEquals()](#objectEquals()) public static
* ##### [objectHasAttribute()](#objectHasAttribute()) public static
* ##### [onConsecutiveCalls()](#onConsecutiveCalls()) public static
* ##### [onNotSuccessfulTest()](#onNotSuccessfulTest()) protected
This method is called when a test method did not execute successfully.
* ##### [once()](#once()) public static
Returns a matcher that matches when the method is executed exactly once.
* ##### [options()](#options()) public
Performs an OPTIONS request using the current request data.
* ##### [patch()](#patch()) public
Performs a PATCH request using the current request data.
* ##### [post()](#post()) public
Performs a POST request using the current request data.
* ##### [prophesize()](#prophesize()) protected
* ##### [provides()](#provides()) public
Returns the normalized test name as class::method.
* ##### [put()](#put()) public
Performs a PUT request using the current request data.
* ##### [recordDoubledType()](#recordDoubledType()) protected
* ##### [registerComparator()](#registerComparator()) public
* ##### [registerMockObject()](#registerMockObject()) public
* ##### [removeMockService()](#removeMockService()) public
Remove a mocked service to the container.
* ##### [removePlugins()](#removePlugins()) public
Remove plugins from the global plugin collection.
* ##### [requires()](#requires()) public
Returns a list of normalized dependency names, class::method.
* ##### [resetCount()](#resetCount()) public static
Reset the assertion counter.
* ##### [returnArgument()](#returnArgument()) public static
* ##### [returnCallback()](#returnCallback()) public static
* ##### [returnSelf()](#returnSelf()) public static
Returns the current object.
* ##### [returnValue()](#returnValue()) public static
* ##### [returnValueMap()](#returnValueMap()) public static
* ##### [run()](#run()) public
Runs the test case and collects the results in a TestResult object. If no TestResult object is passed a new one will be created.
* ##### [runBare()](#runBare()) public
* ##### [runTest()](#runTest()) protected
Override to run the test and assert its state.
* ##### [session()](#session()) public
Sets session data.
* ##### [setAppNamespace()](#setAppNamespace()) public static
Set the app namespace
* ##### [setBackupGlobals()](#setBackupGlobals()) public
* ##### [setBackupStaticAttributes()](#setBackupStaticAttributes()) public
* ##### [setBeStrictAboutChangesToGlobalState()](#setBeStrictAboutChangesToGlobalState()) public
* ##### [setDependencies()](#setDependencies()) public
* ##### [setDependencyInput()](#setDependencyInput()) public
* ##### [setGroups()](#setGroups()) public
* ##### [setInIsolation()](#setInIsolation()) public
* ##### [setLocale()](#setLocale()) protected
This method is a wrapper for the setlocale() function that automatically resets the locale to its original value after the test is run.
* ##### [setName()](#setName()) public
* ##### [setOutputCallback()](#setOutputCallback()) public
* ##### [setPreserveGlobalState()](#setPreserveGlobalState()) public
* ##### [setRegisterMockObjectsFromTestArgumentsRecursively()](#setRegisterMockObjectsFromTestArgumentsRecursively()) public
* ##### [setResult()](#setResult()) public
* ##### [setRunClassInSeparateProcess()](#setRunClassInSeparateProcess()) public
* ##### [setRunTestInSeparateProcess()](#setRunTestInSeparateProcess()) public
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
* ##### [setTestResultObject()](#setTestResultObject()) public
* ##### [setUnlockedFields()](#setUnlockedFields()) public
Set list of fields that are excluded from field validation.
* ##### [setUp()](#setUp()) protected
Setup the test case, backup the static object values so they can be restored. Specifically backs up the contents of Configure and paths in App if they have not already been backed up.
* ##### [setUpBeforeClass()](#setUpBeforeClass()) public static
This method is called before the first test of this test class is run.
* ##### [setupFixtures()](#setupFixtures()) protected
Initialized and loads any use fixtures.
* ##### [skipIf()](#skipIf()) public
Overrides SimpleTestCase::skipIf to provide a boolean return value
* ##### [skipUnless()](#skipUnless()) protected
Compatibility function for skipping.
* ##### [sortId()](#sortId()) public
* ##### [stringContains()](#stringContains()) public static
* ##### [stringEndsWith()](#stringEndsWith()) public static
* ##### [stringStartsWith()](#stringStartsWith()) public static
* ##### [tearDown()](#tearDown()) protected
teardown any static object changes and restore them.
* ##### [tearDownAfterClass()](#tearDownAfterClass()) public static
This method is called after the last test of this test class is run.
* ##### [teardownFixtures()](#teardownFixtures()) protected
Unloads any use fixtures.
* ##### [throwException()](#throwException()) public static
* ##### [toString()](#toString()) public
Returns a string representation of the test case.
* ##### [useHttpServer()](#useHttpServer()) public
No-op method.
* ##### [usesDataProvider()](#usesDataProvider()) public
* ##### [viewVariable()](#viewVariable()) public
Fetches a view variable by name.
* ##### [withErrorReporting()](#withErrorReporting()) public
Helper method for tests that needs to use error\_reporting()
Method Detail
-------------
### \_\_construct() public
```
__construct(?string $name = null, array $data = [], int|string $dataName = '')
```
#### Parameters
`?string` $name optional `array` $data optional `int|string` $dataName optional ### \_addTokens() protected
```
_addTokens(string $url, array $data): array
```
Add the CSRF and Security Component tokens if necessary.
#### Parameters
`string` $url The URL the form is being submitted on.
`array` $data The request body data.
#### Returns
`array`
### \_assertAttributes() protected
```
_assertAttributes(array<string, mixed> $assertions, string $string, bool $fullDebug = false, array|string $regex = ''): string|false
```
Check the attributes as part of an assertTags() check.
#### Parameters
`array<string, mixed>` $assertions Assertions to run.
`string` $string The HTML string to check.
`bool` $fullDebug optional Whether more verbose output should be used.
`array|string` $regex optional Full regexp from `assertHtml`
#### Returns
`string|false`
### \_buildRequest() protected
```
_buildRequest(string $url, string $method, array|string $data = []): array
```
Creates a request object with the configured options and parameters.
#### Parameters
`string` $url The URL
`string` $method The HTTP method
`array|string` $data optional The request data.
#### Returns
`array`
### \_castToString() protected
```
_castToString(array $data): array
```
Recursively casts all data to string as that is how data would be POSTed in the real world
#### Parameters
`array` $data POST data
#### Returns
`array`
### \_checkCipher() protected
```
_checkCipher(string $encrypt): void
```
Helper method for validating encryption cipher names.
#### Parameters
`string` $encrypt The cipher name.
#### Returns
`void`
#### Throws
`RuntimeException`
When an invalid cipher is provided. ### \_decode() protected
```
_decode(string $value, string|false $encrypt, string|null $key): array|string
```
Decodes and decrypts a single value.
#### Parameters
`string` $value The value to decode & decrypt.
`string|false` $encrypt The encryption cipher to use.
`string|null` $key Used as the security salt if specified.
#### Returns
`array|string`
### \_decrypt() protected
```
_decrypt(array<string>|string $values, string|false $mode, string|null $key = null): array|string
```
Decrypts $value using public $type method in Security class
#### Parameters
`array<string>|string` $values Values to decrypt
`string|false` $mode Encryption mode
`string|null` $key optional Used as the security salt if specified.
#### Returns
`array|string`
### \_encrypt() protected
```
_encrypt(array|string $value, string|false $encrypt, string|null $key = null): string
```
Encrypts $value using public $type method in Security class
#### Parameters
`array|string` $value Value to encrypt
`string|false` $encrypt Encryption mode to use. False disabled encryption.
`string|null` $key optional Used as the security salt if specified.
#### Returns
`string`
### \_explode() protected
```
_explode(string $string): array|string
```
Explode method to return array from string set in CookieComponent::\_implode() Maintains reading backwards compatibility with 1.x CookieComponent::\_implode().
#### Parameters
`string` $string A string containing JSON encoded data, or a bare string.
#### Returns
`array|string`
### \_getBodyAsString() protected
```
_getBodyAsString(): string
```
Get the response body as string
#### Returns
`string`
### \_getCookieEncryptionKey() protected
```
_getCookieEncryptionKey(): string
```
Returns the encryption key to be used.
#### Returns
`string`
### \_getTableClassName() protected
```
_getTableClassName(string $alias, array<string, mixed> $options): string
```
Gets the class name for the table.
#### Parameters
`string` $alias The model to get a mock for.
`array<string, mixed>` $options The config data for the mock's constructor.
#### Returns
`string`
#### Throws
`Cake\ORM\Exception\MissingTableClassException`
### \_handleError() protected
```
_handleError(Throwable $exception): void
```
Attempts to render an error response for a given exception.
This method will attempt to use the configured exception renderer. If that class does not exist, the built-in renderer will be used.
#### Parameters
`Throwable` $exception Exception to handle.
#### Returns
`void`
### \_implode() protected
```
_implode(array $array): string
```
Implode method to keep keys are multidimensional arrays
#### Parameters
`array` $array Map of key and values
#### Returns
`string`
### \_makeDispatcher() protected
```
_makeDispatcher(): Cake\TestSuite\MiddlewareDispatcher
```
Get the correct dispatcher instance.
#### Returns
`Cake\TestSuite\MiddlewareDispatcher`
### \_normalizePath() protected
```
_normalizePath(string $path): string
```
Normalize a path for comparison.
#### Parameters
`string` $path Path separated by "/" slash.
#### Returns
`string`
### \_sendRequest() protected
```
_sendRequest(array|string $url, string $method, array|string $data = []): void
```
Creates and send the request into a Dispatcher instance.
Receives and stores the response for future inspection.
#### Parameters
`array|string` $url The URL
`string` $method The HTTP method
`array|string` $data optional The request data.
#### Returns
`void`
#### Throws
`PHPUnit\ExceptionThrowable`
### \_url() protected
```
_url(string $url): array
```
Creates a valid request url and parameter array more like Request::\_url()
#### Parameters
`string` $url The URL
#### Returns
`array`
### addFixture() protected
```
addFixture(string $fixture): $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.
#### Parameters
`string` $fixture Fixture
#### Returns
`$this`
### addToAssertionCount() public
```
addToAssertionCount(int $count): void
```
#### Parameters
`int` $count #### Returns
`void`
### addWarning() public
```
addWarning(string $warning): void
```
#### Parameters
`string` $warning #### Returns
`void`
### any() public static
```
any(): AnyInvokedCountMatcher
```
Returns a matcher that matches when the method is executed zero or more times.
#### Returns
`AnyInvokedCountMatcher`
### anything() public static
```
anything(): IsAnything
```
#### Returns
`IsAnything`
### arrayHasKey() public static
```
arrayHasKey(int|string $key): ArrayHasKey
```
#### Parameters
`int|string` $key #### Returns
`ArrayHasKey`
### assertArrayHasKey() public static
```
assertArrayHasKey(int|string $key, array|ArrayAccess $array, string $message = ''): void
```
Asserts that an array has a specified key.
#### Parameters
`int|string` $key `array|ArrayAccess` $array `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
`ExpectationFailedException`
### assertArrayNotHasKey() public static
```
assertArrayNotHasKey(int|string $key, array|ArrayAccess $array, string $message = ''): void
```
Asserts that an array does not have a specified key.
#### Parameters
`int|string` $key `array|ArrayAccess` $array `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
`ExpectationFailedException`
### assertClassHasAttribute() public static
```
assertClassHasAttribute(string $attributeName, string $className, string $message = ''): void
```
Asserts that a class has a specified attribute.
#### Parameters
`string` $attributeName `string` $className `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
`ExpectationFailedException`
### assertClassHasStaticAttribute() public static
```
assertClassHasStaticAttribute(string $attributeName, string $className, string $message = ''): void
```
Asserts that a class has a specified static attribute.
#### Parameters
`string` $attributeName `string` $className `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
`ExpectationFailedException`
### assertClassNotHasAttribute() public static
```
assertClassNotHasAttribute(string $attributeName, string $className, string $message = ''): void
```
Asserts that a class does not have a specified attribute.
#### Parameters
`string` $attributeName `string` $className `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
`ExpectationFailedException`
### assertClassNotHasStaticAttribute() public static
```
assertClassNotHasStaticAttribute(string $attributeName, string $className, string $message = ''): void
```
Asserts that a class does not have a specified static attribute.
#### Parameters
`string` $attributeName `string` $className `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
`ExpectationFailedException`
### assertContains() public static
```
assertContains(mixed $needle, iterable $haystack, string $message = ''): void
```
Asserts that a haystack contains a needle.
#### Parameters
$needle `iterable` $haystack `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
`ExpectationFailedException`
### assertContainsEquals() public static
```
assertContainsEquals(mixed $needle, iterable $haystack, string $message = ''): void
```
#### Parameters
$needle `iterable` $haystack `string` $message optional #### Returns
`void`
### assertContainsOnly() public static
```
assertContainsOnly(string $type, iterable $haystack, ?bool $isNativeType = null, string $message = ''): void
```
Asserts that a haystack contains only values of a given type.
#### Parameters
`string` $type `iterable` $haystack `?bool` $isNativeType optional `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertContainsOnlyInstancesOf() public static
```
assertContainsOnlyInstancesOf(string $className, iterable $haystack, string $message = ''): void
```
Asserts that a haystack contains only instances of a given class name.
#### Parameters
`string` $className `iterable` $haystack `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertContentType() public
```
assertContentType(string $type, string $message = ''): void
```
Asserts content type
#### Parameters
`string` $type The content-type to check for.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertCookie() public
```
assertCookie(mixed $expected, string $name, string $message = ''): void
```
Asserts cookie values
#### Parameters
`mixed` $expected The expected contents.
`string` $name The cookie name.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertCookieEncrypted() public
```
assertCookieEncrypted(mixed $expected, string $name, string $encrypt = 'aes', string|null $key = null, string $message = ''): void
```
Asserts cookie values which are encrypted by the CookieComponent.
The difference from assertCookie() is this decrypts the cookie value like the CookieComponent for this assertion.
#### Parameters
`mixed` $expected The expected contents.
`string` $name The cookie name.
`string` $encrypt optional Encryption mode to use.
`string|null` $key optional Encryption key used. Defaults to Security.salt.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
#### See Also
\Cake\Utility\CookieCryptTrait::\_encrypt() ### assertCookieNotSet() public
```
assertCookieNotSet(string $cookie, string $message = ''): void
```
Asserts a cookie has not been set in the response
#### Parameters
`string` $cookie The cookie name to check
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertCount() public static
```
assertCount(int $expectedCount, Countable|iterable $haystack, string $message = ''): void
```
Asserts the number of elements of an array, Countable or Traversable.
#### Parameters
`int` $expectedCount `Countable|iterable` $haystack `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
`ExpectationFailedException`
### assertDirectoryDoesNotExist() public static
```
assertDirectoryDoesNotExist(string $directory, string $message = ''): void
```
Asserts that a directory does not exist.
#### Parameters
`string` $directory Directory
`string` $message optional Message
#### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### assertDirectoryExists() public static
```
assertDirectoryExists(string $directory, string $message = ''): void
```
Asserts that a directory exists.
#### Parameters
`string` $directory `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertDirectoryIsNotReadable() public static
```
assertDirectoryIsNotReadable(string $directory, string $message = ''): void
```
Asserts that a directory exists and is not readable.
#### Parameters
`string` $directory `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertDirectoryIsNotWritable() public static
```
assertDirectoryIsNotWritable(string $directory, string $message = ''): void
```
Asserts that a directory exists and is not writable.
#### Parameters
`string` $directory `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertDirectoryIsReadable() public static
```
assertDirectoryIsReadable(string $directory, string $message = ''): void
```
Asserts that a directory exists and is readable.
#### Parameters
`string` $directory `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertDirectoryIsWritable() public static
```
assertDirectoryIsWritable(string $directory, string $message = ''): void
```
Asserts that a directory exists and is writable.
#### Parameters
`string` $directory `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertDirectoryNotExists() public static
```
assertDirectoryNotExists(string $directory, string $message = ''): void
```
Asserts that a directory does not exist.
#### Parameters
`string` $directory `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertDirectoryNotIsReadable() public static
```
assertDirectoryNotIsReadable(string $directory, string $message = ''): void
```
Asserts that a directory exists and is not readable.
#### Parameters
`string` $directory `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertDirectoryNotIsWritable() public static
```
assertDirectoryNotIsWritable(string $directory, string $message = ''): void
```
Asserts that a directory exists and is not writable.
#### Parameters
`string` $directory `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertDoesNotMatchRegularExpression() public static
```
assertDoesNotMatchRegularExpression(string $pattern, string $string, string $message = ''): void
```
Asserts that a string does not match a given regular expression.
#### Parameters
`string` $pattern Regex pattern
`string` $string String to test
`string` $message optional Message
#### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### assertEmpty() public static
```
assertEmpty(mixed $actual, string $message = ''): void
```
Asserts that a variable is empty.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertEqualXMLStructure() public static
```
assertEqualXMLStructure(DOMElement $expectedElement, DOMElement $actualElement, bool $checkAttributes = false, string $message = ''): void
```
Asserts that a hierarchy of DOMElements matches.
#### Parameters
`DOMElement` $expectedElement `DOMElement` $actualElement `bool` $checkAttributes optional `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`AssertionFailedError`
`ExpectationFailedException`
### assertEquals() public static
```
assertEquals(mixed $expected, mixed $actual, string $message = ''): void
```
Asserts that two variables are equal.
#### Parameters
$expected $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertEqualsCanonicalizing() public static
```
assertEqualsCanonicalizing(mixed $expected, mixed $actual, string $message = ''): void
```
Asserts that two variables are equal (canonicalizing).
#### Parameters
$expected $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertEqualsIgnoringCase() public static
```
assertEqualsIgnoringCase(mixed $expected, mixed $actual, string $message = ''): void
```
Asserts that two variables are equal (ignoring case).
#### Parameters
$expected $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertEqualsSql() public
```
assertEqualsSql(string $expected, string $actual, string $message = ''): void
```
Assert that a string matches SQL with db-specific characters like quotes removed.
#### Parameters
`string` $expected The expected sql
`string` $actual The sql to compare
`string` $message optional The message to display on failure
#### Returns
`void`
### assertEqualsWithDelta() public static
```
assertEqualsWithDelta(mixed $expected, mixed $actual, float $delta, string $message = ''): void
```
Asserts that two variables are equal (with delta).
#### Parameters
$expected $actual `float` $delta `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertEventFired() public
```
assertEventFired(string $name, Cake\Event\EventManager|null $eventManager = null, string $message = ''): void
```
Asserts that a global event was fired. You must track events in your event manager for this assertion to work
#### Parameters
`string` $name Event name
`Cake\Event\EventManager|null` $eventManager optional Event manager to check, defaults to global event manager
`string` $message optional Assertion failure message
#### Returns
`void`
### assertEventFiredWith() public
```
assertEventFiredWith(string $name, string $dataKey, mixed $dataValue, Cake\Event\EventManager|null $eventManager = null, string $message = ''): void
```
Asserts an event was fired with data
If a third argument is passed, that value is used to compare with the value in $dataKey
#### Parameters
`string` $name Event name
`string` $dataKey Data key
`mixed` $dataValue Data value
`Cake\Event\EventManager|null` $eventManager optional Event manager to check, defaults to global event manager
`string` $message optional Assertion failure message
#### Returns
`void`
### assertFalse() public static
```
assertFalse(mixed $condition, string $message = ''): void
```
Asserts that a condition is false.
#### Parameters
$condition `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertFileDoesNotExist() public static
```
assertFileDoesNotExist(string $filename, string $message = ''): void
```
Asserts that a file does not exist.
#### Parameters
`string` $filename Filename
`string` $message optional Message
#### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### assertFileEquals() public static
```
assertFileEquals(string $expected, string $actual, string $message = ''): void
```
Asserts that the contents of one file is equal to the contents of another file.
#### Parameters
`string` $expected `string` $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertFileEqualsCanonicalizing() public static
```
assertFileEqualsCanonicalizing(string $expected, string $actual, string $message = ''): void
```
Asserts that the contents of one file is equal to the contents of another file (canonicalizing).
#### Parameters
`string` $expected `string` $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertFileEqualsIgnoringCase() public static
```
assertFileEqualsIgnoringCase(string $expected, string $actual, string $message = ''): void
```
Asserts that the contents of one file is equal to the contents of another file (ignoring case).
#### Parameters
`string` $expected `string` $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertFileExists() public static
```
assertFileExists(string $filename, string $message = ''): void
```
Asserts that a file exists.
#### Parameters
`string` $filename `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertFileIsNotReadable() public static
```
assertFileIsNotReadable(string $file, string $message = ''): void
```
Asserts that a file exists and is not readable.
#### Parameters
`string` $file `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertFileIsNotWritable() public static
```
assertFileIsNotWritable(string $file, string $message = ''): void
```
Asserts that a file exists and is not writable.
#### Parameters
`string` $file `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertFileIsReadable() public static
```
assertFileIsReadable(string $file, string $message = ''): void
```
Asserts that a file exists and is readable.
#### Parameters
`string` $file `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertFileIsWritable() public static
```
assertFileIsWritable(string $file, string $message = ''): void
```
Asserts that a file exists and is writable.
#### Parameters
`string` $file `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertFileNotEquals() public static
```
assertFileNotEquals(string $expected, string $actual, string $message = ''): void
```
Asserts that the contents of one file is not equal to the contents of another file.
#### Parameters
`string` $expected `string` $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertFileNotEqualsCanonicalizing() public static
```
assertFileNotEqualsCanonicalizing(string $expected, string $actual, string $message = ''): void
```
Asserts that the contents of one file is not equal to the contents of another file (canonicalizing).
#### Parameters
`string` $expected `string` $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertFileNotEqualsIgnoringCase() public static
```
assertFileNotEqualsIgnoringCase(string $expected, string $actual, string $message = ''): void
```
Asserts that the contents of one file is not equal to the contents of another file (ignoring case).
#### Parameters
`string` $expected `string` $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertFileNotExists() public static
```
assertFileNotExists(string $filename, string $message = ''): void
```
Asserts that a file does not exist.
#### Parameters
`string` $filename `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertFileNotIsReadable() public static
```
assertFileNotIsReadable(string $file, string $message = ''): void
```
Asserts that a file exists and is not readable.
#### Parameters
`string` $file `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertFileNotIsWritable() public static
```
assertFileNotIsWritable(string $file, string $message = ''): void
```
Asserts that a file exists and is not writable.
#### Parameters
`string` $file `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertFileResponse() public
```
assertFileResponse(string $expected, string $message = ''): void
```
Asserts that a file with the given name was sent in the response
#### Parameters
`string` $expected The absolute file path that should be sent in the response.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertFinite() public static
```
assertFinite(mixed $actual, string $message = ''): void
```
Asserts that a variable is finite.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertFlashElement() public
```
assertFlashElement(string $expected, string $key = 'flash', string $message = ''): void
```
Asserts a flash element was set
#### Parameters
`string` $expected Expected element name
`string` $key optional Flash key
`string` $message optional Assertion failure message
#### Returns
`void`
### assertFlashElementAt() public
```
assertFlashElementAt(int $at, string $expected, string $key = 'flash', string $message = ''): void
```
Asserts a flash element was set at a certain index
#### Parameters
`int` $at Flash index
`string` $expected Expected element name
`string` $key optional Flash key
`string` $message optional Assertion failure message
#### Returns
`void`
### assertFlashMessage() public
```
assertFlashMessage(string $expected, string $key = 'flash', string $message = ''): void
```
Asserts a flash message was set
#### Parameters
`string` $expected Expected message
`string` $key optional Flash key
`string` $message optional Assertion failure message
#### Returns
`void`
### assertFlashMessageAt() public
```
assertFlashMessageAt(int $at, string $expected, string $key = 'flash', string $message = ''): void
```
Asserts a flash message was set at a certain index
#### Parameters
`int` $at Flash index
`string` $expected Expected message
`string` $key optional Flash key
`string` $message optional Assertion failure message
#### Returns
`void`
### assertGreaterThan() public static
```
assertGreaterThan(mixed $expected, mixed $actual, string $message = ''): void
```
Asserts that a value is greater than another value.
#### Parameters
$expected $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertGreaterThanOrEqual() public static
```
assertGreaterThanOrEqual(mixed $expected, mixed $actual, string $message = ''): void
```
Asserts that a value is greater than or equal to another value.
#### Parameters
$expected $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertHeader() public
```
assertHeader(string $header, string $content, string $message = ''): void
```
Asserts response headers
#### Parameters
`string` $header The header to check
`string` $content The content to check for.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertHeaderContains() public
```
assertHeaderContains(string $header, string $content, string $message = ''): void
```
Asserts response header contains a string
#### Parameters
`string` $header The header to check
`string` $content The content to check for.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertHeaderNotContains() public
```
assertHeaderNotContains(string $header, string $content, string $message = ''): void
```
Asserts response header does not contain a string
#### Parameters
`string` $header The header to check
`string` $content The content to check for.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertHtml() public
```
assertHtml(array $expected, string $string, bool $fullDebug = false): bool
```
Asserts HTML tags.
Takes an array $expected and generates a regex from it to match the provided $string. Samples for $expected:
Checks for an input tag with a name attribute (contains any non-empty value) and an id attribute that contains 'my-input':
```
['input' => ['name', 'id' => 'my-input']]
```
Checks for two p elements with some text in them:
```
[
['p' => true],
'textA',
'/p',
['p' => true],
'textB',
'/p'
]
```
You can also specify a pattern expression as part of the attribute values, or the tag being defined, if you prepend the value with preg: and enclose it with slashes, like so:
```
[
['input' => ['name', 'id' => 'preg:/FieldName\d+/']],
'preg:/My\s+field/'
]
```
Important: This function is very forgiving about whitespace and also accepts any permutation of attribute order. It will also allow whitespace between specified tags.
#### Parameters
`array` $expected An array, see above
`string` $string An HTML/XHTML/XML string
`bool` $fullDebug optional Whether more verbose output should be used.
#### Returns
`bool`
### assertInfinite() public static
```
assertInfinite(mixed $actual, string $message = ''): void
```
Asserts that a variable is infinite.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertInstanceOf() public static
```
assertInstanceOf(string $expected, mixed $actual, string $message = ''): void
```
Asserts that a variable is of a given type.
#### Parameters
`string` $expected $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
`ExpectationFailedException`
### assertIsArray() public static
```
assertIsArray(mixed $actual, string $message = ''): void
```
Asserts that a variable is of type array.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsBool() public static
```
assertIsBool(mixed $actual, string $message = ''): void
```
Asserts that a variable is of type bool.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsCallable() public static
```
assertIsCallable(mixed $actual, string $message = ''): void
```
Asserts that a variable is of type callable.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsClosedResource() public static
```
assertIsClosedResource(mixed $actual, string $message = ''): void
```
Asserts that a variable is of type resource and is closed.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsFloat() public static
```
assertIsFloat(mixed $actual, string $message = ''): void
```
Asserts that a variable is of type float.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsInt() public static
```
assertIsInt(mixed $actual, string $message = ''): void
```
Asserts that a variable is of type int.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsIterable() public static
```
assertIsIterable(mixed $actual, string $message = ''): void
```
Asserts that a variable is of type iterable.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsNotArray() public static
```
assertIsNotArray(mixed $actual, string $message = ''): void
```
Asserts that a variable is not of type array.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsNotBool() public static
```
assertIsNotBool(mixed $actual, string $message = ''): void
```
Asserts that a variable is not of type bool.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsNotCallable() public static
```
assertIsNotCallable(mixed $actual, string $message = ''): void
```
Asserts that a variable is not of type callable.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsNotClosedResource() public static
```
assertIsNotClosedResource(mixed $actual, string $message = ''): void
```
Asserts that a variable is not of type resource.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsNotFloat() public static
```
assertIsNotFloat(mixed $actual, string $message = ''): void
```
Asserts that a variable is not of type float.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsNotInt() public static
```
assertIsNotInt(mixed $actual, string $message = ''): void
```
Asserts that a variable is not of type int.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsNotIterable() public static
```
assertIsNotIterable(mixed $actual, string $message = ''): void
```
Asserts that a variable is not of type iterable.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsNotNumeric() public static
```
assertIsNotNumeric(mixed $actual, string $message = ''): void
```
Asserts that a variable is not of type numeric.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsNotObject() public static
```
assertIsNotObject(mixed $actual, string $message = ''): void
```
Asserts that a variable is not of type object.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsNotReadable() public static
```
assertIsNotReadable(string $filename, string $message = ''): void
```
Asserts that a file/dir exists and is not readable.
#### Parameters
`string` $filename `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsNotResource() public static
```
assertIsNotResource(mixed $actual, string $message = ''): void
```
Asserts that a variable is not of type resource.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsNotScalar() public static
```
assertIsNotScalar(mixed $actual, string $message = ''): void
```
Asserts that a variable is not of type scalar.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsNotString() public static
```
assertIsNotString(mixed $actual, string $message = ''): void
```
Asserts that a variable is not of type string.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsNotWritable() public static
```
assertIsNotWritable(string $filename, string $message = ''): void
```
Asserts that a file/dir exists and is not writable.
#### Parameters
`string` $filename `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsNumeric() public static
```
assertIsNumeric(mixed $actual, string $message = ''): void
```
Asserts that a variable is of type numeric.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsObject() public static
```
assertIsObject(mixed $actual, string $message = ''): void
```
Asserts that a variable is of type object.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsReadable() public static
```
assertIsReadable(string $filename, string $message = ''): void
```
Asserts that a file/dir is readable.
#### Parameters
`string` $filename `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsResource() public static
```
assertIsResource(mixed $actual, string $message = ''): void
```
Asserts that a variable is of type resource.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsScalar() public static
```
assertIsScalar(mixed $actual, string $message = ''): void
```
Asserts that a variable is of type scalar.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsString() public static
```
assertIsString(mixed $actual, string $message = ''): void
```
Asserts that a variable is of type string.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertIsWritable() public static
```
assertIsWritable(string $filename, string $message = ''): void
```
Asserts that a file/dir exists and is writable.
#### Parameters
`string` $filename `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertJson() public static
```
assertJson(string $actualJson, string $message = ''): void
```
Asserts that a string is a valid JSON string.
#### Parameters
`string` $actualJson `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertJsonFileEqualsJsonFile() public static
```
assertJsonFileEqualsJsonFile(string $expectedFile, string $actualFile, string $message = ''): void
```
Asserts that two JSON files are equal.
#### Parameters
`string` $expectedFile `string` $actualFile `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertJsonFileNotEqualsJsonFile() public static
```
assertJsonFileNotEqualsJsonFile(string $expectedFile, string $actualFile, string $message = ''): void
```
Asserts that two JSON files are not equal.
#### Parameters
`string` $expectedFile `string` $actualFile `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertJsonStringEqualsJsonFile() public static
```
assertJsonStringEqualsJsonFile(string $expectedFile, string $actualJson, string $message = ''): void
```
Asserts that the generated JSON encoded object and the content of the given file are equal.
#### Parameters
`string` $expectedFile `string` $actualJson `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertJsonStringEqualsJsonString() public static
```
assertJsonStringEqualsJsonString(string $expectedJson, string $actualJson, string $message = ''): void
```
Asserts that two given JSON encoded objects or arrays are equal.
#### Parameters
`string` $expectedJson `string` $actualJson `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertJsonStringNotEqualsJsonFile() public static
```
assertJsonStringNotEqualsJsonFile(string $expectedFile, string $actualJson, string $message = ''): void
```
Asserts that the generated JSON encoded object and the content of the given file are not equal.
#### Parameters
`string` $expectedFile `string` $actualJson `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertJsonStringNotEqualsJsonString() public static
```
assertJsonStringNotEqualsJsonString(string $expectedJson, string $actualJson, string $message = ''): void
```
Asserts that two given JSON encoded objects or arrays are not equal.
#### Parameters
`string` $expectedJson `string` $actualJson `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertLayout() public
```
assertLayout(string $content, string $message = ''): void
```
Asserts that the search string was in the layout name.
#### Parameters
`string` $content The content to check for.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertLessThan() public static
```
assertLessThan(mixed $expected, mixed $actual, string $message = ''): void
```
Asserts that a value is smaller than another value.
#### Parameters
$expected $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertLessThanOrEqual() public static
```
assertLessThanOrEqual(mixed $expected, mixed $actual, string $message = ''): void
```
Asserts that a value is smaller than or equal to another value.
#### Parameters
$expected $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertMatchesRegularExpression() public static
```
assertMatchesRegularExpression(string $pattern, string $string, string $message = ''): void
```
Asserts that a string matches a given regular expression.
#### Parameters
`string` $pattern Regex pattern
`string` $string String to test
`string` $message optional Message
#### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### assertNan() public static
```
assertNan(mixed $actual, string $message = ''): void
```
Asserts that a variable is nan.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertNoRedirect() public
```
assertNoRedirect(string $message = ''): void
```
Asserts that the Location header is not set.
#### Parameters
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertNotContains() public static
```
assertNotContains(mixed $needle, iterable $haystack, string $message = ''): void
```
Asserts that a haystack does not contain a needle.
#### Parameters
$needle `iterable` $haystack `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
`ExpectationFailedException`
### assertNotContainsEquals() public static
```
assertNotContainsEquals(mixed $needle, iterable $haystack, string $message = ''): void
```
#### Parameters
$needle `iterable` $haystack `string` $message optional #### Returns
`void`
### assertNotContainsOnly() public static
```
assertNotContainsOnly(string $type, iterable $haystack, ?bool $isNativeType = null, string $message = ''): void
```
Asserts that a haystack does not contain only values of a given type.
#### Parameters
`string` $type `iterable` $haystack `?bool` $isNativeType optional `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertNotCount() public static
```
assertNotCount(int $expectedCount, Countable|iterable $haystack, string $message = ''): void
```
Asserts the number of elements of an array, Countable or Traversable.
#### Parameters
`int` $expectedCount `Countable|iterable` $haystack `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
`ExpectationFailedException`
### assertNotEmpty() public static
```
assertNotEmpty(mixed $actual, string $message = ''): void
```
Asserts that a variable is not empty.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertNotEquals() public static
```
assertNotEquals(mixed $expected, mixed $actual, string $message = ''): void
```
Asserts that two variables are not equal.
#### Parameters
$expected $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertNotEqualsCanonicalizing() public static
```
assertNotEqualsCanonicalizing(mixed $expected, mixed $actual, string $message = ''): void
```
Asserts that two variables are not equal (canonicalizing).
#### Parameters
$expected $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertNotEqualsIgnoringCase() public static
```
assertNotEqualsIgnoringCase(mixed $expected, mixed $actual, string $message = ''): void
```
Asserts that two variables are not equal (ignoring case).
#### Parameters
$expected $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertNotEqualsWithDelta() public static
```
assertNotEqualsWithDelta(mixed $expected, mixed $actual, float $delta, string $message = ''): void
```
Asserts that two variables are not equal (with delta).
#### Parameters
$expected $actual `float` $delta `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertNotFalse() public static
```
assertNotFalse(mixed $condition, string $message = ''): void
```
Asserts that a condition is not false.
#### Parameters
$condition `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertNotInstanceOf() public static
```
assertNotInstanceOf(string $expected, mixed $actual, string $message = ''): void
```
Asserts that a variable is not of a given type.
#### Parameters
`string` $expected $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
`ExpectationFailedException`
### assertNotIsReadable() public static
```
assertNotIsReadable(string $filename, string $message = ''): void
```
Asserts that a file/dir exists and is not readable.
#### Parameters
`string` $filename `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertNotIsWritable() public static
```
assertNotIsWritable(string $filename, string $message = ''): void
```
Asserts that a file/dir exists and is not writable.
#### Parameters
`string` $filename `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertNotNull() public static
```
assertNotNull(mixed $actual, string $message = ''): void
```
Asserts that a variable is not null.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertNotRegExp() public static
```
assertNotRegExp(string $pattern, string $string, string $message = ''): void
```
Asserts that a string does not match a given regular expression.
#### Parameters
`string` $pattern `string` $string `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertNotSame() public static
```
assertNotSame(mixed $expected, mixed $actual, string $message = ''): void
```
Asserts that two variables do not have the same type and value. Used on objects, it asserts that two variables do not reference the same object.
#### Parameters
$expected $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertNotSameSize() public static
```
assertNotSameSize(Countable|iterable $expected, Countable|iterable $actual, string $message = ''): void
```
Assert that the size of two arrays (or `Countable` or `Traversable` objects) is not the same.
#### Parameters
`Countable|iterable` $expected `Countable|iterable` $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
`ExpectationFailedException`
### assertNotTrue() public static
```
assertNotTrue(mixed $condition, string $message = ''): void
```
Asserts that a condition is not true.
#### Parameters
$condition `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertNotWithinRange() protected static
```
assertNotWithinRange(float $expected, float $result, float $margin, string $message = ''): void
```
Compatibility function to test if a value is not between an acceptable range.
#### Parameters
`float` $expected `float` $result `float` $margin the rage of acceptation
`string` $message optional the text to display if the assertion is not correct
#### Returns
`void`
### assertNull() public static
```
assertNull(mixed $actual, string $message = ''): void
```
Asserts that a variable is null.
#### Parameters
$actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertObjectEquals() public static
```
assertObjectEquals(object $expected, object $actual, string $method = 'equals', string $message = ''): void
```
#### Parameters
`object` $expected `object` $actual `string` $method optional `string` $message optional #### Returns
`void`
#### Throws
`ExpectationFailedException`
### assertObjectHasAttribute() public static
```
assertObjectHasAttribute(string $attributeName, object $object, string $message = ''): void
```
Asserts that an object has a specified attribute.
#### Parameters
`string` $attributeName `object` $object `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
`ExpectationFailedException`
### assertObjectNotHasAttribute() public static
```
assertObjectNotHasAttribute(string $attributeName, object $object, string $message = ''): void
```
Asserts that an object does not have a specified attribute.
#### Parameters
`string` $attributeName `object` $object `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
`ExpectationFailedException`
### assertPathEquals() protected static
```
assertPathEquals(string $expected, string $result, string $message = ''): void
```
Compatibility function to test paths.
#### Parameters
`string` $expected `string` $result `string` $message optional the text to display if the assertion is not correct
#### Returns
`void`
### assertPostConditions() protected
```
assertPostConditions(): void
```
Performs assertions shared by all tests of a test case.
This method is called between test and tearDown().
#### Returns
`void`
### assertPreConditions() protected
```
assertPreConditions(): void
```
Performs assertions shared by all tests of a test case.
This method is called between setUp() and test.
#### Returns
`void`
### assertRedirect() public
```
assertRedirect(array|string|null $url = null, string $message = ''): void
```
Asserts that the Location header is correct. Comparison is made against a full URL.
#### Parameters
`array|string|null` $url optional The URL you expected the client to go to. This can either be a string URL or an array compatible with Router::url(). Use null to simply check for the existence of this header.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertRedirectContains() public
```
assertRedirectContains(string $url, string $message = ''): void
```
Asserts that the Location header contains a substring
#### Parameters
`string` $url The URL you expected the client to go to.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertRedirectEquals() public
```
assertRedirectEquals(array|string|null $url = null, string $message = ''): void
```
Asserts that the Location header is correct. Comparison is made against exactly the URL provided.
#### Parameters
`array|string|null` $url optional The URL you expected the client to go to. This can either be a string URL or an array compatible with Router::url(). Use null to simply check for the existence of this header.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertRedirectNotContains() public
```
assertRedirectNotContains(string $url, string $message = ''): void
```
Asserts that the Location header does not contain a substring
#### Parameters
`string` $url The URL you expected the client to go to.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertRegExp() public static
```
assertRegExp(string $pattern, string $string, string $message = ''): void
```
Asserts that a string matches a given regular expression.
#### Parameters
`string` $pattern `string` $string `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertRegExpSql() public
```
assertRegExpSql(string $pattern, string $actual, bool $optional = false): void
```
Assertion for comparing a regex pattern against a query having its identifiers quoted. It accepts queries quoted with the characters `<` and `>`. If the third parameter is set to true, it will alter the pattern to both accept quoted and unquoted queries
#### Parameters
`string` $pattern The expected sql pattern
`string` $actual The sql to compare
`bool` $optional optional Whether quote characters (marked with <>) are optional
#### Returns
`void`
### assertResponseCode() public
```
assertResponseCode(int $code, string $message = ''): void
```
Asserts a specific response status code.
#### Parameters
`int` $code Status code to assert.
`string` $message optional Custom message for failure.
#### Returns
`void`
### assertResponseContains() public
```
assertResponseContains(string $content, string $message = '', bool $ignoreCase = false): void
```
Asserts content exists in the response body.
#### Parameters
`string` $content The content to check for.
`string` $message optional The failure message that will be appended to the generated message.
`bool` $ignoreCase optional A flag to check whether we should ignore case or not.
#### Returns
`void`
### assertResponseEmpty() public
```
assertResponseEmpty(string $message = ''): void
```
Assert response content is empty.
#### Parameters
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertResponseEquals() public
```
assertResponseEquals(mixed $content, string $message = ''): void
```
Asserts content in the response body equals.
#### Parameters
`mixed` $content The content to check for.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertResponseError() public
```
assertResponseError(string $message = ''): void
```
Asserts that the response status code is in the 4xx range.
#### Parameters
`string` $message optional Custom message for failure.
#### Returns
`void`
### assertResponseFailure() public
```
assertResponseFailure(string $message = ''): void
```
Asserts that the response status code is in the 5xx range.
#### Parameters
`string` $message optional Custom message for failure.
#### Returns
`void`
### assertResponseNotContains() public
```
assertResponseNotContains(string $content, string $message = '', bool $ignoreCase = false): void
```
Asserts content does not exist in the response body.
#### Parameters
`string` $content The content to check for.
`string` $message optional The failure message that will be appended to the generated message.
`bool` $ignoreCase optional A flag to check whether we should ignore case or not.
#### Returns
`void`
### assertResponseNotEmpty() public
```
assertResponseNotEmpty(string $message = ''): void
```
Assert response content is not empty.
#### Parameters
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertResponseNotEquals() public
```
assertResponseNotEquals(mixed $content, string $message = ''): void
```
Asserts content in the response body not equals.
#### Parameters
`mixed` $content The content to check for.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertResponseNotRegExp() public
```
assertResponseNotRegExp(string $pattern, string $message = ''): void
```
Asserts that the response body does not match a given regular expression.
#### Parameters
`string` $pattern The pattern to compare against.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertResponseOk() public
```
assertResponseOk(string $message = ''): void
```
Asserts that the response status code is in the 2xx range.
#### Parameters
`string` $message optional Custom message for failure.
#### Returns
`void`
### assertResponseRegExp() public
```
assertResponseRegExp(string $pattern, string $message = ''): void
```
Asserts that the response body matches a given regular expression.
#### Parameters
`string` $pattern The pattern to compare against.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertResponseSuccess() public
```
assertResponseSuccess(string $message = ''): void
```
Asserts that the response status code is in the 2xx/3xx range.
#### Parameters
`string` $message optional Custom message for failure.
#### Returns
`void`
### assertSame() public static
```
assertSame(mixed $expected, mixed $actual, string $message = ''): void
```
Asserts that two variables have the same type and value. Used on objects, it asserts that two variables reference the same object.
#### Parameters
$expected $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertSameSize() public static
```
assertSameSize(Countable|iterable $expected, Countable|iterable $actual, string $message = ''): void
```
Assert that the size of two arrays (or `Countable` or `Traversable` objects) is the same.
#### Parameters
`Countable|iterable` $expected `Countable|iterable` $actual `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
`ExpectationFailedException`
### assertSession() public
```
assertSession(mixed $expected, string $path, string $message = ''): void
```
Asserts session contents
#### Parameters
`mixed` $expected The expected contents.
`string` $path The session data path. Uses Hash::get() compatible notation
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertSessionHasKey() public
```
assertSessionHasKey(string $path, string $message = ''): void
```
Asserts session key exists.
#### Parameters
`string` $path The session data path. Uses Hash::get() compatible notation.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertSessionNotHasKey() public
```
assertSessionNotHasKey(string $path, string $message = ''): void
```
Asserts a session key does not exist.
#### Parameters
`string` $path The session data path. Uses Hash::get() compatible notation.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertStringContainsString() public static
```
assertStringContainsString(string $needle, string $haystack, string $message = ''): void
```
#### Parameters
`string` $needle `string` $haystack `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertStringContainsStringIgnoringCase() public static
```
assertStringContainsStringIgnoringCase(string $needle, string $haystack, string $message = ''): void
```
#### Parameters
`string` $needle `string` $haystack `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertStringEndsNotWith() public static
```
assertStringEndsNotWith(string $suffix, string $string, string $message = ''): void
```
Asserts that a string ends not with a given suffix.
#### Parameters
`string` $suffix `string` $string `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertStringEndsWith() public static
```
assertStringEndsWith(string $suffix, string $string, string $message = ''): void
```
Asserts that a string ends with a given suffix.
#### Parameters
`string` $suffix `string` $string `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertStringEqualsFile() public static
```
assertStringEqualsFile(string $expectedFile, string $actualString, string $message = ''): void
```
Asserts that the contents of a string is equal to the contents of a file.
#### Parameters
`string` $expectedFile `string` $actualString `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertStringEqualsFileCanonicalizing() public static
```
assertStringEqualsFileCanonicalizing(string $expectedFile, string $actualString, string $message = ''): void
```
Asserts that the contents of a string is equal to the contents of a file (canonicalizing).
#### Parameters
`string` $expectedFile `string` $actualString `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertStringEqualsFileIgnoringCase() public static
```
assertStringEqualsFileIgnoringCase(string $expectedFile, string $actualString, string $message = ''): void
```
Asserts that the contents of a string is equal to the contents of a file (ignoring case).
#### Parameters
`string` $expectedFile `string` $actualString `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertStringMatchesFormat() public static
```
assertStringMatchesFormat(string $format, string $string, string $message = ''): void
```
Asserts that a string matches a given format string.
#### Parameters
`string` $format `string` $string `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertStringMatchesFormatFile() public static
```
assertStringMatchesFormatFile(string $formatFile, string $string, string $message = ''): void
```
Asserts that a string matches a given format file.
#### Parameters
`string` $formatFile `string` $string `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertStringNotContainsString() public static
```
assertStringNotContainsString(string $needle, string $haystack, string $message = ''): void
```
#### Parameters
`string` $needle `string` $haystack `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertStringNotContainsStringIgnoringCase() public static
```
assertStringNotContainsStringIgnoringCase(string $needle, string $haystack, string $message = ''): void
```
#### Parameters
`string` $needle `string` $haystack `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertStringNotEqualsFile() public static
```
assertStringNotEqualsFile(string $expectedFile, string $actualString, string $message = ''): void
```
Asserts that the contents of a string is not equal to the contents of a file.
#### Parameters
`string` $expectedFile `string` $actualString `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertStringNotEqualsFileCanonicalizing() public static
```
assertStringNotEqualsFileCanonicalizing(string $expectedFile, string $actualString, string $message = ''): void
```
Asserts that the contents of a string is not equal to the contents of a file (canonicalizing).
#### Parameters
`string` $expectedFile `string` $actualString `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertStringNotEqualsFileIgnoringCase() public static
```
assertStringNotEqualsFileIgnoringCase(string $expectedFile, string $actualString, string $message = ''): void
```
Asserts that the contents of a string is not equal to the contents of a file (ignoring case).
#### Parameters
`string` $expectedFile `string` $actualString `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertStringNotMatchesFormat() public static
```
assertStringNotMatchesFormat(string $format, string $string, string $message = ''): void
```
Asserts that a string does not match a given format string.
#### Parameters
`string` $format `string` $string `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertStringNotMatchesFormatFile() public static
```
assertStringNotMatchesFormatFile(string $formatFile, string $string, string $message = ''): void
```
Asserts that a string does not match a given format string.
#### Parameters
`string` $formatFile `string` $string `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertStringStartsNotWith() public static
```
assertStringStartsNotWith(string $prefix, string $string, string $message = ''): void
```
Asserts that a string starts not with a given prefix.
#### Parameters
`string` $prefix `string` $string `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertStringStartsWith() public static
```
assertStringStartsWith(string $prefix, string $string, string $message = ''): void
```
Asserts that a string starts with a given prefix.
#### Parameters
`string` $prefix `string` $string `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertTemplate() public
```
assertTemplate(string $content, string $message = ''): void
```
Asserts that the search string was in the template name.
#### Parameters
`string` $content The content to check for.
`string` $message optional The failure message that will be appended to the generated message.
#### Returns
`void`
### assertTextContains() public
```
assertTextContains(string $needle, string $haystack, string $message = '', bool $ignoreCase = false): void
```
Assert that a string contains another string, ignoring differences in newlines. Helpful for doing cross platform tests of blocks of text.
#### Parameters
`string` $needle The string to search for.
`string` $haystack The string to search through.
`string` $message optional The message to display on failure.
`bool` $ignoreCase optional Whether the search should be case-sensitive.
#### Returns
`void`
### assertTextEndsNotWith() public
```
assertTextEndsNotWith(string $suffix, string $string, string $message = ''): void
```
Asserts that a string ends not with a given prefix, ignoring differences in newlines. Helpful for doing cross platform tests of blocks of text.
#### Parameters
`string` $suffix The suffix to not find.
`string` $string The string to search.
`string` $message optional The message to use for failure.
#### Returns
`void`
### assertTextEndsWith() public
```
assertTextEndsWith(string $suffix, string $string, string $message = ''): void
```
Asserts that a string ends with a given prefix, ignoring differences in newlines. Helpful for doing cross platform tests of blocks of text.
#### Parameters
`string` $suffix The suffix to find.
`string` $string The string to search.
`string` $message optional The message to use for failure.
#### Returns
`void`
### assertTextEquals() public
```
assertTextEquals(string $expected, string $result, string $message = ''): void
```
Assert text equality, ignoring differences in newlines. Helpful for doing cross platform tests of blocks of text.
#### Parameters
`string` $expected The expected value.
`string` $result The actual value.
`string` $message optional The message to use for failure.
#### Returns
`void`
### assertTextNotContains() public
```
assertTextNotContains(string $needle, string $haystack, string $message = '', bool $ignoreCase = false): void
```
Assert that a text doesn't contain another text, ignoring differences in newlines. Helpful for doing cross platform tests of blocks of text.
#### Parameters
`string` $needle The string to search for.
`string` $haystack The string to search through.
`string` $message optional The message to display on failure.
`bool` $ignoreCase optional Whether the search should be case-sensitive.
#### Returns
`void`
### assertTextNotEquals() public
```
assertTextNotEquals(string $expected, string $result, string $message = ''): void
```
Assert text equality, ignoring differences in newlines. Helpful for doing cross platform tests of blocks of text.
#### Parameters
`string` $expected The expected value.
`string` $result The actual value.
`string` $message optional The message to use for failure.
#### Returns
`void`
### assertTextStartsNotWith() public
```
assertTextStartsNotWith(string $prefix, string $string, string $message = ''): void
```
Asserts that a string starts not with a given prefix, ignoring differences in newlines. Helpful for doing cross platform tests of blocks of text.
#### Parameters
`string` $prefix The prefix to not find.
`string` $string The string to search.
`string` $message optional The message to use for failure.
#### Returns
`void`
### assertTextStartsWith() public
```
assertTextStartsWith(string $prefix, string $string, string $message = ''): void
```
Asserts that a string starts with a given prefix, ignoring differences in newlines. Helpful for doing cross platform tests of blocks of text.
#### Parameters
`string` $prefix The prefix to check for.
`string` $string The string to search in.
`string` $message optional The message to use for failure.
#### Returns
`void`
### assertThat() public static
```
assertThat(mixed $value, Constraint $constraint, string $message = ''): void
```
Evaluates a PHPUnit\Framework\Constraint matcher object.
#### Parameters
$value `Constraint` $constraint `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertTrue() public static
```
assertTrue(mixed $condition, string $message = ''): void
```
Asserts that a condition is true.
#### Parameters
$condition `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertWithinRange() protected static
```
assertWithinRange(float $expected, float $result, float $margin, string $message = ''): void
```
Compatibility function to test if a value is between an acceptable range.
#### Parameters
`float` $expected `float` $result `float` $margin the rage of acceptation
`string` $message optional the text to display if the assertion is not correct
#### Returns
`void`
### assertXmlFileEqualsXmlFile() public static
```
assertXmlFileEqualsXmlFile(string $expectedFile, string $actualFile, string $message = ''): void
```
Asserts that two XML files are equal.
#### Parameters
`string` $expectedFile `string` $actualFile `string` $message optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
`ExpectationFailedException`
### assertXmlFileNotEqualsXmlFile() public static
```
assertXmlFileNotEqualsXmlFile(string $expectedFile, string $actualFile, string $message = ''): void
```
Asserts that two XML files are not equal.
#### Parameters
`string` $expectedFile `string` $actualFile `string` $message optional #### Returns
`void`
#### Throws
`PHPUnit\Util\Exception`
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertXmlStringEqualsXmlFile() public static
```
assertXmlStringEqualsXmlFile(string $expectedFile, DOMDocument|string $actualXml, string $message = ''): void
```
Asserts that two XML documents are equal.
#### Parameters
`string` $expectedFile `DOMDocument|string` $actualXml `string` $message optional #### Returns
`void`
#### Throws
`PHPUnit\Util\Xml\Exception`
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertXmlStringEqualsXmlString() public static
```
assertXmlStringEqualsXmlString(DOMDocument|string $expectedXml, DOMDocument|string $actualXml, string $message = ''): void
```
Asserts that two XML documents are equal.
#### Parameters
`DOMDocument|string` $expectedXml `DOMDocument|string` $actualXml `string` $message optional #### Returns
`void`
#### Throws
`PHPUnit\Util\Xml\Exception`
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertXmlStringNotEqualsXmlFile() public static
```
assertXmlStringNotEqualsXmlFile(string $expectedFile, DOMDocument|string $actualXml, string $message = ''): void
```
Asserts that two XML documents are not equal.
#### Parameters
`string` $expectedFile `DOMDocument|string` $actualXml `string` $message optional #### Returns
`void`
#### Throws
`PHPUnit\Util\Xml\Exception`
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### assertXmlStringNotEqualsXmlString() public static
```
assertXmlStringNotEqualsXmlString(DOMDocument|string $expectedXml, DOMDocument|string $actualXml, string $message = ''): void
```
Asserts that two XML documents are not equal.
#### Parameters
`DOMDocument|string` $expectedXml `DOMDocument|string` $actualXml `string` $message optional #### Returns
`void`
#### Throws
`PHPUnit\Util\Xml\Exception`
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### at() public static
```
at(int $index): InvokedAtIndexMatcher
```
Returns a matcher that matches when the method is executed at the given index.
#### Parameters
`int` $index #### Returns
`InvokedAtIndexMatcher`
### atLeast() public static
```
atLeast(int $requiredInvocations): InvokedAtLeastCountMatcher
```
Returns a matcher that matches when the method is executed at least N times.
#### Parameters
`int` $requiredInvocations #### Returns
`InvokedAtLeastCountMatcher`
### atLeastOnce() public static
```
atLeastOnce(): InvokedAtLeastOnceMatcher
```
Returns a matcher that matches when the method is executed at least once.
#### Returns
`InvokedAtLeastOnceMatcher`
### atMost() public static
```
atMost(int $allowedInvocations): InvokedAtMostCountMatcher
```
Returns a matcher that matches when the method is executed at most N times.
#### Parameters
`int` $allowedInvocations #### Returns
`InvokedAtMostCountMatcher`
### callback() public static
```
callback(callable $callback): Callback
```
#### Parameters
`callable` $callback #### Returns
`Callback`
### classHasAttribute() public static
```
classHasAttribute(string $attributeName): ClassHasAttribute
```
#### Parameters
`string` $attributeName #### Returns
`ClassHasAttribute`
### classHasStaticAttribute() public static
```
classHasStaticAttribute(string $attributeName): ClassHasStaticAttribute
```
#### Parameters
`string` $attributeName #### Returns
`ClassHasStaticAttribute`
### cleanup() public
```
cleanup(): void
```
Clears the state used for requests.
#### Returns
`void`
### cleanupContainer() public
```
cleanupContainer(): void
```
Clears any mocks that were defined and cleans up application class configuration.
#### Returns
`void`
### clearPlugins() public
```
clearPlugins(): void
```
Clear all plugins from the global plugin collection.
Useful in test case teardown methods.
#### Returns
`void`
### configApplication() public
```
configApplication(string $class, array|null $constructorArgs): void
```
Configure the application class to use in integration tests.
#### Parameters
`string` $class The application class name.
`array|null` $constructorArgs The constructor arguments for your application class.
#### Returns
`void`
### configRequest() public
```
configRequest(array $data): void
```
Configures the data for the *next* request.
This data is cleared in the tearDown() method.
You can call this method multiple times to append into the current state. Sub-keys like 'headers' will be reset, though.
#### Parameters
`array` $data The request data to use.
#### Returns
`void`
### containsEqual() public static
```
containsEqual(mixed $value): TraversableContainsEqual
```
#### Parameters
$value #### Returns
`TraversableContainsEqual`
### containsIdentical() public static
```
containsIdentical(mixed $value): TraversableContainsIdentical
```
#### Parameters
$value #### Returns
`TraversableContainsIdentical`
### containsOnly() public static
```
containsOnly(string $type): TraversableContainsOnly
```
#### Parameters
`string` $type #### Returns
`TraversableContainsOnly`
### containsOnlyInstancesOf() public static
```
containsOnlyInstancesOf(string $className): TraversableContainsOnly
```
#### Parameters
`string` $className #### Returns
`TraversableContainsOnly`
### controllerSpy() public
```
controllerSpy(Cake\Event\EventInterface $event, Cake\Controller\Controller|null $controller = null): void
```
Adds additional event spies to the controller/view event manager.
#### Parameters
`Cake\Event\EventInterface` $event A dispatcher event.
`Cake\Controller\Controller|null` $controller optional Controller instance.
#### Returns
`void`
### cookie() public
```
cookie(string $name, mixed $value): void
```
Sets a request cookie for future requests.
This method lets you configure the session data you want to be used for requests that follow. The session state is reset in each tearDown().
You can call this method multiple times to append into the current state.
#### Parameters
`string` $name The cookie name to use.
`mixed` $value The value of the cookie.
#### Returns
`void`
### cookieEncrypted() public
```
cookieEncrypted(string $name, mixed $value, string|false $encrypt = 'aes', string|null $key = null): void
```
Sets a encrypted request cookie for future requests.
The difference from cookie() is this encrypts the cookie value like the CookieComponent.
#### Parameters
`string` $name The cookie name to use.
`mixed` $value The value of the cookie.
`string|false` $encrypt optional Encryption mode to use.
`string|null` $key optional Encryption key used. Defaults to Security.salt.
#### Returns
`void`
#### See Also
\Cake\Utility\CookieCryptTrait::\_encrypt() ### count() public
```
count(): int
```
#### Returns
`int`
### countOf() public static
```
countOf(int $count): Count
```
#### Parameters
`int` $count #### Returns
`Count`
### createApp() protected
```
createApp(): Cake\Core\HttpApplicationInterfaceCake\Core\ConsoleApplicationInterface
```
Create an application instance.
Uses the configuration set in `configApplication()`.
#### Returns
`Cake\Core\HttpApplicationInterfaceCake\Core\ConsoleApplicationInterface`
### createConfiguredMock() protected
```
createConfiguredMock(string $originalClassName, array $configuration): MockObject
```
Returns a configured mock object for the specified class.
#### Parameters
`string` $originalClassName `array` $configuration #### Returns
`MockObject`
### createMock() protected
```
createMock(string $originalClassName): MockObject
```
Returns a mock object for the specified class.
#### Parameters
`string` $originalClassName #### Returns
`MockObject`
### createPartialMock() protected
```
createPartialMock(string $originalClassName, string[] $methods): MockObject
```
Returns a partial mock object for the specified class.
#### Parameters
`string` $originalClassName `string[]` $methods #### Returns
`MockObject`
### createResult() protected
```
createResult(): TestResult
```
Creates a default TestResult object.
#### Returns
`TestResult`
### createStub() protected
```
createStub(string $originalClassName): Stub
```
Makes configurable stub for the specified class.
#### Parameters
`string` $originalClassName #### Returns
`Stub`
### createTestProxy() protected
```
createTestProxy(string $originalClassName, array $constructorArguments = []): MockObject
```
Returns a test proxy for the specified class.
#### Parameters
`string` $originalClassName `array` $constructorArguments optional #### Returns
`MockObject`
### dataName() public
```
dataName(): int|string
```
#### Returns
`int|string`
### delete() public
```
delete(array|string $url): void
```
Performs a DELETE request using the current request data.
The response of the dispatched request will be stored as a property. You can use various assert methods to check the response.
#### Parameters
`array|string` $url The URL to request.
#### Returns
`void`
### deprecated() public
```
deprecated(callable $callable): void
```
Helper method for check deprecation methods
#### Parameters
`callable` $callable callable function that will receive asserts
#### Returns
`void`
### directoryExists() public static
```
directoryExists(): DirectoryExists
```
#### Returns
`DirectoryExists`
### disableErrorHandlerMiddleware() public
```
disableErrorHandlerMiddleware(): void
```
Disable the error handler middleware.
By using this function, exceptions are no longer caught by the ErrorHandlerMiddleware and are instead re-thrown by the TestExceptionRenderer. This can be helpful when trying to diagnose/debug unexpected failures in test cases.
#### Returns
`void`
### doesNotPerformAssertions() public
```
doesNotPerformAssertions(): bool
```
#### Returns
`bool`
### doubledTypes() public
```
doubledTypes(): string[]
```
#### Returns
`string[]`
### enableCsrfToken() public
```
enableCsrfToken(string $cookieName = 'csrfToken'): void
```
Calling this method will add a CSRF token to the request.
Both the POST data and cookie will be populated when this option is enabled. The default parameter names will be used.
#### Parameters
`string` $cookieName optional The name of the csrf token cookie.
#### Returns
`void`
### enableRetainFlashMessages() public
```
enableRetainFlashMessages(): void
```
Calling this method will re-store flash messages into the test session after being removed by the FlashHelper
#### Returns
`void`
### enableSecurityToken() public
```
enableSecurityToken(): void
```
Calling this method will enable a SecurityComponent compatible token to be added to request data. This lets you easily test actions protected by SecurityComponent.
#### Returns
`void`
### equalTo() public static
```
equalTo(mixed $value): IsEqual
```
#### Parameters
$value #### Returns
`IsEqual`
### equalToCanonicalizing() public static
```
equalToCanonicalizing(mixed $value): IsEqualCanonicalizing
```
#### Parameters
$value #### Returns
`IsEqualCanonicalizing`
### equalToIgnoringCase() public static
```
equalToIgnoringCase(mixed $value): IsEqualIgnoringCase
```
#### Parameters
$value #### Returns
`IsEqualIgnoringCase`
### equalToWithDelta() public static
```
equalToWithDelta(mixed $value, float $delta): IsEqualWithDelta
```
#### Parameters
$value `float` $delta #### Returns
`IsEqualWithDelta`
### exactly() public static
```
exactly(int $count): InvokedCountMatcher
```
Returns a matcher that matches when the method is executed exactly $count times.
#### Parameters
`int` $count #### Returns
`InvokedCountMatcher`
### expectDeprecation() public
```
expectDeprecation(): void
```
#### Returns
`void`
### expectDeprecationMessage() public
```
expectDeprecationMessage(string $message): void
```
#### Parameters
`string` $message #### Returns
`void`
### expectDeprecationMessageMatches() public
```
expectDeprecationMessageMatches(string $regularExpression): void
```
#### Parameters
`string` $regularExpression #### Returns
`void`
### expectError() public
```
expectError(): void
```
#### Returns
`void`
### expectErrorMessage() public
```
expectErrorMessage(string $message): void
```
#### Parameters
`string` $message #### Returns
`void`
### expectErrorMessageMatches() public
```
expectErrorMessageMatches(string $regularExpression): void
```
#### Parameters
`string` $regularExpression #### Returns
`void`
### expectException() public
```
expectException(string $exception): void
```
#### Parameters
`string` $exception #### Returns
`void`
### expectExceptionCode() public
```
expectExceptionCode(int|string $code): void
```
#### Parameters
`int|string` $code #### Returns
`void`
### expectExceptionMessage() public
```
expectExceptionMessage(string $message): void
```
#### Parameters
`string` $message #### Returns
`void`
### expectExceptionMessageMatches() public
```
expectExceptionMessageMatches(string $regularExpression): void
```
#### Parameters
`string` $regularExpression #### Returns
`void`
### expectExceptionObject() public
```
expectExceptionObject(Exception $exception): void
```
Sets up an expectation for an exception to be raised by the code under test. Information for expected exception class, expected exception message, and expected exception code are retrieved from a given Exception object.
#### Parameters
`Exception` $exception #### Returns
`void`
### expectNotToPerformAssertions() public
```
expectNotToPerformAssertions(): void
```
#### Returns
`void`
### expectNotice() public
```
expectNotice(): void
```
#### Returns
`void`
### expectNoticeMessage() public
```
expectNoticeMessage(string $message): void
```
#### Parameters
`string` $message #### Returns
`void`
### expectNoticeMessageMatches() public
```
expectNoticeMessageMatches(string $regularExpression): void
```
#### Parameters
`string` $regularExpression #### Returns
`void`
### expectOutputRegex() public
```
expectOutputRegex(string $expectedRegex): void
```
#### Parameters
`string` $expectedRegex #### Returns
`void`
### expectOutputString() public
```
expectOutputString(string $expectedString): void
```
#### Parameters
`string` $expectedString #### Returns
`void`
### expectWarning() public
```
expectWarning(): void
```
#### Returns
`void`
### expectWarningMessage() public
```
expectWarningMessage(string $message): void
```
#### Parameters
`string` $message #### Returns
`void`
### expectWarningMessageMatches() public
```
expectWarningMessageMatches(string $regularExpression): void
```
#### Parameters
`string` $regularExpression #### Returns
`void`
### extractExceptionMessage() protected
```
extractExceptionMessage(Exception $exception): string
```
Extract verbose message for existing exception
#### Parameters
`Exception` $exception Exception to extract
#### Returns
`string`
### extractVerboseMessage() protected
```
extractVerboseMessage(string $message): string
```
Inspect controller to extract possible causes of the failed assertion
#### Parameters
`string` $message Original message to use as a base
#### Returns
`string`
### fail() public static
```
fail(string $message = ''): void
```
Fails a test with the given message.
#### Parameters
`string` $message optional #### Returns
`void`
#### Throws
`AssertionFailedError`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### fileExists() public static
```
fileExists(): FileExists
```
#### Returns
`FileExists`
### get() public
```
get(array|string $url): void
```
Performs a GET request using the current request data.
The response of the dispatched request will be stored as a property. You can use various assert methods to check the response.
#### Parameters
`array|string` $url The URL to request.
#### Returns
`void`
### getActualOutput() public
```
getActualOutput(): string
```
#### Returns
`string`
### getActualOutputForAssertion() public
```
getActualOutputForAssertion(): string
```
#### Returns
`string`
### getCount() public static
```
getCount(): int
```
Return the current assertion count.
#### Returns
`int`
### getDataSetAsString() public
```
getDataSetAsString(bool $includeData = true): string
```
#### Parameters
`bool` $includeData optional #### Returns
`string`
### getExpectedException() public
```
getExpectedException(): ?string
```
#### Returns
`?string`
### getExpectedExceptionCode() public
```
getExpectedExceptionCode(): null|int|string
```
#### Returns
`null|int|string`
### getExpectedExceptionMessage() public
```
getExpectedExceptionMessage(): ?string
```
#### Returns
`?string`
### getExpectedExceptionMessageRegExp() public
```
getExpectedExceptionMessageRegExp(): ?string
```
#### Returns
`?string`
### getFixtureStrategy() protected
```
getFixtureStrategy(): Cake\TestSuite\Fixture\FixtureStrategyInterface
```
Returns fixture strategy used by these tests.
#### Returns
`Cake\TestSuite\Fixture\FixtureStrategyInterface`
### getFixtures() public
```
getFixtures(): array<string>
```
Get the fixtures this test should use.
#### Returns
`array<string>`
### getGroups() public
```
getGroups(): array
```
#### Returns
`array`
### getMockBuilder() public
```
getMockBuilder(string $className): MockBuilder
```
Returns a builder object to create mock objects using a fluent interface.
#### Parameters
`string` $className #### Returns
`MockBuilder`
### getMockClass() protected
```
getMockClass(string $originalClassName, null|array $methods = [], array $arguments = [], string $mockClassName = '', bool $callOriginalConstructor = false, bool $callOriginalClone = true, bool $callAutoload = true, bool $cloneArguments = false): string
```
Mocks the specified class and returns the name of the mocked class.
#### Parameters
`string` $originalClassName `null|array` $methods optional $methods
`array` $arguments optional `string` $mockClassName optional `bool` $callOriginalConstructor optional `bool` $callOriginalClone optional `bool` $callAutoload optional `bool` $cloneArguments optional #### Returns
`string`
### getMockForAbstractClass() protected
```
getMockForAbstractClass(string $originalClassName, array $arguments = [], string $mockClassName = '', bool $callOriginalConstructor = true, bool $callOriginalClone = true, bool $callAutoload = true, array $mockedMethods = [], bool $cloneArguments = false): MockObject
```
Returns a mock object for the specified abstract class with all abstract methods of the class mocked. Concrete methods are not mocked by default. To mock concrete methods, use the 7th parameter ($mockedMethods).
#### Parameters
`string` $originalClassName `array` $arguments optional `string` $mockClassName optional `bool` $callOriginalConstructor optional `bool` $callOriginalClone optional `bool` $callAutoload optional `array` $mockedMethods optional `bool` $cloneArguments optional #### Returns
`MockObject`
### getMockForModel() public
```
getMockForModel(string $alias, array<string> $methods = [], array<string, mixed> $options = []): Cake\ORM\TablePHPUnit\Framework\MockObject\MockObject
```
Mock a model, maintain fixtures and table association
#### Parameters
`string` $alias The model to get a mock for.
`array<string>` $methods optional The list of methods to mock
`array<string, mixed>` $options optional The config data for the mock's constructor.
#### Returns
`Cake\ORM\TablePHPUnit\Framework\MockObject\MockObject`
#### Throws
`Cake\ORM\Exception\MissingTableClassException`
### getMockForTrait() protected
```
getMockForTrait(string $traitName, array $arguments = [], string $mockClassName = '', bool $callOriginalConstructor = true, bool $callOriginalClone = true, bool $callAutoload = true, array $mockedMethods = [], bool $cloneArguments = false): MockObject
```
Returns a mock object for the specified trait with all abstract methods of the trait mocked. Concrete methods to mock can be specified with the `$mockedMethods` parameter.
#### Parameters
`string` $traitName `array` $arguments optional `string` $mockClassName optional `bool` $callOriginalConstructor optional `bool` $callOriginalClone optional `bool` $callAutoload optional `array` $mockedMethods optional `bool` $cloneArguments optional #### Returns
`MockObject`
### getMockFromWsdl() protected
```
getMockFromWsdl(string $wsdlFile, string $originalClassName = '', string $mockClassName = '', array $methods = [], bool $callOriginalConstructor = true, array $options = []): MockObject
```
Returns a mock object based on the given WSDL file.
#### Parameters
`string` $wsdlFile `string` $originalClassName optional `string` $mockClassName optional `array` $methods optional `bool` $callOriginalConstructor optional `array` $options optional #### Returns
`MockObject`
### getName() public
```
getName(bool $withDataSet = true): string
```
#### Parameters
`bool` $withDataSet optional #### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### getNumAssertions() public
```
getNumAssertions(): int
```
Returns the number of assertions performed by this test.
#### Returns
`int`
### getObjectForTrait() protected
```
getObjectForTrait(string $traitName, array $arguments = [], string $traitClassName = '', bool $callOriginalConstructor = true, bool $callOriginalClone = true, bool $callAutoload = true): object
```
Returns an object for the specified trait.
#### Parameters
`string` $traitName `array` $arguments optional `string` $traitClassName optional `bool` $callOriginalConstructor optional `bool` $callOriginalClone optional `bool` $callAutoload optional #### Returns
`object`
### getProvidedData() public
```
getProvidedData(): array
```
Gets the data set of a TestCase.
#### Returns
`array`
### getResult() public
```
getResult()
```
### getSession() protected
```
getSession(): Cake\TestSuite\TestSession
```
#### Returns
`Cake\TestSuite\TestSession`
### getSize() public
```
getSize(): int
```
Returns the size of the test.
#### Returns
`int`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### getStatus() public
```
getStatus(): int
```
#### Returns
`int`
### getStatusMessage() public
```
getStatusMessage(): string
```
#### Returns
`string`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### getTestResultObject() public
```
getTestResultObject(): ?TestResult
```
#### Returns
`?TestResult`
### greaterThan() public static
```
greaterThan(mixed $value): GreaterThan
```
#### Parameters
$value #### Returns
`GreaterThan`
### greaterThanOrEqual() public static
```
greaterThanOrEqual(mixed $value): LogicalOr
```
#### Parameters
$value #### Returns
`LogicalOr`
### hasExpectationOnOutput() public
```
hasExpectationOnOutput(): bool
```
#### Returns
`bool`
### hasFailed() public
```
hasFailed(): bool
```
#### Returns
`bool`
### hasOutput() public
```
hasOutput(): bool
```
#### Returns
`bool`
### hasSize() public
```
hasSize(): bool
```
#### Returns
`bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### head() public
```
head(array|string $url): void
```
Performs a HEAD request using the current request data.
The response of the dispatched request will be stored as a property. You can use various assert methods to check the response.
#### Parameters
`array|string` $url The URL to request.
#### Returns
`void`
### identicalTo() public static
```
identicalTo(mixed $value): IsIdentical
```
#### Parameters
$value #### Returns
`IsIdentical`
### iniSet() protected
```
iniSet(string $varName, string $newValue): void
```
This method is a wrapper for the ini\_set() function that automatically resets the modified php.ini setting to its original value after the test is run.
#### Parameters
`string` $varName `string` $newValue #### Returns
`void`
#### Throws
`Exception`
### isEmpty() public static
```
isEmpty(): IsEmpty
```
#### Returns
`IsEmpty`
### isFalse() public static
```
isFalse(): IsFalse
```
#### Returns
`IsFalse`
### isFinite() public static
```
isFinite(): IsFinite
```
#### Returns
`IsFinite`
### isInIsolation() public
```
isInIsolation(): bool
```
#### Returns
`bool`
### isInfinite() public static
```
isInfinite(): IsInfinite
```
#### Returns
`IsInfinite`
### isInstanceOf() public static
```
isInstanceOf(string $className): IsInstanceOf
```
#### Parameters
`string` $className #### Returns
`IsInstanceOf`
### isJson() public static
```
isJson(): IsJson
```
#### Returns
`IsJson`
### isLarge() public
```
isLarge(): bool
```
#### Returns
`bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### isMedium() public
```
isMedium(): bool
```
#### Returns
`bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### isNan() public static
```
isNan(): IsNan
```
#### Returns
`IsNan`
### isNull() public static
```
isNull(): IsNull
```
#### Returns
`IsNull`
### isReadable() public static
```
isReadable(): IsReadable
```
#### Returns
`IsReadable`
### isSmall() public
```
isSmall(): bool
```
#### Returns
`bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### isTrue() public static
```
isTrue(): IsTrue
```
#### Returns
`IsTrue`
### isType() public static
```
isType(string $type): IsType
```
#### Parameters
`string` $type #### Returns
`IsType`
### isWritable() public static
```
isWritable(): IsWritable
```
#### Returns
`IsWritable`
### lessThan() public static
```
lessThan(mixed $value): LessThan
```
#### Parameters
$value #### Returns
`LessThan`
### lessThanOrEqual() public static
```
lessThanOrEqual(mixed $value): LogicalOr
```
#### Parameters
$value #### Returns
`LogicalOr`
### loadFixtures() public
```
loadFixtures(): void
```
Chooses which fixtures to load for a given test
Each parameter is a model name that corresponds to a fixture, i.e. 'Posts', 'Authors', etc. Passing no parameters will cause all fixtures on the test case to load.
#### Returns
`void`
#### Throws
`RuntimeException`
when no fixture manager is available. #### See Also
\Cake\TestSuite\TestCase::$autoFixtures ### loadPlugins() public
```
loadPlugins(array<string, mixed> $plugins = []): Cake\Http\BaseApplication
```
Load plugins into a simulated application.
Useful to test how plugins being loaded/not loaded interact with other elements in CakePHP or applications.
#### Parameters
`array<string, mixed>` $plugins optional List of Plugins to load.
#### Returns
`Cake\Http\BaseApplication`
### loadRoutes() public
```
loadRoutes(array|null $appArgs = null): void
```
Load routes for the application.
If no application class can be found an exception will be raised. Routes for plugins will *not* be loaded. Use `loadPlugins()` or use `Cake\TestSuite\IntegrationTestCaseTrait` to better simulate all routes and plugins being loaded.
#### Parameters
`array|null` $appArgs optional Constructor parameters for the application class.
#### Returns
`void`
### logicalAnd() public static
```
logicalAnd(): LogicalAnd
```
#### Returns
`LogicalAnd`
#### Throws
`Exception`
### logicalNot() public static
```
logicalNot(Constraint $constraint): LogicalNot
```
#### Parameters
`Constraint` $constraint #### Returns
`LogicalNot`
### logicalOr() public static
```
logicalOr(): LogicalOr
```
#### Returns
`LogicalOr`
### logicalXor() public static
```
logicalXor(): LogicalXor
```
#### Returns
`LogicalXor`
### markAsRisky() public
```
markAsRisky(): void
```
#### Returns
`void`
### markTestIncomplete() public static
```
markTestIncomplete(string $message = ''): void
```
Mark the test as incomplete.
#### Parameters
`string` $message optional #### Returns
`void`
#### Throws
`IncompleteTestError`
### markTestSkipped() public static
```
markTestSkipped(string $message = ''): void
```
Mark the test as skipped.
#### Parameters
`string` $message optional #### Returns
`void`
#### Throws
`SkippedTestError`
`SyntheticSkippedError`
### matches() public static
```
matches(string $string): StringMatchesFormatDescription
```
#### Parameters
`string` $string #### Returns
`StringMatchesFormatDescription`
### matchesRegularExpression() public static
```
matchesRegularExpression(string $pattern): RegularExpression
```
#### Parameters
`string` $pattern #### Returns
`RegularExpression`
### mockService() public
```
mockService(string $class, Closure $factory): $this
```
Add a mocked service to the container.
When the container is created the provided classname will be mapped to the factory function. The factory function will be used to create mocked services.
#### Parameters
`string` $class The class or interface you want to define.
`Closure` $factory The factory function for mocked services.
#### Returns
`$this`
### modifyContainer() public
```
modifyContainer(Cake\Event\EventInterface $event, Cake\Core\ContainerInterface $container): Cake\Core\ContainerInterface|null
```
Wrap the application's container with one containing mocks.
If any mocked services are defined, the application's container will be replaced with one containing mocks. The original container will be set as a delegate to the mock container.
#### Parameters
`Cake\Event\EventInterface` $event The event
`Cake\Core\ContainerInterface` $container The container to wrap.
#### Returns
`Cake\Core\ContainerInterface|null`
### never() public static
```
never(): InvokedCountMatcher
```
Returns a matcher that matches when the method is never executed.
#### Returns
`InvokedCountMatcher`
### objectEquals() public static
```
objectEquals(object $object, string $method = 'equals'): ObjectEquals
```
#### Parameters
`object` $object `string` $method optional #### Returns
`ObjectEquals`
### objectHasAttribute() public static
```
objectHasAttribute(mixed $attributeName): ObjectHasAttribute
```
#### Parameters
$attributeName #### Returns
`ObjectHasAttribute`
### onConsecutiveCalls() public static
```
onConsecutiveCalls(mixed ...$args): ConsecutiveCallsStub
```
#### Parameters
...$args #### Returns
`ConsecutiveCallsStub`
### onNotSuccessfulTest() protected
```
onNotSuccessfulTest(Throwable $t): void
```
This method is called when a test method did not execute successfully.
#### Parameters
`Throwable` $t #### Returns
`void`
#### Throws
`Throwable`
### once() public static
```
once(): InvokedCountMatcher
```
Returns a matcher that matches when the method is executed exactly once.
#### Returns
`InvokedCountMatcher`
### options() public
```
options(array|string $url): void
```
Performs an OPTIONS request using the current request data.
The response of the dispatched request will be stored as a property. You can use various assert methods to check the response.
#### Parameters
`array|string` $url The URL to request.
#### Returns
`void`
### patch() public
```
patch(array|string $url, array|string $data = []): void
```
Performs a PATCH request using the current request data.
The response of the dispatched request will be stored as a property. You can use various assert methods to check the response.
#### Parameters
`array|string` $url The URL to request.
`array|string` $data optional The data for the request.
#### Returns
`void`
### post() public
```
post(array|string $url, array|string $data = []): void
```
Performs a POST request using the current request data.
The response of the dispatched request will be stored as a property. You can use various assert methods to check the response.
#### Parameters
`array|string` $url The URL to request.
`array|string` $data optional The data for the request.
#### Returns
`void`
### prophesize() protected
```
prophesize(?string $classOrInterface = null): ObjectProphecy
```
#### Parameters
`?string` $classOrInterface optional #### Returns
`ObjectProphecy`
#### Throws
`Prophecy\Exception\Doubler\ClassNotFoundException`
`Prophecy\Exception\Doubler\DoubleException`
`Prophecy\Exception\Doubler\InterfaceNotFoundException`
### provides() public
```
provides(): list<ExecutionOrderDependency>
```
Returns the normalized test name as class::method.
#### Returns
`list<ExecutionOrderDependency>`
### put() public
```
put(array|string $url, array|string $data = []): void
```
Performs a PUT request using the current request data.
The response of the dispatched request will be stored as a property. You can use various assert methods to check the response.
#### Parameters
`array|string` $url The URL to request.
`array|string` $data optional The data for the request.
#### Returns
`void`
### recordDoubledType() protected
```
recordDoubledType(string $originalClassName): void
```
#### Parameters
`string` $originalClassName #### Returns
`void`
### registerComparator() public
```
registerComparator(Comparator $comparator): void
```
#### Parameters
`Comparator` $comparator #### Returns
`void`
### registerMockObject() public
```
registerMockObject(MockObject $mockObject): void
```
#### Parameters
`MockObject` $mockObject #### Returns
`void`
### removeMockService() public
```
removeMockService(string $class): $this
```
Remove a mocked service to the container.
#### Parameters
`string` $class The class or interface you want to remove.
#### Returns
`$this`
### removePlugins() public
```
removePlugins(array<string> $names = []): void
```
Remove plugins from the global plugin collection.
Useful in test case teardown methods.
#### Parameters
`array<string>` $names optional A list of plugins you want to remove.
#### Returns
`void`
### requires() public
```
requires(): list<ExecutionOrderDependency>
```
Returns a list of normalized dependency names, class::method.
This list can differ from the raw dependencies as the resolver has no need for the [!][shallow]clone prefix that is filtered out during normalization.
#### Returns
`list<ExecutionOrderDependency>`
### resetCount() public static
```
resetCount(): void
```
Reset the assertion counter.
#### Returns
`void`
### returnArgument() public static
```
returnArgument(int $argumentIndex): ReturnArgumentStub
```
#### Parameters
`int` $argumentIndex #### Returns
`ReturnArgumentStub`
### returnCallback() public static
```
returnCallback(mixed $callback): ReturnCallbackStub
```
#### Parameters
$callback #### Returns
`ReturnCallbackStub`
### returnSelf() public static
```
returnSelf(): ReturnSelfStub
```
Returns the current object.
This method is useful when mocking a fluent interface.
#### Returns
`ReturnSelfStub`
### returnValue() public static
```
returnValue(mixed $value): ReturnStub
```
#### Parameters
$value #### Returns
`ReturnStub`
### returnValueMap() public static
```
returnValueMap(array $valueMap): ReturnValueMapStub
```
#### Parameters
`array` $valueMap #### Returns
`ReturnValueMapStub`
### run() public
```
run(TestResult $result = null): TestResult
```
Runs the test case and collects the results in a TestResult object. If no TestResult object is passed a new one will be created.
#### Parameters
`TestResult` $result optional #### Returns
`TestResult`
#### Throws
`SebastianBergmann\CodeCoverage\InvalidArgumentException`
`SebastianBergmann\CodeCoverage\UnintentionallyCoveredCodeException`
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`CodeCoverageException`
`UtilException`
### runBare() public
```
runBare(): void
```
#### Returns
`void`
#### Throws
`Throwable`
### runTest() protected
```
runTest()
```
Override to run the test and assert its state.
#### Throws
`SebastianBergmann\ObjectEnumerator\InvalidArgumentException`
`AssertionFailedError`
`Exception`
`ExpectationFailedException`
`Throwable`
### session() public
```
session(array $data): void
```
Sets session data.
This method lets you configure the session data you want to be used for requests that follow. The session state is reset in each tearDown().
You can call this method multiple times to append into the current state.
#### Parameters
`array` $data The session data to use.
#### Returns
`void`
### setAppNamespace() public static
```
setAppNamespace(string $appNamespace = 'TestApp'): string|null
```
Set the app namespace
#### Parameters
`string` $appNamespace optional The app namespace, defaults to "TestApp".
#### Returns
`string|null`
### setBackupGlobals() public
```
setBackupGlobals(?bool $backupGlobals): void
```
#### Parameters
`?bool` $backupGlobals #### Returns
`void`
### setBackupStaticAttributes() public
```
setBackupStaticAttributes(?bool $backupStaticAttributes): void
```
#### Parameters
`?bool` $backupStaticAttributes #### Returns
`void`
### setBeStrictAboutChangesToGlobalState() public
```
setBeStrictAboutChangesToGlobalState(?bool $beStrictAboutChangesToGlobalState): void
```
#### Parameters
`?bool` $beStrictAboutChangesToGlobalState #### Returns
`void`
### setDependencies() public
```
setDependencies(list<ExecutionOrderDependency> $dependencies): void
```
#### Parameters
`list<ExecutionOrderDependency>` $dependencies #### Returns
`void`
### setDependencyInput() public
```
setDependencyInput(array $dependencyInput): void
```
#### Parameters
`array` $dependencyInput #### Returns
`void`
### setGroups() public
```
setGroups(array $groups): void
```
#### Parameters
`array` $groups #### Returns
`void`
### setInIsolation() public
```
setInIsolation(bool $inIsolation): void
```
#### Parameters
`bool` $inIsolation #### Returns
`void`
### setLocale() protected
```
setLocale(mixed ...$args): void
```
This method is a wrapper for the setlocale() function that automatically resets the locale to its original value after the test is run.
#### Parameters
...$args #### Returns
`void`
#### Throws
`Exception`
### setName() public
```
setName(string $name): void
```
#### Parameters
`string` $name #### Returns
`void`
### setOutputCallback() public
```
setOutputCallback(callable $callback): void
```
#### Parameters
`callable` $callback #### Returns
`void`
### setPreserveGlobalState() public
```
setPreserveGlobalState(bool $preserveGlobalState): void
```
#### Parameters
`bool` $preserveGlobalState #### Returns
`void`
### setRegisterMockObjectsFromTestArgumentsRecursively() public
```
setRegisterMockObjectsFromTestArgumentsRecursively(bool $flag): void
```
#### Parameters
`bool` $flag #### Returns
`void`
### setResult() public
```
setResult(mixed $result): void
```
#### Parameters
$result #### Returns
`void`
### setRunClassInSeparateProcess() public
```
setRunClassInSeparateProcess(bool $runClassInSeparateProcess): void
```
#### Parameters
`bool` $runClassInSeparateProcess #### Returns
`void`
### setRunTestInSeparateProcess() public
```
setRunTestInSeparateProcess(bool $runTestInSeparateProcess): void
```
#### Parameters
`bool` $runTestInSeparateProcess #### Returns
`void`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
### setTestResultObject() public
```
setTestResultObject(TestResult $result): void
```
#### Parameters
`TestResult` $result #### Returns
`void`
### setUnlockedFields() public
```
setUnlockedFields(array<string> $unlockedFields = []): void
```
Set list of fields that are excluded from field validation.
#### Parameters
`array<string>` $unlockedFields optional List of fields that are excluded from field validation.
#### Returns
`void`
### setUp() protected
```
setUp(): void
```
Setup the test case, backup the static object values so they can be restored. Specifically backs up the contents of Configure and paths in App if they have not already been backed up.
#### Returns
`void`
### setUpBeforeClass() public static
```
setUpBeforeClass(): void
```
This method is called before the first test of this test class is run.
#### Returns
`void`
### setupFixtures() protected
```
setupFixtures(): void
```
Initialized and loads any use fixtures.
#### Returns
`void`
### skipIf() public
```
skipIf(bool $shouldSkip, string $message = ''): bool
```
Overrides SimpleTestCase::skipIf to provide a boolean return value
#### Parameters
`bool` $shouldSkip Whether the test should be skipped.
`string` $message optional The message to display.
#### Returns
`bool`
### skipUnless() protected
```
skipUnless(bool $condition, string $message = ''): bool
```
Compatibility function for skipping.
#### Parameters
`bool` $condition Condition to trigger skipping
`string` $message optional Message for skip
#### Returns
`bool`
### sortId() public
```
sortId(): string
```
#### Returns
`string`
### stringContains() public static
```
stringContains(string $string, bool $case = true): StringContains
```
#### Parameters
`string` $string `bool` $case optional #### Returns
`StringContains`
### stringEndsWith() public static
```
stringEndsWith(string $suffix): StringEndsWith
```
#### Parameters
`string` $suffix #### Returns
`StringEndsWith`
### stringStartsWith() public static
```
stringStartsWith(mixed $prefix): StringStartsWith
```
#### Parameters
$prefix #### Returns
`StringStartsWith`
### tearDown() protected
```
tearDown(): void
```
teardown any static object changes and restore them.
#### Returns
`void`
### tearDownAfterClass() public static
```
tearDownAfterClass(): void
```
This method is called after the last test of this test class is run.
#### Returns
`void`
### teardownFixtures() protected
```
teardownFixtures(): void
```
Unloads any use fixtures.
#### Returns
`void`
### throwException() public static
```
throwException(Throwable $exception): ExceptionStub
```
#### Parameters
`Throwable` $exception #### Returns
`ExceptionStub`
### toString() public
```
toString(): string
```
Returns a string representation of the test case.
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`Exception`
### useHttpServer() public
```
useHttpServer(bool $enable): void
```
No-op method.
#### Parameters
`bool` $enable Unused.
#### Returns
`void`
### usesDataProvider() public
```
usesDataProvider(): bool
```
#### Returns
`bool`
### viewVariable() public
```
viewVariable(string $name): mixed
```
Fetches a view variable by name.
If the view variable does not exist, null will be returned.
#### Parameters
`string` $name The view variable to get.
#### Returns
`mixed`
### withErrorReporting() public
```
withErrorReporting(int $errorLevel, callable $callable): void
```
Helper method for tests that needs to use error\_reporting()
#### Parameters
`int` $errorLevel value of error\_reporting() that needs to use
`callable` $callable callable function that will receive asserts
#### Returns
`void`
Property Detail
---------------
### $\_appArgs protected
The customized application constructor arguments.
#### Type
`array|null`
### $\_appClass protected
The customized application class name.
#### Type
`string|null`
### $\_configure protected
Configure values to restore at end of test.
#### Type
`array`
### $\_controller protected
The controller used in the last request.
#### Type
`Cake\Controller\Controller|null`
### $\_cookie protected
Cookie data to use in the next request.
#### Type
`array`
### $\_cookieEncryptionKey protected
#### Type
`string|null`
### $\_csrfKeyName protected
The name that will be used when retrieving the csrf token.
#### Type
`string`
### $\_csrfToken protected
Boolean flag for whether the request should have a CSRF token added.
#### Type
`bool`
### $\_exception protected
The exception being thrown if the case.
#### Type
`Throwable|null`
### $\_flashMessages protected
Stored flash messages before render
#### Type
`array`
### $\_layoutName protected
The last rendered layout
#### Type
`string`
### $\_request protected
The data used to build the next request.
#### Type
`array`
### $\_requestSession protected
The session instance from the last request
#### Type
`Cake\Http\Session`
### $\_response protected
The response for the most recent request.
#### Type
`Psr\Http\Message\ResponseInterface|null`
### $\_retainFlashMessages protected
Boolean flag for whether the request should re-store flash messages
#### Type
`bool`
### $\_securityToken protected
Boolean flag for whether the request should have a SecurityComponent token added.
#### Type
`bool`
### $\_session protected
Session data to use in the next request.
#### Type
`array`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $\_unlockedFields protected
List of fields that are excluded from field validation.
#### Type
`array<string>`
### $\_validCiphers protected
Valid cipher names for encrypted cookies.
#### Type
`array<string>`
### $\_viewName protected
The last rendered view
#### Type
`string`
### $autoFixtures public deprecated
By default, all fixtures attached to this class will be truncated and reloaded after each test. Set this to false to handle manually
#### Type
`bool`
### $backupGlobals protected
#### Type
`?bool`
### $backupGlobalsBlacklist protected deprecated
#### Type
`string[]`
### $backupGlobalsExcludeList protected
#### Type
`string[]`
### $backupStaticAttributes protected
#### Type
`bool`
### $backupStaticAttributesBlacklist protected deprecated
#### Type
`array<string, array<int, string>>`
### $backupStaticAttributesExcludeList protected
#### Type
`array<string, array<int, string>>`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
### $dropTables public deprecated
Control table create/drops on each test method.
If true, tables will still be dropped at the end of each test runner execution.
#### Type
`bool`
### $fixtureManager public static
The class responsible for managing the creation, loading and removing of fixtures
#### Type
`Cake\TestSuite\Fixture\FixtureManager|null`
### $fixtureStrategy protected
#### Type
`Cake\TestSuite\Fixture\FixtureStrategyInterface|null`
### $fixtures protected
Fixtures used by this test case.
#### Type
`array<string>`
### $preserveGlobalState protected
#### Type
`bool`
### $providedTests protected
#### Type
`list<ExecutionOrderDependency>`
### $runTestInSeparateProcess protected
#### Type
`bool`
| programming_docs |
cakephp Class IdentifierQuoter Class IdentifierQuoter
=======================
Contains all the logic related to quoting identifiers in a Query object
**Namespace:** [Cake\Database](namespace-cake.database)
Property Summary
----------------
* [$\_driver](#%24_driver) protected `Cake\Database\Driver` The driver instance used to do the identifier quoting
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_basicQuoter()](#_basicQuoter()) protected
A generic identifier quoting function used for various parts of the query
* ##### [\_quoteComparison()](#_quoteComparison()) protected
Quotes identifiers in expression objects implementing the field interface
* ##### [\_quoteIdentifierExpression()](#_quoteIdentifierExpression()) protected
Quotes identifiers in "order by" expression objects
* ##### [\_quoteInsert()](#_quoteInsert()) protected
Quotes the table name and columns for an insert query
* ##### [\_quoteJoins()](#_quoteJoins()) protected
Quotes both the table and alias for an array of joins as stored in a Query object
* ##### [\_quoteOrderBy()](#_quoteOrderBy()) protected
Quotes identifiers in "order by" expression objects
* ##### [\_quoteParts()](#_quoteParts()) protected
Quotes all identifiers in each of the clauses of a query
* ##### [\_quoteUpdate()](#_quoteUpdate()) protected
Quotes the table name for an update query
* ##### [quote()](#quote()) public
Iterates over each of the clauses in a query looking for identifiers and quotes them
* ##### [quoteExpression()](#quoteExpression()) public
Quotes identifiers inside expression objects
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Database\Driver $driver)
```
Constructor
#### Parameters
`Cake\Database\Driver` $driver The driver instance used to do the identifier quoting
### \_basicQuoter() protected
```
_basicQuoter(array<string, mixed> $part): array<string, mixed>
```
A generic identifier quoting function used for various parts of the query
#### Parameters
`array<string, mixed>` $part the part of the query to quote
#### Returns
`array<string, mixed>`
### \_quoteComparison() protected
```
_quoteComparison(Cake\Database\Expression\FieldInterface $expression): void
```
Quotes identifiers in expression objects implementing the field interface
#### Parameters
`Cake\Database\Expression\FieldInterface` $expression The expression to quote.
#### Returns
`void`
### \_quoteIdentifierExpression() protected
```
_quoteIdentifierExpression(Cake\Database\Expression\IdentifierExpression $expression): void
```
Quotes identifiers in "order by" expression objects
#### Parameters
`Cake\Database\Expression\IdentifierExpression` $expression The identifiers to quote.
#### Returns
`void`
### \_quoteInsert() protected
```
_quoteInsert(Cake\Database\Query $query): void
```
Quotes the table name and columns for an insert query
#### Parameters
`Cake\Database\Query` $query The insert query to quote.
#### Returns
`void`
### \_quoteJoins() protected
```
_quoteJoins(array $joins): array<string, array>
```
Quotes both the table and alias for an array of joins as stored in a Query object
#### Parameters
`array` $joins The joins to quote.
#### Returns
`array<string, array>`
### \_quoteOrderBy() protected
```
_quoteOrderBy(Cake\Database\Expression\OrderByExpression $expression): void
```
Quotes identifiers in "order by" expression objects
Strings with spaces are treated as literal expressions and will not have identifiers quoted.
#### Parameters
`Cake\Database\Expression\OrderByExpression` $expression The expression to quote.
#### Returns
`void`
### \_quoteParts() protected
```
_quoteParts(Cake\Database\Query $query): void
```
Quotes all identifiers in each of the clauses of a query
#### Parameters
`Cake\Database\Query` $query The query to quote.
#### Returns
`void`
### \_quoteUpdate() protected
```
_quoteUpdate(Cake\Database\Query $query): void
```
Quotes the table name for an update query
#### Parameters
`Cake\Database\Query` $query The update query to quote.
#### Returns
`void`
### quote() public
```
quote(Cake\Database\Query $query): Cake\Database\Query
```
Iterates over each of the clauses in a query looking for identifiers and quotes them
#### Parameters
`Cake\Database\Query` $query The query to have its identifiers quoted
#### Returns
`Cake\Database\Query`
### quoteExpression() public
```
quoteExpression(Cake\Database\ExpressionInterface $expression): void
```
Quotes identifiers inside expression objects
#### Parameters
`Cake\Database\ExpressionInterface` $expression The expression object to walk and quote.
#### Returns
`void`
Property Detail
---------------
### $\_driver protected
The driver instance used to do the identifier quoting
#### Type
`Cake\Database\Driver`
cakephp Class HasMany Class HasMany
==============
Represents an N - 1 relationship where the target side of the relationship will have one or multiple records per each one in the source side.
An example of a HasMany association would be Author has many Articles.
**Namespace:** [Cake\ORM\Association](namespace-cake.orm.association)
Constants
---------
* `string` **MANY\_TO\_MANY**
```
'manyToMany'
```
Association type for many to many associations.
* `string` **MANY\_TO\_ONE**
```
'manyToOne'
```
Association type for many to one associations.
* `string` **ONE\_TO\_MANY**
```
'oneToMany'
```
Association type for one to many associations.
* `string` **ONE\_TO\_ONE**
```
'oneToOne'
```
Association type for one to one associations.
* `string` **SAVE\_APPEND**
```
'append'
```
Saving strategy that will only append to the links set
* `string` **SAVE\_REPLACE**
```
'replace'
```
Saving strategy that will replace the links with the provided set
* `string` **STRATEGY\_JOIN**
```
'join'
```
Strategy name to use joins for fetching associated records
* `string` **STRATEGY\_SELECT**
```
'select'
```
Strategy name to use a select for fetching associated records
* `string` **STRATEGY\_SUBQUERY**
```
'subquery'
```
Strategy name to use a subquery for fetching associated records
Property Summary
----------------
* [$\_bindingKey](#%24_bindingKey) protected `array<string>|string|null` The field name in the owning side table that is used to match with the foreignKey
* [$\_cascadeCallbacks](#%24_cascadeCallbacks) protected `bool` Whether cascaded deletes should also fire callbacks.
* [$\_className](#%24_className) protected `string` The class name of the target table object
* [$\_conditions](#%24_conditions) protected `Closure|array` A list of conditions to be always included when fetching records from the target association
* [$\_dependent](#%24_dependent) protected `bool` Whether the records on the target table are dependent on the source table, often used to indicate that records should be removed if the owning record in the source table is deleted.
* [$\_finder](#%24_finder) protected `array|string` The default finder name to use for fetching rows from the target table With array value, finder name and default options are allowed.
* [$\_foreignKey](#%24_foreignKey) protected `array<string>|string` The name of the field representing the foreign key to the table to load
* [$\_joinType](#%24_joinType) protected `string` The type of join to be used when adding the association to a query
* [$\_name](#%24_name) protected `string` Name given to the association, it usually represents the alias assigned to the target associated table
* [$\_propertyName](#%24_propertyName) protected `string` The property name that should be filled with data from the target table in the source table record.
* [$\_saveStrategy](#%24_saveStrategy) protected `string` Saving strategy to be used by this association
* [$\_sort](#%24_sort) protected `mixed` Order in which target records should be returned
* [$\_sourceTable](#%24_sourceTable) protected `Cake\ORM\Table` Source table instance
* [$\_strategy](#%24_strategy) protected `string` The strategy name to be used to fetch associated records.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$\_targetTable](#%24_targetTable) protected `Cake\ORM\Table` Target table instance
* [$\_validStrategies](#%24_validStrategies) protected `array<string>` Valid strategies for this type of association
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
Method Summary
--------------
* ##### [\_\_call()](#__call()) public
Proxies method calls to the target table.
* ##### [\_\_construct()](#__construct()) public
Constructor. Subclasses can override \_options function to get the original list of passed options if expecting any other special key
* ##### [\_\_get()](#__get()) public
Proxies property retrieval to the target table. This is handy for getting this association's associations
* ##### [\_\_isset()](#__isset()) public
Proxies the isset call to the target table. This is handy to check if the target table has another association with the passed name
* ##### [\_appendFields()](#_appendFields()) protected
Helper function used to conditionally append fields to the select clause of a query from the fields found in another query object.
* ##### [\_appendNotMatching()](#_appendNotMatching()) protected
Conditionally adds a condition to the passed Query that will make it find records where there is no match with this association.
* ##### [\_bindNewAssociations()](#_bindNewAssociations()) protected
Applies all attachable associations to `$query` out of the containments found in the `$surrogate` query.
* ##### [\_camelize()](#_camelize()) protected
Creates a camelized version of $name
* ##### [\_dispatchBeforeFind()](#_dispatchBeforeFind()) protected
Triggers beforeFind on the target table for the query this association is attaching to
* ##### [\_entityName()](#_entityName()) protected
Creates the proper entity name (singular) for the specified name
* ##### [\_extractFinder()](#_extractFinder()) protected
Helper method to infer the requested finder and its options.
* ##### [\_fixtureName()](#_fixtureName()) protected
Creates a fixture name
* ##### [\_foreignKeyAcceptsNull()](#_foreignKeyAcceptsNull()) protected
Checks the nullable flag of the foreign key
* ##### [\_formatAssociationResults()](#_formatAssociationResults()) protected
Adds a formatter function to the passed `$query` if the `$surrogate` query declares any other formatter. Since the `$surrogate` query correspond to the associated target table, the resulting formatter will be the result of applying the surrogate formatters to only the property corresponding to such table.
* ##### [\_joinCondition()](#_joinCondition()) protected
Returns a single or multiple conditions to be appended to the generated join clause for getting the results on the target table.
* ##### [\_modelKey()](#_modelKey()) protected
Creates the proper underscored model key for associations
* ##### [\_modelNameFromKey()](#_modelNameFromKey()) protected
Creates the proper model name from a foreign key
* ##### [\_options()](#_options()) protected
Parse extra options passed in the constructor.
* ##### [\_pluginNamespace()](#_pluginNamespace()) protected
Return plugin's namespace
* ##### [\_pluginPath()](#_pluginPath()) protected
Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
* ##### [\_pluralHumanName()](#_pluralHumanName()) protected
Creates the plural human name used in views
* ##### [\_propertyName()](#_propertyName()) protected
Returns default property name based on association name.
* ##### [\_saveTarget()](#_saveTarget()) protected
Persists each of the entities into the target table and creates links between the parent entity and each one of the saved target entities.
* ##### [\_singularHumanName()](#_singularHumanName()) protected
Creates the singular human name used in views
* ##### [\_singularName()](#_singularName()) protected
Creates the singular name for use in views.
* ##### [\_unlink()](#_unlink()) protected
Deletes/sets null the related objects matching $conditions.
* ##### [\_unlinkAssociated()](#_unlinkAssociated()) protected
Deletes/sets null the related objects according to the dependency between source and targets and foreign key nullability. Skips deleting records present in $remainingEntities
* ##### [\_variableName()](#_variableName()) protected
Creates the plural variable name for views
* ##### [attachTo()](#attachTo()) public
Alters a Query object to include the associated target table data in the final result
* ##### [canBeJoined()](#canBeJoined()) public
Whether this association can be expressed directly in a query join
* ##### [cascadeDelete()](#cascadeDelete()) public
Handles cascading a delete from an associated model.
* ##### [defaultRowValue()](#defaultRowValue()) public
Returns a modified row after appending a property for this association with the default empty value according to whether the association was joined or fetched externally.
* ##### [deleteAll()](#deleteAll()) public
Proxies the delete operation to the target table's deleteAll method
* ##### [eagerLoader()](#eagerLoader()) public
Eager loads a list of records in the target table that are related to another set of records in the source table. Source records can be specified in two ways: first one is by passing a Query object setup to find on the source table and the other way is by explicitly passing an array of primary key values from the source table.
* ##### [exists()](#exists()) public
Proxies the operation to the target table's exists method after appending the default conditions for this association
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [find()](#find()) public
Proxies the finding operation to the target table's find method and modifies the query accordingly based of this association configuration
* ##### [getBindingKey()](#getBindingKey()) public
Gets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
* ##### [getCascadeCallbacks()](#getCascadeCallbacks()) public
Gets whether cascaded deletes should also fire callbacks.
* ##### [getClassName()](#getClassName()) public
Gets the class name of the target table object.
* ##### [getConditions()](#getConditions()) public
Gets a list of conditions to be always included when fetching records from the target association.
* ##### [getDependent()](#getDependent()) public
Sets whether the records on the target table are dependent on the source table.
* ##### [getFinder()](#getFinder()) public
Gets the default finder to use for fetching rows from the target table.
* ##### [getForeignKey()](#getForeignKey()) public
Gets the name of the field representing the foreign key to the source table.
* ##### [getJoinType()](#getJoinType()) public
Gets the type of join to be used when adding the association to a query.
* ##### [getName()](#getName()) public
Gets the name for this association, usually the alias assigned to the target associated table
* ##### [getProperty()](#getProperty()) public
Gets the property name that should be filled with data from the target table in the source table record.
* ##### [getSaveStrategy()](#getSaveStrategy()) public
Gets the strategy that should be used for saving.
* ##### [getSort()](#getSort()) public
Gets the sort order in which target records should be returned.
* ##### [getSource()](#getSource()) public
Gets the table instance for the source side of the association.
* ##### [getStrategy()](#getStrategy()) public
Gets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [getTarget()](#getTarget()) public
Gets the table instance for the target side of the association.
* ##### [isOwningSide()](#isOwningSide()) public
Returns whether the passed table is the owning side for this association. This means that rows in the 'target' table would miss important or required information if the row in 'source' did not exist.
* ##### [link()](#link()) public
Associates the source entity to each of the target entities provided. When using this method, all entities in `$targetEntities` will be appended to the source entity's property corresponding to this association object.
* ##### [replace()](#replace()) public
Replaces existing association links between the source entity and the target with the ones passed. This method does a smart cleanup, links that are already persisted and present in `$targetEntities` will not be deleted, new links will be created for the passed target entities that are not already in the database and the rest will be removed.
* ##### [requiresKeys()](#requiresKeys()) public
Returns true if the eager loading process will require a set of the owning table's binding keys in order to use them as a filter in the finder query.
* ##### [saveAssociated()](#saveAssociated()) public
Takes an entity from the source table and looks if there is a field matching the property name for this association. The found entity will be saved on the target table for this association by passing supplied `$options`
* ##### [setBindingKey()](#setBindingKey()) public
Sets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
* ##### [setCascadeCallbacks()](#setCascadeCallbacks()) public
Sets whether cascaded deletes should also fire callbacks.
* ##### [setClassName()](#setClassName()) public
Sets the class name of the target table object.
* ##### [setConditions()](#setConditions()) public
Sets a list of conditions to be always included when fetching records from the target association.
* ##### [setDependent()](#setDependent()) public
Sets whether the records on the target table are dependent on the source table.
* ##### [setFinder()](#setFinder()) public
Sets the default finder to use for fetching rows from the target table.
* ##### [setForeignKey()](#setForeignKey()) public
Sets the name of the field representing the foreign key to the target table.
* ##### [setJoinType()](#setJoinType()) public
Sets the type of join to be used when adding the association to a query.
* ##### [setName()](#setName()) public deprecated
Sets the name for this association, usually the alias assigned to the target associated table
* ##### [setProperty()](#setProperty()) public
Sets the property name that should be filled with data from the target table in the source table record.
* ##### [setSaveStrategy()](#setSaveStrategy()) public
Sets the strategy that should be used for saving.
* ##### [setSort()](#setSort()) public
Sets the sort order in which target records should be returned.
* ##### [setSource()](#setSource()) public
Sets the table instance for the source side of the association.
* ##### [setStrategy()](#setStrategy()) public
Sets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
* ##### [setTarget()](#setTarget()) public
Sets the table instance for the target side of the association.
* ##### [transformRow()](#transformRow()) public
Correctly nests a result row associated values into the correct array keys inside the source results.
* ##### [type()](#type()) public
Get the relationship type.
* ##### [unlink()](#unlink()) public
Removes all links between the passed source entity and each of the provided target entities. This method assumes that all passed objects are already persisted in the database and that each of them contain a primary key value.
* ##### [updateAll()](#updateAll()) public
Proxies the update operation to the target table's updateAll method
Method Detail
-------------
### \_\_call() public
```
__call(string $method, array $argument): mixed
```
Proxies method calls to the target table.
#### Parameters
`string` $method name of the method to be invoked
`array` $argument List of arguments passed to the function
#### Returns
`mixed`
#### Throws
`BadMethodCallException`
### \_\_construct() public
```
__construct(string $alias, array<string, mixed> $options = [])
```
Constructor. Subclasses can override \_options function to get the original list of passed options if expecting any other special key
#### Parameters
`string` $alias The name given to the association
`array<string, mixed>` $options optional A list of properties to be set on this object
### \_\_get() public
```
__get(string $property): Cake\ORM\Association
```
Proxies property retrieval to the target table. This is handy for getting this association's associations
#### Parameters
`string` $property the property name
#### Returns
`Cake\ORM\Association`
#### Throws
`RuntimeException`
if no association with such name exists ### \_\_isset() public
```
__isset(string $property): bool
```
Proxies the isset call to the target table. This is handy to check if the target table has another association with the passed name
#### Parameters
`string` $property the property name
#### Returns
`bool`
### \_appendFields() protected
```
_appendFields(Cake\ORM\Query $query, Cake\ORM\Query $surrogate, array<string, mixed> $options): void
```
Helper function used to conditionally append fields to the select clause of a query from the fields found in another query object.
#### Parameters
`Cake\ORM\Query` $query the query that will get the fields appended to
`Cake\ORM\Query` $surrogate the query having the fields to be copied from
`array<string, mixed>` $options options passed to the method `attachTo`
#### Returns
`void`
### \_appendNotMatching() protected
```
_appendNotMatching(Cake\ORM\Query $query, array<string, mixed> $options): void
```
Conditionally adds a condition to the passed Query that will make it find records where there is no match with this association.
#### Parameters
`Cake\ORM\Query` $query The query to modify
`array<string, mixed>` $options Options array containing the `negateMatch` key.
#### Returns
`void`
### \_bindNewAssociations() protected
```
_bindNewAssociations(Cake\ORM\Query $query, Cake\ORM\Query $surrogate, array<string, mixed> $options): void
```
Applies all attachable associations to `$query` out of the containments found in the `$surrogate` query.
Copies all contained associations from the `$surrogate` query into the passed `$query`. Containments are altered so that they respect the associations chain from which they originated.
#### Parameters
`Cake\ORM\Query` $query the query that will get the associations attached to
`Cake\ORM\Query` $surrogate the query having the containments to be attached
`array<string, mixed>` $options options passed to the method `attachTo`
#### Returns
`void`
### \_camelize() protected
```
_camelize(string $name): string
```
Creates a camelized version of $name
#### Parameters
`string` $name name
#### Returns
`string`
### \_dispatchBeforeFind() protected
```
_dispatchBeforeFind(Cake\ORM\Query $query): void
```
Triggers beforeFind on the target table for the query this association is attaching to
#### Parameters
`Cake\ORM\Query` $query the query this association is attaching itself to
#### Returns
`void`
### \_entityName() protected
```
_entityName(string $name): string
```
Creates the proper entity name (singular) for the specified name
#### Parameters
`string` $name Name
#### Returns
`string`
### \_extractFinder() protected
```
_extractFinder(array|string $finderData): array
```
Helper method to infer the requested finder and its options.
Returns the inferred options from the finder $type.
### Examples:
The following will call the finder 'translations' with the value of the finder as its options: $query->contain(['Comments' => ['finder' => ['translations']]]); $query->contain(['Comments' => ['finder' => ['translations' => []]]]); $query->contain(['Comments' => ['finder' => ['translations' => ['locales' => ['en\_US']]]]]);
#### Parameters
`array|string` $finderData The finder name or an array having the name as key and options as value.
#### Returns
`array`
### \_fixtureName() protected
```
_fixtureName(string $name): string
```
Creates a fixture name
#### Parameters
`string` $name Model class name
#### Returns
`string`
### \_foreignKeyAcceptsNull() protected
```
_foreignKeyAcceptsNull(Cake\ORM\Table $table, array $properties): bool
```
Checks the nullable flag of the foreign key
#### Parameters
`Cake\ORM\Table` $table the table containing the foreign key
`array` $properties the list of fields that compose the foreign key
#### Returns
`bool`
### \_formatAssociationResults() protected
```
_formatAssociationResults(Cake\ORM\Query $query, Cake\ORM\Query $surrogate, array<string, mixed> $options): void
```
Adds a formatter function to the passed `$query` if the `$surrogate` query declares any other formatter. Since the `$surrogate` query correspond to the associated target table, the resulting formatter will be the result of applying the surrogate formatters to only the property corresponding to such table.
#### Parameters
`Cake\ORM\Query` $query the query that will get the formatter applied to
`Cake\ORM\Query` $surrogate the query having formatters for the associated target table.
`array<string, mixed>` $options options passed to the method `attachTo`
#### Returns
`void`
### \_joinCondition() protected
```
_joinCondition(array<string, mixed> $options): array
```
Returns a single or multiple conditions to be appended to the generated join clause for getting the results on the target table.
#### Parameters
`array<string, mixed>` $options list of options passed to attachTo method
#### Returns
`array`
#### Throws
`RuntimeException`
if the number of columns in the foreignKey do not match the number of columns in the source table primaryKey ### \_modelKey() protected
```
_modelKey(string $name): string
```
Creates the proper underscored model key for associations
If the input contains a dot, assume that the right side is the real table name.
#### Parameters
`string` $name Model class name
#### Returns
`string`
### \_modelNameFromKey() protected
```
_modelNameFromKey(string $key): string
```
Creates the proper model name from a foreign key
#### Parameters
`string` $key Foreign key
#### Returns
`string`
### \_options() protected
```
_options(array<string, mixed> $options): void
```
Parse extra options passed in the constructor.
#### Parameters
`array<string, mixed>` $options original list of options passed in constructor
#### Returns
`void`
### \_pluginNamespace() protected
```
_pluginNamespace(string $pluginName): string
```
Return plugin's namespace
#### Parameters
`string` $pluginName Plugin name
#### Returns
`string`
### \_pluginPath() protected
```
_pluginPath(string $pluginName): string
```
Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
#### Parameters
`string` $pluginName Name of the plugin you want ie. DebugKit
#### Returns
`string`
### \_pluralHumanName() protected
```
_pluralHumanName(string $name): string
```
Creates the plural human name used in views
#### Parameters
`string` $name Controller name
#### Returns
`string`
### \_propertyName() protected
```
_propertyName(): string
```
Returns default property name based on association name.
#### Returns
`string`
### \_saveTarget() protected
```
_saveTarget(array $foreignKeyReference, Cake\Datasource\EntityInterface $parentEntity, array $entities, array<string, mixed> $options): bool
```
Persists each of the entities into the target table and creates links between the parent entity and each one of the saved target entities.
#### Parameters
`array` $foreignKeyReference The foreign key reference defining the link between the target entity, and the parent entity.
`Cake\Datasource\EntityInterface` $parentEntity The source entity containing the target entities to be saved.
`array` $entities list of entities to persist in target table and to link to the parent entity
`array<string, mixed>` $options list of options accepted by `Table::save()`.
#### Returns
`bool`
### \_singularHumanName() protected
```
_singularHumanName(string $name): string
```
Creates the singular human name used in views
#### Parameters
`string` $name Controller name
#### Returns
`string`
### \_singularName() protected
```
_singularName(string $name): string
```
Creates the singular name for use in views.
#### Parameters
`string` $name Name to use
#### Returns
`string`
### \_unlink() protected
```
_unlink(array $foreignKey, Cake\ORM\Table $target, array $conditions = [], array<string, mixed> $options = []): bool
```
Deletes/sets null the related objects matching $conditions.
The action which is taken depends on the dependency between source and targets and also on foreign key nullability.
#### Parameters
`array` $foreignKey array of foreign key properties
`Cake\ORM\Table` $target The associated table
`array` $conditions optional The conditions that specifies what are the objects to be unlinked
`array<string, mixed>` $options optional list of options accepted by `Table::delete()`
#### Returns
`bool`
### \_unlinkAssociated() protected
```
_unlinkAssociated(array $foreignKeyReference, Cake\Datasource\EntityInterface $entity, Cake\ORM\Table $target, iterable $remainingEntities = [], array<string, mixed> $options = []): bool
```
Deletes/sets null the related objects according to the dependency between source and targets and foreign key nullability. Skips deleting records present in $remainingEntities
#### Parameters
`array` $foreignKeyReference The foreign key reference defining the link between the target entity, and the parent entity.
`Cake\Datasource\EntityInterface` $entity the entity which should have its associated entities unassigned
`Cake\ORM\Table` $target The associated table
`iterable` $remainingEntities optional Entities that should not be deleted
`array<string, mixed>` $options optional list of options accepted by `Table::delete()`
#### Returns
`bool`
### \_variableName() protected
```
_variableName(string $name): string
```
Creates the plural variable name for views
#### Parameters
`string` $name Name to use
#### Returns
`string`
### attachTo() public
```
attachTo(Cake\ORM\Query $query, array<string, mixed> $options = []): void
```
Alters a Query object to include the associated target table data in the final result
The options array accept the following keys:
* includeFields: Whether to include target model fields in the result or not
* foreignKey: The name of the field to use as foreign key, if false none will be used
* conditions: array with a list of conditions to filter the join with, this will be merged with any conditions originally configured for this association
* fields: a list of fields in the target table to include in the result
* aliasPath: A dot separated string representing the path of association names followed from the passed query main table to this association.
* propertyPath: A dot separated string representing the path of association properties to be followed from the passed query main entity to this association
* joinType: The SQL join type to use in the query.
* negateMatch: Will append a condition to the passed query for excluding matches. with this association.
#### Parameters
`Cake\ORM\Query` $query the query to be altered to include the target table data
`array<string, mixed>` $options optional Any extra options or overrides to be taken in account
#### Returns
`void`
#### Throws
`RuntimeException`
Unable to build the query or associations. ### canBeJoined() public
```
canBeJoined(array<string, mixed> $options = []): bool
```
Whether this association can be expressed directly in a query join
#### Parameters
`array<string, mixed>` $options optional custom options key that could alter the return value
#### Returns
`bool`
### cascadeDelete() public
```
cascadeDelete(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): bool
```
Handles cascading a delete from an associated model.
Each implementing class should handle the cascaded delete as required.
#### Parameters
`Cake\Datasource\EntityInterface` $entity `array<string, mixed>` $options optional #### Returns
`bool`
### defaultRowValue() public
```
defaultRowValue(array<string, mixed> $row, bool $joined): array<string, mixed>
```
Returns a modified row after appending a property for this association with the default empty value according to whether the association was joined or fetched externally.
#### Parameters
`array<string, mixed>` $row `bool` $joined #### Returns
`array<string, mixed>`
### deleteAll() public
```
deleteAll(Cake\Database\ExpressionInterfaceClosure|array|string|null $conditions): int
```
Proxies the delete operation to the target table's deleteAll method
#### Parameters
`Cake\Database\ExpressionInterfaceClosure|array|string|null` $conditions Conditions to be used, accepts anything Query::where() can take.
#### Returns
`int`
#### See Also
\Cake\ORM\Table::deleteAll() ### eagerLoader() public
```
eagerLoader(array<string, mixed> $options): Closure
```
Eager loads a list of records in the target table that are related to another set of records in the source table. Source records can be specified in two ways: first one is by passing a Query object setup to find on the source table and the other way is by explicitly passing an array of primary key values from the source table.
The required way of passing related source records is controlled by "strategy" When the subquery strategy is used it will require a query on the source table. When using the select strategy, the list of primary keys will be used.
Returns a closure that should be run for each record returned in a specific Query. This callable will be responsible for injecting the fields that are related to each specific passed row.
Options array accepts the following keys:
* query: Query object setup to find the source table records
* keys: List of primary key values from the source table
* foreignKey: The name of the field used to relate both tables
* conditions: List of conditions to be passed to the query where() method
* sort: The direction in which the records should be returned
* fields: List of fields to select from the target table
* contain: List of related tables to eager load associated to the target table
* strategy: The name of strategy to use for finding target table records
* nestKey: The array key under which results will be found when transforming the row
#### Parameters
`array<string, mixed>` $options #### Returns
`Closure`
### exists() public
```
exists(Cake\Database\ExpressionInterfaceClosure|array|string|null $conditions): bool
```
Proxies the operation to the target table's exists method after appending the default conditions for this association
#### Parameters
`Cake\Database\ExpressionInterfaceClosure|array|string|null` $conditions The conditions to use for checking if any record matches.
#### Returns
`bool`
#### See Also
\Cake\ORM\Table::exists() ### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### find() public
```
find(array<string, mixed>|string|null $type = null, array<string, mixed> $options = []): Cake\ORM\Query
```
Proxies the finding operation to the target table's find method and modifies the query accordingly based of this association configuration
#### Parameters
`array<string, mixed>|string|null` $type optional the type of query to perform, if an array is passed, it will be interpreted as the `$options` parameter
`array<string, mixed>` $options optional The options to for the find
#### Returns
`Cake\ORM\Query`
#### See Also
\Cake\ORM\Table::find() ### getBindingKey() public
```
getBindingKey(): array<string>|string
```
Gets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
#### Returns
`array<string>|string`
### getCascadeCallbacks() public
```
getCascadeCallbacks(): bool
```
Gets whether cascaded deletes should also fire callbacks.
#### Returns
`bool`
### getClassName() public
```
getClassName(): string
```
Gets the class name of the target table object.
#### Returns
`string`
### getConditions() public
```
getConditions(): Closure|array
```
Gets a list of conditions to be always included when fetching records from the target association.
#### Returns
`Closure|array`
#### See Also
\Cake\Database\Query::where() for examples on the format of the array ### getDependent() public
```
getDependent(): bool
```
Sets whether the records on the target table are dependent on the source table.
This is primarily used to indicate that records should be removed if the owning record in the source table is deleted.
#### Returns
`bool`
### getFinder() public
```
getFinder(): array|string
```
Gets the default finder to use for fetching rows from the target table.
#### Returns
`array|string`
### getForeignKey() public
```
getForeignKey(): array<string>|string
```
Gets the name of the field representing the foreign key to the source table.
#### Returns
`array<string>|string`
### getJoinType() public
```
getJoinType(): string
```
Gets the type of join to be used when adding the association to a query.
#### Returns
`string`
### getName() public
```
getName(): string
```
Gets the name for this association, usually the alias assigned to the target associated table
#### Returns
`string`
### getProperty() public
```
getProperty(): string
```
Gets the property name that should be filled with data from the target table in the source table record.
#### Returns
`string`
### getSaveStrategy() public
```
getSaveStrategy(): string
```
Gets the strategy that should be used for saving.
#### Returns
`string`
### getSort() public
```
getSort(): mixed
```
Gets the sort order in which target records should be returned.
#### Returns
`mixed`
### getSource() public
```
getSource(): Cake\ORM\Table
```
Gets the table instance for the source side of the association.
#### Returns
`Cake\ORM\Table`
### getStrategy() public
```
getStrategy(): string
```
Gets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void.
#### Returns
`string`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### getTarget() public
```
getTarget(): Cake\ORM\Table
```
Gets the table instance for the target side of the association.
#### Returns
`Cake\ORM\Table`
### isOwningSide() public
```
isOwningSide(Cake\ORM\Table $side): bool
```
Returns whether the passed table is the owning side for this association. This means that rows in the 'target' table would miss important or required information if the row in 'source' did not exist.
#### Parameters
`Cake\ORM\Table` $side The potential Table with ownership
#### Returns
`bool`
### link() public
```
link(Cake\Datasource\EntityInterface $sourceEntity, array $targetEntities, array<string, mixed> $options = []): bool
```
Associates the source entity to each of the target entities provided. When using this method, all entities in `$targetEntities` will be appended to the source entity's property corresponding to this association object.
This method does not check link uniqueness. Changes are persisted in the database and also in the source entity.
### Example:
```
$user = $users->get(1);
$allArticles = $articles->find('all')->toArray();
$users->Articles->link($user, $allArticles);
```
`$user->get('articles')` will contain all articles in `$allArticles` after linking
#### Parameters
`Cake\Datasource\EntityInterface` $sourceEntity the row belonging to the `source` side of this association
`array` $targetEntities list of entities belonging to the `target` side of this association
`array<string, mixed>` $options optional list of options to be passed to the internal `save` call
#### Returns
`bool`
### replace() public
```
replace(Cake\Datasource\EntityInterface $sourceEntity, array $targetEntities, array<string, mixed> $options = []): bool
```
Replaces existing association links between the source entity and the target with the ones passed. This method does a smart cleanup, links that are already persisted and present in `$targetEntities` will not be deleted, new links will be created for the passed target entities that are not already in the database and the rest will be removed.
For example, if an author has many articles, such as 'article1','article 2' and 'article 3' and you pass to this method an array containing the entities for articles 'article 1' and 'article 4', only the link for 'article 1' will be kept in database, the links for 'article 2' and 'article 3' will be deleted and the link for 'article 4' will be created.
Existing links are not deleted and created again, they are either left untouched or updated.
This method does not check link uniqueness.
On success, the passed `$sourceEntity` will contain `$targetEntities` as value in the corresponding property for this association.
Additional options for new links to be saved can be passed in the third argument, check `Table::save()` for information on the accepted options.
### Example:
```
$author->articles = [$article1, $article2, $article3, $article4];
$authors->save($author);
$articles = [$article1, $article3];
$authors->getAssociation('articles')->replace($author, $articles);
```
`$author->get('articles')` will contain only `[$article1, $article3]` at the end
#### Parameters
`Cake\Datasource\EntityInterface` $sourceEntity an entity persisted in the source table for this association
`array` $targetEntities list of entities from the target table to be linked
`array<string, mixed>` $options optional list of options to be passed to the internal `save`/`delete` calls when persisting/updating new links, or deleting existing ones
#### Returns
`bool`
#### Throws
`InvalidArgumentException`
if non persisted entities are passed or if any of them is lacking a primary key value ### requiresKeys() public
```
requiresKeys(array<string, mixed> $options = []): bool
```
Returns true if the eager loading process will require a set of the owning table's binding keys in order to use them as a filter in the finder query.
#### Parameters
`array<string, mixed>` $options optional The options containing the strategy to be used.
#### Returns
`bool`
### saveAssociated() public
```
saveAssociated(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): Cake\Datasource\EntityInterface|false
```
Takes an entity from the source table and looks if there is a field matching the property name for this association. The found entity will be saved on the target table for this association by passing supplied `$options`
#### Parameters
`Cake\Datasource\EntityInterface` $entity an entity from the source table
`array<string, mixed>` $options optional options to be passed to the save method in the target table
#### Returns
`Cake\Datasource\EntityInterface|false`
#### Throws
`InvalidArgumentException`
when the association data cannot be traversed. #### See Also
\Cake\ORM\Table::save() ### setBindingKey() public
```
setBindingKey(array<string>|string $key): $this
```
Sets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
#### Parameters
`array<string>|string` $key the table field or fields to be used to link both tables together
#### Returns
`$this`
### setCascadeCallbacks() public
```
setCascadeCallbacks(bool $cascadeCallbacks): $this
```
Sets whether cascaded deletes should also fire callbacks.
#### Parameters
`bool` $cascadeCallbacks cascade callbacks switch value
#### Returns
`$this`
### setClassName() public
```
setClassName(string $className): $this
```
Sets the class name of the target table object.
#### Parameters
`string` $className Class name to set.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
In case the class name is set after the target table has been resolved, and it doesn't match the target table's class name. ### setConditions() public
```
setConditions(Closure|array $conditions): $this
```
Sets a list of conditions to be always included when fetching records from the target association.
#### Parameters
`Closure|array` $conditions list of conditions to be used
#### Returns
`$this`
#### See Also
\Cake\Database\Query::where() for examples on the format of the array ### setDependent() public
```
setDependent(bool $dependent): $this
```
Sets whether the records on the target table are dependent on the source table.
This is primarily used to indicate that records should be removed if the owning record in the source table is deleted.
If no parameters are passed the current setting is returned.
#### Parameters
`bool` $dependent Set the dependent mode. Use null to read the current state.
#### Returns
`$this`
### setFinder() public
```
setFinder(array|string $finder): $this
```
Sets the default finder to use for fetching rows from the target table.
#### Parameters
`array|string` $finder the finder name to use or array of finder name and option.
#### Returns
`$this`
### setForeignKey() public
```
setForeignKey(array<string>|string $key): $this
```
Sets the name of the field representing the foreign key to the target table.
#### Parameters
`array<string>|string` $key the key or keys to be used to link both tables together
#### Returns
`$this`
### setJoinType() public
```
setJoinType(string $type): $this
```
Sets the type of join to be used when adding the association to a query.
#### Parameters
`string` $type the join type to be used (e.g. INNER)
#### Returns
`$this`
### setName() public
```
setName(string $name): $this
```
Sets the name for this association, usually the alias assigned to the target associated table
#### Parameters
`string` $name Name to be assigned
#### Returns
`$this`
### setProperty() public
```
setProperty(string $name): $this
```
Sets the property name that should be filled with data from the target table in the source table record.
#### Parameters
`string` $name The name of the association property. Use null to read the current value.
#### Returns
`$this`
### setSaveStrategy() public
```
setSaveStrategy(string $strategy): $this
```
Sets the strategy that should be used for saving.
#### Parameters
`string` $strategy the strategy name to be used
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
if an invalid strategy name is passed ### setSort() public
```
setSort(mixed $sort): $this
```
Sets the sort order in which target records should be returned.
#### Parameters
`mixed` $sort A find() compatible order clause
#### Returns
`$this`
### setSource() public
```
setSource(Cake\ORM\Table $table): $this
```
Sets the table instance for the source side of the association.
#### Parameters
`Cake\ORM\Table` $table the instance to be assigned as source side
#### Returns
`$this`
### setStrategy() public
```
setStrategy(string $name): $this
```
Sets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void.
#### Parameters
`string` $name The strategy type. Use null to read the current value.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
When an invalid strategy is provided. ### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
### setTarget() public
```
setTarget(Cake\ORM\Table $table): $this
```
Sets the table instance for the target side of the association.
#### Parameters
`Cake\ORM\Table` $table the instance to be assigned as target side
#### Returns
`$this`
### transformRow() public
```
transformRow(array $row, string $nestKey, bool $joined, string|null $targetProperty = null): array
```
Correctly nests a result row associated values into the correct array keys inside the source results.
#### Parameters
`array` $row The row to transform
`string` $nestKey The array key under which the results for this association should be found
`bool` $joined Whether the row is a result of a direct join with this association
`string|null` $targetProperty optional The property name in the source results where the association data shuld be nested in. Will use the default one if not provided.
#### Returns
`array`
### type() public
```
type(): string
```
Get the relationship type.
#### Returns
`string`
### unlink() public
```
unlink(Cake\Datasource\EntityInterface $sourceEntity, array $targetEntities, array<string, mixed>|bool $options = []): void
```
Removes all links between the passed source entity and each of the provided target entities. This method assumes that all passed objects are already persisted in the database and that each of them contain a primary key value.
### Options
Additionally to the default options accepted by `Table::delete()`, the following keys are supported:
* cleanProperty: Whether to remove all the objects in `$targetEntities` that are stored in `$sourceEntity` (default: true)
By default this method will unset each of the entity objects stored inside the source entity.
Changes are persisted in the database and also in the source entity.
### Example:
```
$user = $users->get(1);
$user->articles = [$article1, $article2, $article3, $article4];
$users->save($user, ['Associated' => ['Articles']]);
$allArticles = [$article1, $article2, $article3];
$users->Articles->unlink($user, $allArticles);
```
`$article->get('articles')` will contain only `[$article4]` after deleting in the database
#### Parameters
`Cake\Datasource\EntityInterface` $sourceEntity an entity persisted in the source table for this association
`array` $targetEntities list of entities persisted in the target table for this association
`array<string, mixed>|bool` $options optional list of options to be passed to the internal `delete` call. If boolean it will be used a value for "cleanProperty" option.
#### Returns
`void`
#### Throws
`InvalidArgumentException`
if non persisted entities are passed or if any of them is lacking a primary key value ### updateAll() public
```
updateAll(array $fields, Cake\Database\ExpressionInterfaceClosure|array|string|null $conditions): int
```
Proxies the update operation to the target table's updateAll method
#### Parameters
`array` $fields A hash of field => new value.
`Cake\Database\ExpressionInterfaceClosure|array|string|null` $conditions Conditions to be used, accepts anything Query::where() can take.
#### Returns
`int`
#### See Also
\Cake\ORM\Table::updateAll() Property Detail
---------------
### $\_bindingKey protected
The field name in the owning side table that is used to match with the foreignKey
#### Type
`array<string>|string|null`
### $\_cascadeCallbacks protected
Whether cascaded deletes should also fire callbacks.
#### Type
`bool`
### $\_className protected
The class name of the target table object
#### Type
`string`
### $\_conditions protected
A list of conditions to be always included when fetching records from the target association
#### Type
`Closure|array`
### $\_dependent protected
Whether the records on the target table are dependent on the source table, often used to indicate that records should be removed if the owning record in the source table is deleted.
#### Type
`bool`
### $\_finder protected
The default finder name to use for fetching rows from the target table With array value, finder name and default options are allowed.
#### Type
`array|string`
### $\_foreignKey protected
The name of the field representing the foreign key to the table to load
#### Type
`array<string>|string`
### $\_joinType protected
The type of join to be used when adding the association to a query
#### Type
`string`
### $\_name protected
Name given to the association, it usually represents the alias assigned to the target associated table
#### Type
`string`
### $\_propertyName protected
The property name that should be filled with data from the target table in the source table record.
#### Type
`string`
### $\_saveStrategy protected
Saving strategy to be used by this association
#### Type
`string`
### $\_sort protected
Order in which target records should be returned
#### Type
`mixed`
### $\_sourceTable protected
Source table instance
#### Type
`Cake\ORM\Table`
### $\_strategy protected
The strategy name to be used to fetch associated records.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $\_targetTable protected
Target table instance
#### Type
`Cake\ORM\Table`
### $\_validStrategies protected
Valid strategies for this type of association
#### Type
`array<string>`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
| programming_docs |
cakephp Class PasswordHasherFactory Class PasswordHasherFactory
============================
Builds password hashing objects
**Namespace:** [Cake\Auth](namespace-cake.auth)
Method Summary
--------------
* ##### [build()](#build()) public static
Returns password hasher object out of a hasher name or a configuration array
Method Detail
-------------
### build() public static
```
build(array<string, mixed>|string $passwordHasher): Cake\Auth\AbstractPasswordHasher
```
Returns password hasher object out of a hasher name or a configuration array
#### Parameters
`array<string, mixed>|string` $passwordHasher Name of the password hasher or an array with at least the key `className` set to the name of the class to use
#### Returns
`Cake\Auth\AbstractPasswordHasher`
#### Throws
`RuntimeException`
If password hasher class not found or it does not extend {@link \Cake\Auth\AbstractPasswordHasher}
cakephp Class BodyNotRegExp Class BodyNotRegExp
====================
BodyNotRegExp
**Namespace:** [Cake\TestSuite\Constraint\Response](namespace-cake.testsuite.constraint.response)
Property Summary
----------------
* [$response](#%24response) protected `Psr\Http\Message\ResponseInterface`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_getBodyAsString()](#_getBodyAsString()) protected
Get the response body as string
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) public
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Checks assertion
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(Psr\Http\Message\ResponseInterface|null $response)
```
Constructor
#### Parameters
`Psr\Http\Message\ResponseInterface|null` $response Response
### \_getBodyAsString() protected
```
_getBodyAsString(): string
```
Get the response body as string
#### Returns
`string`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() public
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other Expected
#### Returns
`string`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks assertion
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Expected pattern
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $response protected
#### Type
`Psr\Http\Message\ResponseInterface`
cakephp Class MissingConsoleInputException Class MissingConsoleInputException
===================================
Exception class used to indicate missing console input.
**Namespace:** [Cake\Console\TestSuite](namespace-cake.console.testsuite)
Method Summary
--------------
* ##### [setQuestion()](#setQuestion()) public
Update the exception message with the question text
Method Detail
-------------
### setQuestion() public
```
setQuestion(string $question): void
```
Update the exception message with the question text
#### Parameters
`string` $question The question text.
#### Returns
`void`
cakephp Class TextHelper Class TextHelper
=================
Text helper library.
Text manipulations: Highlight, excerpt, truncate, strip of links, convert email addresses to mailto: links...
**Namespace:** [Cake\View\Helper](namespace-cake.view.helper)
**See:** \Cake\Utility\Text
**Link:** https://book.cakephp.org/4/en/views/helpers/text.html
Property Summary
----------------
* [$Html](#%24Html) public @property `Cake\View\Helper\HtmlHelper`
* [$\_View](#%24_View) protected `Cake\View\View` The View instance this helper is attached to
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this class
* [$\_engine](#%24_engine) protected `Cake\Utility\Text` Cake Utility Text instance
* [$\_helperMap](#%24_helperMap) protected `array<string, array>` A helper lookup table used to lazy load helper objects.
* [$\_placeholders](#%24_placeholders) protected `array<string, array>` An array of hashes and their contents. Used when inserting links into text.
* [$helpers](#%24helpers) protected `array` helpers
Method Summary
--------------
* ##### [\_\_call()](#__call()) public
Call methods from String utility class
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_get()](#__get()) public
Lazy loads helpers.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_confirm()](#_confirm()) protected
Returns a string to be used as onclick handler for confirm dialogs.
* ##### [\_insertPlaceHolder()](#_insertPlaceHolder()) protected
Saves the placeholder for a string, for later use. This gets around double escaping content in URL's.
* ##### [\_linkEmails()](#_linkEmails()) protected
Links email addresses
* ##### [\_linkUrls()](#_linkUrls()) protected
Replace placeholders with links.
* ##### [addClass()](#addClass()) public
Adds the given class to the element options
* ##### [autoLink()](#autoLink()) public
Convert all links and email addresses to HTML links.
* ##### [autoLinkEmails()](#autoLinkEmails()) public
Adds email links (<a href="mailto:....") to a given text.
* ##### [autoLinkUrls()](#autoLinkUrls()) public
Adds links (<a href=....) to a given text, by finding text that begins with strings like http:// and ftp://.
* ##### [autoParagraph()](#autoParagraph()) public
Formats paragraphs around given text for all line breaks
added for single line return
added for double line return
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [excerpt()](#excerpt()) public
Extracts an excerpt from the text surrounding the phrase with a number of characters on each side determined by radius.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getView()](#getView()) public
Get the view instance this helper is bound to.
* ##### [highlight()](#highlight()) public
Highlights a given phrase in a text. You can specify any expression in highlighter that may include the \1 expression to include the $phrase found.
* ##### [implementedEvents()](#implementedEvents()) public
Event listeners.
* ##### [initialize()](#initialize()) public
Constructor hook method.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [slug()](#slug()) public
Returns a string with all spaces converted to dashes (by default), characters transliterated to ASCII characters, and non word characters removed.
* ##### [tail()](#tail()) public
Truncates text starting from the end.
* ##### [toList()](#toList()) public
Creates a comma separated list where the last two items are joined with 'and', forming natural language.
* ##### [truncate()](#truncate()) public
Truncates text.
Method Detail
-------------
### \_\_call() public
```
__call(string $method, array $params): mixed
```
Call methods from String utility class
#### Parameters
`string` $method Method to invoke
`array` $params Array of params for the method.
#### Returns
`mixed`
### \_\_construct() public
```
__construct(Cake\View\View $view, array<string, mixed> $config = [])
```
Constructor
### Settings:
* `engine` Class name to use to replace String functionality. The class needs to be placed in the `Utility` directory.
#### Parameters
`Cake\View\View` $view the view object the helper is attached to.
`array<string, mixed>` $config optional Settings array Settings array
#### Throws
`Cake\Core\Exception\CakeException`
when the engine class could not be found. ### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): Cake\View\Helper|null|void
```
Lazy loads helpers.
#### Parameters
`string` $name Name of the property being accessed.
#### Returns
`Cake\View\Helper|null|void`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_confirm() protected
```
_confirm(string $okCode, string $cancelCode): string
```
Returns a string to be used as onclick handler for confirm dialogs.
#### Parameters
`string` $okCode Code to be executed after user chose 'OK'
`string` $cancelCode Code to be executed after user chose 'Cancel'
#### Returns
`string`
### \_insertPlaceHolder() protected
```
_insertPlaceHolder(array $matches): string
```
Saves the placeholder for a string, for later use. This gets around double escaping content in URL's.
#### Parameters
`array` $matches An array of regexp matches.
#### Returns
`string`
### \_linkEmails() protected
```
_linkEmails(string $text, array<string, mixed> $options): string
```
Links email addresses
#### Parameters
`string` $text The text to operate on
`array<string, mixed>` $options An array of options to use for the HTML.
#### Returns
`string`
#### See Also
\Cake\View\Helper\TextHelper::autoLinkEmails() ### \_linkUrls() protected
```
_linkUrls(string $text, array<string, mixed> $htmlOptions): string
```
Replace placeholders with links.
#### Parameters
`string` $text The text to operate on.
`array<string, mixed>` $htmlOptions The options for the generated links.
#### Returns
`string`
### addClass() public
```
addClass(array<string, mixed> $options, string $class, string $key = 'class'): array<string, mixed>
```
Adds the given class to the element options
#### Parameters
`array<string, mixed>` $options Array options/attributes to add a class to
`string` $class The class name being added.
`string` $key optional the key to use for class. Defaults to `'class'`.
#### Returns
`array<string, mixed>`
### autoLink() public
```
autoLink(string $text, array<string, mixed> $options = []): string
```
Convert all links and email addresses to HTML links.
### Options
* `escape` Control HTML escaping of input. Defaults to true.
#### Parameters
`string` $text Text
`array<string, mixed>` $options optional Array of HTML options, and options listed above.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/text.html#linking-both-urls-and-email-addresses
### autoLinkEmails() public
```
autoLinkEmails(string $text, array<string, mixed> $options = []): string
```
Adds email links (<a href="mailto:....") to a given text.
### Options
* `escape` Control HTML escaping of input. Defaults to true.
#### Parameters
`string` $text Text
`array<string, mixed>` $options optional Array of HTML options, and options listed above.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/text.html#linking-email-addresses
### autoLinkUrls() public
```
autoLinkUrls(string $text, array<string, mixed> $options = []): string
```
Adds links (<a href=....) to a given text, by finding text that begins with strings like http:// and ftp://.
### Options
* `escape` Control HTML escaping of input. Defaults to true.
#### Parameters
`string` $text Text
`array<string, mixed>` $options optional Array of HTML options, and options listed above.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/text.html#linking-urls
### autoParagraph() public
```
autoParagraph(string|null $text): string
```
Formats paragraphs around given text for all line breaks
added for single line return
added for double line return
#### Parameters
`string|null` $text Text
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/views/helpers/text.html#converting-text-into-paragraphs
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### excerpt() public
```
excerpt(string $text, string $phrase, int $radius = 100, string $ending = '...'): string
```
Extracts an excerpt from the text surrounding the phrase with a number of characters on each side determined by radius.
#### Parameters
`string` $text String to search the phrase in
`string` $phrase Phrase that will be searched for
`int` $radius optional The amount of characters that will be returned on each side of the founded phrase
`string` $ending optional Ending that will be appended
#### Returns
`string`
#### See Also
\Cake\Utility\Text::excerpt() #### Links
https://book.cakephp.org/4/en/views/helpers/text.html#extracting-an-excerpt
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getView() public
```
getView(): Cake\View\View
```
Get the view instance this helper is bound to.
#### Returns
`Cake\View\View`
### highlight() public
```
highlight(string $text, string $phrase, array<string, mixed> $options = []): string
```
Highlights a given phrase in a text. You can specify any expression in highlighter that may include the \1 expression to include the $phrase found.
#### Parameters
`string` $text Text to search the phrase in
`string` $phrase The phrase that will be searched
`array<string, mixed>` $options optional An array of HTML attributes and options.
#### Returns
`string`
#### See Also
\Cake\Utility\Text::highlight() #### Links
https://book.cakephp.org/4/en/views/helpers/text.html#highlighting-substrings
### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Event listeners.
By defining one of the callback methods a helper is assumed to be interested in the related event.
Override this method if you need to add non-conventional event listeners. Or if you want helpers to listen to non-standard events.
#### Returns
`array<string, mixed>`
### initialize() public
```
initialize(array<string, mixed> $config): void
```
Constructor hook method.
Implement this method to avoid having to overwrite the constructor and call parent.
#### Parameters
`array<string, mixed>` $config The configuration settings provided to this helper.
#### Returns
`void`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### slug() public
```
slug(string $string, array<string, mixed>|string $options = []): string
```
Returns a string with all spaces converted to dashes (by default), characters transliterated to ASCII characters, and non word characters removed.
### Options:
* `replacement`: Replacement string. Default '-'.
* `transliteratorId`: A valid transliterator id string. If `null` (default) the transliterator (identifier) set via `Text::setTransliteratorId()` or `Text::setTransliterator()` will be used. If `false` no transliteration will be done, only non-words will be removed.
* `preserve`: Specific non-word character to preserve. Default `null`. For e.g. this option can be set to '.' to generate clean file names.
#### Parameters
`string` $string the string you want to slug
`array<string, mixed>|string` $options optional If string it will be used as replacement character or an array of options.
#### Returns
`string`
#### See Also
\Cake\Utility\Text::setTransliterator()
\Cake\Utility\Text::setTransliteratorId() ### tail() public
```
tail(string $text, int $length = 100, array<string, mixed> $options = []): string
```
Truncates text starting from the end.
Cuts a string to the length of $length and replaces the first characters with the ellipsis if the text is longer than length.
### Options:
* `ellipsis` Will be used as Beginning and prepended to the trimmed string
* `exact` If false, $text will not be cut mid-word
#### Parameters
`string` $text String to truncate.
`int` $length optional Length of returned string, including ellipsis.
`array<string, mixed>` $options optional An array of HTML attributes and options.
#### Returns
`string`
#### See Also
\Cake\Utility\Text::tail() #### Links
https://book.cakephp.org/4/en/views/helpers/text.html#truncating-the-tail-of-a-string
### toList() public
```
toList(array<string> $list, string|null $and = null, string $separator = ', '): string
```
Creates a comma separated list where the last two items are joined with 'and', forming natural language.
#### Parameters
`array<string>` $list The list to be joined.
`string|null` $and optional The word used to join the last and second last items together with. Defaults to 'and'.
`string` $separator optional The separator used to join all the other items together. Defaults to ', '.
#### Returns
`string`
#### See Also
\Cake\Utility\Text::toList() #### Links
https://book.cakephp.org/4/en/views/helpers/text.html#converting-an-array-to-sentence-form
### truncate() public
```
truncate(string $text, int $length = 100, array<string, mixed> $options = []): string
```
Truncates text.
Cuts a string to the length of $length and replaces the last characters with the ellipsis if the text is longer than length.
### Options:
* `ellipsis` Will be used as Ending and appended to the trimmed string
* `exact` If false, $text will not be cut mid-word
* `html` If true, HTML tags would be handled correctly
#### Parameters
`string` $text String to truncate.
`int` $length optional Length of returned string, including ellipsis.
`array<string, mixed>` $options optional An array of HTML attributes and options.
#### Returns
`string`
#### See Also
\Cake\Utility\Text::truncate() #### Links
https://book.cakephp.org/4/en/views/helpers/text.html#truncating-text
Property Detail
---------------
### $Html public @property
#### Type
`Cake\View\Helper\HtmlHelper`
### $\_View protected
The View instance this helper is attached to
#### Type
`Cake\View\View`
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this class
#### Type
`array<string, mixed>`
### $\_engine protected
Cake Utility Text instance
#### Type
`Cake\Utility\Text`
### $\_helperMap protected
A helper lookup table used to lazy load helper objects.
#### Type
`array<string, array>`
### $\_placeholders protected
An array of hashes and their contents. Used when inserting links into text.
#### Type
`array<string, array>`
### $helpers protected
helpers
#### Type
`array`
| programming_docs |
cakephp Class MissingCellTemplateException Class MissingCellTemplateException
===================================
Used when a template file for a cell cannot be found.
**Namespace:** [Cake\View\Exception](namespace-cake.view.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
* [$filename](#%24filename) protected `string`
* [$name](#%24name) protected `string`
* [$paths](#%24paths) protected `array<string>`
* [$templateName](#%24templateName) protected `string|null`
* [$type](#%24type) protected `string`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [formatMessage()](#formatMessage()) public
Get the formatted exception message.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(string $name, string $file, array<string> $paths = [], int|null $code = null, Throwable|null $previous = null)
```
Constructor
#### Parameters
`string` $name The Cell name that is missing a view.
`string` $file The view filename.
`array<string>` $paths optional The path list that template could not be found in.
`int|null` $code optional The code of the error.
`Throwable|null` $previous optional the previous exception.
### formatMessage() public
```
formatMessage(): string
```
Get the formatted exception message.
#### Returns
`string`
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
### $filename protected
#### Type
`string`
### $name protected
#### Type
`string`
### $paths protected
#### Type
`array<string>`
### $templateName protected
#### Type
`string|null`
### $type protected
#### Type
`string`
cakephp Class AuthComponent Class AuthComponent
====================
Authentication control component class.
Binds access control with user authentication and session management.
**Namespace:** [Cake\Controller\Component](namespace-cake.controller.component)
**Deprecated:** 4.0.0 Use the cakephp/authentication and cakephp/authorization plugins instead.
**See:** https://github.com/cakephp/authentication
**See:** https://github.com/cakephp/authorization
**Link:** https://book.cakephp.org/4/en/controllers/components/authentication.html
Constants
---------
* `string` **ALL**
```
'all'
```
Constant for 'all'
* `string` **QUERY\_STRING\_REDIRECT**
```
'redirect'
```
The query string key used for remembering the referred page when getting redirected to login.
Property Summary
----------------
* [$Flash](#%24Flash) public @property `Cake\Controller\Component\FlashComponent`
* [$RequestHandler](#%24RequestHandler) public @property `Cake\Controller\Component\RequestHandlerComponent`
* [$\_authenticateObjects](#%24_authenticateObjects) protected `arrayCake\Auth\BaseAuthenticate>` Objects that will be used for authentication checks.
* [$\_authenticationProvider](#%24_authenticationProvider) protected `Cake\Auth\BaseAuthenticate|null` The instance of the Authenticate provider that was used for successfully logging in the current user after calling `login()` in the same request
* [$\_authorizationProvider](#%24_authorizationProvider) protected `Cake\Auth\BaseAuthorize|null` The instance of the Authorize provider that was used to grant access to the current user to the URL they are requesting.
* [$\_authorizeObjects](#%24_authorizeObjects) protected `arrayCake\Auth\BaseAuthorize>` Objects that will be used for authorization checks.
* [$\_componentMap](#%24_componentMap) protected `array<string, array>` A component lookup table used to lazy load component objects.
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config
* [$\_eventClass](#%24_eventClass) protected `string` Default class name for new event objects.
* [$\_eventManager](#%24_eventManager) protected `Cake\Event\EventManagerInterface|null` Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
* [$\_registry](#%24_registry) protected `Cake\Controller\ComponentRegistry` Component registry class used to lazy load components.
* [$\_storage](#%24_storage) protected `Cake\Auth\Storage\StorageInterface|null` Storage object.
* [$allowedActions](#%24allowedActions) public `array<string>` Controller actions for which user validation is not required.
* [$components](#%24components) protected `array` Other components utilized by AuthComponent
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_get()](#__get()) public
Magic accessor for backward compatibility for property `$sessionKey`.
* ##### [\_\_set()](#__set()) public
Magic setter for backward compatibility for property `$sessionKey`.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_getUrlToRedirectBackTo()](#_getUrlToRedirectBackTo()) protected
Returns the URL to redirect back to or / if not possible.
* ##### [\_getUser()](#_getUser()) protected
Similar to AuthComponent::user() except if user is not found in configured storage, connected authentication objects will have their getUser() methods called.
* ##### [\_isAllowed()](#_isAllowed()) protected
Checks whether current action is accessible without authentication.
* ##### [\_isLoginAction()](#_isLoginAction()) protected
Normalizes config `loginAction` and checks if current request URL is same as login action.
* ##### [\_loginActionRedirectUrl()](#_loginActionRedirectUrl()) protected
Returns the URL of the login action to redirect to.
* ##### [\_setDefaults()](#_setDefaults()) protected
Sets defaults for configs.
* ##### [\_unauthenticated()](#_unauthenticated()) protected
Handles unauthenticated access attempt. First the `unauthenticated()` method of the last authenticator in the chain will be called. The authenticator can handle sending response or redirection as appropriate and return `true` to indicate no further action is necessary. If authenticator returns null this method redirects user to login action.
* ##### [\_unauthorized()](#_unauthorized()) protected
Handle unauthorized access attempt
* ##### [allow()](#allow()) public
Takes a list of actions in the current controller for which authentication is not required, or no parameters to allow all actions.
* ##### [authCheck()](#authCheck()) public
Main execution method, handles initial authentication check and redirection of invalid users.
* ##### [authenticationProvider()](#authenticationProvider()) public
If login was called during this request and the user was successfully authenticated, this function will return the instance of the authentication object that was used for logging the user in.
* ##### [authorizationProvider()](#authorizationProvider()) public
If there was any authorization processing for the current request, this function will return the instance of the Authorization object that granted access to the user to the current address.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [constructAuthenticate()](#constructAuthenticate()) public
Loads the configured authentication objects.
* ##### [constructAuthorize()](#constructAuthorize()) public
Loads the authorization objects configured.
* ##### [deny()](#deny()) public
Removes items from the list of allowed/no authentication required actions.
* ##### [dispatchEvent()](#dispatchEvent()) public
Wrapper for creating and dispatching events.
* ##### [flash()](#flash()) public
Set a flash message. Uses the Flash component with values from `flash` config.
* ##### [getAuthenticate()](#getAuthenticate()) public
Getter for authenticate objects. Will return a particular authenticate object.
* ##### [getAuthorize()](#getAuthorize()) public
Getter for authorize objects. Will return a particular authorize object.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getController()](#getController()) public
Get the controller this component is bound to.
* ##### [getEventManager()](#getEventManager()) public
Returns the Cake\Event\EventManager manager instance for this object.
* ##### [identify()](#identify()) public
Use the configured authentication adapters, and attempt to identify the user by credentials contained in $request.
* ##### [implementedEvents()](#implementedEvents()) public
Events supported by this component.
* ##### [initialize()](#initialize()) public
Initialize properties.
* ##### [isAuthorized()](#isAuthorized()) public
Check if the provided user is authorized for the request.
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [logout()](#logout()) public
Log a user out.
* ##### [redirectUrl()](#redirectUrl()) public
Get the URL a user should be redirected to upon login.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setEventManager()](#setEventManager()) public
Returns the Cake\Event\EventManagerInterface instance for this object.
* ##### [setUser()](#setUser()) public
Set provided user info to storage as logged in user.
* ##### [startup()](#startup()) public
Callback for Controller.startup event.
* ##### [storage()](#storage()) public
Get/set user record storage object.
* ##### [user()](#user()) public
Get the current user from storage.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Controller\ComponentRegistry $registry, array<string, mixed> $config = [])
```
Constructor
#### Parameters
`Cake\Controller\ComponentRegistry` $registry A component registry this component can use to lazy load its components.
`array<string, mixed>` $config optional Array of configuration settings.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): mixed
```
Magic accessor for backward compatibility for property `$sessionKey`.
#### Parameters
`string` $name Property name
#### Returns
`mixed`
### \_\_set() public
```
__set(string $name, mixed $value): void
```
Magic setter for backward compatibility for property `$sessionKey`.
#### Parameters
`string` $name Property name.
`mixed` $value Value to set.
#### Returns
`void`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_getUrlToRedirectBackTo() protected
```
_getUrlToRedirectBackTo(): string
```
Returns the URL to redirect back to or / if not possible.
This method takes the referrer into account if the request is not of type GET.
#### Returns
`string`
### \_getUser() protected
```
_getUser(): bool
```
Similar to AuthComponent::user() except if user is not found in configured storage, connected authentication objects will have their getUser() methods called.
This lets stateless authentication methods function correctly.
#### Returns
`bool`
### \_isAllowed() protected
```
_isAllowed(Cake\Controller\Controller $controller): bool
```
Checks whether current action is accessible without authentication.
#### Parameters
`Cake\Controller\Controller` $controller A reference to the instantiating controller object
#### Returns
`bool`
### \_isLoginAction() protected
```
_isLoginAction(Cake\Controller\Controller $controller): bool
```
Normalizes config `loginAction` and checks if current request URL is same as login action.
#### Parameters
`Cake\Controller\Controller` $controller A reference to the controller object.
#### Returns
`bool`
### \_loginActionRedirectUrl() protected
```
_loginActionRedirectUrl(): array|string
```
Returns the URL of the login action to redirect to.
This includes the redirect query string if applicable.
#### Returns
`array|string`
### \_setDefaults() protected
```
_setDefaults(): void
```
Sets defaults for configs.
#### Returns
`void`
### \_unauthenticated() protected
```
_unauthenticated(Cake\Controller\Controller $controller): Cake\Http\Response|null
```
Handles unauthenticated access attempt. First the `unauthenticated()` method of the last authenticator in the chain will be called. The authenticator can handle sending response or redirection as appropriate and return `true` to indicate no further action is necessary. If authenticator returns null this method redirects user to login action.
#### Parameters
`Cake\Controller\Controller` $controller A reference to the controller object.
#### Returns
`Cake\Http\Response|null`
#### Throws
`Cake\Core\Exception\CakeException`
### \_unauthorized() protected
```
_unauthorized(Cake\Controller\Controller $controller): Cake\Http\Response|null
```
Handle unauthorized access attempt
#### Parameters
`Cake\Controller\Controller` $controller A reference to the controller object
#### Returns
`Cake\Http\Response|null`
#### Throws
`Cake\Http\Exception\ForbiddenException`
### allow() public
```
allow(array<string>|string|null $actions = null): void
```
Takes a list of actions in the current controller for which authentication is not required, or no parameters to allow all actions.
You can use allow with either an array or a simple string.
```
$this->Auth->allow('view');
$this->Auth->allow(['edit', 'add']);
```
or to allow all actions
```
$this->Auth->allow();
```
#### Parameters
`array<string>|string|null` $actions optional Controller action name or array of actions
#### Returns
`void`
#### Links
https://book.cakephp.org/4/en/controllers/components/authentication.html#making-actions-public
### authCheck() public
```
authCheck(Cake\Event\EventInterface $event): Cake\Http\Response|null
```
Main execution method, handles initial authentication check and redirection of invalid users.
The auth check is done when event name is same as the one configured in `checkAuthIn` config.
#### Parameters
`Cake\Event\EventInterface` $event Event instance.
#### Returns
`Cake\Http\Response|null`
#### Throws
`ReflectionException`
### authenticationProvider() public
```
authenticationProvider(): Cake\Auth\BaseAuthenticate|null
```
If login was called during this request and the user was successfully authenticated, this function will return the instance of the authentication object that was used for logging the user in.
#### Returns
`Cake\Auth\BaseAuthenticate|null`
### authorizationProvider() public
```
authorizationProvider(): Cake\Auth\BaseAuthorize|null
```
If there was any authorization processing for the current request, this function will return the instance of the Authorization object that granted access to the user to the current address.
#### Returns
`Cake\Auth\BaseAuthorize|null`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### constructAuthenticate() public
```
constructAuthenticate(): array<string, object>|null
```
Loads the configured authentication objects.
#### Returns
`array<string, object>|null`
#### Throws
`Cake\Core\Exception\CakeException`
### constructAuthorize() public
```
constructAuthorize(): array|null
```
Loads the authorization objects configured.
#### Returns
`array|null`
#### Throws
`Cake\Core\Exception\CakeException`
### deny() public
```
deny(array<string>|string|null $actions = null): void
```
Removes items from the list of allowed/no authentication required actions.
You can use deny with either an array or a simple string.
```
$this->Auth->deny('view');
$this->Auth->deny(['edit', 'add']);
```
or
```
$this->Auth->deny();
```
to remove all items from the allowed list
#### Parameters
`array<string>|string|null` $actions optional Controller action name or array of actions
#### Returns
`void`
#### See Also
\Cake\Controller\Component\AuthComponent::allow() #### Links
https://book.cakephp.org/4/en/controllers/components/authentication.html#making-actions-require-authorization
### dispatchEvent() public
```
dispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\EventInterface
```
Wrapper for creating and dispatching events.
Returns a dispatched event.
#### Parameters
`string` $name Name of the event.
`array|null` $data optional Any value you wish to be transported with this event to it can be read by listeners.
`object|null` $subject optional The object that this event applies to ($this by default).
#### Returns
`Cake\Event\EventInterface`
### flash() public
```
flash(string|false $message): void
```
Set a flash message. Uses the Flash component with values from `flash` config.
#### Parameters
`string|false` $message The message to set. False to skip.
#### Returns
`void`
### getAuthenticate() public
```
getAuthenticate(string $alias): Cake\Auth\BaseAuthenticate|null
```
Getter for authenticate objects. Will return a particular authenticate object.
#### Parameters
`string` $alias Alias for the authenticate object
#### Returns
`Cake\Auth\BaseAuthenticate|null`
### getAuthorize() public
```
getAuthorize(string $alias): Cake\Auth\BaseAuthorize|null
```
Getter for authorize objects. Will return a particular authorize object.
#### Parameters
`string` $alias Alias for the authorize object
#### Returns
`Cake\Auth\BaseAuthorize|null`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getController() public
```
getController(): Cake\Controller\Controller
```
Get the controller this component is bound to.
#### Returns
`Cake\Controller\Controller`
### getEventManager() public
```
getEventManager(): Cake\Event\EventManagerInterface
```
Returns the Cake\Event\EventManager manager 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.
#### Returns
`Cake\Event\EventManagerInterface`
### identify() public
```
identify(): array|false
```
Use the configured authentication adapters, and attempt to identify the user by credentials contained in $request.
Triggers `Auth.afterIdentify` event which the authenticate classes can listen to.
#### Returns
`array|false`
### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Events supported by this component.
Uses Conventions to map controller events to standard component callback method names. By defining one of the callback methods a component is assumed to be interested in the related event.
Override this method if you need to add non-conventional event listeners. Or if you want components to listen to non-standard events.
#### Returns
`array<string, mixed>`
### initialize() public
```
initialize(array<string, mixed> $config): void
```
Initialize properties.
Implement this method to avoid having to overwrite the constructor and call parent.
#### Parameters
`array<string, mixed>` $config The config data.
#### Returns
`void`
### isAuthorized() public
```
isAuthorized(ArrayAccess|array|null $user = null, Cake\Http\ServerRequest|null $request = null): bool
```
Check if the provided user is authorized for the request.
Uses the configured Authorization adapters to check whether a user is authorized. Each adapter will be checked in sequence, if any of them return true, then the user will be authorized for the request.
#### Parameters
`ArrayAccess|array|null` $user optional The user to check the authorization of. If empty the user fetched from storage will be used.
`Cake\Http\ServerRequest|null` $request optional The request to authenticate for. If empty, the current request will be used.
#### Returns
`bool`
### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### logout() public
```
logout(): string
```
Log a user out.
Returns the logout action to redirect to. Triggers the `Auth.logout` event which the authenticate classes can listen for and perform custom logout logic.
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/controllers/components/authentication.html#logging-users-out
### redirectUrl() public
```
redirectUrl(array|string|null $url = null): string
```
Get the URL a user should be redirected to upon login.
Pass a URL in to set the destination a user should be redirected to upon logging in.
If no parameter is passed, gets the authentication redirect URL. The URL returned is as per following rules:
* Returns the normalized redirect URL from storage if it is present and for the same domain the current app is running on.
+ If there is no URL returned from storage and there is a config `loginRedirect`, the `loginRedirect` value is returned.
+ If there is no session and no `loginRedirect`, / is returned.
#### Parameters
`array|string|null` $url optional Optional URL to write as the login redirect URL.
#### Returns
`string`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setEventManager() public
```
setEventManager(Cake\Event\EventManagerInterface $eventManager): $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.
#### Parameters
`Cake\Event\EventManagerInterface` $eventManager the eventManager to set
#### Returns
`$this`
### setUser() public
```
setUser(ArrayAccess|array $user): void
```
Set provided user info to storage as logged in user.
The storage class is configured using `storage` config key or passing instance to AuthComponent::storage().
#### Parameters
`ArrayAccess|array` $user User data.
#### Returns
`void`
#### Links
https://book.cakephp.org/4/en/controllers/components/authentication.html#identifying-users-and-logging-them-in
### startup() public
```
startup(Cake\Event\EventInterface $event): Cake\Http\Response|null
```
Callback for Controller.startup event.
#### Parameters
`Cake\Event\EventInterface` $event Event instance.
#### Returns
`Cake\Http\Response|null`
### storage() public
```
storage(Cake\Auth\Storage\StorageInterface|null $storage = null): Cake\Auth\Storage\StorageInterface|null
```
Get/set user record storage object.
#### Parameters
`Cake\Auth\Storage\StorageInterface|null` $storage optional Sets provided object as storage or if null returns configured storage object.
#### Returns
`Cake\Auth\Storage\StorageInterface|null`
### user() public
```
user(string|null $key = null): mixed|null
```
Get the current user from storage.
#### Parameters
`string|null` $key optional Field to retrieve. Leave null to get entire User record.
#### Returns
`mixed|null`
#### Links
https://book.cakephp.org/4/en/controllers/components/authentication.html#accessing-the-logged-in-user
Property Detail
---------------
### $Flash public @property
#### Type
`Cake\Controller\Component\FlashComponent`
### $RequestHandler public @property
#### Type
`Cake\Controller\Component\RequestHandlerComponent`
### $\_authenticateObjects protected
Objects that will be used for authentication checks.
#### Type
`arrayCake\Auth\BaseAuthenticate>`
### $\_authenticationProvider protected
The instance of the Authenticate provider that was used for successfully logging in the current user after calling `login()` in the same request
#### Type
`Cake\Auth\BaseAuthenticate|null`
### $\_authorizationProvider protected
The instance of the Authorize provider that was used to grant access to the current user to the URL they are requesting.
#### Type
`Cake\Auth\BaseAuthorize|null`
### $\_authorizeObjects protected
Objects that will be used for authorization checks.
#### Type
`arrayCake\Auth\BaseAuthorize>`
### $\_componentMap protected
A component lookup table used to lazy load component objects.
#### Type
`array<string, array>`
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config
* `authenticate` - An array of authentication objects to use for authenticating users. You can configure multiple adapters and they will be checked sequentially when users are identified.
```
$this->Auth->setConfig('authenticate', [
'Form' => [
'userModel' => 'Users.Users'
]
]);
```
Using the class name without 'Authenticate' as the key, you can pass in an array of config for each authentication object. Additionally, you can define config that should be set to all authentications objects using the 'all' key:
```
$this->Auth->setConfig('authenticate', [
AuthComponent::ALL => [
'userModel' => 'Users.Users',
'scope' => ['Users.active' => 1]
],
'Form',
'Basic'
]);
```
* `authorize` - An array of authorization objects to use for authorizing users. You can configure multiple adapters and they will be checked sequentially when authorization checks are done.
```
$this->Auth->setConfig('authorize', [
'Crud' => [
'actionPath' => 'controllers/'
]
]);
```
Using the class name without 'Authorize' as the key, you can pass in an array of config for each authorization object. Additionally you can define config that should be set to all authorization objects using the AuthComponent::ALL key:
```
$this->Auth->setConfig('authorize', [
AuthComponent::ALL => [
'actionPath' => 'controllers/'
],
'Crud',
'CustomAuth'
]);
```
* `flash` - Settings to use when Auth needs to do a flash message with FlashComponent::set(). Available keys are:
* `key` - The message domain to use for flashes generated by this component, defaults to 'auth'.
+ `element` - Flash element to use, defaults to 'default'.
+ `params` - The array of additional params to use, defaults to ['class' => 'error']
* `loginAction` - A URL (defined as a string or array) to the controller action that handles logins. Defaults to `/users/login`.
* `loginRedirect` - Normally, if a user is redirected to the `loginAction` page, the location they were redirected from will be stored in the session so that they can be redirected back after a successful login. If this session value is not set, redirectUrl() method will return the URL specified in `loginRedirect`.
* `logoutRedirect` - The default action to redirect to after the user is logged out. While AuthComponent does not handle post-logout redirection, a redirect URL will be returned from `AuthComponent::logout()`. Defaults to `loginAction`.
* `authError` - Error to display when user attempts to access an object or action to which they do not have access.
* `unauthorizedRedirect` - Controls handling of unauthorized access.
* For default value `true` unauthorized user is redirected to the referrer URL or `$loginRedirect` or '/'.
+ If set to a string or array the value is used as a URL to redirect to.
+ If set to false a `ForbiddenException` exception is thrown instead of redirecting.
* `storage` - Storage class to use for persisting user record. When using stateless authenticator you should set this to 'Memory'. Defaults to 'Session'.
* `checkAuthIn` - Name of event for which initial auth checks should be done. Defaults to 'Controller.startup'. You can set it to 'Controller.initialize' if you want the check to be done before controller's beforeFilter() is run.
#### Type
`array<string, mixed>`
### $\_eventClass protected
Default class name for new event objects.
#### Type
`string`
### $\_eventManager protected
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
#### Type
`Cake\Event\EventManagerInterface|null`
### $\_registry protected
Component registry class used to lazy load components.
#### Type
`Cake\Controller\ComponentRegistry`
### $\_storage protected
Storage object.
#### Type
`Cake\Auth\Storage\StorageInterface|null`
### $allowedActions public
Controller actions for which user validation is not required.
#### Type
`array<string>`
### $components protected
Other components utilized by AuthComponent
#### Type
`array`
| programming_docs |
cakephp Trait ConventionsTrait Trait ConventionsTrait
=======================
Provides methods that allow other classes access to conventions based inflections.
**Namespace:** [Cake\Core](namespace-cake.core)
Method Summary
--------------
* ##### [\_camelize()](#_camelize()) protected
Creates a camelized version of $name
* ##### [\_entityName()](#_entityName()) protected
Creates the proper entity name (singular) for the specified name
* ##### [\_fixtureName()](#_fixtureName()) protected
Creates a fixture name
* ##### [\_modelKey()](#_modelKey()) protected
Creates the proper underscored model key for associations
* ##### [\_modelNameFromKey()](#_modelNameFromKey()) protected
Creates the proper model name from a foreign key
* ##### [\_pluginNamespace()](#_pluginNamespace()) protected
Return plugin's namespace
* ##### [\_pluginPath()](#_pluginPath()) protected
Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
* ##### [\_pluralHumanName()](#_pluralHumanName()) protected
Creates the plural human name used in views
* ##### [\_singularHumanName()](#_singularHumanName()) protected
Creates the singular human name used in views
* ##### [\_singularName()](#_singularName()) protected
Creates the singular name for use in views.
* ##### [\_variableName()](#_variableName()) protected
Creates the plural variable name for views
Method Detail
-------------
### \_camelize() protected
```
_camelize(string $name): string
```
Creates a camelized version of $name
#### Parameters
`string` $name name
#### Returns
`string`
### \_entityName() protected
```
_entityName(string $name): string
```
Creates the proper entity name (singular) for the specified name
#### Parameters
`string` $name Name
#### Returns
`string`
### \_fixtureName() protected
```
_fixtureName(string $name): string
```
Creates a fixture name
#### Parameters
`string` $name Model class name
#### Returns
`string`
### \_modelKey() protected
```
_modelKey(string $name): string
```
Creates the proper underscored model key for associations
If the input contains a dot, assume that the right side is the real table name.
#### Parameters
`string` $name Model class name
#### Returns
`string`
### \_modelNameFromKey() protected
```
_modelNameFromKey(string $key): string
```
Creates the proper model name from a foreign key
#### Parameters
`string` $key Foreign key
#### Returns
`string`
### \_pluginNamespace() protected
```
_pluginNamespace(string $pluginName): string
```
Return plugin's namespace
#### Parameters
`string` $pluginName Plugin name
#### Returns
`string`
### \_pluginPath() protected
```
_pluginPath(string $pluginName): string
```
Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
#### Parameters
`string` $pluginName Name of the plugin you want ie. DebugKit
#### Returns
`string`
### \_pluralHumanName() protected
```
_pluralHumanName(string $name): string
```
Creates the plural human name used in views
#### Parameters
`string` $name Controller name
#### Returns
`string`
### \_singularHumanName() protected
```
_singularHumanName(string $name): string
```
Creates the singular human name used in views
#### Parameters
`string` $name Controller name
#### Returns
`string`
### \_singularName() protected
```
_singularName(string $name): string
```
Creates the singular name for use in views.
#### Parameters
`string` $name Name to use
#### Returns
`string`
### \_variableName() protected
```
_variableName(string $name): string
```
Creates the plural variable name for views
#### Parameters
`string` $name Name to use
#### Returns
`string`
cakephp Class MailTransport Class MailTransport
====================
Send mail using mail() function
**Namespace:** [Cake\Mailer\Transport](namespace-cake.mailer.transport)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this class
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_mail()](#_mail()) protected
Wraps internal function mail() and throws exception instead of errors if anything goes wrong
* ##### [checkRecipient()](#checkRecipient()) protected
Check that at least one destination header is set.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [send()](#send()) public
Send mail
* ##### [setConfig()](#setConfig()) public
Sets the config.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Constructor
#### Parameters
`array<string, mixed>` $config optional Configuration options.
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_mail() protected
```
_mail(string $to, string $subject, string $message, string $headers = '', string $params = ''): void
```
Wraps internal function mail() and throws exception instead of errors if anything goes wrong
#### Parameters
`string` $to email's recipient
`string` $subject email's subject
`string` $message email's body
`string` $headers optional email's custom headers
`string` $params optional additional params for sending email
#### Returns
`void`
#### Throws
`Cake\Network\Exception\SocketException`
if mail could not be sent ### checkRecipient() protected
```
checkRecipient(Cake\Mailer\Message $message): void
```
Check that at least one destination header is set.
#### Parameters
`Cake\Mailer\Message` $message Message instance.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
If at least one of to, cc or bcc is not specified. ### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### send() public
```
send(Cake\Mailer\Message $message): array
```
Send mail
#### Parameters
`Cake\Mailer\Message` $message #### Returns
`array`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this class
#### Type
`array<string, mixed>`
cakephp Interface RepositoryInterface Interface RepositoryInterface
==============================
Describes the methods that any class representing a data storage should comply with.
**Namespace:** [Cake\Datasource](namespace-cake.datasource)
Method Summary
--------------
* ##### [delete()](#delete()) public
Delete a single entity.
* ##### [deleteAll()](#deleteAll()) public
Deletes all records matching the provided conditions.
* ##### [exists()](#exists()) public
Returns true if there is any record in this repository matching the specified conditions.
* ##### [find()](#find()) public
Creates a new Query for this repository and applies some defaults based on the type of search that was selected.
* ##### [get()](#get()) public
Returns a single record after finding it by its primary key, if no record is found this method throws an exception.
* ##### [getAlias()](#getAlias()) public
Returns the repository alias.
* ##### [getRegistryAlias()](#getRegistryAlias()) public
Returns the table registry key used to create this table instance.
* ##### [hasField()](#hasField()) public
Test to see if a Repository has a specific field/column.
* ##### [newEmptyEntity()](#newEmptyEntity()) public
This creates a new entity object.
* ##### [newEntities()](#newEntities()) public
Create a list of entities + associated entities from an array.
* ##### [newEntity()](#newEntity()) public
Create a new entity + associated entities from an array.
* ##### [patchEntities()](#patchEntities()) public
Merges each of the elements passed in `$data` into the entities found in `$entities` respecting the accessible fields configured on the entities. Merging is done by matching the primary key in each of the elements in `$data` and `$entities`.
* ##### [patchEntity()](#patchEntity()) public
Merges the passed `$data` into `$entity` respecting the accessible fields configured on the entity. Returns the same entity after being altered.
* ##### [query()](#query()) public
Creates a new Query instance for this repository
* ##### [save()](#save()) public
Persists an entity based on the fields that are marked as dirty and returns the same entity after a successful save or false in case of any error.
* ##### [setAlias()](#setAlias()) public
Sets the repository alias.
* ##### [setRegistryAlias()](#setRegistryAlias()) public
Sets the table registry key used to create this table instance.
* ##### [updateAll()](#updateAll()) public
Update all matching records.
Method Detail
-------------
### delete() public
```
delete(Cake\Datasource\EntityInterface $entity, ArrayAccess|array $options = []): bool
```
Delete a single entity.
Deletes an entity and possibly related associations from the database based on the 'dependent' option used when defining the association.
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity to remove.
`ArrayAccess|array` $options optional The options for the delete.
#### Returns
`bool`
### deleteAll() public
```
deleteAll(mixed $conditions): int
```
Deletes all records matching the provided conditions.
This method will *not* trigger beforeDelete/afterDelete events. If you need those first load a collection of records and delete them.
This method will *not* execute on associations' `cascade` attribute. You should use database foreign keys + ON CASCADE rules if you need cascading deletes combined with this method.
#### Parameters
`mixed` $conditions Conditions to be used, accepts anything Query::where() can take.
#### Returns
`int`
#### See Also
\Cake\Datasource\RepositoryInterface::delete() ### exists() public
```
exists(array $conditions): bool
```
Returns true if there is any record in this repository matching the specified conditions.
#### Parameters
`array` $conditions list of conditions to pass to the query
#### Returns
`bool`
### find() public
```
find(string $type = 'all', array<string, mixed> $options = []): Cake\Datasource\QueryInterface
```
Creates a new Query for this repository and applies some defaults based on the type of search that was selected.
#### Parameters
`string` $type optional the type of query to perform
`array<string, mixed>` $options optional An array that will be passed to Query::applyOptions()
#### Returns
`Cake\Datasource\QueryInterface`
### get() public
```
get(mixed $primaryKey, array<string, mixed> $options = []): Cake\Datasource\EntityInterface
```
Returns a single record after finding it by its primary key, if no record is found this method throws an exception.
### Example:
```
$id = 10;
$article = $articles->get($id);
$article = $articles->get($id, ['contain' => ['Comments]]);
```
#### Parameters
`mixed` $primaryKey primary key value to find
`array<string, mixed>` $options optional options accepted by `Table::find()`
#### Returns
`Cake\Datasource\EntityInterface`
#### Throws
`Cake\Datasource\Exception\RecordNotFoundException`
if the record with such id could not be found #### See Also
\Cake\Datasource\RepositoryInterface::find() ### getAlias() public
```
getAlias(): string
```
Returns the repository alias.
#### Returns
`string`
### getRegistryAlias() public
```
getRegistryAlias(): string
```
Returns the table registry key used to create this table instance.
#### Returns
`string`
### hasField() public
```
hasField(string $field): bool
```
Test to see if a Repository has a specific field/column.
#### Parameters
`string` $field The field to check for.
#### Returns
`bool`
### newEmptyEntity() public
```
newEmptyEntity(): Cake\Datasource\EntityInterface
```
This creates a new entity object.
Careful: This does not trigger any field validation. This entity can be persisted without validation error as empty record. Always patch in required fields before saving.
#### Returns
`Cake\Datasource\EntityInterface`
### newEntities() public
```
newEntities(array $data, array<string, mixed> $options = []): arrayCake\Datasource\EntityInterface>
```
Create a list of entities + associated entities from an array.
This is most useful when hydrating request data back into entities. For example, in your controller code:
```
$articles = $this->Articles->newEntities($this->request->getData());
```
The hydrated entities can then be iterated and saved.
#### Parameters
`array` $data The data to build an entity with.
`array<string, mixed>` $options optional A list of options for the objects hydration.
#### Returns
`arrayCake\Datasource\EntityInterface>`
### newEntity() public
```
newEntity(array $data, array<string, mixed> $options = []): Cake\Datasource\EntityInterface
```
Create a new entity + associated entities from an array.
This is most useful when hydrating request data back into entities. For example, in your controller code:
```
$article = $this->Articles->newEntity($this->request->getData());
```
The hydrated entity will correctly do an insert/update based on the primary key data existing in the database when the entity is saved. Until the entity is saved, it will be a detached record.
#### Parameters
`array` $data The data to build an entity with.
`array<string, mixed>` $options optional A list of options for the object hydration.
#### Returns
`Cake\Datasource\EntityInterface`
### patchEntities() public
```
patchEntities(iterableCake\Datasource\EntityInterface> $entities, array $data, array<string, mixed> $options = []): arrayCake\Datasource\EntityInterface>
```
Merges each of the elements passed in `$data` into the entities found in `$entities` respecting the accessible fields configured on the entities. Merging is done by matching the primary key in each of the elements in `$data` and `$entities`.
This is most useful when editing a list of existing entities using request data:
```
$article = $this->Articles->patchEntities($articles, $this->request->getData());
```
#### Parameters
`iterableCake\Datasource\EntityInterface>` $entities the entities that will get the data merged in
`array` $data list of arrays to be merged into the entities
`array<string, mixed>` $options optional A list of options for the objects hydration.
#### Returns
`arrayCake\Datasource\EntityInterface>`
### patchEntity() public
```
patchEntity(Cake\Datasource\EntityInterface $entity, array $data, array<string, mixed> $options = []): Cake\Datasource\EntityInterface
```
Merges the passed `$data` into `$entity` respecting the accessible fields configured on the entity. Returns the same entity after being altered.
This is most useful when editing an existing entity using request data:
```
$article = $this->Articles->patchEntity($article, $this->request->getData());
```
#### Parameters
`Cake\Datasource\EntityInterface` $entity the entity that will get the data merged in
`array` $data key value list of fields to be merged into the entity
`array<string, mixed>` $options optional A list of options for the object hydration.
#### Returns
`Cake\Datasource\EntityInterface`
### query() public
```
query(): Cake\Datasource\QueryInterface
```
Creates a new Query instance for this repository
#### Returns
`Cake\Datasource\QueryInterface`
### save() public
```
save(Cake\Datasource\EntityInterface $entity, ArrayAccess|array $options = []): Cake\Datasource\EntityInterface|false
```
Persists an entity based on the fields that are marked as dirty and returns the same entity after a successful save or false in case of any error.
#### Parameters
`Cake\Datasource\EntityInterface` $entity the entity to be saved
`ArrayAccess|array` $options optional The options to use when saving.
#### Returns
`Cake\Datasource\EntityInterface|false`
### setAlias() public
```
setAlias(string $alias): $this
```
Sets the repository alias.
#### Parameters
`string` $alias Table alias
#### Returns
`$this`
### setRegistryAlias() public
```
setRegistryAlias(string $registryAlias): $this
```
Sets the table registry key used to create this table instance.
#### Parameters
`string` $registryAlias The key used to access this object.
#### Returns
`$this`
### updateAll() public
```
updateAll(Cake\Database\Expression\QueryExpressionClosure|array|string $fields, mixed $conditions): int
```
Update all matching records.
Sets the $fields to the provided values based on $conditions. This method will *not* trigger beforeSave/afterSave events. If you need those first load a collection of records and update them.
#### Parameters
`Cake\Database\Expression\QueryExpressionClosure|array|string` $fields A hash of field => new value.
`mixed` $conditions Conditions to be used, accepts anything Query::where() can take.
#### Returns
`int`
| programming_docs |
cakephp Interface HttpApplicationInterface Interface HttpApplicationInterface
===================================
An interface defining the methods that the http server depend on.
**Namespace:** [Cake\Core](namespace-cake.core)
Method Summary
--------------
* ##### [bootstrap()](#bootstrap()) public
Load all the application configuration and bootstrap logic.
* ##### [handle()](#handle()) public
Handles a request and produces a response.
* ##### [middleware()](#middleware()) public
Define the HTTP middleware layers for an application.
Method Detail
-------------
### bootstrap() public
```
bootstrap(): void
```
Load all the application configuration and bootstrap logic.
Override this method to add additional bootstrap logic for your application.
#### Returns
`void`
### handle() public
```
handle(ServerRequestInterface $request): ResponseInterface
```
Handles a request and produces a response.
May call other collaborating code to generate the response.
#### Parameters
`ServerRequestInterface` $request #### Returns
`ResponseInterface`
### middleware() public
```
middleware(Cake\Http\MiddlewareQueue $middlewareQueue): Cake\Http\MiddlewareQueue
```
Define the HTTP middleware layers for an application.
#### Parameters
`Cake\Http\MiddlewareQueue` $middlewareQueue The middleware queue to set in your App Class
#### Returns
`Cake\Http\MiddlewareQueue`
cakephp Trait HttpClientTrait Trait HttpClientTrait
======================
Define mock responses and have mocks automatically cleared.
**Namespace:** [Cake\Http\TestSuite](namespace-cake.http.testsuite)
Method Summary
--------------
* ##### [cleanupMockResponses()](#cleanupMockResponses()) public
Resets mocked responses
* ##### [mockClientDelete()](#mockClientDelete()) public
Add a mock response for a DELETE request.
* ##### [mockClientGet()](#mockClientGet()) public
Add a mock response for a GET request.
* ##### [mockClientPatch()](#mockClientPatch()) public
Add a mock response for a PATCH request.
* ##### [mockClientPost()](#mockClientPost()) public
Add a mock response for a POST request.
* ##### [mockClientPut()](#mockClientPut()) public
Add a mock response for a PUT request.
* ##### [newClientResponse()](#newClientResponse()) public
Create a new response.
Method Detail
-------------
### cleanupMockResponses() public
```
cleanupMockResponses(): void
```
Resets mocked responses
#### Returns
`void`
### mockClientDelete() public
```
mockClientDelete(string $url, Cake\Http\Client\Response $response, array<string, mixed> $options = []): void
```
Add a mock response for a DELETE request.
#### Parameters
`string` $url The URL to mock
`Cake\Http\Client\Response` $response The response for the mock.
`array<string, mixed>` $options optional Additional options. See Client::addMockResponse()
#### Returns
`void`
### mockClientGet() public
```
mockClientGet(string $url, Cake\Http\Client\Response $response, array<string, mixed> $options = []): void
```
Add a mock response for a GET request.
#### Parameters
`string` $url The URL to mock
`Cake\Http\Client\Response` $response The response for the mock.
`array<string, mixed>` $options optional Additional options. See Client::addMockResponse()
#### Returns
`void`
### mockClientPatch() public
```
mockClientPatch(string $url, Cake\Http\Client\Response $response, array<string, mixed> $options = []): void
```
Add a mock response for a PATCH request.
#### Parameters
`string` $url The URL to mock
`Cake\Http\Client\Response` $response The response for the mock.
`array<string, mixed>` $options optional Additional options. See Client::addMockResponse()
#### Returns
`void`
### mockClientPost() public
```
mockClientPost(string $url, Cake\Http\Client\Response $response, array<string, mixed> $options = []): void
```
Add a mock response for a POST request.
#### Parameters
`string` $url The URL to mock
`Cake\Http\Client\Response` $response The response for the mock.
`array<string, mixed>` $options optional Additional options. See Client::addMockResponse()
#### Returns
`void`
### mockClientPut() public
```
mockClientPut(string $url, Cake\Http\Client\Response $response, array<string, mixed> $options = []): void
```
Add a mock response for a PUT request.
#### Parameters
`string` $url The URL to mock
`Cake\Http\Client\Response` $response The response for the mock.
`array<string, mixed>` $options optional Additional options. See Client::addMockResponse()
#### Returns
`void`
### newClientResponse() public
```
newClientResponse(int $code = 200, array<string> $headers = [], string $body = ''): Cake\Http\Client\Response
```
Create a new response.
#### Parameters
`int` $code optional The response code to use. Defaults to 200
`array<string>` $headers optional A list of headers for the response. Example `Content-Type: application/json`
`string` $body optional The body for the response.
#### Returns
`Cake\Http\Client\Response`
cakephp Class ConsoleErrorRenderer Class ConsoleErrorRenderer
===========================
Plain text error rendering with a stack trace.
Writes to STDERR via a Cake\Console\ConsoleOutput instance for console environments
**Namespace:** [Cake\Error\Renderer](namespace-cake.error.renderer)
Property Summary
----------------
* [$output](#%24output) protected `Cake\Console\ConsoleOutput`
* [$trace](#%24trace) protected `bool`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [render()](#render()) public
Render output for the provided error.
* ##### [write()](#write()) public
Write output to the renderer's output stream
Method Detail
-------------
### \_\_construct() public
```
__construct(array $config)
```
Constructor.
### Options
* `stderr` - The ConsoleOutput instance to use. Defaults to `php://stderr`
* `trace` - Whether or not stacktraces should be output.
#### Parameters
`array` $config Error handling configuration.
### render() public
```
render(Cake\Error\PhpError $error, bool $debug): string
```
Render output for the provided error.
#### Parameters
`Cake\Error\PhpError` $error `bool` $debug #### Returns
`string`
### write() public
```
write(string $out): void
```
Write output to the renderer's output stream
#### Parameters
`string` $out #### Returns
`void`
Property Detail
---------------
### $output protected
#### Type
`Cake\Console\ConsoleOutput`
### $trace protected
#### Type
`bool`
cakephp Class WidgetLocator Class WidgetLocator
====================
A registry/factory for input widgets.
Can be used by helpers/view logic to build form widgets and other HTML widgets.
This class handles the mapping between names and concrete classes. It also has a basic name based dependency resolver that allows widgets to depend on each other.
Each widget should expect a StringTemplate instance as their first argument. All other dependencies will be included after.
Widgets can ask for the current view by using the `_view` widget.
**Namespace:** [Cake\View\Widget](namespace-cake.view.widget)
Property Summary
----------------
* [$\_templates](#%24_templates) protected `Cake\View\StringTemplate` Templates to use.
* [$\_view](#%24_view) protected `Cake\View\View` View instance.
* [$\_widgets](#%24_widgets) protected `array` Array of widgets + widget configuration.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_resolveWidget()](#_resolveWidget()) protected
Resolves a widget spec into an instance.
* ##### [add()](#add()) public
Adds or replaces existing widget instances/configuration with new ones.
* ##### [clear()](#clear()) public
Clear the registry and reset the widgets.
* ##### [get()](#get()) public
Get a widget.
* ##### [load()](#load()) public
Load a config file containing widgets.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\View\StringTemplate $templates, Cake\View\View $view, array $widgets = [])
```
Constructor
#### Parameters
`Cake\View\StringTemplate` $templates Templates instance to use.
`Cake\View\View` $view The view instance to set as a widget.
`array` $widgets optional See add() method for more information.
### \_resolveWidget() protected
```
_resolveWidget(mixed $config): Cake\View\Widget\WidgetInterface
```
Resolves a widget spec into an instance.
#### Parameters
`mixed` $config The widget config.
#### Returns
`Cake\View\Widget\WidgetInterface`
#### Throws
`ReflectionException`
### add() public
```
add(array $widgets): void
```
Adds or replaces existing widget instances/configuration with new ones.
Widget arrays can either be descriptions or instances. For example:
```
$registry->add([
'label' => new MyLabelWidget($templates),
'checkbox' => ['Fancy.MyCheckbox', 'label']
]);
```
The above shows how to define widgets as instances or as descriptions including dependencies. Classes can be defined with plugin notation, or fully namespaced class names.
#### Parameters
`array` $widgets Array of widgets to use.
#### Returns
`void`
#### Throws
`RuntimeException`
When class does not implement WidgetInterface. ### clear() public
```
clear(): void
```
Clear the registry and reset the widgets.
#### Returns
`void`
### get() public
```
get(string $name): Cake\View\Widget\WidgetInterface
```
Get a widget.
Will either fetch an already created widget, or create a new instance if the widget has been defined. If the widget is undefined an instance of the `_default` widget will be returned. An exception will be thrown if the `_default` widget is undefined.
#### Parameters
`string` $name The widget name to get.
#### Returns
`Cake\View\Widget\WidgetInterface`
#### Throws
`RuntimeException`
when widget is undefined. ### load() public
```
load(string $file): void
```
Load a config file containing widgets.
Widget files should define a `$config` variable containing all the widgets to load. Loaded widgets will be merged with existing widgets.
#### Parameters
`string` $file The file to load
#### Returns
`void`
Property Detail
---------------
### $\_templates protected
Templates to use.
#### Type
`Cake\View\StringTemplate`
### $\_view protected
View instance.
#### Type
`Cake\View\View`
### $\_widgets protected
Array of widgets + widget configuration.
#### Type
`array`
cakephp Interface FormatterInterface Interface FormatterInterface
=============================
Interface for formatters used by Debugger::exportVar()
**Namespace:** [Cake\Error\Debug](namespace-cake.error.debug)
Method Summary
--------------
* ##### [dump()](#dump()) public
Convert a tree of NodeInterface objects into a plain text string.
* ##### [formatWrapper()](#formatWrapper()) public
Output a dump wrapper with location context.
Method Detail
-------------
### dump() public
```
dump(Cake\Error\Debug\NodeInterface $node): string
```
Convert a tree of NodeInterface objects into a plain text string.
#### Parameters
`Cake\Error\Debug\NodeInterface` $node The node tree to dump.
#### Returns
`string`
### formatWrapper() public
```
formatWrapper(string $contents, array $location): string
```
Output a dump wrapper with location context.
#### Parameters
`string` $contents The contents to wrap and return
`array` $location The file and line the contents came from.
#### Returns
`string`
cakephp Class ConsoleErrorHandler Class ConsoleErrorHandler
==========================
Error Handler for Cake console. Does simple printing of the exception that occurred and the stack trace of the error.
**Namespace:** [Cake\Error](namespace-cake.error)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Options to use for the Error handling.
* [$\_handled](#%24_handled) protected `bool`
* [$\_stderr](#%24_stderr) protected `Cake\Console\ConsoleOutput` Standard error stream.
* [$logger](#%24logger) protected `Cake\Error\ErrorLoggerInterface|null` Exception logger instance.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_displayError()](#_displayError()) protected
Prints an error to stderr.
* ##### [\_displayException()](#_displayException()) protected
Prints an exception to stderr.
* ##### [\_logError()](#_logError()) protected
Log an error.
* ##### [\_stop()](#_stop()) protected
Stop the execution and set the exit code for the process.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getLogger()](#getLogger()) public
Get exception logger.
* ##### [handleError()](#handleError()) public
Set as the default error handler by CakePHP.
* ##### [handleException()](#handleException()) public
Handle errors in the console environment. Writes errors to stderr, and logs messages if Configure::read('debug') is false.
* ##### [handleFatalError()](#handleFatalError()) public
Display/Log a fatal error.
* ##### [increaseMemoryLimit()](#increaseMemoryLimit()) public
Increases the PHP "memory\_limit" ini setting by the specified amount in kilobytes
* ##### [logException()](#logException()) public
Log an error for the exception if applicable.
* ##### [mapErrorCode()](#mapErrorCode()) public static
Map an error code into an Error word, and log location.
* ##### [register()](#register()) public
Register the error and exception handlers.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [wrapAndHandleException()](#wrapAndHandleException()) public deprecated
Checks the passed exception type. If it is an instance of `Error` then, it wraps the passed object inside another Exception object for backwards compatibility purposes.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Constructor
#### Parameters
`array<string, mixed>` $config optional Config options for the error handler.
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_displayError() protected
```
_displayError(array $error, bool $debug): void
```
Prints an error to stderr.
Template method of BaseErrorHandler.
#### Parameters
`array` $error An array of error data.
`bool` $debug Whether the app is in debug mode.
#### Returns
`void`
### \_displayException() protected
```
_displayException(Throwable $exception): void
```
Prints an exception to stderr.
Subclasses should implement this method to display an uncaught exception as desired for the runtime they operate in.
#### Parameters
`Throwable` $exception The exception to handle
#### Returns
`void`
### \_logError() protected
```
_logError(string|int $level, array $data): bool
```
Log an error.
#### Parameters
`string|int` $level The level name of the log.
`array` $data Array of error data.
#### Returns
`bool`
### \_stop() protected
```
_stop(int $code): void
```
Stop the execution and set the exit code for the process.
Implemented in subclasses that need it.
#### Parameters
`int` $code The exit code.
#### Returns
`void`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getLogger() public
```
getLogger(): Cake\Error\ErrorLoggerInterface
```
Get exception logger.
#### Returns
`Cake\Error\ErrorLoggerInterface`
### handleError() public
```
handleError(int $code, string $description, string|null $file = null, int|null $line = null, array<string, mixed>|null $context = null): bool
```
Set as the default error handler by CakePHP.
Use config/error.php to customize or replace this error handler. This function will use Debugger to display errors when debug mode is on. And will log errors to Log, when debug mode is off.
You can use the 'errorLevel' option to set what type of errors will be handled. Stack traces for errors can be enabled with the 'trace' option.
#### Parameters
`int` $code Code of error
`string` $description Error description
`string|null` $file optional File on which error occurred
`int|null` $line optional Line that triggered the error
`array<string, mixed>|null` $context optional Context
#### Returns
`bool`
### handleException() public
```
handleException(Throwable $exception): void
```
Handle errors in the console environment. Writes errors to stderr, and logs messages if Configure::read('debug') is false.
Uses a template method provided by subclasses to display errors in an environment appropriate way.
#### Parameters
`Throwable` $exception Exception instance.
#### Returns
`void`
#### Throws
`Exception`
When renderer class not found #### See Also
https://secure.php.net/manual/en/function.set-exception-handler.php ### handleFatalError() public
```
handleFatalError(int $code, string $description, string $file, int $line): bool
```
Display/Log a fatal error.
#### Parameters
`int` $code Code of error
`string` $description Error description
`string` $file File on which error occurred
`int` $line Line that triggered the error
#### Returns
`bool`
### increaseMemoryLimit() public
```
increaseMemoryLimit(int $additionalKb): void
```
Increases the PHP "memory\_limit" ini setting by the specified amount in kilobytes
#### Parameters
`int` $additionalKb Number in kilobytes
#### Returns
`void`
### logException() public
```
logException(Throwable $exception, Psr\Http\Message\ServerRequestInterface|null $request = null): bool
```
Log an error for the exception if applicable.
#### Parameters
`Throwable` $exception The exception to log a message for.
`Psr\Http\Message\ServerRequestInterface|null` $request optional The current request.
#### Returns
`bool`
### mapErrorCode() public static
```
mapErrorCode(int $code): array
```
Map an error code into an Error word, and log location.
#### Parameters
`int` $code Error code to map
#### Returns
`array`
### register() public
```
register(): void
```
Register the error and exception handlers.
#### Returns
`void`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### wrapAndHandleException() public
```
wrapAndHandleException(Throwable $exception): void
```
Checks the passed exception type. If it is an instance of `Error` then, it wraps the passed object inside another Exception object for backwards compatibility purposes.
#### Parameters
`Throwable` $exception The exception to handle
#### Returns
`void`
Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Options to use for the Error handling.
#### Type
`array<string, mixed>`
### $\_handled protected
#### Type
`bool`
### $\_stderr protected
Standard error stream.
#### Type
`Cake\Console\ConsoleOutput`
### $logger protected
Exception logger instance.
#### Type
`Cake\Error\ErrorLoggerInterface|null`
| programming_docs |
cakephp Class SqlserverStatement Class SqlserverStatement
=========================
Statement class meant to be used by an Sqlserver driver
**Namespace:** [Cake\Database\Statement](namespace-cake.database.statement)
Constants
---------
* `string` **FETCH\_TYPE\_ASSOC**
```
'assoc'
```
Used to designate that an associated array be returned in a result when calling fetch methods
* `string` **FETCH\_TYPE\_NUM**
```
'num'
```
Used to designate that numeric indexes be returned in a result when calling fetch methods
* `string` **FETCH\_TYPE\_OBJ**
```
'obj'
```
Used to designate that a stdClass object be returned in a result when calling fetch methods
Property Summary
----------------
* [$\_driver](#%24_driver) protected `Cake\Database\DriverInterface` Reference to the driver object associated to this statement.
* [$\_hasExecuted](#%24_hasExecuted) protected `bool` Whether this statement has already been executed
* [$\_statement](#%24_statement) protected `PDOStatement` PDOStatement instance
* [$queryString](#%24queryString) public @property-read `string`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_get()](#__get()) public
Magic getter to return PDOStatement::$queryString as read-only.
* ##### [bind()](#bind()) public
Binds a set of values to statement object with corresponding type.
* ##### [bindValue()](#bindValue()) public
Assign a value to a positional or named variable in prepared query. If using positional variables you need to start with index one, if using named params then just use the name in any order.
* ##### [cast()](#cast()) public
Converts a give value to a suitable database value based on type and return relevant internal statement type
* ##### [closeCursor()](#closeCursor()) public
Closes a cursor in the database, freeing up any resources and memory allocated to it. In most cases you don't need to call this method, as it is automatically called after fetching all results from the result set.
* ##### [columnCount()](#columnCount()) public
Returns the number of columns this statement's results will contain.
* ##### [count()](#count()) public
Statements can be passed as argument for count() to return the number for affected rows from last execution.
* ##### [errorCode()](#errorCode()) public
Returns the error code for the last error that occurred when executing this statement.
* ##### [errorInfo()](#errorInfo()) public
Returns the error information for the last error that occurred when executing this statement.
* ##### [execute()](#execute()) public
Executes the statement by sending the SQL query to the database. It can optionally take an array or arguments to be bound to the query variables. Please note that binding parameters from this method will not perform any custom type conversion as it would normally happen when calling `bindValue`.
* ##### [fetch()](#fetch()) public
Returns the next row for the result set after executing this statement. Rows can be fetched to contain columns as names or positions. If no rows are left in result set, this method will return false
* ##### [fetchAll()](#fetchAll()) public
Returns an array with all rows resulting from executing this statement
* ##### [fetchAssoc()](#fetchAssoc()) public
Returns the next row in a result set as an associative array. Calling this function is the same as calling $statement->fetch(StatementDecorator::FETCH\_TYPE\_ASSOC). If no results are found an empty array is returned.
* ##### [fetchColumn()](#fetchColumn()) public
Returns the value of the result at position.
* ##### [getInnerStatement()](#getInnerStatement()) public
Returns the statement object that was decorated by this class.
* ##### [getIterator()](#getIterator()) public
Statements are iterable as arrays, this method will return the iterator object for traversing all items in the result.
* ##### [lastInsertId()](#lastInsertId()) public
Returns the latest primary inserted using this statement.
* ##### [matchTypes()](#matchTypes()) public
Matches columns to corresponding types
* ##### [rowCount()](#rowCount()) public
Returns the number of rows affected by this SQL statement.
Method Detail
-------------
### \_\_construct() public
```
__construct(PDOStatement $statement, Cake\Database\DriverInterface $driver)
```
Constructor
#### Parameters
`PDOStatement` $statement Original statement to be decorated.
`Cake\Database\DriverInterface` $driver Driver instance.
### \_\_get() public
```
__get(string $property): string|null
```
Magic getter to return PDOStatement::$queryString as read-only.
#### Parameters
`string` $property internal property to get
#### Returns
`string|null`
### bind() public
```
bind(array $params, array $types): void
```
Binds a set of values to statement object with corresponding type.
#### Parameters
`array` $params list of values to be bound
`array` $types list of types to be used, keys should match those in $params
#### Returns
`void`
### bindValue() public
```
bindValue(string|int $column, mixed $value, string|int|null $type = 'string'): void
```
Assign a value to a positional or named variable in prepared query. If using positional variables you need to start with index one, if using named params then just use the name in any order.
The SQL Server PDO driver requires that binary parameters be bound with the SQLSRV\_ENCODING\_BINARY attribute. This overrides the PDOStatement::bindValue method in order to bind binary columns using the required attribute.
#### Parameters
`string|int` $column name or param position to be bound
`mixed` $value The value to bind to variable in query
`string|int|null` $type optional PDO type or name of configured Type class
#### Returns
`void`
### cast() public
```
cast(mixed $value, Cake\Database\TypeInterface|string|int $type = 'string'): array
```
Converts a give value to a suitable database value based on type and return relevant internal statement type
#### Parameters
`mixed` $value The value to cast
`Cake\Database\TypeInterface|string|int` $type optional The type name or type instance to use.
#### Returns
`array`
### closeCursor() public
```
closeCursor(): void
```
Closes a cursor in the database, freeing up any resources and memory allocated to it. In most cases you don't need to call this method, as it is automatically called after fetching all results from the result set.
#### Returns
`void`
### columnCount() public
```
columnCount(): int
```
Returns the number of columns this statement's results will contain.
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
echo $statement->columnCount(); // outputs 2
```
#### Returns
`int`
### count() public
```
count(): int
```
Statements can be passed as argument for count() to return the number for affected rows from last execution.
#### Returns
`int`
### errorCode() public
```
errorCode(): string|int
```
Returns the error code for the last error that occurred when executing this statement.
#### Returns
`string|int`
### errorInfo() public
```
errorInfo(): array
```
Returns the error information for the last error that occurred when executing this statement.
#### Returns
`array`
### execute() public
```
execute(array|null $params = null): bool
```
Executes the statement by sending the SQL query to the database. It can optionally take an array or arguments to be bound to the query variables. Please note that binding parameters from this method will not perform any custom type conversion as it would normally happen when calling `bindValue`.
#### Parameters
`array|null` $params optional list of values to be bound to query
#### Returns
`bool`
### fetch() public
```
fetch(string|int $type = parent::FETCH_TYPE_NUM): mixed
```
Returns the next row for the result set after executing this statement. Rows can be fetched to contain columns as names or positions. If no rows are left in result set, this method will return false
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
print_r($statement->fetch('assoc')); // will show ['id' => 1, 'title' => 'a title']
```
#### Parameters
`string|int` $type optional 'num' for positional columns, assoc for named columns
#### Returns
`mixed`
### fetchAll() public
```
fetchAll(string|int $type = parent::FETCH_TYPE_NUM): array|false
```
Returns an array with all rows resulting from executing this statement
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
print_r($statement->fetchAll('assoc')); // will show [0 => ['id' => 1, 'title' => 'a title']]
```
#### Parameters
`string|int` $type optional num for fetching columns as positional keys or assoc for column names as keys
#### Returns
`array|false`
### fetchAssoc() public
```
fetchAssoc(): array
```
Returns the next row in a result set as an associative array. Calling this function is the same as calling $statement->fetch(StatementDecorator::FETCH\_TYPE\_ASSOC). If no results are found an empty array is returned.
#### Returns
`array`
### fetchColumn() public
```
fetchColumn(int $position): mixed
```
Returns the value of the result at position.
#### Parameters
`int` $position The numeric position of the column to retrieve in the result
#### Returns
`mixed`
### getInnerStatement() public
```
getInnerStatement(): Cake\Database\StatementInterface
```
Returns the statement object that was decorated by this class.
#### Returns
`Cake\Database\StatementInterface`
### getIterator() public
```
getIterator(): Cake\Database\StatementInterface
```
Statements are iterable as arrays, this method will return the iterator object for traversing all items in the result.
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
foreach ($statement as $row) {
//do stuff
}
```
#### Returns
`Cake\Database\StatementInterface`
### lastInsertId() public
```
lastInsertId(string|null $table = null, string|null $column = null): string|int
```
Returns the latest primary inserted using this statement.
#### Parameters
`string|null` $table optional table name or sequence to get last insert value from
`string|null` $column optional the name of the column representing the primary key
#### Returns
`string|int`
### matchTypes() public
```
matchTypes(array $columns, array $types): array
```
Matches columns to corresponding types
Both $columns and $types should either be numeric based or string key based at the same time.
#### Parameters
`array` $columns list or associative array of columns and parameters to be bound with types
`array` $types list or associative array of types
#### Returns
`array`
### rowCount() public
```
rowCount(): int
```
Returns the number of rows affected by this SQL statement.
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
print_r($statement->rowCount()); // will show 1
```
#### Returns
`int`
Property Detail
---------------
### $\_driver protected
Reference to the driver object associated to this statement.
#### Type
`Cake\Database\DriverInterface`
### $\_hasExecuted protected
Whether this statement has already been executed
#### Type
`bool`
### $\_statement protected
PDOStatement instance
#### Type
`PDOStatement`
### $queryString public @property-read
#### Type
`string`
cakephp Class AbstractTransport Class AbstractTransport
========================
Abstract transport for sending email
**Abstract**
**Namespace:** [Cake\Mailer](namespace-cake.mailer)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this class
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [checkRecipient()](#checkRecipient()) protected
Check that at least one destination header is set.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [send()](#send()) abstract public
Send mail
* ##### [setConfig()](#setConfig()) public
Sets the config.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Constructor
#### Parameters
`array<string, mixed>` $config optional Configuration options.
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### checkRecipient() protected
```
checkRecipient(Cake\Mailer\Message $message): void
```
Check that at least one destination header is set.
#### Parameters
`Cake\Mailer\Message` $message Message instance.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
If at least one of to, cc or bcc is not specified. ### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### send() abstract public
```
send(Cake\Mailer\Message $message): array
```
Send mail
#### Parameters
`Cake\Mailer\Message` $message Email message.
#### Returns
`array`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this class
#### Type
`array<string, mixed>`
cakephp Interface RoutingApplicationInterface Interface RoutingApplicationInterface
======================================
Interface for applications that use routing.
**Namespace:** [Cake\Routing](namespace-cake.routing)
Method Summary
--------------
* ##### [routes()](#routes()) public
Define the routes for an application.
Method Detail
-------------
### routes() public
```
routes(Cake\Routing\RouteBuilder $routes): void
```
Define the routes for an application.
Use the provided RouteBuilder to define an application's routing.
#### Parameters
`Cake\Routing\RouteBuilder` $routes A route builder to add routes into.
#### Returns
`void`
cakephp Class UnaryExpression Class UnaryExpression
======================
An expression object that represents an expression with only a single operand.
**Namespace:** [Cake\Database\Expression](namespace-cake.database.expression)
Constants
---------
* `int` **POSTFIX**
```
1
```
Indicates that the operation is in post-order
* `int` **PREFIX**
```
0
```
Indicates that the operation is in pre-order
Property Summary
----------------
* [$\_operator](#%24_operator) protected `string` The operator this unary expression represents
* [$\_value](#%24_value) protected `mixed` Holds the value which the unary expression operates
* [$position](#%24position) protected `int` Where to place the operator
Method Summary
--------------
* ##### [\_\_clone()](#__clone()) public
Perform a deep clone of the inner expression.
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [sql()](#sql()) public
Converts the Node into a SQL string fragment.
* ##### [traverse()](#traverse()) public
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
Method Detail
-------------
### \_\_clone() public
```
__clone(): void
```
Perform a deep clone of the inner expression.
#### Returns
`void`
### \_\_construct() public
```
__construct(string $operator, mixed $value, int $position = self::PREFIX)
```
Constructor
#### Parameters
`string` $operator The operator to used for the expression
`mixed` $value the value to use as the operand for the expression
`int` $position optional either UnaryExpression::PREFIX or UnaryExpression::POSTFIX
### sql() public
```
sql(Cake\Database\ValueBinder $binder): string
```
Converts the Node into a SQL string fragment.
#### Parameters
`Cake\Database\ValueBinder` $binder #### Returns
`string`
### traverse() public
```
traverse(Closure $callback): $this
```
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
#### Parameters
`Closure` $callback #### Returns
`$this`
Property Detail
---------------
### $\_operator protected
The operator this unary expression represents
#### Type
`string`
### $\_value protected
Holds the value which the unary expression operates
#### Type
`mixed`
### $position protected
Where to place the operator
#### Type
`int`
| programming_docs |
cakephp Trait TranslateTrait Trait TranslateTrait
=====================
Contains a translation method aimed to help managing multiple translations for an entity.
**Namespace:** [Cake\ORM\Behavior\Translate](namespace-cake.orm.behavior.translate)
Method Summary
--------------
* ##### [translation()](#translation()) public
Returns the entity containing the translated fields for this object and for the specified language. If the translation for the passed language is not present, a new empty entity will be created so that values can be added to it.
Method Detail
-------------
### translation() public
```
translation(string $language): Cake\Datasource\EntityInterface|$this
```
Returns the entity containing the translated fields for this object and for the specified language. If the translation for the passed language is not present, a new empty entity will be created so that values can be added to it.
#### Parameters
`string` $language Language to return entity for.
#### Returns
`Cake\Datasource\EntityInterface|$this`
cakephp Namespace Rule Namespace Rule
==============
### Classes
* ##### [ExistsIn](class-cake.orm.rule.existsin)
Checks that the value provided in a field exists as the primary key of another table.
* ##### [IsUnique](class-cake.orm.rule.isunique)
Checks that a list of fields from an entity are unique in the table
* ##### [LinkConstraint](class-cake.orm.rule.linkconstraint)
Checks whether links to a given association exist / do not exist.
* ##### [ValidCount](class-cake.orm.rule.validcount)
Validates the count of associated records.
cakephp Class Behavior Class Behavior
===============
Base class for behaviors.
Behaviors allow you to simulate mixins, and create reusable blocks of application logic, that can be reused across several models. Behaviors also provide a way to hook into model callbacks and augment their behavior.
### Mixin methods
Behaviors can provide mixin like features by declaring public methods. These methods will be accessible on the tables the behavior has been added to.
```
function doSomething($arg1, $arg2) {
// do something
}
```
Would be called like `$table->doSomething($arg1, $arg2);`.
### Callback methods
Behaviors can listen to any events fired on a Table. By default, CakePHP provides a number of lifecycle events your behaviors can listen to:
* `beforeFind(EventInterface $event, Query $query, ArrayObject $options, boolean $primary)` Fired before each find operation. By stopping the event and supplying a return value you can bypass the find operation entirely. Any changes done to the $query instance will be retained for the rest of the find. The $primary parameter indicates whether this is the root query, or an associated query.
* `buildValidator(EventInterface $event, Validator $validator, string $name)` Fired when the validator object identified by $name is being built. You can use this callback to add validation rules or add validation providers.
* `buildRules(EventInterface $event, RulesChecker $rules)` Fired when the rules checking object for the table is being built. You can use this callback to add more rules to the set.
* `beforeRules(EventInterface $event, EntityInterface $entity, ArrayObject $options, $operation)` Fired before an entity is validated using by a rules checker. By stopping this event, you can return the final value of the rules checking operation.
* `afterRules(EventInterface $event, EntityInterface $entity, ArrayObject $options, bool $result, $operation)` Fired after the rules have been checked on the entity. By stopping this event, you can return the final value of the rules checking operation.
* `beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)` Fired before each entity is saved. Stopping this event will abort the save operation. When the event is stopped the result of the event will be returned.
* `afterSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)` Fired after an entity is saved.
* `beforeDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options)` Fired before an entity is deleted. By stopping this event you will abort the delete operation.
* `afterDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options)` Fired after an entity has been deleted.
In addition to the core events, behaviors can respond to any event fired from your Table classes including custom application specific ones.
You can set the priority of a behaviors callbacks by using the `priority` setting when attaching a behavior. This will set the priority for all the callbacks a behavior provides.
### Finder methods
Behaviors can provide finder methods that hook into a Table's find() method. Custom finders are a great way to provide preset queries that relate to your behavior. For example a SluggableBehavior could provide a find('slugged') finder. Behavior finders are implemented the same as other finders. Any method starting with `find` will be setup as a finder. Your finder methods should expect the following arguments:
```
findSlugged(Query $query, array $options)
```
**Namespace:** [Cake\ORM](namespace-cake.orm)
**See:** \Cake\ORM\Table::addBehavior()
**See:** \Cake\Event\EventManager
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default configuration
* [$\_reflectionCache](#%24_reflectionCache) protected static `array<string, array>` Reflection method cache for behaviors.
* [$\_table](#%24_table) protected `Cake\ORM\Table` Table instance.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_reflectionCache()](#_reflectionCache()) protected
Gets the methods implemented by this behavior
* ##### [\_resolveMethodAliases()](#_resolveMethodAliases()) protected
Removes aliased methods that would otherwise be duplicated by userland configuration.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getTable()](#getTable()) public deprecated
Get the table instance this behavior is bound to.
* ##### [implementedEvents()](#implementedEvents()) public
Gets the Model callbacks this behavior is interested in.
* ##### [implementedFinders()](#implementedFinders()) public
implementedFinders
* ##### [implementedMethods()](#implementedMethods()) public
implementedMethods
* ##### [initialize()](#initialize()) public
Constructor hook method.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [table()](#table()) public
Get the table instance this behavior is bound to.
* ##### [verifyConfig()](#verifyConfig()) public
verifyConfig
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\ORM\Table $table, array<string, mixed> $config = [])
```
Constructor
Merges config with the default and store in the config property
#### Parameters
`Cake\ORM\Table` $table The table this behavior is attached to.
`array<string, mixed>` $config optional The config for this behavior.
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_reflectionCache() protected
```
_reflectionCache(): array
```
Gets the methods implemented by this behavior
Uses the implementedEvents() method to exclude callback methods. Methods starting with `_` will be ignored, as will methods declared on Cake\ORM\Behavior
#### Returns
`array`
#### Throws
`ReflectionException`
### \_resolveMethodAliases() protected
```
_resolveMethodAliases(string $key, array<string, mixed> $defaults, array<string, mixed> $config): array
```
Removes aliased methods that would otherwise be duplicated by userland configuration.
#### Parameters
`string` $key The key to filter.
`array<string, mixed>` $defaults The default method mappings.
`array<string, mixed>` $config The customized method mappings.
#### Returns
`array`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getTable() public
```
getTable(): Cake\ORM\Table
```
Get the table instance this behavior is bound to.
#### Returns
`Cake\ORM\Table`
### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Gets the Model callbacks this behavior is interested in.
By defining one of the callback methods a behavior is assumed to be interested in the related event.
Override this method if you need to add non-conventional event listeners. Or if you want your behavior to listen to non-standard events.
#### Returns
`array<string, mixed>`
### implementedFinders() public
```
implementedFinders(): array
```
implementedFinders
Provides an alias->methodname map of which finders a behavior implements. Example:
```
[
'this' => 'findThis',
'alias' => 'findMethodName'
]
```
With the above example, a call to `$table->find('this')` will call `$behavior->findThis()` and a call to `$table->find('alias')` will call `$behavior->findMethodName()`
It is recommended, though not required, to define implementedFinders in the config property of child classes such that it is not necessary to use reflections to derive the available method list. See core behaviors for examples
#### Returns
`array`
#### Throws
`ReflectionException`
### implementedMethods() public
```
implementedMethods(): array
```
implementedMethods
Provides an alias->methodname map of which methods a behavior implements. Example:
```
[
'method' => 'method',
'aliasedMethod' => 'somethingElse'
]
```
With the above example, a call to `$table->method()` will call `$behavior->method()` and a call to `$table->aliasedMethod()` will call `$behavior->somethingElse()`
It is recommended, though not required, to define implementedFinders in the config property of child classes such that it is not necessary to use reflections to derive the available method list. See core behaviors for examples
#### Returns
`array`
#### Throws
`ReflectionException`
### initialize() public
```
initialize(array<string, mixed> $config): void
```
Constructor hook method.
Implement this method to avoid having to overwrite the constructor and call parent.
#### Parameters
`array<string, mixed>` $config The configuration settings provided to this behavior.
#### Returns
`void`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### table() public
```
table(): Cake\ORM\Table
```
Get the table instance this behavior is bound to.
#### Returns
`Cake\ORM\Table`
### verifyConfig() public
```
verifyConfig(): void
```
verifyConfig
Checks that implemented keys contain values pointing at callable.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if config are invalid Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default configuration
These are merged with user-provided configuration when the behavior is used.
#### Type
`array<string, mixed>`
### $\_reflectionCache protected static
Reflection method cache for behaviors.
Stores the reflected method + finder methods per class. This prevents reflecting the same class multiple times in a single process.
#### Type
`array<string, array>`
### $\_table protected
Table instance.
#### Type
`Cake\ORM\Table`
cakephp Interface ExceptionRendererInterface Interface ExceptionRendererInterface
=====================================
Interface ExceptionRendererInterface
**Namespace:** [Cake\Error](namespace-cake.error)
Method Summary
--------------
* ##### [render()](#render()) public @method
Render the exception to a string or Http Response.
* ##### [write()](#write()) public @method
Write the output to the output stream. This method is only called when exceptions are handled by a global default exception handler.
Method Detail
-------------
### render() public @method
```
render(): Psr\Http\Message\ResponseInterface|string
```
Render the exception to a string or Http Response.
#### Returns
`Psr\Http\Message\ResponseInterface|string`
### write() public @method
```
write(Psr\Http\Message\ResponseInterface|string $output): void
```
Write the output to the output stream. This method is only called when exceptions are handled by a global default exception handler.
#### Parameters
`Psr\Http\Message\ResponseInterface|string` $output #### Returns
`void`
cakephp Class MiddlewareQueue Class MiddlewareQueue
======================
Provides methods for creating and manipulating a "queue" of middlewares. This queue is used to process a request and generate response via \Cake\Http\Runner.
**Namespace:** [Cake\Http](namespace-cake.http)
Property Summary
----------------
* [$position](#%24position) protected `int` Internal position for iterator.
* [$queue](#%24queue) protected `array<int, mixed>` The queue of middlewares.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [add()](#add()) public
Append a middleware to the end of the queue.
* ##### [count()](#count()) public
Get the number of connected middleware layers.
* ##### [current()](#current()) public
Returns the current middleware.
* ##### [insertAfter()](#insertAfter()) public
Insert a middleware object after the first matching class.
* ##### [insertAt()](#insertAt()) public
Insert a middleware at a specific index.
* ##### [insertBefore()](#insertBefore()) public
Insert a middleware before the first matching class.
* ##### [key()](#key()) public
Return the key of the middleware.
* ##### [next()](#next()) public
Moves the current position to the next middleware.
* ##### [prepend()](#prepend()) public
Prepend a middleware to the start of the queue.
* ##### [push()](#push()) public
Alias for MiddlewareQueue::add().
* ##### [resolve()](#resolve()) protected
Resolve middleware name to a PSR 15 compliant middleware instance.
* ##### [rewind()](#rewind()) public
Rewinds back to the first element of the queue.
* ##### [seek()](#seek()) public
Seeks to a given position in the queue.
* ##### [valid()](#valid()) public
Checks if current position is valid.
Method Detail
-------------
### \_\_construct() public
```
__construct(array $middleware = [])
```
Constructor
#### Parameters
`array` $middleware optional The list of middleware to append.
### add() public
```
add(Psr\Http\Server\MiddlewareInterfaceClosure|array|string $middleware): $this
```
Append a middleware to the end of the queue.
#### Parameters
`Psr\Http\Server\MiddlewareInterfaceClosure|array|string` $middleware The middleware(s) to append.
#### Returns
`$this`
### count() public
```
count(): int
```
Get the number of connected middleware layers.
Implement the Countable interface.
#### Returns
`int`
### current() public
```
current(): Psr\Http\Server\MiddlewareInterface
```
Returns the current middleware.
#### Returns
`Psr\Http\Server\MiddlewareInterface`
#### See Also
\Iterator::current() ### insertAfter() public
```
insertAfter(string $class, Psr\Http\Server\MiddlewareInterfaceClosure|string $middleware): $this
```
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().
#### Parameters
`string` $class The classname to insert the middleware before.
`Psr\Http\Server\MiddlewareInterfaceClosure|string` $middleware The middleware to insert.
#### Returns
`$this`
### insertAt() public
```
insertAt(int $index, Psr\Http\Server\MiddlewareInterfaceClosure|string $middleware): $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.
#### Parameters
`int` $index The index to insert at.
`Psr\Http\Server\MiddlewareInterfaceClosure|string` $middleware The middleware to insert.
#### Returns
`$this`
### insertBefore() public
```
insertBefore(string $class, Psr\Http\Server\MiddlewareInterfaceClosure|string $middleware): $this
```
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.
#### Parameters
`string` $class The classname to insert the middleware before.
`Psr\Http\Server\MiddlewareInterfaceClosure|string` $middleware The middleware to insert.
#### Returns
`$this`
#### Throws
`LogicException`
If middleware to insert before is not found. ### key() public
```
key(): int
```
Return the key of the middleware.
#### Returns
`int`
#### See Also
\Iterator::key() ### next() public
```
next(): void
```
Moves the current position to the next middleware.
#### Returns
`void`
#### See Also
\Iterator::next() ### prepend() public
```
prepend(Psr\Http\Server\MiddlewareInterfaceClosure|array|string $middleware): $this
```
Prepend a middleware to the start of the queue.
#### Parameters
`Psr\Http\Server\MiddlewareInterfaceClosure|array|string` $middleware The middleware(s) to prepend.
#### Returns
`$this`
### push() public
```
push(Psr\Http\Server\MiddlewareInterfaceClosure|array|string $middleware): $this
```
Alias for MiddlewareQueue::add().
#### Parameters
`Psr\Http\Server\MiddlewareInterfaceClosure|array|string` $middleware The middleware(s) to append.
#### Returns
`$this`
#### See Also
MiddlewareQueue::add() ### resolve() protected
```
resolve(Psr\Http\Server\MiddlewareInterfaceClosure|string $middleware): Psr\Http\Server\MiddlewareInterface
```
Resolve middleware name to a PSR 15 compliant middleware instance.
#### Parameters
`Psr\Http\Server\MiddlewareInterfaceClosure|string` $middleware The middleware to resolve.
#### Returns
`Psr\Http\Server\MiddlewareInterface`
#### Throws
`RuntimeException`
If Middleware not found. ### rewind() public
```
rewind(): void
```
Rewinds back to the first element of the queue.
#### Returns
`void`
#### See Also
\Iterator::rewind() ### seek() public
```
seek(int $position): void
```
Seeks to a given position in the queue.
#### Parameters
`int` $position The position to seek to.
#### Returns
`void`
#### See Also
\SeekableIterator::seek() ### valid() public
```
valid(): bool
```
Checks if current position is valid.
#### Returns
`bool`
#### See Also
\Iterator::valid() Property Detail
---------------
### $position protected
Internal position for iterator.
#### Type
`int`
### $queue protected
The queue of middlewares.
#### Type
`array<int, mixed>`
| programming_docs |
cakephp Class TupleComparison Class TupleComparison
======================
This expression represents SQL fragments that are used for comparing one tuple to another, one tuple to a set of other tuples or one tuple to an expression
**Namespace:** [Cake\Database\Expression](namespace-cake.database.expression)
Property Summary
----------------
* [$\_field](#%24_field) protected `Cake\Database\ExpressionInterface|array|string` The field name or expression to be used in the left hand side of the operator
* [$\_isMultiple](#%24_isMultiple) protected `bool` Whether the value in this expression is a traversable
* [$\_operator](#%24_operator) protected `string` The operator used for comparing field and value
* [$\_type](#%24_type) protected `array<string|null>` The type to be used for casting the value to a database representation
* [$\_value](#%24_value) protected `mixed` The value to be used in the right hand side of the operation
* [$\_valueExpressions](#%24_valueExpressions) protected `arrayCake\Database\ExpressionInterface>` A cached list of ExpressionInterface objects that were found in the value for this expression.
Method Summary
--------------
* ##### [\_\_clone()](#__clone()) public
Create a deep clone.
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_bindValue()](#_bindValue()) protected
Registers a value in the placeholder generator and returns the generated placeholder
* ##### [\_castToExpression()](#_castToExpression()) protected
Conditionally converts the passed value to an ExpressionInterface object if the type class implements the ExpressionTypeInterface. Otherwise, returns the value unmodified.
* ##### [\_collectExpressions()](#_collectExpressions()) protected
Returns an array with the original $values in the first position and all ExpressionInterface objects that could be found in the second position.
* ##### [\_flattenValue()](#_flattenValue()) protected
Converts a traversable value into a set of placeholders generated by $binder and separated by `,`
* ##### [\_requiresToExpressionCasting()](#_requiresToExpressionCasting()) protected
Returns an array with the types that require values to be casted to expressions, out of the list of type names passed as parameter.
* ##### [\_stringExpression()](#_stringExpression()) protected
Returns a template and a placeholder for the value after registering it with the placeholder $binder
* ##### [\_stringifyValues()](#_stringifyValues()) protected
Returns a string with the values as placeholders in a string to be used for the SQL version of this expression
* ##### [\_traverseValue()](#_traverseValue()) protected
Conditionally executes the callback for the passed value if it is an ExpressionInterface
* ##### [getField()](#getField()) public
Returns the field name
* ##### [getOperator()](#getOperator()) public
Returns the operator used for comparison
* ##### [getType()](#getType()) public
Returns the type to be used for casting the value to a database representation
* ##### [getValue()](#getValue()) public
Returns the value used for comparison
* ##### [isMulti()](#isMulti()) public
Determines if each of the values in this expressions is a tuple in itself
* ##### [setField()](#setField()) public
Sets the field name
* ##### [setOperator()](#setOperator()) public
Sets the operator to use for the comparison
* ##### [setValue()](#setValue()) public
Sets the value
* ##### [sql()](#sql()) public
Converts the Node into a SQL string fragment.
* ##### [traverse()](#traverse()) public
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
Method Detail
-------------
### \_\_clone() public
```
__clone(): void
```
Create a deep clone.
Clones the field and value if they are expression objects.
#### Returns
`void`
### \_\_construct() public
```
__construct(Cake\Database\ExpressionInterface|array|string $fields, Cake\Database\ExpressionInterface|array $values, array<string|null> $types = [], string $conjunction = '=')
```
Constructor
#### Parameters
`Cake\Database\ExpressionInterface|array|string` $fields the fields to use to form a tuple
`Cake\Database\ExpressionInterface|array` $values the values to use to form a tuple
`array<string|null>` $types optional the types names to use for casting each of the values, only one type per position in the value array in needed
`string` $conjunction optional the operator used for comparing field and value
### \_bindValue() protected
```
_bindValue(mixed $value, Cake\Database\ValueBinder $binder, string|null $type = null): string
```
Registers a value in the placeholder generator and returns the generated placeholder
#### Parameters
`mixed` $value `Cake\Database\ValueBinder` $binder `string|null` $type optional #### Returns
`string`
### \_castToExpression() protected
```
_castToExpression(mixed $value, string|null $type = null): mixed
```
Conditionally converts the passed value to an ExpressionInterface object if the type class implements the ExpressionTypeInterface. Otherwise, returns the value unmodified.
#### Parameters
`mixed` $value The value to convert to ExpressionInterface
`string|null` $type optional The type name
#### Returns
`mixed`
### \_collectExpressions() protected
```
_collectExpressions(Cake\Database\ExpressionInterface|iterable $values): array
```
Returns an array with the original $values in the first position and all ExpressionInterface objects that could be found in the second position.
#### Parameters
`Cake\Database\ExpressionInterface|iterable` $values The rows to insert
#### Returns
`array`
### \_flattenValue() protected
```
_flattenValue(iterable $value, Cake\Database\ValueBinder $binder, string|null $type = null): string
```
Converts a traversable value into a set of placeholders generated by $binder and separated by `,`
#### Parameters
`iterable` $value the value to flatten
`Cake\Database\ValueBinder` $binder The value binder to use
`string|null` $type optional the type to cast values to
#### Returns
`string`
### \_requiresToExpressionCasting() protected
```
_requiresToExpressionCasting(array $types): array
```
Returns an array with the types that require values to be casted to expressions, out of the list of type names passed as parameter.
#### Parameters
`array` $types List of type names
#### Returns
`array`
### \_stringExpression() protected
```
_stringExpression(Cake\Database\ValueBinder $binder): array
```
Returns a template and a placeholder for the value after registering it with the placeholder $binder
#### Parameters
`Cake\Database\ValueBinder` $binder The value binder to use.
#### Returns
`array`
### \_stringifyValues() protected
```
_stringifyValues(Cake\Database\ValueBinder $binder): string
```
Returns a string with the values as placeholders in a string to be used for the SQL version of this expression
#### Parameters
`Cake\Database\ValueBinder` $binder The value binder to convert expressions with.
#### Returns
`string`
### \_traverseValue() protected
```
_traverseValue(mixed $value, Closure $callback): void
```
Conditionally executes the callback for the passed value if it is an ExpressionInterface
#### Parameters
`mixed` $value The value to traverse
`Closure` $callback The callable to use when traversing
#### Returns
`void`
### getField() public
```
getField(): Cake\Database\ExpressionInterface|array|string
```
Returns the field name
#### Returns
`Cake\Database\ExpressionInterface|array|string`
### getOperator() public
```
getOperator(): string
```
Returns the operator used for comparison
#### Returns
`string`
### getType() public
```
getType(): array<string|null>
```
Returns the type to be used for casting the value to a database representation
#### Returns
`array<string|null>`
### getValue() public
```
getValue(): mixed
```
Returns the value used for comparison
#### Returns
`mixed`
### isMulti() public
```
isMulti(): bool
```
Determines if each of the values in this expressions is a tuple in itself
#### Returns
`bool`
### setField() public
```
setField(Cake\Database\ExpressionInterface|array|string $field): void
```
Sets the field name
#### Parameters
`Cake\Database\ExpressionInterface|array|string` $field The field to compare with.
#### Returns
`void`
### setOperator() public
```
setOperator(string $operator): void
```
Sets the operator to use for the comparison
#### Parameters
`string` $operator The operator to be used for the comparison.
#### Returns
`void`
### setValue() public
```
setValue(mixed $value): void
```
Sets the value
#### Parameters
`mixed` $value The value to compare
#### Returns
`void`
### sql() public
```
sql(Cake\Database\ValueBinder $binder): string
```
Converts the Node into a SQL string fragment.
#### Parameters
`Cake\Database\ValueBinder` $binder #### Returns
`string`
### traverse() public
```
traverse(Closure $callback): $this
```
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
#### Parameters
`Closure` $callback #### Returns
`$this`
Property Detail
---------------
### $\_field protected
The field name or expression to be used in the left hand side of the operator
#### Type
`Cake\Database\ExpressionInterface|array|string`
### $\_isMultiple protected
Whether the value in this expression is a traversable
#### Type
`bool`
### $\_operator protected
The operator used for comparing field and value
#### Type
`string`
### $\_type protected
The type to be used for casting the value to a database representation
#### Type
`array<string|null>`
### $\_value protected
The value to be used in the right hand side of the operation
#### Type
`mixed`
### $\_valueExpressions protected
A cached list of ExpressionInterface objects that were found in the value for this expression.
#### Type
`arrayCake\Database\ExpressionInterface>`
cakephp Class Association Class Association
==================
An Association is a relationship established between two tables and is used to configure and customize the way interconnected records are retrieved.
**Abstract**
**Namespace:** [Cake\ORM](namespace-cake.orm)
Constants
---------
* `string` **MANY\_TO\_MANY**
```
'manyToMany'
```
Association type for many to many associations.
* `string` **MANY\_TO\_ONE**
```
'manyToOne'
```
Association type for many to one associations.
* `string` **ONE\_TO\_MANY**
```
'oneToMany'
```
Association type for one to many associations.
* `string` **ONE\_TO\_ONE**
```
'oneToOne'
```
Association type for one to one associations.
* `string` **STRATEGY\_JOIN**
```
'join'
```
Strategy name to use joins for fetching associated records
* `string` **STRATEGY\_SELECT**
```
'select'
```
Strategy name to use a select for fetching associated records
* `string` **STRATEGY\_SUBQUERY**
```
'subquery'
```
Strategy name to use a subquery for fetching associated records
Property Summary
----------------
* [$\_bindingKey](#%24_bindingKey) protected `array<string>|string|null` The field name in the owning side table that is used to match with the foreignKey
* [$\_cascadeCallbacks](#%24_cascadeCallbacks) protected `bool` Whether cascaded deletes should also fire callbacks.
* [$\_className](#%24_className) protected `string` The class name of the target table object
* [$\_conditions](#%24_conditions) protected `Closure|array` A list of conditions to be always included when fetching records from the target association
* [$\_dependent](#%24_dependent) protected `bool` Whether the records on the target table are dependent on the source table, often used to indicate that records should be removed if the owning record in the source table is deleted.
* [$\_finder](#%24_finder) protected `array|string` The default finder name to use for fetching rows from the target table With array value, finder name and default options are allowed.
* [$\_foreignKey](#%24_foreignKey) protected `array<string>|string` The name of the field representing the foreign key to the table to load
* [$\_joinType](#%24_joinType) protected `string` The type of join to be used when adding the association to a query
* [$\_name](#%24_name) protected `string` Name given to the association, it usually represents the alias assigned to the target associated table
* [$\_propertyName](#%24_propertyName) protected `string` The property name that should be filled with data from the target table in the source table record.
* [$\_sourceTable](#%24_sourceTable) protected `Cake\ORM\Table` Source table instance
* [$\_strategy](#%24_strategy) protected `string` The strategy name to be used to fetch associated records. Some association types might not implement but one strategy to fetch records.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$\_targetTable](#%24_targetTable) protected `Cake\ORM\Table` Target table instance
* [$\_validStrategies](#%24_validStrategies) protected `array<string>` Valid strategies for this association. Subclasses can narrow this down.
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
Method Summary
--------------
* ##### [\_\_call()](#__call()) public
Proxies method calls to the target table.
* ##### [\_\_construct()](#__construct()) public
Constructor. Subclasses can override \_options function to get the original list of passed options if expecting any other special key
* ##### [\_\_get()](#__get()) public
Proxies property retrieval to the target table. This is handy for getting this association's associations
* ##### [\_\_isset()](#__isset()) public
Proxies the isset call to the target table. This is handy to check if the target table has another association with the passed name
* ##### [\_appendFields()](#_appendFields()) protected
Helper function used to conditionally append fields to the select clause of a query from the fields found in another query object.
* ##### [\_appendNotMatching()](#_appendNotMatching()) protected
Conditionally adds a condition to the passed Query that will make it find records where there is no match with this association.
* ##### [\_bindNewAssociations()](#_bindNewAssociations()) protected
Applies all attachable associations to `$query` out of the containments found in the `$surrogate` query.
* ##### [\_camelize()](#_camelize()) protected
Creates a camelized version of $name
* ##### [\_dispatchBeforeFind()](#_dispatchBeforeFind()) protected
Triggers beforeFind on the target table for the query this association is attaching to
* ##### [\_entityName()](#_entityName()) protected
Creates the proper entity name (singular) for the specified name
* ##### [\_extractFinder()](#_extractFinder()) protected
Helper method to infer the requested finder and its options.
* ##### [\_fixtureName()](#_fixtureName()) protected
Creates a fixture name
* ##### [\_formatAssociationResults()](#_formatAssociationResults()) protected
Adds a formatter function to the passed `$query` if the `$surrogate` query declares any other formatter. Since the `$surrogate` query correspond to the associated target table, the resulting formatter will be the result of applying the surrogate formatters to only the property corresponding to such table.
* ##### [\_joinCondition()](#_joinCondition()) protected
Returns a single or multiple conditions to be appended to the generated join clause for getting the results on the target table.
* ##### [\_modelKey()](#_modelKey()) protected
Creates the proper underscored model key for associations
* ##### [\_modelNameFromKey()](#_modelNameFromKey()) protected
Creates the proper model name from a foreign key
* ##### [\_options()](#_options()) protected
Override this function to initialize any concrete association class, it will get passed the original list of options used in the constructor
* ##### [\_pluginNamespace()](#_pluginNamespace()) protected
Return plugin's namespace
* ##### [\_pluginPath()](#_pluginPath()) protected
Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
* ##### [\_pluralHumanName()](#_pluralHumanName()) protected
Creates the plural human name used in views
* ##### [\_propertyName()](#_propertyName()) protected
Returns default property name based on association name.
* ##### [\_singularHumanName()](#_singularHumanName()) protected
Creates the singular human name used in views
* ##### [\_singularName()](#_singularName()) protected
Creates the singular name for use in views.
* ##### [\_variableName()](#_variableName()) protected
Creates the plural variable name for views
* ##### [attachTo()](#attachTo()) public
Alters a Query object to include the associated target table data in the final result
* ##### [canBeJoined()](#canBeJoined()) public
Whether this association can be expressed directly in a query join
* ##### [cascadeDelete()](#cascadeDelete()) abstract public
Handles cascading a delete from an associated model.
* ##### [defaultRowValue()](#defaultRowValue()) public
Returns a modified row after appending a property for this association with the default empty value according to whether the association was joined or fetched externally.
* ##### [deleteAll()](#deleteAll()) public
Proxies the delete operation to the target table's deleteAll method
* ##### [eagerLoader()](#eagerLoader()) abstract public
Eager loads a list of records in the target table that are related to another set of records in the source table. Source records can be specified in two ways: first one is by passing a Query object setup to find on the source table and the other way is by explicitly passing an array of primary key values from the source table.
* ##### [exists()](#exists()) public
Proxies the operation to the target table's exists method after appending the default conditions for this association
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [find()](#find()) public
Proxies the finding operation to the target table's find method and modifies the query accordingly based of this association configuration
* ##### [getBindingKey()](#getBindingKey()) public
Gets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
* ##### [getCascadeCallbacks()](#getCascadeCallbacks()) public
Gets whether cascaded deletes should also fire callbacks.
* ##### [getClassName()](#getClassName()) public
Gets the class name of the target table object.
* ##### [getConditions()](#getConditions()) public
Gets a list of conditions to be always included when fetching records from the target association.
* ##### [getDependent()](#getDependent()) public
Sets whether the records on the target table are dependent on the source table.
* ##### [getFinder()](#getFinder()) public
Gets the default finder to use for fetching rows from the target table.
* ##### [getForeignKey()](#getForeignKey()) public
Gets the name of the field representing the foreign key to the target table.
* ##### [getJoinType()](#getJoinType()) public
Gets the type of join to be used when adding the association to a query.
* ##### [getName()](#getName()) public
Gets the name for this association, usually the alias assigned to the target associated table
* ##### [getProperty()](#getProperty()) public
Gets the property name that should be filled with data from the target table in the source table record.
* ##### [getSource()](#getSource()) public
Gets the table instance for the source side of the association.
* ##### [getStrategy()](#getStrategy()) public
Gets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [getTarget()](#getTarget()) public
Gets the table instance for the target side of the association.
* ##### [isOwningSide()](#isOwningSide()) abstract public
Returns whether the passed table is the owning side for this association. This means that rows in the 'target' table would miss important or required information if the row in 'source' did not exist.
* ##### [requiresKeys()](#requiresKeys()) public
Returns true if the eager loading process will require a set of the owning table's binding keys in order to use them as a filter in the finder query.
* ##### [saveAssociated()](#saveAssociated()) abstract public
Extract the target's association data our from the passed entity and proxies the saving operation to the target table.
* ##### [setBindingKey()](#setBindingKey()) public
Sets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
* ##### [setCascadeCallbacks()](#setCascadeCallbacks()) public
Sets whether cascaded deletes should also fire callbacks.
* ##### [setClassName()](#setClassName()) public
Sets the class name of the target table object.
* ##### [setConditions()](#setConditions()) public
Sets a list of conditions to be always included when fetching records from the target association.
* ##### [setDependent()](#setDependent()) public
Sets whether the records on the target table are dependent on the source table.
* ##### [setFinder()](#setFinder()) public
Sets the default finder to use for fetching rows from the target table.
* ##### [setForeignKey()](#setForeignKey()) public
Sets the name of the field representing the foreign key to the target table.
* ##### [setJoinType()](#setJoinType()) public
Sets the type of join to be used when adding the association to a query.
* ##### [setName()](#setName()) public deprecated
Sets the name for this association, usually the alias assigned to the target associated table
* ##### [setProperty()](#setProperty()) public
Sets the property name that should be filled with data from the target table in the source table record.
* ##### [setSource()](#setSource()) public
Sets the table instance for the source side of the association.
* ##### [setStrategy()](#setStrategy()) public
Sets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
* ##### [setTarget()](#setTarget()) public
Sets the table instance for the target side of the association.
* ##### [transformRow()](#transformRow()) public
Correctly nests a result row associated values into the correct array keys inside the source results.
* ##### [type()](#type()) abstract public
Get the relationship type.
* ##### [updateAll()](#updateAll()) public
Proxies the update operation to the target table's updateAll method
Method Detail
-------------
### \_\_call() public
```
__call(string $method, array $argument): mixed
```
Proxies method calls to the target table.
#### Parameters
`string` $method name of the method to be invoked
`array` $argument List of arguments passed to the function
#### Returns
`mixed`
#### Throws
`BadMethodCallException`
### \_\_construct() public
```
__construct(string $alias, array<string, mixed> $options = [])
```
Constructor. Subclasses can override \_options function to get the original list of passed options if expecting any other special key
#### Parameters
`string` $alias The name given to the association
`array<string, mixed>` $options optional A list of properties to be set on this object
### \_\_get() public
```
__get(string $property): Cake\ORM\Association
```
Proxies property retrieval to the target table. This is handy for getting this association's associations
#### Parameters
`string` $property the property name
#### Returns
`Cake\ORM\Association`
#### Throws
`RuntimeException`
if no association with such name exists ### \_\_isset() public
```
__isset(string $property): bool
```
Proxies the isset call to the target table. This is handy to check if the target table has another association with the passed name
#### Parameters
`string` $property the property name
#### Returns
`bool`
### \_appendFields() protected
```
_appendFields(Cake\ORM\Query $query, Cake\ORM\Query $surrogate, array<string, mixed> $options): void
```
Helper function used to conditionally append fields to the select clause of a query from the fields found in another query object.
#### Parameters
`Cake\ORM\Query` $query the query that will get the fields appended to
`Cake\ORM\Query` $surrogate the query having the fields to be copied from
`array<string, mixed>` $options options passed to the method `attachTo`
#### Returns
`void`
### \_appendNotMatching() protected
```
_appendNotMatching(Cake\ORM\Query $query, array<string, mixed> $options): void
```
Conditionally adds a condition to the passed Query that will make it find records where there is no match with this association.
#### Parameters
`Cake\ORM\Query` $query The query to modify
`array<string, mixed>` $options Options array containing the `negateMatch` key.
#### Returns
`void`
### \_bindNewAssociations() protected
```
_bindNewAssociations(Cake\ORM\Query $query, Cake\ORM\Query $surrogate, array<string, mixed> $options): void
```
Applies all attachable associations to `$query` out of the containments found in the `$surrogate` query.
Copies all contained associations from the `$surrogate` query into the passed `$query`. Containments are altered so that they respect the associations chain from which they originated.
#### Parameters
`Cake\ORM\Query` $query the query that will get the associations attached to
`Cake\ORM\Query` $surrogate the query having the containments to be attached
`array<string, mixed>` $options options passed to the method `attachTo`
#### Returns
`void`
### \_camelize() protected
```
_camelize(string $name): string
```
Creates a camelized version of $name
#### Parameters
`string` $name name
#### Returns
`string`
### \_dispatchBeforeFind() protected
```
_dispatchBeforeFind(Cake\ORM\Query $query): void
```
Triggers beforeFind on the target table for the query this association is attaching to
#### Parameters
`Cake\ORM\Query` $query the query this association is attaching itself to
#### Returns
`void`
### \_entityName() protected
```
_entityName(string $name): string
```
Creates the proper entity name (singular) for the specified name
#### Parameters
`string` $name Name
#### Returns
`string`
### \_extractFinder() protected
```
_extractFinder(array|string $finderData): array
```
Helper method to infer the requested finder and its options.
Returns the inferred options from the finder $type.
### Examples:
The following will call the finder 'translations' with the value of the finder as its options: $query->contain(['Comments' => ['finder' => ['translations']]]); $query->contain(['Comments' => ['finder' => ['translations' => []]]]); $query->contain(['Comments' => ['finder' => ['translations' => ['locales' => ['en\_US']]]]]);
#### Parameters
`array|string` $finderData The finder name or an array having the name as key and options as value.
#### Returns
`array`
### \_fixtureName() protected
```
_fixtureName(string $name): string
```
Creates a fixture name
#### Parameters
`string` $name Model class name
#### Returns
`string`
### \_formatAssociationResults() protected
```
_formatAssociationResults(Cake\ORM\Query $query, Cake\ORM\Query $surrogate, array<string, mixed> $options): void
```
Adds a formatter function to the passed `$query` if the `$surrogate` query declares any other formatter. Since the `$surrogate` query correspond to the associated target table, the resulting formatter will be the result of applying the surrogate formatters to only the property corresponding to such table.
#### Parameters
`Cake\ORM\Query` $query the query that will get the formatter applied to
`Cake\ORM\Query` $surrogate the query having formatters for the associated target table.
`array<string, mixed>` $options options passed to the method `attachTo`
#### Returns
`void`
### \_joinCondition() protected
```
_joinCondition(array<string, mixed> $options): array
```
Returns a single or multiple conditions to be appended to the generated join clause for getting the results on the target table.
#### Parameters
`array<string, mixed>` $options list of options passed to attachTo method
#### Returns
`array`
#### Throws
`RuntimeException`
if the number of columns in the foreignKey do not match the number of columns in the source table primaryKey ### \_modelKey() protected
```
_modelKey(string $name): string
```
Creates the proper underscored model key for associations
If the input contains a dot, assume that the right side is the real table name.
#### Parameters
`string` $name Model class name
#### Returns
`string`
### \_modelNameFromKey() protected
```
_modelNameFromKey(string $key): string
```
Creates the proper model name from a foreign key
#### Parameters
`string` $key Foreign key
#### Returns
`string`
### \_options() protected
```
_options(array<string, mixed> $options): void
```
Override this function to initialize any concrete association class, it will get passed the original list of options used in the constructor
#### Parameters
`array<string, mixed>` $options List of options used for initialization
#### Returns
`void`
### \_pluginNamespace() protected
```
_pluginNamespace(string $pluginName): string
```
Return plugin's namespace
#### Parameters
`string` $pluginName Plugin name
#### Returns
`string`
### \_pluginPath() protected
```
_pluginPath(string $pluginName): string
```
Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
#### Parameters
`string` $pluginName Name of the plugin you want ie. DebugKit
#### Returns
`string`
### \_pluralHumanName() protected
```
_pluralHumanName(string $name): string
```
Creates the plural human name used in views
#### Parameters
`string` $name Controller name
#### Returns
`string`
### \_propertyName() protected
```
_propertyName(): string
```
Returns default property name based on association name.
#### Returns
`string`
### \_singularHumanName() protected
```
_singularHumanName(string $name): string
```
Creates the singular human name used in views
#### Parameters
`string` $name Controller name
#### Returns
`string`
### \_singularName() protected
```
_singularName(string $name): string
```
Creates the singular name for use in views.
#### Parameters
`string` $name Name to use
#### Returns
`string`
### \_variableName() protected
```
_variableName(string $name): string
```
Creates the plural variable name for views
#### Parameters
`string` $name Name to use
#### Returns
`string`
### attachTo() public
```
attachTo(Cake\ORM\Query $query, array<string, mixed> $options = []): void
```
Alters a Query object to include the associated target table data in the final result
The options array accept the following keys:
* includeFields: Whether to include target model fields in the result or not
* foreignKey: The name of the field to use as foreign key, if false none will be used
* conditions: array with a list of conditions to filter the join with, this will be merged with any conditions originally configured for this association
* fields: a list of fields in the target table to include in the result
* aliasPath: A dot separated string representing the path of association names followed from the passed query main table to this association.
* propertyPath: A dot separated string representing the path of association properties to be followed from the passed query main entity to this association
* joinType: The SQL join type to use in the query.
* negateMatch: Will append a condition to the passed query for excluding matches. with this association.
#### Parameters
`Cake\ORM\Query` $query the query to be altered to include the target table data
`array<string, mixed>` $options optional Any extra options or overrides to be taken in account
#### Returns
`void`
#### Throws
`RuntimeException`
Unable to build the query or associations. ### canBeJoined() public
```
canBeJoined(array<string, mixed> $options = []): bool
```
Whether this association can be expressed directly in a query join
#### Parameters
`array<string, mixed>` $options optional custom options key that could alter the return value
#### Returns
`bool`
### cascadeDelete() abstract public
```
cascadeDelete(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): bool
```
Handles cascading a delete from an associated model.
Each implementing class should handle the cascaded delete as required.
#### Parameters
`Cake\Datasource\EntityInterface` $entity The entity that started the cascaded delete.
`array<string, mixed>` $options optional The options for the original delete.
#### Returns
`bool`
### defaultRowValue() public
```
defaultRowValue(array<string, mixed> $row, bool $joined): array<string, mixed>
```
Returns a modified row after appending a property for this association with the default empty value according to whether the association was joined or fetched externally.
#### Parameters
`array<string, mixed>` $row The row to set a default on.
`bool` $joined Whether the row is a result of a direct join with this association
#### Returns
`array<string, mixed>`
### deleteAll() public
```
deleteAll(Cake\Database\ExpressionInterfaceClosure|array|string|null $conditions): int
```
Proxies the delete operation to the target table's deleteAll method
#### Parameters
`Cake\Database\ExpressionInterfaceClosure|array|string|null` $conditions Conditions to be used, accepts anything Query::where() can take.
#### Returns
`int`
#### See Also
\Cake\ORM\Table::deleteAll() ### eagerLoader() abstract public
```
eagerLoader(array<string, mixed> $options): Closure
```
Eager loads a list of records in the target table that are related to another set of records in the source table. Source records can be specified in two ways: first one is by passing a Query object setup to find on the source table and the other way is by explicitly passing an array of primary key values from the source table.
The required way of passing related source records is controlled by "strategy" When the subquery strategy is used it will require a query on the source table. When using the select strategy, the list of primary keys will be used.
Returns a closure that should be run for each record returned in a specific Query. This callable will be responsible for injecting the fields that are related to each specific passed row.
Options array accepts the following keys:
* query: Query object setup to find the source table records
* keys: List of primary key values from the source table
* foreignKey: The name of the field used to relate both tables
* conditions: List of conditions to be passed to the query where() method
* sort: The direction in which the records should be returned
* fields: List of fields to select from the target table
* contain: List of related tables to eager load associated to the target table
* strategy: The name of strategy to use for finding target table records
* nestKey: The array key under which results will be found when transforming the row
#### Parameters
`array<string, mixed>` $options The options for eager loading.
#### Returns
`Closure`
### exists() public
```
exists(Cake\Database\ExpressionInterfaceClosure|array|string|null $conditions): bool
```
Proxies the operation to the target table's exists method after appending the default conditions for this association
#### Parameters
`Cake\Database\ExpressionInterfaceClosure|array|string|null` $conditions The conditions to use for checking if any record matches.
#### Returns
`bool`
#### See Also
\Cake\ORM\Table::exists() ### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### find() public
```
find(array<string, mixed>|string|null $type = null, array<string, mixed> $options = []): Cake\ORM\Query
```
Proxies the finding operation to the target table's find method and modifies the query accordingly based of this association configuration
#### Parameters
`array<string, mixed>|string|null` $type optional the type of query to perform, if an array is passed, it will be interpreted as the `$options` parameter
`array<string, mixed>` $options optional The options to for the find
#### Returns
`Cake\ORM\Query`
#### See Also
\Cake\ORM\Table::find() ### getBindingKey() public
```
getBindingKey(): array<string>|string
```
Gets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
#### Returns
`array<string>|string`
### getCascadeCallbacks() public
```
getCascadeCallbacks(): bool
```
Gets whether cascaded deletes should also fire callbacks.
#### Returns
`bool`
### getClassName() public
```
getClassName(): string
```
Gets the class name of the target table object.
#### Returns
`string`
### getConditions() public
```
getConditions(): Closure|array
```
Gets a list of conditions to be always included when fetching records from the target association.
#### Returns
`Closure|array`
#### See Also
\Cake\Database\Query::where() for examples on the format of the array ### getDependent() public
```
getDependent(): bool
```
Sets whether the records on the target table are dependent on the source table.
This is primarily used to indicate that records should be removed if the owning record in the source table is deleted.
#### Returns
`bool`
### getFinder() public
```
getFinder(): array|string
```
Gets the default finder to use for fetching rows from the target table.
#### Returns
`array|string`
### getForeignKey() public
```
getForeignKey(): array<string>|string
```
Gets the name of the field representing the foreign key to the target table.
#### Returns
`array<string>|string`
### getJoinType() public
```
getJoinType(): string
```
Gets the type of join to be used when adding the association to a query.
#### Returns
`string`
### getName() public
```
getName(): string
```
Gets the name for this association, usually the alias assigned to the target associated table
#### Returns
`string`
### getProperty() public
```
getProperty(): string
```
Gets the property name that should be filled with data from the target table in the source table record.
#### Returns
`string`
### getSource() public
```
getSource(): Cake\ORM\Table
```
Gets the table instance for the source side of the association.
#### Returns
`Cake\ORM\Table`
### getStrategy() public
```
getStrategy(): string
```
Gets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void.
#### Returns
`string`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### getTarget() public
```
getTarget(): Cake\ORM\Table
```
Gets the table instance for the target side of the association.
#### Returns
`Cake\ORM\Table`
### isOwningSide() abstract public
```
isOwningSide(Cake\ORM\Table $side): bool
```
Returns whether the passed table is the owning side for this association. This means that rows in the 'target' table would miss important or required information if the row in 'source' did not exist.
#### Parameters
`Cake\ORM\Table` $side The potential Table with ownership
#### Returns
`bool`
### requiresKeys() public
```
requiresKeys(array<string, mixed> $options = []): bool
```
Returns true if the eager loading process will require a set of the owning table's binding keys in order to use them as a filter in the finder query.
#### Parameters
`array<string, mixed>` $options optional The options containing the strategy to be used.
#### Returns
`bool`
### saveAssociated() abstract public
```
saveAssociated(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): Cake\Datasource\EntityInterface|false
```
Extract the target's association data our from the passed entity and proxies the saving operation to the target table.
#### Parameters
`Cake\Datasource\EntityInterface` $entity the data to be saved
`array<string, mixed>` $options optional The options for saving associated data.
#### Returns
`Cake\Datasource\EntityInterface|false`
#### See Also
\Cake\ORM\Table::save() ### setBindingKey() public
```
setBindingKey(array<string>|string $key): $this
```
Sets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
#### Parameters
`array<string>|string` $key the table field or fields to be used to link both tables together
#### Returns
`$this`
### setCascadeCallbacks() public
```
setCascadeCallbacks(bool $cascadeCallbacks): $this
```
Sets whether cascaded deletes should also fire callbacks.
#### Parameters
`bool` $cascadeCallbacks cascade callbacks switch value
#### Returns
`$this`
### setClassName() public
```
setClassName(string $className): $this
```
Sets the class name of the target table object.
#### Parameters
`string` $className Class name to set.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
In case the class name is set after the target table has been resolved, and it doesn't match the target table's class name. ### setConditions() public
```
setConditions(Closure|array $conditions): $this
```
Sets a list of conditions to be always included when fetching records from the target association.
#### Parameters
`Closure|array` $conditions list of conditions to be used
#### Returns
`$this`
#### See Also
\Cake\Database\Query::where() for examples on the format of the array ### setDependent() public
```
setDependent(bool $dependent): $this
```
Sets whether the records on the target table are dependent on the source table.
This is primarily used to indicate that records should be removed if the owning record in the source table is deleted.
If no parameters are passed the current setting is returned.
#### Parameters
`bool` $dependent Set the dependent mode. Use null to read the current state.
#### Returns
`$this`
### setFinder() public
```
setFinder(array|string $finder): $this
```
Sets the default finder to use for fetching rows from the target table.
#### Parameters
`array|string` $finder the finder name to use or array of finder name and option.
#### Returns
`$this`
### setForeignKey() public
```
setForeignKey(array<string>|string $key): $this
```
Sets the name of the field representing the foreign key to the target table.
#### Parameters
`array<string>|string` $key the key or keys to be used to link both tables together
#### Returns
`$this`
### setJoinType() public
```
setJoinType(string $type): $this
```
Sets the type of join to be used when adding the association to a query.
#### Parameters
`string` $type the join type to be used (e.g. INNER)
#### Returns
`$this`
### setName() public
```
setName(string $name): $this
```
Sets the name for this association, usually the alias assigned to the target associated table
#### Parameters
`string` $name Name to be assigned
#### Returns
`$this`
### setProperty() public
```
setProperty(string $name): $this
```
Sets the property name that should be filled with data from the target table in the source table record.
#### Parameters
`string` $name The name of the association property. Use null to read the current value.
#### Returns
`$this`
### setSource() public
```
setSource(Cake\ORM\Table $table): $this
```
Sets the table instance for the source side of the association.
#### Parameters
`Cake\ORM\Table` $table the instance to be assigned as source side
#### Returns
`$this`
### setStrategy() public
```
setStrategy(string $name): $this
```
Sets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void.
#### Parameters
`string` $name The strategy type. Use null to read the current value.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
When an invalid strategy is provided. ### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
### setTarget() public
```
setTarget(Cake\ORM\Table $table): $this
```
Sets the table instance for the target side of the association.
#### Parameters
`Cake\ORM\Table` $table the instance to be assigned as target side
#### Returns
`$this`
### transformRow() public
```
transformRow(array $row, string $nestKey, bool $joined, string|null $targetProperty = null): array
```
Correctly nests a result row associated values into the correct array keys inside the source results.
#### Parameters
`array` $row The row to transform
`string` $nestKey The array key under which the results for this association should be found
`bool` $joined Whether the row is a result of a direct join with this association
`string|null` $targetProperty optional The property name in the source results where the association data shuld be nested in. Will use the default one if not provided.
#### Returns
`array`
### type() abstract public
```
type(): string
```
Get the relationship type.
#### Returns
`string`
### updateAll() public
```
updateAll(array $fields, Cake\Database\ExpressionInterfaceClosure|array|string|null $conditions): int
```
Proxies the update operation to the target table's updateAll method
#### Parameters
`array` $fields A hash of field => new value.
`Cake\Database\ExpressionInterfaceClosure|array|string|null` $conditions Conditions to be used, accepts anything Query::where() can take.
#### Returns
`int`
#### See Also
\Cake\ORM\Table::updateAll() Property Detail
---------------
### $\_bindingKey protected
The field name in the owning side table that is used to match with the foreignKey
#### Type
`array<string>|string|null`
### $\_cascadeCallbacks protected
Whether cascaded deletes should also fire callbacks.
#### Type
`bool`
### $\_className protected
The class name of the target table object
#### Type
`string`
### $\_conditions protected
A list of conditions to be always included when fetching records from the target association
#### Type
`Closure|array`
### $\_dependent protected
Whether the records on the target table are dependent on the source table, often used to indicate that records should be removed if the owning record in the source table is deleted.
#### Type
`bool`
### $\_finder protected
The default finder name to use for fetching rows from the target table With array value, finder name and default options are allowed.
#### Type
`array|string`
### $\_foreignKey protected
The name of the field representing the foreign key to the table to load
#### Type
`array<string>|string`
### $\_joinType protected
The type of join to be used when adding the association to a query
#### Type
`string`
### $\_name protected
Name given to the association, it usually represents the alias assigned to the target associated table
#### Type
`string`
### $\_propertyName protected
The property name that should be filled with data from the target table in the source table record.
#### Type
`string`
### $\_sourceTable protected
Source table instance
#### Type
`Cake\ORM\Table`
### $\_strategy protected
The strategy name to be used to fetch associated records. Some association types might not implement but one strategy to fetch records.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $\_targetTable protected
Target table instance
#### Type
`Cake\ORM\Table`
### $\_validStrategies protected
Valid strategies for this association. Subclasses can narrow this down.
#### Type
`array<string>`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
| programming_docs |
cakephp Class MissingHelperException Class MissingHelperException
=============================
Used when a Helper cannot be found.
**Namespace:** [Cake\Console\Exception](namespace-cake.console.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Namespace Type Namespace Type
==============
### Interfaces
* ##### [BatchCastingInterface](interface-cake.database.type.batchcastinginterface)
Denotes type objects capable of converting many values from their original database representation to php values.
* ##### [ColumnSchemaAwareInterface](interface-cake.database.type.columnschemaawareinterface)
* ##### [ExpressionTypeInterface](interface-cake.database.type.expressiontypeinterface)
An interface used by Type objects to signal whether the value should be converted to an ExpressionInterface instead of a string when sent to the database.
* ##### [OptionalConvertInterface](interface-cake.database.type.optionalconvertinterface)
An interface used by Type objects to signal whether the casting is actually required.
### Classes
* ##### [BaseType](class-cake.database.type.basetype)
Base type class.
* ##### [BinaryType](class-cake.database.type.binarytype)
Binary type converter.
* ##### [BinaryUuidType](class-cake.database.type.binaryuuidtype)
Binary UUID type converter.
* ##### [BoolType](class-cake.database.type.booltype)
Bool type converter.
* ##### [DateTimeFractionalType](class-cake.database.type.datetimefractionaltype)
Extends DateTimeType with support for fractional seconds up to microseconds.
* ##### [DateTimeTimezoneType](class-cake.database.type.datetimetimezonetype)
Extends DateTimeType with support for time zones.
* ##### [DateTimeType](class-cake.database.type.datetimetype)
Datetime type converter.
* ##### [DateType](class-cake.database.type.datetype)
Class DateType
* ##### [DecimalType](class-cake.database.type.decimaltype)
Decimal type converter.
* ##### [FloatType](class-cake.database.type.floattype)
Float type converter.
* ##### [IntegerType](class-cake.database.type.integertype)
Integer type converter.
* ##### [JsonType](class-cake.database.type.jsontype)
JSON type converter.
* ##### [StringType](class-cake.database.type.stringtype)
String type converter.
* ##### [TimeType](class-cake.database.type.timetype)
Time type converter.
* ##### [UuidType](class-cake.database.type.uuidtype)
Provides behavior for the UUID type
### Traits
* ##### [ExpressionTypeCasterTrait](trait-cake.database.type.expressiontypecastertrait)
Offers a method to convert values to ExpressionInterface objects if the type they should be converted to implements ExpressionTypeInterface
cakephp Class EventFired Class EventFired
=================
EventFired constraint
**Namespace:** [Cake\TestSuite\Constraint](namespace-cake.testsuite.constraint)
Property Summary
----------------
* [$\_eventManager](#%24_eventManager) protected `Cake\Event\EventManager` Array of fired events
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Checks if event is in fired array
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message string
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Event\EventManager $eventManager)
```
Constructor
#### Parameters
`Cake\Event\EventManager` $eventManager Event manager to check
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks if event is in fired array
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Constraint check
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message string
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $\_eventManager protected
Array of fired events
#### Type
`Cake\Event\EventManager`
cakephp Class StatusOk Class StatusOk
===============
StatusOk
**Namespace:** [Cake\TestSuite\Constraint\Response](namespace-cake.testsuite.constraint.response)
Property Summary
----------------
* [$code](#%24code) protected `array<int, int>|int`
* [$response](#%24response) protected `Psr\Http\Message\ResponseInterface`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_getBodyAsString()](#_getBodyAsString()) protected
Get the response body as string
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Overwrites the descriptions so we can remove the automatic "expected" message
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Check assertion
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [statusCodeBetween()](#statusCodeBetween()) protected
Helper for checking status codes
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(Psr\Http\Message\ResponseInterface|null $response)
```
Constructor
#### Parameters
`Psr\Http\Message\ResponseInterface|null` $response Response
### \_getBodyAsString() protected
```
_getBodyAsString(): string
```
Get the response body as string
#### Returns
`string`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Overwrites the descriptions so we can remove the automatic "expected" message
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other Value
#### Returns
`string`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Check assertion
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Array of min/max status codes, or a single code
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### statusCodeBetween() protected
```
statusCodeBetween(int $min, int $max): bool
```
Helper for checking status codes
#### Parameters
`int` $min Min status code (inclusive)
`int` $max Max status code (inclusive)
#### Returns
`bool`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $code protected
#### Type
`array<int, int>|int`
### $response protected
#### Type
`Psr\Http\Message\ResponseInterface`
| programming_docs |
cakephp Class BufferedIterator Class BufferedIterator
=======================
Creates an iterator from another iterator that will keep the results of the inner iterator in memory, so that results don't have to be re-calculated.
**Namespace:** [Cake\Collection\Iterator](namespace-cake.collection.iterator)
Property Summary
----------------
* [$\_buffer](#%24_buffer) protected `SplDoublyLinkedList` The in-memory cache containing results from previous iterators
* [$\_current](#%24_current) protected `mixed` Last record fetched from the inner iterator
* [$\_finished](#%24_finished) protected `bool` Whether the internal iterator has reached its end.
* [$\_index](#%24_index) protected `int` Points to the next record number that should be fetched
* [$\_key](#%24_key) protected `mixed` Last key obtained from the inner iterator
* [$\_started](#%24_started) protected `bool` Whether the internal iterator's rewind method was already called
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Maintains an in-memory cache of the results yielded by the internal iterator.
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_serialize()](#__serialize()) public
Magic method used for serializing the iterator instance.
* ##### [\_\_unserialize()](#__unserialize()) public
Magic method used to rebuild the iterator instance.
* ##### [\_createMatcherFilter()](#_createMatcherFilter()) protected
Returns a callable that receives a value and will return whether it matches certain condition.
* ##### [\_extract()](#_extract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
* ##### [\_propertyExtractor()](#_propertyExtractor()) protected
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
* ##### [\_simpleExtract()](#_simpleExtract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path
* ##### [append()](#append()) public
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
* ##### [appendItem()](#appendItem()) public
Append a single item creating a new collection.
* ##### [avg()](#avg()) public
Returns the average of all the values extracted with $path or of this collection.
* ##### [buffered()](#buffered()) public
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
* ##### [cartesianProduct()](#cartesianProduct()) public
Create a new collection that is the cartesian product of the current collection
* ##### [chunk()](#chunk()) public
Breaks the collection into smaller arrays of the given size.
* ##### [chunkWithKeys()](#chunkWithKeys()) public
Breaks the collection into smaller arrays of the given size.
* ##### [combine()](#combine()) public
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
* ##### [compile()](#compile()) public
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
* ##### [contains()](#contains()) public
Returns true if $value is present in this collection. Comparisons are made both by value and type.
* ##### [count()](#count()) public
Returns the number or items in this collection
* ##### [countBy()](#countBy()) public
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
* ##### [countKeys()](#countKeys()) public
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
* ##### [current()](#current()) public
Returns the current record in the iterator
* ##### [each()](#each()) public
Applies a callback to the elements in this collection.
* ##### [every()](#every()) public
Returns true if all values in this collection pass the truth test provided in the callback.
* ##### [extract()](#extract()) public
Returns a new collection containing the column or property value found in each of the elements.
* ##### [filter()](#filter()) public
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
* ##### [first()](#first()) public
Returns the first result in this collection
* ##### [firstMatch()](#firstMatch()) public
Returns the first result matching all the key-value pairs listed in conditions.
* ##### [groupBy()](#groupBy()) public
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
* ##### [indexBy()](#indexBy()) public
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
* ##### [insert()](#insert()) public
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
* ##### [isEmpty()](#isEmpty()) public
Returns whether there are elements in this collection
* ##### [jsonSerialize()](#jsonSerialize()) public
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
* ##### [key()](#key()) public
Returns the current key in the iterator
* ##### [last()](#last()) public
Returns the last result in this collection
* ##### [lazy()](#lazy()) public
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
* ##### [listNested()](#listNested()) public
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
* ##### [map()](#map()) public
Returns another collection after modifying each of the values in this one using the provided callable.
* ##### [match()](#match()) public
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
* ##### [max()](#max()) public
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [median()](#median()) public
Returns the median of all the values extracted with $path or of this collection.
* ##### [min()](#min()) public
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [nest()](#nest()) public
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
* ##### [newCollection()](#newCollection()) protected
Returns a new collection.
* ##### [next()](#next()) public
Advances the iterator pointer to the next element
* ##### [optimizeUnwrap()](#optimizeUnwrap()) protected
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
* ##### [prepend()](#prepend()) public
Prepend a set of items to a collection creating a new collection
* ##### [prependItem()](#prependItem()) public
Prepend a single item creating a new collection.
* ##### [reduce()](#reduce()) public
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
* ##### [reject()](#reject()) public
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
* ##### [rewind()](#rewind()) public
Rewinds the collection
* ##### [sample()](#sample()) public
Returns a new collection with maximum $size random elements from this collection
* ##### [serialize()](#serialize()) public
Returns a string representation of this object that can be used to reconstruct it
* ##### [shuffle()](#shuffle()) public
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
* ##### [skip()](#skip()) public
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
* ##### [some()](#some()) public
Returns true if any of the values in this collection pass the truth test provided in the callback.
* ##### [sortBy()](#sortBy()) public
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
* ##### [stopWhen()](#stopWhen()) public
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
* ##### [sumOf()](#sumOf()) public
Returns the total sum of all the values extracted with $matcher or of this collection.
* ##### [take()](#take()) public
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
* ##### [takeLast()](#takeLast()) public
Returns the last N elements of a collection
* ##### [through()](#through()) public
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
* ##### [toArray()](#toArray()) public
Returns an array representation of the results
* ##### [toList()](#toList()) public
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
* ##### [transpose()](#transpose()) public
Transpose rows and columns into columns and rows
* ##### [unfold()](#unfold()) public
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
* ##### [unserialize()](#unserialize()) public
Unserializes the passed string and rebuilds the BufferedIterator instance
* ##### [unwrap()](#unwrap()) public
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
* ##### [valid()](#valid()) public
Returns whether the iterator has more elements
* ##### [zip()](#zip()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
* ##### [zipWith()](#zipWith()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
Method Detail
-------------
### \_\_construct() public
```
__construct(iterable $items)
```
Maintains an in-memory cache of the results yielded by the internal iterator.
#### Parameters
`iterable` $items The items to be filtered.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_serialize() public
```
__serialize(): array
```
Magic method used for serializing the iterator instance.
#### Returns
`array`
### \_\_unserialize() public
```
__unserialize(array $data): void
```
Magic method used to rebuild the iterator instance.
#### Parameters
`array` $data Data array.
#### Returns
`void`
### \_createMatcherFilter() protected
```
_createMatcherFilter(array $conditions): Closure
```
Returns a callable that receives a value and will return whether it matches certain condition.
#### Parameters
`array` $conditions A key-value list of conditions to match where the key is the property path to get from the current item and the value is the value to be compared the item with.
#### Returns
`Closure`
### \_extract() protected
```
_extract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### \_propertyExtractor() protected
```
_propertyExtractor(callable|string $path): callable
```
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
#### Parameters
`callable|string` $path A dot separated path of column to follow so that the final one can be returned or a callable that will take care of doing that.
#### Returns
`callable`
### \_simpleExtract() protected
```
_simpleExtract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### append() public
```
append(iterable $items): self
```
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
#### Parameters
`iterable` $items #### Returns
`self`
### appendItem() public
```
appendItem(mixed $item, mixed $key = null): self
```
Append a single item creating a new collection.
#### Parameters
`mixed` $item `mixed` $key optional #### Returns
`self`
### avg() public
```
avg(callable|string|null $path = null): float|int|null
```
Returns the average of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->avg('invoice.total');
// Total: 150
$total = (new Collection([1, 2, 3]))->avg();
// Total: 2
```
The average of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int|null`
### buffered() public
```
buffered(): self
```
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
This can also be used to make any non-rewindable iterator rewindable.
#### Returns
`self`
### cartesianProduct() public
```
cartesianProduct(callable|null $operation = null, callable|null $filter = null): Cake\Collection\CollectionInterface
```
Create a new collection that is the cartesian product of the current collection
In order to create a carteisan product a collection must contain a single dimension of data.
### Example
```
$collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
$result = $collection->cartesianProduct()->toArray();
$expected = [
['A', 1],
['A', 2],
['A', 3],
['B', 1],
['B', 2],
['B', 3],
['C', 1],
['C', 2],
['C', 3],
];
```
#### Parameters
`callable|null` $operation optional A callable that allows you to customize the product result.
`callable|null` $filter optional A filtering callback that must return true for a result to be part of the final results.
#### Returns
`Cake\Collection\CollectionInterface`
#### Throws
`LogicException`
### chunk() public
```
chunk(int $chunkSize): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
$chunked = (new Collection($items))->chunk(3)->toList();
// Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
```
#### Parameters
`int` $chunkSize #### Returns
`self`
### chunkWithKeys() public
```
chunkWithKeys(int $chunkSize, bool $keepKeys = true): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
$chunked = (new Collection($items))->chunkWithKeys(3)->toList();
// Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
```
#### Parameters
`int` $chunkSize `bool` $keepKeys optional #### Returns
`self`
### combine() public
```
combine(callable|string $keyPath, callable|string $valuePath, callable|string|null $groupPath = null): self
```
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
### Examples:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent' => 'a'],
['id' => 2, 'name' => 'bar', 'parent' => 'b'],
['id' => 3, 'name' => 'baz', 'parent' => 'a'],
];
$combined = (new Collection($items))->combine('id', 'name');
// Result will look like this when converted to array
[
1 => 'foo',
2 => 'bar',
3 => 'baz',
];
$combined = (new Collection($items))->combine('id', 'name', 'parent');
// Result will look like this when converted to array
[
'a' => [1 => 'foo', 3 => 'baz'],
'b' => [2 => 'bar']
];
```
#### Parameters
`callable|string` $keyPath `callable|string` $valuePath `callable|string|null` $groupPath optional #### Returns
`self`
### compile() public
```
compile(bool $keepKeys = true): self
```
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
A common use case is to re-use the same variable for calculating different data. In those cases it may be helpful and more performant to first compile a collection and then apply more operations to it.
### Example:
```
$collection->map($mapper)->sortBy('age')->extract('name');
$compiled = $collection->compile();
$isJohnHere = $compiled->some($johnMatcher);
$allButJohn = $compiled->filter($johnMatcher);
```
In the above example, had the collection not been compiled before, the iterations for `map`, `sortBy` and `extract` would've been executed twice: once for getting `$isJohnHere` and once for `$allButJohn`
You can think of this method as a way to create save points for complex calculations in a collection.
#### Parameters
`bool` $keepKeys optional #### Returns
`self`
### contains() public
```
contains(mixed $value): bool
```
Returns true if $value is present in this collection. Comparisons are made both by value and type.
#### Parameters
`mixed` $value #### Returns
`bool`
### count() public
```
count(): int
```
Returns the number or items in this collection
WARNINGS:
---------
### Will change the current position of the iterator:
Calling this method at the same time that you are iterating this collections, for example in a foreach, will result in undefined behavior. Avoid doing this.
### Consumes all elements for NoRewindIterator collections:
On certain type of collections, calling this method may render unusable afterwards. That is, you may not be able to get elements out of it, or to iterate on it anymore.
Specifically any collection wrapping a Generator (a function with a yield statement) or a unbuffered database cursor will not accept any other function calls after calling `count()` on it.
Create a new collection with `buffered()` method to overcome this problem.
### Can report more elements than unique keys:
Any collection constructed by appending collections together, or by having internal iterators returning duplicate keys, will report a larger amount of elements using this functions than the final amount of elements when converting the collections to a keyed array. This is because duplicate keys will be collapsed into a single one in the final array, whereas this count method is only concerned by the amount of elements after converting it to a plain list.
If you need the count of elements after taking the keys in consideration (the count of unique keys), you can call `countKeys()`
#### Returns
`int`
### countBy() public
```
countBy(callable|string $path): self
```
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->countBy('parent_id');
// Or
$group = (new Collection($items))->countBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => 2,
11 => 1
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### countKeys() public
```
countKeys(): int
```
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
This method comes with a number of caveats. Please refer to `CollectionInterface::count()` for details.
#### Returns
`int`
### current() public
```
current(): mixed
```
Returns the current record in the iterator
#### Returns
`mixed`
### each() public
```
each(callable $callback): $this
```
Applies a callback to the elements in this collection.
### Example:
```
$collection = (new Collection($items))->each(function ($value, $key) {
echo "Element $key: $value";
});
```
#### Parameters
`callable` $callback #### Returns
`$this`
### every() public
```
every(callable $callback): bool
```
Returns true if all values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$overTwentyOne = (new Collection([24, 45, 60, 15]))->every(function ($value, $key) {
return $value > 21;
});
```
Empty collections always return true.
#### Parameters
`callable` $callback #### Returns
`bool`
### extract() public
```
extract(callable|string $path): self
```
Returns a new collection containing the column or property value found in each of the elements.
The matcher can be a string with a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection, that position is filled with null.
### Example:
Extract the user name for all comments in the array:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->extract('comment.user.name');
// Result will look like this when converted to array
['Mark', 'Renan']
```
It is also possible to extract a flattened collection out of nested properties
```
$items = [
['comment' => ['votes' => [['value' => 1], ['value' => 2], ['value' => 3]]],
['comment' => ['votes' => [['value' => 4]]
];
$extracted = (new Collection($items))->extract('comment.votes.{*}.value');
// Result will contain
[1, 2, 3, 4]
```
#### Parameters
`callable|string` $path #### Returns
`self`
### filter() public
```
filter(callable|null $callback = null): self
```
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering odd numbers in an array, at the end only the value 2 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->filter(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable|null` $callback optional #### Returns
`self`
### first() public
```
first(): mixed
```
Returns the first result in this collection
#### Returns
`mixed`
### firstMatch() public
```
firstMatch(array $conditions): mixed
```
Returns the first result matching all the key-value pairs listed in conditions.
#### Parameters
`array` $conditions #### Returns
`mixed`
### groupBy() public
```
groupBy(callable|string $path): self
```
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->groupBy('parent_id');
// Or
$group = (new Collection($items))->groupBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
],
11 => [
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
]
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### indexBy() public
```
indexBy(callable|string $path): self
```
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo'],
['id' => 2, 'name' => 'bar'],
['id' => 3, 'name' => 'baz'],
];
$indexed = (new Collection($items))->indexBy('id');
// Or
$indexed = (new Collection($items))->indexBy(function ($e) {
return $e['id'];
});
// Result will look like this when converted to array
[
1 => ['id' => 1, 'name' => 'foo'],
3 => ['id' => 3, 'name' => 'baz'],
2 => ['id' => 2, 'name' => 'bar'],
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### insert() public
```
insert(string $path, mixed $values): self
```
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
The $path can be a string with a property name or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection as part of the path, the element will be kept unchanged.
### Example:
Insert ages into a collection containing users:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
];
$ages = [25, 28];
$inserted = (new Collection($items))->insert('comment.user.age', $ages);
// Result will look like this when converted to array
[
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
];
```
#### Parameters
`string` $path `mixed` $values #### Returns
`self`
### isEmpty() public
```
isEmpty(): bool
```
Returns whether there are elements in this collection
### Example:
```
$items [1, 2, 3];
(new Collection($items))->isEmpty(); // false
```
```
(new Collection([]))->isEmpty(); // true
```
#### Returns
`bool`
### jsonSerialize() public
```
jsonSerialize(): array
```
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
Part of JsonSerializable interface.
#### Returns
`array`
### key() public
```
key(): mixed
```
Returns the current key in the iterator
#### Returns
`mixed`
### last() public
```
last(): mixed
```
Returns the last result in this collection
#### Returns
`mixed`
### lazy() public
```
lazy(): self
```
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
A lazy collection can only be iterated once. A second attempt results in an error.
#### Returns
`self`
### listNested() public
```
listNested(string|int $order = 'desc', callable|string $nestingKey = 'children'): self
```
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
By default all elements in the tree following a Depth First Search will be returned, that is, elements from the top parent to the leaves for each branch.
It is possible to return all elements from bottom to top using a Breadth First Search approach by passing the '$dir' parameter with 'asc'. That is, it will return all elements for the same tree depth first and from bottom to top.
Finally, you can specify to only get a collection with the leaf nodes in the tree structure. You do so by passing 'leaves' in the first argument.
The possible values for the first argument are aliases for the following constants and it is valid to pass those instead of the alias:
* desc: RecursiveIteratorIterator::SELF\_FIRST
* asc: RecursiveIteratorIterator::CHILD\_FIRST
* leaves: RecursiveIteratorIterator::LEAVES\_ONLY
### Example:
```
$collection = new Collection([
['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
['id' => 4, 'children' => [['id' => 5]]]
]);
$flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
```
#### Parameters
`string|int` $order optional `callable|string` $nestingKey optional #### Returns
`self`
### map() public
```
map(callable $callback): self
```
Returns another collection after modifying each of the values in this one using the provided callable.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Getting a collection of booleans where true indicates if a person is female:
```
$collection = (new Collection($people))->map(function ($person, $key) {
return $person->gender === 'female';
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### match() public
```
match(array $conditions): self
```
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
### Example:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->match(['user.name' => 'Renan']);
// Result will look like this when converted to array
[
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
]
```
#### Parameters
`array` $conditions #### Returns
`self`
### max() public
```
max(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$max = $collection->max('age');
$max = $collection->max('user.salary');
$max = $collection->max(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $max->name;
```
#### Parameters
`callable|string` $path `int` $sort optional #### Returns
`mixed`
### median() public
```
median(callable|string|null $path = null): float|int|null
```
Returns the median of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 400]],
['invoice' => ['total' => 500]]
['invoice' => ['total' => 100]]
['invoice' => ['total' => 333]]
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->median('invoice.total');
// Total: 333
$total = (new Collection([1, 2, 3, 4]))->median();
// Total: 2.5
```
The median of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int|null`
### min() public
```
min(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$min = $collection->min('age');
$min = $collection->min('user.salary');
$min = $collection->min(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $min->name;
```
#### Parameters
`callable|string` $path `int` $sort optional #### Returns
`mixed`
### nest() public
```
nest(callable|string $idPath, callable|string $parentPath, string $nestingKey = 'children'): self
```
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
#### Parameters
`callable|string` $idPath `callable|string` $parentPath `string` $nestingKey optional #### Returns
`self`
### newCollection() protected
```
newCollection(mixed ...$args): Cake\Collection\CollectionInterface
```
Returns a new collection.
Allows classes which use this trait to determine their own type of returned collection interface
#### Parameters
`mixed` ...$args Constructor arguments.
#### Returns
`Cake\Collection\CollectionInterface`
### next() public
```
next(): void
```
Advances the iterator pointer to the next element
#### Returns
`void`
### optimizeUnwrap() protected
```
optimizeUnwrap(): iterable
```
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
#### Returns
`iterable`
### prepend() public
```
prepend(mixed $items): self
```
Prepend a set of items to a collection creating a new collection
#### Parameters
`mixed` $items #### Returns
`self`
### prependItem() public
```
prependItem(mixed $item, mixed $key = null): self
```
Prepend a single item creating a new collection.
#### Parameters
`mixed` $item `mixed` $key optional #### Returns
`self`
### reduce() public
```
reduce(callable $callback, mixed $initial = null): mixed
```
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
#### Parameters
`callable` $callback `mixed` $initial optional #### Returns
`mixed`
### reject() public
```
reject(callable $callback): self
```
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering even numbers in an array, at the end only values 1 and 3 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->reject(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### rewind() public
```
rewind(): void
```
Rewinds the collection
#### Returns
`void`
### sample() public
```
sample(int $length = 10): self
```
Returns a new collection with maximum $size random elements from this collection
#### Parameters
`int` $length optional #### Returns
`self`
### serialize() public
```
serialize(): string
```
Returns a string representation of this object that can be used to reconstruct it
#### Returns
`string`
### shuffle() public
```
shuffle(): self
```
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
#### Returns
`self`
### skip() public
```
skip(int $length): self
```
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
#### Parameters
`int` $length #### Returns
`self`
### some() public
```
some(callable $callback): bool
```
Returns true if any of the values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$hasYoungPeople = (new Collection([24, 45, 15]))->some(function ($value, $key) {
return $value < 21;
});
```
#### Parameters
`callable` $callback #### Returns
`bool`
### sortBy() public
```
sortBy(callable|string $path, int $order = \SORT_DESC, int $sort = \SORT_NUMERIC): self
```
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
The callback will receive as its first argument each of the elements in $items, the value returned by the callback will be used as the value for sorting such element. Please note that the callback function could be called more than once per element.
### Example:
```
$items = $collection->sortBy(function ($user) {
return $user->age;
});
// alternatively
$items = $collection->sortBy('age');
// or use a property path
$items = $collection->sortBy('department.name');
// output all user name order by their age in descending order
foreach ($items as $user) {
echo $user->name;
}
```
#### Parameters
`callable|string` $path `int` $order optional `int` $sort optional #### Returns
`self`
### stopWhen() public
```
stopWhen(callable|array $condition): self
```
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
This is handy for dealing with infinite iterators or any generator that could start returning invalid elements at a certain point. For example, when reading lines from a file stream you may want to stop the iteration after a certain value is reached.
### Example:
Get an array of lines in a CSV file until the timestamp column is less than a date
```
$lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
return (new DateTime($value))->format('Y') < 2012;
})
->toArray();
```
Get elements until the first unapproved message is found:
```
$comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
```
#### Parameters
`callable|array` $condition #### Returns
`self`
### sumOf() public
```
sumOf(callable|string|null $path = null): float|int
```
Returns the total sum of all the values extracted with $matcher or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->sumOf('invoice.total');
// Total: 300
$total = (new Collection([1, 2, 3]))->sumOf();
// Total: 6
```
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int`
### take() public
```
take(int $length = 1, int $offset = 0): self
```
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
#### Parameters
`int` $length optional `int` $offset optional #### Returns
`self`
### takeLast() public
```
takeLast(int $length): self
```
Returns the last N elements of a collection
### Example:
```
$items = [1, 2, 3, 4, 5];
$last = (new Collection($items))->takeLast(3);
// Result will look like this when converted to array
[3, 4, 5];
```
#### Parameters
`int` $length #### Returns
`self`
### through() public
```
through(callable $callback): self
```
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
### Example:
```
$items = [1, 2, 3];
$decorated = (new Collection($items))->through(function ($collection) {
return new MyCustomCollection($collection);
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### toArray() public
```
toArray(bool $keepKeys = true): array
```
Returns an array representation of the results
#### Parameters
`bool` $keepKeys optional #### Returns
`array`
### toList() public
```
toList(): array
```
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
#### Returns
`array`
### transpose() public
```
transpose(): Cake\Collection\CollectionInterface
```
Transpose rows and columns into columns and rows
### Example:
```
$items = [
['Products', '2012', '2013', '2014'],
['Product A', '200', '100', '50'],
['Product B', '300', '200', '100'],
['Product C', '400', '300', '200'],
]
$transpose = (new Collection($items))->transpose()->toList();
// Returns
// [
// ['Products', 'Product A', 'Product B', 'Product C'],
// ['2012', '200', '300', '400'],
// ['2013', '100', '200', '300'],
// ['2014', '50', '100', '200'],
// ]
```
#### Returns
`Cake\Collection\CollectionInterface`
#### Throws
`LogicException`
### unfold() public
```
unfold(callable|null $callback = null): self
```
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
The transformer function will receive the value and the key for each of the items in the collection, in that order, and it must return an array or a Traversable object that can be concatenated to the final result.
If no transformer function is passed, an "identity" function will be used. This is useful when each of the elements in the source collection are lists of items to be appended one after another.
### Example:
```
$items [[1, 2, 3], [4, 5]];
$unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
```
Using a transformer
```
$items [1, 2, 3];
$allItems = (new Collection($items))->unfold(function ($page) {
return $service->fetchPage($page)->toArray();
});
```
#### Parameters
`callable|null` $callback optional #### Returns
`self`
### unserialize() public
```
unserialize(string $collection): void
```
Unserializes the passed string and rebuilds the BufferedIterator instance
#### Parameters
`string` $collection The serialized buffer iterator
#### Returns
`void`
### unwrap() public
```
unwrap(): Traversable
```
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
#### Returns
`Traversable`
### valid() public
```
valid(): bool
```
Returns whether the iterator has more elements
#### Returns
`bool`
### zip() public
```
zip(iterable $items): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
### Example:
```
$collection = new Collection([1, 2]);
$collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
```
#### Parameters
`iterable` $items #### Returns
`self`
### zipWith() public
```
zipWith(iterable $items, callable $callback): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
The resulting element will be the return value of the $callable function.
### Example:
```
$collection = new Collection([1, 2]);
$zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
return array_sum($args);
});
$zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
```
#### Parameters
`iterable` $items `callable` $callback #### Returns
`self`
Property Detail
---------------
### $\_buffer protected
The in-memory cache containing results from previous iterators
#### Type
`SplDoublyLinkedList`
### $\_current protected
Last record fetched from the inner iterator
#### Type
`mixed`
### $\_finished protected
Whether the internal iterator has reached its end.
#### Type
`bool`
### $\_index protected
Points to the next record number that should be fetched
#### Type
`int`
### $\_key protected
Last key obtained from the inner iterator
#### Type
`mixed`
### $\_started protected
Whether the internal iterator's rewind method was already called
#### Type
`bool`
| programming_docs |
cakephp Interface RetryStrategyInterface Interface RetryStrategyInterface
=================================
Used to instruct a CommandRetry object on whether a retry for an action should be performed
**Namespace:** [Cake\Core\Retry](namespace-cake.core.retry)
Method Summary
--------------
* ##### [shouldRetry()](#shouldRetry()) public
Returns true if the action can be retried, false otherwise.
Method Detail
-------------
### shouldRetry() public
```
shouldRetry(Exception $exception, int $retryCount): bool
```
Returns true if the action can be retried, false otherwise.
#### Parameters
`Exception` $exception The exception that caused the action to fail
`int` $retryCount The number of times action has been retried
#### Returns
`bool`
cakephp Class HeaderSet Class HeaderSet
================
HeaderSet
**Namespace:** [Cake\TestSuite\Constraint\Response](namespace-cake.testsuite.constraint.response)
Property Summary
----------------
* [$headerName](#%24headerName) protected `string`
* [$response](#%24response) protected `Psr\Http\Message\ResponseInterface`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_getBodyAsString()](#_getBodyAsString()) protected
Get the response body as string
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Overwrites the descriptions so we can remove the automatic "expected" message
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Checks assertion
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(Psr\Http\Message\ResponseInterface|null $response, string $headerName)
```
Constructor.
#### Parameters
`Psr\Http\Message\ResponseInterface|null` $response A response instance.
`string` $headerName Header name
### \_getBodyAsString() protected
```
_getBodyAsString(): string
```
Get the response body as string
#### Returns
`string`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Overwrites the descriptions so we can remove the automatic "expected" message
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other Value
#### Returns
`string`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks assertion
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Expected content
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $headerName protected
#### Type
`string`
### $response protected
#### Type
`Psr\Http\Message\ResponseInterface`
cakephp Class FileLog Class FileLog
==============
File Storage stream for Logging. Writes logs to different files based on the level of log it is.
**Namespace:** [Cake\Log\Engine](namespace-cake.log.engine)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this class
* [$\_file](#%24_file) protected `string|null` The name of the file to save logs into.
* [$\_path](#%24_path) protected `string` Path to save log files on.
* [$\_size](#%24_size) protected `int|null` Max file size, used for log file rotation.
* [$formatter](#%24formatter) protected `Cake\Log\Formatter\AbstractFormatter`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Sets protected properties based on config provided
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_format()](#_format()) protected deprecated
Formats the message to be logged.
* ##### [\_getFilename()](#_getFilename()) protected
Get filename
* ##### [\_rotateFile()](#_rotateFile()) protected
Rotate log file if size specified in config is reached. Also if `rotate` count is reached oldest file is removed.
* ##### [alert()](#alert()) public
Action must be taken immediately.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [critical()](#critical()) public
Critical conditions.
* ##### [debug()](#debug()) public
Detailed debug information.
* ##### [emergency()](#emergency()) public
System is unusable.
* ##### [error()](#error()) public
Runtime errors that do not require immediate action but should typically be logged and monitored.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [info()](#info()) public
Interesting events.
* ##### [interpolate()](#interpolate()) protected
Replaces placeholders in message string with context values.
* ##### [levels()](#levels()) public
Get the levels this logger is interested in.
* ##### [log()](#log()) public
Implements writing to log files.
* ##### [notice()](#notice()) public
Normal but significant events.
* ##### [scopes()](#scopes()) public
Get the scopes this logger is interested in.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [warning()](#warning()) public
Exceptional occurrences that are not errors.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Sets protected properties based on config provided
#### Parameters
`array<string, mixed>` $config optional Configuration array
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_format() protected
```
_format(string $message, array $context = []): string
```
Formats the message to be logged.
The context can optionally be used by log engines to interpolate variables or add additional info to the logged message.
#### Parameters
`string` $message The message to be formatted.
`array` $context optional Additional logging information for the message.
#### Returns
`string`
### \_getFilename() protected
```
_getFilename(string $level): string
```
Get filename
#### Parameters
`string` $level The level of log.
#### Returns
`string`
### \_rotateFile() protected
```
_rotateFile(string $filename): bool|null
```
Rotate log file if size specified in config is reached. Also if `rotate` count is reached oldest file is removed.
#### Parameters
`string` $filename Log file name
#### Returns
`bool|null`
### alert() public
```
alert(string $message, mixed[] $context = array()): void
```
Action must be taken immediately.
Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### critical() public
```
critical(string $message, mixed[] $context = array()): void
```
Critical conditions.
Example: Application component unavailable, unexpected exception.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### debug() public
```
debug(string $message, mixed[] $context = array()): void
```
Detailed debug information.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### emergency() public
```
emergency(string $message, mixed[] $context = array()): void
```
System is unusable.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### error() public
```
error(string $message, mixed[] $context = array()): void
```
Runtime errors that do not require immediate action but should typically be logged and monitored.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### info() public
```
info(string $message, mixed[] $context = array()): void
```
Interesting events.
Example: User logs in, SQL logs.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### interpolate() protected
```
interpolate(string $message, array $context = []): string
```
Replaces placeholders in message string with context values.
#### Parameters
`string` $message Formatted string
`array` $context optional Context for placeholder values.
#### Returns
`string`
### levels() public
```
levels(): array<string>
```
Get the levels this logger is interested in.
#### Returns
`array<string>`
### log() public
```
log(mixed $level, string $message, mixed[] $context = []): void
```
Implements writing to log files.
#### Parameters
`mixed` $level The severity level of the message being written.
`string` $message The message you want to log.
`mixed[]` $context optional Additional information about the logged message
#### Returns
`void`
#### See Also
\Cake\Log\Log::$\_levels ### notice() public
```
notice(string $message, mixed[] $context = array()): void
```
Normal but significant events.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### scopes() public
```
scopes(): array<string>|false
```
Get the scopes this logger is interested in.
#### Returns
`array<string>|false`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### warning() public
```
warning(string $message, mixed[] $context = array()): void
```
Exceptional occurrences that are not errors.
Example: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this class
* `levels` string or array, levels the engine is interested in
* `scopes` string or array, scopes the engine is interested in
* `file` Log file name
* `path` The path to save logs on.
* `size` Used to implement basic log file rotation. If log file size reaches specified size the existing file is renamed by appending timestamp to filename and new log file is created. Can be integer bytes value or human readable string values like '10MB', '100KB' etc.
* `rotate` Log files are rotated specified times before being removed. If value is 0, old versions are removed rather then rotated.
* `mask` A mask is applied when log files are created. Left empty no chmod is made.
* `dateFormat` PHP date() format.
#### Type
`array<string, mixed>`
### $\_file protected
The name of the file to save logs into.
#### Type
`string|null`
### $\_path protected
Path to save log files on.
#### Type
`string`
### $\_size protected
Max file size, used for log file rotation.
#### Type
`int|null`
### $formatter protected
#### Type
`Cake\Log\Formatter\AbstractFormatter`
| programming_docs |
cakephp Class MailSentTo Class MailSentTo
=================
MailSentTo
**Namespace:** [Cake\TestSuite\Constraint\Email](namespace-cake.testsuite.constraint.email)
Property Summary
----------------
* [$at](#%24at) protected `int|null`
* [$method](#%24method) protected `string`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [getMessages()](#getMessages()) public
Gets the email or emails to check
* ##### [matches()](#matches()) public
Checks constraint
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message string
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(int|null $at = null, string|null $method = null): void
```
Constructor
#### Parameters
`int|null` $at optional At
`string|null` $method optional Method
#### Returns
`void`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### getMessages() public
```
getMessages(): arrayCake\Mailer\Message>
```
Gets the email or emails to check
#### Returns
`arrayCake\Mailer\Message>`
### matches() public
```
matches(mixed $other): bool
```
Checks constraint
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Constraint check
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message string
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $at protected
#### Type
`int|null`
### $method protected
#### Type
`string`
cakephp Class TreeIterator Class TreeIterator
===================
A Recursive iterator used to flatten nested structures and also exposes all Collection methods
**Namespace:** [Cake\Collection\Iterator](namespace-cake.collection.iterator)
Property Summary
----------------
* [$\_mode](#%24_mode) protected `int` The iteration mode
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_createMatcherFilter()](#_createMatcherFilter()) protected
Returns a callable that receives a value and will return whether it matches certain condition.
* ##### [\_extract()](#_extract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
* ##### [\_propertyExtractor()](#_propertyExtractor()) protected
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
* ##### [\_simpleExtract()](#_simpleExtract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path
* ##### [append()](#append()) public
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
* ##### [appendItem()](#appendItem()) public
Append a single item creating a new collection.
* ##### [avg()](#avg()) public
Returns the average of all the values extracted with $path or of this collection.
* ##### [buffered()](#buffered()) public
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
* ##### [cartesianProduct()](#cartesianProduct()) public
Create a new collection that is the cartesian product of the current collection
* ##### [chunk()](#chunk()) public
Breaks the collection into smaller arrays of the given size.
* ##### [chunkWithKeys()](#chunkWithKeys()) public
Breaks the collection into smaller arrays of the given size.
* ##### [combine()](#combine()) public
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
* ##### [compile()](#compile()) public
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
* ##### [contains()](#contains()) public
Returns true if $value is present in this collection. Comparisons are made both by value and type.
* ##### [count()](#count()) public
Returns the amount of elements in the collection.
* ##### [countBy()](#countBy()) public
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
* ##### [countKeys()](#countKeys()) public
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
* ##### [each()](#each()) public
Applies a callback to the elements in this collection.
* ##### [every()](#every()) public
Returns true if all values in this collection pass the truth test provided in the callback.
* ##### [extract()](#extract()) public
Returns a new collection containing the column or property value found in each of the elements.
* ##### [filter()](#filter()) public
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
* ##### [first()](#first()) public
Returns the first result in this collection
* ##### [firstMatch()](#firstMatch()) public
Returns the first result matching all the key-value pairs listed in conditions.
* ##### [groupBy()](#groupBy()) public
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
* ##### [indexBy()](#indexBy()) public
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
* ##### [insert()](#insert()) public
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
* ##### [isEmpty()](#isEmpty()) public
Returns whether there are elements in this collection
* ##### [jsonSerialize()](#jsonSerialize()) public
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
* ##### [last()](#last()) public
Returns the last result in this collection
* ##### [lazy()](#lazy()) public
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
* ##### [listNested()](#listNested()) public
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
* ##### [map()](#map()) public
Returns another collection after modifying each of the values in this one using the provided callable.
* ##### [match()](#match()) public
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
* ##### [max()](#max()) public
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [median()](#median()) public
Returns the median of all the values extracted with $path or of this collection.
* ##### [min()](#min()) public
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [nest()](#nest()) public
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
* ##### [newCollection()](#newCollection()) protected
Returns a new collection.
* ##### [optimizeUnwrap()](#optimizeUnwrap()) protected
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
* ##### [prepend()](#prepend()) public
Prepend a set of items to a collection creating a new collection
* ##### [prependItem()](#prependItem()) public
Prepend a single item creating a new collection.
* ##### [printer()](#printer()) public
Returns another iterator which will return the values ready to be displayed to a user. It does so by extracting one property from each of the elements and prefixing it with a spacer so that the relative position in the tree can be visualized.
* ##### [reduce()](#reduce()) public
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
* ##### [reject()](#reject()) public
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
* ##### [sample()](#sample()) public
Returns a new collection with maximum $size random elements from this collection
* ##### [shuffle()](#shuffle()) public
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
* ##### [skip()](#skip()) public
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
* ##### [some()](#some()) public
Returns true if any of the values in this collection pass the truth test provided in the callback.
* ##### [sortBy()](#sortBy()) public
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
* ##### [stopWhen()](#stopWhen()) public
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
* ##### [sumOf()](#sumOf()) public
Returns the total sum of all the values extracted with $matcher or of this collection.
* ##### [take()](#take()) public
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
* ##### [takeLast()](#takeLast()) public
Returns the last N elements of a collection
* ##### [through()](#through()) public
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
* ##### [toArray()](#toArray()) public
Returns an array representation of the results
* ##### [toList()](#toList()) public
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
* ##### [transpose()](#transpose()) public
Transpose rows and columns into columns and rows
* ##### [unfold()](#unfold()) public
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
* ##### [unwrap()](#unwrap()) public
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
* ##### [zip()](#zip()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
* ##### [zipWith()](#zipWith()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
Method Detail
-------------
### \_\_construct() public
```
__construct(RecursiveIterator $items, int $mode = RecursiveIteratorIterator::SELF_FIRST, int $flags = 0)
```
Constructor
#### Parameters
`RecursiveIterator` $items The iterator to flatten.
`int` $mode optional Iterator mode.
`int` $flags optional Iterator flags.
### \_createMatcherFilter() protected
```
_createMatcherFilter(array $conditions): Closure
```
Returns a callable that receives a value and will return whether it matches certain condition.
#### Parameters
`array` $conditions A key-value list of conditions to match where the key is the property path to get from the current item and the value is the value to be compared the item with.
#### Returns
`Closure`
### \_extract() protected
```
_extract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### \_propertyExtractor() protected
```
_propertyExtractor(callable|string $path): callable
```
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
#### Parameters
`callable|string` $path A dot separated path of column to follow so that the final one can be returned or a callable that will take care of doing that.
#### Returns
`callable`
### \_simpleExtract() protected
```
_simpleExtract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### append() public
```
append(iterable $items): self
```
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
#### Parameters
`iterable` $items #### Returns
`self`
### appendItem() public
```
appendItem(mixed $item, mixed $key = null): self
```
Append a single item creating a new collection.
#### Parameters
`mixed` $item `mixed` $key optional #### Returns
`self`
### avg() public
```
avg(callable|string|null $path = null): float|int|null
```
Returns the average of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->avg('invoice.total');
// Total: 150
$total = (new Collection([1, 2, 3]))->avg();
// Total: 2
```
The average of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int|null`
### buffered() public
```
buffered(): self
```
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
This can also be used to make any non-rewindable iterator rewindable.
#### Returns
`self`
### cartesianProduct() public
```
cartesianProduct(callable|null $operation = null, callable|null $filter = null): Cake\Collection\CollectionInterface
```
Create a new collection that is the cartesian product of the current collection
In order to create a carteisan product a collection must contain a single dimension of data.
### Example
```
$collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
$result = $collection->cartesianProduct()->toArray();
$expected = [
['A', 1],
['A', 2],
['A', 3],
['B', 1],
['B', 2],
['B', 3],
['C', 1],
['C', 2],
['C', 3],
];
```
#### Parameters
`callable|null` $operation optional A callable that allows you to customize the product result.
`callable|null` $filter optional A filtering callback that must return true for a result to be part of the final results.
#### Returns
`Cake\Collection\CollectionInterface`
#### Throws
`LogicException`
### chunk() public
```
chunk(int $chunkSize): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
$chunked = (new Collection($items))->chunk(3)->toList();
// Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
```
#### Parameters
`int` $chunkSize #### Returns
`self`
### chunkWithKeys() public
```
chunkWithKeys(int $chunkSize, bool $keepKeys = true): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
$chunked = (new Collection($items))->chunkWithKeys(3)->toList();
// Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
```
#### Parameters
`int` $chunkSize `bool` $keepKeys optional #### Returns
`self`
### combine() public
```
combine(callable|string $keyPath, callable|string $valuePath, callable|string|null $groupPath = null): self
```
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
### Examples:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent' => 'a'],
['id' => 2, 'name' => 'bar', 'parent' => 'b'],
['id' => 3, 'name' => 'baz', 'parent' => 'a'],
];
$combined = (new Collection($items))->combine('id', 'name');
// Result will look like this when converted to array
[
1 => 'foo',
2 => 'bar',
3 => 'baz',
];
$combined = (new Collection($items))->combine('id', 'name', 'parent');
// Result will look like this when converted to array
[
'a' => [1 => 'foo', 3 => 'baz'],
'b' => [2 => 'bar']
];
```
#### Parameters
`callable|string` $keyPath `callable|string` $valuePath `callable|string|null` $groupPath optional #### Returns
`self`
### compile() public
```
compile(bool $keepKeys = true): self
```
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
A common use case is to re-use the same variable for calculating different data. In those cases it may be helpful and more performant to first compile a collection and then apply more operations to it.
### Example:
```
$collection->map($mapper)->sortBy('age')->extract('name');
$compiled = $collection->compile();
$isJohnHere = $compiled->some($johnMatcher);
$allButJohn = $compiled->filter($johnMatcher);
```
In the above example, had the collection not been compiled before, the iterations for `map`, `sortBy` and `extract` would've been executed twice: once for getting `$isJohnHere` and once for `$allButJohn`
You can think of this method as a way to create save points for complex calculations in a collection.
#### Parameters
`bool` $keepKeys optional #### Returns
`self`
### contains() public
```
contains(mixed $value): bool
```
Returns true if $value is present in this collection. Comparisons are made both by value and type.
#### Parameters
`mixed` $value #### Returns
`bool`
### count() public
```
count(): int
```
Returns the amount of elements in the collection.
WARNINGS:
---------
### Will change the current position of the iterator:
Calling this method at the same time that you are iterating this collections, for example in a foreach, will result in undefined behavior. Avoid doing this.
### Consumes all elements for NoRewindIterator collections:
On certain type of collections, calling this method may render unusable afterwards. That is, you may not be able to get elements out of it, or to iterate on it anymore.
Specifically any collection wrapping a Generator (a function with a yield statement) or a unbuffered database cursor will not accept any other function calls after calling `count()` on it.
Create a new collection with `buffered()` method to overcome this problem.
### Can report more elements than unique keys:
Any collection constructed by appending collections together, or by having internal iterators returning duplicate keys, will report a larger amount of elements using this functions than the final amount of elements when converting the collections to a keyed array. This is because duplicate keys will be collapsed into a single one in the final array, whereas this count method is only concerned by the amount of elements after converting it to a plain list.
If you need the count of elements after taking the keys in consideration (the count of unique keys), you can call `countKeys()`
#### Returns
`int`
### countBy() public
```
countBy(callable|string $path): self
```
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->countBy('parent_id');
// Or
$group = (new Collection($items))->countBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => 2,
11 => 1
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### countKeys() public
```
countKeys(): int
```
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
This method comes with a number of caveats. Please refer to `CollectionInterface::count()` for details.
#### Returns
`int`
### each() public
```
each(callable $callback): $this
```
Applies a callback to the elements in this collection.
### Example:
```
$collection = (new Collection($items))->each(function ($value, $key) {
echo "Element $key: $value";
});
```
#### Parameters
`callable` $callback #### Returns
`$this`
### every() public
```
every(callable $callback): bool
```
Returns true if all values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$overTwentyOne = (new Collection([24, 45, 60, 15]))->every(function ($value, $key) {
return $value > 21;
});
```
Empty collections always return true.
#### Parameters
`callable` $callback #### Returns
`bool`
### extract() public
```
extract(callable|string $path): self
```
Returns a new collection containing the column or property value found in each of the elements.
The matcher can be a string with a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection, that position is filled with null.
### Example:
Extract the user name for all comments in the array:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->extract('comment.user.name');
// Result will look like this when converted to array
['Mark', 'Renan']
```
It is also possible to extract a flattened collection out of nested properties
```
$items = [
['comment' => ['votes' => [['value' => 1], ['value' => 2], ['value' => 3]]],
['comment' => ['votes' => [['value' => 4]]
];
$extracted = (new Collection($items))->extract('comment.votes.{*}.value');
// Result will contain
[1, 2, 3, 4]
```
#### Parameters
`callable|string` $path #### Returns
`self`
### filter() public
```
filter(callable|null $callback = null): self
```
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering odd numbers in an array, at the end only the value 2 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->filter(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable|null` $callback optional #### Returns
`self`
### first() public
```
first(): mixed
```
Returns the first result in this collection
#### Returns
`mixed`
### firstMatch() public
```
firstMatch(array $conditions): mixed
```
Returns the first result matching all the key-value pairs listed in conditions.
#### Parameters
`array` $conditions #### Returns
`mixed`
### groupBy() public
```
groupBy(callable|string $path): self
```
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->groupBy('parent_id');
// Or
$group = (new Collection($items))->groupBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
],
11 => [
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
]
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### indexBy() public
```
indexBy(callable|string $path): self
```
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo'],
['id' => 2, 'name' => 'bar'],
['id' => 3, 'name' => 'baz'],
];
$indexed = (new Collection($items))->indexBy('id');
// Or
$indexed = (new Collection($items))->indexBy(function ($e) {
return $e['id'];
});
// Result will look like this when converted to array
[
1 => ['id' => 1, 'name' => 'foo'],
3 => ['id' => 3, 'name' => 'baz'],
2 => ['id' => 2, 'name' => 'bar'],
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### insert() public
```
insert(string $path, mixed $values): self
```
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
The $path can be a string with a property name or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection as part of the path, the element will be kept unchanged.
### Example:
Insert ages into a collection containing users:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
];
$ages = [25, 28];
$inserted = (new Collection($items))->insert('comment.user.age', $ages);
// Result will look like this when converted to array
[
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
];
```
#### Parameters
`string` $path `mixed` $values #### Returns
`self`
### isEmpty() public
```
isEmpty(): bool
```
Returns whether there are elements in this collection
### Example:
```
$items [1, 2, 3];
(new Collection($items))->isEmpty(); // false
```
```
(new Collection([]))->isEmpty(); // true
```
#### Returns
`bool`
### jsonSerialize() public
```
jsonSerialize(): array
```
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
Part of JsonSerializable interface.
#### Returns
`array`
### last() public
```
last(): mixed
```
Returns the last result in this collection
#### Returns
`mixed`
### lazy() public
```
lazy(): self
```
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
A lazy collection can only be iterated once. A second attempt results in an error.
#### Returns
`self`
### listNested() public
```
listNested(string|int $order = 'desc', callable|string $nestingKey = 'children'): self
```
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
By default all elements in the tree following a Depth First Search will be returned, that is, elements from the top parent to the leaves for each branch.
It is possible to return all elements from bottom to top using a Breadth First Search approach by passing the '$dir' parameter with 'asc'. That is, it will return all elements for the same tree depth first and from bottom to top.
Finally, you can specify to only get a collection with the leaf nodes in the tree structure. You do so by passing 'leaves' in the first argument.
The possible values for the first argument are aliases for the following constants and it is valid to pass those instead of the alias:
* desc: RecursiveIteratorIterator::SELF\_FIRST
* asc: RecursiveIteratorIterator::CHILD\_FIRST
* leaves: RecursiveIteratorIterator::LEAVES\_ONLY
### Example:
```
$collection = new Collection([
['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
['id' => 4, 'children' => [['id' => 5]]]
]);
$flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
```
#### Parameters
`string|int` $order optional `callable|string` $nestingKey optional #### Returns
`self`
### map() public
```
map(callable $callback): self
```
Returns another collection after modifying each of the values in this one using the provided callable.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Getting a collection of booleans where true indicates if a person is female:
```
$collection = (new Collection($people))->map(function ($person, $key) {
return $person->gender === 'female';
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### match() public
```
match(array $conditions): self
```
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
### Example:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->match(['user.name' => 'Renan']);
// Result will look like this when converted to array
[
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
]
```
#### Parameters
`array` $conditions #### Returns
`self`
### max() public
```
max(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$max = $collection->max('age');
$max = $collection->max('user.salary');
$max = $collection->max(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $max->name;
```
#### Parameters
`callable|string` $path `int` $sort optional #### Returns
`mixed`
### median() public
```
median(callable|string|null $path = null): float|int|null
```
Returns the median of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 400]],
['invoice' => ['total' => 500]]
['invoice' => ['total' => 100]]
['invoice' => ['total' => 333]]
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->median('invoice.total');
// Total: 333
$total = (new Collection([1, 2, 3, 4]))->median();
// Total: 2.5
```
The median of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int|null`
### min() public
```
min(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$min = $collection->min('age');
$min = $collection->min('user.salary');
$min = $collection->min(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $min->name;
```
#### Parameters
`callable|string` $path `int` $sort optional #### Returns
`mixed`
### nest() public
```
nest(callable|string $idPath, callable|string $parentPath, string $nestingKey = 'children'): self
```
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
#### Parameters
`callable|string` $idPath `callable|string` $parentPath `string` $nestingKey optional #### Returns
`self`
### newCollection() protected
```
newCollection(mixed ...$args): Cake\Collection\CollectionInterface
```
Returns a new collection.
Allows classes which use this trait to determine their own type of returned collection interface
#### Parameters
`mixed` ...$args Constructor arguments.
#### Returns
`Cake\Collection\CollectionInterface`
### optimizeUnwrap() protected
```
optimizeUnwrap(): iterable
```
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
#### Returns
`iterable`
### prepend() public
```
prepend(mixed $items): self
```
Prepend a set of items to a collection creating a new collection
#### Parameters
`mixed` $items #### Returns
`self`
### prependItem() public
```
prependItem(mixed $item, mixed $key = null): self
```
Prepend a single item creating a new collection.
#### Parameters
`mixed` $item `mixed` $key optional #### Returns
`self`
### printer() public
```
printer(callable|string $valuePath, callable|string|null $keyPath = null, string $spacer = '__'): Cake\Collection\Iterator\TreePrinter
```
Returns another iterator which will return the values ready to be displayed to a user. It does so by extracting one property from each of the elements and prefixing it with a spacer so that the relative position in the tree can be visualized.
Both $valuePath and $keyPath can be a string with a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
Alternatively, $valuePath and $keyPath can be callable functions. They will get the current element as first parameter, the current iteration key as second parameter, and the iterator instance as third argument.
### Example
```
$printer = (new Collection($treeStructure))->listNested()->printer('name');
```
Using a closure:
```
$printer = (new Collection($treeStructure))
->listNested()
->printer(function ($item, $key, $iterator) {
return $item->name;
});
```
#### Parameters
`callable|string` $valuePath The property to extract or a callable to return the display value
`callable|string|null` $keyPath optional The property to use as iteration key or a callable returning the key value.
`string` $spacer optional The string to use for prefixing the values according to their depth in the tree
#### Returns
`Cake\Collection\Iterator\TreePrinter`
### reduce() public
```
reduce(callable $callback, mixed $initial = null): mixed
```
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
#### Parameters
`callable` $callback `mixed` $initial optional #### Returns
`mixed`
### reject() public
```
reject(callable $callback): self
```
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering even numbers in an array, at the end only values 1 and 3 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->reject(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### sample() public
```
sample(int $length = 10): self
```
Returns a new collection with maximum $size random elements from this collection
#### Parameters
`int` $length optional #### Returns
`self`
### shuffle() public
```
shuffle(): self
```
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
#### Returns
`self`
### skip() public
```
skip(int $length): self
```
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
#### Parameters
`int` $length #### Returns
`self`
### some() public
```
some(callable $callback): bool
```
Returns true if any of the values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$hasYoungPeople = (new Collection([24, 45, 15]))->some(function ($value, $key) {
return $value < 21;
});
```
#### Parameters
`callable` $callback #### Returns
`bool`
### sortBy() public
```
sortBy(callable|string $path, int $order = \SORT_DESC, int $sort = \SORT_NUMERIC): self
```
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
The callback will receive as its first argument each of the elements in $items, the value returned by the callback will be used as the value for sorting such element. Please note that the callback function could be called more than once per element.
### Example:
```
$items = $collection->sortBy(function ($user) {
return $user->age;
});
// alternatively
$items = $collection->sortBy('age');
// or use a property path
$items = $collection->sortBy('department.name');
// output all user name order by their age in descending order
foreach ($items as $user) {
echo $user->name;
}
```
#### Parameters
`callable|string` $path `int` $order optional `int` $sort optional #### Returns
`self`
### stopWhen() public
```
stopWhen(callable|array $condition): self
```
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
This is handy for dealing with infinite iterators or any generator that could start returning invalid elements at a certain point. For example, when reading lines from a file stream you may want to stop the iteration after a certain value is reached.
### Example:
Get an array of lines in a CSV file until the timestamp column is less than a date
```
$lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
return (new DateTime($value))->format('Y') < 2012;
})
->toArray();
```
Get elements until the first unapproved message is found:
```
$comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
```
#### Parameters
`callable|array` $condition #### Returns
`self`
### sumOf() public
```
sumOf(callable|string|null $path = null): float|int
```
Returns the total sum of all the values extracted with $matcher or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->sumOf('invoice.total');
// Total: 300
$total = (new Collection([1, 2, 3]))->sumOf();
// Total: 6
```
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int`
### take() public
```
take(int $length = 1, int $offset = 0): self
```
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
#### Parameters
`int` $length optional `int` $offset optional #### Returns
`self`
### takeLast() public
```
takeLast(int $length): self
```
Returns the last N elements of a collection
### Example:
```
$items = [1, 2, 3, 4, 5];
$last = (new Collection($items))->takeLast(3);
// Result will look like this when converted to array
[3, 4, 5];
```
#### Parameters
`int` $length #### Returns
`self`
### through() public
```
through(callable $callback): self
```
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
### Example:
```
$items = [1, 2, 3];
$decorated = (new Collection($items))->through(function ($collection) {
return new MyCustomCollection($collection);
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### toArray() public
```
toArray(bool $keepKeys = true): array
```
Returns an array representation of the results
#### Parameters
`bool` $keepKeys optional #### Returns
`array`
### toList() public
```
toList(): array
```
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
#### Returns
`array`
### transpose() public
```
transpose(): Cake\Collection\CollectionInterface
```
Transpose rows and columns into columns and rows
### Example:
```
$items = [
['Products', '2012', '2013', '2014'],
['Product A', '200', '100', '50'],
['Product B', '300', '200', '100'],
['Product C', '400', '300', '200'],
]
$transpose = (new Collection($items))->transpose()->toList();
// Returns
// [
// ['Products', 'Product A', 'Product B', 'Product C'],
// ['2012', '200', '300', '400'],
// ['2013', '100', '200', '300'],
// ['2014', '50', '100', '200'],
// ]
```
#### Returns
`Cake\Collection\CollectionInterface`
#### Throws
`LogicException`
### unfold() public
```
unfold(callable|null $callback = null): self
```
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
The transformer function will receive the value and the key for each of the items in the collection, in that order, and it must return an array or a Traversable object that can be concatenated to the final result.
If no transformer function is passed, an "identity" function will be used. This is useful when each of the elements in the source collection are lists of items to be appended one after another.
### Example:
```
$items [[1, 2, 3], [4, 5]];
$unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
```
Using a transformer
```
$items [1, 2, 3];
$allItems = (new Collection($items))->unfold(function ($page) {
return $service->fetchPage($page)->toArray();
});
```
#### Parameters
`callable|null` $callback optional #### Returns
`self`
### unwrap() public
```
unwrap(): Traversable
```
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
#### Returns
`Traversable`
### zip() public
```
zip(iterable $items): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
### Example:
```
$collection = new Collection([1, 2]);
$collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
```
#### Parameters
`iterable` $items #### Returns
`self`
### zipWith() public
```
zipWith(iterable $items, callable $callback): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
The resulting element will be the return value of the $callable function.
### Example:
```
$collection = new Collection([1, 2]);
$zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
return array_sum($args);
});
$zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
```
#### Parameters
`iterable` $items `callable` $callback #### Returns
`self`
Property Detail
---------------
### $\_mode protected
The iteration mode
#### Type
`int`
| programming_docs |
cakephp Class ChainMessagesLoader Class ChainMessagesLoader
==========================
Wraps multiple message loaders calling them one after another until one of them returns a non-empty package.
**Namespace:** [Cake\I18n](namespace-cake.i18n)
Property Summary
----------------
* [$\_loaders](#%24_loaders) protected `array<callable>` The list of callables to execute one after another for loading messages
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
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
* ##### [\_\_invoke()](#__invoke()) public
Executes this object returning the translations package as configured in the chain.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<callable> $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
#### Parameters
`array<callable>` $loaders List of callables to execute
### \_\_invoke() public
```
__invoke(): Cake\I18n\Package
```
Executes this object returning the translations package as configured in the chain.
#### Returns
`Cake\I18n\Package`
#### Throws
`RuntimeException`
if any of the loaders in the chain is not a valid callable Property Detail
---------------
### $\_loaders protected
The list of callables to execute one after another for loading messages
#### Type
`array<callable>`
cakephp Class Client Class Client
=============
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 {@link \Cake\Http\Client\CookieCollection} 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.
**Namespace:** [Cake\Http](namespace-cake.http)
Property Summary
----------------
* [$\_adapter](#%24_adapter) protected `Cake\Http\Client\AdapterInterface` Adapter for sending requests.
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_cookies](#%24_cookies) protected `Cake\Http\Cookie\CookieCollection` List of cookies from responses made with this client.
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default configuration for the client.
* [$\_mockAdapter](#%24_mockAdapter) protected static `Cake\Http\Client\Adapter\Mock|null` Mock adapter for stubbing requests in tests.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Create a new HTTP Client.
* ##### [\_addAuthentication()](#_addAuthentication()) protected
Add authentication headers to the request.
* ##### [\_addProxy()](#_addProxy()) protected
Add proxy authentication headers.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_createAuth()](#_createAuth()) protected
Create the authentication strategy.
* ##### [\_createRequest()](#_createRequest()) protected
Creates a new request object based on the parameters.
* ##### [\_doRequest()](#_doRequest()) protected
Helper method for doing non-GET requests.
* ##### [\_mergeOptions()](#_mergeOptions()) protected
Does a recursive merge of the parameter with the scope config.
* ##### [\_sendRequest()](#_sendRequest()) protected
Send a request without redirection.
* ##### [\_typeHeaders()](#_typeHeaders()) protected
Returns headers for Accept/Content-Type based on a short type or full mime-type.
* ##### [addCookie()](#addCookie()) public
Adds a cookie to the Client collection.
* ##### [addMockResponse()](#addMockResponse()) public static
Add a mocked response.
* ##### [buildUrl()](#buildUrl()) public
Generate a URL based on the scoped client options.
* ##### [clearMockResponses()](#clearMockResponses()) public static
Clear all mocked responses
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [cookies()](#cookies()) public
Get the cookies stored in the Client.
* ##### [createFromUrl()](#createFromUrl()) public 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. Other parts of the url string are ignored.
* ##### [delete()](#delete()) public
Do a DELETE request.
* ##### [get()](#get()) public
Do a GET request.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [head()](#head()) public
Do a HEAD request.
* ##### [options()](#options()) public
Do an OPTIONS request.
* ##### [patch()](#patch()) public
Do a PATCH request.
* ##### [post()](#post()) public
Do a POST request.
* ##### [put()](#put()) public
Do a PUT request.
* ##### [send()](#send()) public
Send a request.
* ##### [sendRequest()](#sendRequest()) public
Sends a PSR-7 request and returns a PSR-7 response.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [trace()](#trace()) public
Do a TRACE request.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
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.
#### Parameters
`array<string, mixed>` $config optional Config options for scoped clients.
#### Throws
`InvalidArgumentException`
### \_addAuthentication() protected
```
_addAuthentication(Cake\Http\Client\Request $request, array<string, mixed> $options): Cake\Http\Client\Request
```
Add authentication headers to the request.
Uses the authentication type to choose the correct strategy and use its methods to add headers.
#### Parameters
`Cake\Http\Client\Request` $request The request to modify.
`array<string, mixed>` $options Array of options containing the 'auth' key.
#### Returns
`Cake\Http\Client\Request`
### \_addProxy() protected
```
_addProxy(Cake\Http\Client\Request $request, array<string, mixed> $options): Cake\Http\Client\Request
```
Add proxy authentication headers.
Uses the authentication type to choose the correct strategy and use its methods to add headers.
#### Parameters
`Cake\Http\Client\Request` $request The request to modify.
`array<string, mixed>` $options Array of options containing the 'proxy' key.
#### Returns
`Cake\Http\Client\Request`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_createAuth() protected
```
_createAuth(array $auth, array<string, mixed> $options): object
```
Create the authentication strategy.
Use the configuration options to create the correct authentication strategy handler.
#### Parameters
`array` $auth The authentication options to use.
`array<string, mixed>` $options The overall request options to use.
#### Returns
`object`
#### Throws
`Cake\Core\Exception\CakeException`
when an invalid strategy is chosen. ### \_createRequest() protected
```
_createRequest(string $method, string $url, mixed $data, array<string, mixed> $options): Cake\Http\Client\Request
```
Creates a new request object based on the parameters.
#### Parameters
`string` $method HTTP method name.
`string` $url The url including query string.
`mixed` $data The request body.
`array<string, mixed>` $options The options to use. Contains auth, proxy, etc.
#### Returns
`Cake\Http\Client\Request`
### \_doRequest() protected
```
_doRequest(string $method, string $url, mixed $data, array<string, mixed> $options): Cake\Http\Client\Response
```
Helper method for doing non-GET requests.
#### Parameters
`string` $method HTTP method.
`string` $url URL to request.
`mixed` $data The request body.
`array<string, mixed>` $options The options to use. Contains auth, proxy, etc.
#### Returns
`Cake\Http\Client\Response`
### \_mergeOptions() protected
```
_mergeOptions(array<string, mixed> $options): array
```
Does a recursive merge of the parameter with the scope config.
#### Parameters
`array<string, mixed>` $options Options to merge.
#### Returns
`array`
### \_sendRequest() protected
```
_sendRequest(Psr\Http\Message\RequestInterface $request, array<string, mixed> $options): Cake\Http\Client\Response
```
Send a request without redirection.
#### Parameters
`Psr\Http\Message\RequestInterface` $request The request to send.
`array<string, mixed>` $options Additional options to use.
#### Returns
`Cake\Http\Client\Response`
### \_typeHeaders() protected
```
_typeHeaders(string $type): array<string, string>
```
Returns headers for Accept/Content-Type based on a short type or full mime-type.
#### Parameters
`string` $type short type alias or full mimetype.
#### Returns
`array<string, string>`
#### Throws
`Cake\Core\Exception\CakeException`
When an unknown type alias is used. ### addCookie() public
```
addCookie(Cake\Http\Cookie\CookieInterface $cookie): $this
```
Adds a cookie to the Client collection.
#### Parameters
`Cake\Http\Cookie\CookieInterface` $cookie Cookie object.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
### addMockResponse() public static
```
addMockResponse(string $method, string $url, Cake\Http\Client\Response $response, array<string, mixed> $options = []): void
```
Add a mocked response.
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
`string` $method The HTTP method being mocked.
`string` $url The URL being matched. See above for examples.
`Cake\Http\Client\Response` $response The response that matches the request.
`array<string, mixed>` $options optional See above.
#### Returns
`void`
### buildUrl() public
```
buildUrl(string $url, array|string $query = [], array<string, mixed> $options = []): string
```
Generate a URL based on the scoped client options.
#### Parameters
`string` $url Either a full URL or just the path.
`array|string` $query optional The query data for the URL.
`array<string, mixed>` $options optional The config options stored with Client::config()
#### Returns
`string`
### clearMockResponses() public static
```
clearMockResponses(): void
```
Clear all mocked responses
#### Returns
`void`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### cookies() public
```
cookies(): Cake\Http\Cookie\CookieCollection
```
Get the cookies stored in the Client.
#### Returns
`Cake\Http\Cookie\CookieCollection`
### createFromUrl() public static
```
createFromUrl(string $url): 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. Other parts of the url string are ignored.
#### Parameters
`string` $url A string URL e.g. <https://example.com>
#### Returns
`static`
#### Throws
`InvalidArgumentException`
### delete() public
```
delete(string $url, mixed $data = [], array<string, mixed> $options = []): Cake\Http\Client\Response
```
Do a DELETE request.
#### Parameters
`string` $url The url or path you want to request.
`mixed` $data optional The request data you want to send.
`array<string, mixed>` $options optional Additional options for the request.
#### Returns
`Cake\Http\Client\Response`
### get() public
```
get(string $url, array|string $data = [], array<string, mixed> $options = []): Cake\Http\Client\Response
```
Do a GET request.
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
`string` $url The url or path you want to request.
`array|string` $data optional The query data you want to send.
`array<string, mixed>` $options optional Additional options for the request.
#### Returns
`Cake\Http\Client\Response`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### head() public
```
head(string $url, array $data = [], array<string, mixed> $options = []): Cake\Http\Client\Response
```
Do a HEAD request.
#### Parameters
`string` $url The url or path you want to request.
`array` $data optional The query string data you want to send.
`array<string, mixed>` $options optional Additional options for the request.
#### Returns
`Cake\Http\Client\Response`
### options() public
```
options(string $url, mixed $data = [], array<string, mixed> $options = []): Cake\Http\Client\Response
```
Do an OPTIONS request.
#### Parameters
`string` $url The url or path you want to request.
`mixed` $data optional The request data you want to send.
`array<string, mixed>` $options optional Additional options for the request.
#### Returns
`Cake\Http\Client\Response`
### patch() public
```
patch(string $url, mixed $data = [], array<string, mixed> $options = []): Cake\Http\Client\Response
```
Do a PATCH request.
#### Parameters
`string` $url The url or path you want to request.
`mixed` $data optional The request data you want to send.
`array<string, mixed>` $options optional Additional options for the request.
#### Returns
`Cake\Http\Client\Response`
### post() public
```
post(string $url, mixed $data = [], array<string, mixed> $options = []): Cake\Http\Client\Response
```
Do a POST request.
#### Parameters
`string` $url The url or path you want to request.
`mixed` $data optional The post data you want to send.
`array<string, mixed>` $options optional Additional options for the request.
#### Returns
`Cake\Http\Client\Response`
### put() public
```
put(string $url, mixed $data = [], array<string, mixed> $options = []): Cake\Http\Client\Response
```
Do a PUT request.
#### Parameters
`string` $url The url or path you want to request.
`mixed` $data optional The request data you want to send.
`array<string, mixed>` $options optional Additional options for the request.
#### Returns
`Cake\Http\Client\Response`
### send() public
```
send(Psr\Http\Message\RequestInterface $request, array<string, mixed> $options = []): Cake\Http\Client\Response
```
Send a request.
Used internally by other methods, but can also be used to send handcrafted Request objects.
#### Parameters
`Psr\Http\Message\RequestInterface` $request The request to send.
`array<string, mixed>` $options optional Additional options to use.
#### Returns
`Cake\Http\Client\Response`
### sendRequest() public
```
sendRequest(RequestInterface $request): Psr\Http\Message\ResponseInterface
```
Sends a PSR-7 request and returns a PSR-7 response.
#### Parameters
`RequestInterface` $request Request instance.
#### Returns
`Psr\Http\Message\ResponseInterface`
#### Throws
`Psr\Http\Client\ClientExceptionInterface`
If an error happens while processing the request. ### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### trace() public
```
trace(string $url, mixed $data = [], array<string, mixed> $options = []): Cake\Http\Client\Response
```
Do a TRACE request.
#### Parameters
`string` $url The url or path you want to request.
`mixed` $data optional The request data you want to send.
`array<string, mixed>` $options optional Additional options for the request.
#### Returns
`Cake\Http\Client\Response`
Property Detail
---------------
### $\_adapter protected
Adapter for sending requests.
#### Type
`Cake\Http\Client\AdapterInterface`
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_cookies protected
List of cookies from responses made with this client.
Cookies are indexed by the cookie's domain or request host name.
#### Type
`Cake\Http\Cookie\CookieCollection`
### $\_defaultConfig protected
Default configuration for the client.
#### Type
`array<string, mixed>`
### $\_mockAdapter protected static
Mock adapter for stubbing requests in tests.
#### Type
`Cake\Http\Client\Adapter\Mock|null`
| programming_docs |
cakephp Class CaseExpression Class CaseExpression
=====================
This class represents a SQL Case statement
**Namespace:** [Cake\Database\Expression](namespace-cake.database.expression)
**Deprecated:** 4.3.0 Use QueryExpression::case() or CaseStatementExpression instead
Property Summary
----------------
* [$\_conditions](#%24_conditions) protected `array` A list of strings or other expression objects that represent the conditions of the case statement. For example one key of the array might look like "sum > :value"
* [$\_elseValue](#%24_elseValue) protected `Cake\Database\ExpressionInterface|array|string|null` The `ELSE` value for the case statement. If null then no `ELSE` will be included.
* [$\_values](#%24_values) protected `array` Values that are associated with the conditions in the $\_conditions array. Each value represents the 'true' value for the condition with the corresponding key.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructs the case expression
* ##### [\_addExpressions()](#_addExpressions()) protected
Iterates over the passed in conditions and ensures that there is a matching true value for each. If no matching true value, then it is defaulted to '1'.
* ##### [\_castToExpression()](#_castToExpression()) protected
Conditionally converts the passed value to an ExpressionInterface object if the type class implements the ExpressionTypeInterface. Otherwise, returns the value unmodified.
* ##### [\_compile()](#_compile()) protected
Compiles the relevant parts into sql
* ##### [\_requiresToExpressionCasting()](#_requiresToExpressionCasting()) protected
Returns an array with the types that require values to be casted to expressions, out of the list of type names passed as parameter.
* ##### [add()](#add()) public
Adds one or more conditions and their respective true values to the case object. Conditions must be a one dimensional array or a QueryExpression. The trueValues must be a similar structure, but may contain a string value.
* ##### [elseValue()](#elseValue()) public
Sets the default value
* ##### [sql()](#sql()) public
Converts the Node into a SQL string fragment.
* ##### [traverse()](#traverse()) public
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Database\ExpressionInterface|array $conditions = [], Cake\Database\ExpressionInterface|array $values = [], array<string> $types = [])
```
Constructs the case expression
#### Parameters
`Cake\Database\ExpressionInterface|array` $conditions optional The conditions to test. Must be a ExpressionInterface instance, or an array of ExpressionInterface instances.
`Cake\Database\ExpressionInterface|array` $values optional Associative array of values to be associated with the conditions passed in $conditions. If there are more $values than $conditions, the last $value is used as the `ELSE` value.
`array<string>` $types optional Associative array of types to be associated with the values passed in $values
### \_addExpressions() protected
```
_addExpressions(array $conditions, array<mixed> $values, array<string> $types): void
```
Iterates over the passed in conditions and ensures that there is a matching true value for each. If no matching true value, then it is defaulted to '1'.
#### Parameters
`array` $conditions Array of ExpressionInterface instances.
`array<mixed>` $values Associative array of values of each condition
`array<string>` $types Associative array of types to be associated with the values
#### Returns
`void`
### \_castToExpression() protected
```
_castToExpression(mixed $value, string|null $type = null): mixed
```
Conditionally converts the passed value to an ExpressionInterface object if the type class implements the ExpressionTypeInterface. Otherwise, returns the value unmodified.
#### Parameters
`mixed` $value The value to convert to ExpressionInterface
`string|null` $type optional The type name
#### Returns
`mixed`
### \_compile() protected
```
_compile(Cake\Database\ExpressionInterface|array|string $part, Cake\Database\ValueBinder $binder): string
```
Compiles the relevant parts into sql
#### Parameters
`Cake\Database\ExpressionInterface|array|string` $part The part to compile
`Cake\Database\ValueBinder` $binder Sql generator
#### Returns
`string`
### \_requiresToExpressionCasting() protected
```
_requiresToExpressionCasting(array $types): array
```
Returns an array with the types that require values to be casted to expressions, out of the list of type names passed as parameter.
#### Parameters
`array` $types List of type names
#### Returns
`array`
### add() public
```
add(Cake\Database\ExpressionInterface|array $conditions = [], Cake\Database\ExpressionInterface|array $values = [], array<string> $types = []): $this
```
Adds one or more conditions and their respective true values to the case object. Conditions must be a one dimensional array or a QueryExpression. The trueValues must be a similar structure, but may contain a string value.
#### Parameters
`Cake\Database\ExpressionInterface|array` $conditions optional Must be a ExpressionInterface instance, or an array of ExpressionInterface instances.
`Cake\Database\ExpressionInterface|array` $values optional Associative array of values of each condition
`array<string>` $types optional Associative array of types to be associated with the values
#### Returns
`$this`
### elseValue() public
```
elseValue(Cake\Database\ExpressionInterface|array|string|null $value = null, string|null $type = null): void
```
Sets the default value
#### Parameters
`Cake\Database\ExpressionInterface|array|string|null` $value optional Value to set
`string|null` $type optional Type of value
#### Returns
`void`
### sql() public
```
sql(Cake\Database\ValueBinder $binder): string
```
Converts the Node into a SQL string fragment.
#### Parameters
`Cake\Database\ValueBinder` $binder Placeholder generator object
#### Returns
`string`
### traverse() public
```
traverse(Closure $callback): $this
```
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
#### Parameters
`Closure` $callback #### Returns
`$this`
Property Detail
---------------
### $\_conditions protected
A list of strings or other expression objects that represent the conditions of the case statement. For example one key of the array might look like "sum > :value"
#### Type
`array`
### $\_elseValue protected
The `ELSE` value for the case statement. If null then no `ELSE` will be included.
#### Type
`Cake\Database\ExpressionInterface|array|string|null`
### $\_values protected
Values that are associated with the conditions in the $\_conditions array. Each value represents the 'true' value for the condition with the corresponding key.
#### Type
`array`
cakephp Class MailSubjectContains Class MailSubjectContains
==========================
MailSubjectContains
**Namespace:** [Cake\TestSuite\Constraint\Email](namespace-cake.testsuite.constraint.email)
Property Summary
----------------
* [$at](#%24at) protected `int|null`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [getAssertedMessages()](#getAssertedMessages()) protected
Returns the subjects of all messages respects $this->at
* ##### [getMessages()](#getMessages()) public
Gets the email or emails to check
* ##### [matches()](#matches()) public
Checks constraint
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message string
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(int|null $at = null): void
```
Constructor
#### Parameters
`int|null` $at optional At
#### Returns
`void`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### getAssertedMessages() protected
```
getAssertedMessages(): string
```
Returns the subjects of all messages respects $this->at
#### Returns
`string`
### getMessages() public
```
getMessages(): arrayCake\Mailer\Message>
```
Gets the email or emails to check
#### Returns
`arrayCake\Mailer\Message>`
### matches() public
```
matches(mixed $other): bool
```
Checks constraint
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Constraint check
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message string
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $at protected
#### Type
`int|null`
cakephp Class BetweenExpression Class BetweenExpression
========================
An expression object that represents a SQL BETWEEN snippet
**Namespace:** [Cake\Database\Expression](namespace-cake.database.expression)
Property Summary
----------------
* [$\_field](#%24_field) protected `Cake\Database\ExpressionInterface|array|string` The field name or expression to be used in the left hand side of the operator
* [$\_from](#%24_from) protected `mixed` The first value in the expression
* [$\_to](#%24_to) protected `mixed` The second value in the expression
* [$\_type](#%24_type) protected `mixed` The data type for the from and to arguments
Method Summary
--------------
* ##### [\_\_clone()](#__clone()) public
Do a deep clone of this expression.
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_bindValue()](#_bindValue()) protected
Registers a value in the placeholder generator and returns the generated placeholder
* ##### [\_castToExpression()](#_castToExpression()) protected
Conditionally converts the passed value to an ExpressionInterface object if the type class implements the ExpressionTypeInterface. Otherwise, returns the value unmodified.
* ##### [\_requiresToExpressionCasting()](#_requiresToExpressionCasting()) protected
Returns an array with the types that require values to be casted to expressions, out of the list of type names passed as parameter.
* ##### [getField()](#getField()) public
Returns the field name
* ##### [setField()](#setField()) public
Sets the field name
* ##### [sql()](#sql()) public
Converts the Node into a SQL string fragment.
* ##### [traverse()](#traverse()) public
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
Method Detail
-------------
### \_\_clone() public
```
__clone(): void
```
Do a deep clone of this expression.
#### Returns
`void`
### \_\_construct() public
```
__construct(Cake\Database\ExpressionInterface|string $field, mixed $from, mixed $to, string|null $type = null)
```
Constructor
#### Parameters
`Cake\Database\ExpressionInterface|string` $field The field name to compare for values inbetween the range.
`mixed` $from The initial value of the range.
`mixed` $to The ending value in the comparison range.
`string|null` $type optional The data type name to bind the values with.
### \_bindValue() protected
```
_bindValue(mixed $value, Cake\Database\ValueBinder $binder, string $type): string
```
Registers a value in the placeholder generator and returns the generated placeholder
#### Parameters
`mixed` $value The value to bind
`Cake\Database\ValueBinder` $binder The value binder to use
`string` $type The type of $value
#### Returns
`string`
### \_castToExpression() protected
```
_castToExpression(mixed $value, string|null $type = null): mixed
```
Conditionally converts the passed value to an ExpressionInterface object if the type class implements the ExpressionTypeInterface. Otherwise, returns the value unmodified.
#### Parameters
`mixed` $value The value to convert to ExpressionInterface
`string|null` $type optional The type name
#### Returns
`mixed`
### \_requiresToExpressionCasting() protected
```
_requiresToExpressionCasting(array $types): array
```
Returns an array with the types that require values to be casted to expressions, out of the list of type names passed as parameter.
#### Parameters
`array` $types List of type names
#### Returns
`array`
### getField() public
```
getField(): Cake\Database\ExpressionInterface|array|string
```
Returns the field name
#### Returns
`Cake\Database\ExpressionInterface|array|string`
### setField() public
```
setField(Cake\Database\ExpressionInterface|array|string $field): void
```
Sets the field name
#### Parameters
`Cake\Database\ExpressionInterface|array|string` $field The field to compare with.
#### Returns
`void`
### sql() public
```
sql(Cake\Database\ValueBinder $binder): string
```
Converts the Node into a SQL string fragment.
#### Parameters
`Cake\Database\ValueBinder` $binder #### Returns
`string`
### traverse() public
```
traverse(Closure $callback): $this
```
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
#### Parameters
`Closure` $callback #### Returns
`$this`
Property Detail
---------------
### $\_field protected
The field name or expression to be used in the left hand side of the operator
#### Type
`Cake\Database\ExpressionInterface|array|string`
### $\_from protected
The first value in the expression
#### Type
`mixed`
### $\_to protected
The second value in the expression
#### Type
`mixed`
### $\_type protected
The data type for the from and to arguments
#### Type
`mixed`
| programming_docs |
cakephp Interface ContextInterface Interface ContextInterface
===========================
Interface for FormHelper context implementations.
**Namespace:** [Cake\View\Form](namespace-cake.view.form)
Constants
---------
* `array<string>` **VALID\_ATTRIBUTES**
```
['length', 'precision', 'comment', 'null', 'default']
```
Method Summary
--------------
* ##### [attributes()](#attributes()) public
Get an associative array of other attributes for a field name.
* ##### [error()](#error()) public
Get the errors for a given field
* ##### [fieldNames()](#fieldNames()) public
Get the field names of the top level object in this context.
* ##### [getMaxLength()](#getMaxLength()) public
Get maximum length of a field from model validation.
* ##### [getPrimaryKey()](#getPrimaryKey()) public
Get the fields used in the context as a primary key.
* ##### [getRequiredMessage()](#getRequiredMessage()) public
Gets the default "required" error message for a field
* ##### [hasError()](#hasError()) public
Check whether a field has an error attached to it
* ##### [isCreate()](#isCreate()) public
Returns whether this form is for a create operation.
* ##### [isPrimaryKey()](#isPrimaryKey()) public
Returns true if the passed field name is part of the primary key for this context
* ##### [isRequired()](#isRequired()) public
Check if a given field is 'required'.
* ##### [type()](#type()) public
Get the abstract field type for a given field name.
* ##### [val()](#val()) public
Get the current value for a given field.
Method Detail
-------------
### attributes() public
```
attributes(string $field): array
```
Get an associative array of other attributes for a field name.
#### Parameters
`string` $field A dot separated path to get additional data on.
#### Returns
`array`
### error() public
```
error(string $field): array
```
Get the errors for a given field
#### Parameters
`string` $field A dot separated path to check errors on.
#### Returns
`array`
### fieldNames() public
```
fieldNames(): array<string>
```
Get the field names of the top level object in this context.
#### Returns
`array<string>`
### getMaxLength() public
```
getMaxLength(string $field): int|null
```
Get maximum length of a field from model validation.
#### Parameters
`string` $field Field name.
#### Returns
`int|null`
### getPrimaryKey() public
```
getPrimaryKey(): array<string>
```
Get the fields used in the context as a primary key.
#### Returns
`array<string>`
### getRequiredMessage() public
```
getRequiredMessage(string $field): string|null
```
Gets the default "required" error message for a field
#### Parameters
`string` $field A dot separated path to the field name
#### Returns
`string|null`
### hasError() public
```
hasError(string $field): bool
```
Check whether a field has an error attached to it
#### Parameters
`string` $field A dot separated path to check errors on.
#### Returns
`bool`
### isCreate() public
```
isCreate(): bool
```
Returns whether this form is for a create operation.
#### Returns
`bool`
### isPrimaryKey() public
```
isPrimaryKey(string $field): bool
```
Returns true if the passed field name is part of the primary key for this context
#### Parameters
`string` $field A dot separated path to the field a value is needed for.
#### Returns
`bool`
### isRequired() public
```
isRequired(string $field): bool|null
```
Check if a given field is 'required'.
In this context class, this is simply defined by the 'required' array.
#### Parameters
`string` $field A dot separated path to check required-ness for.
#### Returns
`bool|null`
### type() public
```
type(string $field): string|null
```
Get the abstract field type for a given field name.
#### Parameters
`string` $field A dot separated path to get a schema type for.
#### Returns
`string|null`
#### See Also
\Cake\Database\TypeFactory ### val() public
```
val(string $field, array<string, mixed> $options = []): mixed
```
Get the current value for a given field.
Classes implementing this method can optionally have a second argument `$options`. Valid key for `$options` array are:
* `default`: Default value to return if no value found in data or context record.
+ `schemaDefault`: Boolean indicating whether default value from context's schema should be used if it's not explicitly provided.
#### Parameters
`string` $field A dot separated path to the field a value
`array<string, mixed>` $options optional Options. is needed for.
#### Returns
`mixed`
cakephp Class ReferenceNode Class ReferenceNode
====================
Dump node for class references.
To prevent cyclic references from being output multiple times a reference node can be used after an object has been seen the first time.
**Namespace:** [Cake\Error\Debug](namespace-cake.error.debug)
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getChildren()](#getChildren()) public
Get the child nodes of this node.
* ##### [getId()](#getId()) public
Get the reference id for this node.
* ##### [getValue()](#getValue()) public
Get the class name/value
Method Detail
-------------
### \_\_construct() public
```
__construct(string $class, int $id)
```
Constructor
#### Parameters
`string` $class The class name
`int` $id The id of the referenced class.
### getChildren() public
```
getChildren(): arrayCake\Error\Debug\NodeInterface>
```
Get the child nodes of this node.
#### Returns
`arrayCake\Error\Debug\NodeInterface>`
### getId() public
```
getId(): int
```
Get the reference id for this node.
#### Returns
`int`
### getValue() public
```
getValue(): string
```
Get the class name/value
#### Returns
`string`
cakephp Class RedirectRoute Class RedirectRoute
====================
Redirect route will perform an immediate redirect. Redirect routes are useful when you want to have Routing layer redirects occur in your application, for when URLs move.
Redirection is signalled by an exception that halts route matching and defines the redirect URL and status code.
**Namespace:** [Cake\Routing\Route](namespace-cake.routing.route)
Constants
---------
* `string` **PLACEHOLDER\_REGEX**
```
'#\\{([a-z][a-z0-9-_]*)\\}#i'
```
Regex for matching braced placholders in route template.
* `array<string>` **VALID\_METHODS**
```
['GET', 'PUT', 'POST', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD']
```
Valid HTTP methods.
Property Summary
----------------
* [$\_compiledRoute](#%24_compiledRoute) protected `string|null` The compiled route regular expression
* [$\_extensions](#%24_extensions) protected `array<string>` List of connected extensions for this route.
* [$\_greedy](#%24_greedy) protected `bool` Is this route a greedy route? Greedy routes have a `/*` in their template
* [$\_name](#%24_name) protected `string|null` The name for a route. Fetch with Route::getName();
* [$braceKeys](#%24braceKeys) protected `bool` Track whether brace keys `{var}` were used.
* [$defaults](#%24defaults) public `array` Default parameters for a Route
* [$keys](#%24keys) public `array` An array of named segments in a Route. `/{controller}/{action}/{id}` has 3 key elements
* [$middleware](#%24middleware) protected `array` List of middleware that should be applied.
* [$options](#%24options) public `array` An array of additional parameters for the Route.
* [$redirect](#%24redirect) public `array` The location to redirect to.
* [$template](#%24template) public `string` The routes template string.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_set\_state()](#__set_state()) public static
Set state magic method to support var\_export
* ##### [\_matchMethod()](#_matchMethod()) protected
Check whether the URL's HTTP method matches.
* ##### [\_parseArgs()](#_parseArgs()) protected
Parse passed parameters into a list of passed args.
* ##### [\_parseExtension()](#_parseExtension()) protected
Removes the extension from $url if it contains a registered extension. If no registered extension is found, no extension is returned and the URL is returned unmodified.
* ##### [\_persistParams()](#_persistParams()) protected
Apply persistent parameters to a URL array. Persistent parameters are a special key used during route creation to force route parameters to persist when omitted from a URL array.
* ##### [\_writeRoute()](#_writeRoute()) protected
Builds a route regular expression.
* ##### [\_writeUrl()](#_writeUrl()) protected
Converts a matching route array into a URL string.
* ##### [compile()](#compile()) public
Compiles the route's regular expression.
* ##### [compiled()](#compiled()) public
Check if a Route has been compiled into a regular expression.
* ##### [getExtensions()](#getExtensions()) public
Get the supported extensions for this route.
* ##### [getMiddleware()](#getMiddleware()) public
Get the names of the middleware that should be applied to this route.
* ##### [getName()](#getName()) public
Get the standardized plugin.controller:action name for a route.
* ##### [hostMatches()](#hostMatches()) public
Check to see if the host matches the route requirements
* ##### [match()](#match()) public
There is no reverse routing redirection routes.
* ##### [normalizeAndValidateMethods()](#normalizeAndValidateMethods()) protected
Normalize method names to upper case and validate that they are valid HTTP methods.
* ##### [parse()](#parse()) public
Parses a string URL into an array. Parsed URLs will result in an automatic redirection.
* ##### [parseRequest()](#parseRequest()) public
Checks to see if the given URL can be parsed by this route.
* ##### [setExtensions()](#setExtensions()) public
Set the supported extensions for this route.
* ##### [setHost()](#setHost()) public
Set host requirement
* ##### [setMethods()](#setMethods()) public
Set the accepted HTTP methods for this route.
* ##### [setMiddleware()](#setMiddleware()) public
Set the names of the middleware that should be applied to this route.
* ##### [setPass()](#setPass()) public
Set the names of parameters that will be converted into passed parameters
* ##### [setPatterns()](#setPatterns()) public
Set regexp patterns for routing parameters
* ##### [setPersist()](#setPersist()) public
Set the names of parameters that will persisted automatically
* ##### [setStatus()](#setStatus()) public
Sets the HTTP status
* ##### [staticPath()](#staticPath()) public
Get the static path portion for this route.
Method Detail
-------------
### \_\_construct() public
```
__construct(string $template, array $defaults = [], array<string, mixed> $options = [])
```
Constructor
### Options
* `_ext` - Defines the extensions used for this route.
* `_middleware` - Define the middleware names for this route.
* `pass` - Copies the listed parameters into params['pass'].
* `_method` - Defines the HTTP method(s) the route applies to. It can be a string or array of valid HTTP method name.
* `_host` - Define the host name pattern if you want this route to only match specific host names. You can use `.*` and to create wildcard subdomains/hosts e.g. `*.example.com` matches all subdomains on `example.com`.
* '\_port` - Define the port if you want this route to only match specific port number.
* '\_urldecode' - Set to `false` to disable URL decoding before route parsing.
#### Parameters
`string` $template Template string with parameter placeholders
`array` $defaults optional Defaults for the route. Either a redirect=>value array or a CakePHP array URL.
`array<string, mixed>` $options optional Array of additional options for the Route
### \_\_set\_state() public static
```
__set_state(array<string, mixed> $fields): static
```
Set state magic method to support var\_export
This method helps for applications that want to implement router caching.
#### Parameters
`array<string, mixed>` $fields Key/Value of object attributes
#### Returns
`static`
### \_matchMethod() protected
```
_matchMethod(array $url): bool
```
Check whether the URL's HTTP method matches.
#### Parameters
`array` $url The array for the URL being generated.
#### Returns
`bool`
### \_parseArgs() protected
```
_parseArgs(string $args, array $context): array<string>
```
Parse passed parameters into a list of passed args.
Return true if a given named $param's $val matches a given $rule depending on $context. Currently implemented rule types are controller, action and match that can be combined with each other.
#### Parameters
`string` $args A string with the passed params. eg. /1/foo
`array` $context The current route context, which should contain controller/action keys.
#### Returns
`array<string>`
### \_parseExtension() protected
```
_parseExtension(string $url): array
```
Removes the extension from $url if it contains a registered extension. If no registered extension is found, no extension is returned and the URL is returned unmodified.
#### Parameters
`string` $url The url to parse.
#### Returns
`array`
### \_persistParams() protected
```
_persistParams(array $url, array $params): array
```
Apply persistent parameters to a URL array. Persistent parameters are a special key used during route creation to force route parameters to persist when omitted from a URL array.
#### Parameters
`array` $url The array to apply persistent parameters to.
`array` $params An array of persistent values to replace persistent ones.
#### Returns
`array`
### \_writeRoute() protected
```
_writeRoute(): void
```
Builds a route regular expression.
Uses the template, defaults and options properties to compile a regular expression that can be used to parse request strings.
#### Returns
`void`
### \_writeUrl() protected
```
_writeUrl(array $params, array $pass = [], array $query = []): string
```
Converts a matching route array into a URL string.
Composes the string URL using the template used to create the route.
#### Parameters
`array` $params The params to convert to a string url
`array` $pass optional The additional passed arguments
`array` $query optional An array of parameters
#### Returns
`string`
### compile() public
```
compile(): string
```
Compiles the route's regular expression.
Modifies defaults property so all necessary keys are set and populates $this->names with the named routing elements.
#### Returns
`string`
### compiled() public
```
compiled(): bool
```
Check if a Route has been compiled into a regular expression.
#### Returns
`bool`
### getExtensions() public
```
getExtensions(): array<string>
```
Get the supported extensions for this route.
#### Returns
`array<string>`
### getMiddleware() public
```
getMiddleware(): array
```
Get the names of the middleware that should be applied to this route.
#### Returns
`array`
### getName() public
```
getName(): string
```
Get the standardized plugin.controller:action name for a route.
#### Returns
`string`
### hostMatches() public
```
hostMatches(string $host): bool
```
Check to see if the host matches the route requirements
#### Parameters
`string` $host The request's host name
#### Returns
`bool`
### match() public
```
match(array $url, array $context = []): string|null
```
There is no reverse routing redirection routes.
If the URL matches the route parameters and settings, then return a generated string URL. If the URL doesn't match the route parameters, false will be returned. This method handles the reverse routing or conversion of URL arrays into string URLs.
#### Parameters
`array` $url Array of parameters to convert to a string.
`array` $context optional Array of request context parameters.
#### Returns
`string|null`
### normalizeAndValidateMethods() protected
```
normalizeAndValidateMethods(array<string>|string $methods): array<string>|string
```
Normalize method names to upper case and validate that they are valid HTTP methods.
#### Parameters
`array<string>|string` $methods Methods.
#### Returns
`array<string>|string`
#### Throws
`InvalidArgumentException`
When methods are not in `VALID\_METHODS` list. ### parse() public
```
parse(string $url, string $method = ''): array|null
```
Parses a string URL into an array. Parsed URLs will result in an automatic redirection.
If the route can be parsed an array of parameters will be returned; if not `null` will be returned. String URLs are parsed if they match a routes regular expression.
#### Parameters
`string` $url The URL to parse.
`string` $method optional The HTTP method being used.
#### Returns
`array|null`
#### Throws
`Cake\Http\Exception\RedirectException`
An exception is raised on successful match. This is used to halt route matching and signal to the middleware that a redirect should happen. ### parseRequest() public
```
parseRequest(Psr\Http\Message\ServerRequestInterface $request): array|null
```
Checks to see if the given URL can be parsed by this route.
If the route can be parsed an array of parameters will be returned; if not `null` will be returned.
#### Parameters
`Psr\Http\Message\ServerRequestInterface` $request The URL to attempt to parse.
#### Returns
`array|null`
### setExtensions() public
```
setExtensions(array<string> $extensions): $this
```
Set the supported extensions for this route.
#### Parameters
`array<string>` $extensions The extensions to set.
#### Returns
`$this`
### setHost() public
```
setHost(string $host): $this
```
Set host requirement
#### Parameters
`string` $host The host name this route is bound to
#### Returns
`$this`
### setMethods() public
```
setMethods(array<string> $methods): $this
```
Set the accepted HTTP methods for this route.
#### Parameters
`array<string>` $methods The HTTP methods to accept.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
When methods are not in `VALID\_METHODS` list. ### setMiddleware() public
```
setMiddleware(array $middleware): $this
```
Set the names of the middleware that should be applied to this route.
#### Parameters
`array` $middleware The list of middleware names to apply to this route. Middleware names will not be checked until the route is matched.
#### Returns
`$this`
### setPass() public
```
setPass(array<string> $names): $this
```
Set the names of parameters that will be converted into passed parameters
#### Parameters
`array<string>` $names The names of the parameters that should be passed.
#### Returns
`$this`
### setPatterns() public
```
setPatterns(array<string> $patterns): $this
```
Set regexp patterns for routing parameters
If any of your patterns contain multibyte values, the `multibytePattern` mode will be enabled.
#### Parameters
`array<string>` $patterns The patterns to apply to routing elements
#### Returns
`$this`
### setPersist() public
```
setPersist(array $names): $this
```
Set the names of parameters that will persisted automatically
Persistent parameters allow you to define which route parameters should be automatically included when generating new URLs. You can override persistent parameters by redefining them in a URL or remove them by setting the persistent parameter to `false`.
```
// remove a persistent 'date' parameter
Router::url(['date' => false', ...]);
```
#### Parameters
`array` $names The names of the parameters that should be passed.
#### Returns
`$this`
### setStatus() public
```
setStatus(int $status): $this
```
Sets the HTTP status
#### Parameters
`int` $status The status code for this route
#### Returns
`$this`
### staticPath() public
```
staticPath(): string
```
Get the static path portion for this route.
#### Returns
`string`
Property Detail
---------------
### $\_compiledRoute protected
The compiled route regular expression
#### Type
`string|null`
### $\_extensions protected
List of connected extensions for this route.
#### Type
`array<string>`
### $\_greedy protected
Is this route a greedy route? Greedy routes have a `/*` in their template
#### Type
`bool`
### $\_name protected
The name for a route. Fetch with Route::getName();
#### Type
`string|null`
### $braceKeys protected
Track whether brace keys `{var}` were used.
#### Type
`bool`
### $defaults public
Default parameters for a Route
#### Type
`array`
### $keys public
An array of named segments in a Route. `/{controller}/{action}/{id}` has 3 key elements
#### Type
`array`
### $middleware protected
List of middleware that should be applied.
#### Type
`array`
### $options public
An array of additional parameters for the Route.
#### Type
`array`
### $redirect public
The location to redirect to.
#### Type
`array`
### $template public
The routes template string.
#### Type
`string`
| programming_docs |
cakephp Class FailedRouteCacheException Class FailedRouteCacheException
================================
Thrown when unable to cache route collection.
**Namespace:** [Cake\Routing\Exception](namespace-cake.routing.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Class MissingElementException Class MissingElementException
==============================
Used when an element file cannot be found.
**Namespace:** [Cake\View\Exception](namespace-cake.view.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
* [$filename](#%24filename) protected `string`
* [$paths](#%24paths) protected `array<string>`
* [$templateName](#%24templateName) protected `string|null`
* [$type](#%24type) protected `string`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [formatMessage()](#formatMessage()) public
Get the formatted exception message.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string>|string $file, array<string> $paths = [], int|null $code = null, Throwable|null $previous = null)
```
Constructor
#### Parameters
`array<string>|string` $file Either the file name as a string, or in an array for backwards compatibility.
`array<string>` $paths optional The path list that template could not be found in.
`int|null` $code optional The code of the error.
`Throwable|null` $previous optional the previous exception.
### formatMessage() public
```
formatMessage(): string
```
Get the formatted exception message.
#### Returns
`string`
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
### $filename protected
#### Type
`string`
### $paths protected
#### Type
`array<string>`
### $templateName protected
#### Type
`string|null`
### $type protected
#### Type
`string`
cakephp Trait TypeMapTrait Trait TypeMapTrait
===================
Trait TypeMapTrait
**Namespace:** [Cake\Database](namespace-cake.database)
Property Summary
----------------
* [$\_typeMap](#%24_typeMap) protected `Cake\Database\TypeMap|null`
Method Summary
--------------
* ##### [getDefaultTypes()](#getDefaultTypes()) public
Gets default types of current type map.
* ##### [getTypeMap()](#getTypeMap()) public
Returns the existing type map.
* ##### [setDefaultTypes()](#setDefaultTypes()) public
Overwrite the default type mappings for fields in the implementing object.
* ##### [setTypeMap()](#setTypeMap()) public
Creates a new TypeMap if $typeMap is an array, otherwise exchanges it for the given one.
Method Detail
-------------
### getDefaultTypes() public
```
getDefaultTypes(): array<int|string, string>
```
Gets default types of current type map.
#### Returns
`array<int|string, string>`
### getTypeMap() public
```
getTypeMap(): Cake\Database\TypeMap
```
Returns the existing type map.
#### Returns
`Cake\Database\TypeMap`
### setDefaultTypes() public
```
setDefaultTypes(array<int|string, string> $types): $this
```
Overwrite the default type mappings for fields in the implementing object.
This method is useful if you need to set type mappings that are shared across multiple functions/expressions in a query.
To add a default without overwriting existing ones use `getTypeMap()->addDefaults()`
#### Parameters
`array<int|string, string>` $types The array of types to set.
#### Returns
`$this`
#### See Also
\Cake\Database\TypeMap::setDefaults() ### setTypeMap() public
```
setTypeMap(Cake\Database\TypeMap|array $typeMap): $this
```
Creates a new TypeMap if $typeMap is an array, otherwise exchanges it for the given one.
#### Parameters
`Cake\Database\TypeMap|array` $typeMap Creates a TypeMap if array, otherwise sets the given TypeMap
#### Returns
`$this`
Property Detail
---------------
### $\_typeMap protected
#### Type
`Cake\Database\TypeMap|null`
cakephp Interface OptionalConvertInterface Interface OptionalConvertInterface
===================================
An interface used by Type objects to signal whether the casting is actually required.
**Namespace:** [Cake\Database\Type](namespace-cake.database.type)
Method Summary
--------------
* ##### [requiresToPhpCast()](#requiresToPhpCast()) public
Returns whether the cast to PHP is required to be invoked, since it is not a identity function.
Method Detail
-------------
### requiresToPhpCast() public
```
requiresToPhpCast(): bool
```
Returns whether the cast to PHP is required to be invoked, since it is not a identity function.
#### Returns
`bool`
cakephp Namespace Command Namespace Command
=================
### Classes
* ##### [HelpCommand](class-cake.console.command.helpcommand)
Print out command list
cakephp Class ViewBuilder Class ViewBuilder
==================
Provides an API for iteratively building a view up.
Once you have configured the view and established all the context you can create a view instance with `build()`.
**Namespace:** [Cake\View](namespace-cake.view)
Property Summary
----------------
* [$\_autoLayout](#%24_autoLayout) protected `bool` Whether autoLayout should be enabled.
* [$\_className](#%24_className) protected `string|null` The view class name to use. Can either use plugin notation, a short name or a fully namespaced classname.
* [$\_helpers](#%24_helpers) protected `array` The helpers to use
* [$\_layout](#%24_layout) protected `string|null` The layout name to render.
* [$\_layoutPath](#%24_layoutPath) protected `string|null` The layout path to build the view with.
* [$\_name](#%24_name) protected `string|null` The view variables to use
* [$\_options](#%24_options) protected `array<string, mixed>` Additional options used when constructing the view.
* [$\_plugin](#%24_plugin) protected `string|null` The plugin name to use.
* [$\_template](#%24_template) protected `string|null` The template file to render.
* [$\_templatePath](#%24_templatePath) protected `string|null` The subdirectory to the template.
* [$\_theme](#%24_theme) protected `string|null` The theme name to use.
* [$\_vars](#%24_vars) protected `array<string, mixed>` View vars
Method Summary
--------------
* ##### [\_\_serialize()](#__serialize()) public
Magic method used for serializing the view builder object.
* ##### [\_\_unserialize()](#__unserialize()) public
Magic method used to rebuild the view builder object.
* ##### [\_checkViewVars()](#_checkViewVars()) protected
Iterates through hash to clean up and normalize.
* ##### [addHelper()](#addHelper()) public
Adds a helper to use.
* ##### [addHelpers()](#addHelpers()) public
Adds helpers to use by merging with existing ones.
* ##### [build()](#build()) public
Using the data in the builder, create a view instance.
* ##### [createFromArray()](#createFromArray()) public
Configures a view builder instance from serialized config.
* ##### [disableAutoLayout()](#disableAutoLayout()) public
Turns off CakePHP's conventional mode of applying layout files.
* ##### [enableAutoLayout()](#enableAutoLayout()) public
Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered views.
* ##### [getClassName()](#getClassName()) public
Gets the view classname.
* ##### [getHelpers()](#getHelpers()) public
Gets the helpers to use.
* ##### [getLayout()](#getLayout()) public
Gets the name of the layout file to render the view inside of.
* ##### [getLayoutPath()](#getLayoutPath()) public
Gets path for layout files.
* ##### [getName()](#getName()) public
Gets the view name.
* ##### [getOption()](#getOption()) public
Get view option.
* ##### [getOptions()](#getOptions()) public
Gets additional options for the view.
* ##### [getPlugin()](#getPlugin()) public
Gets the plugin name to use.
* ##### [getTemplate()](#getTemplate()) public
Gets the name of the view file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
* ##### [getTemplatePath()](#getTemplatePath()) public
Gets path for template files.
* ##### [getTheme()](#getTheme()) public
Gets the view theme to use.
* ##### [getVar()](#getVar()) public
Get view var
* ##### [getVars()](#getVars()) public
Get all view vars.
* ##### [hasVar()](#hasVar()) public
Check if view var is set.
* ##### [isAutoLayoutEnabled()](#isAutoLayoutEnabled()) public
Returns if CakePHP's conventional mode of applying layout files is enabled. Disabled means that layouts will not be automatically applied to rendered views.
* ##### [jsonSerialize()](#jsonSerialize()) public
Serializes the view builder object to a value that can be natively serialized and re-used to clone this builder instance.
* ##### [serialize()](#serialize()) public
Serializes the view builder object.
* ##### [setClassName()](#setClassName()) public
Sets the view classname.
* ##### [setHelpers()](#setHelpers()) public
Sets the helpers to use.
* ##### [setLayout()](#setLayout()) public
Sets the name of the layout file to render the view inside of. The name specified is the filename of the layout in `templates/layout/` without the .php extension.
* ##### [setLayoutPath()](#setLayoutPath()) public
Sets path for layout files.
* ##### [setName()](#setName()) public
Sets the view name.
* ##### [setOption()](#setOption()) public
Set view option.
* ##### [setOptions()](#setOptions()) public
Sets additional options for the view.
* ##### [setPlugin()](#setPlugin()) public
Sets the plugin name to use.
* ##### [setTemplate()](#setTemplate()) public
Sets the name of the view file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
* ##### [setTemplatePath()](#setTemplatePath()) public
Sets path for template files.
* ##### [setTheme()](#setTheme()) public
Sets the view theme to use.
* ##### [setVar()](#setVar()) public
Saves a variable for use inside a template.
* ##### [setVars()](#setVars()) public
Saves view vars for use inside templates.
* ##### [unserialize()](#unserialize()) public
Unserializes the view builder object.
Method Detail
-------------
### \_\_serialize() public
```
__serialize(): array
```
Magic method used for serializing the view builder object.
#### Returns
`array`
### \_\_unserialize() public
```
__unserialize(array<string, mixed> $data): void
```
Magic method used to rebuild the view builder object.
#### Parameters
`array<string, mixed>` $data Data array.
#### Returns
`void`
### \_checkViewVars() protected
```
_checkViewVars(mixed $item, string $key): void
```
Iterates through hash to clean up and normalize.
#### Parameters
`mixed` $item Reference to the view var value.
`string` $key View var key.
#### Returns
`void`
#### Throws
`RuntimeException`
### addHelper() public
```
addHelper(string $helper, array<string, mixed> $options = []): $this
```
Adds a helper to use.
#### Parameters
`string` $helper Helper to use.
`array<string, mixed>` $options optional Options.
#### Returns
`$this`
### addHelpers() public
```
addHelpers(array $helpers): $this
```
Adds helpers to use by merging with existing ones.
#### Parameters
`array` $helpers Helpers to use.
#### Returns
`$this`
### build() public
```
build(array<string, mixed> $vars = [], Cake\Http\ServerRequest|null $request = null, Cake\Http\Response|null $response = null, Cake\Event\EventManagerInterface|null $events = null): Cake\View\View
```
Using the data in the builder, create a view instance.
If className() is null, App\View\AppView will be used. If that class does not exist, then {@link \Cake\View\View} will be used.
#### Parameters
`array<string, mixed>` $vars optional The view variables/context to use.
`Cake\Http\ServerRequest|null` $request optional The request to use.
`Cake\Http\Response|null` $response optional The response to use.
`Cake\Event\EventManagerInterface|null` $events optional The event manager to use.
#### Returns
`Cake\View\View`
#### Throws
`Cake\View\Exception\MissingViewException`
### createFromArray() public
```
createFromArray(array<string, mixed> $config): $this
```
Configures a view builder instance from serialized config.
#### Parameters
`array<string, mixed>` $config View builder configuration array.
#### Returns
`$this`
### disableAutoLayout() public
```
disableAutoLayout(): $this
```
Turns off CakePHP's conventional mode of applying layout files.
Setting to off means that layouts will not be automatically applied to rendered views.
#### Returns
`$this`
### enableAutoLayout() public
```
enableAutoLayout(bool $enable = true): $this
```
Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered views.
#### Parameters
`bool` $enable optional Boolean to turn on/off.
#### Returns
`$this`
### getClassName() public
```
getClassName(): string|null
```
Gets the view classname.
#### Returns
`string|null`
### getHelpers() public
```
getHelpers(): array
```
Gets the helpers to use.
#### Returns
`array`
### getLayout() public
```
getLayout(): string|null
```
Gets the name of the layout file to render the view inside of.
#### Returns
`string|null`
### getLayoutPath() public
```
getLayoutPath(): string|null
```
Gets path for layout files.
#### Returns
`string|null`
### getName() public
```
getName(): string|null
```
Gets the view name.
#### Returns
`string|null`
### getOption() public
```
getOption(string $name): mixed
```
Get view option.
#### Parameters
`string` $name The name of the option.
#### Returns
`mixed`
### getOptions() public
```
getOptions(): array<string, mixed>
```
Gets additional options for the view.
#### Returns
`array<string, mixed>`
### getPlugin() public
```
getPlugin(): string|null
```
Gets the plugin name to use.
#### Returns
`string|null`
### getTemplate() public
```
getTemplate(): string|null
```
Gets the name of the view file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
#### Returns
`string|null`
### getTemplatePath() public
```
getTemplatePath(): string|null
```
Gets path for template files.
#### Returns
`string|null`
### getTheme() public
```
getTheme(): string|null
```
Gets the view theme to use.
#### Returns
`string|null`
### getVar() public
```
getVar(string $name): mixed
```
Get view var
#### Parameters
`string` $name Var name
#### Returns
`mixed`
### getVars() public
```
getVars(): array<string, mixed>
```
Get all view vars.
#### Returns
`array<string, mixed>`
### hasVar() public
```
hasVar(string $name): bool
```
Check if view var is set.
#### Parameters
`string` $name Var name
#### Returns
`bool`
### isAutoLayoutEnabled() public
```
isAutoLayoutEnabled(): bool
```
Returns if CakePHP's conventional mode of applying layout files is enabled. Disabled means that layouts will not be automatically applied to rendered views.
#### Returns
`bool`
### jsonSerialize() public
```
jsonSerialize(): array
```
Serializes the view builder object to a value that can be natively serialized and re-used to clone this builder instance.
There are limitations for viewVars that are good to know:
* ORM\Query executed and stored as resultset
* SimpleXMLElements stored as associative array
* Exceptions stored as strings
* Resources, \Closure and \PDO are not supported.
#### Returns
`array`
### serialize() public
```
serialize(): string
```
Serializes the view builder object.
#### Returns
`string`
### setClassName() public
```
setClassName(string|null $name): $this
```
Sets the view classname.
Accepts either a short name (Ajax) a plugin name (MyPlugin.Ajax) or a fully namespaced name (App\View\AppView) or null to use the View class provided by CakePHP.
#### Parameters
`string|null` $name The class name for the view.
#### Returns
`$this`
### setHelpers() public
```
setHelpers(array $helpers, bool $merge = true): $this
```
Sets the helpers to use.
#### Parameters
`array` $helpers Helpers to use.
`bool` $merge optional Whether to merge existing data with the new data.
#### Returns
`$this`
### setLayout() public
```
setLayout(string|null $name): $this
```
Sets the name of the layout file to render the view inside of. The name specified is the filename of the layout in `templates/layout/` without the .php extension.
#### Parameters
`string|null` $name Layout file name to set.
#### Returns
`$this`
### setLayoutPath() public
```
setLayoutPath(string|null $path): $this
```
Sets path for layout files.
#### Parameters
`string|null` $path Path for layout files.
#### Returns
`$this`
### setName() public
```
setName(string|null $name): $this
```
Sets the view name.
#### Parameters
`string|null` $name The name of the view, or null to remove the current name.
#### Returns
`$this`
### setOption() public
```
setOption(string $name, mixed $value): $this
```
Set view option.
#### Parameters
`string` $name The name of the option.
`mixed` $value Value to set.
#### Returns
`$this`
### setOptions() public
```
setOptions(array<string, mixed> $options, bool $merge = true): $this
```
Sets additional options for the view.
This lets you provide custom constructor arguments to application/plugin view classes.
#### Parameters
`array<string, mixed>` $options An array of options.
`bool` $merge optional Whether to merge existing data with the new data.
#### Returns
`$this`
### setPlugin() public
```
setPlugin(string|null $name): $this
```
Sets the plugin name to use.
#### Parameters
`string|null` $name Plugin name. Use null to remove the current plugin name.
#### Returns
`$this`
### setTemplate() public
```
setTemplate(string|null $name): $this
```
Sets the name of the view file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
#### Parameters
`string|null` $name View file name to set, or null to remove the template name.
#### Returns
`$this`
### setTemplatePath() public
```
setTemplatePath(string|null $path): $this
```
Sets path for template files.
#### Parameters
`string|null` $path Path for view files.
#### Returns
`$this`
### setTheme() public
```
setTheme(string|null $theme): $this
```
Sets the view theme to use.
#### Parameters
`string|null` $theme Theme name. Use null to remove the current theme.
#### Returns
`$this`
### setVar() public
```
setVar(string $name, mixed $value = null): $this
```
Saves a variable for use inside a template.
#### Parameters
`string` $name A string or an array of data.
`mixed` $value optional Value.
#### Returns
`$this`
### setVars() public
```
setVars(array<string, mixed> $data, bool $merge = true): $this
```
Saves view vars for use inside templates.
#### Parameters
`array<string, mixed>` $data Array of data.
`bool` $merge optional Whether to merge with existing vars, default true.
#### Returns
`$this`
### unserialize() public
```
unserialize(string $data): void
```
Unserializes the view builder object.
#### Parameters
`string` $data Serialized string.
#### Returns
`void`
Property Detail
---------------
### $\_autoLayout protected
Whether autoLayout should be enabled.
#### Type
`bool`
### $\_className protected
The view class name to use. Can either use plugin notation, a short name or a fully namespaced classname.
#### Type
`string|null`
### $\_helpers protected
The helpers to use
#### Type
`array`
### $\_layout protected
The layout name to render.
#### Type
`string|null`
### $\_layoutPath protected
The layout path to build the view with.
#### Type
`string|null`
### $\_name protected
The view variables to use
#### Type
`string|null`
### $\_options protected
Additional options used when constructing the view.
These options array lets you provide custom constructor arguments to application/plugin view classes.
#### Type
`array<string, mixed>`
### $\_plugin protected
The plugin name to use.
#### Type
`string|null`
### $\_template protected
The template file to render.
#### Type
`string|null`
### $\_templatePath protected
The subdirectory to the template.
#### Type
`string|null`
### $\_theme protected
The theme name to use.
#### Type
`string|null`
### $\_vars protected
View vars
#### Type
`array<string, mixed>`
| programming_docs |
cakephp Class BinaryType Class BinaryType
=================
Binary type converter.
Use to convert binary data between PHP and the database types.
**Namespace:** [Cake\Database\Type](namespace-cake.database.type)
Property Summary
----------------
* [$\_name](#%24_name) protected `string|null` Identifier name for this type
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getBaseType()](#getBaseType()) public
Returns the base type name that this class is inheriting.
* ##### [getName()](#getName()) public
Returns type identifier name for this object.
* ##### [marshal()](#marshal()) public
Marshals flat data into PHP objects.
* ##### [newId()](#newId()) public
Generate a new primary key value for a given type.
* ##### [toDatabase()](#toDatabase()) public
Convert binary data into the database format.
* ##### [toPHP()](#toPHP()) public
Convert binary into resource handles
* ##### [toStatement()](#toStatement()) public
Get the correct PDO binding type for Binary data.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $name = null)
```
Constructor
#### Parameters
`string|null` $name optional The name identifying this type
### getBaseType() public
```
getBaseType(): string|null
```
Returns the base type name that this class is inheriting.
This is useful when extending base type for adding extra functionality, but still want the rest of the framework to use the same assumptions it would do about the base type it inherits from.
#### Returns
`string|null`
### getName() public
```
getName(): string|null
```
Returns type identifier name for this object.
#### Returns
`string|null`
### marshal() public
```
marshal(mixed $value): mixed
```
Marshals flat data into PHP objects.
Most useful for converting request data into PHP objects that make sense for the rest of the ORM/Database layers.
#### Parameters
`mixed` $value The value to convert.
#### Returns
`mixed`
### newId() public
```
newId(): mixed
```
Generate a new primary key value for a given type.
This method can be used by types to create new primary key values when entities are inserted.
#### Returns
`mixed`
### toDatabase() public
```
toDatabase(mixed $value, Cake\Database\DriverInterface $driver): resource|string
```
Convert binary data into the database format.
Binary data is not altered before being inserted into the database. As PDO will handle reading file handles.
#### Parameters
`mixed` $value The value to convert.
`Cake\Database\DriverInterface` $driver The driver instance to convert with.
#### Returns
`resource|string`
### toPHP() public
```
toPHP(mixed $value, Cake\Database\DriverInterface $driver): resource|null
```
Convert binary into resource handles
#### Parameters
`mixed` $value The value to convert.
`Cake\Database\DriverInterface` $driver The driver instance to convert with.
#### Returns
`resource|null`
#### Throws
`Cake\Core\Exception\CakeException`
### toStatement() public
```
toStatement(mixed $value, Cake\Database\DriverInterface $driver): int
```
Get the correct PDO binding type for Binary data.
#### Parameters
`mixed` $value The value being bound.
`Cake\Database\DriverInterface` $driver The driver.
#### Returns
`int`
Property Detail
---------------
### $\_name protected
Identifier name for this type
#### Type
`string|null`
cakephp Class ValidationRule Class ValidationRule
=====================
ValidationRule object. Represents a validation method, error message and rules for applying such method to a field.
**Namespace:** [Cake\Validation](namespace-cake.validation)
Property Summary
----------------
* [$\_last](#%24_last) protected `bool` The 'last' key
* [$\_message](#%24_message) protected `string` The 'message' key
* [$\_on](#%24_on) protected `callable|string` The 'on' key
* [$\_pass](#%24_pass) protected `array` Extra arguments to be passed to the validation method
* [$\_provider](#%24_provider) protected `string` Key under which the object or class where the method to be used for validation will be found
* [$\_rule](#%24_rule) protected `callable|string` The method to be called for a given scope
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_addValidatorProps()](#_addValidatorProps()) protected
Sets the rule properties from the rule entry in validate
* ##### [\_skip()](#_skip()) protected
Checks if the validation rule should be skipped
* ##### [get()](#get()) public
Returns the value of a property by name
* ##### [isLast()](#isLast()) public
Returns whether this rule should break validation process for associated field after it fails
* ##### [process()](#process()) public
Dispatches the validation rule to the given validator method and returns a boolean indicating whether the rule passed or not. If a string is returned it is assumed that the rule failed and the error message was given as a result.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $validator = [])
```
Constructor
#### Parameters
`array<string, mixed>` $validator optional [optional] The validator properties
### \_addValidatorProps() protected
```
_addValidatorProps(array<string, mixed> $validator = []): void
```
Sets the rule properties from the rule entry in validate
#### Parameters
`array<string, mixed>` $validator optional [optional]
#### Returns
`void`
### \_skip() protected
```
_skip(array<string, mixed> $context): bool
```
Checks if the validation rule should be skipped
#### Parameters
`array<string, mixed>` $context
A key value list of data that could be used as context during validation. Recognized keys are:
* newRecord: (boolean) whether the data to be validated belongs to a new record
* data: The full data that was passed to the validation process
* providers associative array with objects or class names that will be passed as the last argument for the validation method
#### Returns
`bool`
### get() public
```
get(string $property): mixed
```
Returns the value of a property by name
#### Parameters
`string` $property The name of the property to retrieve.
#### Returns
`mixed`
### isLast() public
```
isLast(): bool
```
Returns whether this rule should break validation process for associated field after it fails
#### Returns
`bool`
### process() public
```
process(mixed $value, array<string, mixed> $providers, array<string, mixed> $context = []): array|string|bool
```
Dispatches the validation rule to the given validator method and returns a boolean indicating whether the rule passed or not. If a string is returned it is assumed that the rule failed and the error message was given as a result.
#### Parameters
`mixed` $value The data to validate
`array<string, mixed>` $providers Associative array with objects or class names that will be passed as the last argument for the validation method
`array<string, mixed>` $context optional
A key value list of data that could be used as context during validation. Recognized keys are:
* newRecord: (boolean) whether the data to be validated belongs to a new record
* data: The full data that was passed to the validation process
* field: The name of the field that is being processed
#### Returns
`array|string|bool`
#### Throws
`InvalidArgumentException`
when the supplied rule is not a valid callable for the configured scope Property Detail
---------------
### $\_last protected
The 'last' key
#### Type
`bool`
### $\_message protected
The 'message' key
#### Type
`string`
### $\_on protected
The 'on' key
#### Type
`callable|string`
### $\_pass protected
Extra arguments to be passed to the validation method
#### Type
`array`
### $\_provider protected
Key under which the object or class where the method to be used for validation will be found
#### Type
`string`
### $\_rule protected
The method to be called for a given scope
#### Type
`callable|string`
cakephp Class DuplicateNamedRouteException Class DuplicateNamedRouteException
===================================
Exception raised when a route names used twice.
**Namespace:** [Cake\Routing\Exception](namespace-cake.routing.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message, int|null $code = 404, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|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
`int|null` $code optional The code of the error, is also the HTTP status code for the error. Defaults to 404.
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Class LazyEagerLoader Class LazyEagerLoader
======================
Contains methods that are capable of injecting eagerly loaded associations into entities or lists of entities by using the same syntax as the EagerLoader.
**Namespace:** [Cake\ORM](namespace-cake.orm)
Method Summary
--------------
* ##### [\_getPropertyMap()](#_getPropertyMap()) protected
Returns a map of property names where the association results should be injected in the top level entities.
* ##### [\_getQuery()](#_getQuery()) protected
Builds a query for loading the passed list of entity objects along with the associations specified in $contain.
* ##### [\_injectResults()](#_injectResults()) protected
Injects the results of the eager loader query into the original list of entities.
* ##### [loadInto()](#loadInto()) public
Loads the specified associations in the passed entity or list of entities by executing extra queries in the database and merging the results in the appropriate properties.
Method Detail
-------------
### \_getPropertyMap() protected
```
_getPropertyMap(Cake\ORM\Table $source, array<string> $associations): array<string>
```
Returns a map of property names where the association results should be injected in the top level entities.
#### Parameters
`Cake\ORM\Table` $source The table having the top level associations
`array<string>` $associations The name of the top level associations
#### Returns
`array<string>`
### \_getQuery() protected
```
_getQuery(Cake\Collection\CollectionInterface $objects, array $contain, Cake\ORM\Table $source): Cake\ORM\Query
```
Builds a query for loading the passed list of entity objects along with the associations specified in $contain.
#### Parameters
`Cake\Collection\CollectionInterface` $objects The original entities
`array` $contain The associations to be loaded
`Cake\ORM\Table` $source The table to use for fetching the top level entities
#### Returns
`Cake\ORM\Query`
### \_injectResults() protected
```
_injectResults(iterableCake\Datasource\EntityInterface> $objects, Cake\ORM\Query $results, array<string> $associations, Cake\ORM\Table $source): arrayCake\Datasource\EntityInterface>
```
Injects the results of the eager loader query into the original list of entities.
#### Parameters
`iterableCake\Datasource\EntityInterface>` $objects The original list of entities
`Cake\ORM\Query` $results The loaded results
`array<string>` $associations The top level associations that were loaded
`Cake\ORM\Table` $source The table where the entities came from
#### Returns
`arrayCake\Datasource\EntityInterface>`
### loadInto() public
```
loadInto(Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface> $entities, array $contain, Cake\ORM\Table $source): Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface>
```
Loads the specified associations in the passed entity or list of entities by executing extra queries in the database and merging the results in the appropriate properties.
The properties for the associations to be loaded will be overwritten on each entity.
#### Parameters
`Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface>` $entities a single entity or list of entities
`array` $contain A `contain()` compatible array.
`Cake\ORM\Table` $source The table to use for fetching the top level entities
#### Returns
`Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface>`
#### See Also
\Cake\ORM\Query::contain()
cakephp Class AuthSecurityException Class AuthSecurityException
============================
Auth Security exception - used when SecurityComponent detects any issue with the current request
**Namespace:** [Cake\Controller\Exception](namespace-cake.controller.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_reason](#%24_reason) protected `string|null` Reason for request blackhole
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
* [$\_type](#%24_type) protected `string` Security Exception type
* [$headers](#%24headers) protected `array<string, mixed>`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [getHeaders()](#getHeaders()) public
Returns array of response headers.
* ##### [getReason()](#getReason()) public
Get Reason
* ##### [getType()](#getType()) public
Getter for type
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
* ##### [setHeader()](#setHeader()) public
Set a single HTTP response header.
* ##### [setHeaders()](#setHeaders()) public
Sets HTTP response headers.
* ##### [setMessage()](#setMessage()) public
Set Message
* ##### [setReason()](#setReason()) public
Set Reason
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $message = null, int|null $code = null, Throwable|null $previous = null)
```
Constructor
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`string|null` $message optional If no message is given 'Bad Request' will be the message
`int|null` $code optional Status code, defaults to 400
`Throwable|null` $previous optional The previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### getHeaders() public
```
getHeaders(): array<string, mixed>
```
Returns array of response headers.
#### Returns
`array<string, mixed>`
### getReason() public
```
getReason(): string|null
```
Get Reason
#### Returns
`string|null`
### getType() public
```
getType(): string
```
Getter for type
#### Returns
`string`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
### setHeader() public
```
setHeader(string $header, array<string>|string|null $value = null): void
```
Set a single HTTP response header.
#### Parameters
`string` $header Header name
`array<string>|string|null` $value optional Header value
#### Returns
`void`
### setHeaders() public
```
setHeaders(array<string, mixed> $headers): void
```
Sets HTTP response headers.
#### Parameters
`array<string, mixed>` $headers Array of header name and value pairs.
#### Returns
`void`
### setMessage() public
```
setMessage(string $message): void
```
Set Message
#### Parameters
`string` $message Exception message
#### Returns
`void`
### setReason() public
```
setReason(string|null $reason = null): $this
```
Set Reason
#### Parameters
`string|null` $reason optional Reason details
#### Returns
`$this`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_reason protected
Reason for request blackhole
#### Type
`string|null`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
### $\_type protected
Security Exception type
#### Type
`string`
### $headers protected
#### Type
`array<string, mixed>`
| programming_docs |
cakephp Class CookieCollection Class CookieCollection
=======================
Cookie Collection
Provides an immutable collection of cookies objects. Adding or removing to a collection returns a *new* collection that you must retain.
**Namespace:** [Cake\Http\Cookie](namespace-cake.http.cookie)
Property Summary
----------------
* [$cookies](#%24cookies) protected `arrayCake\Http\Cookie\CookieInterface>` Cookie objects
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [add()](#add()) public
Add a cookie and get an updated collection.
* ##### [addFromResponse()](#addFromResponse()) public
Create a new collection that includes cookies from the response.
* ##### [addToRequest()](#addToRequest()) public
Add cookies that match the path/domain/expiration to the request.
* ##### [checkCookies()](#checkCookies()) protected
Checks if only valid cookie objects are in the array
* ##### [count()](#count()) public
Get the number of cookies in the collection.
* ##### [createFromHeader()](#createFromHeader()) public static
Create a Cookie Collection from an array of Set-Cookie Headers
* ##### [createFromServerRequest()](#createFromServerRequest()) public static
Create a new collection from the cookies in a ServerRequest
* ##### [findMatchingCookies()](#findMatchingCookies()) protected
Find cookies matching the scheme, host, and path
* ##### [get()](#get()) public
Get the first cookie by name.
* ##### [getIterator()](#getIterator()) public
Gets the iterator
* ##### [has()](#has()) public
Check if a cookie with the given name exists
* ##### [remove()](#remove()) public
Create a new collection with all cookies matching $name removed.
* ##### [removeExpiredCookies()](#removeExpiredCookies()) protected
Remove expired cookies from the collection.
Method Detail
-------------
### \_\_construct() public
```
__construct(arrayCake\Http\Cookie\CookieInterface> $cookies = [])
```
Constructor
#### Parameters
`arrayCake\Http\Cookie\CookieInterface>` $cookies optional Array of cookie objects
### add() public
```
add(Cake\Http\Cookie\CookieInterface $cookie): static
```
Add a cookie and get an updated collection.
Cookies are stored by id. This means that there can be duplicate cookies if a cookie collection is used for cookies across multiple domains. This can impact how get(), has() and remove() behave.
#### Parameters
`Cake\Http\Cookie\CookieInterface` $cookie Cookie instance to add.
#### Returns
`static`
### addFromResponse() public
```
addFromResponse(Psr\Http\Message\ResponseInterface $response, Psr\Http\Message\RequestInterface $request): static
```
Create a new collection that includes cookies from the response.
#### Parameters
`Psr\Http\Message\ResponseInterface` $response Response to extract cookies from.
`Psr\Http\Message\RequestInterface` $request Request to get cookie context from.
#### Returns
`static`
### addToRequest() public
```
addToRequest(Psr\Http\Message\RequestInterface $request, array $extraCookies = []): Psr\Http\Message\RequestInterface
```
Add cookies that match the path/domain/expiration to the request.
This allows CookieCollections to be used as a 'cookie jar' in an HTTP client situation. Cookies that match the request's domain + path that are not expired when this method is called will be applied to the request.
#### Parameters
`Psr\Http\Message\RequestInterface` $request The request to update.
`array` $extraCookies optional Associative array of additional cookies to add into the request. This is useful when you have cookie data from outside the collection you want to send.
#### Returns
`Psr\Http\Message\RequestInterface`
### checkCookies() protected
```
checkCookies(arrayCake\Http\Cookie\CookieInterface> $cookies): void
```
Checks if only valid cookie objects are in the array
#### Parameters
`arrayCake\Http\Cookie\CookieInterface>` $cookies Array of cookie objects
#### Returns
`void`
#### Throws
`InvalidArgumentException`
### count() public
```
count(): int
```
Get the number of cookies in the collection.
#### Returns
`int`
### createFromHeader() public static
```
createFromHeader(array<string> $header, array<string, mixed> $defaults = []): static
```
Create a Cookie Collection from an array of Set-Cookie Headers
#### Parameters
`array<string>` $header The array of set-cookie header values.
`array<string, mixed>` $defaults optional The defaults attributes.
#### Returns
`static`
### createFromServerRequest() public static
```
createFromServerRequest(Psr\Http\Message\ServerRequestInterface $request): static
```
Create a new collection from the cookies in a ServerRequest
#### Parameters
`Psr\Http\Message\ServerRequestInterface` $request The request to extract cookie data from
#### Returns
`static`
### findMatchingCookies() protected
```
findMatchingCookies(string $scheme, string $host, string $path): array<string, mixed>
```
Find cookies matching the scheme, host, and path
#### Parameters
`string` $scheme The http scheme to match
`string` $host The host to match.
`string` $path The path to match
#### Returns
`array<string, mixed>`
### get() public
```
get(string $name): Cake\Http\Cookie\CookieInterface
```
Get the first cookie by name.
#### Parameters
`string` $name The name of the cookie.
#### Returns
`Cake\Http\Cookie\CookieInterface`
#### Throws
`InvalidArgumentException`
If cookie not found. ### getIterator() public
```
getIterator(): Traversable<string,Cake\Http\Cookie\CookieInterface>
```
Gets the iterator
#### Returns
`Traversable<string,Cake\Http\Cookie\CookieInterface>`
### has() public
```
has(string $name): bool
```
Check if a cookie with the given name exists
#### Parameters
`string` $name The cookie name to check.
#### Returns
`bool`
### remove() public
```
remove(string $name): static
```
Create a new collection with all cookies matching $name removed.
If the cookie is not in the collection, this method will do nothing.
#### Parameters
`string` $name The name of the cookie to remove.
#### Returns
`static`
### removeExpiredCookies() protected
```
removeExpiredCookies(string $host, string $path): void
```
Remove expired cookies from the collection.
#### Parameters
`string` $host The host to check for expired cookies on.
`string` $path The path to check for expired cookies on.
#### Returns
`void`
Property Detail
---------------
### $cookies protected
Cookie objects
#### Type
`arrayCake\Http\Cookie\CookieInterface>`
cakephp Class MissingControllerException Class MissingControllerException
=================================
Missing Controller exception - used when a controller cannot be found.
**Namespace:** [Cake\Http\Exception](namespace-cake.http.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Namespace Command Namespace Command
=================
### Classes
* ##### [CacheClearCommand](class-cake.command.cacheclearcommand)
CacheClear command.
* ##### [CacheClearallCommand](class-cake.command.cacheclearallcommand)
CacheClearall command.
* ##### [CacheListCommand](class-cake.command.cachelistcommand)
CacheList command.
* ##### [Command](class-cake.command.command)
Base class for commands using the full stack CakePHP Framework.
* ##### [CompletionCommand](class-cake.command.completioncommand)
Provide command completion shells such as bash.
* ##### [I18nCommand](class-cake.command.i18ncommand)
Command for interactive I18N management.
* ##### [I18nExtractCommand](class-cake.command.i18nextractcommand)
Language string extractor
* ##### [I18nInitCommand](class-cake.command.i18ninitcommand)
Command for interactive I18N management.
* ##### [PluginAssetsCopyCommand](class-cake.command.pluginassetscopycommand)
Command for copying plugin assets to app's webroot.
* ##### [PluginAssetsRemoveCommand](class-cake.command.pluginassetsremovecommand)
Command for removing plugin assets from app's webroot.
* ##### [PluginAssetsSymlinkCommand](class-cake.command.pluginassetssymlinkcommand)
Command for symlinking / copying plugin assets to app's webroot.
* ##### [PluginLoadCommand](class-cake.command.pluginloadcommand)
Command for loading plugins.
* ##### [PluginLoadedCommand](class-cake.command.pluginloadedcommand)
Displays all currently loaded plugins.
* ##### [PluginUnloadCommand](class-cake.command.pluginunloadcommand)
Command for unloading plugins.
* ##### [RoutesCheckCommand](class-cake.command.routescheckcommand)
Provides interactive CLI tool for testing routes.
* ##### [RoutesCommand](class-cake.command.routescommand)
Provides interactive CLI tools for routing.
* ##### [RoutesGenerateCommand](class-cake.command.routesgeneratecommand)
Provides interactive CLI tools for URL generation
* ##### [SchemacacheBuildCommand](class-cake.command.schemacachebuildcommand)
Provides CLI tool for updating schema cache.
* ##### [SchemacacheClearCommand](class-cake.command.schemacacheclearcommand)
Provides CLI tool for clearing schema cache.
* ##### [ServerCommand](class-cake.command.servercommand)
built-in Server command
* ##### [VersionCommand](class-cake.command.versioncommand)
Print out the version of CakePHP in use.
### Traits
* ##### [PluginAssetsTrait](trait-cake.command.pluginassetstrait)
trait for symlinking / copying plugin assets to app's webroot.
cakephp Trait FileConfigTrait Trait FileConfigTrait
======================
Trait providing utility methods for file based config engines.
**Namespace:** [Cake\Core\Configure](namespace-cake.core.configure)
Property Summary
----------------
* [$\_path](#%24_path) protected `string` The path this engine finds files on.
Method Summary
--------------
* ##### [\_getFilePath()](#_getFilePath()) protected
Get file path
Method Detail
-------------
### \_getFilePath() protected
```
_getFilePath(string $key, bool $checkExists = false): string
```
Get file path
#### Parameters
`string` $key The identifier to write to. If the key has a . it will be treated as a plugin prefix.
`bool` $checkExists optional Whether to check if file exists. Defaults to false.
#### Returns
`string`
#### Throws
`Cake\Core\Exception\CakeException`
When files don't exist or when files contain '..' as this could lead to abusive reads. Property Detail
---------------
### $\_path protected
The path this engine finds files on.
#### Type
`string`
cakephp Namespace Exception Namespace Exception
===================
### Classes
* ##### [BadRequestException](class-cake.http.exception.badrequestexception)
Represents an HTTP 400 error.
* ##### [ConflictException](class-cake.http.exception.conflictexception)
Represents an HTTP 409 error.
* ##### [ForbiddenException](class-cake.http.exception.forbiddenexception)
Represents an HTTP 403 error.
* ##### [GoneException](class-cake.http.exception.goneexception)
Represents an HTTP 410 error.
* ##### [HttpException](class-cake.http.exception.httpexception)
Parent class for all the HTTP related exceptions in CakePHP. All HTTP status/error related exceptions should extend this class so catch blocks can be specifically typed.
* ##### [InternalErrorException](class-cake.http.exception.internalerrorexception)
Represents an HTTP 500 error.
* ##### [InvalidCsrfTokenException](class-cake.http.exception.invalidcsrftokenexception)
Represents an HTTP 403 error caused by an invalid CSRF token
* ##### [MethodNotAllowedException](class-cake.http.exception.methodnotallowedexception)
Represents an HTTP 405 error.
* ##### [MissingControllerException](class-cake.http.exception.missingcontrollerexception)
Missing Controller exception - used when a controller cannot be found.
* ##### [NotAcceptableException](class-cake.http.exception.notacceptableexception)
Represents an HTTP 406 error.
* ##### [NotFoundException](class-cake.http.exception.notfoundexception)
Represents an HTTP 404 error.
* ##### [NotImplementedException](class-cake.http.exception.notimplementedexception)
Not Implemented Exception - used when an API method is not implemented
* ##### [RedirectException](class-cake.http.exception.redirectexception)
An exception subclass used by routing and application code to trigger a redirect.
* ##### [ServiceUnavailableException](class-cake.http.exception.serviceunavailableexception)
Represents an HTTP 503 error.
* ##### [UnauthorizedException](class-cake.http.exception.unauthorizedexception)
Represents an HTTP 401 error.
* ##### [UnavailableForLegalReasonsException](class-cake.http.exception.unavailableforlegalreasonsexception)
Represents an HTTP 451 error.
cakephp Class RoutingMiddleware Class RoutingMiddleware
========================
Applies routing rules to the request and creates the controller instance if possible.
**Namespace:** [Cake\Routing\Middleware](namespace-cake.routing.middleware)
Constants
---------
* `string` **ROUTE\_COLLECTION\_CACHE\_KEY**
```
'routeCollection'
```
Key used to store the route collection in the cache engine
Property Summary
----------------
* [$app](#%24app) protected `Cake\Routing\RoutingApplicationInterface` The application that will have its routing hook invoked.
* [$cacheConfig](#%24cacheConfig) protected `string|null` The cache configuration name to use for route collection caching, null to disable caching
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [buildRouteCollection()](#buildRouteCollection()) protected
Check if route cache is enabled and use the configured Cache to 'remember' the route collection
* ##### [loadRoutes()](#loadRoutes()) protected
Trigger the application's routes() hook if the application exists and Router isn't initialized. Uses the routes cache if enabled via configuration param "Router.cache"
* ##### [prepareRouteCollection()](#prepareRouteCollection()) protected
Generate the route collection using the builder
* ##### [process()](#process()) public
Apply routing and update the request.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Routing\RoutingApplicationInterface $app, string|null $cacheConfig = null)
```
Constructor
#### Parameters
`Cake\Routing\RoutingApplicationInterface` $app The application instance that routes are defined on.
`string|null` $cacheConfig optional The cache config name to use or null to disable routes cache
### buildRouteCollection() protected
```
buildRouteCollection(): Cake\Routing\RouteCollection
```
Check if route cache is enabled and use the configured Cache to 'remember' the route collection
#### Returns
`Cake\Routing\RouteCollection`
### loadRoutes() protected
```
loadRoutes(): void
```
Trigger the application's routes() hook if the application exists and Router isn't initialized. Uses the routes cache if enabled via configuration param "Router.cache"
If the middleware is created without an Application, routes will be loaded via the automatic route loading that pre-dates the routes() hook.
#### Returns
`void`
### prepareRouteCollection() protected
```
prepareRouteCollection(): Cake\Routing\RouteCollection
```
Generate the route collection using the builder
#### Returns
`Cake\Routing\RouteCollection`
### process() public
```
process(ServerRequestInterface $request, RequestHandlerInterface $handler): Psr\Http\Message\ResponseInterface
```
Apply routing and update the request.
Any route/path specific middleware will be wrapped around $next and then the new middleware stack will be invoked.
#### Parameters
`ServerRequestInterface` $request The request.
`RequestHandlerInterface` $handler The request handler.
#### Returns
`Psr\Http\Message\ResponseInterface`
Property Detail
---------------
### $app protected
The application that will have its routing hook invoked.
#### Type
`Cake\Routing\RoutingApplicationInterface`
### $cacheConfig protected
The cache configuration name to use for route collection caching, null to disable caching
#### Type
`string|null`
cakephp Class HtmlFormatter Class HtmlFormatter
====================
A Debugger formatter for generating interactive styled HTML output.
**Namespace:** [Cake\Error\Debug](namespace-cake.error.debug)
Property Summary
----------------
* [$id](#%24id) protected `string` Random id so that HTML ids are not shared between dump outputs.
* [$outputHeader](#%24outputHeader) protected static `bool`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [dump()](#dump()) public
Convert a tree of NodeInterface objects into HTML
* ##### [dumpHeader()](#dumpHeader()) protected
Generate the CSS and Javascript for dumps
* ##### [environmentMatches()](#environmentMatches()) public static
Check if the current environment is not a CLI context
* ##### [export()](#export()) protected
Convert a tree of NodeInterface objects into HTML
* ##### [exportArray()](#exportArray()) protected
Export an array type object
* ##### [exportObject()](#exportObject()) protected
Handles object to string conversion.
* ##### [formatWrapper()](#formatWrapper()) public
Output a dump wrapper with location context.
* ##### [style()](#style()) protected
Style text with HTML class names
Method Detail
-------------
### \_\_construct() public
```
__construct()
```
Constructor.
### dump() public
```
dump(Cake\Error\Debug\NodeInterface $node): string
```
Convert a tree of NodeInterface objects into HTML
#### Parameters
`Cake\Error\Debug\NodeInterface` $node The node tree to dump.
#### Returns
`string`
### dumpHeader() protected
```
dumpHeader(): string
```
Generate the CSS and Javascript for dumps
Only output once per process as we don't need it more than once.
#### Returns
`string`
### environmentMatches() public static
```
environmentMatches(): bool
```
Check if the current environment is not a CLI context
#### Returns
`bool`
### export() protected
```
export(Cake\Error\Debug\NodeInterface $var, int $indent): string
```
Convert a tree of NodeInterface objects into HTML
#### Parameters
`Cake\Error\Debug\NodeInterface` $var The node tree to dump.
`int` $indent The current indentation level.
#### Returns
`string`
### exportArray() protected
```
exportArray(Cake\Error\Debug\ArrayNode $var, int $indent): string
```
Export an array type object
#### Parameters
`Cake\Error\Debug\ArrayNode` $var The array to export.
`int` $indent The current indentation level.
#### Returns
`string`
### exportObject() protected
```
exportObject(Cake\Error\Debug\ClassNodeCake\Error\Debug\ReferenceNode $var, int $indent): string
```
Handles object to string conversion.
#### Parameters
`Cake\Error\Debug\ClassNodeCake\Error\Debug\ReferenceNode` $var Object to convert.
`int` $indent The current indentation level.
#### Returns
`string`
#### See Also
\Cake\Error\Debugger::exportVar() ### formatWrapper() public
```
formatWrapper(string $contents, array $location): string
```
Output a dump wrapper with location context.
#### Parameters
`string` $contents `array` $location #### Returns
`string`
### style() protected
```
style(string $style, string $text): string
```
Style text with HTML class names
#### Parameters
`string` $style The style name to use.
`string` $text The text to style.
#### Returns
`string`
Property Detail
---------------
### $id protected
Random id so that HTML ids are not shared between dump outputs.
#### Type
`string`
### $outputHeader protected static
#### Type
`bool`
| programming_docs |
cakephp Class StubConsoleInput Class StubConsoleInput
=======================
Stub class used by the console integration harness.
This class enables input to be stubbed and have exceptions raised when no answer is available.
**Namespace:** [Cake\Console\TestSuite](namespace-cake.console.testsuite)
Property Summary
----------------
* [$\_canReadline](#%24_canReadline) protected `bool` Can this instance use readline? Two conditions must be met:
1. Readline support must be enabled.
2. Handle we are attached to must be stdin. Allows rich editing with arrow keys and history when inputting a string.
* [$\_input](#%24_input) protected `resource` Input value.
* [$currentIndex](#%24currentIndex) protected `int` Current message index
* [$replies](#%24replies) protected `array<string>` Reply values for ask() and askChoice()
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [dataAvailable()](#dataAvailable()) public
Check if data is available on stdin
* ##### [read()](#read()) public
Read a reply
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string> $replies)
```
Constructor
#### Parameters
`array<string>` $replies A list of replies for read()
### dataAvailable() public
```
dataAvailable(int $timeout = 0): bool
```
Check if data is available on stdin
#### Parameters
`int` $timeout optional An optional time to wait for data
#### Returns
`bool`
### read() public
```
read(): string
```
Read a reply
#### Returns
`string`
Property Detail
---------------
### $\_canReadline protected
Can this instance use readline? Two conditions must be met:
1. Readline support must be enabled.
2. Handle we are attached to must be stdin. Allows rich editing with arrow keys and history when inputting a string.
#### Type
`bool`
### $\_input protected
Input value.
#### Type
`resource`
### $currentIndex protected
Current message index
#### Type
`int`
### $replies protected
Reply values for ask() and askChoice()
#### Type
`array<string>`
cakephp Class ResultSetDecorator Class ResultSetDecorator
=========================
Generic ResultSet decorator. This will make any traversable object appear to be a database result
**Namespace:** [Cake\Datasource](namespace-cake.datasource)
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor. You can provide an array or any traversable object
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_serialize()](#__serialize()) public
Returns an array for serializing this of this object.
* ##### [\_\_unserialize()](#__unserialize()) public
Rebuilds the Collection instance.
* ##### [\_createMatcherFilter()](#_createMatcherFilter()) protected
Returns a callable that receives a value and will return whether it matches certain condition.
* ##### [\_extract()](#_extract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
* ##### [\_propertyExtractor()](#_propertyExtractor()) protected
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
* ##### [\_simpleExtract()](#_simpleExtract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path
* ##### [append()](#append()) public
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
* ##### [appendItem()](#appendItem()) public
Append a single item creating a new collection.
* ##### [avg()](#avg()) public
Returns the average of all the values extracted with $path or of this collection.
* ##### [buffered()](#buffered()) public
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
* ##### [cartesianProduct()](#cartesianProduct()) public
Create a new collection that is the cartesian product of the current collection
* ##### [chunk()](#chunk()) public
Breaks the collection into smaller arrays of the given size.
* ##### [chunkWithKeys()](#chunkWithKeys()) public
Breaks the collection into smaller arrays of the given size.
* ##### [combine()](#combine()) public
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
* ##### [compile()](#compile()) public
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
* ##### [contains()](#contains()) public
Returns true if $value is present in this collection. Comparisons are made both by value and type.
* ##### [count()](#count()) public
Make this object countable.
* ##### [countBy()](#countBy()) public
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
* ##### [countKeys()](#countKeys()) public
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
* ##### [each()](#each()) public
Applies a callback to the elements in this collection.
* ##### [every()](#every()) public
Returns true if all values in this collection pass the truth test provided in the callback.
* ##### [extract()](#extract()) public
Returns a new collection containing the column or property value found in each of the elements.
* ##### [filter()](#filter()) public
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
* ##### [first()](#first()) public
Returns the first result in this collection
* ##### [firstMatch()](#firstMatch()) public
Returns the first result matching all the key-value pairs listed in conditions.
* ##### [groupBy()](#groupBy()) public
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
* ##### [indexBy()](#indexBy()) public
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
* ##### [insert()](#insert()) public
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
* ##### [isEmpty()](#isEmpty()) public
Returns whether there are elements in this collection
* ##### [jsonSerialize()](#jsonSerialize()) public
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
* ##### [last()](#last()) public
Returns the last result in this collection
* ##### [lazy()](#lazy()) public
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
* ##### [listNested()](#listNested()) public
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
* ##### [map()](#map()) public
Returns another collection after modifying each of the values in this one using the provided callable.
* ##### [match()](#match()) public
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
* ##### [max()](#max()) public
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [median()](#median()) public
Returns the median of all the values extracted with $path or of this collection.
* ##### [min()](#min()) public
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [nest()](#nest()) public
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
* ##### [newCollection()](#newCollection()) protected
Returns a new collection.
* ##### [optimizeUnwrap()](#optimizeUnwrap()) protected
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
* ##### [prepend()](#prepend()) public
Prepend a set of items to a collection creating a new collection
* ##### [prependItem()](#prependItem()) public
Prepend a single item creating a new collection.
* ##### [reduce()](#reduce()) public
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
* ##### [reject()](#reject()) public
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
* ##### [sample()](#sample()) public
Returns a new collection with maximum $size random elements from this collection
* ##### [serialize()](#serialize()) public
Returns a string representation of this object that can be used to reconstruct it
* ##### [shuffle()](#shuffle()) public
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
* ##### [skip()](#skip()) public
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
* ##### [some()](#some()) public
Returns true if any of the values in this collection pass the truth test provided in the callback.
* ##### [sortBy()](#sortBy()) public
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
* ##### [stopWhen()](#stopWhen()) public
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
* ##### [sumOf()](#sumOf()) public
Returns the total sum of all the values extracted with $matcher or of this collection.
* ##### [take()](#take()) public
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
* ##### [takeLast()](#takeLast()) public
Returns the last N elements of a collection
* ##### [through()](#through()) public
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
* ##### [toArray()](#toArray()) public
Returns an array representation of the results
* ##### [toList()](#toList()) public
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
* ##### [transpose()](#transpose()) public
Transpose rows and columns into columns and rows
* ##### [unfold()](#unfold()) public
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
* ##### [unserialize()](#unserialize()) public
Unserializes the passed string and rebuilds the Collection instance
* ##### [unwrap()](#unwrap()) public
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
* ##### [zip()](#zip()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
* ##### [zipWith()](#zipWith()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
Method Detail
-------------
### \_\_construct() public
```
__construct(iterable $items)
```
Constructor. You can provide an array or any traversable object
#### Parameters
`iterable` $items Items.
#### Throws
`InvalidArgumentException`
If passed incorrect type for items. ### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_serialize() public
```
__serialize(): array
```
Returns an array for serializing this of this object.
#### Returns
`array`
### \_\_unserialize() public
```
__unserialize(array $data): void
```
Rebuilds the Collection instance.
#### Parameters
`array` $data Data array.
#### Returns
`void`
### \_createMatcherFilter() protected
```
_createMatcherFilter(array $conditions): Closure
```
Returns a callable that receives a value and will return whether it matches certain condition.
#### Parameters
`array` $conditions A key-value list of conditions to match where the key is the property path to get from the current item and the value is the value to be compared the item with.
#### Returns
`Closure`
### \_extract() protected
```
_extract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### \_propertyExtractor() protected
```
_propertyExtractor(callable|string $path): callable
```
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
#### Parameters
`callable|string` $path A dot separated path of column to follow so that the final one can be returned or a callable that will take care of doing that.
#### Returns
`callable`
### \_simpleExtract() protected
```
_simpleExtract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### append() public
```
append(iterable $items): self
```
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
#### Parameters
`iterable` $items Items list.
#### Returns
`self`
### appendItem() public
```
appendItem(mixed $item, mixed $key = null): self
```
Append a single item creating a new collection.
#### Parameters
`mixed` $item The item to append.
`mixed` $key optional The key to append the item with. If null a key will be generated.
#### Returns
`self`
### avg() public
```
avg(callable|string|null $path = null): float|int|null
```
Returns the average of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->avg('invoice.total');
// Total: 150
$total = (new Collection([1, 2, 3]))->avg();
// Total: 2
```
The average of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional The property name to sum or a function If no value is passed, an identity function will be used. that will return the value of the property to sum.
#### Returns
`float|int|null`
### buffered() public
```
buffered(): self
```
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
This can also be used to make any non-rewindable iterator rewindable.
#### Returns
`self`
### cartesianProduct() public
```
cartesianProduct(callable|null $operation = null, callable|null $filter = null): self
```
Create a new collection that is the cartesian product of the current collection
In order to create a carteisan product a collection must contain a single dimension of data.
### Example
```
$collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
$result = $collection->cartesianProduct()->toArray();
$expected = [
['A', 1],
['A', 2],
['A', 3],
['B', 1],
['B', 2],
['B', 3],
['C', 1],
['C', 2],
['C', 3],
];
```
#### Parameters
`callable|null` $operation optional A callable that allows you to customize the product result.
`callable|null` $filter optional A filtering callback that must return true for a result to be part of the final results.
#### Returns
`self`
### chunk() public
```
chunk(int $chunkSize): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
$chunked = (new Collection($items))->chunk(3)->toList();
// Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
```
#### Parameters
`int` $chunkSize The maximum size for each chunk
#### Returns
`self`
### chunkWithKeys() public
```
chunkWithKeys(int $chunkSize, bool $keepKeys = true): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
$chunked = (new Collection($items))->chunkWithKeys(3)->toList();
// Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
```
#### Parameters
`int` $chunkSize The maximum size for each chunk
`bool` $keepKeys optional If the keys of the array should be kept
#### Returns
`self`
### combine() public
```
combine(callable|string $keyPath, callable|string $valuePath, callable|string|null $groupPath = null): self
```
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
### Examples:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent' => 'a'],
['id' => 2, 'name' => 'bar', 'parent' => 'b'],
['id' => 3, 'name' => 'baz', 'parent' => 'a'],
];
$combined = (new Collection($items))->combine('id', 'name');
// Result will look like this when converted to array
[
1 => 'foo',
2 => 'bar',
3 => 'baz',
];
$combined = (new Collection($items))->combine('id', 'name', 'parent');
// Result will look like this when converted to array
[
'a' => [1 => 'foo', 3 => 'baz'],
'b' => [2 => 'bar']
];
```
#### Parameters
`callable|string` $keyPath the column name path to use for indexing or a function returning the indexing key out of the provided element
`callable|string` $valuePath the column name path to use as the array value or a function returning the value out of the provided element
`callable|string|null` $groupPath optional the column name path to use as the parent grouping key or a function returning the key out of the provided element
#### Returns
`self`
### compile() public
```
compile(bool $keepKeys = true): self
```
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
A common use case is to re-use the same variable for calculating different data. In those cases it may be helpful and more performant to first compile a collection and then apply more operations to it.
### Example:
```
$collection->map($mapper)->sortBy('age')->extract('name');
$compiled = $collection->compile();
$isJohnHere = $compiled->some($johnMatcher);
$allButJohn = $compiled->filter($johnMatcher);
```
In the above example, had the collection not been compiled before, the iterations for `map`, `sortBy` and `extract` would've been executed twice: once for getting `$isJohnHere` and once for `$allButJohn`
You can think of this method as a way to create save points for complex calculations in a collection.
#### Parameters
`bool` $keepKeys optional Whether to use the keys returned by this collection as the array keys. Keep in mind that it is valid for iterators to return the same key for different elements, setting this value to false can help getting all items if keys are not important in the result.
#### Returns
`self`
### contains() public
```
contains(mixed $value): bool
```
Returns true if $value is present in this collection. Comparisons are made both by value and type.
#### Parameters
`mixed` $value The value to check for
#### Returns
`bool`
### count() public
```
count(): int
```
Make this object countable.
Part of the Countable interface. Calling this method will convert the underlying traversable object into an array and get the count of the underlying data.
#### Returns
`int`
### countBy() public
```
countBy(callable|string $path): self
```
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->countBy('parent_id');
// Or
$group = (new Collection($items))->countBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => 2,
11 => 1
];
```
#### Parameters
`callable|string` $path The column name to use for indexing or callback that returns the value. or a function returning the indexing key out of the provided element
#### Returns
`self`
### countKeys() public
```
countKeys(): int
```
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
This method comes with a number of caveats. Please refer to `CollectionInterface::count()` for details.
#### Returns
`int`
#### See Also
\Cake\Collection\CollectionInterface::count() ### each() public
```
each(callable $callback): $this
```
Applies a callback to the elements in this collection.
### Example:
```
$collection = (new Collection($items))->each(function ($value, $key) {
echo "Element $key: $value";
});
```
#### Parameters
`callable` $callback Callback to run for each element in collection.
#### Returns
`$this`
### every() public
```
every(callable $callback): bool
```
Returns true if all values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$overTwentyOne = (new Collection([24, 45, 60, 15]))->every(function ($value, $key) {
return $value > 21;
});
```
Empty collections always return true.
#### Parameters
`callable` $callback a callback function
#### Returns
`bool`
### extract() public
```
extract(callable|string $path): self
```
Returns a new collection containing the column or property value found in each of the elements.
The matcher can be a string with a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection, that position is filled with null.
### Example:
Extract the user name for all comments in the array:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->extract('comment.user.name');
// Result will look like this when converted to array
['Mark', 'Renan']
```
It is also possible to extract a flattened collection out of nested properties
```
$items = [
['comment' => ['votes' => [['value' => 1], ['value' => 2], ['value' => 3]]],
['comment' => ['votes' => [['value' => 4]]
];
$extracted = (new Collection($items))->extract('comment.votes.{*}.value');
// Result will contain
[1, 2, 3, 4]
```
#### Parameters
`callable|string` $path A dot separated path of column to follow so that the final one can be returned or a callable that will take care of doing that.
#### Returns
`self`
### filter() public
```
filter(callable|null $callback = null): self
```
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering odd numbers in an array, at the end only the value 2 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->filter(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable|null` $callback optional the method that will receive each of the elements and returns true whether they should be in the resulting collection. If left null, a callback that filters out falsey values will be used.
#### Returns
`self`
### first() public
```
first(): mixed
```
Returns the first result in this collection
#### Returns
`mixed`
### firstMatch() public
```
firstMatch(array $conditions): mixed
```
Returns the first result matching all the key-value pairs listed in conditions.
#### Parameters
`array` $conditions a key-value list of conditions where the key is a property path as accepted by `Collection::extract`, and the value the condition against with each element will be matched
#### Returns
`mixed`
#### See Also
\Cake\Collection\CollectionInterface::match() ### groupBy() public
```
groupBy(callable|string $path): self
```
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->groupBy('parent_id');
// Or
$group = (new Collection($items))->groupBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
],
11 => [
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
]
];
```
#### Parameters
`callable|string` $path The column name to use for grouping or callback that returns the value. or a function returning the grouping key out of the provided element
#### Returns
`self`
### indexBy() public
```
indexBy(callable|string $path): self
```
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo'],
['id' => 2, 'name' => 'bar'],
['id' => 3, 'name' => 'baz'],
];
$indexed = (new Collection($items))->indexBy('id');
// Or
$indexed = (new Collection($items))->indexBy(function ($e) {
return $e['id'];
});
// Result will look like this when converted to array
[
1 => ['id' => 1, 'name' => 'foo'],
3 => ['id' => 3, 'name' => 'baz'],
2 => ['id' => 2, 'name' => 'bar'],
];
```
#### Parameters
`callable|string` $path The column name to use for indexing or callback that returns the value. or a function returning the indexing key out of the provided element
#### Returns
`self`
### insert() public
```
insert(string $path, mixed $values): self
```
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
The $path can be a string with a property name or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection as part of the path, the element will be kept unchanged.
### Example:
Insert ages into a collection containing users:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
];
$ages = [25, 28];
$inserted = (new Collection($items))->insert('comment.user.age', $ages);
// Result will look like this when converted to array
[
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
];
```
#### Parameters
`string` $path a dot separated string symbolizing the path to follow inside the hierarchy of each value so that the value can be inserted
`mixed` $values The values to be inserted at the specified path, values are matched with the elements in this collection by its positional index.
#### Returns
`self`
### isEmpty() public
```
isEmpty(): bool
```
Returns whether there are elements in this collection
### Example:
```
$items [1, 2, 3];
(new Collection($items))->isEmpty(); // false
```
```
(new Collection([]))->isEmpty(); // true
```
#### Returns
`bool`
### jsonSerialize() public
```
jsonSerialize(): array
```
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
Part of JsonSerializable interface.
#### Returns
`array`
### last() public
```
last(): mixed
```
Returns the last result in this collection
#### Returns
`mixed`
### lazy() public
```
lazy(): self
```
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
A lazy collection can only be iterated once. A second attempt results in an error.
#### Returns
`self`
### listNested() public
```
listNested(string|int $order = 'desc', callable|string $nestingKey = 'children'): self
```
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
By default all elements in the tree following a Depth First Search will be returned, that is, elements from the top parent to the leaves for each branch.
It is possible to return all elements from bottom to top using a Breadth First Search approach by passing the '$dir' parameter with 'asc'. That is, it will return all elements for the same tree depth first and from bottom to top.
Finally, you can specify to only get a collection with the leaf nodes in the tree structure. You do so by passing 'leaves' in the first argument.
The possible values for the first argument are aliases for the following constants and it is valid to pass those instead of the alias:
* desc: RecursiveIteratorIterator::SELF\_FIRST
* asc: RecursiveIteratorIterator::CHILD\_FIRST
* leaves: RecursiveIteratorIterator::LEAVES\_ONLY
### Example:
```
$collection = new Collection([
['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
['id' => 4, 'children' => [['id' => 5]]]
]);
$flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
```
#### Parameters
`string|int` $order optional The order in which to return the elements
`callable|string` $nestingKey optional The key name under which children are nested or a callable function that will return the children list
#### Returns
`self`
### map() public
```
map(callable $callback): self
```
Returns another collection after modifying each of the values in this one using the provided callable.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Getting a collection of booleans where true indicates if a person is female:
```
$collection = (new Collection($people))->map(function ($person, $key) {
return $person->gender === 'female';
});
```
#### Parameters
`callable` $callback the method that will receive each of the elements and returns the new value for the key that is being iterated
#### Returns
`self`
### match() public
```
match(array $conditions): self
```
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
### Example:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->match(['user.name' => 'Renan']);
// Result will look like this when converted to array
[
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
]
```
#### Parameters
`array` $conditions a key-value list of conditions where the key is a property path as accepted by `Collection::extract, and the value the condition against with each element will be matched
#### Returns
`self`
### max() public
```
max(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$max = $collection->max('age');
$max = $collection->max('user.salary');
$max = $collection->max(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $max->name;
```
#### Parameters
`callable|string` $path The column name to use for sorting or callback that returns the value.
`int` $sort optional The sort type, one of SORT\_STRING SORT\_NUMERIC or SORT\_NATURAL
#### Returns
`mixed`
#### See Also
\Cake\Collection\CollectionInterface::sortBy() ### median() public
```
median(callable|string|null $path = null): float|int|null
```
Returns the median of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 400]],
['invoice' => ['total' => 500]]
['invoice' => ['total' => 100]]
['invoice' => ['total' => 333]]
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->median('invoice.total');
// Total: 333
$total = (new Collection([1, 2, 3, 4]))->median();
// Total: 2.5
```
The median of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional The property name to sum or a function If no value is passed, an identity function will be used. that will return the value of the property to sum.
#### Returns
`float|int|null`
### min() public
```
min(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$min = $collection->min('age');
$min = $collection->min('user.salary');
$min = $collection->min(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $min->name;
```
#### Parameters
`callable|string` $path The column name to use for sorting or callback that returns the value.
`int` $sort optional The sort type, one of SORT\_STRING SORT\_NUMERIC or SORT\_NATURAL
#### Returns
`mixed`
#### See Also
\Cake\Collection\CollectionInterface::sortBy() ### nest() public
```
nest(callable|string $idPath, callable|string $parentPath, string $nestingKey = 'children'): self
```
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
#### Parameters
`callable|string` $idPath the column name path to use for determining whether an element is parent of another
`callable|string` $parentPath the column name path to use for determining whether an element is child of another
`string` $nestingKey optional The key name under which children are nested
#### Returns
`self`
### newCollection() protected
```
newCollection(mixed ...$args): Cake\Collection\CollectionInterface
```
Returns a new collection.
Allows classes which use this trait to determine their own type of returned collection interface
#### Parameters
`mixed` ...$args Constructor arguments.
#### Returns
`Cake\Collection\CollectionInterface`
### optimizeUnwrap() protected
```
optimizeUnwrap(): iterable
```
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
#### Returns
`iterable`
### prepend() public
```
prepend(mixed $items): self
```
Prepend a set of items to a collection creating a new collection
#### Parameters
`mixed` $items The items to prepend.
#### Returns
`self`
### prependItem() public
```
prependItem(mixed $item, mixed $key = null): self
```
Prepend a single item creating a new collection.
#### Parameters
`mixed` $item The item to prepend.
`mixed` $key optional The key to prepend the item with. If null a key will be generated.
#### Returns
`self`
### reduce() public
```
reduce(callable $callback, mixed $initial = null): mixed
```
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
#### Parameters
`callable` $callback The callback function to be called
`mixed` $initial optional The state of reduction
#### Returns
`mixed`
### reject() public
```
reject(callable $callback): self
```
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering even numbers in an array, at the end only values 1 and 3 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->reject(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable` $callback the method that will receive each of the elements and returns true whether they should be out of the resulting collection.
#### Returns
`self`
### sample() public
```
sample(int $length = 10): self
```
Returns a new collection with maximum $size random elements from this collection
#### Parameters
`int` $length optional the maximum number of elements to randomly take from this collection
#### Returns
`self`
### serialize() public
```
serialize(): string
```
Returns a string representation of this object that can be used to reconstruct it
#### Returns
`string`
### shuffle() public
```
shuffle(): self
```
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
#### Returns
`self`
### skip() public
```
skip(int $length): self
```
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
#### Parameters
`int` $length The number of elements to skip.
#### Returns
`self`
### some() public
```
some(callable $callback): bool
```
Returns true if any of the values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$hasYoungPeople = (new Collection([24, 45, 15]))->some(function ($value, $key) {
return $value < 21;
});
```
#### Parameters
`callable` $callback a callback function
#### Returns
`bool`
### sortBy() public
```
sortBy(callable|string $path, int $order = SORT_DESC, int $sort = \SORT_NUMERIC): self
```
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
The callback will receive as its first argument each of the elements in $items, the value returned by the callback will be used as the value for sorting such element. Please note that the callback function could be called more than once per element.
### Example:
```
$items = $collection->sortBy(function ($user) {
return $user->age;
});
// alternatively
$items = $collection->sortBy('age');
// or use a property path
$items = $collection->sortBy('department.name');
// output all user name order by their age in descending order
foreach ($items as $user) {
echo $user->name;
}
```
#### Parameters
`callable|string` $path The column name to use for sorting or callback that returns the value.
`int` $order optional The sort order, either SORT\_DESC or SORT\_ASC
`int` $sort optional The sort type, one of SORT\_STRING SORT\_NUMERIC or SORT\_NATURAL
#### Returns
`self`
### stopWhen() public
```
stopWhen(callable|array $condition): self
```
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
This is handy for dealing with infinite iterators or any generator that could start returning invalid elements at a certain point. For example, when reading lines from a file stream you may want to stop the iteration after a certain value is reached.
### Example:
Get an array of lines in a CSV file until the timestamp column is less than a date
```
$lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
return (new DateTime($value))->format('Y') < 2012;
})
->toArray();
```
Get elements until the first unapproved message is found:
```
$comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
```
#### Parameters
`callable|array` $condition the method that will receive each of the elements and returns true when the iteration should be stopped. If an array, it will be interpreted as a key-value list of conditions where the key is a property path as accepted by `Collection::extract`, and the value the condition against with each element will be matched.
#### Returns
`self`
### sumOf() public
```
sumOf(callable|string|null $path = null): float|int
```
Returns the total sum of all the values extracted with $matcher or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->sumOf('invoice.total');
// Total: 300
$total = (new Collection([1, 2, 3]))->sumOf();
// Total: 6
```
#### Parameters
`callable|string|null` $path optional The property name to sum or a function If no value is passed, an identity function will be used. that will return the value of the property to sum.
#### Returns
`float|int`
### take() public
```
take(int $length = 1, int $offset = 0): self
```
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
#### Parameters
`int` $length optional the maximum number of elements to take from this collection
`int` $offset optional A positional offset from where to take the elements
#### Returns
`self`
### takeLast() public
```
takeLast(int $length): self
```
Returns the last N elements of a collection
### Example:
```
$items = [1, 2, 3, 4, 5];
$last = (new Collection($items))->takeLast(3);
// Result will look like this when converted to array
[3, 4, 5];
```
#### Parameters
`int` $length The number of elements at the end of the collection
#### Returns
`self`
### through() public
```
through(callable $callback): self
```
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
### Example:
```
$items = [1, 2, 3];
$decorated = (new Collection($items))->through(function ($collection) {
return new MyCustomCollection($collection);
});
```
#### Parameters
`callable` $callback A callable function that will receive this collection as first argument.
#### Returns
`self`
### toArray() public
```
toArray(bool $keepKeys = true): array
```
Returns an array representation of the results
#### Parameters
`bool` $keepKeys optional Whether to use the keys returned by this collection as the array keys. Keep in mind that it is valid for iterators to return the same key for different elements, setting this value to false can help getting all items if keys are not important in the result.
#### Returns
`array`
### toList() public
```
toList(): array
```
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
#### Returns
`array`
### transpose() public
```
transpose(): self
```
Transpose rows and columns into columns and rows
### Example:
```
$items = [
['Products', '2012', '2013', '2014'],
['Product A', '200', '100', '50'],
['Product B', '300', '200', '100'],
['Product C', '400', '300', '200'],
]
$transpose = (new Collection($items))->transpose()->toList();
// Returns
// [
// ['Products', 'Product A', 'Product B', 'Product C'],
// ['2012', '200', '300', '400'],
// ['2013', '100', '200', '300'],
// ['2014', '50', '100', '200'],
// ]
```
#### Returns
`self`
### unfold() public
```
unfold(callable|null $callback = null): self
```
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
The transformer function will receive the value and the key for each of the items in the collection, in that order, and it must return an array or a Traversable object that can be concatenated to the final result.
If no transformer function is passed, an "identity" function will be used. This is useful when each of the elements in the source collection are lists of items to be appended one after another.
### Example:
```
$items [[1, 2, 3], [4, 5]];
$unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
```
Using a transformer
```
$items [1, 2, 3];
$allItems = (new Collection($items))->unfold(function ($page) {
return $service->fetchPage($page)->toArray();
});
```
#### Parameters
`callable|null` $callback optional A callable function that will receive each of the items in the collection and should return an array or Traversable object
#### Returns
`self`
### unserialize() public
```
unserialize(string $collection): void
```
Unserializes the passed string and rebuilds the Collection instance
#### Parameters
`string` $collection The serialized collection
#### Returns
`void`
### unwrap() public
```
unwrap(): Traversable
```
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
#### Returns
`Traversable`
### zip() public
```
zip(iterable $items): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
### Example:
```
$collection = new Collection([1, 2]);
$collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
```
#### Parameters
`iterable` $items The collections to zip.
#### Returns
`self`
### zipWith() public
```
zipWith(iterable $items, callable $callback): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
The resulting element will be the return value of the $callable function.
### Example:
```
$collection = new Collection([1, 2]);
$zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
return array_sum($args);
});
$zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
```
#### Parameters
`iterable` $items The collections to zip.
`callable` $callback The function to use for zipping the elements together.
#### Returns
`self`
| programming_docs |
cakephp Namespace Exception Namespace Exception
===================
### Classes
* ##### [AuthSecurityException](class-cake.controller.exception.authsecurityexception)
Auth Security exception - used when SecurityComponent detects any issue with the current request
* ##### [InvalidParameterException](class-cake.controller.exception.invalidparameterexception)
Used when a passed parameter or action parameter type declaration is missing or invalid.
* ##### [MissingActionException](class-cake.controller.exception.missingactionexception)
Missing Action exception - used when a controller action cannot be found, or when the controller's isAction() method returns false.
* ##### [MissingComponentException](class-cake.controller.exception.missingcomponentexception)
Used when a component cannot be found.
* ##### [SecurityException](class-cake.controller.exception.securityexception)
Security exception - used when SecurityComponent detects any issue with the current request
cakephp Interface CollectionInterface Interface CollectionInterface
==============================
Describes the methods a Collection should implement. A collection is an immutable list of elements exposing a number of traversing and extracting method for generating other collections.
**Namespace:** [Cake\Collection](namespace-cake.collection)
Method Summary
--------------
* ##### [append()](#append()) public
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
* ##### [appendItem()](#appendItem()) public
Append a single item creating a new collection.
* ##### [avg()](#avg()) public
Returns the average of all the values extracted with $path or of this collection.
* ##### [buffered()](#buffered()) public
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
* ##### [cartesianProduct()](#cartesianProduct()) public
Create a new collection that is the cartesian product of the current collection
* ##### [chunk()](#chunk()) public
Breaks the collection into smaller arrays of the given size.
* ##### [chunkWithKeys()](#chunkWithKeys()) public
Breaks the collection into smaller arrays of the given size.
* ##### [combine()](#combine()) public
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
* ##### [compile()](#compile()) public
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
* ##### [contains()](#contains()) public
Returns true if $value is present in this collection. Comparisons are made both by value and type.
* ##### [count()](#count()) public
Returns the amount of elements in the collection.
* ##### [countBy()](#countBy()) public
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
* ##### [countKeys()](#countKeys()) public
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
* ##### [each()](#each()) public
Applies a callback to the elements in this collection.
* ##### [every()](#every()) public
Returns true if all values in this collection pass the truth test provided in the callback.
* ##### [extract()](#extract()) public
Returns a new collection containing the column or property value found in each of the elements.
* ##### [filter()](#filter()) public
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
* ##### [first()](#first()) public
Returns the first result in this collection
* ##### [firstMatch()](#firstMatch()) public
Returns the first result matching all the key-value pairs listed in conditions.
* ##### [groupBy()](#groupBy()) public
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
* ##### [indexBy()](#indexBy()) public
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
* ##### [insert()](#insert()) public
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
* ##### [isEmpty()](#isEmpty()) public
Returns whether there are elements in this collection
* ##### [jsonSerialize()](#jsonSerialize()) public
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
* ##### [last()](#last()) public
Returns the last result in this collection
* ##### [lazy()](#lazy()) public
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
* ##### [listNested()](#listNested()) public
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
* ##### [map()](#map()) public
Returns another collection after modifying each of the values in this one using the provided callable.
* ##### [match()](#match()) public
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
* ##### [max()](#max()) public
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [median()](#median()) public
Returns the median of all the values extracted with $path or of this collection.
* ##### [min()](#min()) public
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [nest()](#nest()) public
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
* ##### [prepend()](#prepend()) public
Prepend a set of items to a collection creating a new collection
* ##### [prependItem()](#prependItem()) public
Prepend a single item creating a new collection.
* ##### [reduce()](#reduce()) public
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
* ##### [reject()](#reject()) public
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
* ##### [sample()](#sample()) public
Returns a new collection with maximum $size random elements from this collection
* ##### [shuffle()](#shuffle()) public
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
* ##### [skip()](#skip()) public
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
* ##### [some()](#some()) public
Returns true if any of the values in this collection pass the truth test provided in the callback.
* ##### [sortBy()](#sortBy()) public
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
* ##### [stopWhen()](#stopWhen()) public
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
* ##### [sumOf()](#sumOf()) public
Returns the total sum of all the values extracted with $matcher or of this collection.
* ##### [take()](#take()) public
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
* ##### [takeLast()](#takeLast()) public
Returns the last N elements of a collection
* ##### [through()](#through()) public
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
* ##### [toArray()](#toArray()) public
Returns an array representation of the results
* ##### [toList()](#toList()) public
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
* ##### [transpose()](#transpose()) public
Transpose rows and columns into columns and rows
* ##### [unfold()](#unfold()) public
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
* ##### [unwrap()](#unwrap()) public
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
* ##### [zip()](#zip()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
* ##### [zipWith()](#zipWith()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
Method Detail
-------------
### append() public
```
append(iterable $items): self
```
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
#### Parameters
`iterable` $items Items list.
#### Returns
`self`
### appendItem() public
```
appendItem(mixed $item, mixed $key = null): self
```
Append a single item creating a new collection.
#### Parameters
`mixed` $item The item to append.
`mixed` $key optional The key to append the item with. If null a key will be generated.
#### Returns
`self`
### avg() public
```
avg(callable|string|null $path = null): float|int|null
```
Returns the average of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->avg('invoice.total');
// Total: 150
$total = (new Collection([1, 2, 3]))->avg();
// Total: 2
```
The average of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional The property name to sum or a function If no value is passed, an identity function will be used. that will return the value of the property to sum.
#### Returns
`float|int|null`
### buffered() public
```
buffered(): self
```
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
This can also be used to make any non-rewindable iterator rewindable.
#### Returns
`self`
### cartesianProduct() public
```
cartesianProduct(callable|null $operation = null, callable|null $filter = null): self
```
Create a new collection that is the cartesian product of the current collection
In order to create a carteisan product a collection must contain a single dimension of data.
### Example
```
$collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
$result = $collection->cartesianProduct()->toArray();
$expected = [
['A', 1],
['A', 2],
['A', 3],
['B', 1],
['B', 2],
['B', 3],
['C', 1],
['C', 2],
['C', 3],
];
```
#### Parameters
`callable|null` $operation optional A callable that allows you to customize the product result.
`callable|null` $filter optional A filtering callback that must return true for a result to be part of the final results.
#### Returns
`self`
### chunk() public
```
chunk(int $chunkSize): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
$chunked = (new Collection($items))->chunk(3)->toList();
// Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
```
#### Parameters
`int` $chunkSize The maximum size for each chunk
#### Returns
`self`
### chunkWithKeys() public
```
chunkWithKeys(int $chunkSize, bool $keepKeys = true): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
$chunked = (new Collection($items))->chunkWithKeys(3)->toList();
// Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
```
#### Parameters
`int` $chunkSize The maximum size for each chunk
`bool` $keepKeys optional If the keys of the array should be kept
#### Returns
`self`
### combine() public
```
combine(callable|string $keyPath, callable|string $valuePath, callable|string|null $groupPath = null): self
```
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
### Examples:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent' => 'a'],
['id' => 2, 'name' => 'bar', 'parent' => 'b'],
['id' => 3, 'name' => 'baz', 'parent' => 'a'],
];
$combined = (new Collection($items))->combine('id', 'name');
// Result will look like this when converted to array
[
1 => 'foo',
2 => 'bar',
3 => 'baz',
];
$combined = (new Collection($items))->combine('id', 'name', 'parent');
// Result will look like this when converted to array
[
'a' => [1 => 'foo', 3 => 'baz'],
'b' => [2 => 'bar']
];
```
#### Parameters
`callable|string` $keyPath the column name path to use for indexing or a function returning the indexing key out of the provided element
`callable|string` $valuePath the column name path to use as the array value or a function returning the value out of the provided element
`callable|string|null` $groupPath optional the column name path to use as the parent grouping key or a function returning the key out of the provided element
#### Returns
`self`
### compile() public
```
compile(bool $keepKeys = true): self
```
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
A common use case is to re-use the same variable for calculating different data. In those cases it may be helpful and more performant to first compile a collection and then apply more operations to it.
### Example:
```
$collection->map($mapper)->sortBy('age')->extract('name');
$compiled = $collection->compile();
$isJohnHere = $compiled->some($johnMatcher);
$allButJohn = $compiled->filter($johnMatcher);
```
In the above example, had the collection not been compiled before, the iterations for `map`, `sortBy` and `extract` would've been executed twice: once for getting `$isJohnHere` and once for `$allButJohn`
You can think of this method as a way to create save points for complex calculations in a collection.
#### Parameters
`bool` $keepKeys optional Whether to use the keys returned by this collection as the array keys. Keep in mind that it is valid for iterators to return the same key for different elements, setting this value to false can help getting all items if keys are not important in the result.
#### Returns
`self`
### contains() public
```
contains(mixed $value): bool
```
Returns true if $value is present in this collection. Comparisons are made both by value and type.
#### Parameters
`mixed` $value The value to check for
#### Returns
`bool`
### count() public
```
count(): int
```
Returns the amount of elements in the collection.
WARNINGS:
---------
### Will change the current position of the iterator:
Calling this method at the same time that you are iterating this collections, for example in a foreach, will result in undefined behavior. Avoid doing this.
### Consumes all elements for NoRewindIterator collections:
On certain type of collections, calling this method may render unusable afterwards. That is, you may not be able to get elements out of it, or to iterate on it anymore.
Specifically any collection wrapping a Generator (a function with a yield statement) or a unbuffered database cursor will not accept any other function calls after calling `count()` on it.
Create a new collection with `buffered()` method to overcome this problem.
### Can report more elements than unique keys:
Any collection constructed by appending collections together, or by having internal iterators returning duplicate keys, will report a larger amount of elements using this functions than the final amount of elements when converting the collections to a keyed array. This is because duplicate keys will be collapsed into a single one in the final array, whereas this count method is only concerned by the amount of elements after converting it to a plain list.
If you need the count of elements after taking the keys in consideration (the count of unique keys), you can call `countKeys()`
#### Returns
`int`
### countBy() public
```
countBy(callable|string $path): self
```
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->countBy('parent_id');
// Or
$group = (new Collection($items))->countBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => 2,
11 => 1
];
```
#### Parameters
`callable|string` $path The column name to use for indexing or callback that returns the value. or a function returning the indexing key out of the provided element
#### Returns
`self`
### countKeys() public
```
countKeys(): int
```
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
This method comes with a number of caveats. Please refer to `CollectionInterface::count()` for details.
#### Returns
`int`
#### See Also
\Cake\Collection\CollectionInterface::count() ### each() public
```
each(callable $callback): $this
```
Applies a callback to the elements in this collection.
### Example:
```
$collection = (new Collection($items))->each(function ($value, $key) {
echo "Element $key: $value";
});
```
#### Parameters
`callable` $callback Callback to run for each element in collection.
#### Returns
`$this`
### every() public
```
every(callable $callback): bool
```
Returns true if all values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$overTwentyOne = (new Collection([24, 45, 60, 15]))->every(function ($value, $key) {
return $value > 21;
});
```
Empty collections always return true.
#### Parameters
`callable` $callback a callback function
#### Returns
`bool`
### extract() public
```
extract(callable|string $path): self
```
Returns a new collection containing the column or property value found in each of the elements.
The matcher can be a string with a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection, that position is filled with null.
### Example:
Extract the user name for all comments in the array:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->extract('comment.user.name');
// Result will look like this when converted to array
['Mark', 'Renan']
```
It is also possible to extract a flattened collection out of nested properties
```
$items = [
['comment' => ['votes' => [['value' => 1], ['value' => 2], ['value' => 3]]],
['comment' => ['votes' => [['value' => 4]]
];
$extracted = (new Collection($items))->extract('comment.votes.{*}.value');
// Result will contain
[1, 2, 3, 4]
```
#### Parameters
`callable|string` $path A dot separated path of column to follow so that the final one can be returned or a callable that will take care of doing that.
#### Returns
`self`
### filter() public
```
filter(callable|null $callback = null): self
```
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering odd numbers in an array, at the end only the value 2 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->filter(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable|null` $callback optional the method that will receive each of the elements and returns true whether they should be in the resulting collection. If left null, a callback that filters out falsey values will be used.
#### Returns
`self`
### first() public
```
first(): mixed
```
Returns the first result in this collection
#### Returns
`mixed`
### firstMatch() public
```
firstMatch(array $conditions): mixed
```
Returns the first result matching all the key-value pairs listed in conditions.
#### Parameters
`array` $conditions a key-value list of conditions where the key is a property path as accepted by `Collection::extract`, and the value the condition against with each element will be matched
#### Returns
`mixed`
#### See Also
\Cake\Collection\CollectionInterface::match() ### groupBy() public
```
groupBy(callable|string $path): self
```
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->groupBy('parent_id');
// Or
$group = (new Collection($items))->groupBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
],
11 => [
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
]
];
```
#### Parameters
`callable|string` $path The column name to use for grouping or callback that returns the value. or a function returning the grouping key out of the provided element
#### Returns
`self`
### indexBy() public
```
indexBy(callable|string $path): self
```
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo'],
['id' => 2, 'name' => 'bar'],
['id' => 3, 'name' => 'baz'],
];
$indexed = (new Collection($items))->indexBy('id');
// Or
$indexed = (new Collection($items))->indexBy(function ($e) {
return $e['id'];
});
// Result will look like this when converted to array
[
1 => ['id' => 1, 'name' => 'foo'],
3 => ['id' => 3, 'name' => 'baz'],
2 => ['id' => 2, 'name' => 'bar'],
];
```
#### Parameters
`callable|string` $path The column name to use for indexing or callback that returns the value. or a function returning the indexing key out of the provided element
#### Returns
`self`
### insert() public
```
insert(string $path, mixed $values): self
```
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
The $path can be a string with a property name or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection as part of the path, the element will be kept unchanged.
### Example:
Insert ages into a collection containing users:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
];
$ages = [25, 28];
$inserted = (new Collection($items))->insert('comment.user.age', $ages);
// Result will look like this when converted to array
[
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
];
```
#### Parameters
`string` $path a dot separated string symbolizing the path to follow inside the hierarchy of each value so that the value can be inserted
`mixed` $values The values to be inserted at the specified path, values are matched with the elements in this collection by its positional index.
#### Returns
`self`
### isEmpty() public
```
isEmpty(): bool
```
Returns whether there are elements in this collection
### Example:
```
$items [1, 2, 3];
(new Collection($items))->isEmpty(); // false
```
```
(new Collection([]))->isEmpty(); // true
```
#### Returns
`bool`
### jsonSerialize() public
```
jsonSerialize(): array
```
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
Part of JsonSerializable interface.
#### Returns
`array`
### last() public
```
last(): mixed
```
Returns the last result in this collection
#### Returns
`mixed`
### lazy() public
```
lazy(): self
```
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
A lazy collection can only be iterated once. A second attempt results in an error.
#### Returns
`self`
### listNested() public
```
listNested(string|int $order = 'desc', callable|string $nestingKey = 'children'): self
```
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
By default all elements in the tree following a Depth First Search will be returned, that is, elements from the top parent to the leaves for each branch.
It is possible to return all elements from bottom to top using a Breadth First Search approach by passing the '$dir' parameter with 'asc'. That is, it will return all elements for the same tree depth first and from bottom to top.
Finally, you can specify to only get a collection with the leaf nodes in the tree structure. You do so by passing 'leaves' in the first argument.
The possible values for the first argument are aliases for the following constants and it is valid to pass those instead of the alias:
* desc: RecursiveIteratorIterator::SELF\_FIRST
* asc: RecursiveIteratorIterator::CHILD\_FIRST
* leaves: RecursiveIteratorIterator::LEAVES\_ONLY
### Example:
```
$collection = new Collection([
['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
['id' => 4, 'children' => [['id' => 5]]]
]);
$flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
```
#### Parameters
`string|int` $order optional The order in which to return the elements
`callable|string` $nestingKey optional The key name under which children are nested or a callable function that will return the children list
#### Returns
`self`
### map() public
```
map(callable $callback): self
```
Returns another collection after modifying each of the values in this one using the provided callable.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Getting a collection of booleans where true indicates if a person is female:
```
$collection = (new Collection($people))->map(function ($person, $key) {
return $person->gender === 'female';
});
```
#### Parameters
`callable` $callback the method that will receive each of the elements and returns the new value for the key that is being iterated
#### Returns
`self`
### match() public
```
match(array $conditions): self
```
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
### Example:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->match(['user.name' => 'Renan']);
// Result will look like this when converted to array
[
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
]
```
#### Parameters
`array` $conditions a key-value list of conditions where the key is a property path as accepted by `Collection::extract, and the value the condition against with each element will be matched
#### Returns
`self`
### max() public
```
max(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$max = $collection->max('age');
$max = $collection->max('user.salary');
$max = $collection->max(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $max->name;
```
#### Parameters
`callable|string` $path The column name to use for sorting or callback that returns the value.
`int` $sort optional The sort type, one of SORT\_STRING SORT\_NUMERIC or SORT\_NATURAL
#### Returns
`mixed`
#### See Also
\Cake\Collection\CollectionInterface::sortBy() ### median() public
```
median(callable|string|null $path = null): float|int|null
```
Returns the median of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 400]],
['invoice' => ['total' => 500]]
['invoice' => ['total' => 100]]
['invoice' => ['total' => 333]]
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->median('invoice.total');
// Total: 333
$total = (new Collection([1, 2, 3, 4]))->median();
// Total: 2.5
```
The median of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional The property name to sum or a function If no value is passed, an identity function will be used. that will return the value of the property to sum.
#### Returns
`float|int|null`
### min() public
```
min(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$min = $collection->min('age');
$min = $collection->min('user.salary');
$min = $collection->min(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $min->name;
```
#### Parameters
`callable|string` $path The column name to use for sorting or callback that returns the value.
`int` $sort optional The sort type, one of SORT\_STRING SORT\_NUMERIC or SORT\_NATURAL
#### Returns
`mixed`
#### See Also
\Cake\Collection\CollectionInterface::sortBy() ### nest() public
```
nest(callable|string $idPath, callable|string $parentPath, string $nestingKey = 'children'): self
```
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
#### Parameters
`callable|string` $idPath the column name path to use for determining whether an element is parent of another
`callable|string` $parentPath the column name path to use for determining whether an element is child of another
`string` $nestingKey optional The key name under which children are nested
#### Returns
`self`
### prepend() public
```
prepend(mixed $items): self
```
Prepend a set of items to a collection creating a new collection
#### Parameters
`mixed` $items The items to prepend.
#### Returns
`self`
### prependItem() public
```
prependItem(mixed $item, mixed $key = null): self
```
Prepend a single item creating a new collection.
#### Parameters
`mixed` $item The item to prepend.
`mixed` $key optional The key to prepend the item with. If null a key will be generated.
#### Returns
`self`
### reduce() public
```
reduce(callable $callback, mixed $initial = null): mixed
```
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
#### Parameters
`callable` $callback The callback function to be called
`mixed` $initial optional The state of reduction
#### Returns
`mixed`
### reject() public
```
reject(callable $callback): self
```
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering even numbers in an array, at the end only values 1 and 3 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->reject(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable` $callback the method that will receive each of the elements and returns true whether they should be out of the resulting collection.
#### Returns
`self`
### sample() public
```
sample(int $length = 10): self
```
Returns a new collection with maximum $size random elements from this collection
#### Parameters
`int` $length optional the maximum number of elements to randomly take from this collection
#### Returns
`self`
### shuffle() public
```
shuffle(): self
```
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
#### Returns
`self`
### skip() public
```
skip(int $length): self
```
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
#### Parameters
`int` $length The number of elements to skip.
#### Returns
`self`
### some() public
```
some(callable $callback): bool
```
Returns true if any of the values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$hasYoungPeople = (new Collection([24, 45, 15]))->some(function ($value, $key) {
return $value < 21;
});
```
#### Parameters
`callable` $callback a callback function
#### Returns
`bool`
### sortBy() public
```
sortBy(callable|string $path, int $order = SORT_DESC, int $sort = \SORT_NUMERIC): self
```
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
The callback will receive as its first argument each of the elements in $items, the value returned by the callback will be used as the value for sorting such element. Please note that the callback function could be called more than once per element.
### Example:
```
$items = $collection->sortBy(function ($user) {
return $user->age;
});
// alternatively
$items = $collection->sortBy('age');
// or use a property path
$items = $collection->sortBy('department.name');
// output all user name order by their age in descending order
foreach ($items as $user) {
echo $user->name;
}
```
#### Parameters
`callable|string` $path The column name to use for sorting or callback that returns the value.
`int` $order optional The sort order, either SORT\_DESC or SORT\_ASC
`int` $sort optional The sort type, one of SORT\_STRING SORT\_NUMERIC or SORT\_NATURAL
#### Returns
`self`
### stopWhen() public
```
stopWhen(callable|array $condition): self
```
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
This is handy for dealing with infinite iterators or any generator that could start returning invalid elements at a certain point. For example, when reading lines from a file stream you may want to stop the iteration after a certain value is reached.
### Example:
Get an array of lines in a CSV file until the timestamp column is less than a date
```
$lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
return (new DateTime($value))->format('Y') < 2012;
})
->toArray();
```
Get elements until the first unapproved message is found:
```
$comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
```
#### Parameters
`callable|array` $condition the method that will receive each of the elements and returns true when the iteration should be stopped. If an array, it will be interpreted as a key-value list of conditions where the key is a property path as accepted by `Collection::extract`, and the value the condition against with each element will be matched.
#### Returns
`self`
### sumOf() public
```
sumOf(callable|string|null $path = null): float|int
```
Returns the total sum of all the values extracted with $matcher or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->sumOf('invoice.total');
// Total: 300
$total = (new Collection([1, 2, 3]))->sumOf();
// Total: 6
```
#### Parameters
`callable|string|null` $path optional The property name to sum or a function If no value is passed, an identity function will be used. that will return the value of the property to sum.
#### Returns
`float|int`
### take() public
```
take(int $length = 1, int $offset = 0): self
```
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
#### Parameters
`int` $length optional the maximum number of elements to take from this collection
`int` $offset optional A positional offset from where to take the elements
#### Returns
`self`
### takeLast() public
```
takeLast(int $length): self
```
Returns the last N elements of a collection
### Example:
```
$items = [1, 2, 3, 4, 5];
$last = (new Collection($items))->takeLast(3);
// Result will look like this when converted to array
[3, 4, 5];
```
#### Parameters
`int` $length The number of elements at the end of the collection
#### Returns
`self`
### through() public
```
through(callable $callback): self
```
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
### Example:
```
$items = [1, 2, 3];
$decorated = (new Collection($items))->through(function ($collection) {
return new MyCustomCollection($collection);
});
```
#### Parameters
`callable` $callback A callable function that will receive this collection as first argument.
#### Returns
`self`
### toArray() public
```
toArray(bool $keepKeys = true): array
```
Returns an array representation of the results
#### Parameters
`bool` $keepKeys optional Whether to use the keys returned by this collection as the array keys. Keep in mind that it is valid for iterators to return the same key for different elements, setting this value to false can help getting all items if keys are not important in the result.
#### Returns
`array`
### toList() public
```
toList(): array
```
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
#### Returns
`array`
### transpose() public
```
transpose(): self
```
Transpose rows and columns into columns and rows
### Example:
```
$items = [
['Products', '2012', '2013', '2014'],
['Product A', '200', '100', '50'],
['Product B', '300', '200', '100'],
['Product C', '400', '300', '200'],
]
$transpose = (new Collection($items))->transpose()->toList();
// Returns
// [
// ['Products', 'Product A', 'Product B', 'Product C'],
// ['2012', '200', '300', '400'],
// ['2013', '100', '200', '300'],
// ['2014', '50', '100', '200'],
// ]
```
#### Returns
`self`
### unfold() public
```
unfold(callable|null $callback = null): self
```
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
The transformer function will receive the value and the key for each of the items in the collection, in that order, and it must return an array or a Traversable object that can be concatenated to the final result.
If no transformer function is passed, an "identity" function will be used. This is useful when each of the elements in the source collection are lists of items to be appended one after another.
### Example:
```
$items [[1, 2, 3], [4, 5]];
$unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
```
Using a transformer
```
$items [1, 2, 3];
$allItems = (new Collection($items))->unfold(function ($page) {
return $service->fetchPage($page)->toArray();
});
```
#### Parameters
`callable|null` $callback optional A callable function that will receive each of the items in the collection and should return an array or Traversable object
#### Returns
`self`
### unwrap() public
```
unwrap(): Traversable
```
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
#### Returns
`Traversable`
### zip() public
```
zip(iterable $items): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
### Example:
```
$collection = new Collection([1, 2]);
$collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
```
#### Parameters
`iterable` $items The collections to zip.
#### Returns
`self`
### zipWith() public
```
zipWith(iterable $items, callable $callback): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
The resulting element will be the return value of the $callable function.
### Example:
```
$collection = new Collection([1, 2]);
$zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
return array_sum($args);
});
$zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
```
#### Parameters
`iterable` $items The collections to zip.
`callable` $callback The function to use for zipping the elements together.
#### Returns
`self`
| programming_docs |
cakephp Interface ValidatableInterface Interface ValidatableInterface
===============================
Describes objects that can be validated by passing a Validator object.
**Namespace:** [Cake\Validation](namespace-cake.validation)
**Deprecated:** 4.4.5 This interface is unused.
Method Summary
--------------
* ##### [validate()](#validate()) public
Validates the internal properties using a validator object and returns any validation errors found.
Method Detail
-------------
### validate() public
```
validate(Cake\Validation\Validator $validator): array
```
Validates the internal properties using a validator object and returns any validation errors found.
#### Parameters
`Cake\Validation\Validator` $validator The validator to use when validating the entity.
#### Returns
`array`
cakephp Class Sqlite Class Sqlite
=============
Class Sqlite
**Namespace:** [Cake\Database\Driver](namespace-cake.database.driver)
Constants
---------
* `string` **FEATURE\_CTE**
```
'cte'
```
Common Table Expressions (with clause) support.
* `string` **FEATURE\_DISABLE\_CONSTRAINT\_WITHOUT\_TRANSACTION**
```
'disable-constraint-without-transaction'
```
Disabling constraints without being in transaction support.
* `string` **FEATURE\_JSON**
```
'json'
```
Native JSON data type support.
* `string` **FEATURE\_QUOTE**
```
'quote'
```
PDO::quote() support.
* `string` **FEATURE\_SAVEPOINT**
```
'savepoint'
```
Transaction savepoint support.
* `string` **FEATURE\_TRUNCATE\_WITH\_CONSTRAINTS**
```
'truncate-with-constraints'
```
Truncate with foreign keys attached support.
* `string` **FEATURE\_WINDOW**
```
'window'
```
Window function support (all or partial clauses).
* `int|null` **MAX\_ALIAS\_LENGTH**
```
null
```
* `array<int>` **RETRY\_ERROR\_CODES**
```
[]
```
Property Summary
----------------
* [$\_autoQuoting](#%24_autoQuoting) protected `bool` Indicates whether the driver is doing automatic identifier quoting for all queries
* [$\_baseConfig](#%24_baseConfig) protected `array<string, mixed>` Base configuration settings for Sqlite driver
* [$\_config](#%24_config) protected `array<string, mixed>` Configuration data.
* [$\_connection](#%24_connection) protected `PDO` Instance of PDO.
* [$\_dateParts](#%24_dateParts) protected `array<string, string>` Mapping of date parts.
* [$\_endQuote](#%24_endQuote) protected `string` String used to end a database identifier quoting to make it safe
* [$\_schemaDialect](#%24_schemaDialect) protected `Cake\Database\Schema\SqliteSchemaDialect|null` The schema dialect class for this driver
* [$\_startQuote](#%24_startQuote) protected `string` String used to start a database identifier quoting to make it safe
* [$\_supportsWindowFunctions](#%24_supportsWindowFunctions) protected `bool|null` Whether the connected server supports window functions.
* [$\_version](#%24_version) protected `string|null` The server version
* [$connectRetries](#%24connectRetries) protected `int` The last number of connection retry attempts.
* [$featureVersions](#%24featureVersions) protected `array<string, string>` Mapping of feature to db server version for feature availability checks.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_destruct()](#__destruct()) public
Destructor
* ##### [\_connect()](#_connect()) protected
Establishes a connection to the database server
* ##### [\_deleteQueryTranslator()](#_deleteQueryTranslator()) protected
Apply translation steps to delete queries.
* ##### [\_expressionTranslators()](#_expressionTranslators()) protected
Returns an associative array of methods that will transform Expression objects to conform with the specific SQL dialect. Keys are class names and values a method in this class.
* ##### [\_insertQueryTranslator()](#_insertQueryTranslator()) protected
Apply translation steps to insert queries.
* ##### [\_removeAliasesFromConditions()](#_removeAliasesFromConditions()) protected
Removes aliases from the `WHERE` clause of a query.
* ##### [\_selectQueryTranslator()](#_selectQueryTranslator()) protected
Apply translation steps to select queries.
* ##### [\_transformDistinct()](#_transformDistinct()) protected
Returns the passed query after rewriting the DISTINCT clause, so that drivers that do not support the "ON" part can provide the actual way it should be done
* ##### [\_transformFunctionExpression()](#_transformFunctionExpression()) protected
Receives a FunctionExpression and changes it so that it conforms to this SQL dialect.
* ##### [\_transformTupleComparison()](#_transformTupleComparison()) protected
Receives a TupleExpression and changes it so that it conforms to this SQL dialect.
* ##### [\_updateQueryTranslator()](#_updateQueryTranslator()) protected
Apply translation steps to update queries.
* ##### [beginTransaction()](#beginTransaction()) public
Starts a transaction.
* ##### [commitTransaction()](#commitTransaction()) public
Commits a transaction.
* ##### [compileQuery()](#compileQuery()) public
Transforms the passed query to this Driver's dialect and returns an instance of the transformed query and the full compiled SQL string.
* ##### [connect()](#connect()) public
Establishes a connection to the database server
* ##### [disableAutoQuoting()](#disableAutoQuoting()) public
Disable auto quoting of identifiers in queries.
* ##### [disableForeignKeySQL()](#disableForeignKeySQL()) public
Get the SQL for disabling foreign keys.
* ##### [disconnect()](#disconnect()) public
Disconnects from database server.
* ##### [enableAutoQuoting()](#enableAutoQuoting()) public
Sets whether this driver should automatically quote identifiers in queries.
* ##### [enableForeignKeySQL()](#enableForeignKeySQL()) public
Get the SQL for enabling foreign keys.
* ##### [enabled()](#enabled()) public
Returns whether php is able to use this driver for connecting to database
* ##### [getConnectRetries()](#getConnectRetries()) public
Returns the number of connection retry attempts made.
* ##### [getConnection()](#getConnection()) public
Get the internal PDO connection instance.
* ##### [getMaxAliasLength()](#getMaxAliasLength()) public
Returns the maximum alias length allowed. This can be different from the maximum identifier length for columns.
* ##### [inTransaction()](#inTransaction()) public
Returns whether a transaction is active for connection.
* ##### [isAutoQuotingEnabled()](#isAutoQuotingEnabled()) public
Returns whether this driver should automatically quote identifiers in queries.
* ##### [isConnected()](#isConnected()) public
Checks whether the driver is connected.
* ##### [lastInsertId()](#lastInsertId()) public
Returns last id generated for a table or sequence in database.
* ##### [newCompiler()](#newCompiler()) public
Returns an instance of a QueryCompiler.
* ##### [newTableSchema()](#newTableSchema()) public
Constructs new TableSchema.
* ##### [prepare()](#prepare()) public
Prepares a sql statement to be executed
* ##### [queryTranslator()](#queryTranslator()) public
Returns a callable function that will be used to transform a passed Query object. This function, in turn, will return an instance of a Query object that has been transformed to accommodate any specificities of the SQL dialect in use.
* ##### [quote()](#quote()) public
Returns a value in a safe representation to be used in a query string
* ##### [quoteIdentifier()](#quoteIdentifier()) public
Quotes a database identifier (a column name, table name, etc..) to be used safely in queries without the risk of using reserved words
* ##### [releaseSavePointSQL()](#releaseSavePointSQL()) public
Returns a SQL snippet for releasing a previously created save point
* ##### [rollbackSavePointSQL()](#rollbackSavePointSQL()) public
Returns a SQL snippet for rollbacking a previously created save point
* ##### [rollbackTransaction()](#rollbackTransaction()) public
Rollbacks a transaction.
* ##### [savePointSQL()](#savePointSQL()) public
Returns a SQL snippet for creating a new transaction savepoint
* ##### [schema()](#schema()) public
Returns the schema name that's being used.
* ##### [schemaDialect()](#schemaDialect()) public
Get the schema dialect.
* ##### [schemaValue()](#schemaValue()) public
Escapes values for use in schema definitions.
* ##### [setConnection()](#setConnection()) public
Set the internal PDO connection instance.
* ##### [supports()](#supports()) public
Returns whether the driver supports the feature.
* ##### [supportsCTEs()](#supportsCTEs()) public deprecated
Returns true if the server supports common table expressions.
* ##### [supportsDynamicConstraints()](#supportsDynamicConstraints()) public
Returns whether the driver supports adding or dropping constraints to already created tables.
* ##### [supportsQuoting()](#supportsQuoting()) public deprecated
Checks if the driver supports quoting, as PDO\_ODBC does not support it.
* ##### [supportsSavePoints()](#supportsSavePoints()) public
Returns whether this driver supports save points for nested transactions.
* ##### [supportsWindowFunctions()](#supportsWindowFunctions()) public deprecated
Returns true if the connected server supports window functions.
* ##### [version()](#version()) public
Returns connected server version.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Constructor
#### Parameters
`array<string, mixed>` $config optional The configuration for the driver.
#### Throws
`InvalidArgumentException`
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_destruct() public
```
__destruct()
```
Destructor
### \_connect() protected
```
_connect(string $dsn, array<string, mixed> $config): bool
```
Establishes a connection to the database server
#### Parameters
`string` $dsn A Driver-specific PDO-DSN
`array<string, mixed>` $config configuration to be used for creating connection
#### Returns
`bool`
### \_deleteQueryTranslator() protected
```
_deleteQueryTranslator(Cake\Database\Query $query): Cake\Database\Query
```
Apply translation steps to delete queries.
Chops out aliases on delete query conditions as most database dialects do not support aliases in delete queries. This also removes aliases in table names as they frequently don't work either.
We are intentionally not supporting deletes with joins as they have even poorer support.
#### Parameters
`Cake\Database\Query` $query The query to translate
#### Returns
`Cake\Database\Query`
### \_expressionTranslators() protected
```
_expressionTranslators(): array<string>
```
Returns an associative array of methods that will transform Expression objects to conform with the specific SQL dialect. Keys are class names and values a method in this class.
#### Returns
`array<string>`
### \_insertQueryTranslator() protected
```
_insertQueryTranslator(Cake\Database\Query $query): Cake\Database\Query
```
Apply translation steps to insert queries.
#### Parameters
`Cake\Database\Query` $query The query to translate
#### Returns
`Cake\Database\Query`
### \_removeAliasesFromConditions() protected
```
_removeAliasesFromConditions(Cake\Database\Query $query): Cake\Database\Query
```
Removes aliases from the `WHERE` clause of a query.
#### Parameters
`Cake\Database\Query` $query The query to process.
#### Returns
`Cake\Database\Query`
#### Throws
`RuntimeException`
In case the processed query contains any joins, as removing aliases from the conditions can break references to the joined tables. ### \_selectQueryTranslator() protected
```
_selectQueryTranslator(Cake\Database\Query $query): Cake\Database\Query
```
Apply translation steps to select queries.
#### Parameters
`Cake\Database\Query` $query The query to translate
#### Returns
`Cake\Database\Query`
### \_transformDistinct() protected
```
_transformDistinct(Cake\Database\Query $query): Cake\Database\Query
```
Returns the passed query after rewriting the DISTINCT clause, so that drivers that do not support the "ON" part can provide the actual way it should be done
#### Parameters
`Cake\Database\Query` $query The query to be transformed
#### Returns
`Cake\Database\Query`
### \_transformFunctionExpression() protected
```
_transformFunctionExpression(Cake\Database\Expression\FunctionExpression $expression): void
```
Receives a FunctionExpression and changes it so that it conforms to this SQL dialect.
#### Parameters
`Cake\Database\Expression\FunctionExpression` $expression The function expression to convert to TSQL.
#### Returns
`void`
### \_transformTupleComparison() protected
```
_transformTupleComparison(Cake\Database\Expression\TupleComparison $expression, Cake\Database\Query $query): void
```
Receives a TupleExpression and changes it so that it conforms to this SQL dialect.
It transforms expressions looking like '(a, b) IN ((c, d), (e, f))' into an equivalent expression of the form '((a = c) AND (b = d)) OR ((a = e) AND (b = f))'.
It can also transform transform expressions where the right hand side is a query selecting the same amount of columns as the elements in the left hand side of the expression:
(a, b) IN (SELECT c, d FROM a\_table) is transformed into
1 = (SELECT 1 FROM a\_table WHERE (a = c) AND (b = d))
#### Parameters
`Cake\Database\Expression\TupleComparison` $expression The expression to transform
`Cake\Database\Query` $query The query to update.
#### Returns
`void`
### \_updateQueryTranslator() protected
```
_updateQueryTranslator(Cake\Database\Query $query): Cake\Database\Query
```
Apply translation steps to update queries.
Chops out aliases on update query conditions as not all database dialects do support aliases in update queries.
Just like for delete queries, joins are currently not supported for update queries.
#### Parameters
`Cake\Database\Query` $query The query to translate
#### Returns
`Cake\Database\Query`
### beginTransaction() public
```
beginTransaction(): bool
```
Starts a transaction.
#### Returns
`bool`
### commitTransaction() public
```
commitTransaction(): bool
```
Commits a transaction.
#### Returns
`bool`
### compileQuery() public
```
compileQuery(Cake\Database\Query $query, Cake\Database\ValueBinder $binder): array
```
Transforms the passed query to this Driver's dialect and returns an instance of the transformed query and the full compiled SQL string.
#### Parameters
`Cake\Database\Query` $query `Cake\Database\ValueBinder` $binder #### Returns
`array`
### connect() public
```
connect(): bool
```
Establishes a connection to the database server
#### Returns
`bool`
### disableAutoQuoting() public
```
disableAutoQuoting(): $this
```
Disable auto quoting of identifiers in queries.
#### Returns
`$this`
### disableForeignKeySQL() public
```
disableForeignKeySQL(): string
```
Get the SQL for disabling foreign keys.
#### Returns
`string`
### disconnect() public
```
disconnect(): void
```
Disconnects from database server.
#### Returns
`void`
### enableAutoQuoting() public
```
enableAutoQuoting(bool $enable = true): $this
```
Sets whether this driver should automatically quote identifiers in queries.
#### Parameters
`bool` $enable optional #### Returns
`$this`
### enableForeignKeySQL() public
```
enableForeignKeySQL(): string
```
Get the SQL for enabling foreign keys.
#### Returns
`string`
### enabled() public
```
enabled(): bool
```
Returns whether php is able to use this driver for connecting to database
#### Returns
`bool`
### getConnectRetries() public
```
getConnectRetries(): int
```
Returns the number of connection retry attempts made.
#### Returns
`int`
### getConnection() public
```
getConnection(): PDO
```
Get the internal PDO connection instance.
#### Returns
`PDO`
### getMaxAliasLength() public
```
getMaxAliasLength(): int|null
```
Returns the maximum alias length allowed. This can be different from the maximum identifier length for columns.
#### Returns
`int|null`
### inTransaction() public
```
inTransaction(): bool
```
Returns whether a transaction is active for connection.
#### Returns
`bool`
### isAutoQuotingEnabled() public
```
isAutoQuotingEnabled(): bool
```
Returns whether this driver should automatically quote identifiers in queries.
#### Returns
`bool`
### isConnected() public
```
isConnected(): bool
```
Checks whether the driver is connected.
#### Returns
`bool`
### lastInsertId() public
```
lastInsertId(string|null $table = null, string|null $column = null): string|int
```
Returns last id generated for a table or sequence in database.
#### Parameters
`string|null` $table optional `string|null` $column optional #### Returns
`string|int`
### newCompiler() public
```
newCompiler(): Cake\Database\QueryCompiler
```
Returns an instance of a QueryCompiler.
#### Returns
`Cake\Database\QueryCompiler`
### newTableSchema() public
```
newTableSchema(string $table, array $columns = []): Cake\Database\Schema\TableSchema
```
Constructs new TableSchema.
#### Parameters
`string` $table `array` $columns optional #### Returns
`Cake\Database\Schema\TableSchema`
### prepare() public
```
prepare(Cake\Database\Query|string $query): Cake\Database\StatementInterface
```
Prepares a sql statement to be executed
#### Parameters
`Cake\Database\Query|string` $query The query to prepare.
#### Returns
`Cake\Database\StatementInterface`
### queryTranslator() public
```
queryTranslator(string $type): Closure
```
Returns a callable function that will be used to transform a passed Query object. This function, in turn, will return an instance of a Query object that has been transformed to accommodate any specificities of the SQL dialect in use.
#### Parameters
`string` $type the type of query to be transformed (select, insert, update, delete)
#### Returns
`Closure`
### quote() public
```
quote(mixed $value, int $type = PDO::PARAM_STR): string
```
Returns a value in a safe representation to be used in a query string
#### Parameters
`mixed` $value `int` $type optional #### Returns
`string`
### quoteIdentifier() public
```
quoteIdentifier(string $identifier): string
```
Quotes a database identifier (a column name, table name, etc..) to be used safely in queries without the risk of using reserved words
#### Parameters
`string` $identifier The identifier to quote.
#### Returns
`string`
### releaseSavePointSQL() public
```
releaseSavePointSQL(string|int $name): string
```
Returns a SQL snippet for releasing a previously created save point
#### Parameters
`string|int` $name save point name
#### Returns
`string`
### rollbackSavePointSQL() public
```
rollbackSavePointSQL(string|int $name): string
```
Returns a SQL snippet for rollbacking a previously created save point
#### Parameters
`string|int` $name save point name
#### Returns
`string`
### rollbackTransaction() public
```
rollbackTransaction(): bool
```
Rollbacks a transaction.
#### Returns
`bool`
### savePointSQL() public
```
savePointSQL(string|int $name): string
```
Returns a SQL snippet for creating a new transaction savepoint
#### Parameters
`string|int` $name save point name
#### Returns
`string`
### schema() public
```
schema(): string
```
Returns the schema name that's being used.
#### Returns
`string`
### schemaDialect() public
```
schemaDialect(): Cake\Database\Schema\SchemaDialect
```
Get the schema dialect.
Used by {@link \Cake\Database\Schema} package to reflect schema and generate schema.
If all the tables that use this Driver specify their own schemas, then this may return null.
#### Returns
`Cake\Database\Schema\SchemaDialect`
### schemaValue() public
```
schemaValue(mixed $value): string
```
Escapes values for use in schema definitions.
#### Parameters
`mixed` $value #### Returns
`string`
### setConnection() public
```
setConnection(object $connection): $this
```
Set the internal PDO connection instance.
#### Parameters
`object` $connection PDO instance.
#### Returns
`$this`
### supports() public
```
supports(string $feature): bool
```
Returns whether the driver supports the feature.
Defaults to true for FEATURE\_QUOTE and FEATURE\_SAVEPOINT.
#### Parameters
`string` $feature #### Returns
`bool`
### supportsCTEs() public
```
supportsCTEs(): bool
```
Returns true if the server supports common table expressions.
#### Returns
`bool`
### supportsDynamicConstraints() public
```
supportsDynamicConstraints(): bool
```
Returns whether the driver supports adding or dropping constraints to already created tables.
#### Returns
`bool`
### supportsQuoting() public
```
supportsQuoting(): bool
```
Checks if the driver supports quoting, as PDO\_ODBC does not support it.
#### Returns
`bool`
### supportsSavePoints() public
```
supportsSavePoints(): bool
```
Returns whether this driver supports save points for nested transactions.
#### Returns
`bool`
### supportsWindowFunctions() public
```
supportsWindowFunctions(): bool
```
Returns true if the connected server supports window functions.
#### Returns
`bool`
### version() public
```
version(): string
```
Returns connected server version.
#### Returns
`string`
Property Detail
---------------
### $\_autoQuoting protected
Indicates whether the driver is doing automatic identifier quoting for all queries
#### Type
`bool`
### $\_baseConfig protected
Base configuration settings for Sqlite driver
* `mask` The mask used for created database
#### Type
`array<string, mixed>`
### $\_config protected
Configuration data.
#### Type
`array<string, mixed>`
### $\_connection protected
Instance of PDO.
#### Type
`PDO`
### $\_dateParts protected
Mapping of date parts.
#### Type
`array<string, string>`
### $\_endQuote protected
String used to end a database identifier quoting to make it safe
#### Type
`string`
### $\_schemaDialect protected
The schema dialect class for this driver
#### Type
`Cake\Database\Schema\SqliteSchemaDialect|null`
### $\_startQuote protected
String used to start a database identifier quoting to make it safe
#### Type
`string`
### $\_supportsWindowFunctions protected
Whether the connected server supports window functions.
#### Type
`bool|null`
### $\_version protected
The server version
#### Type
`string|null`
### $connectRetries protected
The last number of connection retry attempts.
#### Type
`int`
### $featureVersions protected
Mapping of feature to db server version for feature availability checks.
#### Type
`array<string, string>`
| programming_docs |
cakephp Interface ContainerInterface Interface ContainerInterface
=============================
Interface for the Dependency Injection Container in CakePHP applications
This interface extends the PSR-11 container interface and adds methods to add services and service providers to the container.
The methods defined in this interface use the conventions provided by league/container as that is the library that CakePHP uses.
**Namespace:** [Cake\Core](namespace-cake.core)
Method Summary
--------------
* ##### [add()](#add()) public
* ##### [addServiceProvider()](#addServiceProvider()) public
* ##### [addShared()](#addShared()) public
* ##### [extend()](#extend()) public
* ##### [get()](#get()) public
Finds an entry of the container by its identifier and returns it.
* ##### [getNew()](#getNew()) public
* ##### [has()](#has()) public
Returns true if the container can return an entry for the given identifier. Returns false otherwise.
* ##### [inflector()](#inflector()) public
Method Detail
-------------
### add() public
```
add(string $id, mixed $concrete = null): DefinitionInterface
```
#### Parameters
`string` $id $concrete optional #### Returns
`DefinitionInterface`
### addServiceProvider() public
```
addServiceProvider(ServiceProviderInterface $provider): self
```
#### Parameters
`ServiceProviderInterface` $provider #### Returns
`self`
### addShared() public
```
addShared(string $id, mixed $concrete = null): DefinitionInterface
```
#### Parameters
`string` $id $concrete optional #### Returns
`DefinitionInterface`
### extend() public
```
extend(string $id): DefinitionInterface
```
#### Parameters
`string` $id #### Returns
`DefinitionInterface`
### get() public
```
get(string $id): mixed
```
Finds an entry of the container by its identifier and returns it.
#### Parameters
`string` $id Identifier of the entry to look for.
#### Returns
`mixed`
#### Throws
`NotFoundExceptionInterface`
No entry was found for \*\*this\*\* identifier.
`ContainerExceptionInterface`
Error while retrieving the entry. ### getNew() public
```
getNew(mixed $id)
```
#### Parameters
$id ### has() public
```
has(string $id): bool
```
Returns true if the container can return an entry for the given identifier. Returns false otherwise.
`has($id)` returning true does not mean that `get($id)` will not throw an exception. It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`.
#### Parameters
`string` $id Identifier of the entry to look for.
#### Returns
`bool`
### inflector() public
```
inflector(string $type, callable $callback = null): InflectorInterface
```
#### Parameters
`string` $type `callable` $callback optional #### Returns
`InflectorInterface`
cakephp Namespace Filesystem Namespace Filesystem
====================
### Classes
* ##### [File](class-cake.filesystem.file)
Convenience class for reading, writing and appending to files.
* ##### [Filesystem](class-cake.filesystem.filesystem)
This provides convenience wrappers around common filesystem queries.
* ##### [Folder](class-cake.filesystem.folder)
Folder structure browser, lists folders and files. Provides an Object interface for Common directory related tasks.
cakephp Class CookieEquals Class CookieEquals
===================
CookieEquals
**Namespace:** [Cake\TestSuite\Constraint\Response](namespace-cake.testsuite.constraint.response)
Property Summary
----------------
* [$cookieName](#%24cookieName) protected `string`
* [$response](#%24response) protected `Cake\Http\Response`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_getBodyAsString()](#_getBodyAsString()) protected
Get the response body as string
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Checks assertion
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Http\Response|null $response, string $cookieName)
```
Constructor.
#### Parameters
`Cake\Http\Response|null` $response A response instance.
`string` $cookieName Cookie name
### \_getBodyAsString() protected
```
_getBodyAsString(): string
```
Get the response body as string
#### Returns
`string`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks assertion
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Expected content
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $cookieName protected
#### Type
`string`
### $response protected
#### Type
`Cake\Http\Response`
cakephp Class SubjectFilterDecorator Class SubjectFilterDecorator
=============================
Event Subject Filter Decorator
Use this decorator to allow your event listener to only be invoked if event subject matches the `allowedSubject` option.
The `allowedSubject` option can be a list of class names, if you want to check multiple classes.
**Namespace:** [Cake\Event\Decorator](namespace-cake.event.decorator)
Property Summary
----------------
* [$\_callable](#%24_callable) protected `callable` Callable
* [$\_options](#%24_options) protected `array` Decorator options
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_\_invoke()](#__invoke()) public
Invoke
* ##### [\_call()](#_call()) protected
Calls the decorated callable with the passed arguments.
* ##### [canTrigger()](#canTrigger()) public
Checks if the event is triggered for this listener.
Method Detail
-------------
### \_\_construct() public
```
__construct(callable $callable, array<string, mixed> $options = [])
```
Constructor.
#### Parameters
`callable` $callable Callable.
`array<string, mixed>` $options optional Decorator options.
### \_\_invoke() public
```
__invoke(): mixed
```
Invoke
#### Returns
`mixed`
### \_call() protected
```
_call(array $args): mixed
```
Calls the decorated callable with the passed arguments.
#### Parameters
`array` $args Arguments for the callable.
#### Returns
`mixed`
### canTrigger() public
```
canTrigger(Cake\Event\EventInterface $event): bool
```
Checks if the event is triggered for this listener.
#### Parameters
`Cake\Event\EventInterface` $event Event object.
#### Returns
`bool`
Property Detail
---------------
### $\_callable protected
Callable
#### Type
`callable`
### $\_options protected
Decorator options
#### Type
`array`
cakephp Class MailSentFrom Class MailSentFrom
===================
MailSentFromConstraint
**Namespace:** [Cake\TestSuite\Constraint\Email](namespace-cake.testsuite.constraint.email)
Property Summary
----------------
* [$at](#%24at) protected `int|null`
* [$method](#%24method) protected `string`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [getMessages()](#getMessages()) public
Gets the email or emails to check
* ##### [matches()](#matches()) public
Checks constraint
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message string
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(int|null $at = null, string|null $method = null): void
```
Constructor
#### Parameters
`int|null` $at optional At
`string|null` $method optional Method
#### Returns
`void`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### getMessages() public
```
getMessages(): arrayCake\Mailer\Message>
```
Gets the email or emails to check
#### Returns
`arrayCake\Mailer\Message>`
### matches() public
```
matches(mixed $other): bool
```
Checks constraint
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Constraint check
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message string
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $at protected
#### Type
`int|null`
### $method protected
#### Type
`string`
| programming_docs |
cakephp Class RoutesCommand Class RoutesCommand
====================
Provides interactive CLI tools for routing.
**Namespace:** [Cake\Command](namespace-cake.command)
Constants
---------
* `int` **CODE\_ERROR**
```
1
```
Default error code
* `int` **CODE\_SUCCESS**
```
0
```
Default success code
Property Summary
----------------
* [$\_modelFactories](#%24_modelFactories) protected `array<callableCake\Datasource\Locator\LocatorInterface>` A list of overridden model factory functions.
* [$\_modelType](#%24_modelType) protected `string` The model type to use.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
* [$modelClass](#%24modelClass) protected deprecated `string|null` This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
* [$name](#%24name) protected `string` The name of this command.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_setModelClass()](#_setModelClass()) protected
Set the modelClass property based on conventions.
* ##### [abort()](#abort()) public
Halt the the current process with a StopException.
* ##### [buildOptionParser()](#buildOptionParser()) public
Get the option parser.
* ##### [defaultName()](#defaultName()) public static
Get the command name.
* ##### [displayHelp()](#displayHelp()) protected
Output help content
* ##### [execute()](#execute()) public
Display all routes in an application
* ##### [executeCommand()](#executeCommand()) public
Execute another command with the provided set of arguments.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getDescription()](#getDescription()) public static
Get the command description.
* ##### [getModelType()](#getModelType()) public
Get the model type to be used by this class
* ##### [getName()](#getName()) public
Get the command name.
* ##### [getOptionParser()](#getOptionParser()) public
Get the option parser.
* ##### [getRootName()](#getRootName()) public
Get the root command name.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [initialize()](#initialize()) public
Hook method invoked by CakePHP when a command is about to be executed.
* ##### [loadModel()](#loadModel()) public deprecated
Loads and constructs repository objects required by this object
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [modelFactory()](#modelFactory()) public
Override a existing callable to generate repositories of a given type.
* ##### [run()](#run()) public
Run the command.
* ##### [setModelType()](#setModelType()) public
Set the model type to be used by this class
* ##### [setName()](#setName()) public
Set the name this command uses in the collection.
* ##### [setOutputLevel()](#setOutputLevel()) protected
Set the output level based on the Arguments.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
Method Detail
-------------
### \_\_construct() public
```
__construct()
```
Constructor
By default CakePHP will construct command objects when building the CommandCollection for your application.
### \_setModelClass() protected
```
_setModelClass(string $name): void
```
Set the modelClass property based on conventions.
If the property is already set it will not be overwritten
#### Parameters
`string` $name Class name.
#### Returns
`void`
### abort() public
```
abort(int $code = self::CODE_ERROR): void
```
Halt the the current process with a StopException.
#### Parameters
`int` $code optional The exit code to use.
#### Returns
`void`
#### Throws
`Cake\Console\Exception\StopException`
### buildOptionParser() public
```
buildOptionParser(Cake\Console\ConsoleOptionParser $parser): Cake\Console\ConsoleOptionParser
```
Get the option parser.
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser to update
#### Returns
`Cake\Console\ConsoleOptionParser`
### defaultName() public static
```
defaultName(): string
```
Get the command name.
Returns the command name based on class name. For e.g. for a command with class name `UpdateTableCommand` the default name returned would be `'update_table'`.
#### Returns
`string`
### displayHelp() protected
```
displayHelp(Cake\Console\ConsoleOptionParser $parser, Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Output help content
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser.
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### execute() public
```
execute(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): int|null
```
Display all routes in an application
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`int|null`
### executeCommand() public
```
executeCommand(Cake\Console\CommandInterface|string $command, array $args = [], Cake\Console\ConsoleIo|null $io = null): int|null
```
Execute another command with the provided set of arguments.
If you are using a string command name, that command's dependencies will not be resolved with the application container. Instead you will need to pass the command as an object with all of its dependencies.
#### Parameters
`Cake\Console\CommandInterface|string` $command The command class name or command instance.
`array` $args optional The arguments to invoke the command with.
`Cake\Console\ConsoleIo|null` $io optional The ConsoleIo instance to use for the executed command.
#### Returns
`int|null`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getDescription() public static
```
getDescription(): string
```
Get the command description.
#### Returns
`string`
### getModelType() public
```
getModelType(): string
```
Get the model type to be used by this class
#### Returns
`string`
### getName() public
```
getName(): string
```
Get the command name.
#### Returns
`string`
### getOptionParser() public
```
getOptionParser(): Cake\Console\ConsoleOptionParser
```
Get the option parser.
You can override buildOptionParser() to define your options & arguments.
#### Returns
`Cake\Console\ConsoleOptionParser`
#### Throws
`RuntimeException`
When the parser is invalid ### getRootName() public
```
getRootName(): string
```
Get the root command name.
#### Returns
`string`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### initialize() public
```
initialize(): void
```
Hook method invoked by CakePHP when a command is about to be executed.
Override this method and implement expensive/important setup steps that should not run on every command run. This method will be called *before* the options and arguments are validated and processed.
#### Returns
`void`
### loadModel() public
```
loadModel(string|null $modelClass = null, string|null $modelType = null): Cake\Datasource\RepositoryInterface
```
Loads and constructs repository objects required by this object
Typically used to load ORM Table objects as required. Can also be used to load other types of repository objects your application uses.
If a repository provider does not return an object a MissingModelException will be thrown.
#### Parameters
`string|null` $modelClass optional Name of model class to load. Defaults to $this->modelClass. The name can be an alias like `'Post'` or FQCN like `App\Model\Table\PostsTable::class`.
`string|null` $modelType optional The type of repository to load. Defaults to the getModelType() value.
#### Returns
`Cake\Datasource\RepositoryInterface`
#### Throws
`Cake\Datasource\Exception\MissingModelException`
If the model class cannot be found.
`UnexpectedValueException`
If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty. ### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### modelFactory() public
```
modelFactory(string $type, Cake\Datasource\Locator\LocatorInterface|callable $factory): void
```
Override a existing callable to generate repositories of a given type.
#### Parameters
`string` $type The name of the repository type the factory function is for.
`Cake\Datasource\Locator\LocatorInterface|callable` $factory The factory function used to create instances.
#### Returns
`void`
### run() public
```
run(array $argv, Cake\Console\ConsoleIo $io): int|null
```
Run the command.
#### Parameters
`array` $argv `Cake\Console\ConsoleIo` $io #### Returns
`int|null`
### setModelType() public
```
setModelType(string $modelType): $this
```
Set the model type to be used by this class
#### Parameters
`string` $modelType The model type
#### Returns
`$this`
### setName() public
```
setName(string $name): $this
```
Set the name this command uses in the collection.
Generally invoked by the CommandCollection when the command is added. Required to have at least one space in the name so that the root command can be calculated.
#### Parameters
`string` $name #### Returns
`$this`
### setOutputLevel() protected
```
setOutputLevel(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Set the output level based on the Arguments.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
Property Detail
---------------
### $\_modelFactories protected
A list of overridden model factory functions.
#### Type
`array<callableCake\Datasource\Locator\LocatorInterface>`
### $\_modelType protected
The model type to use.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
### $modelClass protected deprecated
This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
Example: For an object named 'Comments', the modelClass would be 'Comments'. Plugin classes should use `Plugin.Comments` style names to correctly load models from the correct plugin.
Use empty string to not use auto-loading on this object. Null auto-detects based on controller name.
#### Type
`string|null`
### $name protected
The name of this command.
#### Type
`string`
cakephp Class TaskRegistry Class TaskRegistry
===================
Registry for Tasks. Provides features for lazily loading tasks.
**Namespace:** [Cake\Console](namespace-cake.console)
Property Summary
----------------
* [$\_Shell](#%24_Shell) protected `Cake\Console\Shell` Shell to use to set params to tasks.
* [$\_loaded](#%24_loaded) protected `array<object>` Map of loaded objects.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Debug friendly object properties.
* ##### [\_\_get()](#__get()) public
Provide public read access to the loaded objects
* ##### [\_\_isset()](#__isset()) public
Provide isset access to \_loaded
* ##### [\_\_set()](#__set()) public
Sets an object.
* ##### [\_\_unset()](#__unset()) public
Unsets an object.
* ##### [\_checkDuplicate()](#_checkDuplicate()) protected
Check for duplicate object loading.
* ##### [\_create()](#_create()) protected
Create the task instance.
* ##### [\_resolveClassName()](#_resolveClassName()) protected
Resolve a task classname.
* ##### [\_throwMissingClassError()](#_throwMissingClassError()) protected
Throws an exception when a task is missing.
* ##### [count()](#count()) public
Returns the number of loaded objects.
* ##### [get()](#get()) public
Get loaded object instance.
* ##### [getIterator()](#getIterator()) public
Returns an array iterator.
* ##### [has()](#has()) public
Check whether a given object is loaded.
* ##### [load()](#load()) public
Loads/constructs an object instance.
* ##### [loaded()](#loaded()) public
Get the list of loaded objects.
* ##### [normalizeArray()](#normalizeArray()) public
Normalizes an object array, creates an array that makes lazy loading easier
* ##### [reset()](#reset()) public
Clear loaded instances in the registry.
* ##### [set()](#set()) public
Set an object directly into the registry by name.
* ##### [unload()](#unload()) public
Remove an object from the registry.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Console\Shell $shell)
```
Constructor
#### Parameters
`Cake\Console\Shell` $shell Shell instance
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Debug friendly object properties.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): object|null
```
Provide public read access to the loaded objects
#### Parameters
`string` $name Name of property to read
#### Returns
`object|null`
### \_\_isset() public
```
__isset(string $name): bool
```
Provide isset access to \_loaded
#### Parameters
`string` $name Name of object being checked.
#### Returns
`bool`
### \_\_set() public
```
__set(string $name, object $object): void
```
Sets an object.
#### Parameters
`string` $name Name of a property to set.
`object` $object Object to set.
#### Returns
`void`
### \_\_unset() public
```
__unset(string $name): void
```
Unsets an object.
#### Parameters
`string` $name Name of a property to unset.
#### Returns
`void`
### \_checkDuplicate() protected
```
_checkDuplicate(string $name, array<string, mixed> $config): void
```
Check for duplicate object loading.
If a duplicate is being loaded and has different configuration, that is bad and an exception will be raised.
An exception is raised, as replacing the object will not update any references other objects may have. Additionally, simply updating the runtime configuration is not a good option as we may be missing important constructor logic dependent on the configuration.
#### Parameters
`string` $name The name of the alias in the registry.
`array<string, mixed>` $config The config data for the new instance.
#### Returns
`void`
#### Throws
`RuntimeException`
When a duplicate is found. ### \_create() protected
```
_create(object|string $class, string $alias, array<string, mixed> $config): Cake\Console\Shell
```
Create the task instance.
Part of the template method for Cake\Core\ObjectRegistry::load()
#### Parameters
`object|string` $class The classname to create.
`string` $alias The alias of the task.
`array<string, mixed>` $config An array of settings to use for the task.
#### Returns
`Cake\Console\Shell`
### \_resolveClassName() protected
```
_resolveClassName(string $class): string|null
```
Resolve a task classname.
Part of the template method for {@link \Cake\Core\ObjectRegistry::load()}.
#### Parameters
`string` $class Partial classname to resolve.
#### Returns
`string|null`
### \_throwMissingClassError() protected
```
_throwMissingClassError(string $class, string|null $plugin): void
```
Throws an exception when a task is missing.
Part of the template method for Cake\Core\ObjectRegistry::load() and Cake\Core\ObjectRegistry::unload()
#### Parameters
`string` $class The classname that is missing.
`string|null` $plugin The plugin the task is missing in.
#### Returns
`void`
#### Throws
`Cake\Console\Exception\MissingTaskException`
### count() public
```
count(): int
```
Returns the number of loaded objects.
#### Returns
`int`
### get() public
```
get(string $name): object
```
Get loaded object instance.
#### Parameters
`string` $name Name of object.
#### Returns
`object`
#### Throws
`RuntimeException`
If not loaded or found. ### getIterator() public
```
getIterator(): Traversable
```
Returns an array iterator.
#### Returns
`Traversable`
### has() public
```
has(string $name): bool
```
Check whether a given object is loaded.
#### Parameters
`string` $name The object name to check for.
#### Returns
`bool`
### load() public
```
load(string $name, array<string, mixed> $config = []): mixed
```
Loads/constructs an object instance.
Will return the instance in the registry if it already exists. If a subclass provides event support, you can use `$config['enabled'] = false` to exclude constructed objects from being registered for events.
Using {@link \Cake\Controller\Component::$components} as an example. You can alias an object by setting the 'className' key, i.e.,
```
protected $components = [
'Email' => [
'className' => 'App\Controller\Component\AliasedEmailComponent'
];
];
```
All calls to the `Email` component would use `AliasedEmail` instead.
#### Parameters
`string` $name The name/class of the object to load.
`array<string, mixed>` $config optional Additional settings to use when loading the object.
#### Returns
`mixed`
#### Throws
`Exception`
If the class cannot be found. ### loaded() public
```
loaded(): array<string>
```
Get the list of loaded objects.
#### Returns
`array<string>`
### normalizeArray() public
```
normalizeArray(array $objects): array<string, array>
```
Normalizes an object array, creates an array that makes lazy loading easier
#### Parameters
`array` $objects Array of child objects to normalize.
#### Returns
`array<string, array>`
### reset() public
```
reset(): $this
```
Clear loaded instances in the registry.
If the registry subclass has an event manager, the objects will be detached from events as well.
#### Returns
`$this`
### set() public
```
set(string $name, object $object): $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
#### Parameters
`string` $name The name of the object to set in the registry.
`object` $object instance to store in the registry
#### Returns
`$this`
### unload() public
```
unload(string $name): $this
```
Remove an object from the registry.
If this registry has an event manager, the object will be detached from any events as well.
#### Parameters
`string` $name The name of the object to remove from the registry.
#### Returns
`$this`
Property Detail
---------------
### $\_Shell protected
Shell to use to set params to tasks.
#### Type
`Cake\Console\Shell`
### $\_loaded protected
Map of loaded objects.
#### Type
`array<object>`
| programming_docs |
cakephp Interface CommandFactoryInterface Interface CommandFactoryInterface
==================================
An interface for abstracting creation of command and shell instances.
**Namespace:** [Cake\Console](namespace-cake.console)
Method Summary
--------------
* ##### [create()](#create()) public
The factory method for creating Command and Shell instances.
Method Detail
-------------
### create() public
```
create(string $className): Cake\Console\ShellCake\Console\CommandInterface
```
The factory method for creating Command and Shell instances.
#### Parameters
`string` $className Command/Shell class name.
#### Returns
`Cake\Console\ShellCake\Console\CommandInterface`
cakephp Class PageOutOfBoundsException Class PageOutOfBoundsException
===============================
Exception raised when requested page number does not exist.
**Namespace:** [Cake\Datasource\Paging\Exception](namespace-cake.datasource.paging.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Class ServiceUnavailableException Class ServiceUnavailableException
==================================
Represents an HTTP 503 error.
**Namespace:** [Cake\Http\Exception](namespace-cake.http.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
* [$headers](#%24headers) protected `array<string, mixed>`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [getHeaders()](#getHeaders()) public
Returns array of response headers.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
* ##### [setHeader()](#setHeader()) public
Set a single HTTP response header.
* ##### [setHeaders()](#setHeaders()) public
Sets HTTP response headers.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $message = null, int|null $code = null, Throwable|null $previous = null)
```
Constructor
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`string|null` $message optional If no message is given 'Service Unavailable' will be the message
`int|null` $code optional Status code, defaults to 503
`Throwable|null` $previous optional The previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### getHeaders() public
```
getHeaders(): array<string, mixed>
```
Returns array of response headers.
#### Returns
`array<string, mixed>`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
### setHeader() public
```
setHeader(string $header, array<string>|string|null $value = null): void
```
Set a single HTTP response header.
#### Parameters
`string` $header Header name
`array<string>|string|null` $value optional Header value
#### Returns
`void`
### setHeaders() public
```
setHeaders(array<string, mixed> $headers): void
```
Sets HTTP response headers.
#### Parameters
`array<string, mixed>` $headers Array of header name and value pairs.
#### Returns
`void`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
### $headers protected
#### Type
`array<string, mixed>`
cakephp Class InvalidPrimaryKeyException Class InvalidPrimaryKeyException
=================================
Exception raised when the provided primary key does not match the table primary key
**Namespace:** [Cake\Datasource\Exception](namespace-cake.datasource.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Namespace Expression Namespace Expression
====================
### Interfaces
* ##### [FieldInterface](interface-cake.database.expression.fieldinterface)
Describes a getter and a setter for the a field property. Useful for expressions that contain an identifier to compare against.
* ##### [WindowInterface](interface-cake.database.expression.windowinterface)
This defines the functions used for building window expressions.
### Classes
* ##### [AggregateExpression](class-cake.database.expression.aggregateexpression)
This represents an SQL aggregate function expression in an SQL statement. Calls can be constructed by passing the name of the function and a list of params. For security reasons, all params passed are quoted by default unless explicitly told otherwise.
* ##### [BetweenExpression](class-cake.database.expression.betweenexpression)
An expression object that represents a SQL BETWEEN snippet
* ##### [CaseExpression](class-cake.database.expression.caseexpression)
This class represents a SQL Case statement
* ##### [CaseStatementExpression](class-cake.database.expression.casestatementexpression)
Represents a SQL case statement with a fluid API
* ##### [CommonTableExpression](class-cake.database.expression.commontableexpression)
An expression that represents a common table expression definition.
* ##### [ComparisonExpression](class-cake.database.expression.comparisonexpression)
A Comparison is a type of query expression that represents an operation involving a field an operator and a value. In its most common form the string representation of a comparison is `field = value`
* ##### [FunctionExpression](class-cake.database.expression.functionexpression)
This class represents a function call string in a SQL statement. Calls can be constructed by passing the name of the function and a list of params. For security reasons, all params passed are quoted by default unless explicitly told otherwise.
* ##### [IdentifierExpression](class-cake.database.expression.identifierexpression)
Represents a single identifier name in the database.
* ##### [OrderByExpression](class-cake.database.expression.orderbyexpression)
An expression object for ORDER BY clauses
* ##### [OrderClauseExpression](class-cake.database.expression.orderclauseexpression)
An expression object for complex ORDER BY clauses
* ##### [QueryExpression](class-cake.database.expression.queryexpression)
Represents a SQL Query expression. Internally it stores a tree of expressions that can be compiled by converting this object to string and will contain a correctly parenthesized and nested expression.
* ##### [StringExpression](class-cake.database.expression.stringexpression)
String expression with collation.
* ##### [TupleComparison](class-cake.database.expression.tuplecomparison)
This expression represents SQL fragments that are used for comparing one tuple to another, one tuple to a set of other tuples or one tuple to an expression
* ##### [UnaryExpression](class-cake.database.expression.unaryexpression)
An expression object that represents an expression with only a single operand.
* ##### [ValuesExpression](class-cake.database.expression.valuesexpression)
An expression object to contain values being inserted.
* ##### [WhenThenExpression](class-cake.database.expression.whenthenexpression)
Represents a SQL when/then clause with a fluid API
* ##### [WindowExpression](class-cake.database.expression.windowexpression)
This represents a SQL window expression used by aggregate and window functions.
### Traits
* ##### [CaseExpressionTrait](trait-cake.database.expression.caseexpressiontrait)
Trait that holds shared functionality for case related expressions.
* ##### [FieldTrait](trait-cake.database.expression.fieldtrait)
Contains the field property with a getter and a setter for it
cakephp Class ReplaceIterator Class ReplaceIterator
======================
Creates an iterator from another iterator that will modify each of the values by converting them using a callback function.
**Namespace:** [Cake\Collection\Iterator](namespace-cake.collection.iterator)
Property Summary
----------------
* [$\_callback](#%24_callback) protected `callable` The callback function to be used to transform values
* [$\_innerIterator](#%24_innerIterator) protected `Traversable` A reference to the internal iterator this object is wrapping.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Creates an iterator from another iterator that will modify each of the values by converting them using a callback function.
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_serialize()](#__serialize()) public
Returns an array for serializing this of this object.
* ##### [\_\_unserialize()](#__unserialize()) public
Rebuilds the Collection instance.
* ##### [\_createMatcherFilter()](#_createMatcherFilter()) protected
Returns a callable that receives a value and will return whether it matches certain condition.
* ##### [\_extract()](#_extract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
* ##### [\_propertyExtractor()](#_propertyExtractor()) protected
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
* ##### [\_simpleExtract()](#_simpleExtract()) protected
Returns a column from $data that can be extracted by iterating over the column names contained in $path
* ##### [append()](#append()) public
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
* ##### [appendItem()](#appendItem()) public
Append a single item creating a new collection.
* ##### [avg()](#avg()) public
Returns the average of all the values extracted with $path or of this collection.
* ##### [buffered()](#buffered()) public
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
* ##### [cartesianProduct()](#cartesianProduct()) public
Create a new collection that is the cartesian product of the current collection
* ##### [chunk()](#chunk()) public
Breaks the collection into smaller arrays of the given size.
* ##### [chunkWithKeys()](#chunkWithKeys()) public
Breaks the collection into smaller arrays of the given size.
* ##### [combine()](#combine()) public
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
* ##### [compile()](#compile()) public
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
* ##### [contains()](#contains()) public
Returns true if $value is present in this collection. Comparisons are made both by value and type.
* ##### [count()](#count()) public
Returns the amount of elements in the collection.
* ##### [countBy()](#countBy()) public
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
* ##### [countKeys()](#countKeys()) public
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
* ##### [current()](#current()) public
Returns the value returned by the callback after passing the current value in the iteration
* ##### [each()](#each()) public
Applies a callback to the elements in this collection.
* ##### [every()](#every()) public
Returns true if all values in this collection pass the truth test provided in the callback.
* ##### [extract()](#extract()) public
Returns a new collection containing the column or property value found in each of the elements.
* ##### [filter()](#filter()) public
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
* ##### [first()](#first()) public
Returns the first result in this collection
* ##### [firstMatch()](#firstMatch()) public
Returns the first result matching all the key-value pairs listed in conditions.
* ##### [groupBy()](#groupBy()) public
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
* ##### [indexBy()](#indexBy()) public
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
* ##### [insert()](#insert()) public
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
* ##### [isEmpty()](#isEmpty()) public
Returns whether there are elements in this collection
* ##### [jsonSerialize()](#jsonSerialize()) public
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
* ##### [last()](#last()) public
Returns the last result in this collection
* ##### [lazy()](#lazy()) public
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
* ##### [listNested()](#listNested()) public
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
* ##### [map()](#map()) public
Returns another collection after modifying each of the values in this one using the provided callable.
* ##### [match()](#match()) public
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
* ##### [max()](#max()) public
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [median()](#median()) public
Returns the median of all the values extracted with $path or of this collection.
* ##### [min()](#min()) public
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
* ##### [nest()](#nest()) public
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
* ##### [newCollection()](#newCollection()) protected
Returns a new collection.
* ##### [optimizeUnwrap()](#optimizeUnwrap()) protected
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
* ##### [prepend()](#prepend()) public
Prepend a set of items to a collection creating a new collection
* ##### [prependItem()](#prependItem()) public
Prepend a single item creating a new collection.
* ##### [reduce()](#reduce()) public
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
* ##### [reject()](#reject()) public
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
* ##### [sample()](#sample()) public
Returns a new collection with maximum $size random elements from this collection
* ##### [serialize()](#serialize()) public
Returns a string representation of this object that can be used to reconstruct it
* ##### [shuffle()](#shuffle()) public
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
* ##### [skip()](#skip()) public
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
* ##### [some()](#some()) public
Returns true if any of the values in this collection pass the truth test provided in the callback.
* ##### [sortBy()](#sortBy()) public
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
* ##### [stopWhen()](#stopWhen()) public
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
* ##### [sumOf()](#sumOf()) public
Returns the total sum of all the values extracted with $matcher or of this collection.
* ##### [take()](#take()) public
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
* ##### [takeLast()](#takeLast()) public
Returns the last N elements of a collection
* ##### [through()](#through()) public
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
* ##### [toArray()](#toArray()) public
Returns an array representation of the results
* ##### [toList()](#toList()) public
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
* ##### [transpose()](#transpose()) public
Transpose rows and columns into columns and rows
* ##### [unfold()](#unfold()) public
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
* ##### [unserialize()](#unserialize()) public
Unserializes the passed string and rebuilds the Collection instance
* ##### [unwrap()](#unwrap()) public
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
* ##### [zip()](#zip()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
* ##### [zipWith()](#zipWith()) public
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
Method Detail
-------------
### \_\_construct() public
```
__construct(iterable $items, callable $callback)
```
Creates an iterator from another iterator that will modify each of the values by converting them using a callback function.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and the passed $items iterator as arguments, in that order.
#### Parameters
`iterable` $items The items to be filtered.
`callable` $callback Callback.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_serialize() public
```
__serialize(): array
```
Returns an array for serializing this of this object.
#### Returns
`array`
### \_\_unserialize() public
```
__unserialize(array $data): void
```
Rebuilds the Collection instance.
#### Parameters
`array` $data Data array.
#### Returns
`void`
### \_createMatcherFilter() protected
```
_createMatcherFilter(array $conditions): Closure
```
Returns a callable that receives a value and will return whether it matches certain condition.
#### Parameters
`array` $conditions A key-value list of conditions to match where the key is the property path to get from the current item and the value is the value to be compared the item with.
#### Returns
`Closure`
### \_extract() protected
```
_extract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path. It will return arrays for elements in represented with `{*}`
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### \_propertyExtractor() protected
```
_propertyExtractor(callable|string $path): callable
```
Returns a callable that can be used to extract a property or column from an array or object based on a dot separated path.
#### Parameters
`callable|string` $path A dot separated path of column to follow so that the final one can be returned or a callable that will take care of doing that.
#### Returns
`callable`
### \_simpleExtract() protected
```
_simpleExtract(ArrayAccess|array $data, array<string> $parts): mixed
```
Returns a column from $data that can be extracted by iterating over the column names contained in $path
#### Parameters
`ArrayAccess|array` $data Data.
`array<string>` $parts Path to extract from.
#### Returns
`mixed`
### append() public
```
append(iterable $items): self
```
Returns a new collection as the result of concatenating the list of elements in this collection with the passed list of elements
#### Parameters
`iterable` $items #### Returns
`self`
### appendItem() public
```
appendItem(mixed $item, mixed $key = null): self
```
Append a single item creating a new collection.
#### Parameters
`mixed` $item `mixed` $key optional #### Returns
`self`
### avg() public
```
avg(callable|string|null $path = null): float|int|null
```
Returns the average of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->avg('invoice.total');
// Total: 150
$total = (new Collection([1, 2, 3]))->avg();
// Total: 2
```
The average of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int|null`
### buffered() public
```
buffered(): self
```
Returns a new collection where the operations performed by this collection. No matter how many times the new collection is iterated, those operations will only be performed once.
This can also be used to make any non-rewindable iterator rewindable.
#### Returns
`self`
### cartesianProduct() public
```
cartesianProduct(callable|null $operation = null, callable|null $filter = null): Cake\Collection\CollectionInterface
```
Create a new collection that is the cartesian product of the current collection
In order to create a carteisan product a collection must contain a single dimension of data.
### Example
```
$collection = new Collection([['A', 'B', 'C'], [1, 2, 3]]);
$result = $collection->cartesianProduct()->toArray();
$expected = [
['A', 1],
['A', 2],
['A', 3],
['B', 1],
['B', 2],
['B', 3],
['C', 1],
['C', 2],
['C', 3],
];
```
#### Parameters
`callable|null` $operation optional A callable that allows you to customize the product result.
`callable|null` $filter optional A filtering callback that must return true for a result to be part of the final results.
#### Returns
`Cake\Collection\CollectionInterface`
#### Throws
`LogicException`
### chunk() public
```
chunk(int $chunkSize): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
$chunked = (new Collection($items))->chunk(3)->toList();
// Returns [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
```
#### Parameters
`int` $chunkSize #### Returns
`self`
### chunkWithKeys() public
```
chunkWithKeys(int $chunkSize, bool $keepKeys = true): self
```
Breaks the collection into smaller arrays of the given size.
### Example:
```
$items ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
$chunked = (new Collection($items))->chunkWithKeys(3)->toList();
// Returns [['a' => 1, 'b' => 2, 'c' => 3], ['d' => 4, 'e' => 5, 'f' => 6]]
```
#### Parameters
`int` $chunkSize `bool` $keepKeys optional #### Returns
`self`
### combine() public
```
combine(callable|string $keyPath, callable|string $valuePath, callable|string|null $groupPath = null): self
```
Returns a new collection where the values extracted based on a value path and then indexed by a key path. Optionally this method can produce parent groups based on a group property path.
### Examples:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent' => 'a'],
['id' => 2, 'name' => 'bar', 'parent' => 'b'],
['id' => 3, 'name' => 'baz', 'parent' => 'a'],
];
$combined = (new Collection($items))->combine('id', 'name');
// Result will look like this when converted to array
[
1 => 'foo',
2 => 'bar',
3 => 'baz',
];
$combined = (new Collection($items))->combine('id', 'name', 'parent');
// Result will look like this when converted to array
[
'a' => [1 => 'foo', 3 => 'baz'],
'b' => [2 => 'bar']
];
```
#### Parameters
`callable|string` $keyPath `callable|string` $valuePath `callable|string|null` $groupPath optional #### Returns
`self`
### compile() public
```
compile(bool $keepKeys = true): self
```
Iterates once all elements in this collection and executes all stacked operations of them, finally it returns a new collection with the result. This is useful for converting non-rewindable internal iterators into a collection that can be rewound and used multiple times.
A common use case is to re-use the same variable for calculating different data. In those cases it may be helpful and more performant to first compile a collection and then apply more operations to it.
### Example:
```
$collection->map($mapper)->sortBy('age')->extract('name');
$compiled = $collection->compile();
$isJohnHere = $compiled->some($johnMatcher);
$allButJohn = $compiled->filter($johnMatcher);
```
In the above example, had the collection not been compiled before, the iterations for `map`, `sortBy` and `extract` would've been executed twice: once for getting `$isJohnHere` and once for `$allButJohn`
You can think of this method as a way to create save points for complex calculations in a collection.
#### Parameters
`bool` $keepKeys optional #### Returns
`self`
### contains() public
```
contains(mixed $value): bool
```
Returns true if $value is present in this collection. Comparisons are made both by value and type.
#### Parameters
`mixed` $value #### Returns
`bool`
### count() public
```
count(): int
```
Returns the amount of elements in the collection.
WARNINGS:
---------
### Will change the current position of the iterator:
Calling this method at the same time that you are iterating this collections, for example in a foreach, will result in undefined behavior. Avoid doing this.
### Consumes all elements for NoRewindIterator collections:
On certain type of collections, calling this method may render unusable afterwards. That is, you may not be able to get elements out of it, or to iterate on it anymore.
Specifically any collection wrapping a Generator (a function with a yield statement) or a unbuffered database cursor will not accept any other function calls after calling `count()` on it.
Create a new collection with `buffered()` method to overcome this problem.
### Can report more elements than unique keys:
Any collection constructed by appending collections together, or by having internal iterators returning duplicate keys, will report a larger amount of elements using this functions than the final amount of elements when converting the collections to a keyed array. This is because duplicate keys will be collapsed into a single one in the final array, whereas this count method is only concerned by the amount of elements after converting it to a plain list.
If you need the count of elements after taking the keys in consideration (the count of unique keys), you can call `countKeys()`
#### Returns
`int`
### countBy() public
```
countBy(callable|string $path): self
```
Sorts a list into groups and returns a count for the number of elements in each group. Similar to groupBy, but instead of returning a list of values, returns a count for the number of values in that group.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->countBy('parent_id');
// Or
$group = (new Collection($items))->countBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => 2,
11 => 1
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### countKeys() public
```
countKeys(): int
```
Returns the number of unique keys in this iterator. This is the same as the number of elements the collection will contain after calling `toArray()`
This method comes with a number of caveats. Please refer to `CollectionInterface::count()` for details.
#### Returns
`int`
### current() public
```
current(): mixed
```
Returns the value returned by the callback after passing the current value in the iteration
#### Returns
`mixed`
### each() public
```
each(callable $callback): $this
```
Applies a callback to the elements in this collection.
### Example:
```
$collection = (new Collection($items))->each(function ($value, $key) {
echo "Element $key: $value";
});
```
#### Parameters
`callable` $callback #### Returns
`$this`
### every() public
```
every(callable $callback): bool
```
Returns true if all values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$overTwentyOne = (new Collection([24, 45, 60, 15]))->every(function ($value, $key) {
return $value > 21;
});
```
Empty collections always return true.
#### Parameters
`callable` $callback #### Returns
`bool`
### extract() public
```
extract(callable|string $path): self
```
Returns a new collection containing the column or property value found in each of the elements.
The matcher can be a string with a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection, that position is filled with null.
### Example:
Extract the user name for all comments in the array:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->extract('comment.user.name');
// Result will look like this when converted to array
['Mark', 'Renan']
```
It is also possible to extract a flattened collection out of nested properties
```
$items = [
['comment' => ['votes' => [['value' => 1], ['value' => 2], ['value' => 3]]],
['comment' => ['votes' => [['value' => 4]]
];
$extracted = (new Collection($items))->extract('comment.votes.{*}.value');
// Result will contain
[1, 2, 3, 4]
```
#### Parameters
`callable|string` $path #### Returns
`self`
### filter() public
```
filter(callable|null $callback = null): self
```
Looks through each value in the collection, and returns another collection with all the values that pass a truth test. Only the values for which the callback returns true will be present in the resulting collection.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering odd numbers in an array, at the end only the value 2 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->filter(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable|null` $callback optional #### Returns
`self`
### first() public
```
first(): mixed
```
Returns the first result in this collection
#### Returns
`mixed`
### firstMatch() public
```
firstMatch(array $conditions): mixed
```
Returns the first result matching all the key-value pairs listed in conditions.
#### Parameters
`array` $conditions #### Returns
`mixed`
### groupBy() public
```
groupBy(callable|string $path): self
```
Splits a collection into sets, grouped by the result of running each value through the callback. If $callback is a string instead of a callable, groups by the property named by $callback on each of the values.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
];
$group = (new Collection($items))->groupBy('parent_id');
// Or
$group = (new Collection($items))->groupBy(function ($e) {
return $e['parent_id'];
});
// Result will look like this when converted to array
[
10 => [
['id' => 1, 'name' => 'foo', 'parent_id' => 10],
['id' => 3, 'name' => 'baz', 'parent_id' => 10],
],
11 => [
['id' => 2, 'name' => 'bar', 'parent_id' => 11],
]
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### indexBy() public
```
indexBy(callable|string $path): self
```
Given a list and a callback function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.
When $callback is a string it should be a property name to extract or a dot separated path of properties that should be followed to get the last one in the path.
### Example:
```
$items = [
['id' => 1, 'name' => 'foo'],
['id' => 2, 'name' => 'bar'],
['id' => 3, 'name' => 'baz'],
];
$indexed = (new Collection($items))->indexBy('id');
// Or
$indexed = (new Collection($items))->indexBy(function ($e) {
return $e['id'];
});
// Result will look like this when converted to array
[
1 => ['id' => 1, 'name' => 'foo'],
3 => ['id' => 3, 'name' => 'baz'],
2 => ['id' => 2, 'name' => 'bar'],
];
```
#### Parameters
`callable|string` $path #### Returns
`self`
### insert() public
```
insert(string $path, mixed $values): self
```
Returns a new collection containing each of the elements found in `$values` as a property inside the corresponding elements in this collection. The property where the values will be inserted is described by the `$path` parameter.
The $path can be a string with a property name or a dot separated path of properties that should be followed to get the last one in the path.
If a column or property could not be found for a particular element in the collection as part of the path, the element will be kept unchanged.
### Example:
Insert ages into a collection containing users:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan']]
];
$ages = [25, 28];
$inserted = (new Collection($items))->insert('comment.user.age', $ages);
// Result will look like this when converted to array
[
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark', 'age' => 25]],
['comment' => ['body' => 'awesome', 'user' => ['name' => 'Renan', 'age' => 28]]
];
```
#### Parameters
`string` $path `mixed` $values #### Returns
`self`
### isEmpty() public
```
isEmpty(): bool
```
Returns whether there are elements in this collection
### Example:
```
$items [1, 2, 3];
(new Collection($items))->isEmpty(); // false
```
```
(new Collection([]))->isEmpty(); // true
```
#### Returns
`bool`
### jsonSerialize() public
```
jsonSerialize(): array
```
Returns the data that can be converted to JSON. This returns the same data as `toArray()` which contains only unique keys.
Part of JsonSerializable interface.
#### Returns
`array`
### last() public
```
last(): mixed
```
Returns the last result in this collection
#### Returns
`mixed`
### lazy() public
```
lazy(): self
```
Returns a new collection where any operations chained after it are guaranteed to be run lazily. That is, elements will be yieleded one at a time.
A lazy collection can only be iterated once. A second attempt results in an error.
#### Returns
`self`
### listNested() public
```
listNested(string|int $order = 'desc', callable|string $nestingKey = 'children'): self
```
Returns a new collection with each of the elements of this collection after flattening the tree structure. The tree structure is defined by nesting elements under a key with a known name. It is possible to specify such name by using the '$nestingKey' parameter.
By default all elements in the tree following a Depth First Search will be returned, that is, elements from the top parent to the leaves for each branch.
It is possible to return all elements from bottom to top using a Breadth First Search approach by passing the '$dir' parameter with 'asc'. That is, it will return all elements for the same tree depth first and from bottom to top.
Finally, you can specify to only get a collection with the leaf nodes in the tree structure. You do so by passing 'leaves' in the first argument.
The possible values for the first argument are aliases for the following constants and it is valid to pass those instead of the alias:
* desc: RecursiveIteratorIterator::SELF\_FIRST
* asc: RecursiveIteratorIterator::CHILD\_FIRST
* leaves: RecursiveIteratorIterator::LEAVES\_ONLY
### Example:
```
$collection = new Collection([
['id' => 1, 'children' => [['id' => 2, 'children' => [['id' => 3]]]]],
['id' => 4, 'children' => [['id' => 5]]]
]);
$flattenedIds = $collection->listNested()->extract('id'); // Yields [1, 2, 3, 4, 5]
```
#### Parameters
`string|int` $order optional `callable|string` $nestingKey optional #### Returns
`self`
### map() public
```
map(callable $callback): self
```
Returns another collection after modifying each of the values in this one using the provided callable.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Getting a collection of booleans where true indicates if a person is female:
```
$collection = (new Collection($people))->map(function ($person, $key) {
return $person->gender === 'female';
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### match() public
```
match(array $conditions): self
```
Looks through each value in the list, returning a Collection of all the values that contain all of the key-value pairs listed in $conditions.
### Example:
```
$items = [
['comment' => ['body' => 'cool', 'user' => ['name' => 'Mark']],
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
];
$extracted = (new Collection($items))->match(['user.name' => 'Renan']);
// Result will look like this when converted to array
[
['comment' => ['body' => 'very cool', 'user' => ['name' => 'Renan']]
]
```
#### Parameters
`array` $conditions #### Returns
`self`
### max() public
```
max(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the top element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$max = $collection->max('age');
$max = $collection->max('user.salary');
$max = $collection->max(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $max->name;
```
#### Parameters
`callable|string` $path `int` $sort optional #### Returns
`mixed`
### median() public
```
median(callable|string|null $path = null): float|int|null
```
Returns the median of all the values extracted with $path or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 400]],
['invoice' => ['total' => 500]]
['invoice' => ['total' => 100]]
['invoice' => ['total' => 333]]
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->median('invoice.total');
// Total: 333
$total = (new Collection([1, 2, 3, 4]))->median();
// Total: 2.5
```
The median of an empty set or 0 rows is `null`. Collections with `null` values are not considered empty.
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int|null`
### min() public
```
min(callable|string $path, int $sort = \SORT_NUMERIC): mixed
```
Returns the bottom element in this collection after being sorted by a property. Check the sortBy method for information on the callback and $sort parameters
### Examples:
```
// For a collection of employees
$min = $collection->min('age');
$min = $collection->min('user.salary');
$min = $collection->min(function ($e) {
return $e->get('user')->get('salary');
});
// Display employee name
echo $min->name;
```
#### Parameters
`callable|string` $path `int` $sort optional #### Returns
`mixed`
### nest() public
```
nest(callable|string $idPath, callable|string $parentPath, string $nestingKey = 'children'): self
```
Returns a new collection where the values are nested in a tree-like structure based on an id property path and a parent id property path.
#### Parameters
`callable|string` $idPath `callable|string` $parentPath `string` $nestingKey optional #### Returns
`self`
### newCollection() protected
```
newCollection(mixed ...$args): Cake\Collection\CollectionInterface
```
Returns a new collection.
Allows classes which use this trait to determine their own type of returned collection interface
#### Parameters
`mixed` ...$args Constructor arguments.
#### Returns
`Cake\Collection\CollectionInterface`
### optimizeUnwrap() protected
```
optimizeUnwrap(): iterable
```
Unwraps this iterator and returns the simplest traversable that can be used for getting the data out
#### Returns
`iterable`
### prepend() public
```
prepend(mixed $items): self
```
Prepend a set of items to a collection creating a new collection
#### Parameters
`mixed` $items #### Returns
`self`
### prependItem() public
```
prependItem(mixed $item, mixed $key = null): self
```
Prepend a single item creating a new collection.
#### Parameters
`mixed` $item `mixed` $key optional #### Returns
`self`
### reduce() public
```
reduce(callable $callback, mixed $initial = null): mixed
```
Folds the values in this collection to a single value, as the result of applying the callback function to all elements. $zero is the initial state of the reduction, and each successive step of it should be returned by the callback function. If $zero is omitted the first value of the collection will be used in its place and reduction will start from the second item.
#### Parameters
`callable` $callback `mixed` $initial optional #### Returns
`mixed`
### reject() public
```
reject(callable $callback): self
```
Looks through each value in the collection, and returns another collection with all the values that do not pass a truth test. This is the opposite of `filter`.
Each time the callback is executed it will receive the value of the element in the current iteration, the key of the element and this collection as arguments, in that order.
### Example:
Filtering even numbers in an array, at the end only values 1 and 3 will be present in the resulting collection:
```
$collection = (new Collection([1, 2, 3]))->reject(function ($value, $key) {
return $value % 2 === 0;
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### sample() public
```
sample(int $length = 10): self
```
Returns a new collection with maximum $size random elements from this collection
#### Parameters
`int` $length optional #### Returns
`self`
### serialize() public
```
serialize(): string
```
Returns a string representation of this object that can be used to reconstruct it
#### Returns
`string`
### shuffle() public
```
shuffle(): self
```
Returns a new collection with the elements placed in a random order, this function does not preserve the original keys in the collection.
#### Returns
`self`
### skip() public
```
skip(int $length): self
```
Returns a new collection that will skip the specified amount of elements at the beginning of the iteration.
#### Parameters
`int` $length #### Returns
`self`
### some() public
```
some(callable $callback): bool
```
Returns true if any of the values in this collection pass the truth test provided in the callback.
The callback is passed the value and key of the element being tested and should return true if the test passed.
### Example:
```
$hasYoungPeople = (new Collection([24, 45, 15]))->some(function ($value, $key) {
return $value < 21;
});
```
#### Parameters
`callable` $callback #### Returns
`bool`
### sortBy() public
```
sortBy(callable|string $path, int $order = \SORT_DESC, int $sort = \SORT_NUMERIC): self
```
Returns a sorted iterator out of the elements in this collection, ranked in ascending order by the results of running each value through a callback. $callback can also be a string representing the column or property name.
The callback will receive as its first argument each of the elements in $items, the value returned by the callback will be used as the value for sorting such element. Please note that the callback function could be called more than once per element.
### Example:
```
$items = $collection->sortBy(function ($user) {
return $user->age;
});
// alternatively
$items = $collection->sortBy('age');
// or use a property path
$items = $collection->sortBy('department.name');
// output all user name order by their age in descending order
foreach ($items as $user) {
echo $user->name;
}
```
#### Parameters
`callable|string` $path `int` $order optional `int` $sort optional #### Returns
`self`
### stopWhen() public
```
stopWhen(callable|array $condition): self
```
Creates a new collection that when iterated will stop yielding results if the provided condition evaluates to true.
This is handy for dealing with infinite iterators or any generator that could start returning invalid elements at a certain point. For example, when reading lines from a file stream you may want to stop the iteration after a certain value is reached.
### Example:
Get an array of lines in a CSV file until the timestamp column is less than a date
```
$lines = (new Collection($fileLines))->stopWhen(function ($value, $key) {
return (new DateTime($value))->format('Y') < 2012;
})
->toArray();
```
Get elements until the first unapproved message is found:
```
$comments = (new Collection($comments))->stopWhen(['is_approved' => false]);
```
#### Parameters
`callable|array` $condition #### Returns
`self`
### sumOf() public
```
sumOf(callable|string|null $path = null): float|int
```
Returns the total sum of all the values extracted with $matcher or of this collection.
### Example:
```
$items = [
['invoice' => ['total' => 100]],
['invoice' => ['total' => 200]]
];
$total = (new Collection($items))->sumOf('invoice.total');
// Total: 300
$total = (new Collection([1, 2, 3]))->sumOf();
// Total: 6
```
#### Parameters
`callable|string|null` $path optional #### Returns
`float|int`
### take() public
```
take(int $length = 1, int $offset = 0): self
```
Returns a new collection with maximum $size elements in the internal order this collection was created. If a second parameter is passed, it will determine from what position to start taking elements.
#### Parameters
`int` $length optional `int` $offset optional #### Returns
`self`
### takeLast() public
```
takeLast(int $length): self
```
Returns the last N elements of a collection
### Example:
```
$items = [1, 2, 3, 4, 5];
$last = (new Collection($items))->takeLast(3);
// Result will look like this when converted to array
[3, 4, 5];
```
#### Parameters
`int` $length #### Returns
`self`
### through() public
```
through(callable $callback): self
```
Passes this collection through a callable as its first argument. This is useful for decorating the full collection with another object.
### Example:
```
$items = [1, 2, 3];
$decorated = (new Collection($items))->through(function ($collection) {
return new MyCustomCollection($collection);
});
```
#### Parameters
`callable` $callback #### Returns
`self`
### toArray() public
```
toArray(bool $keepKeys = true): array
```
Returns an array representation of the results
#### Parameters
`bool` $keepKeys optional #### Returns
`array`
### toList() public
```
toList(): array
```
Returns an numerically-indexed array representation of the results. This is equivalent to calling `toArray(false)`
#### Returns
`array`
### transpose() public
```
transpose(): Cake\Collection\CollectionInterface
```
Transpose rows and columns into columns and rows
### Example:
```
$items = [
['Products', '2012', '2013', '2014'],
['Product A', '200', '100', '50'],
['Product B', '300', '200', '100'],
['Product C', '400', '300', '200'],
]
$transpose = (new Collection($items))->transpose()->toList();
// Returns
// [
// ['Products', 'Product A', 'Product B', 'Product C'],
// ['2012', '200', '300', '400'],
// ['2013', '100', '200', '300'],
// ['2014', '50', '100', '200'],
// ]
```
#### Returns
`Cake\Collection\CollectionInterface`
#### Throws
`LogicException`
### unfold() public
```
unfold(callable|null $callback = null): self
```
Creates a new collection where the items are the concatenation of the lists of items generated by the transformer function applied to each item in the original collection.
The transformer function will receive the value and the key for each of the items in the collection, in that order, and it must return an array or a Traversable object that can be concatenated to the final result.
If no transformer function is passed, an "identity" function will be used. This is useful when each of the elements in the source collection are lists of items to be appended one after another.
### Example:
```
$items [[1, 2, 3], [4, 5]];
$unfold = (new Collection($items))->unfold(); // Returns [1, 2, 3, 4, 5]
```
Using a transformer
```
$items [1, 2, 3];
$allItems = (new Collection($items))->unfold(function ($page) {
return $service->fetchPage($page)->toArray();
});
```
#### Parameters
`callable|null` $callback optional #### Returns
`self`
### unserialize() public
```
unserialize(string $collection): void
```
Unserializes the passed string and rebuilds the Collection instance
#### Parameters
`string` $collection The serialized collection
#### Returns
`void`
### unwrap() public
```
unwrap(): Traversable
```
Returns the closest nested iterator that can be safely traversed without losing any possible transformations. This is used mainly to remove empty IteratorIterator wrappers that can only slowdown the iteration process.
#### Returns
`Traversable`
### zip() public
```
zip(iterable $items): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
### Example:
```
$collection = new Collection([1, 2]);
$collection->zip([3, 4], [5, 6])->toList(); // returns [[1, 3, 5], [2, 4, 6]]
```
#### Parameters
`iterable` $items #### Returns
`self`
### zipWith() public
```
zipWith(iterable $items, callable $callback): self
```
Combines the elements of this collection with each of the elements of the passed iterables, using their positional index as a reference.
The resulting element will be the return value of the $callable function.
### Example:
```
$collection = new Collection([1, 2]);
$zipped = $collection->zipWith([3, 4], [5, 6], function (...$args) {
return array_sum($args);
});
$zipped->toList(); // returns [9, 12]; [(1 + 3 + 5), (2 + 4 + 6)]
```
#### Parameters
`iterable` $items `callable` $callback #### Returns
`self`
Property Detail
---------------
### $\_callback protected
The callback function to be used to transform values
#### Type
`callable`
### $\_innerIterator protected
A reference to the internal iterator this object is wrapping.
#### Type
`Traversable`
| programming_docs |
cakephp Namespace Exception Namespace Exception
===================
### Classes
* ##### [CakeException](class-cake.core.exception.cakeexception)
Base class that all CakePHP Exceptions extend.
* ##### [MissingPluginException](class-cake.core.exception.missingpluginexception)
Exception raised when a plugin could not be found
cakephp Class BoolType Class BoolType
===============
Bool type converter.
Use to convert bool data between PHP and the database types.
**Namespace:** [Cake\Database\Type](namespace-cake.database.type)
Property Summary
----------------
* [$\_name](#%24_name) protected `string|null` Identifier name for this type
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [getBaseType()](#getBaseType()) public
Returns the base type name that this class is inheriting.
* ##### [getName()](#getName()) public
Returns type identifier name for this object.
* ##### [manyToPHP()](#manyToPHP()) public
Returns an array of the values converted to the PHP representation of this type.
* ##### [marshal()](#marshal()) public
Marshals request data into PHP booleans.
* ##### [newId()](#newId()) public
Generate a new primary key value for a given type.
* ##### [toDatabase()](#toDatabase()) public
Convert bool data into the database format.
* ##### [toPHP()](#toPHP()) public
Convert bool values to PHP booleans
* ##### [toStatement()](#toStatement()) public
Get the correct PDO binding type for bool data.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $name = null)
```
Constructor
#### Parameters
`string|null` $name optional The name identifying this type
### getBaseType() public
```
getBaseType(): string|null
```
Returns the base type name that this class is inheriting.
This is useful when extending base type for adding extra functionality, but still want the rest of the framework to use the same assumptions it would do about the base type it inherits from.
#### Returns
`string|null`
### getName() public
```
getName(): string|null
```
Returns type identifier name for this object.
#### Returns
`string|null`
### manyToPHP() public
```
manyToPHP(array $values, array<string> $fields, Cake\Database\DriverInterface $driver): array<string, mixed>
```
Returns an array of the values converted to the PHP representation of this type.
#### Parameters
`array` $values `array<string>` $fields `Cake\Database\DriverInterface` $driver #### Returns
`array<string, mixed>`
### marshal() public
```
marshal(mixed $value): bool|null
```
Marshals request data into PHP booleans.
Most useful for converting request data into PHP objects, that make sense for the rest of the ORM/Database layers.
#### Parameters
`mixed` $value The value to convert.
#### Returns
`bool|null`
### newId() public
```
newId(): mixed
```
Generate a new primary key value for a given type.
This method can be used by types to create new primary key values when entities are inserted.
#### Returns
`mixed`
### toDatabase() public
```
toDatabase(mixed $value, Cake\Database\DriverInterface $driver): bool|null
```
Convert bool data into the database format.
#### Parameters
`mixed` $value The value to convert.
`Cake\Database\DriverInterface` $driver The driver instance to convert with.
#### Returns
`bool|null`
### toPHP() public
```
toPHP(mixed $value, Cake\Database\DriverInterface $driver): bool|null
```
Convert bool values to PHP booleans
#### Parameters
`mixed` $value The value to convert.
`Cake\Database\DriverInterface` $driver The driver instance to convert with.
#### Returns
`bool|null`
### toStatement() public
```
toStatement(mixed $value, Cake\Database\DriverInterface $driver): int
```
Get the correct PDO binding type for bool data.
#### Parameters
`mixed` $value The value being bound.
`Cake\Database\DriverInterface` $driver The driver.
#### Returns
`int`
Property Detail
---------------
### $\_name protected
Identifier name for this type
#### Type
`string|null`
cakephp Class CommandCollection Class CommandCollection
========================
Collection for Commands.
Used by Applications to specify their console commands. CakePHP will use the mapped commands to construct and dispatch shell commands.
**Namespace:** [Cake\Console](namespace-cake.console)
Property Summary
----------------
* [$commands](#%24commands) protected `array<string,Cake\Console\ShellCake\Console\CommandInterface|string>` Command list
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [add()](#add()) public
Add a command to the collection
* ##### [addMany()](#addMany()) public
Add multiple commands at once.
* ##### [autoDiscover()](#autoDiscover()) public
Automatically discover shell commands in CakePHP, the application and all plugins.
* ##### [count()](#count()) public
Implementation of Countable.
* ##### [discoverPlugin()](#discoverPlugin()) public
Auto-discover shell & commands from the named plugin.
* ##### [get()](#get()) public
Get the target for a command.
* ##### [getIterator()](#getIterator()) public
Implementation of IteratorAggregate.
* ##### [has()](#has()) public
Check whether the named shell exists in the collection.
* ##### [keys()](#keys()) public
Get the list of available command names.
* ##### [remove()](#remove()) public
Remove a command from the collection if it exists.
* ##### [resolveNames()](#resolveNames()) protected
Resolve names based on existing commands
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string,Cake\Console\ShellCake\Console\CommandInterface|string> $commands = [])
```
Constructor
#### Parameters
`array<string,Cake\Console\ShellCake\Console\CommandInterface|string>` $commands optional The map of commands to add to the collection.
### add() public
```
add(string $name, Cake\Console\CommandInterfaceCake\Console\Shell|string $command): $this
```
Add a command to the collection
#### Parameters
`string` $name The name of the command you want to map.
`Cake\Console\CommandInterfaceCake\Console\Shell|string` $command The command to map. Can be a FQCN, Shell instance or CommandInterface instance.
#### Returns
`$this`
#### Throws
`InvalidArgumentException`
### addMany() public
```
addMany(array<string,Cake\Console\ShellCake\Console\CommandInterface|string> $commands): $this
```
Add multiple commands at once.
#### Parameters
`array<string,Cake\Console\ShellCake\Console\CommandInterface|string>` $commands A map of command names => command classes/instances.
#### Returns
`$this`
#### See Also
\Cake\Console\CommandCollection::add() ### autoDiscover() public
```
autoDiscover(): array<string, string>
```
Automatically discover shell commands in CakePHP, the application and all plugins.
Commands will be located using filesystem conventions. Commands are discovered in the following order:
* CakePHP provided commands
* Application commands
Commands defined in the application will overwrite commands with the same name provided by CakePHP.
#### Returns
`array<string, string>`
### count() public
```
count(): int
```
Implementation of Countable.
Get the number of commands in the collection.
#### Returns
`int`
### discoverPlugin() public
```
discoverPlugin(string $plugin): array<string, string>
```
Auto-discover shell & commands from the named plugin.
Discovered commands will have their names de-duplicated with existing commands in the collection. If a command is already defined in the collection and discovered in a plugin, only the long name (`plugin.command`) will be returned.
#### Parameters
`string` $plugin The plugin to scan.
#### Returns
`array<string, string>`
### get() public
```
get(string $name): Cake\Console\CommandInterfaceCake\Console\Shell|string
```
Get the target for a command.
#### Parameters
`string` $name The named shell.
#### Returns
`Cake\Console\CommandInterfaceCake\Console\Shell|string`
#### Throws
`InvalidArgumentException`
when unknown commands are fetched. ### getIterator() public
```
getIterator(): Traversable
```
Implementation of IteratorAggregate.
#### Returns
`Traversable`
### has() public
```
has(string $name): bool
```
Check whether the named shell exists in the collection.
#### Parameters
`string` $name The named shell.
#### Returns
`bool`
### keys() public
```
keys(): array<string>
```
Get the list of available command names.
#### Returns
`array<string>`
### remove() public
```
remove(string $name): $this
```
Remove a command from the collection if it exists.
#### Parameters
`string` $name The named shell.
#### Returns
`$this`
### resolveNames() protected
```
resolveNames(array $input): array<string, string>
```
Resolve names based on existing commands
#### Parameters
`array` $input The results of a CommandScanner operation.
#### Returns
`array<string, string>`
Property Detail
---------------
### $commands protected
Command list
#### Type
`array<string,Cake\Console\ShellCake\Console\CommandInterface|string>`
cakephp Class Number Class Number
=============
Number helper library.
Methods to make numbers more readable.
**Namespace:** [Cake\I18n](namespace-cake.i18n)
**Link:** https://book.cakephp.org/4/en/core-libraries/number.html
Constants
---------
* `int` **CURRENCY\_ACCOUNTING**
```
12
```
ICU Constant for accounting format; not yet widely supported by INTL library. This will be able to go away once CakePHP minimum PHP requirement is 7.4.1 or higher. See UNUM\_CURRENCY\_ACCOUNTING in <https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/unum_8h.html>
* `string` **DEFAULT\_LOCALE**
```
'en_US'
```
Default locale
* `string` **FORMAT\_CURRENCY**
```
'currency'
```
Format type to format as currency
* `string` **FORMAT\_CURRENCY\_ACCOUNTING**
```
'currency_accounting'
```
Format type to format as currency, accounting style (negative numbers in parentheses)
Property Summary
----------------
* [$\_defaultCurrency](#%24_defaultCurrency) protected static `string|null` Default currency used by Number::currency()
* [$\_defaultCurrencyFormat](#%24_defaultCurrencyFormat) protected static `string|null` Default currency format used by Number::currency()
* [$\_formatters](#%24_formatters) protected static `array<string, array<int, mixed>>` A list of number formatters indexed by locale and type
Method Summary
--------------
* ##### [\_setAttributes()](#_setAttributes()) protected static
Set formatter attributes
* ##### [config()](#config()) public static
Configure formatters.
* ##### [currency()](#currency()) public static
Formats a number into a currency format.
* ##### [defaultCurrency()](#defaultCurrency()) public static deprecated
Getter/setter for default currency. This behavior is *deprecated* and will be removed in future versions of CakePHP.
* ##### [format()](#format()) public static
Formats a number into the correct locale format
* ##### [formatDelta()](#formatDelta()) public static
Formats a number into the correct locale format to show deltas (signed differences in value).
* ##### [formatter()](#formatter()) public static
Returns a formatter object that can be reused for similar formatting task under the same locale and options. This is often a speedier alternative to using other methods in this class as only one formatter object needs to be constructed.
* ##### [getDefaultCurrency()](#getDefaultCurrency()) public static
Getter for default currency
* ##### [getDefaultCurrencyFormat()](#getDefaultCurrencyFormat()) public static
Getter for default currency format
* ##### [ordinal()](#ordinal()) public static
Returns a formatted integer as an ordinal number string (e.g. 1st, 2nd, 3rd, 4th, [...])
* ##### [parseFloat()](#parseFloat()) public static
Parse a localized numeric string and transform it in a float point
* ##### [precision()](#precision()) public static
Formats a number with a level of precision.
* ##### [setDefaultCurrency()](#setDefaultCurrency()) public static
Setter for default currency
* ##### [setDefaultCurrencyFormat()](#setDefaultCurrencyFormat()) public static
Setter for default currency format
* ##### [toPercentage()](#toPercentage()) public static
Formats a number into a percentage string.
* ##### [toReadableSize()](#toReadableSize()) public static
Returns a formatted-for-humans file size.
Method Detail
-------------
### \_setAttributes() protected static
```
_setAttributes(NumberFormatter $formatter, array<string, mixed> $options = []): NumberFormatter
```
Set formatter attributes
#### Parameters
`NumberFormatter` $formatter Number formatter instance.
`array<string, mixed>` $options optional See Number::formatter() for possible options.
#### Returns
`NumberFormatter`
### config() public static
```
config(string $locale, int $type = NumberFormatter::DECIMAL, array<string, mixed> $options = []): void
```
Configure formatters.
#### Parameters
`string` $locale The locale name to use for formatting the number, e.g. fr\_FR
`int` $type optional The formatter type to construct. Defaults to NumberFormatter::DECIMAL.
`array<string, mixed>` $options optional See Number::formatter() for possible options.
#### Returns
`void`
### currency() public static
```
currency(string|float $value, string|null $currency = null, array<string, mixed> $options = []): string
```
Formats a number into a currency format.
### Options
* `locale` - The locale name to use for formatting the number, e.g. fr\_FR
* `fractionSymbol` - The currency symbol to use for fractional numbers.
* `fractionPosition` - The position the fraction symbol should be placed valid options are 'before' & 'after'.
* `before` - Text to display before the rendered number
* `after` - Text to display after the rendered number
* `zero` - The text to use for zero values, can be a string or a number. e.g. 0, 'Free!'
* `places` - Number of decimal places to use. e.g. 2
* `precision` - Maximum Number of decimal places to use, e.g. 2
* `pattern` - An ICU number pattern to use for formatting the number. e.g #,##0.00
* `useIntlCode` - Whether to replace the currency symbol with the international currency code.
#### Parameters
`string|float` $value Value to format.
`string|null` $currency optional International currency name such as 'USD', 'EUR', 'JPY', 'CAD'
`array<string, mixed>` $options optional Options list.
#### Returns
`string`
### defaultCurrency() public static
```
defaultCurrency(string|false|null $currency = null): string|null
```
Getter/setter for default currency. This behavior is *deprecated* and will be removed in future versions of CakePHP.
#### Parameters
`string|false|null` $currency optional Default currency string to be used by {@link currency()} if $currency argument is not provided. If boolean false is passed, it will clear the currently stored value
#### Returns
`string|null`
### format() public static
```
format(string|int|float $value, array<string, mixed> $options = []): string
```
Formats a number into the correct locale format
Options:
* `places` - Minimum number or decimals to use, e.g 0
* `precision` - Maximum Number of decimal places to use, e.g. 2
* `pattern` - An ICU number pattern to use for formatting the number. e.g #,##0.00
* `locale` - The locale name to use for formatting the number, e.g. fr\_FR
* `before` - The string to place before whole numbers, e.g. '['
* `after` - The string to place after decimal numbers, e.g. ']'
#### Parameters
`string|int|float` $value A floating point number.
`array<string, mixed>` $options optional An array with options.
#### Returns
`string`
### formatDelta() public static
```
formatDelta(string|float $value, array<string, mixed> $options = []): string
```
Formats a number into the correct locale format to show deltas (signed differences in value).
### Options
* `places` - Minimum number or decimals to use, e.g 0
* `precision` - Maximum Number of decimal places to use, e.g. 2
* `locale` - The locale name to use for formatting the number, e.g. fr\_FR
* `before` - The string to place before whole numbers, e.g. '['
* `after` - The string to place after decimal numbers, e.g. ']'
#### Parameters
`string|float` $value A floating point number
`array<string, mixed>` $options optional Options list.
#### Returns
`string`
### formatter() public static
```
formatter(array<string, mixed> $options = []): NumberFormatter
```
Returns a formatter object that can be reused for similar formatting task under the same locale and options. This is often a speedier alternative to using other methods in this class as only one formatter object needs to be constructed.
### Options
* `locale` - The locale name to use for formatting the number, e.g. fr\_FR
* `type` - The formatter type to construct, set it to `currency` if you need to format numbers representing money or a NumberFormatter constant.
* `places` - Number of decimal places to use. e.g. 2
* `precision` - Maximum Number of decimal places to use, e.g. 2
* `pattern` - An ICU number pattern to use for formatting the number. e.g #,##0.00
* `useIntlCode` - Whether to replace the currency symbol with the international currency code.
#### Parameters
`array<string, mixed>` $options optional An array with options.
#### Returns
`NumberFormatter`
### getDefaultCurrency() public static
```
getDefaultCurrency(): string
```
Getter for default currency
#### Returns
`string`
### getDefaultCurrencyFormat() public static
```
getDefaultCurrencyFormat(): string
```
Getter for default currency format
#### Returns
`string`
### ordinal() public static
```
ordinal(float|int $value, array<string, mixed> $options = []): string
```
Returns a formatted integer as an ordinal number string (e.g. 1st, 2nd, 3rd, 4th, [...])
### Options
* `type` - The formatter type to construct, set it to `currency` if you need to format numbers representing money or a NumberFormatter constant.
For all other options see formatter().
#### Parameters
`float|int` $value An integer
`array<string, mixed>` $options optional An array with options.
#### Returns
`string`
### parseFloat() public static
```
parseFloat(string $value, array<string, mixed> $options = []): float
```
Parse a localized numeric string and transform it in a float point
Options:
* `locale` - The locale name to use for parsing the number, e.g. fr\_FR
* `type` - The formatter type to construct, set it to `currency` if you need to parse numbers representing money.
#### Parameters
`string` $value A numeric string.
`array<string, mixed>` $options optional An array with options.
#### Returns
`float`
### precision() public static
```
precision(string|float $value, int $precision = 3, array<string, mixed> $options = []): string
```
Formats a number with a level of precision.
Options:
* `locale`: The locale name to use for formatting the number, e.g. fr\_FR
#### Parameters
`string|float` $value A floating point number.
`int` $precision optional The precision of the returned number.
`array<string, mixed>` $options optional Additional options
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/core-libraries/number.html#formatting-floating-point-numbers
### setDefaultCurrency() public static
```
setDefaultCurrency(string|null $currency = null): void
```
Setter for default currency
#### Parameters
`string|null` $currency optional Default currency string to be used by {@link currency()} if $currency argument is not provided. If null is passed, it will clear the currently stored value
#### Returns
`void`
### setDefaultCurrencyFormat() public static
```
setDefaultCurrencyFormat(string|null $currencyFormat = null): void
```
Setter for default currency format
#### Parameters
`string|null` $currencyFormat optional Default currency format to be used by currency() if $currencyFormat argument is not provided. If null is passed, it will clear the currently stored value
#### Returns
`void`
### toPercentage() public static
```
toPercentage(string|float $value, int $precision = 2, array<string, mixed> $options = []): string
```
Formats a number into a percentage string.
Options:
* `multiply`: Multiply the input value by 100 for decimal percentages.
* `locale`: The locale name to use for formatting the number, e.g. fr\_FR
#### Parameters
`string|float` $value A floating point number
`int` $precision optional The precision of the returned number
`array<string, mixed>` $options optional Options
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/core-libraries/number.html#formatting-percentages
### toReadableSize() public static
```
toReadableSize(string|int $size): string
```
Returns a formatted-for-humans file size.
#### Parameters
`string|int` $size Size in bytes
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/core-libraries/number.html#interacting-with-human-readable-values
Property Detail
---------------
### $\_defaultCurrency protected static
Default currency used by Number::currency()
#### Type
`string|null`
### $\_defaultCurrencyFormat protected static
Default currency format used by Number::currency()
#### Type
`string|null`
### $\_formatters protected static
A list of number formatters indexed by locale and type
#### Type
`array<string, array<int, mixed>>`
| programming_docs |
cakephp Namespace Exception Namespace Exception
===================
### Classes
* ##### [MissingCellException](class-cake.view.exception.missingcellexception)
Used when a cell class file cannot be found.
* ##### [MissingCellTemplateException](class-cake.view.exception.missingcelltemplateexception)
Used when a template file for a cell cannot be found.
* ##### [MissingElementException](class-cake.view.exception.missingelementexception)
Used when an element file cannot be found.
* ##### [MissingHelperException](class-cake.view.exception.missinghelperexception)
Used when a helper cannot be found.
* ##### [MissingLayoutException](class-cake.view.exception.missinglayoutexception)
Used when a layout file cannot be found.
* ##### [MissingTemplateException](class-cake.view.exception.missingtemplateexception)
Used when a template file cannot be found.
* ##### [MissingViewException](class-cake.view.exception.missingviewexception)
Used when a view class file cannot be found.
* ##### [SerializationFailureException](class-cake.view.exception.serializationfailureexception)
Used when a SerializedView class fails to serialize data.
cakephp Interface FixtureInterface Interface FixtureInterface
===========================
Defines the interface that testing fixtures use.
**Namespace:** [Cake\Datasource](namespace-cake.datasource)
Method Summary
--------------
* ##### [connection()](#connection()) public
Get the connection name this fixture should be inserted into.
* ##### [create()](#create()) public
Create the fixture schema/mapping/definition
* ##### [drop()](#drop()) public
Run after all tests executed, should remove the table/collection from the connection.
* ##### [insert()](#insert()) public
Run before each test is executed.
* ##### [sourceName()](#sourceName()) public
Get the table/collection name for this fixture.
* ##### [truncate()](#truncate()) public
Truncates the current fixture.
Method Detail
-------------
### connection() public
```
connection(): string
```
Get the connection name this fixture should be inserted into.
#### Returns
`string`
### create() public
```
create(Cake\Datasource\ConnectionInterface $connection): bool
```
Create the fixture schema/mapping/definition
#### Parameters
`Cake\Datasource\ConnectionInterface` $connection An instance of the connection the fixture should be created on.
#### Returns
`bool`
### drop() public
```
drop(Cake\Datasource\ConnectionInterface $connection): bool
```
Run after all tests executed, should remove the table/collection from the connection.
#### Parameters
`Cake\Datasource\ConnectionInterface` $connection An instance of the connection the fixture should be removed from.
#### Returns
`bool`
### insert() public
```
insert(Cake\Datasource\ConnectionInterface $connection): Cake\Database\StatementInterface|bool
```
Run before each test is executed.
Should insert all the records into the test database.
#### Parameters
`Cake\Datasource\ConnectionInterface` $connection An instance of the connection into which the records will be inserted.
#### Returns
`Cake\Database\StatementInterface|bool`
### sourceName() public
```
sourceName(): string
```
Get the table/collection name for this fixture.
#### Returns
`string`
### truncate() public
```
truncate(Cake\Datasource\ConnectionInterface $connection): bool
```
Truncates the current fixture.
#### Parameters
`Cake\Datasource\ConnectionInterface` $connection A reference to a db instance
#### Returns
`bool`
cakephp Class FormAuthenticate Class FormAuthenticate
=======================
Form authentication adapter for AuthComponent.
Allows you to authenticate users based on form POST data. Usually, this is a login form that users enter information into.
### Using Form auth
Load `AuthComponent` in your controller's `initialize()` and add 'Form' in 'authenticate' key
```
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => ['username' => 'email', 'password' => 'passwd'],
'finder' => 'auth',
]
]
]);
```
When configuring FormAuthenticate you can pass in config to which fields, model and finder are used. See `BaseAuthenticate::$_defaultConfig` for more information.
**Namespace:** [Cake\Auth](namespace-cake.auth)
**See:** https://book.cakephp.org/4/en/controllers/components/authentication.html
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this object.
* [$\_needsPasswordRehash](#%24_needsPasswordRehash) protected `bool` Whether the user authenticated by this class requires their password to be rehashed with another algorithm.
* [$\_passwordHasher](#%24_passwordHasher) protected `Cake\Auth\AbstractPasswordHasher|null` Password hasher instance.
* [$\_registry](#%24_registry) protected `Cake\Controller\ComponentRegistry` A Component registry, used to get more components.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_checkFields()](#_checkFields()) protected
Checks the fields to ensure they are supplied.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_findUser()](#_findUser()) protected
Find a user record using the username and password provided.
* ##### [\_query()](#_query()) protected
Get query object for fetching user from database.
* ##### [authenticate()](#authenticate()) public
Authenticates the identity contained in a request. Will use the `config.userModel`, and `config.fields` to find POST data that is used to find a matching record in the `config.userModel`. Will return false if there is no post data, either username or password is missing, or if the scope conditions have not been met.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [getUser()](#getUser()) public
Get a user based on information in the request. Primarily used by stateless authentication systems like basic and digest auth.
* ##### [implementedEvents()](#implementedEvents()) public
Returns a list of all events that this authenticate class will listen to.
* ##### [needsPasswordRehash()](#needsPasswordRehash()) public
Returns whether the password stored in the repository for the logged in user requires to be rehashed with another algorithm
* ##### [passwordHasher()](#passwordHasher()) public
Return password hasher object
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
* ##### [unauthenticated()](#unauthenticated()) public
Handle unauthenticated access attempt. In implementation valid return values can be:
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Controller\ComponentRegistry $registry, array<string, mixed> $config = [])
```
Constructor
#### Parameters
`Cake\Controller\ComponentRegistry` $registry The Component registry used on this request.
`array<string, mixed>` $config optional Array of config to use.
### \_checkFields() protected
```
_checkFields(Cake\Http\ServerRequest $request, array<string, string> $fields): bool
```
Checks the fields to ensure they are supplied.
#### Parameters
`Cake\Http\ServerRequest` $request The request that contains login information.
`array<string, string>` $fields The fields to be checked.
#### Returns
`bool`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_findUser() protected
```
_findUser(string $username, string|null $password = null): array<string, mixed>|false
```
Find a user record using the username and password provided.
Input passwords will be hashed even when a user doesn't exist. This helps mitigate timing attacks that are attempting to find valid usernames.
#### Parameters
`string` $username The username/identifier.
`string|null` $password optional The password, if not provided password checking is skipped and result of find is returned.
#### Returns
`array<string, mixed>|false`
### \_query() protected
```
_query(string $username): Cake\ORM\Query
```
Get query object for fetching user from database.
#### Parameters
`string` $username The username/identifier.
#### Returns
`Cake\ORM\Query`
### authenticate() public
```
authenticate(Cake\Http\ServerRequest $request, Cake\Http\Response $response): array<string, mixed>|false
```
Authenticates the identity contained in a request. Will use the `config.userModel`, and `config.fields` to find POST data that is used to find a matching record in the `config.userModel`. Will return false if there is no post data, either username or password is missing, or if the scope conditions have not been met.
#### Parameters
`Cake\Http\ServerRequest` $request The request that contains login information.
`Cake\Http\Response` $response Unused response object.
#### Returns
`array<string, mixed>|false`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### getUser() public
```
getUser(Cake\Http\ServerRequest $request): array<string, mixed>|false
```
Get a user based on information in the request. Primarily used by stateless authentication systems like basic and digest auth.
#### Parameters
`Cake\Http\ServerRequest` $request Request object.
#### Returns
`array<string, mixed>|false`
### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Returns a list of all events that this authenticate class will listen to.
An authenticate class can listen to following events fired by AuthComponent:
* `Auth.afterIdentify` - Fired after a user has been identified using one of configured authenticate class. The callback function should have signature like `afterIdentify(EventInterface $event, array $user)` when `$user` is the identified user record.
* `Auth.logout` - Fired when AuthComponent::logout() is called. The callback function should have signature like `logout(EventInterface $event, array $user)` where `$user` is the user about to be logged out.
#### Returns
`array<string, mixed>`
### needsPasswordRehash() public
```
needsPasswordRehash(): bool
```
Returns whether the password stored in the repository for the logged in user requires to be rehashed with another algorithm
#### Returns
`bool`
### passwordHasher() public
```
passwordHasher(): Cake\Auth\AbstractPasswordHasher
```
Return password hasher object
#### Returns
`Cake\Auth\AbstractPasswordHasher`
#### Throws
`RuntimeException`
If password hasher class not found or it does not extend AbstractPasswordHasher ### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
### unauthenticated() public
```
unauthenticated(Cake\Http\ServerRequest $request, Cake\Http\Response $response): Cake\Http\Response|null|void
```
Handle unauthenticated access attempt. In implementation valid return values can be:
* Null - No action taken, AuthComponent should return appropriate response.
* \Cake\Http\Response - A response object, which will cause AuthComponent to simply return that response.
#### Parameters
`Cake\Http\ServerRequest` $request A request object.
`Cake\Http\Response` $response A response object.
#### Returns
`Cake\Http\Response|null|void`
Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this object.
* `fields` The fields to use to identify a user by.
* `userModel` The alias for users table, defaults to Users.
* `finder` The finder method to use to fetch user record. Defaults to 'all'. You can set finder name as string or an array where key is finder name and value is an array passed to `Table::find()` options. E.g. ['finderName' => ['some\_finder\_option' => 'some\_value']]
* `passwordHasher` Password hasher class. Can be a string specifying class name or an array containing `className` key, any other keys will be passed as config to the class. Defaults to 'Default'.
#### Type
`array<string, mixed>`
### $\_needsPasswordRehash protected
Whether the user authenticated by this class requires their password to be rehashed with another algorithm.
#### Type
`bool`
### $\_passwordHasher protected
Password hasher instance.
#### Type
`Cake\Auth\AbstractPasswordHasher|null`
### $\_registry protected
A Component registry, used to get more components.
#### Type
`Cake\Controller\ComponentRegistry`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
cakephp Interface EventDispatcherInterface Interface EventDispatcherInterface
===================================
Objects implementing this interface can emit events.
Objects with this interface can trigger events, and have an event manager retrieved from them.
The {@link \Cake\Event\EventDispatcherTrait} lets you easily implement this interface.
**Namespace:** [Cake\Event](namespace-cake.event)
Method Summary
--------------
* ##### [dispatchEvent()](#dispatchEvent()) public
Wrapper for creating and dispatching events.
* ##### [getEventManager()](#getEventManager()) public
Returns the Cake\Event\EventManager manager instance for this object.
* ##### [setEventManager()](#setEventManager()) public
Sets the Cake\Event\EventManager manager instance for this object.
Method Detail
-------------
### dispatchEvent() public
```
dispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\EventInterface
```
Wrapper for creating and dispatching events.
Returns a dispatched event.
#### Parameters
`string` $name Name of the event.
`array|null` $data optional Any value you wish to be transported with this event to it can be read by listeners.
`object|null` $subject optional The object that this event applies to ($this by default).
#### Returns
`Cake\Event\EventInterface`
### getEventManager() public
```
getEventManager(): Cake\Event\EventManagerInterface
```
Returns the Cake\Event\EventManager manager instance for this object.
#### Returns
`Cake\Event\EventManagerInterface`
### setEventManager() public
```
setEventManager(Cake\Event\EventManagerInterface $eventManager): $this
```
Sets the Cake\Event\EventManager manager 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.
#### Parameters
`Cake\Event\EventManagerInterface` $eventManager the eventManager to set
#### Returns
`$this`
| programming_docs |
cakephp Namespace Exception Namespace Exception
===================
### Classes
* ##### [DuplicateNamedRouteException](class-cake.routing.exception.duplicatenamedrouteexception)
Exception raised when a route names used twice.
* ##### [FailedRouteCacheException](class-cake.routing.exception.failedroutecacheexception)
Thrown when unable to cache route collection.
* ##### [MissingDispatcherFilterException](class-cake.routing.exception.missingdispatcherfilterexception)
Exception raised when a Dispatcher filter could not be found
* ##### [MissingRouteException](class-cake.routing.exception.missingrouteexception)
Exception raised when a URL cannot be reverse routed or when a URL cannot be parsed.
* ##### [RedirectException](class-cake.routing.exception.redirectexception)
An exception subclass used by the routing layer to indicate that a route has resolved to a redirect.
cakephp Class ConsoleExceptionRenderer Class ConsoleExceptionRenderer
===============================
Plain text exception rendering with a stack trace.
Useful in CI or plain text environments.
**Namespace:** [Cake\Error\Renderer](namespace-cake.error.renderer)
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [render()](#render()) public
Render an exception into a plain text message.
* ##### [renderException()](#renderException()) protected
Render an individual exception
* ##### [write()](#write()) public
Write output to the output stream
Method Detail
-------------
### \_\_construct() public
```
__construct(Throwable $error, Psr\Http\Message\ServerRequestInterface|null $request, array $config)
```
Constructor.
#### Parameters
`Throwable` $error The error to render.
`Psr\Http\Message\ServerRequestInterface|null` $request Not used.
`array` $config Error handling configuration.
### render() public
```
render(): Psr\Http\Message\ResponseInterface|string
```
Render an exception into a plain text message.
#### Returns
`Psr\Http\Message\ResponseInterface|string`
### renderException() protected
```
renderException(Throwable $exception, int $index): array
```
Render an individual exception
#### Parameters
`Throwable` $exception The exception to render.
`int` $index Exception index in the chain
#### Returns
`array`
### write() public
```
write(string $output): void
```
Write output to the output stream
#### Parameters
`string` $output The output to print.
#### Returns
`void`
cakephp Class MissingRouteException Class MissingRouteException
============================
Exception raised when a URL cannot be reverse routed or when a URL cannot be parsed.
**Namespace:** [Cake\Routing\Exception](namespace-cake.routing.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_messageTemplateWithMethod](#%24_messageTemplateWithMethod) protected `string` Message template to use when the requested method is included.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message, int|null $code = 404, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|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
`int|null` $code optional The code of the error, is also the HTTP status code for the error. Defaults to 404.
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_messageTemplateWithMethod protected
Message template to use when the requested method is included.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Trait IdGeneratorTrait Trait IdGeneratorTrait
=======================
A trait that provides id generating methods to be used in various widget classes.
**Namespace:** [Cake\View\Helper](namespace-cake.view.helper)
Property Summary
----------------
* [$\_idPrefix](#%24_idPrefix) protected `string|null` Prefix for id attribute.
* [$\_idSuffixes](#%24_idSuffixes) protected `array<string>` A list of id suffixes used in the current rendering.
Method Summary
--------------
* ##### [\_clearIds()](#_clearIds()) protected
Clear the stored ID suffixes.
* ##### [\_domId()](#_domId()) protected
Generate an ID suitable for use in an ID attribute.
* ##### [\_id()](#_id()) protected
Generate an ID attribute for an element.
* ##### [\_idSuffix()](#_idSuffix()) protected
Generate an ID suffix.
Method Detail
-------------
### \_clearIds() protected
```
_clearIds(): void
```
Clear the stored ID suffixes.
#### Returns
`void`
### \_domId() protected
```
_domId(string $value): string
```
Generate an ID suitable for use in an ID attribute.
#### Parameters
`string` $value The value to convert into an ID.
#### Returns
`string`
### \_id() protected
```
_id(string $name, string $val): string
```
Generate an ID attribute for an element.
Ensures that id's for a given set of fields are unique.
#### Parameters
`string` $name The ID attribute name.
`string` $val The ID attribute value.
#### Returns
`string`
### \_idSuffix() protected
```
_idSuffix(string $val): string
```
Generate an ID suffix.
Ensures that id's for a given set of fields are unique.
#### Parameters
`string` $val The ID attribute value.
#### Returns
`string`
Property Detail
---------------
### $\_idPrefix protected
Prefix for id attribute.
#### Type
`string|null`
### $\_idSuffixes protected
A list of id suffixes used in the current rendering.
#### Type
`array<string>`
cakephp Class BasePlugin Class BasePlugin
=================
Base Plugin Class
Every plugin should extend from this class or implement the interfaces and include a plugin class in its src root folder.
**Namespace:** [Cake\Core](namespace-cake.core)
Constants
---------
* `array<string>` **VALID\_HOOKS**
```
['bootstrap', 'console', 'middleware', 'routes', 'services']
```
List of valid hooks.
Property Summary
----------------
* [$bootstrapEnabled](#%24bootstrapEnabled) protected `bool` Do bootstrapping or not
* [$classPath](#%24classPath) protected `string` The class path for this plugin.
* [$configPath](#%24configPath) protected `string` The config path for this plugin.
* [$consoleEnabled](#%24consoleEnabled) protected `bool` Console middleware
* [$middlewareEnabled](#%24middlewareEnabled) protected `bool` Enable middleware
* [$name](#%24name) protected `string` The name of this plugin
* [$path](#%24path) protected `string` The path to this plugin.
* [$routesEnabled](#%24routesEnabled) protected `bool` Load routes or not
* [$servicesEnabled](#%24servicesEnabled) protected `bool` Register container services
* [$templatePath](#%24templatePath) protected `string` The templates path for this plugin.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [bootstrap()](#bootstrap()) public
Load all the application configuration and bootstrap logic.
* ##### [checkHook()](#checkHook()) protected
Check if a hook name is valid
* ##### [console()](#console()) public
Add console commands for the plugin.
* ##### [disable()](#disable()) public
Disables the named hook
* ##### [enable()](#enable()) public
Enables the named hook
* ##### [getClassPath()](#getClassPath()) public
Get the filesystem path to configuration for this plugin
* ##### [getConfigPath()](#getConfigPath()) public
Get the filesystem path to configuration for this plugin
* ##### [getName()](#getName()) public
Get the name of this plugin.
* ##### [getPath()](#getPath()) public
Get the filesystem path to this plugin
* ##### [getTemplatePath()](#getTemplatePath()) public
Get the filesystem path to templates for this plugin
* ##### [initialize()](#initialize()) public
Initialization hook called from constructor.
* ##### [isEnabled()](#isEnabled()) public
Check if the named hook is enabled
* ##### [middleware()](#middleware()) public
Add middleware for the plugin.
* ##### [routes()](#routes()) public
Add routes for the plugin.
* ##### [services()](#services()) public
Register container services for this plugin.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $options = [])
```
Constructor
#### Parameters
`array<string, mixed>` $options optional Options
### bootstrap() public
```
bootstrap(Cake\Core\PluginApplicationInterface $app): void
```
Load all the application configuration and bootstrap logic.
The default implementation of this method will include the `config/bootstrap.php` in the plugin if it exist. You can override this method to replace that behavior.
The host application is provided as an argument. This allows you to load additional plugin dependencies, or attach events.
#### Parameters
`Cake\Core\PluginApplicationInterface` $app #### Returns
`void`
### checkHook() protected
```
checkHook(string $hook): void
```
Check if a hook name is valid
#### Parameters
`string` $hook The hook name to check
#### Returns
`void`
#### Throws
`InvalidArgumentException`
on invalid hooks ### console() public
```
console(Cake\Console\CommandCollection $commands): Cake\Console\CommandCollection
```
Add console commands for the plugin.
#### Parameters
`Cake\Console\CommandCollection` $commands #### Returns
`Cake\Console\CommandCollection`
### disable() public
```
disable(string $hook): $this
```
Disables the named hook
#### Parameters
`string` $hook #### Returns
`$this`
### enable() public
```
enable(string $hook): $this
```
Enables the named hook
#### Parameters
`string` $hook #### Returns
`$this`
### getClassPath() public
```
getClassPath(): string
```
Get the filesystem path to configuration for this plugin
#### Returns
`string`
### getConfigPath() public
```
getConfigPath(): string
```
Get the filesystem path to configuration for this plugin
#### Returns
`string`
### getName() public
```
getName(): string
```
Get the name of this plugin.
#### Returns
`string`
### getPath() public
```
getPath(): string
```
Get the filesystem path to this plugin
#### Returns
`string`
### getTemplatePath() public
```
getTemplatePath(): string
```
Get the filesystem path to templates for this plugin
#### Returns
`string`
### initialize() public
```
initialize(): void
```
Initialization hook called from constructor.
#### Returns
`void`
### isEnabled() public
```
isEnabled(string $hook): bool
```
Check if the named hook is enabled
#### Parameters
`string` $hook #### Returns
`bool`
### middleware() public
```
middleware(Cake\Http\MiddlewareQueue $middlewareQueue): Cake\Http\MiddlewareQueue
```
Add middleware for the plugin.
#### Parameters
`Cake\Http\MiddlewareQueue` $middlewareQueue #### Returns
`Cake\Http\MiddlewareQueue`
### routes() public
```
routes(Cake\Routing\RouteBuilder $routes): void
```
Add routes for the plugin.
The default implementation of this method will include the `config/routes.php` in the plugin if it exists. You can override this method to replace that behavior.
#### Parameters
`Cake\Routing\RouteBuilder` $routes #### Returns
`void`
### services() public
```
services(Cake\Core\ContainerInterface $container): void
```
Register container services for this plugin.
#### Parameters
`Cake\Core\ContainerInterface` $container The container to add services to.
#### Returns
`void`
Property Detail
---------------
### $bootstrapEnabled protected
Do bootstrapping or not
#### Type
`bool`
### $classPath protected
The class path for this plugin.
#### Type
`string`
### $configPath protected
The config path for this plugin.
#### Type
`string`
### $consoleEnabled protected
Console middleware
#### Type
`bool`
### $middlewareEnabled protected
Enable middleware
#### Type
`bool`
### $name protected
The name of this plugin
#### Type
`string`
### $path protected
The path to this plugin.
#### Type
`string`
### $routesEnabled protected
Load routes or not
#### Type
`bool`
### $servicesEnabled protected
Register container services
#### Type
`bool`
### $templatePath protected
The templates path for this plugin.
#### Type
`string`
cakephp Class SqliteCompiler Class SqliteCompiler
=====================
Responsible for compiling a Query object into its SQL representation for SQLite
**Namespace:** [Cake\Database](namespace-cake.database)
Property Summary
----------------
* [$\_deleteParts](#%24_deleteParts) protected `array<string>` The list of query clauses to traverse for generating a DELETE statement
* [$\_insertParts](#%24_insertParts) protected `array<string>` The list of query clauses to traverse for generating an INSERT statement
* [$\_orderedUnion](#%24_orderedUnion) protected `bool` SQLite does not support ORDER BY in UNION queries.
* [$\_quotedSelectAliases](#%24_quotedSelectAliases) protected `bool` Indicate whether aliases in SELECT clause need to be always quoted.
* [$\_selectParts](#%24_selectParts) protected `array<string>` The list of query clauses to traverse for generating a SELECT statement
* [$\_templates](#%24_templates) protected `array<string, string>` List of sprintf templates that will be used for compiling the SQL for this query. There are some clauses that can be built as just as the direct concatenation of the internal parts, those are listed here.
* [$\_updateParts](#%24_updateParts) protected `array<string>` The list of query clauses to traverse for generating an UPDATE statement
Method Summary
--------------
* ##### [\_buildFromPart()](#_buildFromPart()) protected
Helper function used to build the string representation of a FROM clause, it constructs the tables list taking care of aliasing and converting expression objects to string.
* ##### [\_buildInsertPart()](#_buildInsertPart()) protected
Builds the SQL fragment for INSERT INTO.
* ##### [\_buildJoinPart()](#_buildJoinPart()) protected
Helper function used to build the string representation of multiple JOIN clauses, it constructs the joins list taking care of aliasing and converting expression objects to string in both the table to be joined and the conditions to be used.
* ##### [\_buildModifierPart()](#_buildModifierPart()) protected
Builds the SQL modifier fragment
* ##### [\_buildSelectPart()](#_buildSelectPart()) protected
Helper function used to build the string representation of a SELECT clause, it constructs the field list taking care of aliasing and converting expression objects to string. This function also constructs the DISTINCT clause for the query.
* ##### [\_buildSetPart()](#_buildSetPart()) protected
Helper function to generate SQL for SET expressions.
* ##### [\_buildUnionPart()](#_buildUnionPart()) protected
Builds the SQL string for all the UNION clauses in this query, when dealing with query objects it will also transform them using their configured SQL dialect.
* ##### [\_buildUpdatePart()](#_buildUpdatePart()) protected
Builds the SQL fragment for UPDATE.
* ##### [\_buildValuesPart()](#_buildValuesPart()) protected
Builds the SQL fragment for INSERT INTO.
* ##### [\_buildWindowPart()](#_buildWindowPart()) protected
Helper function to build the string representation of a window clause.
* ##### [\_buildWithPart()](#_buildWithPart()) protected
Helper function used to build the string representation of a `WITH` clause, it constructs the CTE definitions list and generates the `RECURSIVE` keyword when required.
* ##### [\_sqlCompiler()](#_sqlCompiler()) protected
Returns a callable object that can be used to compile a SQL string representation of this query.
* ##### [\_stringifyExpressions()](#_stringifyExpressions()) protected
Helper function used to covert ExpressionInterface objects inside an array into their string representation.
* ##### [compile()](#compile()) public
Returns the SQL representation of the provided query after generating the placeholders for the bound values using the provided generator
Method Detail
-------------
### \_buildFromPart() protected
```
_buildFromPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Helper function used to build the string representation of a FROM clause, it constructs the tables list taking care of aliasing and converting expression objects to string.
#### Parameters
`array` $parts list of tables to be transformed to string
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildInsertPart() protected
```
_buildInsertPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Builds the SQL fragment for INSERT INTO.
#### Parameters
`array` $parts The insert parts.
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildJoinPart() protected
```
_buildJoinPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Helper function used to build the string representation of multiple JOIN clauses, it constructs the joins list taking care of aliasing and converting expression objects to string in both the table to be joined and the conditions to be used.
#### Parameters
`array` $parts list of joins to be transformed to string
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildModifierPart() protected
```
_buildModifierPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Builds the SQL modifier fragment
#### Parameters
`array` $parts The query modifier parts
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildSelectPart() protected
```
_buildSelectPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Helper function used to build the string representation of a SELECT clause, it constructs the field list taking care of aliasing and converting expression objects to string. This function also constructs the DISTINCT clause for the query.
#### Parameters
`array` $parts list of fields to be transformed to string
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildSetPart() protected
```
_buildSetPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Helper function to generate SQL for SET expressions.
#### Parameters
`array` $parts List of keys & values to set.
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildUnionPart() protected
```
_buildUnionPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Builds the SQL string for all the UNION clauses in this query, when dealing with query objects it will also transform them using their configured SQL dialect.
#### Parameters
`array` $parts list of queries to be operated with UNION
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildUpdatePart() protected
```
_buildUpdatePart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Builds the SQL fragment for UPDATE.
#### Parameters
`array` $parts The update parts.
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildValuesPart() protected
```
_buildValuesPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Builds the SQL fragment for INSERT INTO.
#### Parameters
`array` $parts The values parts.
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildWindowPart() protected
```
_buildWindowPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Helper function to build the string representation of a window clause.
#### Parameters
`array` $parts List of windows to be transformed to string
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_buildWithPart() protected
```
_buildWithPart(array $parts, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Helper function used to build the string representation of a `WITH` clause, it constructs the CTE definitions list and generates the `RECURSIVE` keyword when required.
#### Parameters
`array` $parts List of CTEs to be transformed to string
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`string`
### \_sqlCompiler() protected
```
_sqlCompiler(string $sql, Cake\Database\Query $query, Cake\Database\ValueBinder $binder): Closure
```
Returns a callable object that can be used to compile a SQL string representation of this query.
#### Parameters
`string` $sql initial sql string to append to
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
#### Returns
`Closure`
### \_stringifyExpressions() protected
```
_stringifyExpressions(array $expressions, Cake\Database\ValueBinder $binder, bool $wrap = true): array
```
Helper function used to covert ExpressionInterface objects inside an array into their string representation.
#### Parameters
`array` $expressions list of strings and ExpressionInterface objects
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholder
`bool` $wrap optional Whether to wrap each expression object with parenthesis
#### Returns
`array`
### compile() public
```
compile(Cake\Database\Query $query, Cake\Database\ValueBinder $binder): string
```
Returns the SQL representation of the provided query after generating the placeholders for the bound values using the provided generator
#### Parameters
`Cake\Database\Query` $query The query that is being compiled
`Cake\Database\ValueBinder` $binder Value binder used to generate parameter placeholders
#### Returns
`string`
Property Detail
---------------
### $\_deleteParts protected
The list of query clauses to traverse for generating a DELETE statement
#### Type
`array<string>`
### $\_insertParts protected
The list of query clauses to traverse for generating an INSERT statement
#### Type
`array<string>`
### $\_orderedUnion protected
SQLite does not support ORDER BY in UNION queries.
Overridden in subclasses.
#### Type
`bool`
### $\_quotedSelectAliases protected
Indicate whether aliases in SELECT clause need to be always quoted.
#### Type
`bool`
### $\_selectParts protected
The list of query clauses to traverse for generating a SELECT statement
#### Type
`array<string>`
### $\_templates protected
List of sprintf templates that will be used for compiling the SQL for this query. There are some clauses that can be built as just as the direct concatenation of the internal parts, those are listed here.
#### Type
`array<string, string>`
### $\_updateParts protected
The list of query clauses to traverse for generating an UPDATE statement
#### Type
`array<string>`
| programming_docs |
cakephp Class MailContainsText Class MailContainsText
=======================
MailContainsText
**Namespace:** [Cake\TestSuite\Constraint\Email](namespace-cake.testsuite.constraint.email)
Property Summary
----------------
* [$at](#%24at) protected `int|null`
* [$type](#%24type) protected `string|null` Mail type to check contents of
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [getAssertedMessages()](#getAssertedMessages()) protected
Returns the type-dependent strings of all messages respects $this->at
* ##### [getMessages()](#getMessages()) public
Gets the email or emails to check
* ##### [getTypeMethod()](#getTypeMethod()) protected
* ##### [matches()](#matches()) public
Checks constraint
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message string
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(int|null $at = null): void
```
Constructor
#### Parameters
`int|null` $at optional At
#### Returns
`void`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### getAssertedMessages() protected
```
getAssertedMessages(): string
```
Returns the type-dependent strings of all messages respects $this->at
#### Returns
`string`
### getMessages() public
```
getMessages(): arrayCake\Mailer\Message>
```
Gets the email or emails to check
#### Returns
`arrayCake\Mailer\Message>`
### getTypeMethod() protected
```
getTypeMethod(): string
```
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks constraint
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Constraint check
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message string
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $at protected
#### Type
`int|null`
### $type protected
Mail type to check contents of
#### Type
`string|null`
cakephp Class SessionEquals Class SessionEquals
====================
SessionEquals
**Namespace:** [Cake\TestSuite\Constraint\Session](namespace-cake.testsuite.constraint.session)
Property Summary
----------------
* [$path](#%24path) protected `string`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Returns the description of the failure.
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Compare session value
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(string $path)
```
Constructor
#### Parameters
`string` $path Session Path
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Returns the description of the failure.
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Compare session value
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Value to compare with
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $path protected
#### Type
`string`
cakephp Class MissingComponentException Class MissingComponentException
================================
Used when a component cannot be found.
**Namespace:** [Cake\Controller\Exception](namespace-cake.controller.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
| programming_docs |
cakephp Class LegacySyslogFormatter Class LegacySyslogFormatter
============================
**Namespace:** [Cake\Log\Formatter](namespace-cake.log.formatter)
**Deprecated:** 4.3.0 Create a custom formatter and set it with `formatter` config instead.
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this class
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [format()](#format()) public
Formats message.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [setConfig()](#setConfig()) public
Sets the config.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
#### Parameters
`array<string, mixed>` $config optional Formatter config
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### format() public
```
format(mixed $level, string $message, array $context = []): string
```
Formats message.
#### Parameters
`mixed` $level `string` $message `array` $context optional #### Returns
`string`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this class
#### Type
`array<string, mixed>`
cakephp Interface PluginApplicationInterface Interface PluginApplicationInterface
=====================================
Interface for Applications that leverage plugins & events.
Events can be bound to the application event manager during the application's bootstrap and plugin bootstrap.
**Namespace:** [Cake\Core](namespace-cake.core)
Method Summary
--------------
* ##### [addPlugin()](#addPlugin()) public
Add a plugin to the loaded plugin set.
* ##### [dispatchEvent()](#dispatchEvent()) public
Wrapper for creating and dispatching events.
* ##### [getEventManager()](#getEventManager()) public
Returns the Cake\Event\EventManager manager instance for this object.
* ##### [pluginBootstrap()](#pluginBootstrap()) public
Run bootstrap logic for loaded plugins.
* ##### [pluginConsole()](#pluginConsole()) public
Run console hooks for plugins
* ##### [pluginMiddleware()](#pluginMiddleware()) public
Run middleware hooks for plugins
* ##### [pluginRoutes()](#pluginRoutes()) public
Run routes hooks for loaded plugins
* ##### [setEventManager()](#setEventManager()) public
Sets the Cake\Event\EventManager manager instance for this object.
Method Detail
-------------
### addPlugin() public
```
addPlugin(Cake\Core\PluginInterface|string $name, array<string, mixed> $config = []): $this
```
Add a plugin to the loaded plugin set.
If the named plugin does not exist, or does not define a Plugin class, an instance of `Cake\Core\BasePlugin` will be used. This generated class will have all plugin hooks enabled.
#### Parameters
`Cake\Core\PluginInterface|string` $name The plugin name or plugin object.
`array<string, mixed>` $config optional The configuration data for the plugin if using a string for $name
#### Returns
`$this`
### dispatchEvent() public
```
dispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\EventInterface
```
Wrapper for creating and dispatching events.
Returns a dispatched event.
#### Parameters
`string` $name Name of the event.
`array|null` $data optional Any value you wish to be transported with this event to it can be read by listeners.
`object|null` $subject optional The object that this event applies to ($this by default).
#### Returns
`Cake\Event\EventInterface`
### getEventManager() public
```
getEventManager(): Cake\Event\EventManagerInterface
```
Returns the Cake\Event\EventManager manager instance for this object.
#### Returns
`Cake\Event\EventManagerInterface`
### pluginBootstrap() public
```
pluginBootstrap(): void
```
Run bootstrap logic for loaded plugins.
#### Returns
`void`
### pluginConsole() public
```
pluginConsole(Cake\Console\CommandCollection $commands): Cake\Console\CommandCollection
```
Run console hooks for plugins
#### Parameters
`Cake\Console\CommandCollection` $commands The CommandCollection to use.
#### Returns
`Cake\Console\CommandCollection`
### pluginMiddleware() public
```
pluginMiddleware(Cake\Http\MiddlewareQueue $middleware): Cake\Http\MiddlewareQueue
```
Run middleware hooks for plugins
#### Parameters
`Cake\Http\MiddlewareQueue` $middleware The MiddlewareQueue to use.
#### Returns
`Cake\Http\MiddlewareQueue`
### pluginRoutes() public
```
pluginRoutes(Cake\Routing\RouteBuilder $routes): Cake\Routing\RouteBuilder
```
Run routes hooks for loaded plugins
#### Parameters
`Cake\Routing\RouteBuilder` $routes The route builder to use.
#### Returns
`Cake\Routing\RouteBuilder`
### setEventManager() public
```
setEventManager(Cake\Event\EventManagerInterface $eventManager): $this
```
Sets the Cake\Event\EventManager manager 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.
#### Parameters
`Cake\Event\EventManagerInterface` $eventManager the eventManager to set
#### Returns
`$this`
cakephp Class JsonConfig Class JsonConfig
=================
JSON engine allows Configure to load configuration values from files containing JSON strings.
An example JSON file would look like::
```
{
"debug": false,
"App": {
"namespace": "MyApp"
},
"Security": {
"salt": "its-secret"
}
}
```
**Namespace:** [Cake\Core\Configure\Engine](namespace-cake.core.configure.engine)
Property Summary
----------------
* [$\_extension](#%24_extension) protected `string` File extension.
* [$\_path](#%24_path) protected `string` The path this engine finds files on.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor for JSON Config file reading.
* ##### [\_getFilePath()](#_getFilePath()) protected
Get file path
* ##### [dump()](#dump()) public
Converts the provided $data into a JSON string that can be used saved into a file and loaded later.
* ##### [read()](#read()) public
Read a config file and return its contents.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $path = null)
```
Constructor for JSON Config file reading.
#### Parameters
`string|null` $path optional The path to read config files from. Defaults to CONFIG.
### \_getFilePath() protected
```
_getFilePath(string $key, bool $checkExists = false): string
```
Get file path
#### Parameters
`string` $key The identifier to write to. If the key has a . it will be treated as a plugin prefix.
`bool` $checkExists optional Whether to check if file exists. Defaults to false.
#### Returns
`string`
#### Throws
`Cake\Core\Exception\CakeException`
When files don't exist or when files contain '..' as this could lead to abusive reads. ### dump() public
```
dump(string $key, array $data): bool
```
Converts the provided $data into a JSON string that can be used saved into a file and loaded later.
#### Parameters
`string` $key The identifier to write to. If the key has a . it will be treated as a plugin prefix.
`array` $data Data to dump.
#### Returns
`bool`
### read() public
```
read(string $key): array
```
Read a config file and return its contents.
Files with `.` in the name will be treated as values in plugins. Instead of reading from the initialized path, plugin keys will be located using Plugin::path().
#### Parameters
`string` $key The identifier to read from. If the key has a . it will be treated as a plugin prefix.
#### Returns
`array`
#### Throws
`Cake\Core\Exception\CakeException`
When files don't exist or when files contain '..' (as this could lead to abusive reads) or when there is an error parsing the JSON string. Property Detail
---------------
### $\_extension protected
File extension.
#### Type
`string`
### $\_path protected
The path this engine finds files on.
#### Type
`string`
cakephp Interface EntityInterface Interface EntityInterface
==========================
Describes the methods that any class representing a data storage should comply with.
**Namespace:** [Cake\Datasource](namespace-cake.datasource)
Property Summary
----------------
* [$id](#%24id) public @property `mixed` Alias for commonly used primary key.
Method Summary
--------------
* ##### [clean()](#clean()) public
Sets the entire entity as clean, which means that it will appear as no fields being modified or added at all. This is an useful call for an initial object hydration
* ##### [extract()](#extract()) public
Returns an array with the requested fields stored in this entity, indexed by field name
* ##### [extractOriginal()](#extractOriginal()) public
Returns an array with the requested original fields stored in this entity, indexed by field name.
* ##### [extractOriginalChanged()](#extractOriginalChanged()) public
Returns an array with only the original fields stored in this entity, indexed by field name.
* ##### [get()](#get()) public
Returns the value of a field by name
* ##### [getAccessible()](#getAccessible()) public @method
Accessible configuration for this entity.
* ##### [getDirty()](#getDirty()) public
Gets the dirty fields.
* ##### [getError()](#getError()) public
Returns validation errors of a field
* ##### [getErrors()](#getErrors()) public
Returns all validation errors.
* ##### [getHidden()](#getHidden()) public
Gets the hidden fields.
* ##### [getOriginal()](#getOriginal()) public
Returns the original value of a field.
* ##### [getOriginalValues()](#getOriginalValues()) public
Gets all original values of the entity.
* ##### [getSource()](#getSource()) public
Returns the alias of the repository from which this entity came from.
* ##### [getVirtual()](#getVirtual()) public
Gets the virtual fields on this entity.
* ##### [getVisible()](#getVisible()) public
Get the list of visible fields.
* ##### [has()](#has()) public
Returns whether this entity contains a field named $field and is not set to null.
* ##### [hasErrors()](#hasErrors()) public
Returns whether this entity has errors.
* ##### [isAccessible()](#isAccessible()) public
Checks if a field is accessible
* ##### [isDirty()](#isDirty()) public
Checks if the entity is dirty or if a single field of it is dirty.
* ##### [isNew()](#isNew()) public
Returns whether this entity has already been persisted.
* ##### [set()](#set()) public
Sets one or multiple fields to the specified value
* ##### [setAccess()](#setAccess()) public
Stores whether a field value can be changed or set in this entity.
* ##### [setDirty()](#setDirty()) public
Sets the dirty status of a single field.
* ##### [setError()](#setError()) public
Sets errors for a single field
* ##### [setErrors()](#setErrors()) public
Sets error messages to the entity
* ##### [setHidden()](#setHidden()) public
Sets hidden fields.
* ##### [setNew()](#setNew()) public
Set the status of this entity.
* ##### [setSource()](#setSource()) public
Sets the source alias
* ##### [setVirtual()](#setVirtual()) public
Sets the virtual fields on this entity.
* ##### [toArray()](#toArray()) public
Returns an array with all the visible fields set in this entity.
* ##### [unset()](#unset()) public
Removes a field or list of fields from this entity
Method Detail
-------------
### clean() public
```
clean(): void
```
Sets the entire entity as clean, which means that it will appear as no fields being modified or added at all. This is an useful call for an initial object hydration
#### Returns
`void`
### extract() public
```
extract(array<string> $fields, bool $onlyDirty = false): array
```
Returns an array with the requested fields stored in this entity, indexed by field name
#### Parameters
`array<string>` $fields list of fields to be returned
`bool` $onlyDirty optional Return the requested field only if it is dirty
#### Returns
`array`
### extractOriginal() public
```
extractOriginal(array<string> $fields): array
```
Returns an array with the requested original fields stored in this entity, indexed by field name.
#### Parameters
`array<string>` $fields List of fields to be returned
#### Returns
`array`
### extractOriginalChanged() public
```
extractOriginalChanged(array<string> $fields): array
```
Returns an array with only the original fields stored in this entity, indexed by field name.
#### Parameters
`array<string>` $fields List of fields to be returned
#### Returns
`array`
### get() public
```
get(string $field): mixed
```
Returns the value of a field by name
#### Parameters
`string` $field the name of the field to retrieve
#### Returns
`mixed`
### getAccessible() public @method
```
getAccessible(): bool[]
```
Accessible configuration for this entity.
#### Returns
`bool[]`
### getDirty() public
```
getDirty(): array<string>
```
Gets the dirty fields.
#### Returns
`array<string>`
### getError() public
```
getError(string $field): array
```
Returns validation errors of a field
#### Parameters
`string` $field Field name to get the errors from
#### Returns
`array`
### getErrors() public
```
getErrors(): array
```
Returns all validation errors.
#### Returns
`array`
### getHidden() public
```
getHidden(): array<string>
```
Gets the hidden fields.
#### Returns
`array<string>`
### getOriginal() public
```
getOriginal(string $field): mixed
```
Returns the original value of a field.
#### Parameters
`string` $field The name of the field.
#### Returns
`mixed`
### getOriginalValues() public
```
getOriginalValues(): array
```
Gets all original values of the entity.
#### Returns
`array`
### getSource() public
```
getSource(): string
```
Returns the alias of the repository from which this entity came from.
#### Returns
`string`
### getVirtual() public
```
getVirtual(): array<string>
```
Gets the virtual fields on this entity.
#### Returns
`array<string>`
### getVisible() public
```
getVisible(): array<string>
```
Get the list of visible fields.
#### Returns
`array<string>`
### has() public
```
has(array<string>|string $field): bool
```
Returns whether this entity contains a field named $field and is not set to null.
#### Parameters
`array<string>|string` $field The field to check.
#### Returns
`bool`
### hasErrors() public
```
hasErrors(bool $includeNested = true): bool
```
Returns whether this entity has errors.
#### Parameters
`bool` $includeNested optional true will check nested entities for hasErrors()
#### Returns
`bool`
### isAccessible() public
```
isAccessible(string $field): bool
```
Checks if a field is accessible
#### Parameters
`string` $field Field name to check
#### Returns
`bool`
### isDirty() public
```
isDirty(string|null $field = null): bool
```
Checks if the entity is dirty or if a single field of it is dirty.
#### Parameters
`string|null` $field optional The field to check the status for. Null for the whole entity.
#### Returns
`bool`
### isNew() public
```
isNew(): bool
```
Returns whether this entity has already been persisted.
#### Returns
`bool`
### set() public
```
set(array<string, mixed>|string $field, mixed $value = null, array<string, mixed> $options = []): $this
```
Sets one or multiple fields to the specified value
#### Parameters
`array<string, mixed>|string` $field the name of field to set or a list of fields with their respective values
`mixed` $value optional The value to set to the field or an array if the first argument is also an array, in which case will be treated as $options
`array<string, mixed>` $options optional Options to be used for setting the field. Allowed option keys are `setter` and `guard`
#### Returns
`$this`
### setAccess() public
```
setAccess(array<string>|string $field, bool $set): $this
```
Stores whether a field value can be changed or set in this entity.
#### Parameters
`array<string>|string` $field single or list of fields to change its accessibility
`bool` $set true marks the field as accessible, false will mark it as protected.
#### Returns
`$this`
### setDirty() public
```
setDirty(string $field, bool $isDirty = true): $this
```
Sets the dirty status of a single field.
#### Parameters
`string` $field the field to set or check status for
`bool` $isDirty optional true means the field was changed, false means it was not changed. Default true.
#### Returns
`$this`
### setError() public
```
setError(string $field, array|string $errors, bool $overwrite = false): $this
```
Sets errors for a single field
#### Parameters
`string` $field The field to get errors for, or the array of errors to set.
`array|string` $errors The errors to be set for $field
`bool` $overwrite optional Whether to overwrite pre-existing errors for $field
#### Returns
`$this`
### setErrors() public
```
setErrors(array $errors, bool $overwrite = false): $this
```
Sets error messages to the entity
#### Parameters
`array` $errors The array of errors to set.
`bool` $overwrite optional Whether to overwrite pre-existing errors for $fields
#### Returns
`$this`
### setHidden() public
```
setHidden(array<string> $fields, bool $merge = false): $this
```
Sets hidden fields.
#### Parameters
`array<string>` $fields An array of fields to hide from array exports.
`bool` $merge optional Merge the new fields with the existing. By default false.
#### Returns
`$this`
### setNew() public
```
setNew(bool $new): $this
```
Set the status of this entity.
Using `true` means that the entity has not been persisted in the database, `false` indicates that the entity has been persisted.
#### Parameters
`bool` $new Indicate whether this entity has been persisted.
#### Returns
`$this`
### setSource() public
```
setSource(string $alias): $this
```
Sets the source alias
#### Parameters
`string` $alias the alias of the repository
#### Returns
`$this`
### setVirtual() public
```
setVirtual(array<string> $fields, bool $merge = false): $this
```
Sets the virtual fields on this entity.
#### Parameters
`array<string>` $fields An array of fields to treat as virtual.
`bool` $merge optional Merge the new fields with the existing. By default false.
#### Returns
`$this`
### toArray() public
```
toArray(): array
```
Returns an array with all the visible fields set in this entity.
*Note* hidden fields are not visible, and will not be output by toArray().
#### Returns
`array`
### unset() public
```
unset(array<string>|string $field): $this
```
Removes a field or list of fields from this entity
#### Parameters
`array<string>|string` $field The field to unset.
#### Returns
`$this`
Property Detail
---------------
### $id public @property
Alias for commonly used primary key.
#### Type
`mixed`
| programming_docs |
cakephp Class NullContext Class NullContext
==================
Provides a context provider that does nothing.
This context provider simply fulfils the interface requirements that FormHelper has.
**Namespace:** [Cake\View\Form](namespace-cake.view.form)
Constants
---------
* `array<string>` **VALID\_ATTRIBUTES**
```
['length', 'precision', 'comment', 'null', 'default']
```
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [attributes()](#attributes()) public
Get an associative array of other attributes for a field name.
* ##### [error()](#error()) public
Get the errors for a given field
* ##### [fieldNames()](#fieldNames()) public
Get the field names of the top level object in this context.
* ##### [getMaxLength()](#getMaxLength()) public
Get maximum length of a field from model validation.
* ##### [getPrimaryKey()](#getPrimaryKey()) public
Get the fields used in the context as a primary key.
* ##### [getRequiredMessage()](#getRequiredMessage()) public
Gets the default "required" error message for a field
* ##### [hasError()](#hasError()) public
Check whether a field has an error attached to it
* ##### [isCreate()](#isCreate()) public
Returns whether this form is for a create operation.
* ##### [isPrimaryKey()](#isPrimaryKey()) public
Returns true if the passed field name is part of the primary key for this context
* ##### [isRequired()](#isRequired()) public
Check if a given field is 'required'.
* ##### [primaryKey()](#primaryKey()) public deprecated
Get the fields used in the context as a primary key.
* ##### [type()](#type()) public
Get the abstract field type for a given field name.
* ##### [val()](#val()) public
Get the current value for a given field.
Method Detail
-------------
### \_\_construct() public
```
__construct(array $context)
```
Constructor.
#### Parameters
`array` $context Context info.
### attributes() public
```
attributes(string $field): array
```
Get an associative array of other attributes for a field name.
#### Parameters
`string` $field #### Returns
`array`
### error() public
```
error(string $field): array
```
Get the errors for a given field
#### Parameters
`string` $field #### Returns
`array`
### fieldNames() public
```
fieldNames(): array<string>
```
Get the field names of the top level object in this context.
#### Returns
`array<string>`
### getMaxLength() public
```
getMaxLength(string $field): int|null
```
Get maximum length of a field from model validation.
#### Parameters
`string` $field #### Returns
`int|null`
### getPrimaryKey() public
```
getPrimaryKey(): array<string>
```
Get the fields used in the context as a primary key.
#### Returns
`array<string>`
### getRequiredMessage() public
```
getRequiredMessage(string $field): string|null
```
Gets the default "required" error message for a field
#### Parameters
`string` $field #### Returns
`string|null`
### hasError() public
```
hasError(string $field): bool
```
Check whether a field has an error attached to it
#### Parameters
`string` $field #### Returns
`bool`
### isCreate() public
```
isCreate(): bool
```
Returns whether this form is for a create operation.
#### Returns
`bool`
### isPrimaryKey() public
```
isPrimaryKey(string $field): bool
```
Returns true if the passed field name is part of the primary key for this context
#### Parameters
`string` $field #### Returns
`bool`
### isRequired() public
```
isRequired(string $field): bool|null
```
Check if a given field is 'required'.
In this context class, this is simply defined by the 'required' array.
#### Parameters
`string` $field #### Returns
`bool|null`
### primaryKey() public
```
primaryKey(): array<string>
```
Get the fields used in the context as a primary key.
#### Returns
`array<string>`
### type() public
```
type(string $field): string|null
```
Get the abstract field type for a given field name.
#### Parameters
`string` $field #### Returns
`string|null`
### val() public
```
val(string $field, array<string, mixed> $options = []): mixed
```
Get the current value for a given field.
Classes implementing this method can optionally have a second argument `$options`. Valid key for `$options` array are:
* `default`: Default value to return if no value found in data or context record.
+ `schemaDefault`: Boolean indicating whether default value from context's schema should be used if it's not explicitly provided.
#### Parameters
`string` $field `array<string, mixed>` $options optional #### Returns
`mixed`
cakephp Class FileWidget Class FileWidget
=================
Input widget class for generating a file upload control.
This class is usually used internally by `Cake\View\Helper\FormHelper`, it but can be used to generate standalone file upload controls.
**Namespace:** [Cake\View\Widget](namespace-cake.view.widget)
Property Summary
----------------
* [$\_templates](#%24_templates) protected `Cake\View\StringTemplate` StringTemplate instance.
* [$defaults](#%24defaults) protected `array<string, mixed>` Data defaults.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [mergeDefaults()](#mergeDefaults()) protected
Merge default values with supplied data.
* ##### [render()](#render()) public
Render a file upload form widget.
* ##### [secureFields()](#secureFields()) public
Returns a list of fields that need to be secured for this widget.
* ##### [setMaxLength()](#setMaxLength()) protected
Set value for "maxlength" attribute if applicable.
* ##### [setRequired()](#setRequired()) protected
Set value for "required" attribute if applicable.
* ##### [setStep()](#setStep()) protected
Set value for "step" attribute if applicable.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\View\StringTemplate $templates)
```
Constructor.
#### Parameters
`Cake\View\StringTemplate` $templates Templates list.
### mergeDefaults() protected
```
mergeDefaults(array<string, mixed> $data, Cake\View\Form\ContextInterface $context): array<string, mixed>
```
Merge default values with supplied data.
#### Parameters
`array<string, mixed>` $data Data array
`Cake\View\Form\ContextInterface` $context Context instance.
#### Returns
`array<string, mixed>`
### render() public
```
render(array<string, mixed> $data, Cake\View\Form\ContextInterface $context): string
```
Render a file upload form widget.
Data supports the following keys:
* `name` - Set the input name.
* `escape` - Set to false to disable HTML escaping.
All other keys will be converted into HTML attributes. Unlike other input objects the `val` property will be specifically ignored.
#### Parameters
`array<string, mixed>` $data The data to build a file input with.
`Cake\View\Form\ContextInterface` $context The current form context.
#### Returns
`string`
### secureFields() public
```
secureFields(array<string, mixed> $data): array<string>
```
Returns a list of fields that need to be secured for this widget.
#### Parameters
`array<string, mixed>` $data #### Returns
`array<string>`
### setMaxLength() protected
```
setMaxLength(array<string, mixed> $data, Cake\View\Form\ContextInterface $context, string $fieldName): array<string, mixed>
```
Set value for "maxlength" attribute if applicable.
#### Parameters
`array<string, mixed>` $data Data array
`Cake\View\Form\ContextInterface` $context Context instance.
`string` $fieldName Field name.
#### Returns
`array<string, mixed>`
### setRequired() protected
```
setRequired(array<string, mixed> $data, Cake\View\Form\ContextInterface $context, string $fieldName): array<string, mixed>
```
Set value for "required" attribute if applicable.
#### Parameters
`array<string, mixed>` $data Data array
`Cake\View\Form\ContextInterface` $context Context instance.
`string` $fieldName Field name.
#### Returns
`array<string, mixed>`
### setStep() protected
```
setStep(array<string, mixed> $data, Cake\View\Form\ContextInterface $context, string $fieldName): array<string, mixed>
```
Set value for "step" attribute if applicable.
#### Parameters
`array<string, mixed>` $data Data array
`Cake\View\Form\ContextInterface` $context Context instance.
`string` $fieldName Field name.
#### Returns
`array<string, mixed>`
Property Detail
---------------
### $\_templates protected
StringTemplate instance.
#### Type
`Cake\View\StringTemplate`
### $defaults protected
Data defaults.
#### Type
`array<string, mixed>`
cakephp Class TestExceptionRenderer Class TestExceptionRenderer
============================
Test Exception Renderer.
Use this class if you want to re-throw exceptions that would otherwise be caught by the ErrorHandlerMiddleware. This is useful while debugging or writing integration test cases.
**Namespace:** [Cake\TestSuite\Stub](namespace-cake.testsuite.stub)
**See:** \Cake\TestSuite\IntegrationTestCase::disableErrorHandlerMiddleware()
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Simply rethrow the given exception
* ##### [render()](#render()) public
Render the exception to a string or Http Response.
* ##### [write()](#write()) public
Part of upcoming interface requirements
Method Detail
-------------
### \_\_construct() public
```
__construct(Throwable $exception): void
```
Simply rethrow the given exception
#### Parameters
`Throwable` $exception Exception.
#### Returns
`void`
#### Throws
`Throwable`
$exception Rethrows the passed exception. ### render() public
```
render(): ResponseInterface
```
Render the exception to a string or Http Response.
#### Returns
`ResponseInterface`
### write() public
```
write(Psr\Http\Message\ResponseInterface|string $output): void
```
Part of upcoming interface requirements
#### Parameters
`Psr\Http\Message\ResponseInterface|string` $output The output or response to send.
#### Returns
`void`
cakephp Namespace Helper Namespace Helper
================
### Classes
* ##### [ProgressHelper](class-cake.shell.helper.progresshelper)
Create a progress bar using a supplied callback.
* ##### [TableHelper](class-cake.shell.helper.tablehelper)
Create a visually pleasing ASCII art table from 2 dimensional array data.
cakephp Class Shell Class Shell
============
Base class for command-line utilities for automating programmer chores.
Is the equivalent of Cake\Controller\Controller on the command line.
**Namespace:** [Cake\Console](namespace-cake.console)
**Deprecated:** 3.6.0 ShellDispatcher and Shell will be removed in 5.0
Constants
---------
* `int` **CODE\_ERROR**
```
1
```
Default error code
* `int` **CODE\_SUCCESS**
```
0
```
Default success code
* `int` **NORMAL**
```
ConsoleIo::NORMAL
```
Output constant for making normal shells.
* `int` **QUIET**
```
ConsoleIo::QUIET
```
Output constants for making quiet shells.
* `int` **VERBOSE**
```
ConsoleIo::VERBOSE
```
Output constant making verbose shells.
Property Summary
----------------
* [$OptionParser](#%24OptionParser) public `Cake\Console\ConsoleOptionParser` An instance of ConsoleOptionParser that has been configured for this class.
* [$Tasks](#%24Tasks) public `Cake\Console\TaskRegistry` Task Collection for the command, used to create Tasks.
* [$\_io](#%24_io) protected `Cake\Console\ConsoleIo` ConsoleIo instance.
* [$\_modelFactories](#%24_modelFactories) protected `array<callableCake\Datasource\Locator\LocatorInterface>` A list of overridden model factory functions.
* [$\_modelType](#%24_modelType) protected `string` The model type to use.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$\_taskMap](#%24_taskMap) protected `array<string, array>` Normalized map of tasks.
* [$args](#%24args) public `array` Contains arguments parsed from the command line.
* [$command](#%24command) public `string|null` The command (method/task) that is being run.
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
* [$interactive](#%24interactive) public `bool` If true, the script will ask for permission to perform actions.
* [$modelClass](#%24modelClass) protected deprecated `string|null` This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
* [$name](#%24name) public `string` The name of the shell in camelized.
* [$params](#%24params) public `array` Contains command switches parsed from the command line.
* [$plugin](#%24plugin) public `string` The name of the plugin the shell belongs to. Is automatically set by ShellDispatcher when a shell is constructed.
* [$rootName](#%24rootName) protected `string` The root command name used when generating help output.
* [$taskNames](#%24taskNames) public `array<string>` Contains the loaded tasks
* [$tasks](#%24tasks) public `array|bool` Contains tasks to load and instantiate
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructs this Shell instance.
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_get()](#__get()) public
Overload get for lazy building of tasks
* ##### [\_displayHelp()](#_displayHelp()) protected
Display the help in the correct format
* ##### [\_mergeProperty()](#_mergeProperty()) protected
Merge a single property with the values declared in all parent classes.
* ##### [\_mergePropertyData()](#_mergePropertyData()) protected
Merge each of the keys in a property together.
* ##### [\_mergeVars()](#_mergeVars()) protected
Merge the list of $properties with all parent classes of the current class.
* ##### [\_setModelClass()](#_setModelClass()) protected
Set the modelClass property based on conventions.
* ##### [\_setOutputLevel()](#_setOutputLevel()) protected
Set the output level based on the parameters.
* ##### [\_stop()](#_stop()) protected
Stop execution of the current script. Raises a StopException to try and halt the execution.
* ##### [\_validateTasks()](#_validateTasks()) protected
Checks that the tasks in the task map are actually available
* ##### [\_welcome()](#_welcome()) protected
Displays a header for the shell
* ##### [abort()](#abort()) public
Displays a formatted error message and exits the application with an error code.
* ##### [clear()](#clear()) public
Clear the console
* ##### [createFile()](#createFile()) public
Creates a file at given path
* ##### [dispatchShell()](#dispatchShell()) public
Dispatch a command to another Shell. Similar to Object::requestAction() but intended for running shells from other shells.
* ##### [err()](#err()) public
Outputs a single or multiple error messages to stderr. If no parameters are passed outputs just a newline.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getIo()](#getIo()) public
Get the io object for this shell.
* ##### [getModelType()](#getModelType()) public
Get the model type to be used by this class
* ##### [getOptionParser()](#getOptionParser()) public
Gets the option parser instance and configures it.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [hasMethod()](#hasMethod()) public
Check to see if this shell has a callable method by the given name.
* ##### [hasTask()](#hasTask()) public
Check to see if this shell has a task with the provided name.
* ##### [helper()](#helper()) public
Render a Console Helper
* ##### [hr()](#hr()) public
Outputs a series of minus characters to the standard output, acts as a visual separator.
* ##### [in()](#in()) public
Prompts the user for input, and returns it.
* ##### [info()](#info()) public
Convenience method for out() that wraps message between tag
* ##### [initialize()](#initialize()) public
Initializes the Shell acts as constructor for subclasses allows configuration of tasks prior to shell execution
* ##### [loadModel()](#loadModel()) public deprecated
Loads and constructs repository objects required by this object
* ##### [loadTasks()](#loadTasks()) public
Loads tasks defined in public $tasks
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [main()](#main()) public @method
Main entry method for the shell.
* ##### [modelFactory()](#modelFactory()) public
Override a existing callable to generate repositories of a given type.
* ##### [nl()](#nl()) public
Returns a single or multiple linefeeds sequences.
* ##### [out()](#out()) public
Outputs a single or multiple messages to stdout. If no parameters are passed outputs just a newline.
* ##### [param()](#param()) public
Safely access the values in $this->params.
* ##### [parseDispatchArguments()](#parseDispatchArguments()) public
Parses the arguments for the dispatchShell() method.
* ##### [quiet()](#quiet()) public
Output at all levels.
* ##### [runCommand()](#runCommand()) public
Runs the Shell with the provided argv.
* ##### [setIo()](#setIo()) public
Set the io object for this shell.
* ##### [setModelType()](#setModelType()) public
Set the model type to be used by this class
* ##### [setRootName()](#setRootName()) public
Set the root command name for help output.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
* ##### [shortPath()](#shortPath()) public
Makes absolute file path easier to read
* ##### [startup()](#startup()) public
Starts up the Shell and displays the welcome message. Allows for checking and configuring prior to command or main execution
* ##### [success()](#success()) public
Convenience method for out() that wraps message between tag
* ##### [verbose()](#verbose()) public
Output at the verbose level.
* ##### [warn()](#warn()) public
Convenience method for err() that wraps message between tag
* ##### [wrapText()](#wrapText()) public
Wrap a block of text. Allows you to set the width, and indenting on a block of text.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Console\ConsoleIo|null $io = null, Cake\ORM\Locator\LocatorInterface|null $locator = null)
```
Constructs this Shell instance.
#### Parameters
`Cake\Console\ConsoleIo|null` $io optional An io instance.
`Cake\ORM\Locator\LocatorInterface|null` $locator optional Table locator instance.
#### Links
https://book.cakephp.org/4/en/console-commands/shells.html
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): Cake\Console\Shell
```
Overload get for lazy building of tasks
#### Parameters
`string` $name The task to get.
#### Returns
`Cake\Console\Shell`
### \_displayHelp() protected
```
_displayHelp(string|null $command = null): int|null
```
Display the help in the correct format
#### Parameters
`string|null` $command optional The command to get help for.
#### Returns
`int|null`
### \_mergeProperty() protected
```
_mergeProperty(string $property, array<string> $parentClasses, array<string, mixed> $options): void
```
Merge a single property with the values declared in all parent classes.
#### Parameters
`string` $property The name of the property being merged.
`array<string>` $parentClasses An array of classes you want to merge with.
`array<string, mixed>` $options Options for merging the property, see \_mergeVars()
#### Returns
`void`
### \_mergePropertyData() protected
```
_mergePropertyData(array $current, array $parent, bool $isAssoc): array
```
Merge each of the keys in a property together.
#### Parameters
`array` $current The current merged value.
`array` $parent The parent class' value.
`bool` $isAssoc Whether the merging should be done in associative mode.
#### Returns
`array`
### \_mergeVars() protected
```
_mergeVars(array<string> $properties, array<string, mixed> $options = []): void
```
Merge the list of $properties with all parent classes of the current class.
### Options:
* `associative` - A list of properties that should be treated as associative arrays. Properties in this list will be passed through Hash::normalize() before merging.
#### Parameters
`array<string>` $properties An array of properties and the merge strategy for them.
`array<string, mixed>` $options optional The options to use when merging properties.
#### Returns
`void`
### \_setModelClass() protected
```
_setModelClass(string $name): void
```
Set the modelClass property based on conventions.
If the property is already set it will not be overwritten
#### Parameters
`string` $name Class name.
#### Returns
`void`
### \_setOutputLevel() protected
```
_setOutputLevel(): void
```
Set the output level based on the parameters.
This reconfigures both the output level for out() and the configured stdout/stderr logging
#### Returns
`void`
### \_stop() protected
```
_stop(int $status = self::CODE_SUCCESS): void
```
Stop execution of the current script. Raises a StopException to try and halt the execution.
#### Parameters
`int` $status optional see <https://secure.php.net/exit> for values
#### Returns
`void`
#### Throws
`Cake\Console\Exception\StopException`
### \_validateTasks() protected
```
_validateTasks(): void
```
Checks that the tasks in the task map are actually available
#### Returns
`void`
#### Throws
`RuntimeException`
### \_welcome() protected
```
_welcome(): void
```
Displays a header for the shell
#### Returns
`void`
### abort() public
```
abort(string $message, int $exitCode = self::CODE_ERROR): void
```
Displays a formatted error message and exits the application with an error code.
#### Parameters
`string` $message The error message
`int` $exitCode optional The exit code for the shell task.
#### Returns
`void`
#### Throws
`Cake\Console\Exception\StopException`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#styling-output
### clear() public
```
clear(): void
```
Clear the console
#### Returns
`void`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#console-output
### createFile() public
```
createFile(string $path, string $contents): bool
```
Creates a file at given path
#### Parameters
`string` $path Where to put the file.
`string` $contents Content to put in the file.
#### Returns
`bool`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#creating-files
### dispatchShell() public
```
dispatchShell(): int
```
Dispatch a command to another Shell. Similar to Object::requestAction() but intended for running shells from other shells.
### Usage:
With a string command:
```
return $this->dispatchShell('schema create DbAcl');
```
Avoid using this form if you have string arguments, with spaces in them. The dispatched will be invoked incorrectly. Only use this form for simple command dispatching.
With an array command:
```
return $this->dispatchShell('schema', 'create', 'i18n', '--dry');
```
With an array having two key / value pairs:
* `command` can accept either a string or an array. Represents the command to dispatch
+ `extra` can accept an array of extra parameters to pass on to the dispatcher. This parameters will be available in the `param` property of the called `Shell`
`return $this->dispatchShell([ 'command' => 'schema create DbAcl', 'extra' => ['param' => 'value'] ]);`
or
`return $this->dispatchShell([ 'command' => ['schema', 'create', 'DbAcl'], 'extra' => ['param' => 'value'] ]);`
#### Returns
`int`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#invoking-other-shells-from-your-shell
### err() public
```
err(array<string>|string $message, int $newlines = 1): int
```
Outputs a single or multiple error messages to stderr. If no parameters are passed outputs just a newline.
#### Parameters
`array<string>|string` $message A string or an array of strings to output
`int` $newlines optional Number of newlines to append
#### Returns
`int`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getIo() public
```
getIo(): Cake\Console\ConsoleIo
```
Get the io object for this shell.
#### Returns
`Cake\Console\ConsoleIo`
### getModelType() public
```
getModelType(): string
```
Get the model type to be used by this class
#### Returns
`string`
### getOptionParser() public
```
getOptionParser(): Cake\Console\ConsoleOptionParser
```
Gets the option parser instance and configures it.
By overriding this method you can configure the ConsoleOptionParser before returning it.
#### Returns
`Cake\Console\ConsoleOptionParser`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#configuring-options-and-generating-help
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### hasMethod() public
```
hasMethod(string $name): bool
```
Check to see if this shell has a callable method by the given name.
#### Parameters
`string` $name The method name to check.
#### Returns
`bool`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#shell-tasks
### hasTask() public
```
hasTask(string $task): bool
```
Check to see if this shell has a task with the provided name.
#### Parameters
`string` $task The task name to check.
#### Returns
`bool`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#shell-tasks
### helper() public
```
helper(string $name, array<string, mixed> $config = []): Cake\Console\Helper
```
Render a Console Helper
Create and render the output for a helper object. If the helper object has not already been loaded, it will be loaded and constructed.
#### Parameters
`string` $name The name of the helper to render
`array<string, mixed>` $config optional Configuration data for the helper.
#### Returns
`Cake\Console\Helper`
### hr() public
```
hr(int $newlines = 0, int $width = 63): void
```
Outputs a series of minus characters to the standard output, acts as a visual separator.
#### Parameters
`int` $newlines optional Number of newlines to pre- and append
`int` $width optional Width of the line, defaults to 63
#### Returns
`void`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#Shell::hr
### in() public
```
in(string $prompt, array<string>|string|null $options = null, string|null $default = null): string|null
```
Prompts the user for input, and returns it.
#### Parameters
`string` $prompt Prompt text.
`array<string>|string|null` $options optional Array or string of options.
`string|null` $default optional Default input value.
#### Returns
`string|null`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#Shell::in
### info() public
```
info(array<string>|string $message, int $newlines = 1, int $level = Shell::NORMAL): int|null
```
Convenience method for out() that wraps message between tag
#### Parameters
`array<string>|string` $message A string or an array of strings to output
`int` $newlines optional Number of newlines to append
`int` $level optional The message's output level, see above.
#### Returns
`int|null`
#### See Also
https://book.cakephp.org/4/en/console-and-shells.html#Shell::out ### initialize() public
```
initialize(): void
```
Initializes the Shell acts as constructor for subclasses allows configuration of tasks prior to shell execution
#### Returns
`void`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#Cake\Console\ConsoleOptionParser::initialize
### loadModel() public
```
loadModel(string|null $modelClass = null, string|null $modelType = null): Cake\Datasource\RepositoryInterface
```
Loads and constructs repository objects required by this object
Typically used to load ORM Table objects as required. Can also be used to load other types of repository objects your application uses.
If a repository provider does not return an object a MissingModelException will be thrown.
#### Parameters
`string|null` $modelClass optional Name of model class to load. Defaults to $this->modelClass. The name can be an alias like `'Post'` or FQCN like `App\Model\Table\PostsTable::class`.
`string|null` $modelType optional The type of repository to load. Defaults to the getModelType() value.
#### Returns
`Cake\Datasource\RepositoryInterface`
#### Throws
`Cake\Datasource\Exception\MissingModelException`
If the model class cannot be found.
`UnexpectedValueException`
If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty. ### loadTasks() public
```
loadTasks(): true
```
Loads tasks defined in public $tasks
#### Returns
`true`
### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### main() public @method
```
main(mixed ...$args): int|bool|null|void
```
Main entry method for the shell.
#### Parameters
...$args #### Returns
`int|bool|null|void`
### modelFactory() public
```
modelFactory(string $type, Cake\Datasource\Locator\LocatorInterface|callable $factory): void
```
Override a existing callable to generate repositories of a given type.
#### Parameters
`string` $type The name of the repository type the factory function is for.
`Cake\Datasource\Locator\LocatorInterface|callable` $factory The factory function used to create instances.
#### Returns
`void`
### nl() public
```
nl(int $multiplier = 1): string
```
Returns a single or multiple linefeeds sequences.
#### Parameters
`int` $multiplier optional Number of times the linefeed sequence should be repeated
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#Shell::nl
### out() public
```
out(array<string>|string $message, int $newlines = 1, int $level = Shell::NORMAL): int|null
```
Outputs a single or multiple messages to stdout. If no parameters are passed outputs just a newline.
### Output levels
There are 3 built-in output level. Shell::QUIET, Shell::NORMAL, Shell::VERBOSE. The verbose and quiet output levels, map to the `verbose` and `quiet` output switches present in most shells. Using Shell::QUIET for a message means it will always display. While using Shell::VERBOSE means it will only display when verbose output is toggled.
#### Parameters
`array<string>|string` $message A string or an array of strings to output
`int` $newlines optional Number of newlines to append
`int` $level optional The message's output level, see above.
#### Returns
`int|null`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#Shell::out
### param() public
```
param(string $name): string|bool|null
```
Safely access the values in $this->params.
#### Parameters
`string` $name The name of the parameter to get.
#### Returns
`string|bool|null`
### parseDispatchArguments() public
```
parseDispatchArguments(array $args): array
```
Parses the arguments for the dispatchShell() method.
#### Parameters
`array` $args Arguments fetch from the dispatchShell() method with func\_get\_args()
#### Returns
`array`
### quiet() public
```
quiet(array<string>|string $message, int $newlines = 1): int|null
```
Output at all levels.
#### Parameters
`array<string>|string` $message A string or an array of strings to output
`int` $newlines optional Number of newlines to append
#### Returns
`int|null`
### runCommand() public
```
runCommand(array $argv, bool $autoMethod = false, array $extra = []): int|bool|null
```
Runs the Shell with the provided argv.
Delegates calls to Tasks and resolves methods inside the class. Commands are looked up with the following order:
* Method on the shell.
* Matching task name.
* `main()` method.
If a shell implements a `main()` method, all missing method calls will be sent to `main()` with the original method name in the argv.
For tasks to be invoked they *must* be exposed as subcommands. If you define any subcommands, you must define all the subcommands your shell needs, whether they be methods on this class or methods on tasks.
#### Parameters
`array` $argv Array of arguments to run the shell with. This array should be missing the shell name.
`bool` $autoMethod optional Set to true to allow any public method to be called even if it was not defined as a subcommand. This is used by ShellDispatcher to make building simple shells easy.
`array` $extra optional Extra parameters that you can manually pass to the Shell to be dispatched. Built-in extra parameter is :
#### Returns
`int|bool|null`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#the-cakephp-console
### setIo() public
```
setIo(Cake\Console\ConsoleIo $io): void
```
Set the io object for this shell.
#### Parameters
`Cake\Console\ConsoleIo` $io The ConsoleIo object to use.
#### Returns
`void`
### setModelType() public
```
setModelType(string $modelType): $this
```
Set the model type to be used by this class
#### Parameters
`string` $modelType The model type
#### Returns
`$this`
### setRootName() public
```
setRootName(string $name): $this
```
Set the root command name for help output.
#### Parameters
`string` $name The name of the root command.
#### Returns
`$this`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
### shortPath() public
```
shortPath(string $file): string
```
Makes absolute file path easier to read
#### Parameters
`string` $file Absolute file path
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#Shell::shortPath
### startup() public
```
startup(): void
```
Starts up the Shell and displays the welcome message. Allows for checking and configuring prior to command or main execution
Override this method if you want to remove the welcome information, or otherwise modify the pre-command flow.
#### Returns
`void`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#Cake\Console\ConsoleOptionParser::startup
### success() public
```
success(array<string>|string $message, int $newlines = 1, int $level = Shell::NORMAL): int|null
```
Convenience method for out() that wraps message between tag
#### Parameters
`array<string>|string` $message A string or an array of strings to output
`int` $newlines optional Number of newlines to append
`int` $level optional The message's output level, see above.
#### Returns
`int|null`
#### See Also
https://book.cakephp.org/4/en/console-and-shells.html#Shell::out ### verbose() public
```
verbose(array<string>|string $message, int $newlines = 1): int|null
```
Output at the verbose level.
#### Parameters
`array<string>|string` $message A string or an array of strings to output
`int` $newlines optional Number of newlines to append
#### Returns
`int|null`
### warn() public
```
warn(array<string>|string $message, int $newlines = 1): int
```
Convenience method for err() that wraps message between tag
#### Parameters
`array<string>|string` $message A string or an array of strings to output
`int` $newlines optional Number of newlines to append
#### Returns
`int`
#### See Also
https://book.cakephp.org/4/en/console-and-shells.html#Shell::err ### wrapText() public
```
wrapText(string $text, array<string, mixed>|int $options = []): string
```
Wrap a block of text. Allows you to set the width, and indenting on a block of text.
### Options
* `width` The width to wrap to. Defaults to 72
* `wordWrap` Only wrap on words breaks (spaces) Defaults to true.
* `indent` Indent the text with the string provided. Defaults to null.
#### Parameters
`string` $text Text the text to format.
`array<string, mixed>|int` $options optional Array of options to use, or an integer to wrap the text to.
#### Returns
`string`
#### See Also
\Cake\Utility\Text::wrap() #### Links
https://book.cakephp.org/4/en/console-and-shells.html#Shell::wrapText
Property Detail
---------------
### $OptionParser public
An instance of ConsoleOptionParser that has been configured for this class.
#### Type
`Cake\Console\ConsoleOptionParser`
### $Tasks public
Task Collection for the command, used to create Tasks.
#### Type
`Cake\Console\TaskRegistry`
### $\_io protected
ConsoleIo instance.
#### Type
`Cake\Console\ConsoleIo`
### $\_modelFactories protected
A list of overridden model factory functions.
#### Type
`array<callableCake\Datasource\Locator\LocatorInterface>`
### $\_modelType protected
The model type to use.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $\_taskMap protected
Normalized map of tasks.
#### Type
`array<string, array>`
### $args public
Contains arguments parsed from the command line.
#### Type
`array`
### $command public
The command (method/task) that is being run.
#### Type
`string|null`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
### $interactive public
If true, the script will ask for permission to perform actions.
#### Type
`bool`
### $modelClass protected deprecated
This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
Example: For an object named 'Comments', the modelClass would be 'Comments'. Plugin classes should use `Plugin.Comments` style names to correctly load models from the correct plugin.
Use empty string to not use auto-loading on this object. Null auto-detects based on controller name.
#### Type
`string|null`
### $name public
The name of the shell in camelized.
#### Type
`string`
### $params public
Contains command switches parsed from the command line.
#### Type
`array`
### $plugin public
The name of the plugin the shell belongs to. Is automatically set by ShellDispatcher when a shell is constructed.
#### Type
`string`
### $rootName protected
The root command name used when generating help output.
#### Type
`string`
### $taskNames public
Contains the loaded tasks
#### Type
`array<string>`
### $tasks public
Contains tasks to load and instantiate
#### Type
`array|bool`
| programming_docs |
cakephp Namespace Iterator Namespace Iterator
==================
### Classes
* ##### [BufferedIterator](class-cake.collection.iterator.bufferediterator)
Creates an iterator from another iterator that will keep the results of the inner iterator in memory, so that results don't have to be re-calculated.
* ##### [ExtractIterator](class-cake.collection.iterator.extractiterator)
Creates an iterator from another iterator that extract the requested column or property based on a path
* ##### [FilterIterator](class-cake.collection.iterator.filteriterator)
Creates a filtered iterator from another iterator. The filtering is done by passing a callback function to each of the elements and taking them out if it does not return true.
* ##### [InsertIterator](class-cake.collection.iterator.insertiterator)
This iterator will insert values into a property of each of the records returned. The values to be inserted come out of another traversal object. This is useful when you have two separate collections and want to merge them together by placing each of the values from one collection into a property inside the other collection.
* ##### [MapReduce](class-cake.collection.iterator.mapreduce)
Implements a simplistic version of the popular Map-Reduce algorithm. Acts like an iterator for the original passed data after each result has been processed, thus offering a transparent wrapper for results coming from any source.
* ##### [NestIterator](class-cake.collection.iterator.nestiterator)
A type of collection that is aware of nested items and exposes methods to check or retrieve them
* ##### [NoChildrenIterator](class-cake.collection.iterator.nochildreniterator)
An iterator that can be used as an argument for other iterators that require a RecursiveIterator but do not want children. This iterator will always behave as having no nested items.
* ##### [ReplaceIterator](class-cake.collection.iterator.replaceiterator)
Creates an iterator from another iterator that will modify each of the values by converting them using a callback function.
* ##### [SortIterator](class-cake.collection.iterator.sortiterator)
An iterator that will return the passed items in order. The order is given by the value returned in a callback function that maps each of the elements.
* ##### [StoppableIterator](class-cake.collection.iterator.stoppableiterator)
Creates an iterator from another iterator that will verify a condition on each step. If the condition evaluates to false, the iterator will not yield more results.
* ##### [TreeIterator](class-cake.collection.iterator.treeiterator)
A Recursive iterator used to flatten nested structures and also exposes all Collection methods
* ##### [TreePrinter](class-cake.collection.iterator.treeprinter)
Iterator for flattening elements in a tree structure while adding some visual markers for their relative position in the tree
* ##### [UnfoldIterator](class-cake.collection.iterator.unfolditerator)
An iterator that can be used to generate nested iterators out of a collection of items by applying an function to each of the elements in this iterator.
* ##### [ZipIterator](class-cake.collection.iterator.zipiterator)
Creates an iterator that returns elements grouped in pairs
cakephp Interface StatementInterface Interface StatementInterface
=============================
Represents a database statement. Concrete implementations can either use PDOStatement or a native driver
**Namespace:** [Cake\Database](namespace-cake.database)
Constants
---------
* `string` **FETCH\_TYPE\_ASSOC**
```
'assoc'
```
Used to designate that an associated array be returned in a result when calling fetch methods
* `string` **FETCH\_TYPE\_NUM**
```
'num'
```
Used to designate that numeric indexes be returned in a result when calling fetch methods
* `string` **FETCH\_TYPE\_OBJ**
```
'obj'
```
Used to designate that a stdClass object be returned in a result when calling fetch methods
Property Summary
----------------
* [$queryString](#%24queryString) public @property-read `string`
Method Summary
--------------
* ##### [bind()](#bind()) public
Binds a set of values to statement object with corresponding type
* ##### [bindValue()](#bindValue()) public
Assign a value to a positional or named variable in prepared query. If using positional variables you need to start with index one, if using named params then just use the name in any order.
* ##### [closeCursor()](#closeCursor()) public
Closes a cursor in the database, freeing up any resources and memory allocated to it. In most cases you don't need to call this method, as it is automatically called after fetching all results from the result set.
* ##### [columnCount()](#columnCount()) public
Returns the number of columns this statement's results will contain
* ##### [count()](#count()) public
Statements can be passed as argument for count() to return the number for affected rows from last execution
* ##### [errorCode()](#errorCode()) public
Returns the error code for the last error that occurred when executing this statement
* ##### [errorInfo()](#errorInfo()) public
Returns the error information for the last error that occurred when executing this statement
* ##### [execute()](#execute()) public
Executes the statement by sending the SQL query to the database. It can optionally take an array or arguments to be bound to the query variables. Please note that binding parameters from this method will not perform any custom type conversion as it would normally happen when calling `bindValue`
* ##### [fetch()](#fetch()) public
Returns the next row for the result set after executing this statement. Rows can be fetched to contain columns as names or positions. If no rows are left in result set, this method will return false
* ##### [fetchAll()](#fetchAll()) public
Returns an array with all rows resulting from executing this statement
* ##### [fetchColumn()](#fetchColumn()) public
Returns the value of the result at position.
* ##### [lastInsertId()](#lastInsertId()) public
Returns the latest primary inserted using this statement
* ##### [rowCount()](#rowCount()) public
Returns the number of rows affected by this SQL statement
Method Detail
-------------
### bind() public
```
bind(array $params, array $types): void
```
Binds a set of values to statement object with corresponding type
#### Parameters
`array` $params list of values to be bound
`array` $types list of types to be used, keys should match those in $params
#### Returns
`void`
### bindValue() public
```
bindValue(string|int $column, mixed $value, string|int|null $type = 'string'): void
```
Assign a value to a positional or named variable in prepared query. If using positional variables you need to start with index one, if using named params then just use the name in any order.
It is not allowed to combine positional and named variables in the same statement
### Examples:
```
$statement->bindValue(1, 'a title');
$statement->bindValue('active', true, 'boolean');
$statement->bindValue(5, new \DateTime(), 'date');
```
#### Parameters
`string|int` $column name or param position to be bound
`mixed` $value The value to bind to variable in query
`string|int|null` $type optional name of configured Type class, or PDO type constant.
#### Returns
`void`
### closeCursor() public
```
closeCursor(): void
```
Closes a cursor in the database, freeing up any resources and memory allocated to it. In most cases you don't need to call this method, as it is automatically called after fetching all results from the result set.
#### Returns
`void`
### columnCount() public
```
columnCount(): int
```
Returns the number of columns this statement's results will contain
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
echo $statement->columnCount(); // outputs 2
```
#### Returns
`int`
### count() public
```
count(): int
```
Statements can be passed as argument for count() to return the number for affected rows from last execution
#### Returns
`int`
### errorCode() public
```
errorCode(): string|int
```
Returns the error code for the last error that occurred when executing this statement
#### Returns
`string|int`
### errorInfo() public
```
errorInfo(): array
```
Returns the error information for the last error that occurred when executing this statement
#### Returns
`array`
### execute() public
```
execute(array|null $params = null): bool
```
Executes the statement by sending the SQL query to the database. It can optionally take an array or arguments to be bound to the query variables. Please note that binding parameters from this method will not perform any custom type conversion as it would normally happen when calling `bindValue`
#### Parameters
`array|null` $params optional list of values to be bound to query
#### Returns
`bool`
### fetch() public
```
fetch(string|int $type = 'num'): mixed
```
Returns the next row for the result set after executing this statement. Rows can be fetched to contain columns as names or positions. If no rows are left in result set, this method will return false
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
print_r($statement->fetch('assoc')); // will show ['id' => 1, 'title' => 'a title']
```
#### Parameters
`string|int` $type optional 'num' for positional columns, assoc for named columns, or PDO fetch mode constants.
#### Returns
`mixed`
### fetchAll() public
```
fetchAll(string|int $type = 'num'): array|false
```
Returns an array with all rows resulting from executing this statement
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
print_r($statement->fetchAll('assoc')); // will show [0 => ['id' => 1, 'title' => 'a title']]
```
#### Parameters
`string|int` $type optional num for fetching columns as positional keys or assoc for column names as keys
#### Returns
`array|false`
### fetchColumn() public
```
fetchColumn(int $position): mixed
```
Returns the value of the result at position.
#### Parameters
`int` $position The numeric position of the column to retrieve in the result
#### Returns
`mixed`
### lastInsertId() public
```
lastInsertId(string|null $table = null, string|null $column = null): string|int
```
Returns the latest primary inserted using this statement
#### Parameters
`string|null` $table optional table name or sequence to get last insert value from
`string|null` $column optional the name of the column representing the primary key
#### Returns
`string|int`
### rowCount() public
```
rowCount(): int
```
Returns the number of rows affected by this SQL statement
### Example:
```
$statement = $connection->prepare('SELECT id, title from articles');
$statement->execute();
print_r($statement->rowCount()); // will show 1
```
#### Returns
`int`
Property Detail
---------------
### $queryString public @property-read
#### Type
`string`
cakephp Class XmlView Class XmlView
==============
A view class that is used for creating XML responses.
By setting the 'serialize' option in view builder of your controller, you can specify a view variable that should be serialized to XML and used as the response for the request. This allows you to omit views + layouts, if your just need to emit a single view variable as the XML response.
In your controller, you could do the following:
```
$this->set(['posts' => $posts]);
$this->viewBuilder()->setOption('serialize', true);
```
When the view is rendered, the `$posts` view variable will be serialized into XML.
**Note** The view variable you specify must be compatible with Xml::fromArray().
You can also set `'serialize'` as an array. This will create an additional top level element named `<response>` containing all the named view variables:
```
$this->set(compact('posts', 'users', 'stuff'));
$this->viewBuilder()->setOption('serialize', true);
```
The above would generate a XML object that looks like:
`<response><posts>...</posts><users>...</users></response>`
You can also set `'serialize'` to a string or array to serialize only the specified view variables.
If you don't set the `serialize` option, you will need a view. You can use extended views to provide layout like functionality.
**Namespace:** [Cake\View](namespace-cake.view)
Constants
---------
* `string` **NAME\_TEMPLATE**
```
'templates'
```
Constant for type used for App::path().
* `string` **PLUGIN\_TEMPLATE\_FOLDER**
```
'plugin'
```
Constant for folder name containing files for overriding plugin templates.
* `string` **TYPE\_ELEMENT**
```
'element'
```
Constant for view file type 'element'
* `string` **TYPE\_LAYOUT**
```
'layout'
```
Constant for view file type 'layout'
* `string` **TYPE\_MATCH\_ALL**
```
'_match_all_'
```
The magic 'match-all' content type that views can use to behave as a fallback during content-type negotiation.
* `string` **TYPE\_TEMPLATE**
```
'template'
```
Constant for view file type 'template'.
Property Summary
----------------
* [$Blocks](#%24Blocks) public @property `Cake\View\ViewBlock`
* [$Breadcrumbs](#%24Breadcrumbs) public @property `Cake\View\Helper\BreadcrumbsHelper`
* [$Flash](#%24Flash) public @property `Cake\View\Helper\FlashHelper`
* [$Form](#%24Form) public @property `Cake\View\Helper\FormHelper`
* [$Html](#%24Html) public @property `Cake\View\Helper\HtmlHelper`
* [$Number](#%24Number) public @property `Cake\View\Helper\NumberHelper`
* [$Paginator](#%24Paginator) public @property `Cake\View\Helper\PaginatorHelper`
* [$Text](#%24Text) public @property `Cake\View\Helper\TextHelper`
* [$Time](#%24Time) public @property `Cake\View\Helper\TimeHelper`
* [$Url](#%24Url) public @property `Cake\View\Helper\UrlHelper`
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_current](#%24_current) protected `string` The currently rendering view file. Used for resolving parent files.
* [$\_currentType](#%24_currentType) protected `string` Currently rendering an element. Used for finding parent fragments for elements.
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config options.
* [$\_eventClass](#%24_eventClass) protected `string` Default class name for new event objects.
* [$\_eventManager](#%24_eventManager) protected `Cake\Event\EventManagerInterface|null` Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
* [$\_ext](#%24_ext) protected `string` File extension. Defaults to ".php".
* [$\_helpers](#%24_helpers) protected `Cake\View\HelperRegistry` Helpers collection
* [$\_parents](#%24_parents) protected `array<string>` The names of views and their parents used with View::extend();
* [$\_passedVars](#%24_passedVars) protected `array<string>` List of variables to collect from the associated controller.
* [$\_paths](#%24_paths) protected `array<string>` Holds an array of paths.
* [$\_pathsForPlugin](#%24_pathsForPlugin) protected `array<string[]>` Holds an array of plugin paths.
* [$\_responseType](#%24_responseType) protected deprecated `string` Response type.
* [$\_stack](#%24_stack) protected `array<string>` Content stack, used for nested templates that all use View::extend();
* [$\_viewBlockClass](#%24_viewBlockClass) protected `string` ViewBlock class.
* [$autoLayout](#%24autoLayout) protected `bool` Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered templates.
* [$elementCache](#%24elementCache) protected `string` The Cache configuration View will use to store cached elements. Changing this will change the default configuration elements are stored under. You can also choose a cache config per element.
* [$helpers](#%24helpers) protected `array` An array of names of built-in helpers to include.
* [$layout](#%24layout) protected `string` The name of the layout file to render the template inside of. The name specified is the filename of the layout in `templates/layout/` without the .php extension.
* [$layoutPath](#%24layoutPath) protected `string` XML layouts are located in the `layouts/xml/` subdirectory
* [$name](#%24name) protected `string` Name of the controller that created the View if any.
* [$plugin](#%24plugin) protected `string|null` The name of the plugin.
* [$request](#%24request) protected `Cake\Http\ServerRequest` An instance of a \Cake\Http\ServerRequest object that contains information about the current request. This object contains all the information about a request and several methods for reading additional information about the request.
* [$response](#%24response) protected `Cake\Http\Response` Reference to the Response object
* [$subDir](#%24subDir) protected `string` XML views are located in the 'xml' subdirectory for controllers' views.
* [$template](#%24template) protected `string` The name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
* [$templatePath](#%24templatePath) protected `string` The name of the subfolder containing templates for this View.
* [$theme](#%24theme) protected `string|null` The view theme to use.
* [$viewVars](#%24viewVars) protected `array<string, mixed>` An array of variables
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_get()](#__get()) public
Magic accessor for helpers.
* ##### [\_checkFilePath()](#_checkFilePath()) protected
Check that a view file path does not go outside of the defined template paths.
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_createCell()](#_createCell()) protected
Create and configure the cell instance.
* ##### [\_elementCache()](#_elementCache()) protected
Generate the cache configuration options for an element.
* ##### [\_evaluate()](#_evaluate()) protected
Sandbox method to evaluate a template / view script in.
* ##### [\_getElementFileName()](#_getElementFileName()) protected
Finds an element filename, returns false on failure.
* ##### [\_getLayoutFileName()](#_getLayoutFileName()) protected
Returns layout filename for this template as a string.
* ##### [\_getSubPaths()](#_getSubPaths()) protected
Find all sub templates path, based on $basePath If a prefix is defined in the current request, this method will prepend the prefixed template path to the $basePath, cascading up in case the prefix is nested. This is essentially used to find prefixed template paths for elements and layouts.
* ##### [\_getTemplateFileName()](#_getTemplateFileName()) protected
Returns filename of given action's template file as a string. CamelCased action names will be under\_scored by default. This means that you can have LongActionNames that refer to long\_action\_names.php templates. You can change the inflection rule by overriding \_inflectTemplateFileName.
* ##### [\_inflectTemplateFileName()](#_inflectTemplateFileName()) protected
Change the name of a view template file into underscored format.
* ##### [\_paths()](#_paths()) protected
Return all possible paths to find view files in order
* ##### [\_render()](#_render()) protected
Renders and returns output for given template filename with its array of data. Handles parent/extended templates.
* ##### [\_renderElement()](#_renderElement()) protected
Renders an element and fires the before and afterRender callbacks for it and writes to the cache if a cache is used
* ##### [\_serialize()](#_serialize()) protected
Serialize view vars.
* ##### [append()](#append()) public
Append to an existing or new block.
* ##### [assign()](#assign()) public
Set the content for a block. This will overwrite any existing content.
* ##### [blocks()](#blocks()) public
Get the names of all the existing blocks.
* ##### [cache()](#cache()) public
Create a cached block of view logic.
* ##### [cell()](#cell()) protected
Renders the given cell.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [contentType()](#contentType()) public static
Mime-type this view class renders as.
* ##### [disableAutoLayout()](#disableAutoLayout()) public
Turns off CakePHP's conventional mode of applying layout files. Layouts will not be automatically applied to rendered views.
* ##### [dispatchEvent()](#dispatchEvent()) public
Wrapper for creating and dispatching events.
* ##### [element()](#element()) public
Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
* ##### [elementExists()](#elementExists()) public
Checks if an element exists
* ##### [enableAutoLayout()](#enableAutoLayout()) public
Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered views.
* ##### [end()](#end()) public
End a capturing block. The compliment to View::start()
* ##### [exists()](#exists()) public
Check if a block exists
* ##### [extend()](#extend()) public
Provides template or element extension/inheritance. Templates can extends a parent template and populate blocks in the parent template.
* ##### [fetch()](#fetch()) public
Fetch the content for a block. If a block is empty or undefined '' will be returned.
* ##### [get()](#get()) public
Returns the contents of the given View variable.
* ##### [getConfig()](#getConfig()) public
Get config value.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getCurrentType()](#getCurrentType()) public
Retrieve the current template type
* ##### [getElementPaths()](#getElementPaths()) protected
Get an iterator for element paths.
* ##### [getEventManager()](#getEventManager()) public
Returns the Cake\Event\EventManager manager instance for this object.
* ##### [getLayout()](#getLayout()) public
Get the name of the layout file to render the template inside of. The name specified is the filename of the layout in `templates/layout/` without the .php extension.
* ##### [getLayoutPath()](#getLayoutPath()) public
Get path for layout files.
* ##### [getLayoutPaths()](#getLayoutPaths()) protected
Get an iterator for layout paths.
* ##### [getName()](#getName()) public
Returns the View's controller name.
* ##### [getPlugin()](#getPlugin()) public
Returns the plugin name.
* ##### [getRequest()](#getRequest()) public
Gets the request instance.
* ##### [getResponse()](#getResponse()) public
Gets the response instance.
* ##### [getSubDir()](#getSubDir()) public
Get sub-directory for this template files.
* ##### [getTemplate()](#getTemplate()) public
Get the name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
* ##### [getTemplatePath()](#getTemplatePath()) public
Get path for templates files.
* ##### [getTheme()](#getTheme()) public
Get the current view theme.
* ##### [getVars()](#getVars()) public
Returns a list of variables available in the current View context
* ##### [helpers()](#helpers()) public
Get the helper registry in use by this View class.
* ##### [initialize()](#initialize()) public
Initialization hook method.
* ##### [isAutoLayoutEnabled()](#isAutoLayoutEnabled()) public
Returns if CakePHP's conventional mode of applying layout files is enabled. Disabled means that layouts will not be automatically applied to rendered views.
* ##### [loadHelper()](#loadHelper()) public
Loads a helper. Delegates to the `HelperRegistry::load()` to load the helper
* ##### [loadHelpers()](#loadHelpers()) public
Load helpers only if serialization is disabled.
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [pluginSplit()](#pluginSplit()) public
Splits a dot syntax plugin name into its plugin and filename. If $name does not have a dot, then index 0 will be null. It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
* ##### [prepend()](#prepend()) public
Prepend to an existing or new block.
* ##### [render()](#render()) public
Render view template or return serialized data.
* ##### [renderLayout()](#renderLayout()) public
Renders a layout. Returns output from \_render().
* ##### [reset()](#reset()) public
Reset the content for a block. This will overwrite any existing content.
* ##### [set()](#set()) public
Saves a variable or an associative array of variables for use inside a template.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setContentType()](#setContentType()) protected
Set the response content-type based on the view's contentType()
* ##### [setElementCache()](#setElementCache()) public
Set The cache configuration View will use to store cached elements
* ##### [setEventManager()](#setEventManager()) public
Returns the Cake\Event\EventManagerInterface instance for this object.
* ##### [setLayout()](#setLayout()) public
Set the name of the layout file to render the template inside of. The name specified is the filename of the layout in `templates/layout/` without the .php extension.
* ##### [setLayoutPath()](#setLayoutPath()) public
Set path for layout files.
* ##### [setPlugin()](#setPlugin()) public
Sets the plugin name.
* ##### [setRequest()](#setRequest()) public
Sets the request objects and configures a number of controller properties based on the contents of the request. The properties that get set are:
* ##### [setResponse()](#setResponse()) public
Sets the response instance.
* ##### [setSubDir()](#setSubDir()) public
Set sub-directory for this template files.
* ##### [setTemplate()](#setTemplate()) public
Set the name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
* ##### [setTemplatePath()](#setTemplatePath()) public
Set path for templates files.
* ##### [setTheme()](#setTheme()) public
Set the view theme to use.
* ##### [start()](#start()) public
Start capturing output for a 'block'
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Http\ServerRequest|null $request = null, Cake\Http\Response|null $response = null, Cake\Event\EventManager|null $eventManager = null, array<string, mixed> $viewOptions = [])
```
Constructor
#### Parameters
`Cake\Http\ServerRequest|null` $request optional Request instance.
`Cake\Http\Response|null` $response optional Response instance.
`Cake\Event\EventManager|null` $eventManager optional Event manager instance.
`array<string, mixed>` $viewOptions optional View options. See {@link View::$\_passedVars} for list of options which get set as class properties.
### \_\_get() public
```
__get(string $name): Cake\View\Helper|null
```
Magic accessor for helpers.
#### Parameters
`string` $name Name of the attribute to get.
#### Returns
`Cake\View\Helper|null`
### \_checkFilePath() protected
```
_checkFilePath(string $file, string $path): string
```
Check that a view file path does not go outside of the defined template paths.
Only paths that contain `..` will be checked, as they are the ones most likely to have the ability to resolve to files outside of the template paths.
#### Parameters
`string` $file The path to the template file.
`string` $path Base path that $file should be inside of.
#### Returns
`string`
#### Throws
`InvalidArgumentException`
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_createCell() protected
```
_createCell(string $className, string $action, string|null $plugin, array<string, mixed> $options): Cake\View\Cell
```
Create and configure the cell instance.
#### Parameters
`string` $className The cell classname.
`string` $action The action name.
`string|null` $plugin The plugin name.
`array<string, mixed>` $options The constructor options for the cell.
#### Returns
`Cake\View\Cell`
### \_elementCache() protected
```
_elementCache(string $name, array $data, array<string, mixed> $options): array
```
Generate the cache configuration options for an element.
#### Parameters
`string` $name Element name
`array` $data Data
`array<string, mixed>` $options Element options
#### Returns
`array`
### \_evaluate() protected
```
_evaluate(string $templateFile, array $dataForView): string
```
Sandbox method to evaluate a template / view script in.
#### Parameters
`string` $templateFile Filename of the template.
`array` $dataForView Data to include in rendered view.
#### Returns
`string`
### \_getElementFileName() protected
```
_getElementFileName(string $name, bool $pluginCheck = true): string|false
```
Finds an element filename, returns false on failure.
#### Parameters
`string` $name The name of the element to find.
`bool` $pluginCheck optional * if false will ignore the request's plugin if parsed plugin is not loaded
#### Returns
`string|false`
### \_getLayoutFileName() protected
```
_getLayoutFileName(string|null $name = null): string
```
Returns layout filename for this template as a string.
#### Parameters
`string|null` $name optional The name of the layout to find.
#### Returns
`string`
#### Throws
`Cake\View\Exception\MissingLayoutException`
when a layout cannot be located
`RuntimeException`
### \_getSubPaths() protected
```
_getSubPaths(string $basePath): array<string>
```
Find all sub templates path, based on $basePath If a prefix is defined in the current request, this method will prepend the prefixed template path to the $basePath, cascading up in case the prefix is nested. This is essentially used to find prefixed template paths for elements and layouts.
#### Parameters
`string` $basePath Base path on which to get the prefixed one.
#### Returns
`array<string>`
### \_getTemplateFileName() protected
```
_getTemplateFileName(string|null $name = null): string
```
Returns filename of given action's template file as a string. CamelCased action names will be under\_scored by default. This means that you can have LongActionNames that refer to long\_action\_names.php templates. You can change the inflection rule by overriding \_inflectTemplateFileName.
#### Parameters
`string|null` $name optional Controller action to find template filename for
#### Returns
`string`
#### Throws
`Cake\View\Exception\MissingTemplateException`
when a template file could not be found.
`RuntimeException`
When template name not provided. ### \_inflectTemplateFileName() protected
```
_inflectTemplateFileName(string $name): string
```
Change the name of a view template file into underscored format.
#### Parameters
`string` $name Name of file which should be inflected.
#### Returns
`string`
### \_paths() protected
```
_paths(string|null $plugin = null, bool $cached = true): array<string>
```
Return all possible paths to find view files in order
#### Parameters
`string|null` $plugin optional Optional plugin name to scan for view files.
`bool` $cached optional Set to false to force a refresh of view paths. Default true.
#### Returns
`array<string>`
### \_render() protected
```
_render(string $templateFile, array $data = []): string
```
Renders and returns output for given template filename with its array of data. Handles parent/extended templates.
#### Parameters
`string` $templateFile Filename of the template
`array` $data optional Data to include in rendered view. If empty the current View::$viewVars will be used.
#### Returns
`string`
#### Throws
`LogicException`
When a block is left open. ### \_renderElement() protected
```
_renderElement(string $file, array $data, array<string, mixed> $options): string
```
Renders an element and fires the before and afterRender callbacks for it and writes to the cache if a cache is used
#### Parameters
`string` $file Element file path
`array` $data Data to render
`array<string, mixed>` $options Element options
#### Returns
`string`
### \_serialize() protected
```
_serialize(array|string $serialize): string
```
Serialize view vars.
#### Parameters
`array|string` $serialize #### Returns
`string`
### append() public
```
append(string $name, mixed $value = null): $this
```
Append to an existing or new block.
Appending to a new block will create the block.
#### Parameters
`string` $name Name of the block
`mixed` $value optional The content for the block. Value will be type cast to string.
#### Returns
`$this`
#### See Also
\Cake\View\ViewBlock::concat() ### assign() public
```
assign(string $name, mixed $value): $this
```
Set the content for a block. This will overwrite any existing content.
#### Parameters
`string` $name Name of the block
`mixed` $value The content for the block. Value will be type cast to string.
#### Returns
`$this`
#### See Also
\Cake\View\ViewBlock::set() ### blocks() public
```
blocks(): array<string>
```
Get the names of all the existing blocks.
#### Returns
`array<string>`
#### See Also
\Cake\View\ViewBlock::keys() ### cache() public
```
cache(callable $block, array<string, mixed> $options = []): string
```
Create a cached block of view logic.
This allows you to cache a block of view output into the cache defined in `elementCache`.
This method will attempt to read the cache first. If the cache is empty, the $block will be run and the output stored.
#### Parameters
`callable` $block The block of code that you want to cache the output of.
`array<string, mixed>` $options optional The options defining the cache key etc.
#### Returns
`string`
#### Throws
`RuntimeException`
When $options is lacking a 'key' option. ### cell() protected
```
cell(string $cell, array $data = [], array<string, mixed> $options = []): Cake\View\Cell
```
Renders the given cell.
Example:
```
// Taxonomy\View\Cell\TagCloudCell::smallList()
$cell = $this->cell('Taxonomy.TagCloud::smallList', ['limit' => 10]);
// App\View\Cell\TagCloudCell::smallList()
$cell = $this->cell('TagCloud::smallList', ['limit' => 10]);
```
The `display` action will be used by default when no action is provided:
```
// Taxonomy\View\Cell\TagCloudCell::display()
$cell = $this->cell('Taxonomy.TagCloud');
```
Cells are not rendered until they are echoed.
#### Parameters
`string` $cell You must indicate cell name, and optionally a cell action. e.g.: `TagCloud::smallList` will invoke `View\Cell\TagCloudCell::smallList()`, `display` action will be invoked by default when none is provided.
`array` $data optional Additional arguments for cell method. e.g.: `cell('TagCloud::smallList', ['a1' => 'v1', 'a2' => 'v2'])` maps to `View\Cell\TagCloud::smallList(v1, v2)`
`array<string, mixed>` $options optional Options for Cell's constructor
#### Returns
`Cake\View\Cell`
#### Throws
`Cake\View\Exception\MissingCellException`
If Cell class was not found. ### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### contentType() public static
```
contentType(): string
```
Mime-type this view class renders as.
#### Returns
`string`
### disableAutoLayout() public
```
disableAutoLayout(): $this
```
Turns off CakePHP's conventional mode of applying layout files. Layouts will not be automatically applied to rendered views.
#### Returns
`$this`
### dispatchEvent() public
```
dispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\EventInterface
```
Wrapper for creating and dispatching events.
Returns a dispatched event.
#### Parameters
`string` $name Name of the event.
`array|null` $data optional Any value you wish to be transported with this event to it can be read by listeners.
`object|null` $subject optional The object that this event applies to ($this by default).
#### Returns
`Cake\Event\EventInterface`
### element() public
```
element(string $name, array $data = [], array<string, mixed> $options = []): string
```
Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send data to be used in the element. Elements can be cached improving performance by using the `cache` option.
#### Parameters
`string` $name Name of template file in the `templates/element/` folder, or `MyPlugin.template` to use the template element from MyPlugin. If the element is not found in the plugin, the normal view path cascade will be searched.
`array` $data optional Array of data to be made available to the rendered view (i.e. the Element)
`array<string, mixed>` $options optional Array of options. Possible keys are:
#### Returns
`string`
#### Throws
`Cake\View\Exception\MissingElementException`
When an element is missing and `ignoreMissing` is false. ### elementExists() public
```
elementExists(string $name): bool
```
Checks if an element exists
#### Parameters
`string` $name Name of template file in the `templates/element/` folder, or `MyPlugin.template` to check the template element from MyPlugin. If the element is not found in the plugin, the normal view path cascade will be searched.
#### Returns
`bool`
### enableAutoLayout() public
```
enableAutoLayout(bool $enable = true): $this
```
Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered views.
#### Parameters
`bool` $enable optional Boolean to turn on/off.
#### Returns
`$this`
### end() public
```
end(): $this
```
End a capturing block. The compliment to View::start()
#### Returns
`$this`
#### See Also
\Cake\View\ViewBlock::end() ### exists() public
```
exists(string $name): bool
```
Check if a block exists
#### Parameters
`string` $name Name of the block
#### Returns
`bool`
### extend() public
```
extend(string $name): $this
```
Provides template or element extension/inheritance. Templates can extends a parent template and populate blocks in the parent template.
#### Parameters
`string` $name The template or element to 'extend' the current one with.
#### Returns
`$this`
#### Throws
`LogicException`
when you extend a template with itself or make extend loops.
`LogicException`
when you extend an element which doesn't exist ### fetch() public
```
fetch(string $name, string $default = ''): string
```
Fetch the content for a block. If a block is empty or undefined '' will be returned.
#### Parameters
`string` $name Name of the block
`string` $default optional Default text
#### Returns
`string`
#### See Also
\Cake\View\ViewBlock::get() ### get() public
```
get(string $var, mixed $default = null): mixed
```
Returns the contents of the given View variable.
#### Parameters
`string` $var The view var you want the contents of.
`mixed` $default optional The default/fallback content of $var.
#### Returns
`mixed`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Get config value.
Currently if config is not set it fallbacks to checking corresponding view var with underscore prefix. Using underscore prefixed special view vars is deprecated and this fallback will be removed in CakePHP 4.1.0.
#### Parameters
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getCurrentType() public
```
getCurrentType(): string
```
Retrieve the current template type
#### Returns
`string`
### getElementPaths() protected
```
getElementPaths(string|null $plugin): Generator
```
Get an iterator for element paths.
#### Parameters
`string|null` $plugin The plugin to fetch paths for.
#### Returns
`Generator`
### getEventManager() public
```
getEventManager(): Cake\Event\EventManagerInterface
```
Returns the Cake\Event\EventManager manager 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.
#### Returns
`Cake\Event\EventManagerInterface`
### getLayout() public
```
getLayout(): string
```
Get the name of the layout file to render the template inside of. The name specified is the filename of the layout in `templates/layout/` without the .php extension.
#### Returns
`string`
### getLayoutPath() public
```
getLayoutPath(): string
```
Get path for layout files.
#### Returns
`string`
### getLayoutPaths() protected
```
getLayoutPaths(string|null $plugin): Generator
```
Get an iterator for layout paths.
#### Parameters
`string|null` $plugin The plugin to fetch paths for.
#### Returns
`Generator`
### getName() public
```
getName(): string
```
Returns the View's controller name.
#### Returns
`string`
### getPlugin() public
```
getPlugin(): string|null
```
Returns the plugin name.
#### Returns
`string|null`
### getRequest() public
```
getRequest(): Cake\Http\ServerRequest
```
Gets the request instance.
#### Returns
`Cake\Http\ServerRequest`
### getResponse() public
```
getResponse(): Cake\Http\Response
```
Gets the response instance.
#### Returns
`Cake\Http\Response`
### getSubDir() public
```
getSubDir(): string
```
Get sub-directory for this template files.
#### Returns
`string`
#### See Also
\Cake\View\View::$subDir ### getTemplate() public
```
getTemplate(): string
```
Get the name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
#### Returns
`string`
### getTemplatePath() public
```
getTemplatePath(): string
```
Get path for templates files.
#### Returns
`string`
### getTheme() public
```
getTheme(): string|null
```
Get the current view theme.
#### Returns
`string|null`
### getVars() public
```
getVars(): array<string>
```
Returns a list of variables available in the current View context
#### Returns
`array<string>`
### helpers() public
```
helpers(): Cake\View\HelperRegistry
```
Get the helper registry in use by this View class.
#### Returns
`Cake\View\HelperRegistry`
### initialize() public
```
initialize(): void
```
Initialization hook method.
Properties like $helpers etc. cannot be initialized statically in your custom view class as they are overwritten by values from controller in constructor. So this method allows you to manipulate them as required after view instance is constructed.
#### Returns
`void`
### isAutoLayoutEnabled() public
```
isAutoLayoutEnabled(): bool
```
Returns if CakePHP's conventional mode of applying layout files is enabled. Disabled means that layouts will not be automatically applied to rendered views.
#### Returns
`bool`
### loadHelper() public
```
loadHelper(string $name, array<string, mixed> $config = []): Cake\View\Helper
```
Loads a helper. Delegates to the `HelperRegistry::load()` to load the helper
#### Parameters
`string` $name Name of the helper to load.
`array<string, mixed>` $config optional Settings for the helper
#### Returns
`Cake\View\Helper`
#### See Also
\Cake\View\HelperRegistry::load() ### loadHelpers() public
```
loadHelpers(): $this
```
Load helpers only if serialization is disabled.
#### Returns
`$this`
### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### pluginSplit() public
```
pluginSplit(string $name, bool $fallback = true): array
```
Splits a dot syntax plugin name into its plugin and filename. If $name does not have a dot, then index 0 will be null. It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
#### Parameters
`string` $name The name you want to plugin split.
`bool` $fallback optional If true uses the plugin set in the current Request when parsed plugin is not loaded
#### Returns
`array`
### prepend() public
```
prepend(string $name, mixed $value): $this
```
Prepend to an existing or new block.
Prepending to a new block will create the block.
#### Parameters
`string` $name Name of the block
`mixed` $value The content for the block. Value will be type cast to string.
#### Returns
`$this`
#### See Also
\Cake\View\ViewBlock::concat() ### render() public
```
render(string|null $template = null, string|false|null $layout = null): string
```
Render view template or return serialized data.
Render triggers helper callbacks, which are fired before and after the template are rendered, as well as before and after the layout. The helper callbacks are called:
* `beforeRender`
* `afterRender`
* `beforeLayout`
* `afterLayout`
If View::$autoLayout is set to `false`, the template will be returned bare.
Template and layout names can point to plugin templates or layouts. Using the `Plugin.template` syntax a plugin template/layout/ can be used instead of the app ones. If the chosen plugin is not found the template will be located along the regular view path cascade.
#### Parameters
`string|null` $template optional The template being rendered.
`string|false|null` $layout optional The layout being rendered.
#### Returns
`string`
#### Throws
`Cake\View\Exception\SerializationFailureException`
When serialization fails. ### renderLayout() public
```
renderLayout(string $content, string|null $layout = null): string
```
Renders a layout. Returns output from \_render().
Several variables are created for use in layout.
#### Parameters
`string` $content Content to render in a template, wrapped by the surrounding layout.
`string|null` $layout optional Layout name
#### Returns
`string`
#### Throws
`Cake\Core\Exception\CakeException`
if there is an error in the view. ### reset() public
```
reset(string $name): $this
```
Reset the content for a block. This will overwrite any existing content.
#### Parameters
`string` $name Name of the block
#### Returns
`$this`
#### See Also
\Cake\View\ViewBlock::set() ### set() public
```
set(array|string $name, mixed $value = null): $this
```
Saves a variable or an associative array of variables for use inside a template.
#### Parameters
`array|string` $name A string or an array of data.
`mixed` $value optional Value in case $name is a string (which then works as the key). Unused if $name is an associative array, otherwise serves as the values to $name's keys.
#### Returns
`$this`
#### Throws
`RuntimeException`
If the array combine operation failed. ### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setContentType() protected
```
setContentType(): void
```
Set the response content-type based on the view's contentType()
#### Returns
`void`
### setElementCache() public
```
setElementCache(string $elementCache): $this
```
Set The cache configuration View will use to store cached elements
#### Parameters
`string` $elementCache Cache config name.
#### Returns
`$this`
#### See Also
\Cake\View\View::$elementCache ### setEventManager() public
```
setEventManager(Cake\Event\EventManagerInterface $eventManager): $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.
#### Parameters
`Cake\Event\EventManagerInterface` $eventManager the eventManager to set
#### Returns
`$this`
### setLayout() public
```
setLayout(string $name): $this
```
Set the name of the layout file to render the template inside of. The name specified is the filename of the layout in `templates/layout/` without the .php extension.
#### Parameters
`string` $name Layout file name to set.
#### Returns
`$this`
### setLayoutPath() public
```
setLayoutPath(string $path): $this
```
Set path for layout files.
#### Parameters
`string` $path Path for layout files.
#### Returns
`$this`
### setPlugin() public
```
setPlugin(string|null $name): $this
```
Sets the plugin name.
#### Parameters
`string|null` $name Plugin name.
#### Returns
`$this`
### setRequest() public
```
setRequest(Cake\Http\ServerRequest $request): $this
```
Sets the request objects and configures a number of controller properties based on the contents of the request. The properties that get set are:
* $this->request - To the $request parameter
* $this->plugin - To the value returned by $request->getParam('plugin')
#### Parameters
`Cake\Http\ServerRequest` $request Request instance.
#### Returns
`$this`
### setResponse() public
```
setResponse(Cake\Http\Response $response): $this
```
Sets the response instance.
#### Parameters
`Cake\Http\Response` $response Response instance.
#### Returns
`$this`
### setSubDir() public
```
setSubDir(string $subDir): $this
```
Set sub-directory for this template files.
#### Parameters
`string` $subDir Sub-directory name.
#### Returns
`$this`
#### See Also
\Cake\View\View::$subDir ### setTemplate() public
```
setTemplate(string $name): $this
```
Set the name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
#### Parameters
`string` $name Template file name to set.
#### Returns
`$this`
### setTemplatePath() public
```
setTemplatePath(string $path): $this
```
Set path for templates files.
#### Parameters
`string` $path Path for template files.
#### Returns
`$this`
### setTheme() public
```
setTheme(string|null $theme): $this
```
Set the view theme to use.
#### Parameters
`string|null` $theme Theme name.
#### Returns
`$this`
### start() public
```
start(string $name): $this
```
Start capturing output for a 'block'
You can use start on a block multiple times to append or prepend content in a capture mode.
```
// Append content to an existing block.
$this->start('content');
echo $this->fetch('content');
echo 'Some new content';
$this->end();
// Prepend content to an existing block
$this->start('content');
echo 'Some new content';
echo $this->fetch('content');
$this->end();
```
#### Parameters
`string` $name The name of the block to capture for.
#### Returns
`$this`
#### See Also
\Cake\View\ViewBlock::start() Property Detail
---------------
### $Blocks public @property
#### Type
`Cake\View\ViewBlock`
### $Breadcrumbs public @property
#### Type
`Cake\View\Helper\BreadcrumbsHelper`
### $Flash public @property
#### Type
`Cake\View\Helper\FlashHelper`
### $Form public @property
#### Type
`Cake\View\Helper\FormHelper`
### $Html public @property
#### Type
`Cake\View\Helper\HtmlHelper`
### $Number public @property
#### Type
`Cake\View\Helper\NumberHelper`
### $Paginator public @property
#### Type
`Cake\View\Helper\PaginatorHelper`
### $Text public @property
#### Type
`Cake\View\Helper\TextHelper`
### $Time public @property
#### Type
`Cake\View\Helper\TimeHelper`
### $Url public @property
#### Type
`Cake\View\Helper\UrlHelper`
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_current protected
The currently rendering view file. Used for resolving parent files.
#### Type
`string`
### $\_currentType protected
Currently rendering an element. Used for finding parent fragments for elements.
#### Type
`string`
### $\_defaultConfig protected
Default config options.
Use ViewBuilder::setOption()/setOptions() in your controller to set these options.
* `serialize`: Option to convert a set of view variables into a serialized response. Its value can be a string for single variable name or array for multiple names. If true all view variables will be serialized. If null or false normal view template will be rendered.
* `xmlOptions`: Option to allow setting an array of custom options for Xml::fromArray(). For e.g. 'format' as 'attributes' instead of 'tags'.
* `rootNode`: Root node name. Defaults to "response".
#### Type
`array<string, mixed>`
### $\_eventClass protected
Default class name for new event objects.
#### Type
`string`
### $\_eventManager protected
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
#### Type
`Cake\Event\EventManagerInterface|null`
### $\_ext protected
File extension. Defaults to ".php".
#### Type
`string`
### $\_helpers protected
Helpers collection
#### Type
`Cake\View\HelperRegistry`
### $\_parents protected
The names of views and their parents used with View::extend();
#### Type
`array<string>`
### $\_passedVars protected
List of variables to collect from the associated controller.
#### Type
`array<string>`
### $\_paths protected
Holds an array of paths.
#### Type
`array<string>`
### $\_pathsForPlugin protected
Holds an array of plugin paths.
#### Type
`array<string[]>`
### $\_responseType protected deprecated
Response type.
#### Type
`string`
### $\_stack protected
Content stack, used for nested templates that all use View::extend();
#### Type
`array<string>`
### $\_viewBlockClass protected
ViewBlock class.
#### Type
`string`
### $autoLayout protected
Turns on or off CakePHP's conventional mode of applying layout files. On by default. Setting to off means that layouts will not be automatically applied to rendered templates.
#### Type
`bool`
### $elementCache protected
The Cache configuration View will use to store cached elements. Changing this will change the default configuration elements are stored under. You can also choose a cache config per element.
#### Type
`string`
### $helpers protected
An array of names of built-in helpers to include.
#### Type
`array`
### $layout protected
The name of the layout file to render the template inside of. The name specified is the filename of the layout in `templates/layout/` without the .php extension.
#### Type
`string`
### $layoutPath protected
XML layouts are located in the `layouts/xml/` subdirectory
#### Type
`string`
### $name protected
Name of the controller that created the View if any.
#### Type
`string`
### $plugin protected
The name of the plugin.
#### Type
`string|null`
### $request protected
An instance of a \Cake\Http\ServerRequest object that contains information about the current request. This object contains all the information about a request and several methods for reading additional information about the request.
#### Type
`Cake\Http\ServerRequest`
### $response protected
Reference to the Response object
#### Type
`Cake\Http\Response`
### $subDir protected
XML views are located in the 'xml' subdirectory for controllers' views.
#### Type
`string`
### $template protected
The name of the template file to render. The name specified is the filename in `templates/<SubFolder>/` without the .php extension.
#### Type
`string`
### $templatePath protected
The name of the subfolder containing templates for this View.
#### Type
`string`
### $theme protected
The view theme to use.
#### Type
`string|null`
### $viewVars protected
An array of variables
#### Type
`array<string, mixed>`
| programming_docs |
cakephp Class DefaultFormatter Class DefaultFormatter
=======================
**Namespace:** [Cake\Log\Formatter](namespace-cake.log.formatter)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this class
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [format()](#format()) public
Formats message.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [setConfig()](#setConfig()) public
Sets the config.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
#### Parameters
`array<string, mixed>` $config optional Formatter config
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### format() public
```
format(mixed $level, string $message, array $context = []): string
```
Formats message.
#### Parameters
`mixed` $level `string` $message `array` $context optional #### Returns
`string`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this class
#### Type
`array<string, mixed>`
cakephp Namespace Client Namespace Client
================
### Namespaces
* [Cake\Http\Client\Adapter](namespace-cake.http.client.adapter)
* [Cake\Http\Client\Auth](namespace-cake.http.client.auth)
* [Cake\Http\Client\Exception](namespace-cake.http.client.exception)
### Interfaces
* ##### [AdapterInterface](interface-cake.http.client.adapterinterface)
Http client adapter interface.
### Classes
* ##### [FormData](class-cake.http.client.formdata)
Provides an interface for building multipart/form-encoded message bodies.
* ##### [FormDataPart](class-cake.http.client.formdatapart)
Contains the data and behavior for a single part in a Multipart FormData request body.
* ##### [Message](class-cake.http.client.message)
Base class for other HTTP requests/responses
* ##### [Request](class-cake.http.client.request)
Implements methods for HTTP requests.
* ##### [Response](class-cake.http.client.response)
Implements methods for HTTP responses.
cakephp Class ComponentRegistry Class ComponentRegistry
========================
ComponentRegistry is a registry for loaded components
Handles loading, constructing and binding events for component class objects.
**Namespace:** [Cake\Controller](namespace-cake.controller)
Property Summary
----------------
* [$\_Controller](#%24_Controller) protected `Cake\Controller\Controller|null` The controller that this collection was initialized with.
* [$\_eventClass](#%24_eventClass) protected `string` Default class name for new event objects.
* [$\_eventManager](#%24_eventManager) protected `Cake\Event\EventManagerInterface|null` Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
* [$\_loaded](#%24_loaded) protected `array<object>` Map of loaded objects.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_\_debugInfo()](#__debugInfo()) public
Debug friendly object properties.
* ##### [\_\_get()](#__get()) public
Provide public read access to the loaded objects
* ##### [\_\_isset()](#__isset()) public
Provide isset access to \_loaded
* ##### [\_\_set()](#__set()) public
Sets an object.
* ##### [\_\_unset()](#__unset()) public
Unsets an object.
* ##### [\_checkDuplicate()](#_checkDuplicate()) protected
Check for duplicate object loading.
* ##### [\_create()](#_create()) protected
Create the component instance.
* ##### [\_resolveClassName()](#_resolveClassName()) protected
Resolve a component classname.
* ##### [\_throwMissingClassError()](#_throwMissingClassError()) protected
Throws an exception when a component is missing.
* ##### [count()](#count()) public
Returns the number of loaded objects.
* ##### [dispatchEvent()](#dispatchEvent()) public
Wrapper for creating and dispatching events.
* ##### [get()](#get()) public
Get loaded object instance.
* ##### [getController()](#getController()) public
Get the controller associated with the collection.
* ##### [getEventManager()](#getEventManager()) public
Returns the Cake\Event\EventManager manager instance for this object.
* ##### [getIterator()](#getIterator()) public
Returns an array iterator.
* ##### [has()](#has()) public
Check whether a given object is loaded.
* ##### [load()](#load()) public
Loads/constructs an object instance.
* ##### [loaded()](#loaded()) public
Get the list of loaded objects.
* ##### [normalizeArray()](#normalizeArray()) public
Normalizes an object array, creates an array that makes lazy loading easier
* ##### [reset()](#reset()) public
Clear loaded instances in the registry.
* ##### [set()](#set()) public
Set an object directly into the registry by name.
* ##### [setController()](#setController()) public
Set the controller associated with the collection.
* ##### [setEventManager()](#setEventManager()) public
Returns the Cake\Event\EventManagerInterface instance for this object.
* ##### [unload()](#unload()) public
Remove an object from the registry.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Controller\Controller|null $controller = null)
```
Constructor.
#### Parameters
`Cake\Controller\Controller|null` $controller optional Controller instance.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Debug friendly object properties.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): object|null
```
Provide public read access to the loaded objects
#### Parameters
`string` $name Name of property to read
#### Returns
`object|null`
### \_\_isset() public
```
__isset(string $name): bool
```
Provide isset access to \_loaded
#### Parameters
`string` $name Name of object being checked.
#### Returns
`bool`
### \_\_set() public
```
__set(string $name, object $object): void
```
Sets an object.
#### Parameters
`string` $name Name of a property to set.
`object` $object Object to set.
#### Returns
`void`
### \_\_unset() public
```
__unset(string $name): void
```
Unsets an object.
#### Parameters
`string` $name Name of a property to unset.
#### Returns
`void`
### \_checkDuplicate() protected
```
_checkDuplicate(string $name, array<string, mixed> $config): void
```
Check for duplicate object loading.
If a duplicate is being loaded and has different configuration, that is bad and an exception will be raised.
An exception is raised, as replacing the object will not update any references other objects may have. Additionally, simply updating the runtime configuration is not a good option as we may be missing important constructor logic dependent on the configuration.
#### Parameters
`string` $name The name of the alias in the registry.
`array<string, mixed>` $config The config data for the new instance.
#### Returns
`void`
#### Throws
`RuntimeException`
When a duplicate is found. ### \_create() protected
```
_create(object|string $class, string $alias, array<string, mixed> $config): Cake\Controller\Component
```
Create the component instance.
Part of the template method for {@link \Cake\Core\ObjectRegistry::load()} Enabled components will be registered with the event manager.
#### Parameters
`object|string` $class The classname to create.
`string` $alias The alias of the component.
`array<string, mixed>` $config An array of config to use for the component.
#### Returns
`Cake\Controller\Component`
### \_resolveClassName() protected
```
_resolveClassName(string $class): string|null
```
Resolve a component classname.
Part of the template method for {@link \Cake\Core\ObjectRegistry::load()}.
#### Parameters
`string` $class Partial classname to resolve.
#### Returns
`string|null`
### \_throwMissingClassError() protected
```
_throwMissingClassError(string $class, string|null $plugin): void
```
Throws an exception when a component is missing.
Part of the template method for {@link \Cake\Core\ObjectRegistry::load()} and {@link \Cake\Core\ObjectRegistry::unload()}
#### Parameters
`string` $class The classname that is missing.
`string|null` $plugin The plugin the component is missing in.
#### Returns
`void`
#### Throws
`Cake\Controller\Exception\MissingComponentException`
### count() public
```
count(): int
```
Returns the number of loaded objects.
#### Returns
`int`
### dispatchEvent() public
```
dispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\EventInterface
```
Wrapper for creating and dispatching events.
Returns a dispatched event.
#### Parameters
`string` $name Name of the event.
`array|null` $data optional Any value you wish to be transported with this event to it can be read by listeners.
`object|null` $subject optional The object that this event applies to ($this by default).
#### Returns
`Cake\Event\EventInterface`
### get() public
```
get(string $name): object
```
Get loaded object instance.
#### Parameters
`string` $name Name of object.
#### Returns
`object`
#### Throws
`RuntimeException`
If not loaded or found. ### getController() public
```
getController(): Cake\Controller\Controller
```
Get the controller associated with the collection.
#### Returns
`Cake\Controller\Controller`
### getEventManager() public
```
getEventManager(): Cake\Event\EventManagerInterface
```
Returns the Cake\Event\EventManager manager 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.
#### Returns
`Cake\Event\EventManagerInterface`
### getIterator() public
```
getIterator(): Traversable
```
Returns an array iterator.
#### Returns
`Traversable`
### has() public
```
has(string $name): bool
```
Check whether a given object is loaded.
#### Parameters
`string` $name The object name to check for.
#### Returns
`bool`
### load() public
```
load(string $name, array<string, mixed> $config = []): mixed
```
Loads/constructs an object instance.
Will return the instance in the registry if it already exists. If a subclass provides event support, you can use `$config['enabled'] = false` to exclude constructed objects from being registered for events.
Using {@link \Cake\Controller\Component::$components} as an example. You can alias an object by setting the 'className' key, i.e.,
```
protected $components = [
'Email' => [
'className' => 'App\Controller\Component\AliasedEmailComponent'
];
];
```
All calls to the `Email` component would use `AliasedEmail` instead.
#### Parameters
`string` $name The name/class of the object to load.
`array<string, mixed>` $config optional Additional settings to use when loading the object.
#### Returns
`mixed`
#### Throws
`Exception`
If the class cannot be found. ### loaded() public
```
loaded(): array<string>
```
Get the list of loaded objects.
#### Returns
`array<string>`
### normalizeArray() public
```
normalizeArray(array $objects): array<string, array>
```
Normalizes an object array, creates an array that makes lazy loading easier
#### Parameters
`array` $objects Array of child objects to normalize.
#### Returns
`array<string, array>`
### reset() public
```
reset(): $this
```
Clear loaded instances in the registry.
If the registry subclass has an event manager, the objects will be detached from events as well.
#### Returns
`$this`
### set() public
```
set(string $name, object $object): $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
#### Parameters
`string` $name The name of the object to set in the registry.
`object` $object instance to store in the registry
#### Returns
`$this`
### setController() public
```
setController(Cake\Controller\Controller $controller): $this
```
Set the controller associated with the collection.
#### Parameters
`Cake\Controller\Controller` $controller Controller instance.
#### Returns
`$this`
### setEventManager() public
```
setEventManager(Cake\Event\EventManagerInterface $eventManager): $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.
#### Parameters
`Cake\Event\EventManagerInterface` $eventManager the eventManager to set
#### Returns
`$this`
### unload() public
```
unload(string $name): $this
```
Remove an object from the registry.
If this registry has an event manager, the object will be detached from any events as well.
#### Parameters
`string` $name The name of the object to remove from the registry.
#### Returns
`$this`
Property Detail
---------------
### $\_Controller protected
The controller that this collection was initialized with.
#### Type
`Cake\Controller\Controller|null`
### $\_eventClass protected
Default class name for new event objects.
#### Type
`string`
### $\_eventManager protected
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
#### Type
`Cake\Event\EventManagerInterface|null`
### $\_loaded protected
Map of loaded objects.
#### Type
`array<object>`
cakephp Namespace Storage Namespace Storage
=================
### Interfaces
* ##### [StorageInterface](interface-cake.auth.storage.storageinterface)
Describes the methods that any class representing an Auth data storage should comply with.
### Classes
* ##### [MemoryStorage](class-cake.auth.storage.memorystorage)
Memory based non-persistent storage for authenticated user record.
* ##### [SessionStorage](class-cake.auth.storage.sessionstorage)
Session based persistent storage for authenticated user record.
cakephp Class DateTimeTimezoneType Class DateTimeTimezoneType
===========================
Extends DateTimeType with support for time zones.
**Namespace:** [Cake\Database\Type](namespace-cake.database.type)
Property Summary
----------------
* [$\_className](#%24_className) protected `string` The classname to use when creating objects.
* [$\_format](#%24_format) protected `string` The DateTime format used when converting to string.
* [$\_localeMarshalFormat](#%24_localeMarshalFormat) protected `array|string|int` The locale-aware format `marshal()` uses when `_useLocaleParser` is true.
* [$\_marshalFormats](#%24_marshalFormats) protected `array<string>` The DateTime formats allowed by `marshal()`.
* [$\_name](#%24_name) protected `string|null` Identifier name for this type
* [$\_useLocaleMarshal](#%24_useLocaleMarshal) protected `bool` Whether `marshal()` should use locale-aware parser with `_localeMarshalFormat`.
* [$dbTimezone](#%24dbTimezone) protected `DateTimeZone|null` Database time zone.
* [$defaultTimezone](#%24defaultTimezone) protected `DateTimeZone` Default time zone.
* [$keepDatabaseTimezone](#%24keepDatabaseTimezone) protected `bool` Whether database time zone is kept when converting
* [$setToDateStart](#%24setToDateStart) protected `bool` Whether we want to override the time of the converted Time objects so it points to the start of the day.
* [$userTimezone](#%24userTimezone) protected `DateTimeZone|null` User time zone.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_parseLocaleValue()](#_parseLocaleValue()) protected
Converts a string into a DateTime object after parsing it using the locale aware parser with the format set by `setLocaleFormat()`.
* ##### [\_parseValue()](#_parseValue()) protected
Converts a string into a DateTime object after parsing it using the formats in `_marshalFormats`.
* ##### [\_setClassName()](#_setClassName()) protected
Set the classname to use when building objects.
* ##### [getBaseType()](#getBaseType()) public
Returns the base type name that this class is inheriting.
* ##### [getDateTimeClassName()](#getDateTimeClassName()) public
Get the classname used for building objects.
* ##### [getName()](#getName()) public
Returns type identifier name for this object.
* ##### [manyToPHP()](#manyToPHP()) public
Returns an array of the values converted to the PHP representation of this type.
* ##### [marshal()](#marshal()) public
Convert request data into a datetime object.
* ##### [newId()](#newId()) public
Generate a new primary key value for a given type.
* ##### [setDatabaseTimezone()](#setDatabaseTimezone()) public
Set database timezone.
* ##### [setKeepDatabaseTimezone()](#setKeepDatabaseTimezone()) public
Set whether DateTime object created from database string is converted to default time zone.
* ##### [setLocaleFormat()](#setLocaleFormat()) public
Sets the locale-aware format used by `marshal()` when parsing strings.
* ##### [setTimezone()](#setTimezone()) public deprecated
Alias for `setDatabaseTimezone()`.
* ##### [setUserTimezone()](#setUserTimezone()) public
Set user timezone.
* ##### [toDatabase()](#toDatabase()) public
Convert DateTime instance into strings.
* ##### [toPHP()](#toPHP()) public
Casts given value from a database type to a PHP equivalent.
* ##### [toStatement()](#toStatement()) public
Casts given value to Statement equivalent
* ##### [useImmutable()](#useImmutable()) public deprecated
Change the preferred class name to the FrozenTime implementation.
* ##### [useLocaleParser()](#useLocaleParser()) public
Sets whether to parse strings passed to `marshal()` using the locale-aware format set by `setLocaleFormat()`.
* ##### [useMutable()](#useMutable()) public deprecated
Change the preferred class name to the mutable Time implementation.
Method Detail
-------------
### \_\_construct() public
```
__construct(string|null $name = null)
```
Constructor
#### Parameters
`string|null` $name optional The name identifying this type
### \_parseLocaleValue() protected
```
_parseLocaleValue(string $value): Cake\I18n\I18nDateTimeInterface|null
```
Converts a string into a DateTime object after parsing it using the locale aware parser with the format set by `setLocaleFormat()`.
#### Parameters
`string` $value The value to parse and convert to an object.
#### Returns
`Cake\I18n\I18nDateTimeInterface|null`
### \_parseValue() protected
```
_parseValue(string $value): DateTimeInterface|null
```
Converts a string into a DateTime object after parsing it using the formats in `_marshalFormats`.
#### Parameters
`string` $value The value to parse and convert to an object.
#### Returns
`DateTimeInterface|null`
### \_setClassName() protected
```
_setClassName(string $class, string $fallback): void
```
Set the classname to use when building objects.
#### Parameters
`string` $class The classname to use.
`string` $fallback The classname to use when the preferred class does not exist.
#### Returns
`void`
### getBaseType() public
```
getBaseType(): string|null
```
Returns the base type name that this class is inheriting.
This is useful when extending base type for adding extra functionality, but still want the rest of the framework to use the same assumptions it would do about the base type it inherits from.
#### Returns
`string|null`
### getDateTimeClassName() public
```
getDateTimeClassName(): string
```
Get the classname used for building objects.
#### Returns
`string`
### getName() public
```
getName(): string|null
```
Returns type identifier name for this object.
#### Returns
`string|null`
### manyToPHP() public
```
manyToPHP(array $values, array<string> $fields, Cake\Database\DriverInterface $driver): array<string, mixed>
```
Returns an array of the values converted to the PHP representation of this type.
#### Parameters
`array` $values `array<string>` $fields `Cake\Database\DriverInterface` $driver #### Returns
`array<string, mixed>`
### marshal() public
```
marshal(mixed $value): DateTimeInterface|null
```
Convert request data into a datetime object.
Most useful for converting request data into PHP objects, that make sense for the rest of the ORM/Database layers.
#### Parameters
`mixed` $value Request data
#### Returns
`DateTimeInterface|null`
### newId() public
```
newId(): mixed
```
Generate a new primary key value for a given type.
This method can be used by types to create new primary key values when entities are inserted.
#### Returns
`mixed`
### setDatabaseTimezone() public
```
setDatabaseTimezone(DateTimeZone|string|null $timezone): $this
```
Set database timezone.
This is the time zone used when converting database strings to DateTime instances and converting DateTime instances to database strings.
#### Parameters
`DateTimeZone|string|null` $timezone Database timezone.
#### Returns
`$this`
#### See Also
DateTimeType::setKeepDatabaseTimezone ### setKeepDatabaseTimezone() public
```
setKeepDatabaseTimezone(bool $keep): $this
```
Set whether DateTime object created from database string is converted to default time zone.
If your database date times are in a specific time zone that you want to keep in the DateTime instance then set this to true.
When false, datetime timezones are converted to default time zone. This is default behavior.
#### Parameters
`bool` $keep If true, database time zone is kept when converting to DateTime instances.
#### Returns
`$this`
### setLocaleFormat() public
```
setLocaleFormat(array|string $format): $this
```
Sets the locale-aware format used by `marshal()` when parsing strings.
See `Cake\I18n\Time::parseDateTime()` for accepted formats.
#### Parameters
`array|string` $format The locale-aware format
#### Returns
`$this`
#### See Also
\Cake\I18n\Time::parseDateTime() ### setTimezone() public
```
setTimezone(DateTimeZone|string|null $timezone): $this
```
Alias for `setDatabaseTimezone()`.
#### Parameters
`DateTimeZone|string|null` $timezone Database timezone.
#### Returns
`$this`
### setUserTimezone() public
```
setUserTimezone(DateTimeZone|string|null $timezone): $this
```
Set user timezone.
This is the time zone used when marshalling strings to DateTime instances.
#### Parameters
`DateTimeZone|string|null` $timezone User timezone.
#### Returns
`$this`
### toDatabase() public
```
toDatabase(mixed $value, Cake\Database\DriverInterface $driver): string|null
```
Convert DateTime instance into strings.
#### Parameters
`mixed` $value The value to convert.
`Cake\Database\DriverInterface` $driver The driver instance to convert with.
#### Returns
`string|null`
### toPHP() public
```
toPHP(mixed $value, Cake\Database\DriverInterface $driver): DateTimeInterface|null
```
Casts given value from a database type to a PHP equivalent.
#### Parameters
`mixed` $value Value to be converted to PHP equivalent
`Cake\Database\DriverInterface` $driver Object from which database preferences and configuration will be extracted
#### Returns
`DateTimeInterface|null`
### toStatement() public
```
toStatement(mixed $value, Cake\Database\DriverInterface $driver): mixed
```
Casts given value to Statement equivalent
#### Parameters
`mixed` $value value to be converted to PDO statement
`Cake\Database\DriverInterface` $driver object from which database preferences and configuration will be extracted
#### Returns
`mixed`
### useImmutable() public
```
useImmutable(): $this
```
Change the preferred class name to the FrozenTime implementation.
#### Returns
`$this`
### useLocaleParser() public
```
useLocaleParser(bool $enable = true): $this
```
Sets whether to parse strings passed to `marshal()` using the locale-aware format set by `setLocaleFormat()`.
#### Parameters
`bool` $enable optional Whether to enable
#### Returns
`$this`
### useMutable() public
```
useMutable(): $this
```
Change the preferred class name to the mutable Time implementation.
#### Returns
`$this`
Property Detail
---------------
### $\_className protected
The classname to use when creating objects.
#### Type
`string`
### $\_format protected
The DateTime format used when converting to string.
#### Type
`string`
### $\_localeMarshalFormat protected
The locale-aware format `marshal()` uses when `_useLocaleParser` is true.
See `Cake\I18n\Time::parseDateTime()` for accepted formats.
#### Type
`array|string|int`
### $\_marshalFormats protected
The DateTime formats allowed by `marshal()`.
#### Type
`array<string>`
### $\_name protected
Identifier name for this type
#### Type
`string|null`
### $\_useLocaleMarshal protected
Whether `marshal()` should use locale-aware parser with `_localeMarshalFormat`.
#### Type
`bool`
### $dbTimezone protected
Database time zone.
#### Type
`DateTimeZone|null`
### $defaultTimezone protected
Default time zone.
#### Type
`DateTimeZone`
### $keepDatabaseTimezone protected
Whether database time zone is kept when converting
#### Type
`bool`
### $setToDateStart protected
Whether we want to override the time of the converted Time objects so it points to the start of the day.
This is primarily to avoid subclasses needing to re-implement the same functionality.
#### Type
`bool`
### $userTimezone protected
User time zone.
#### Type
`DateTimeZone|null`
| programming_docs |
cakephp Class BehaviorRegistry Class BehaviorRegistry
=======================
BehaviorRegistry is used as a registry for loaded behaviors and handles loading and constructing behavior objects.
This class also provides method for checking and dispatching behavior methods.
**Namespace:** [Cake\ORM](namespace-cake.orm)
Property Summary
----------------
* [$\_eventClass](#%24_eventClass) protected `string` Default class name for new event objects.
* [$\_eventManager](#%24_eventManager) protected `Cake\Event\EventManagerInterface|null` Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
* [$\_finderMap](#%24_finderMap) protected `array<string, array>` Finder method mappings.
* [$\_loaded](#%24_loaded) protected `array<object>` Map of loaded objects.
* [$\_methodMap](#%24_methodMap) protected `array<string, array>` Method mappings.
* [$\_table](#%24_table) protected `Cake\ORM\Table` The table using this registry.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Debug friendly object properties.
* ##### [\_\_get()](#__get()) public
Provide public read access to the loaded objects
* ##### [\_\_isset()](#__isset()) public
Provide isset access to \_loaded
* ##### [\_\_set()](#__set()) public
Sets an object.
* ##### [\_\_unset()](#__unset()) public
Unsets an object.
* ##### [\_checkDuplicate()](#_checkDuplicate()) protected
Check for duplicate object loading.
* ##### [\_create()](#_create()) protected
Create the behavior instance.
* ##### [\_getMethods()](#_getMethods()) protected
Get the behavior methods and ensure there are no duplicates.
* ##### [\_resolveClassName()](#_resolveClassName()) protected
Resolve a behavior classname.
* ##### [\_throwMissingClassError()](#_throwMissingClassError()) protected
Throws an exception when a behavior is missing.
* ##### [call()](#call()) public
Invoke a method on a behavior.
* ##### [callFinder()](#callFinder()) public
Invoke a finder on a behavior.
* ##### [className()](#className()) public static
Resolve a behavior classname.
* ##### [count()](#count()) public
Returns the number of loaded objects.
* ##### [dispatchEvent()](#dispatchEvent()) public
Wrapper for creating and dispatching events.
* ##### [get()](#get()) public
Get loaded object instance.
* ##### [getEventManager()](#getEventManager()) public
Returns the Cake\Event\EventManager manager instance for this object.
* ##### [getIterator()](#getIterator()) public
Returns an array iterator.
* ##### [has()](#has()) public
Check whether a given object is loaded.
* ##### [hasFinder()](#hasFinder()) public
Check if any loaded behavior implements the named finder.
* ##### [hasMethod()](#hasMethod()) public
Check if any loaded behavior implements a method.
* ##### [load()](#load()) public
Loads/constructs an object instance.
* ##### [loaded()](#loaded()) public
Get the list of loaded objects.
* ##### [normalizeArray()](#normalizeArray()) public
Normalizes an object array, creates an array that makes lazy loading easier
* ##### [reset()](#reset()) public
Clear loaded instances in the registry.
* ##### [set()](#set()) public
Set an object directly into the registry by name.
* ##### [setEventManager()](#setEventManager()) public
Returns the Cake\Event\EventManagerInterface instance for this object.
* ##### [setTable()](#setTable()) public
Attaches a table instance to this registry.
* ##### [unload()](#unload()) public
Remove an object from the registry.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\ORM\Table|null $table = null)
```
Constructor
#### Parameters
`Cake\ORM\Table|null` $table optional The table this registry is attached to.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Debug friendly object properties.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): object|null
```
Provide public read access to the loaded objects
#### Parameters
`string` $name Name of property to read
#### Returns
`object|null`
### \_\_isset() public
```
__isset(string $name): bool
```
Provide isset access to \_loaded
#### Parameters
`string` $name Name of object being checked.
#### Returns
`bool`
### \_\_set() public
```
__set(string $name, object $object): void
```
Sets an object.
#### Parameters
`string` $name Name of a property to set.
`object` $object Object to set.
#### Returns
`void`
### \_\_unset() public
```
__unset(string $name): void
```
Unsets an object.
#### Parameters
`string` $name Name of a property to unset.
#### Returns
`void`
### \_checkDuplicate() protected
```
_checkDuplicate(string $name, array<string, mixed> $config): void
```
Check for duplicate object loading.
If a duplicate is being loaded and has different configuration, that is bad and an exception will be raised.
An exception is raised, as replacing the object will not update any references other objects may have. Additionally, simply updating the runtime configuration is not a good option as we may be missing important constructor logic dependent on the configuration.
#### Parameters
`string` $name The name of the alias in the registry.
`array<string, mixed>` $config The config data for the new instance.
#### Returns
`void`
#### Throws
`RuntimeException`
When a duplicate is found. ### \_create() protected
```
_create(object|string $class, string $alias, array<string, mixed> $config): Cake\ORM\Behavior
```
Create the behavior instance.
Part of the template method for Cake\Core\ObjectRegistry::load() Enabled behaviors will be registered with the event manager.
#### Parameters
`object|string` $class The classname that is missing.
`string` $alias The alias of the object.
`array<string, mixed>` $config An array of config to use for the behavior.
#### Returns
`Cake\ORM\Behavior`
### \_getMethods() protected
```
_getMethods(Cake\ORM\Behavior $instance, string $class, string $alias): array
```
Get the behavior methods and ensure there are no duplicates.
Use the implementedEvents() method to exclude callback methods. Methods starting with `_` will be ignored, as will methods declared on Cake\ORM\Behavior
#### Parameters
`Cake\ORM\Behavior` $instance The behavior to get methods from.
`string` $class The classname that is missing.
`string` $alias The alias of the object.
#### Returns
`array`
#### Throws
`LogicException`
when duplicate methods are connected. ### \_resolveClassName() protected
```
_resolveClassName(string $class): string|null
```
Resolve a behavior classname.
Part of the template method for Cake\Core\ObjectRegistry::load()
#### Parameters
`string` $class Partial classname to resolve.
#### Returns
`string|null`
### \_throwMissingClassError() protected
```
_throwMissingClassError(string $class, string|null $plugin): void
```
Throws an exception when a behavior is missing.
Part of the template method for Cake\Core\ObjectRegistry::load() and Cake\Core\ObjectRegistry::unload()
#### Parameters
`string` $class The classname that is missing.
`string|null` $plugin The plugin the behavior is missing in.
#### Returns
`void`
#### Throws
`Cake\ORM\Exception\MissingBehaviorException`
### call() public
```
call(string $method, array $args = []): mixed
```
Invoke a method on a behavior.
#### Parameters
`string` $method The method to invoke.
`array` $args optional The arguments you want to invoke the method with.
#### Returns
`mixed`
#### Throws
`BadMethodCallException`
When the method is unknown. ### callFinder() public
```
callFinder(string $type, array $args = []): Cake\ORM\Query
```
Invoke a finder on a behavior.
#### Parameters
`string` $type The finder type to invoke.
`array` $args optional The arguments you want to invoke the method with.
#### Returns
`Cake\ORM\Query`
#### Throws
`BadMethodCallException`
When the method is unknown. ### className() public static
```
className(string $class): string|null
```
Resolve a behavior classname.
#### Parameters
`string` $class Partial classname to resolve.
#### Returns
`string|null`
### count() public
```
count(): int
```
Returns the number of loaded objects.
#### Returns
`int`
### dispatchEvent() public
```
dispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\EventInterface
```
Wrapper for creating and dispatching events.
Returns a dispatched event.
#### Parameters
`string` $name Name of the event.
`array|null` $data optional Any value you wish to be transported with this event to it can be read by listeners.
`object|null` $subject optional The object that this event applies to ($this by default).
#### Returns
`Cake\Event\EventInterface`
### get() public
```
get(string $name): object
```
Get loaded object instance.
#### Parameters
`string` $name Name of object.
#### Returns
`object`
#### Throws
`RuntimeException`
If not loaded or found. ### getEventManager() public
```
getEventManager(): Cake\Event\EventManagerInterface
```
Returns the Cake\Event\EventManager manager 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.
#### Returns
`Cake\Event\EventManagerInterface`
### getIterator() public
```
getIterator(): Traversable
```
Returns an array iterator.
#### Returns
`Traversable`
### has() public
```
has(string $name): bool
```
Check whether a given object is loaded.
#### Parameters
`string` $name The object name to check for.
#### Returns
`bool`
### hasFinder() public
```
hasFinder(string $method): bool
```
Check if any loaded behavior implements the named finder.
Will return true if any behavior provides a public method with the chosen name.
#### Parameters
`string` $method The method to check for.
#### Returns
`bool`
### hasMethod() public
```
hasMethod(string $method): bool
```
Check if any loaded behavior implements a method.
Will return true if any behavior provides a public non-finder method with the chosen name.
#### Parameters
`string` $method The method to check for.
#### Returns
`bool`
### load() public
```
load(string $name, array<string, mixed> $config = []): mixed
```
Loads/constructs an object instance.
Will return the instance in the registry if it already exists. If a subclass provides event support, you can use `$config['enabled'] = false` to exclude constructed objects from being registered for events.
Using {@link \Cake\Controller\Component::$components} as an example. You can alias an object by setting the 'className' key, i.e.,
```
protected $components = [
'Email' => [
'className' => 'App\Controller\Component\AliasedEmailComponent'
];
];
```
All calls to the `Email` component would use `AliasedEmail` instead.
#### Parameters
`string` $name The name/class of the object to load.
`array<string, mixed>` $config optional Additional settings to use when loading the object.
#### Returns
`mixed`
#### Throws
`Exception`
If the class cannot be found. ### loaded() public
```
loaded(): array<string>
```
Get the list of loaded objects.
#### Returns
`array<string>`
### normalizeArray() public
```
normalizeArray(array $objects): array<string, array>
```
Normalizes an object array, creates an array that makes lazy loading easier
#### Parameters
`array` $objects Array of child objects to normalize.
#### Returns
`array<string, array>`
### reset() public
```
reset(): $this
```
Clear loaded instances in the registry.
If the registry subclass has an event manager, the objects will be detached from events as well.
#### Returns
`$this`
### set() public
```
set(string $name, object $object): $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
#### Parameters
`string` $name The name of the object to set in the registry.
`object` $object instance to store in the registry
#### Returns
`$this`
### setEventManager() public
```
setEventManager(Cake\Event\EventManagerInterface $eventManager): $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.
#### Parameters
`Cake\Event\EventManagerInterface` $eventManager the eventManager to set
#### Returns
`$this`
### setTable() public
```
setTable(Cake\ORM\Table $table): void
```
Attaches a table instance to this registry.
#### Parameters
`Cake\ORM\Table` $table The table this registry is attached to.
#### Returns
`void`
### unload() public
```
unload(string $name): $this
```
Remove an object from the registry.
If this registry has an event manager, the object will be detached from any events as well.
#### Parameters
`string` $name The name of the object to remove from the registry.
#### Returns
`$this`
Property Detail
---------------
### $\_eventClass protected
Default class name for new event objects.
#### Type
`string`
### $\_eventManager protected
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
#### Type
`Cake\Event\EventManagerInterface|null`
### $\_finderMap protected
Finder method mappings.
#### Type
`array<string, array>`
### $\_loaded protected
Map of loaded objects.
#### Type
`array<object>`
### $\_methodMap protected
Method mappings.
#### Type
`array<string, array>`
### $\_table protected
The table using this registry.
#### Type
`Cake\ORM\Table`
cakephp Class SyslogLog Class SyslogLog
================
Syslog stream for Logging. Writes logs to the system logger
**Namespace:** [Cake\Log\Engine](namespace-cake.log.engine)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this class
* [$\_levelMap](#%24_levelMap) protected `array<int>` Used to map the string names back to their LOG\_\* constants
* [$\_open](#%24_open) protected `bool` Whether the logger connection is open or not
* [$formatter](#%24formatter) protected `Cake\Log\Formatter\AbstractFormatter`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
\_\_construct method
* ##### [\_\_destruct()](#__destruct()) public
Closes the logger connection
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_format()](#_format()) protected deprecated
Formats the message to be logged.
* ##### [\_open()](#_open()) protected
Extracts the call to openlog() in order to run unit tests on it. This function will initialize the connection to the system logger
* ##### [\_write()](#_write()) protected
Extracts the call to syslog() in order to run unit tests on it. This function will perform the actual write in the system logger
* ##### [alert()](#alert()) public
Action must be taken immediately.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [critical()](#critical()) public
Critical conditions.
* ##### [debug()](#debug()) public
Detailed debug information.
* ##### [emergency()](#emergency()) public
System is unusable.
* ##### [error()](#error()) public
Runtime errors that do not require immediate action but should typically be logged and monitored.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [info()](#info()) public
Interesting events.
* ##### [interpolate()](#interpolate()) protected
Replaces placeholders in message string with context values.
* ##### [levels()](#levels()) public
Get the levels this logger is interested in.
* ##### [log()](#log()) public
Writes a message to syslog
* ##### [notice()](#notice()) public
Normal but significant events.
* ##### [scopes()](#scopes()) public
Get the scopes this logger is interested in.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [warning()](#warning()) public
Exceptional occurrences that are not errors.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
\_\_construct method
#### Parameters
`array<string, mixed>` $config optional ### \_\_destruct() public
```
__destruct()
```
Closes the logger connection
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_format() protected
```
_format(string $message, array $context = []): string
```
Formats the message to be logged.
The context can optionally be used by log engines to interpolate variables or add additional info to the logged message.
#### Parameters
`string` $message The message to be formatted.
`array` $context optional Additional logging information for the message.
#### Returns
`string`
### \_open() protected
```
_open(string $ident, int $options, int $facility): void
```
Extracts the call to openlog() in order to run unit tests on it. This function will initialize the connection to the system logger
#### Parameters
`string` $ident the prefix to add to all messages logged
`int` $options the options flags to be used for logged messages
`int` $facility the stream or facility to log to
#### Returns
`void`
### \_write() protected
```
_write(int $priority, string $message): bool
```
Extracts the call to syslog() in order to run unit tests on it. This function will perform the actual write in the system logger
#### Parameters
`int` $priority Message priority.
`string` $message Message to log.
#### Returns
`bool`
### alert() public
```
alert(string $message, mixed[] $context = array()): void
```
Action must be taken immediately.
Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### critical() public
```
critical(string $message, mixed[] $context = array()): void
```
Critical conditions.
Example: Application component unavailable, unexpected exception.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### debug() public
```
debug(string $message, mixed[] $context = array()): void
```
Detailed debug information.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### emergency() public
```
emergency(string $message, mixed[] $context = array()): void
```
System is unusable.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### error() public
```
error(string $message, mixed[] $context = array()): void
```
Runtime errors that do not require immediate action but should typically be logged and monitored.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### info() public
```
info(string $message, mixed[] $context = array()): void
```
Interesting events.
Example: User logs in, SQL logs.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### interpolate() protected
```
interpolate(string $message, array $context = []): string
```
Replaces placeholders in message string with context values.
#### Parameters
`string` $message Formatted string
`array` $context optional Context for placeholder values.
#### Returns
`string`
### levels() public
```
levels(): array<string>
```
Get the levels this logger is interested in.
#### Returns
`array<string>`
### log() public
```
log(mixed $level, string $message, mixed[] $context = []): void
```
Writes a message to syslog
Map the $level back to a LOG\_ constant value, split multi-line messages into multiple log messages, pass all messages through the format defined in the configuration
#### Parameters
`mixed` $level The severity level of log you are making.
`string` $message The message you want to log.
`mixed[]` $context optional Additional information about the logged message
#### Returns
`void`
#### See Also
\Cake\Log\Log::$\_levels ### notice() public
```
notice(string $message, mixed[] $context = array()): void
```
Normal but significant events.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
### scopes() public
```
scopes(): array<string>|false
```
Get the scopes this logger is interested in.
#### Returns
`array<string>|false`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### warning() public
```
warning(string $message, mixed[] $context = array()): void
```
Exceptional occurrences that are not errors.
Example: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.
#### Parameters
`string` $message `mixed[]` $context optional #### Returns
`void`
Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this class
By default messages are formatted as: level: message
To override the log format (e.g. to add your own info) define the format key when configuring this logger
If you wish to include a prefix to all messages, for instance to identify the application or the web server, then use the prefix option. Please keep in mind the prefix is shared by all streams using syslog, as it is dependent of the running process. For a local prefix, to be used only by one stream, you can use the format key.
### Example:
```
Log::config('error', ]
'engine' => 'Syslog',
'levels' => ['emergency', 'alert', 'critical', 'error'],
'prefix' => 'Web Server 01'
]);
```
#### Type
`array<string, mixed>`
### $\_levelMap protected
Used to map the string names back to their LOG\_\* constants
#### Type
`array<int>`
### $\_open protected
Whether the logger connection is open or not
#### Type
`bool`
### $formatter protected
#### Type
`Cake\Log\Formatter\AbstractFormatter`
| programming_docs |
cakephp Trait EmailTrait Trait EmailTrait
=================
Make assertions on emails sent through the Cake\TestSuite\TestEmailTransport
After adding the trait to your test case, all mail transports will be replaced with TestEmailTransport which is used for making assertions and will *not* actually send emails.
**Namespace:** [Cake\TestSuite](namespace-cake.testsuite)
Method Summary
--------------
* ##### [assertMailContains()](#assertMailContains()) public
Asserts an email contains expected contents
* ##### [assertMailContainsAt()](#assertMailContainsAt()) public
Asserts an email at a specific index contains expected contents
* ##### [assertMailContainsAttachment()](#assertMailContainsAttachment()) public
Asserts an email contains expected attachment
* ##### [assertMailContainsHtml()](#assertMailContainsHtml()) public
Asserts an email contains expected html contents
* ##### [assertMailContainsHtmlAt()](#assertMailContainsHtmlAt()) public
Asserts an email at a specific index contains expected html contents
* ##### [assertMailContainsText()](#assertMailContainsText()) public
Asserts an email contains an expected text content
* ##### [assertMailContainsTextAt()](#assertMailContainsTextAt()) public
Asserts an email at a specific index contains expected text contents
* ##### [assertMailCount()](#assertMailCount()) public
Asserts an expected number of emails were sent
* ##### [assertMailSentFrom()](#assertMailSentFrom()) public
Asserts an email was sent from an address
* ##### [assertMailSentFromAt()](#assertMailSentFromAt()) public
Asserts an email at a specific index was sent from an address
* ##### [assertMailSentTo()](#assertMailSentTo()) public
Asserts an email was sent to an address
* ##### [assertMailSentToAt()](#assertMailSentToAt()) public
Asserts an email at a specific index was sent to an address
* ##### [assertMailSentWith()](#assertMailSentWith()) public
Asserts an email contains the expected value within an Email getter
* ##### [assertMailSentWithAt()](#assertMailSentWithAt()) public
Asserts an email at a specific index contains the expected value within an Email getter
* ##### [assertMailSubjectContains()](#assertMailSubjectContains()) public
Asserts an email subject contains expected contents
* ##### [assertMailSubjectContainsAt()](#assertMailSubjectContainsAt()) public
Asserts an email at a specific index contains expected html contents
* ##### [assertNoMailSent()](#assertNoMailSent()) public
Asserts that no emails were sent
* ##### [cleanupEmailTrait()](#cleanupEmailTrait()) public
Resets transport state
* ##### [setupTransports()](#setupTransports()) public
Replaces all transports with the test transport during test setup
Method Detail
-------------
### assertMailContains() public
```
assertMailContains(string $contents, string $message = ''): void
```
Asserts an email contains expected contents
#### Parameters
`string` $contents Contents
`string` $message optional Message
#### Returns
`void`
### assertMailContainsAt() public
```
assertMailContainsAt(int $at, string $contents, string $message = ''): void
```
Asserts an email at a specific index contains expected contents
#### Parameters
`int` $at Email index
`string` $contents Contents
`string` $message optional Message
#### Returns
`void`
### assertMailContainsAttachment() public
```
assertMailContainsAttachment(string $filename, array $file = [], string $message = ''): void
```
Asserts an email contains expected attachment
#### Parameters
`string` $filename Filename
`array` $file optional Additional file properties
`string` $message optional Message
#### Returns
`void`
### assertMailContainsHtml() public
```
assertMailContainsHtml(string $contents, string $message = ''): void
```
Asserts an email contains expected html contents
#### Parameters
`string` $contents Contents
`string` $message optional Message
#### Returns
`void`
### assertMailContainsHtmlAt() public
```
assertMailContainsHtmlAt(int $at, string $contents, string $message = ''): void
```
Asserts an email at a specific index contains expected html contents
#### Parameters
`int` $at Email index
`string` $contents Contents
`string` $message optional Message
#### Returns
`void`
### assertMailContainsText() public
```
assertMailContainsText(string $expected, string $message = ''): void
```
Asserts an email contains an expected text content
#### Parameters
`string` $expected Expected text.
`string` $message optional Message to display if assertion fails.
#### Returns
`void`
### assertMailContainsTextAt() public
```
assertMailContainsTextAt(int $at, string $contents, string $message = ''): void
```
Asserts an email at a specific index contains expected text contents
#### Parameters
`int` $at Email index
`string` $contents Contents
`string` $message optional Message
#### Returns
`void`
### assertMailCount() public
```
assertMailCount(int $count, string $message = ''): void
```
Asserts an expected number of emails were sent
#### Parameters
`int` $count Email count
`string` $message optional Message
#### Returns
`void`
### assertMailSentFrom() public
```
assertMailSentFrom(string $address, string $message = ''): void
```
Asserts an email was sent from an address
#### Parameters
`string` $address Email address
`string` $message optional Message
#### Returns
`void`
### assertMailSentFromAt() public
```
assertMailSentFromAt(int $at, string $address, string $message = ''): void
```
Asserts an email at a specific index was sent from an address
#### Parameters
`int` $at Email index
`string` $address Email address
`string` $message optional Message
#### Returns
`void`
### assertMailSentTo() public
```
assertMailSentTo(string $address, string $message = ''): void
```
Asserts an email was sent to an address
#### Parameters
`string` $address Email address
`string` $message optional Message
#### Returns
`void`
### assertMailSentToAt() public
```
assertMailSentToAt(int $at, string $address, string $message = ''): void
```
Asserts an email at a specific index was sent to an address
#### Parameters
`int` $at Email index
`string` $address Email address
`string` $message optional Message
#### Returns
`void`
### assertMailSentWith() public
```
assertMailSentWith(string $expected, string $parameter, string $message = ''): void
```
Asserts an email contains the expected value within an Email getter
#### Parameters
`string` $expected Contents
`string` $parameter Email getter parameter (e.g. "cc", "subject")
`string` $message optional Message
#### Returns
`void`
### assertMailSentWithAt() public
```
assertMailSentWithAt(int $at, string $expected, string $parameter, string $message = ''): void
```
Asserts an email at a specific index contains the expected value within an Email getter
#### Parameters
`int` $at Email index
`string` $expected Contents
`string` $parameter Email getter parameter (e.g. "cc", "bcc")
`string` $message optional Message
#### Returns
`void`
### assertMailSubjectContains() public
```
assertMailSubjectContains(string $contents, string $message = ''): void
```
Asserts an email subject contains expected contents
#### Parameters
`string` $contents Contents
`string` $message optional Message
#### Returns
`void`
### assertMailSubjectContainsAt() public
```
assertMailSubjectContainsAt(int $at, string $contents, string $message = ''): void
```
Asserts an email at a specific index contains expected html contents
#### Parameters
`int` $at Email index
`string` $contents Contents
`string` $message optional Message
#### Returns
`void`
### assertNoMailSent() public
```
assertNoMailSent(string $message = ''): void
```
Asserts that no emails were sent
#### Parameters
`string` $message optional Message
#### Returns
`void`
### cleanupEmailTrait() public
```
cleanupEmailTrait(): void
```
Resets transport state
#### Returns
`void`
### setupTransports() public
```
setupTransports(): void
```
Replaces all transports with the test transport during test setup
#### Returns
`void`
cakephp Class Form Class Form
===========
Form abstraction used to create forms not tied to ORM backed models, or to other permanent datastores. Ideal for implementing forms on top of API services, or contact forms.
### Building a form
This class is most useful when subclassed. In a subclass you should define the `_buildSchema`, `validationDefault` and optionally, the `_execute` methods. These allow you to declare your form's fields, validation and primary action respectively.
Forms are conventionally placed in the `App\Form` namespace.
**Namespace:** [Cake\Form](namespace-cake.form)
Constants
---------
* `string` **BUILD\_VALIDATOR\_EVENT**
```
'Form.buildValidator'
```
The name of the event dispatched when a validator has been built.
* `string` **DEFAULT\_VALIDATOR**
```
'default'
```
Name of default validation set.
* `string` **VALIDATOR\_PROVIDER\_NAME**
```
'form'
```
The alias this object is assigned to validators as.
Property Summary
----------------
* [$\_data](#%24_data) protected `array` Form's data.
* [$\_errors](#%24_errors) protected `array` The errors if any
* [$\_eventClass](#%24_eventClass) protected `string` Default class name for new event objects.
* [$\_eventManager](#%24_eventManager) protected `Cake\Event\EventManagerInterface|null` Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
* [$\_schema](#%24_schema) protected `Cake\Form\Schema|null` The schema used by this form.
* [$\_schemaClass](#%24_schemaClass) protected `string` Schema class.
* [$\_validatorClass](#%24_validatorClass) protected `string` Validator class.
* [$\_validators](#%24_validators) protected `arrayCake\Validation\Validator>` A list of validation objects indexed by name
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Get the printable version of a Form instance.
* ##### [\_buildSchema()](#_buildSchema()) protected
A hook method intended to be implemented by subclasses.
* ##### [\_execute()](#_execute()) protected
Hook method to be implemented in subclasses.
* ##### [createValidator()](#createValidator()) protected
Creates a validator using a custom method inside your class.
* ##### [dispatchEvent()](#dispatchEvent()) public
Wrapper for creating and dispatching events.
* ##### [execute()](#execute()) public
Execute the form if it is valid.
* ##### [getData()](#getData()) public
Get field data.
* ##### [getErrors()](#getErrors()) public
Get the errors in the form
* ##### [getEventManager()](#getEventManager()) public
Returns the Cake\Event\EventManager manager instance for this object.
* ##### [getSchema()](#getSchema()) public
Get the schema for this form.
* ##### [getValidator()](#getValidator()) public
Returns the validation rules tagged with $name. It is possible to have multiple different named validation sets, this is useful when you need to use varying rules when saving from different routines in your system.
* ##### [hasValidator()](#hasValidator()) public
Checks whether a validator has been set.
* ##### [implementedEvents()](#implementedEvents()) public
Get the Form callbacks this form is interested in.
* ##### [schema()](#schema()) public deprecated
Get/Set the schema for this form.
* ##### [set()](#set()) public
Saves a variable or an associative array of variables for use inside form data.
* ##### [setData()](#setData()) public
Set form data.
* ##### [setErrors()](#setErrors()) public
Set the errors in the form.
* ##### [setEventManager()](#setEventManager()) public
Returns the Cake\Event\EventManagerInterface instance for this object.
* ##### [setSchema()](#setSchema()) public
Set the schema for this form.
* ##### [setValidator()](#setValidator()) public
This method stores a custom validator under the given name.
* ##### [validate()](#validate()) public
Used to check if $data passes this form's validation.
* ##### [validationDefault()](#validationDefault()) public
Returns the default validator object. Subclasses can override this function to add a default validation set to the validator object.
* ##### [validationMethodExists()](#validationMethodExists()) protected
Checks if validation method exists.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Event\EventManager|null $eventManager = null)
```
Constructor
#### Parameters
`Cake\Event\EventManager|null` $eventManager optional The event manager. Defaults to a new instance.
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Get the printable version of a Form instance.
#### Returns
`array<string, mixed>`
### \_buildSchema() protected
```
_buildSchema(Cake\Form\Schema $schema): Cake\Form\Schema
```
A hook method intended to be implemented by subclasses.
You can use this method to define the schema using the methods on {@link \Cake\Form\Schema}, or loads a pre-defined schema from a concrete class.
#### Parameters
`Cake\Form\Schema` $schema The schema to customize.
#### Returns
`Cake\Form\Schema`
### \_execute() protected
```
_execute(array $data): bool
```
Hook method to be implemented in subclasses.
Used by `execute()` to execute the form's action.
#### Parameters
`array` $data Form data.
#### Returns
`bool`
### createValidator() protected
```
createValidator(string $name): Cake\Validation\Validator
```
Creates a validator using a custom method inside your class.
This method is used only to build a new validator and it does not store it in your object. If you want to build and reuse validators, use getValidator() method instead.
#### Parameters
`string` $name The name of the validation set to create.
#### Returns
`Cake\Validation\Validator`
#### Throws
`RuntimeException`
### dispatchEvent() public
```
dispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\EventInterface
```
Wrapper for creating and dispatching events.
Returns a dispatched event.
#### Parameters
`string` $name Name of the event.
`array|null` $data optional Any value you wish to be transported with this event to it can be read by listeners.
`object|null` $subject optional The object that this event applies to ($this by default).
#### Returns
`Cake\Event\EventInterface`
### execute() public
```
execute(array $data, array<string, mixed> $options = []): bool
```
Execute the form if it is valid.
First validates the form, then calls the `_execute()` hook method. This hook method can be implemented in subclasses to perform the action of the form. This may be sending email, interacting with a remote API, or anything else you may need.
### Options:
* validate: Set to `false` to disable validation. Can also be a string of the validator ruleset to be applied. Defaults to `true`/`'default'`.
#### Parameters
`array` $data Form data.
`array<string, mixed>` $options optional List of options.
#### Returns
`bool`
### getData() public
```
getData(string|null $field = null): mixed
```
Get field data.
#### Parameters
`string|null` $field optional The field name or null to get data array with all fields.
#### Returns
`mixed`
### getErrors() public
```
getErrors(): array
```
Get the errors in the form
Will return the errors from the last call to `validate()` or `execute()`.
#### Returns
`array`
### getEventManager() public
```
getEventManager(): Cake\Event\EventManagerInterface
```
Returns the Cake\Event\EventManager manager 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.
#### Returns
`Cake\Event\EventManagerInterface`
### getSchema() public
```
getSchema(): Cake\Form\Schema
```
Get the schema for this form.
This method will call `_buildSchema()` when the schema is first built. This hook method lets you configure the schema or load a pre-defined one.
#### Returns
`Cake\Form\Schema`
### getValidator() public
```
getValidator(string|null $name = null): Cake\Validation\Validator
```
Returns the validation rules tagged with $name. It is possible to have multiple different named validation sets, this is useful when you need to use varying rules when saving from different routines in your system.
If a validator has not been set earlier, this method will build a valiator using a method inside your class.
For example, if you wish to create a validation set called 'forSubscription', you will need to create a method in your Table subclass as follows:
```
public function validationForSubscription($validator)
{
return $validator
->add('email', 'valid-email', ['rule' => 'email'])
->add('password', 'valid', ['rule' => 'notBlank'])
->requirePresence('username');
}
$validator = $this->getValidator('forSubscription');
```
You can implement the method in `validationDefault` in your Table subclass should you wish to have a validation set that applies in cases where no other set is specified.
If a $name argument has not been provided, the default validator will be returned. You can configure your default validator name in a `DEFAULT_VALIDATOR` class constant.
#### Parameters
`string|null` $name optional The name of the validation set to return.
#### Returns
`Cake\Validation\Validator`
### hasValidator() public
```
hasValidator(string $name): bool
```
Checks whether a validator has been set.
#### Parameters
`string` $name The name of a validator.
#### Returns
`bool`
### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Get the Form callbacks this form is interested in.
The conventional method map is:
* Form.buildValidator => buildValidator
#### Returns
`array<string, mixed>`
### schema() public
```
schema(Cake\Form\Schema|null $schema = null): Cake\Form\Schema
```
Get/Set the schema for this form.
This method will call `_buildSchema()` when the schema is first built. This hook method lets you configure the schema or load a pre-defined one.
#### Parameters
`Cake\Form\Schema|null` $schema optional The schema to set, or null.
#### Returns
`Cake\Form\Schema`
### set() public
```
set(array|string $name, mixed $value = null): $this
```
Saves a variable or an associative array of variables for use inside form data.
#### Parameters
`array|string` $name The key to write, can be a dot notation value. Alternatively can be an array containing key(s) and value(s).
`mixed` $value optional Value to set for var
#### Returns
`$this`
### setData() public
```
setData(array $data): $this
```
Set form data.
#### Parameters
`array` $data Data array.
#### Returns
`$this`
### setErrors() public
```
setErrors(array $errors): $this
```
Set the errors in the form.
```
$errors = [
'field_name' => ['rule_name' => 'message']
];
$form->setErrors($errors);
```
#### Parameters
`array` $errors Errors list.
#### Returns
`$this`
### setEventManager() public
```
setEventManager(Cake\Event\EventManagerInterface $eventManager): $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.
#### Parameters
`Cake\Event\EventManagerInterface` $eventManager the eventManager to set
#### Returns
`$this`
### setSchema() public
```
setSchema(Cake\Form\Schema $schema): $this
```
Set the schema for this form.
#### Parameters
`Cake\Form\Schema` $schema The schema to set
#### Returns
`$this`
### setValidator() public
```
setValidator(string $name, Cake\Validation\Validator $validator): $this
```
This method stores a custom validator under the given name.
You can build the object by yourself and store it in your object:
```
$validator = new \Cake\Validation\Validator();
$validator
->add('email', 'valid-email', ['rule' => 'email'])
->add('password', 'valid', ['rule' => 'notBlank'])
->allowEmpty('bio');
$this->setValidator('forSubscription', $validator);
```
#### Parameters
`string` $name The name of a validator to be set.
`Cake\Validation\Validator` $validator Validator object to be set.
#### Returns
`$this`
### validate() public
```
validate(array $data, string|null $validator = null): bool
```
Used to check if $data passes this form's validation.
#### Parameters
`array` $data The data to check.
`string|null` $validator optional Validator name.
#### Returns
`bool`
#### Throws
`RuntimeException`
If validator is invalid. ### validationDefault() public
```
validationDefault(Cake\Validation\Validator $validator): Cake\Validation\Validator
```
Returns the default validator object. Subclasses can override this function to add a default validation set to the validator object.
#### Parameters
`Cake\Validation\Validator` $validator The validator that can be modified to add some rules to it.
#### Returns
`Cake\Validation\Validator`
### validationMethodExists() protected
```
validationMethodExists(string $name): bool
```
Checks if validation method exists.
#### Parameters
`string` $name Validation method name.
#### Returns
`bool`
Property Detail
---------------
### $\_data protected
Form's data.
#### Type
`array`
### $\_errors protected
The errors if any
#### Type
`array`
### $\_eventClass protected
Default class name for new event objects.
#### Type
`string`
### $\_eventManager protected
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
#### Type
`Cake\Event\EventManagerInterface|null`
### $\_schema protected
The schema used by this form.
#### Type
`Cake\Form\Schema|null`
### $\_schemaClass protected
Schema class.
#### Type
`string`
### $\_validatorClass protected
Validator class.
#### Type
`string`
### $\_validators protected
A list of validation objects indexed by name
#### Type
`arrayCake\Validation\Validator>`
| programming_docs |
cakephp Class ExceptionTrap Class ExceptionTrap
====================
Entry point to CakePHP's exception handling.
Using the `register()` method you can attach an ExceptionTrap to PHP's default exception handler and register a shutdown handler to handle fatal errors.
When exceptions are trapped the `Exception.beforeRender` event is triggered. Then exceptions are logged (if enabled) and finally 'rendered' using the defined renderer.
Stopping the `Exception.beforeRender` event has no effect, as we always need to render a response to an exception and custom renderers should be used if you want to replace or skip rendering an exception.
If undefined, an ExceptionRenderer will be selected based on the current SAPI (CLI or Web).
**Namespace:** [Cake\Error](namespace-cake.error)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Configuration options. Generally these will be defined in your config/app.php
* [$\_eventClass](#%24_eventClass) protected `string` Default class name for new event objects.
* [$\_eventManager](#%24_eventManager) protected `Cake\Event\EventManagerInterface|null` Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
* [$callbacks](#%24callbacks) protected `arrayClosure>` A list of handling callbacks.
* [$disabled](#%24disabled) protected `bool` Track if this trap was removed from the global handler.
* [$registeredTrap](#%24registeredTrap) protected static `Cake\Error\ExceptionTrap|null` The currently registered global exception handler
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [chooseRenderer()](#chooseRenderer()) protected
Choose an exception renderer based on config or the SAPI
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [dispatchEvent()](#dispatchEvent()) public
Wrapper for creating and dispatching events.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getEventManager()](#getEventManager()) public
Returns the Cake\Event\EventManager manager instance for this object.
* ##### [handleException()](#handleException()) public
Handle uncaught exceptions.
* ##### [handleFatalError()](#handleFatalError()) public
Display/Log a fatal error.
* ##### [handleShutdown()](#handleShutdown()) public
Shutdown handler
* ##### [increaseMemoryLimit()](#increaseMemoryLimit()) public
Increases the PHP "memory\_limit" ini setting by the specified amount in kilobytes
* ##### [instance()](#instance()) public static
Get the registered global instance if set.
* ##### [logException()](#logException()) public
Log an exception.
* ##### [logInternalError()](#logInternalError()) public
Trigger an error that occurred during rendering an exception.
* ##### [logger()](#logger()) public
Get an instance of the logger.
* ##### [register()](#register()) public
Attach this ExceptionTrap to PHP's default exception handler.
* ##### [renderer()](#renderer()) public
Get an instance of the renderer.
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setEventManager()](#setEventManager()) public
Returns the Cake\Event\EventManagerInterface instance for this object.
* ##### [unregister()](#unregister()) public
Remove this instance from the singleton
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $options = [])
```
Constructor
#### Parameters
`array<string, mixed>` $options optional An options array. See $\_defaultConfig.
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### chooseRenderer() protected
```
chooseRenderer(): class-stringCake\Error\ExceptionRendererInterface>
```
Choose an exception renderer based on config or the SAPI
#### Returns
`class-stringCake\Error\ExceptionRendererInterface>`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### dispatchEvent() public
```
dispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\EventInterface
```
Wrapper for creating and dispatching events.
Returns a dispatched event.
#### Parameters
`string` $name Name of the event.
`array|null` $data optional Any value you wish to be transported with this event to it can be read by listeners.
`object|null` $subject optional The object that this event applies to ($this by default).
#### Returns
`Cake\Event\EventInterface`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getEventManager() public
```
getEventManager(): Cake\Event\EventManagerInterface
```
Returns the Cake\Event\EventManager manager 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.
#### Returns
`Cake\Event\EventManagerInterface`
### handleException() public
```
handleException(Throwable $exception): void
```
Handle uncaught exceptions.
Uses a template method provided by subclasses to display errors in an environment appropriate way.
#### Parameters
`Throwable` $exception Exception instance.
#### Returns
`void`
#### Throws
`Exception`
When renderer class not found #### See Also
https://secure.php.net/manual/en/function.set-exception-handler.php ### handleFatalError() public
```
handleFatalError(int $code, string $description, string $file, int $line): void
```
Display/Log a fatal error.
#### Parameters
`int` $code Code of error
`string` $description Error description
`string` $file File on which error occurred
`int` $line Line that triggered the error
#### Returns
`void`
### handleShutdown() public
```
handleShutdown(): void
```
Shutdown handler
Convert fatal errors into exceptions that we can render.
#### Returns
`void`
### increaseMemoryLimit() public
```
increaseMemoryLimit(int $additionalKb): void
```
Increases the PHP "memory\_limit" ini setting by the specified amount in kilobytes
#### Parameters
`int` $additionalKb Number in kilobytes
#### Returns
`void`
### instance() public static
```
instance(): Cake\Error\ExceptionTrap|null
```
Get the registered global instance if set.
Keep in mind that the global state contained here is mutable and the object returned by this method could be a stale value.
#### Returns
`Cake\Error\ExceptionTrap|null`
### logException() public
```
logException(Throwable $exception, Psr\Http\Message\ServerRequestInterface|null $request = null): void
```
Log an exception.
Primarily a public function to ensure consistency between global exception handling and the ErrorHandlerMiddleware. This method will apply the `skipLog` filter skipping logging if the exception should not be logged.
After logging is attempted the `Exception.beforeRender` event is triggered.
#### Parameters
`Throwable` $exception The exception to log
`Psr\Http\Message\ServerRequestInterface|null` $request optional The optional request
#### Returns
`void`
### logInternalError() public
```
logInternalError(Throwable $exception): void
```
Trigger an error that occurred during rendering an exception.
By triggering an E\_USER\_ERROR we can end up in the default exception handling which will log the rendering failure, and hopefully render an error page.
#### Parameters
`Throwable` $exception Exception to log
#### Returns
`void`
### logger() public
```
logger(): Cake\Error\ErrorLoggerInterface
```
Get an instance of the logger.
#### Returns
`Cake\Error\ErrorLoggerInterface`
### register() public
```
register(): void
```
Attach this ExceptionTrap to PHP's default exception handler.
This will replace the existing exception handler, and the previous exception handler will be discarded.
#### Returns
`void`
### renderer() public
```
renderer(Throwable $exception, Psr\Http\Message\ServerRequestInterface|null $request = null): Cake\Error\ExceptionRendererInterface
```
Get an instance of the renderer.
#### Parameters
`Throwable` $exception Exception to render
`Psr\Http\Message\ServerRequestInterface|null` $request optional The request if possible.
#### Returns
`Cake\Error\ExceptionRendererInterface`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setEventManager() public
```
setEventManager(Cake\Event\EventManagerInterface $eventManager): $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.
#### Parameters
`Cake\Event\EventManagerInterface` $eventManager the eventManager to set
#### Returns
`$this`
### unregister() public
```
unregister(): void
```
Remove this instance from the singleton
If this instance is not currently the registered singleton nothing happens.
#### Returns
`void`
Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Configuration options. Generally these will be defined in your config/app.php
* `exceptionRenderer` - string - The class responsible for rendering uncaught exceptions. The chosen class will be used for for both CLI and web environments. If you want different classes used in CLI and web environments you'll need to write that conditional logic as well. The conventional location for custom renderers is in `src/Error`. Your exception renderer needs to implement the `render()` method and return either a string or Http\Response.
* `log` Set to false to disable logging.
* `logger` - string - The class name of the error logger to use.
* `trace` - boolean - Whether or not backtraces should be included in logged exceptions.
* `skipLog` - array - List of exceptions to skip for logging. Exceptions that extend one of the listed exceptions will also not be logged. E.g.:
```
'skipLog' => ['Cake\Http\Exception\NotFoundException', 'Cake\Http\Exception\UnauthorizedException']
```
This option is forwarded to the configured `logger`
* `extraFatalErrorMemory` - int - The number of megabytes to increase the memory limit by when a fatal error is encountered. This allows breathing room to complete logging or error handling.
* `stderr` Used in console environments so that renderers have access to the current console output stream.
#### Type
`array<string, mixed>`
### $\_eventClass protected
Default class name for new event objects.
#### Type
`string`
### $\_eventManager protected
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
#### Type
`Cake\Event\EventManagerInterface|null`
### $callbacks protected
A list of handling callbacks.
Callbacks are invoked for each error that is handled. Callbacks are invoked in the order they are attached.
#### Type
`arrayClosure>`
### $disabled protected
Track if this trap was removed from the global handler.
#### Type
`bool`
### $registeredTrap protected static
The currently registered global exception handler
This is best effort as we can't know if/when another exception handler is registered.
#### Type
`Cake\Error\ExceptionTrap|null`
cakephp Class Package Class Package
==============
Message Catalog
**Namespace:** [Cake\I18n](namespace-cake.i18n)
Property Summary
----------------
* [$fallback](#%24fallback) protected `string|null` The name of a fallback package to use when a message key does not exist.
* [$formatter](#%24formatter) protected `string` The name of the formatter to use when formatting translated messages.
* [$messages](#%24messages) protected `array<array|string>` Message keys and translations in this package.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [addMessage()](#addMessage()) public
Adds one message for this package.
* ##### [addMessages()](#addMessages()) public
Adds new messages for this package.
* ##### [getFallback()](#getFallback()) public
Gets the fallback package name.
* ##### [getFormatter()](#getFormatter()) public
Gets the formatter name for this package.
* ##### [getMessage()](#getMessage()) public
Gets the message of the given key for this package.
* ##### [getMessages()](#getMessages()) public
Gets the messages for this package.
* ##### [setFallback()](#setFallback()) public
Sets the fallback package name.
* ##### [setFormatter()](#setFormatter()) public
Sets the formatter name for this package.
* ##### [setMessages()](#setMessages()) public
Sets the messages for this package.
Method Detail
-------------
### \_\_construct() public
```
__construct(string $formatter = 'default', string|null $fallback = null, array<array|string> $messages = [])
```
Constructor.
#### Parameters
`string` $formatter optional The name of the formatter to use.
`string|null` $fallback optional The name of the fallback package to use.
`array<array|string>` $messages optional The messages in this package.
### addMessage() public
```
addMessage(string $key, array|string $message): void
```
Adds one message for this package.
#### Parameters
`string` $key the key of the message
`array|string` $message the actual message
#### Returns
`void`
### addMessages() public
```
addMessages(array<array|string> $messages): void
```
Adds new messages for this package.
#### Parameters
`array<array|string>` $messages The messages to add in this package.
#### Returns
`void`
### getFallback() public
```
getFallback(): string|null
```
Gets the fallback package name.
#### Returns
`string|null`
### getFormatter() public
```
getFormatter(): string
```
Gets the formatter name for this package.
#### Returns
`string`
### getMessage() public
```
getMessage(string $key): array|string|false
```
Gets the message of the given key for this package.
#### Parameters
`string` $key the key of the message to return
#### Returns
`array|string|false`
### getMessages() public
```
getMessages(): array<array|string>
```
Gets the messages for this package.
#### Returns
`array<array|string>`
### setFallback() public
```
setFallback(string|null $fallback): void
```
Sets the fallback package name.
#### Parameters
`string|null` $fallback The fallback package name.
#### Returns
`void`
### setFormatter() public
```
setFormatter(string $formatter): void
```
Sets the formatter name for this package.
#### Parameters
`string` $formatter The formatter name for this package.
#### Returns
`void`
### setMessages() public
```
setMessages(array<array|string> $messages): void
```
Sets the messages for this package.
#### Parameters
`array<array|string>` $messages The messages for this package.
#### Returns
`void`
Property Detail
---------------
### $fallback protected
The name of a fallback package to use when a message key does not exist.
#### Type
`string|null`
### $formatter protected
The name of the formatter to use when formatting translated messages.
#### Type
`string`
### $messages protected
Message keys and translations in this package.
#### Type
`array<array|string>`
cakephp Class Collection Class Collection
=================
Represents a database schema collection
Used to access information about the tables, and other data in a database.
**Namespace:** [Cake\Database\Schema](namespace-cake.database.schema)
Property Summary
----------------
* [$\_connection](#%24_connection) protected `Cake\Database\Connection` Connection object
* [$\_dialect](#%24_dialect) protected `Cake\Database\Schema\SchemaDialect` Schema dialect instance.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_reflect()](#_reflect()) protected
Helper method for running each step of the reflection process.
* ##### [describe()](#describe()) public
Get the column metadata for a table.
* ##### [listTables()](#listTables()) public
Get the list of tables and views available in the current connection.
* ##### [listTablesWithoutViews()](#listTablesWithoutViews()) public
Get the list of tables, excluding any views, available in the current connection.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Database\Connection $connection)
```
Constructor.
#### Parameters
`Cake\Database\Connection` $connection The connection instance.
### \_reflect() protected
```
_reflect(string $stage, string $name, array<string, mixed> $config, Cake\Database\Schema\TableSchema $schema): void
```
Helper method for running each step of the reflection process.
#### Parameters
`string` $stage The stage name.
`string` $name The table name.
`array<string, mixed>` $config The config data.
`Cake\Database\Schema\TableSchema` $schema The table schema instance.
#### Returns
`void`
#### Throws
`Cake\Database\Exception\DatabaseException`
on query failure. ### describe() public
```
describe(string $name, array<string, mixed> $options = []): Cake\Database\Schema\TableSchema
```
Get the column metadata for a table.
The name can include a database schema name in the form 'schema.table'.
Caching will be applied if `cacheMetadata` key is present in the Connection configuration options. Defaults to \_cake*model* when true.
### Options
* `forceRefresh` - Set to true to force rebuilding the cached metadata. Defaults to false.
#### Parameters
`string` $name The name of the table to describe.
`array<string, mixed>` $options optional The options to use, see above.
#### Returns
`Cake\Database\Schema\TableSchema`
#### Throws
`Cake\Database\Exception\DatabaseException`
when table cannot be described. ### listTables() public
```
listTables(): array<string>
```
Get the list of tables and views available in the current connection.
#### Returns
`array<string>`
### listTablesWithoutViews() public
```
listTablesWithoutViews(): array<string>
```
Get the list of tables, excluding any views, available in the current connection.
#### Returns
`array<string>`
Property Detail
---------------
### $\_connection protected
Connection object
#### Type
`Cake\Database\Connection`
### $\_dialect protected
Schema dialect instance.
#### Type
`Cake\Database\Schema\SchemaDialect`
| programming_docs |
cakephp Class FormContext Class FormContext
==================
Provides a context provider for {@link \Cake\Form\Form} instances.
This context provider simply fulfils the interface requirements that FormHelper has and allows access to the form data.
**Namespace:** [Cake\View\Form](namespace-cake.view.form)
Constants
---------
* `array<string>` **VALID\_ATTRIBUTES**
```
['length', 'precision', 'comment', 'null', 'default']
```
Property Summary
----------------
* [$\_form](#%24_form) protected `Cake\Form\Form` The form object.
* [$\_validator](#%24_validator) protected `string|null` Validator name.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [\_schemaDefault()](#_schemaDefault()) protected
Get default value from form schema for given field.
* ##### [attributes()](#attributes()) public
Get an associative array of other attributes for a field name.
* ##### [error()](#error()) public
Get the errors for a given field
* ##### [fieldNames()](#fieldNames()) public
Get the field names of the top level object in this context.
* ##### [getMaxLength()](#getMaxLength()) public
Get maximum length of a field from model validation.
* ##### [getPrimaryKey()](#getPrimaryKey()) public
Get the fields used in the context as a primary key.
* ##### [getRequiredMessage()](#getRequiredMessage()) public
Gets the default "required" error message for a field
* ##### [hasError()](#hasError()) public
Check whether a field has an error attached to it
* ##### [isCreate()](#isCreate()) public
Returns whether this form is for a create operation.
* ##### [isPrimaryKey()](#isPrimaryKey()) public
Returns true if the passed field name is part of the primary key for this context
* ##### [isRequired()](#isRequired()) public
Check if a given field is 'required'.
* ##### [primaryKey()](#primaryKey()) public deprecated
Get the fields used in the context as a primary key.
* ##### [type()](#type()) public
Get the abstract field type for a given field name.
* ##### [val()](#val()) public
Get the current value for a given field.
Method Detail
-------------
### \_\_construct() public
```
__construct(array $context)
```
Constructor.
#### Parameters
`array` $context Context info.
### \_schemaDefault() protected
```
_schemaDefault(string $field): mixed
```
Get default value from form schema for given field.
#### Parameters
`string` $field Field name.
#### Returns
`mixed`
### attributes() public
```
attributes(string $field): array
```
Get an associative array of other attributes for a field name.
#### Parameters
`string` $field #### Returns
`array`
### error() public
```
error(string $field): array
```
Get the errors for a given field
#### Parameters
`string` $field #### Returns
`array`
### fieldNames() public
```
fieldNames(): array<string>
```
Get the field names of the top level object in this context.
#### Returns
`array<string>`
### getMaxLength() public
```
getMaxLength(string $field): int|null
```
Get maximum length of a field from model validation.
#### Parameters
`string` $field #### Returns
`int|null`
### getPrimaryKey() public
```
getPrimaryKey(): array<string>
```
Get the fields used in the context as a primary key.
#### Returns
`array<string>`
### getRequiredMessage() public
```
getRequiredMessage(string $field): string|null
```
Gets the default "required" error message for a field
#### Parameters
`string` $field #### Returns
`string|null`
### hasError() public
```
hasError(string $field): bool
```
Check whether a field has an error attached to it
#### Parameters
`string` $field #### Returns
`bool`
### isCreate() public
```
isCreate(): bool
```
Returns whether this form is for a create operation.
#### Returns
`bool`
### isPrimaryKey() public
```
isPrimaryKey(string $field): bool
```
Returns true if the passed field name is part of the primary key for this context
#### Parameters
`string` $field #### Returns
`bool`
### isRequired() public
```
isRequired(string $field): bool|null
```
Check if a given field is 'required'.
In this context class, this is simply defined by the 'required' array.
#### Parameters
`string` $field #### Returns
`bool|null`
### primaryKey() public
```
primaryKey(): array<string>
```
Get the fields used in the context as a primary key.
#### Returns
`array<string>`
### type() public
```
type(string $field): string|null
```
Get the abstract field type for a given field name.
#### Parameters
`string` $field #### Returns
`string|null`
### val() public
```
val(string $field, array<string, mixed> $options = []): mixed
```
Get the current value for a given field.
Classes implementing this method can optionally have a second argument `$options`. Valid key for `$options` array are:
* `default`: Default value to return if no value found in data or context record.
+ `schemaDefault`: Boolean indicating whether default value from context's schema should be used if it's not explicitly provided.
#### Parameters
`string` $field `array<string, mixed>` $options optional #### Returns
`mixed`
Property Detail
---------------
### $\_form protected
The form object.
#### Type
`Cake\Form\Form`
### $\_validator protected
Validator name.
#### Type
`string|null`
cakephp Namespace Retry Namespace Retry
===============
### Classes
* ##### [ErrorCodeWaitStrategy](class-cake.database.retry.errorcodewaitstrategy)
Implements retry strategy based on db error codes and wait interval.
* ##### [ReconnectStrategy](class-cake.database.retry.reconnectstrategy)
Makes sure the connection to the database is alive before authorizing the retry of an action.
cakephp Class TestEmailTransport Class TestEmailTransport
=========================
TestEmailTransport
Set this as the email transport to capture emails for later assertions
**Namespace:** [Cake\TestSuite](namespace-cake.testsuite)
**See:** \Cake\TestSuite\EmailTrait
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this class
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [checkRecipient()](#checkRecipient()) protected
Check that at least one destination header is set.
* ##### [clearMessages()](#clearMessages()) public static
Clears list of emails that have been sent
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getMessages()](#getMessages()) public static
Gets emails sent
* ##### [replaceAllTransports()](#replaceAllTransports()) public static
Replaces all currently configured transports with this one
* ##### [send()](#send()) public
Stores email for later assertions
* ##### [setConfig()](#setConfig()) public
Sets the config.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Constructor
#### Parameters
`array<string, mixed>` $config optional Configuration options.
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### checkRecipient() protected
```
checkRecipient(Cake\Mailer\Message $message): void
```
Check that at least one destination header is set.
#### Parameters
`Cake\Mailer\Message` $message Message instance.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
If at least one of to, cc or bcc is not specified. ### clearMessages() public static
```
clearMessages(): void
```
Clears list of emails that have been sent
#### Returns
`void`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getMessages() public static
```
getMessages(): arrayCake\Mailer\Message>
```
Gets emails sent
#### Returns
`arrayCake\Mailer\Message>`
### replaceAllTransports() public static
```
replaceAllTransports(): void
```
Replaces all currently configured transports with this one
#### Returns
`void`
### send() public
```
send(Cake\Mailer\Message $message): array{headers: string, message: string}
```
Stores email for later assertions
#### Parameters
`Cake\Mailer\Message` $message Message
#### Returns
`array{headers: string, message: string}`
### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this class
#### Type
`array<string, mixed>`
cakephp Class LoggedQuery Class LoggedQuery
==================
Contains a query string, the params used to executed it, time taken to do it and the number of rows found or affected by its execution.
**Namespace:** [Cake\Database\Log](namespace-cake.database.log)
Property Summary
----------------
* [$driver](#%24driver) public `Cake\Database\DriverInterface|null` Driver executing the query
* [$error](#%24error) public `Exception|null` The exception that was thrown by the execution of this query
* [$numRows](#%24numRows) public `int` Number of rows affected or returned by the query execution
* [$params](#%24params) public `array` Associative array with the params bound to the query string
* [$query](#%24query) public `string` Query string that was executed
* [$took](#%24took) public `float` Number of milliseconds this query took to complete
Method Summary
--------------
* ##### [\_\_toString()](#__toString()) public
Returns the string representation of this logged query
* ##### [getContext()](#getContext()) public
Get the logging context data for a query.
* ##### [interpolate()](#interpolate()) protected
Helper function used to replace query placeholders by the real params used to execute the query
* ##### [jsonSerialize()](#jsonSerialize()) public
Returns data that will be serialized as JSON
Method Detail
-------------
### \_\_toString() public
```
__toString(): string
```
Returns the string representation of this logged query
#### Returns
`string`
### getContext() public
```
getContext(): array<string, mixed>
```
Get the logging context data for a query.
#### Returns
`array<string, mixed>`
### interpolate() protected
```
interpolate(): string
```
Helper function used to replace query placeholders by the real params used to execute the query
#### Returns
`string`
### jsonSerialize() public
```
jsonSerialize(): array<string, mixed>
```
Returns data that will be serialized as JSON
#### Returns
`array<string, mixed>`
Property Detail
---------------
### $driver public
Driver executing the query
#### Type
`Cake\Database\DriverInterface|null`
### $error public
The exception that was thrown by the execution of this query
#### Type
`Exception|null`
### $numRows public
Number of rows affected or returned by the query execution
#### Type
`int`
### $params public
Associative array with the params bound to the query string
#### Type
`array`
### $query public
Query string that was executed
#### Type
`string`
### $took public
Number of milliseconds this query took to complete
#### Type
`float`
cakephp Class FileSent Class FileSent
===============
FileSent
**Namespace:** [Cake\TestSuite\Constraint\Response](namespace-cake.testsuite.constraint.response)
Property Summary
----------------
* [$response](#%24response) protected `Cake\Http\Response`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_getBodyAsString()](#_getBodyAsString()) protected
Get the response body as string
* ##### [additionalFailureDescription()](#additionalFailureDescription()) protected
Return additional failure description where needed.
* ##### [count()](#count()) public
Counts the number of constraint elements.
* ##### [evaluate()](#evaluate()) public
Evaluates the constraint for parameter $other.
* ##### [exporter()](#exporter()) protected
* ##### [fail()](#fail()) protected
Throws an exception for the given compared value and test description.
* ##### [failureDescription()](#failureDescription()) protected
Overwrites the descriptions so we can remove the automatic "expected" message
* ##### [failureDescriptionInContext()](#failureDescriptionInContext()) protected
Returns the description of the failure when this constraint appears in context of an $operator expression.
* ##### [matches()](#matches()) public
Checks assertion
* ##### [reduce()](#reduce()) protected
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
* ##### [toString()](#toString()) public
Assertion message
* ##### [toStringInContext()](#toStringInContext()) protected
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
Method Detail
-------------
### \_\_construct() public
```
__construct(Psr\Http\Message\ResponseInterface|null $response)
```
Constructor
#### Parameters
`Psr\Http\Message\ResponseInterface|null` $response Response
### \_getBodyAsString() protected
```
_getBodyAsString(): string
```
Get the response body as string
#### Returns
`string`
### additionalFailureDescription() protected
```
additionalFailureDescription(mixed $other): string
```
Return additional failure description where needed.
The function can be overridden to provide additional failure information like a diff
#### Parameters
`mixed` $other evaluated value or object
#### Returns
`string`
### count() public
```
count(): int
```
Counts the number of constraint elements.
#### Returns
`int`
### evaluate() public
```
evaluate(mixed $other, string $description = '', bool $returnResult = false): ?bool
```
Evaluates the constraint for parameter $other.
If $returnResult is set to false (the default), an exception is thrown in case of a failure. null is returned otherwise.
If $returnResult is true, the result of the evaluation is returned as a boolean value instead: true in case of success, false in case of a failure.
#### Parameters
$other `string` $description optional `bool` $returnResult optional #### Returns
`?bool`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### exporter() protected
```
exporter(): Exporter
```
#### Returns
`Exporter`
### fail() protected
```
fail(mixed $other, string $description, ComparisonFailure $comparisonFailure = null): void
```
Throws an exception for the given compared value and test description.
#### Parameters
`mixed` $other evaluated value or object
`string` $description Additional information about the test
`ComparisonFailure` $comparisonFailure optional #### Returns
`void`
#### Throws
`SebastianBergmann\RecursionContext\InvalidArgumentException`
`ExpectationFailedException`
### failureDescription() protected
```
failureDescription(mixed $other): string
```
Overwrites the descriptions so we can remove the automatic "expected" message
The beginning of failure messages is "Failed asserting that" in most cases. This method should return the second part of that sentence.
To provide additional failure information additionalFailureDescription can be used.
#### Parameters
`mixed` $other Value
#### Returns
`string`
### failureDescriptionInContext() protected
```
failureDescriptionInContext(Operator $operator, mixed $role, mixed $other): string
```
Returns the description of the failure when this constraint appears in context of an $operator expression.
The purpose of this method is to provide meaningful failure description in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct messages in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
`mixed` $other evaluated value or object
#### Returns
`string`
### matches() public
```
matches(mixed $other): bool
```
Checks assertion
This method can be overridden to implement the evaluation algorithm.
#### Parameters
`mixed` $other Expected type
#### Returns
`bool`
### reduce() protected
```
reduce(): self
```
Reduces the sub-expression starting at $this by skipping degenerate sub-expression and returns first descendant constraint that starts a non-reducible sub-expression.
Returns $this for terminal constraints and for operators that start non-reducible sub-expression, or the nearest descendant of $this that starts a non-reducible sub-expression.
A constraint expression may be modelled as a tree with non-terminal nodes (operators) and terminal nodes. For example:
LogicalOr (operator, non-terminal)
* LogicalAnd (operator, non-terminal) | + IsType('int') (terminal) | + GreaterThan(10) (terminal)
* LogicalNot (operator, non-terminal)
+ IsType('array') (terminal)
A degenerate sub-expression is a part of the tree, that effectively does not contribute to the evaluation of the expression it appears in. An example of degenerate sub-expression is a BinaryOperator constructed with single operand or nested BinaryOperators, each with single operand. An expression involving a degenerate sub-expression is equivalent to a reduced expression with the degenerate sub-expression removed, for example
LogicalAnd (operator)
* LogicalOr (degenerate operator) | + LogicalAnd (degenerate operator) | + IsType('int') (terminal)
* GreaterThan(10) (terminal)
is equivalent to
LogicalAnd (operator)
* IsType('int') (terminal)
* GreaterThan(10) (terminal)
because the subexpression
* LogicalOr
+ LogicalAnd
- -
is degenerate. Calling reduce() on the LogicalOr object above, as well as on LogicalAnd, shall return the IsType('int') instance.
Other specific reductions can be implemented, for example cascade of LogicalNot operators
* LogicalNot
+ LogicalNot +LogicalNot
- IsTrue
can be reduced to
LogicalNot
* IsTrue
#### Returns
`self`
### toString() public
```
toString(): string
```
Assertion message
#### Returns
`string`
### toStringInContext() protected
```
toStringInContext(Operator $operator, mixed $role): string
```
Returns a custom string representation of the constraint object when it appears in context of an $operator expression.
The purpose of this method is to provide meaningful descriptive string in context of operators such as LogicalNot. Native PHPUnit constraints are supported out of the box by LogicalNot, but externally developed ones had no way to provide correct strings in this context.
The method shall return empty string, when it does not handle customization by itself.
#### Parameters
`Operator` $operator the $operator of the expression
`mixed` $role role of $this constraint in the $operator expression
#### Returns
`string`
Property Detail
---------------
### $response protected
#### Type
`Cake\Http\Response`
| programming_docs |
cakephp Class CacheListCommand Class CacheListCommand
=======================
CacheList command.
**Namespace:** [Cake\Command](namespace-cake.command)
Constants
---------
* `int` **CODE\_ERROR**
```
1
```
Default error code
* `int` **CODE\_SUCCESS**
```
0
```
Default success code
Property Summary
----------------
* [$\_modelFactories](#%24_modelFactories) protected `array<callableCake\Datasource\Locator\LocatorInterface>` A list of overridden model factory functions.
* [$\_modelType](#%24_modelType) protected `string` The model type to use.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
* [$modelClass](#%24modelClass) protected deprecated `string|null` This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
* [$name](#%24name) protected `string` The name of this command.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_setModelClass()](#_setModelClass()) protected
Set the modelClass property based on conventions.
* ##### [abort()](#abort()) public
Halt the the current process with a StopException.
* ##### [buildOptionParser()](#buildOptionParser()) public
Hook method for defining this command's option parser.
* ##### [defaultName()](#defaultName()) public static
Get the command name.
* ##### [displayHelp()](#displayHelp()) protected
Output help content
* ##### [execute()](#execute()) public
Get the list of cache prefixes
* ##### [executeCommand()](#executeCommand()) public
Execute another command with the provided set of arguments.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getDescription()](#getDescription()) public static
Get the command description.
* ##### [getModelType()](#getModelType()) public
Get the model type to be used by this class
* ##### [getName()](#getName()) public
Get the command name.
* ##### [getOptionParser()](#getOptionParser()) public
Get the option parser.
* ##### [getRootName()](#getRootName()) public
Get the root command name.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [initialize()](#initialize()) public
Hook method invoked by CakePHP when a command is about to be executed.
* ##### [loadModel()](#loadModel()) public deprecated
Loads and constructs repository objects required by this object
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [modelFactory()](#modelFactory()) public
Override a existing callable to generate repositories of a given type.
* ##### [run()](#run()) public
Run the command.
* ##### [setModelType()](#setModelType()) public
Set the model type to be used by this class
* ##### [setName()](#setName()) public
Set the name this command uses in the collection.
* ##### [setOutputLevel()](#setOutputLevel()) protected
Set the output level based on the Arguments.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
Method Detail
-------------
### \_\_construct() public
```
__construct()
```
Constructor
By default CakePHP will construct command objects when building the CommandCollection for your application.
### \_setModelClass() protected
```
_setModelClass(string $name): void
```
Set the modelClass property based on conventions.
If the property is already set it will not be overwritten
#### Parameters
`string` $name Class name.
#### Returns
`void`
### abort() public
```
abort(int $code = self::CODE_ERROR): void
```
Halt the the current process with a StopException.
#### Parameters
`int` $code optional The exit code to use.
#### Returns
`void`
#### Throws
`Cake\Console\Exception\StopException`
### buildOptionParser() public
```
buildOptionParser(Cake\Console\ConsoleOptionParser $parser): Cake\Console\ConsoleOptionParser
```
Hook method for defining this command's option parser.
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The parser to be defined
#### Returns
`Cake\Console\ConsoleOptionParser`
#### See Also
https://book.cakephp.org/4/en/console-commands/option-parsers.html ### defaultName() public static
```
defaultName(): string
```
Get the command name.
Returns the command name based on class name. For e.g. for a command with class name `UpdateTableCommand` the default name returned would be `'update_table'`.
#### Returns
`string`
### displayHelp() protected
```
displayHelp(Cake\Console\ConsoleOptionParser $parser, Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Output help content
#### Parameters
`Cake\Console\ConsoleOptionParser` $parser The option parser.
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### execute() public
```
execute(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): int|null
```
Get the list of cache prefixes
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`int|null`
### executeCommand() public
```
executeCommand(Cake\Console\CommandInterface|string $command, array $args = [], Cake\Console\ConsoleIo|null $io = null): int|null
```
Execute another command with the provided set of arguments.
If you are using a string command name, that command's dependencies will not be resolved with the application container. Instead you will need to pass the command as an object with all of its dependencies.
#### Parameters
`Cake\Console\CommandInterface|string` $command The command class name or command instance.
`array` $args optional The arguments to invoke the command with.
`Cake\Console\ConsoleIo|null` $io optional The ConsoleIo instance to use for the executed command.
#### Returns
`int|null`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getDescription() public static
```
getDescription(): string
```
Get the command description.
#### Returns
`string`
### getModelType() public
```
getModelType(): string
```
Get the model type to be used by this class
#### Returns
`string`
### getName() public
```
getName(): string
```
Get the command name.
#### Returns
`string`
### getOptionParser() public
```
getOptionParser(): Cake\Console\ConsoleOptionParser
```
Get the option parser.
You can override buildOptionParser() to define your options & arguments.
#### Returns
`Cake\Console\ConsoleOptionParser`
#### Throws
`RuntimeException`
When the parser is invalid ### getRootName() public
```
getRootName(): string
```
Get the root command name.
#### Returns
`string`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### initialize() public
```
initialize(): void
```
Hook method invoked by CakePHP when a command is about to be executed.
Override this method and implement expensive/important setup steps that should not run on every command run. This method will be called *before* the options and arguments are validated and processed.
#### Returns
`void`
### loadModel() public
```
loadModel(string|null $modelClass = null, string|null $modelType = null): Cake\Datasource\RepositoryInterface
```
Loads and constructs repository objects required by this object
Typically used to load ORM Table objects as required. Can also be used to load other types of repository objects your application uses.
If a repository provider does not return an object a MissingModelException will be thrown.
#### Parameters
`string|null` $modelClass optional Name of model class to load. Defaults to $this->modelClass. The name can be an alias like `'Post'` or FQCN like `App\Model\Table\PostsTable::class`.
`string|null` $modelType optional The type of repository to load. Defaults to the getModelType() value.
#### Returns
`Cake\Datasource\RepositoryInterface`
#### Throws
`Cake\Datasource\Exception\MissingModelException`
If the model class cannot be found.
`UnexpectedValueException`
If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty. ### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### modelFactory() public
```
modelFactory(string $type, Cake\Datasource\Locator\LocatorInterface|callable $factory): void
```
Override a existing callable to generate repositories of a given type.
#### Parameters
`string` $type The name of the repository type the factory function is for.
`Cake\Datasource\Locator\LocatorInterface|callable` $factory The factory function used to create instances.
#### Returns
`void`
### run() public
```
run(array $argv, Cake\Console\ConsoleIo $io): int|null
```
Run the command.
#### Parameters
`array` $argv `Cake\Console\ConsoleIo` $io #### Returns
`int|null`
### setModelType() public
```
setModelType(string $modelType): $this
```
Set the model type to be used by this class
#### Parameters
`string` $modelType The model type
#### Returns
`$this`
### setName() public
```
setName(string $name): $this
```
Set the name this command uses in the collection.
Generally invoked by the CommandCollection when the command is added. Required to have at least one space in the name so that the root command can be calculated.
#### Parameters
`string` $name #### Returns
`$this`
### setOutputLevel() protected
```
setOutputLevel(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void
```
Set the output level based on the Arguments.
#### Parameters
`Cake\Console\Arguments` $args The command arguments.
`Cake\Console\ConsoleIo` $io The console io
#### Returns
`void`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
Property Detail
---------------
### $\_modelFactories protected
A list of overridden model factory functions.
#### Type
`array<callableCake\Datasource\Locator\LocatorInterface>`
### $\_modelType protected
The model type to use.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
### $modelClass protected deprecated
This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
Example: For an object named 'Comments', the modelClass would be 'Comments'. Plugin classes should use `Plugin.Comments` style names to correctly load models from the correct plugin.
Use empty string to not use auto-loading on this object. Null auto-detects based on controller name.
#### Type
`string|null`
### $name protected
The name of this command.
#### Type
`string`
cakephp Class MissingDispatcherFilterException Class MissingDispatcherFilterException
=======================================
Exception raised when a Dispatcher filter could not be found
**Namespace:** [Cake\Routing\Exception](namespace-cake.routing.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Class BaseAuthenticate Class BaseAuthenticate
=======================
Base Authentication class with common methods and properties.
**Abstract**
**Namespace:** [Cake\Auth](namespace-cake.auth)
Property Summary
----------------
* [$\_config](#%24_config) protected `array<string, mixed>` Runtime config
* [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults
* [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` Default config for this object.
* [$\_needsPasswordRehash](#%24_needsPasswordRehash) protected `bool` Whether the user authenticated by this class requires their password to be rehashed with another algorithm.
* [$\_passwordHasher](#%24_passwordHasher) protected `Cake\Auth\AbstractPasswordHasher|null` Password hasher instance.
* [$\_registry](#%24_registry) protected `Cake\Controller\ComponentRegistry` A Component registry, used to get more components.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_configDelete()](#_configDelete()) protected
Deletes a single config key.
* ##### [\_configRead()](#_configRead()) protected
Reads a config key.
* ##### [\_configWrite()](#_configWrite()) protected
Writes a config key.
* ##### [\_findUser()](#_findUser()) protected
Find a user record using the username and password provided.
* ##### [\_query()](#_query()) protected
Get query object for fetching user from database.
* ##### [authenticate()](#authenticate()) abstract public
Authenticate a user based on the request information.
* ##### [configShallow()](#configShallow()) public
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getConfig()](#getConfig()) public
Returns the config.
* ##### [getConfigOrFail()](#getConfigOrFail()) public
Returns the config for this specific key.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [getUser()](#getUser()) public
Get a user based on information in the request. Primarily used by stateless authentication systems like basic and digest auth.
* ##### [implementedEvents()](#implementedEvents()) public
Returns a list of all events that this authenticate class will listen to.
* ##### [needsPasswordRehash()](#needsPasswordRehash()) public
Returns whether the password stored in the repository for the logged in user requires to be rehashed with another algorithm
* ##### [passwordHasher()](#passwordHasher()) public
Return password hasher object
* ##### [setConfig()](#setConfig()) public
Sets the config.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
* ##### [unauthenticated()](#unauthenticated()) public
Handle unauthenticated access attempt. In implementation valid return values can be:
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Controller\ComponentRegistry $registry, array<string, mixed> $config = [])
```
Constructor
#### Parameters
`Cake\Controller\ComponentRegistry` $registry The Component registry used on this request.
`array<string, mixed>` $config optional Array of config to use.
### \_configDelete() protected
```
_configDelete(string $key): void
```
Deletes a single config key.
#### Parameters
`string` $key Key to delete.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_configRead() protected
```
_configRead(string|null $key): mixed
```
Reads a config key.
#### Parameters
`string|null` $key Key to read.
#### Returns
`mixed`
### \_configWrite() protected
```
_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void
```
Writes a config key.
#### Parameters
`array<string, mixed>|string` $key Key to write to.
`mixed` $value Value to write.
`string|bool` $merge optional True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.
#### Returns
`void`
#### Throws
`Cake\Core\Exception\CakeException`
if attempting to clobber existing config ### \_findUser() protected
```
_findUser(string $username, string|null $password = null): array<string, mixed>|false
```
Find a user record using the username and password provided.
Input passwords will be hashed even when a user doesn't exist. This helps mitigate timing attacks that are attempting to find valid usernames.
#### Parameters
`string` $username The username/identifier.
`string|null` $password optional The password, if not provided password checking is skipped and result of find is returned.
#### Returns
`array<string, mixed>|false`
### \_query() protected
```
_query(string $username): Cake\ORM\Query
```
Get query object for fetching user from database.
#### Parameters
`string` $username The username/identifier.
#### Returns
`Cake\ORM\Query`
### authenticate() abstract public
```
authenticate(Cake\Http\ServerRequest $request, Cake\Http\Response $response): array<string, mixed>|false
```
Authenticate a user based on the request information.
#### Parameters
`Cake\Http\ServerRequest` $request Request to get authentication information from.
`Cake\Http\Response` $response A response object that can have headers added.
#### Returns
`array<string, mixed>|false`
### configShallow() public
```
configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this
```
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
#### Returns
`$this`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getConfig() public
```
getConfig(string|null $key = null, mixed $default = null): mixed
```
Returns the config.
### 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
`string|null` $key optional The key to get or null for the whole config.
`mixed` $default optional The return value when the key does not exist.
#### Returns
`mixed`
### getConfigOrFail() public
```
getConfigOrFail(string $key): mixed
```
Returns the config for this specific key.
The config value for this key must exist, it can never be null.
#### Parameters
`string` $key The key to get.
#### Returns
`mixed`
#### Throws
`InvalidArgumentException`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### getUser() public
```
getUser(Cake\Http\ServerRequest $request): array<string, mixed>|false
```
Get a user based on information in the request. Primarily used by stateless authentication systems like basic and digest auth.
#### Parameters
`Cake\Http\ServerRequest` $request Request object.
#### Returns
`array<string, mixed>|false`
### implementedEvents() public
```
implementedEvents(): array<string, mixed>
```
Returns a list of all events that this authenticate class will listen to.
An authenticate class can listen to following events fired by AuthComponent:
* `Auth.afterIdentify` - Fired after a user has been identified using one of configured authenticate class. The callback function should have signature like `afterIdentify(EventInterface $event, array $user)` when `$user` is the identified user record.
* `Auth.logout` - Fired when AuthComponent::logout() is called. The callback function should have signature like `logout(EventInterface $event, array $user)` where `$user` is the user about to be logged out.
#### Returns
`array<string, mixed>`
### needsPasswordRehash() public
```
needsPasswordRehash(): bool
```
Returns whether the password stored in the repository for the logged in user requires to be rehashed with another algorithm
#### Returns
`bool`
### passwordHasher() public
```
passwordHasher(): Cake\Auth\AbstractPasswordHasher
```
Return password hasher object
#### Returns
`Cake\Auth\AbstractPasswordHasher`
#### Throws
`RuntimeException`
If password hasher class not found or it does not extend AbstractPasswordHasher ### setConfig() public
```
setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this
```
Sets the config.
### 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
`array<string, mixed>|string` $key The key to set, or a complete array of configs.
`mixed|null` $value optional The value to set.
`bool` $merge optional Whether to recursively merge or overwrite existing config, defaults to true.
#### Returns
`$this`
#### Throws
`Cake\Core\Exception\CakeException`
When trying to set a key that is invalid. ### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
### unauthenticated() public
```
unauthenticated(Cake\Http\ServerRequest $request, Cake\Http\Response $response): Cake\Http\Response|null|void
```
Handle unauthenticated access attempt. In implementation valid return values can be:
* Null - No action taken, AuthComponent should return appropriate response.
* \Cake\Http\Response - A response object, which will cause AuthComponent to simply return that response.
#### Parameters
`Cake\Http\ServerRequest` $request A request object.
`Cake\Http\Response` $response A response object.
#### Returns
`Cake\Http\Response|null|void`
Property Detail
---------------
### $\_config protected
Runtime config
#### Type
`array<string, mixed>`
### $\_configInitialized protected
Whether the config property has already been configured with defaults
#### Type
`bool`
### $\_defaultConfig protected
Default config for this object.
* `fields` The fields to use to identify a user by.
* `userModel` The alias for users table, defaults to Users.
* `finder` The finder method to use to fetch user record. Defaults to 'all'. You can set finder name as string or an array where key is finder name and value is an array passed to `Table::find()` options. E.g. ['finderName' => ['some\_finder\_option' => 'some\_value']]
* `passwordHasher` Password hasher class. Can be a string specifying class name or an array containing `className` key, any other keys will be passed as config to the class. Defaults to 'Default'.
#### Type
`array<string, mixed>`
### $\_needsPasswordRehash protected
Whether the user authenticated by this class requires their password to be rehashed with another algorithm.
#### Type
`bool`
### $\_passwordHasher protected
Password hasher instance.
#### Type
`Cake\Auth\AbstractPasswordHasher|null`
### $\_registry protected
A Component registry, used to get more components.
#### Type
`Cake\Controller\ComponentRegistry`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
| programming_docs |
cakephp Class Time Class Time
===========
Extends the built-in DateTime class to provide handy methods and locale-aware formatting helpers
**Namespace:** [Cake\I18n](namespace-cake.i18n)
**Deprecated:** 4.3.0 Use the immutable alternative `FrozenTime` instead.
Constants
---------
* `int` **DAYS\_PER\_WEEK**
```
7
```
* `string` **DEFAULT\_TO\_STRING\_FORMAT**
```
'Y-m-d H:i:s'
```
Default format to use for \_\_toString method when type juggling occurs.
* `int` **FRIDAY**
```
5
```
* `int` **HOURS\_PER\_DAY**
```
24
```
* `int` **MINUTES\_PER\_HOUR**
```
60
```
* `int` **MONDAY**
```
1
```
* `int` **MONTHS\_PER\_QUARTER**
```
3
```
* `int` **MONTHS\_PER\_YEAR**
```
12
```
* `int` **SATURDAY**
```
6
```
* `int` **SECONDS\_PER\_MINUTE**
```
60
```
* `int` **SUNDAY**
```
7
```
* `int` **THURSDAY**
```
4
```
* `int` **TUESDAY**
```
2
```
* `string` **UNIX\_TIMESTAMP\_FORMAT**
```
'unixTimestampFormat'
```
serialise the value as a Unix Timestamp
* `int` **WEDNESDAY**
```
3
```
* `int` **WEEKS\_PER\_YEAR**
```
52
```
* `int` **YEARS\_PER\_CENTURY**
```
100
```
* `int` **YEARS\_PER\_DECADE**
```
10
```
Property Summary
----------------
* [$\_formatters](#%24_formatters) protected static `arrayIntlDateFormatter>` In-memory cache of date formatters
* [$\_jsonEncodeFormat](#%24_jsonEncodeFormat) protected static `Closure|array<int>|string|int` The format to use when converting this object to JSON.
* [$\_lastErrors](#%24_lastErrors) protected static `array` Holds the last error generated by createFromFormat
* [$\_toStringFormat](#%24_toStringFormat) protected static `array<int>|string|int` The format to use when formatting a time using `Cake\I18n\Time::i18nFormat()` and `__toString`. This format is also used by `parseDateTime()`.
* [$age](#%24age) public @property-read `int` does a diffInYears() with default parameters
* [$day](#%24day) public @property-read `int`
* [$dayOfWeek](#%24dayOfWeek) public @property-read `int` 1 (for Monday) through 7 (for Sunday)
* [$dayOfWeekName](#%24dayOfWeekName) public @property-read `string`
* [$dayOfYear](#%24dayOfYear) public @property-read `int` 0 through 365
* [$days](#%24days) protected static `array` Names of days of the week.
* [$daysInMonth](#%24daysInMonth) public @property-read `int` number of days in the given month
* [$defaultLocale](#%24defaultLocale) protected static `string|null` The default locale to be used for displaying formatted date strings.
* [$diffFormatter](#%24diffFormatter) protected static `Cake\Chronos\DifferenceFormatterInterface` Instance of the diff formatting object.
* [$dst](#%24dst) public @property-read `bool` daylight savings time indicator, true if DST, false otherwise
* [$hour](#%24hour) public @property-read `int`
* [$lenientParsing](#%24lenientParsing) protected static `bool` Whether lenient parsing is enabled for IntlDateFormatter.
* [$local](#%24local) public @property-read `bool` checks if the timezone is local, true if local, false otherwise
* [$micro](#%24micro) public @property-read `int`
* [$microsecond](#%24microsecond) public @property-read `int`
* [$minute](#%24minute) public @property-read `int`
* [$month](#%24month) public @property-read `int`
* [$niceFormat](#%24niceFormat) public static `array<int>|string|int` The format to use when formatting a time using `Cake\I18n\Time::nice()`
* [$offset](#%24offset) public @property-read `int` the timezone offset in seconds from UTC
* [$offsetHours](#%24offsetHours) public @property-read `int` the timezone offset in hours from UTC
* [$quarter](#%24quarter) public @property-read `int` the quarter of this instance, 1 - 4
* [$relativePattern](#%24relativePattern) protected static `string` Regex for relative period.
* [$second](#%24second) public @property-read `int`
* [$timestamp](#%24timestamp) public @property-read `int` seconds since the Unix Epoch
* [$timezone](#%24timezone) public @property-read `DateTimeZone|string` the current timezone
* [$timezoneName](#%24timezoneName) public @property-read `string`
* [$toStringFormat](#%24toStringFormat) protected static `string` Format to use for \_\_toString method when type juggling occurs.
* [$tz](#%24tz) public @property-read `DateTimeZone|string` alias of timezone
* [$tzName](#%24tzName) public @property-read `string`
* [$utc](#%24utc) public @property-read `bool` checks if the timezone is UTC, true if UTC, false otherwise
* [$weekEndsAt](#%24weekEndsAt) protected static `int` Last day of week
* [$weekOfMonth](#%24weekOfMonth) public @property-read `int` 1 through 5
* [$weekOfYear](#%24weekOfYear) public @property-read `int` ISO-8601 week number of year, weeks starting on Monday
* [$weekStartsAt](#%24weekStartsAt) protected static `int` First day of week
* [$weekendDays](#%24weekendDays) protected static `array` Days of weekend
* [$wordAccuracy](#%24wordAccuracy) public static `array<string>` The format to use when formatting a time using `Time::timeAgoInWords()` and the difference is less than `Time::$wordEnd`
* [$wordEnd](#%24wordEnd) public static `string` The end of relative time telling
* [$wordFormat](#%24wordFormat) public static `array<int>|string|int` The format to use when formatting a time using `Cake\I18n\Time::timeAgoInWords()` and the difference is more than `Cake\I18n\Time::$wordEnd`
* [$year](#%24year) public @property-read `int`
* [$yearIso](#%24yearIso) public @property-read `int`
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Create a new mutable time instance.
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns the data that should be displayed when debugging this object
* ##### [\_\_get()](#__get()) public
Get a part of the ChronosInterface object
* ##### [\_\_isset()](#__isset()) public
Check if an attribute exists on the object
* ##### [\_\_set()](#__set()) public
Set a part of the ChronosInterface object
* ##### [\_\_toString()](#__toString()) public
Format the instance as a string using the set format
* ##### [\_formatObject()](#_formatObject()) protected
Returns a translated and localized date string. Implements what IntlDateFormatter::formatObject() is in PHP 5.5+
* ##### [addDay()](#addDay()) public
Add a day to the instance
* ##### [addDays()](#addDays()) public
Add days to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addHour()](#addHour()) public
Add an hour to the instance
* ##### [addHours()](#addHours()) public
Add hours to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addMinute()](#addMinute()) public
Add a minute to the instance
* ##### [addMinutes()](#addMinutes()) public
Add minutes to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addMonth()](#addMonth()) public
Add a month to the instance.
* ##### [addMonthWithOverflow()](#addMonthWithOverflow()) public
Add a month with overflow to the instance.
* ##### [addMonths()](#addMonths()) public
Add months to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addMonthsWithOverflow()](#addMonthsWithOverflow()) public
Add months with overflowing to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addSecond()](#addSecond()) public
Add a second to the instance
* ##### [addSeconds()](#addSeconds()) public
Add seconds to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addWeek()](#addWeek()) public
Add a week to the instance
* ##### [addWeekday()](#addWeekday()) public
Add a weekday to the instance
* ##### [addWeekdays()](#addWeekdays()) public
Add weekdays to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addWeeks()](#addWeeks()) public
Add weeks to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [addYear()](#addYear()) public
Add a year to the instance
* ##### [addYearWithOverflow()](#addYearWithOverflow()) public
Add a year with overflow to the instance
* ##### [addYears()](#addYears()) public
Add years to the instance. Positive $value travel forward while negative $value travel into the past.
* ##### [addYearsWithOverflow()](#addYearsWithOverflow()) public
Add years with overflowing to the instance. Positive $value travels forward while negative $value travels into the past.
* ##### [average()](#average()) public
Modify the current instance to the average of a given instance (default now) and the current instance.
* ##### [between()](#between()) public
Determines if the instance is between two others
* ##### [closest()](#closest()) public
Get the closest date from the instance.
* ##### [copy()](#copy()) public
Get a copy of the instance
* ##### [create()](#create()) public static
Create a new ChronosInterface instance from a specific date and time.
* ##### [createFromArray()](#createFromArray()) public static
Creates a ChronosInterface instance from an array of date and time values.
* ##### [createFromDate()](#createFromDate()) public static
Create a ChronosInterface instance from just a date. The time portion is set to now.
* ##### [createFromFormat()](#createFromFormat()) public static
Create a ChronosInterface instance from a specific format
* ##### [createFromTime()](#createFromTime()) public static
Create a ChronosInterface instance from just a time. The date portion is set to today.
* ##### [createFromTimestamp()](#createFromTimestamp()) public static
Create a ChronosInterface instance from a timestamp
* ##### [createFromTimestampUTC()](#createFromTimestampUTC()) public static
Create a ChronosInterface instance from an UTC timestamp
* ##### [day()](#day()) public
Set the instance's day
* ##### [diffFiltered()](#diffFiltered()) public
Get the difference by the given interval using a filter callable
* ##### [diffForHumans()](#diffForHumans()) public
Get the difference in a human readable format.
* ##### [diffFormatter()](#diffFormatter()) public static
Get the difference formatter instance or overwrite the current one.
* ##### [diffInDays()](#diffInDays()) public
Get the difference in days
* ##### [diffInDaysFiltered()](#diffInDaysFiltered()) public
Get the difference in days using a filter callable
* ##### [diffInHours()](#diffInHours()) public
Get the difference in hours
* ##### [diffInHoursFiltered()](#diffInHoursFiltered()) public
Get the difference in hours using a filter callable
* ##### [diffInMinutes()](#diffInMinutes()) public
Get the difference in minutes
* ##### [diffInMonths()](#diffInMonths()) public
Get the difference in months
* ##### [diffInMonthsIgnoreTimezone()](#diffInMonthsIgnoreTimezone()) public
Get the difference in months ignoring the timezone. This means the months are calculated in the specified timezone without converting to UTC first. This prevents the day from changing which can change the month.
* ##### [diffInSeconds()](#diffInSeconds()) public
Get the difference in seconds
* ##### [diffInWeekdays()](#diffInWeekdays()) public
Get the difference in weekdays
* ##### [diffInWeekendDays()](#diffInWeekendDays()) public
Get the difference in weekend days using a filter
* ##### [diffInWeeks()](#diffInWeeks()) public
Get the difference in weeks
* ##### [diffInYears()](#diffInYears()) public
Get the difference in years
* ##### [disableLenientParsing()](#disableLenientParsing()) public static
Enables lenient parsing for locale formats.
* ##### [enableLenientParsing()](#enableLenientParsing()) public static
Enables lenient parsing for locale formats.
* ##### [endOfCentury()](#endOfCentury()) public
Resets the date to end of the century and time to 23:59:59
* ##### [endOfDay()](#endOfDay()) public
Resets the time to 23:59:59
* ##### [endOfDecade()](#endOfDecade()) public
Resets the date to end of the decade and time to 23:59:59
* ##### [endOfMonth()](#endOfMonth()) public
Resets the date to end of the month and time to 23:59:59
* ##### [endOfWeek()](#endOfWeek()) public
Resets the date to end of week (defined in $weekEndsAt) and time to 23:59:59
* ##### [endOfYear()](#endOfYear()) public
Resets the date to end of the year and time to 23:59:59
* ##### [eq()](#eq()) public
Determines if the instance is equal to another
* ##### [equals()](#equals()) public
Determines if the instance is equal to another
* ##### [farthest()](#farthest()) public
Get the farthest date from the instance.
* ##### [firstOfMonth()](#firstOfMonth()) public
Modify to the first occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the first day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [firstOfQuarter()](#firstOfQuarter()) public
Modify to the first occurrence of a given day of the week in the current quarter. If no dayOfWeek is provided, modify to the first day of the current quarter. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [firstOfYear()](#firstOfYear()) public
Modify to the first occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the first day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [fromNow()](#fromNow()) public static
Convenience method for getting the remaining time from a given time.
* ##### [getDefaultLocale()](#getDefaultLocale()) public static
Gets the default locale.
* ##### [getDiffFormatter()](#getDiffFormatter()) public static
Get the difference formatter instance.
* ##### [getLastErrors()](#getLastErrors()) public static
Returns any errors or warnings that were found during the parsing of the last object created by this class.
* ##### [getTestNow()](#getTestNow()) public static
Get the test instance stored in Chronos
* ##### [getWeekEndsAt()](#getWeekEndsAt()) public static
Get the last day of week
* ##### [getWeekStartsAt()](#getWeekStartsAt()) public static
Get the first day of week
* ##### [getWeekendDays()](#getWeekendDays()) public static
Get weekend days
* ##### [greaterThan()](#greaterThan()) public
Determines if the instance is greater (after) than another
* ##### [greaterThanOrEquals()](#greaterThanOrEquals()) public
Determines if the instance is greater (after) than or equal to another
* ##### [gt()](#gt()) public
Determines if the instance is greater (after) than another
* ##### [gte()](#gte()) public
Determines if the instance is greater (after) than or equal to another
* ##### [hasRelativeKeywords()](#hasRelativeKeywords()) public static
Determine if there is a relative keyword in the time string, this is to create dates relative to now for test instances. e.g.: next tuesday
* ##### [hasTestNow()](#hasTestNow()) public static
Get whether or not Chronos has a test instance set.
* ##### [hour()](#hour()) public
Set the instance's hour
* ##### [i18nFormat()](#i18nFormat()) public
Returns a formatted string for this time object using the preferred format and language for the specified locale.
* ##### [instance()](#instance()) public static
Create a ChronosInterface instance from a DateTimeInterface one
* ##### [isBirthday()](#isBirthday()) public
Check if its the birthday. Compares the date/month values of the two dates.
* ##### [isFriday()](#isFriday()) public
Checks if this day is a Friday.
* ##### [isFuture()](#isFuture()) public
Determines if the instance is in the future, ie. greater (after) than now
* ##### [isLastMonth()](#isLastMonth()) public
Determines if the instance is within the last month
* ##### [isLastWeek()](#isLastWeek()) public
Determines if the instance is within the last week
* ##### [isLastYear()](#isLastYear()) public
Determines if the instance is within the last year
* ##### [isLeapYear()](#isLeapYear()) public
Determines if the instance is a leap year
* ##### [isMonday()](#isMonday()) public
Checks if this day is a Monday.
* ##### [isMutable()](#isMutable()) public
Check if instance of ChronosInterface is mutable.
* ##### [isNextMonth()](#isNextMonth()) public
Determines if the instance is within the next month
* ##### [isNextWeek()](#isNextWeek()) public
Determines if the instance is within the next week
* ##### [isNextYear()](#isNextYear()) public
Determines if the instance is within the next year
* ##### [isPast()](#isPast()) public
Determines if the instance is in the past, ie. less (before) than now
* ##### [isSameDay()](#isSameDay()) public
Checks if the passed in date is the same day as the instance current day.
* ##### [isSaturday()](#isSaturday()) public
Checks if this day is a Saturday.
* ##### [isSunday()](#isSunday()) public
Checks if this day is a Sunday.
* ##### [isThisMonth()](#isThisMonth()) public
Returns true if this object represents a date within the current month
* ##### [isThisWeek()](#isThisWeek()) public
Returns true if this object represents a date within the current week
* ##### [isThisYear()](#isThisYear()) public
Returns true if this object represents a date within the current year
* ##### [isThursday()](#isThursday()) public
Checks if this day is a Thursday.
* ##### [isToday()](#isToday()) public
Determines if the instance is today
* ##### [isTomorrow()](#isTomorrow()) public
Determines if the instance is tomorrow
* ##### [isTuesday()](#isTuesday()) public
Checks if this day is a Tuesday.
* ##### [isWednesday()](#isWednesday()) public
Checks if this day is a Wednesday.
* ##### [isWeekday()](#isWeekday()) public
Determines if the instance is a weekday
* ##### [isWeekend()](#isWeekend()) public
Determines if the instance is a weekend day
* ##### [isWithinNext()](#isWithinNext()) public
Returns true this instance will happen within the specified interval
* ##### [isYesterday()](#isYesterday()) public
Determines if the instance is yesterday
* ##### [jsonSerialize()](#jsonSerialize()) public
Returns a string that should be serialized when converting this object to JSON
* ##### [lastOfMonth()](#lastOfMonth()) public
Modify to the last occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the last day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [lastOfQuarter()](#lastOfQuarter()) public
Modify to the last occurrence of a given day of the week in the current quarter. If no dayOfWeek is provided, modify to the last day of the current quarter. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [lastOfYear()](#lastOfYear()) public
Modify to the last occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the last day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [lenientParsingEnabled()](#lenientParsingEnabled()) public static
Gets whether locale format parsing is set to lenient.
* ##### [lessThan()](#lessThan()) public
Determines if the instance is less (before) than another
* ##### [lessThanOrEquals()](#lessThanOrEquals()) public
Determines if the instance is less (before) or equal to another
* ##### [listTimezones()](#listTimezones()) public static
Get list of timezone identifiers
* ##### [lt()](#lt()) public
Determines if the instance is less (before) than another
* ##### [lte()](#lte()) public
Determines if the instance is less (before) or equal to another
* ##### [max()](#max()) public
Get the maximum instance between a given instance (default now) and the current instance.
* ##### [maxValue()](#maxValue()) public static
Create a ChronosInterface instance for the greatest supported date.
* ##### [microsecond()](#microsecond()) public
Set the instance's microsecond
* ##### [min()](#min()) public
Get the minimum instance between a given instance (default now) and the current instance.
* ##### [minValue()](#minValue()) public static
Create a ChronosInterface instance for the lowest supported date.
* ##### [minute()](#minute()) public
Set the instance's minute
* ##### [modify()](#modify()) public @method
* ##### [month()](#month()) public
Set the instance's month
* ##### [ne()](#ne()) public
Determines if the instance is not equal to another
* ##### [next()](#next()) public
Modify to the next occurrence of a given day of the week. If no dayOfWeek is provided, modify to the next occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [nice()](#nice()) public
Returns a nicely formatted date string for this object.
* ##### [notEquals()](#notEquals()) public
Determines if the instance is not equal to another
* ##### [now()](#now()) public static
Get a ChronosInterface instance for the current date and time
* ##### [nthOfMonth()](#nthOfMonth()) public
Modify to the given occurrence of a given day of the week in the current month. If the calculated occurrence is outside the scope of the current month, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [nthOfQuarter()](#nthOfQuarter()) public
Modify to the given occurrence of a given day of the week in the current quarter. If the calculated occurrence is outside the scope of the current quarter, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [nthOfYear()](#nthOfYear()) public
Modify to the given occurrence of a given day of the week in the current year. If the calculated occurrence is outside the scope of the current year, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [parse()](#parse()) public static
Create a ChronosInterface instance from a string. This is an alias for the constructor that allows better fluent syntax as it allows you to do ChronosInterface::parse('Monday next week')->fn() rather than (new Chronos('Monday next week'))->fn()
* ##### [parseDate()](#parseDate()) public static
Returns a new Time object after parsing the provided $date string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
* ##### [parseDateTime()](#parseDateTime()) public static
Returns a new Time object after parsing the provided time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
* ##### [parseTime()](#parseTime()) public static
Returns a new Time object after parsing the provided $time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
* ##### [previous()](#previous()) public
Modify to the previous occurrence of a given day of the week. If no dayOfWeek is provided, modify to the previous occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
* ##### [resetToStringFormat()](#resetToStringFormat()) public static
Resets the format used to the default when converting an instance of this type to a string
* ##### [safeCreateDateTimeZone()](#safeCreateDateTimeZone()) protected static
Creates a DateTimeZone from a string or a DateTimeZone
* ##### [second()](#second()) public
Set the instance's second
* ##### [secondsSinceMidnight()](#secondsSinceMidnight()) public
The number of seconds since midnight.
* ##### [secondsUntilEndOfDay()](#secondsUntilEndOfDay()) public
The number of seconds until 23:59:59.
* ##### [setDate()](#setDate()) public
Set the date to a different date.
* ##### [setDateTime()](#setDateTime()) public
Set the date and time all together
* ##### [setDefaultLocale()](#setDefaultLocale()) public static
Sets the default locale.
* ##### [setDiffFormatter()](#setDiffFormatter()) public static
Set the difference formatter instance.
* ##### [setJsonEncodeFormat()](#setJsonEncodeFormat()) public static
Sets the default format used when converting this object to JSON
* ##### [setTestNow()](#setTestNow()) public static
Set the test now used by Date and Time classes provided by Chronos
* ##### [setTimeFromTimeString()](#setTimeFromTimeString()) public
Set the time by time string
* ##### [setTimezone()](#setTimezone()) public
Set the instance's timezone from a string or object
* ##### [setToStringFormat()](#setToStringFormat()) public static
Sets the default format used when type converting instances of this type to string
* ##### [setWeekEndsAt()](#setWeekEndsAt()) public static
Set the last day of week
* ##### [setWeekStartsAt()](#setWeekStartsAt()) public static
Set the first day of week
* ##### [setWeekendDays()](#setWeekendDays()) public static
Set weekend days
* ##### [startOfCentury()](#startOfCentury()) public
Resets the date to the first day of the century and the time to 00:00:00
* ##### [startOfDay()](#startOfDay()) public
Resets the time to 00:00:00
* ##### [startOfDecade()](#startOfDecade()) public
Resets the date to the first day of the decade and the time to 00:00:00
* ##### [startOfMonth()](#startOfMonth()) public
Resets the date to the first day of the month and the time to 00:00:00
* ##### [startOfWeek()](#startOfWeek()) public
Resets the date to the first day of week (defined in $weekStartsAt) and the time to 00:00:00
* ##### [startOfYear()](#startOfYear()) public
Resets the date to the first day of the year and the time to 00:00:00
* ##### [subDay()](#subDay()) public
Remove a day from the instance
* ##### [subDays()](#subDays()) public
Remove days from the instance
* ##### [subHour()](#subHour()) public
Remove an hour from the instance
* ##### [subHours()](#subHours()) public
Remove hours from the instance
* ##### [subMinute()](#subMinute()) public
Remove a minute from the instance
* ##### [subMinutes()](#subMinutes()) public
Remove minutes from the instance
* ##### [subMonth()](#subMonth()) public
Remove a month from the instance
* ##### [subMonthWithOverflow()](#subMonthWithOverflow()) public
Remove a month with overflow from the instance.
* ##### [subMonths()](#subMonths()) public
Remove months from the instance.
* ##### [subMonthsWithOverflow()](#subMonthsWithOverflow()) public
Remove months with overflow from the instance.
* ##### [subSecond()](#subSecond()) public
Remove a second from the instance
* ##### [subSeconds()](#subSeconds()) public
Remove seconds from the instance
* ##### [subWeek()](#subWeek()) public
Remove a week from the instance
* ##### [subWeekday()](#subWeekday()) public
Remove a weekday from the instance
* ##### [subWeekdays()](#subWeekdays()) public
Remove weekdays from the instance
* ##### [subWeeks()](#subWeeks()) public
Remove weeks to the instance
* ##### [subYear()](#subYear()) public
Remove a year from the instance.
* ##### [subYearWithOverflow()](#subYearWithOverflow()) public
Remove a year with overflow from the instance
* ##### [subYears()](#subYears()) public
Remove years from the instance.
* ##### [subYearsWithOverflow()](#subYearsWithOverflow()) public
Remove years with overflow from the instance
* ##### [timeAgoInWords()](#timeAgoInWords()) public
Returns either a relative or a formatted absolute date depending on the difference between the current time and this object.
* ##### [timestamp()](#timestamp()) public
Set the instance's timestamp
* ##### [timezone()](#timezone()) public
Alias for setTimezone()
* ##### [toAtomString()](#toAtomString()) public
Format the instance as ATOM
* ##### [toCookieString()](#toCookieString()) public
Format the instance as COOKIE
* ##### [toDateString()](#toDateString()) public
Format the instance as date
* ##### [toDateTimeString()](#toDateTimeString()) public
Format the instance as date and time
* ##### [toDayDateTimeString()](#toDayDateTimeString()) public
Format the instance with day, date and time
* ##### [toFormattedDateString()](#toFormattedDateString()) public
Format the instance as a readable date
* ##### [toImmutable()](#toImmutable()) public
Create a new immutable instance from current mutable instance.
* ##### [toIso8601String()](#toIso8601String()) public
Format the instance as ISO8601
* ##### [toQuarter()](#toQuarter()) public
Returns the quarter
* ##### [toRfc1036String()](#toRfc1036String()) public
Format the instance as RFC1036
* ##### [toRfc1123String()](#toRfc1123String()) public
Format the instance as RFC1123
* ##### [toRfc2822String()](#toRfc2822String()) public
Format the instance as RFC2822
* ##### [toRfc3339String()](#toRfc3339String()) public
Format the instance as RFC3339
* ##### [toRfc822String()](#toRfc822String()) public
Format the instance as RFC822
* ##### [toRfc850String()](#toRfc850String()) public
Format the instance as RFC850
* ##### [toRssString()](#toRssString()) public
Format the instance as RSS
* ##### [toTimeString()](#toTimeString()) public
Format the instance as time
* ##### [toUnixString()](#toUnixString()) public
Returns a UNIX timestamp.
* ##### [toW3cString()](#toW3cString()) public
Format the instance as W3C
* ##### [toWeek()](#toWeek()) public
* ##### [today()](#today()) public static
Create a ChronosInterface instance for today
* ##### [tomorrow()](#tomorrow()) public static
Create a ChronosInterface instance for tomorrow
* ##### [tz()](#tz()) public
Alias for setTimezone()
* ##### [wasWithinLast()](#wasWithinLast()) public
Returns true this instance happened within the specified interval
* ##### [year()](#year()) public
Set the instance's year
* ##### [yesterday()](#yesterday()) public static
Create a ChronosInterface instance for yesterday
Method Detail
-------------
### \_\_construct() public
```
__construct(DateTimeInterface|string|int|null $time = null, DateTimeZone|string|null $tz = null)
```
Create a new mutable time instance.
Please see the testing aids section (specifically static::setTestNow()) for more on the possibility of this constructor returning a test instance.
#### Parameters
`DateTimeInterface|string|int|null` $time optional Fixed or relative time
`DateTimeZone|string|null` $tz optional The timezone for the instance
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns the data that should be displayed when debugging this object
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): string|int|boolDateTimeZone
```
Get a part of the ChronosInterface object
#### Parameters
`string` $name The property name to read.
#### Returns
`string|int|boolDateTimeZone`
#### Throws
`InvalidArgumentException`
### \_\_isset() public
```
__isset(string $name): bool
```
Check if an attribute exists on the object
#### Parameters
`string` $name The property name to check.
#### Returns
`bool`
### \_\_set() public
```
__set(string $name, string|intDateTimeZone $value): void
```
Set a part of the ChronosInterface object
#### Parameters
`string` $name The property to set.
`string|intDateTimeZone` $value The value to set.
#### Returns
`void`
#### Throws
`InvalidArgumentException`
### \_\_toString() public
```
__toString(): string
```
Format the instance as a string using the set format
#### Returns
`string`
### \_formatObject() protected
```
_formatObject(DateTimeDateTimeImmutable $date, array<int>|string|int $format, string|null $locale): string
```
Returns a translated and localized date string. Implements what IntlDateFormatter::formatObject() is in PHP 5.5+
#### Parameters
`DateTimeDateTimeImmutable` $date Date.
`array<int>|string|int` $format Format.
`string|null` $locale The locale name in which the date should be displayed.
#### Returns
`string`
### addDay() public
```
addDay(int $value = 1): static
```
Add a day to the instance
#### Parameters
`int` $value optional The number of days to add.
#### Returns
`static`
### addDays() public
```
addDays(int $value): static
```
Add days to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of days to add.
#### Returns
`static`
### addHour() public
```
addHour(int $value = 1): static
```
Add an hour to the instance
#### Parameters
`int` $value optional The number of hours to add.
#### Returns
`static`
### addHours() public
```
addHours(int $value): static
```
Add hours to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of hours to add.
#### Returns
`static`
### addMinute() public
```
addMinute(int $value = 1): static
```
Add a minute to the instance
#### Parameters
`int` $value optional The number of minutes to add.
#### Returns
`static`
### addMinutes() public
```
addMinutes(int $value): static
```
Add minutes to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of minutes to add.
#### Returns
`static`
### addMonth() public
```
addMonth(int $value = 1): static
```
Add a month to the instance.
Has the same behavior as `addMonths()`.
#### Parameters
`int` $value optional The number of months to add.
#### Returns
`static`
### addMonthWithOverflow() public
```
addMonthWithOverflow(int $value = 1): static
```
Add a month with overflow to the instance.
Has the same behavior as `addMonthsWithOverflow()`.
#### Parameters
`int` $value optional The number of months to add.
#### Returns
`static`
### addMonths() public
```
addMonths(int $value): static
```
Add months to the instance. Positive $value travels forward while negative $value travels into the past.
If the new date does not exist, the last day of the month is used instead instead of overflowing into the next month.
### Example:
```
(new Chronos('2015-01-03'))->addMonths(1); // Results in 2015-02-03
(new Chronos('2015-01-31'))->addMonths(1); // Results in 2015-02-28
```
#### Parameters
`int` $value The number of months to add.
#### Returns
`static`
### addMonthsWithOverflow() public
```
addMonthsWithOverflow(int $value): static
```
Add months with overflowing to the instance. Positive $value travels forward while negative $value travels into the past.
If the new date does not exist, the days overflow into the next month.
### Example:
```
(new Chronos('2012-01-30'))->addMonthsWithOverflow(1); // Results in 2013-03-01
```
#### Parameters
`int` $value The number of months to add.
#### Returns
`static`
### addSecond() public
```
addSecond(int $value = 1): static
```
Add a second to the instance
#### Parameters
`int` $value optional The number of seconds to add.
#### Returns
`static`
### addSeconds() public
```
addSeconds(int $value): static
```
Add seconds to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of seconds to add.
#### Returns
`static`
### addWeek() public
```
addWeek(int $value = 1): static
```
Add a week to the instance
#### Parameters
`int` $value optional The number of weeks to add.
#### Returns
`static`
### addWeekday() public
```
addWeekday(int $value = 1): static
```
Add a weekday to the instance
#### Parameters
`int` $value optional The number of weekdays to add.
#### Returns
`static`
### addWeekdays() public
```
addWeekdays(int $value): static
```
Add weekdays to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of weekdays to add.
#### Returns
`static`
### addWeeks() public
```
addWeeks(int $value): static
```
Add weeks to the instance. Positive $value travels forward while negative $value travels into the past.
#### Parameters
`int` $value The number of weeks to add.
#### Returns
`static`
### addYear() public
```
addYear(int $value = 1): static
```
Add a year to the instance
Has the same behavior as `addYears()`.
#### Parameters
`int` $value optional The number of years to add.
#### Returns
`static`
### addYearWithOverflow() public
```
addYearWithOverflow(int $value = 1): static
```
Add a year with overflow to the instance
Has the same behavior as `addYearsWithOverflow()`.
#### Parameters
`int` $value optional The number of years to add.
#### Returns
`static`
### addYears() public
```
addYears(int $value): static
```
Add years to the instance. Positive $value travel forward while negative $value travel into the past.
If the new date does not exist, the last day of the month is used instead instead of overflowing into the next month.
### Example:
```
(new Chronos('2015-01-03'))->addYears(1); // Results in 2016-01-03
(new Chronos('2012-02-29'))->addYears(1); // Results in 2013-02-28
```
#### Parameters
`int` $value The number of years to add.
#### Returns
`static`
### addYearsWithOverflow() public
```
addYearsWithOverflow(int $value): static
```
Add years with overflowing to the instance. Positive $value travels forward while negative $value travels into the past.
If the new date does not exist, the days overflow into the next month.
### Example:
```
(new Chronos('2012-02-29'))->addYearsWithOverflow(1); // Results in 2013-03-01
```
#### Parameters
`int` $value The number of years to add.
#### Returns
`static`
### average() public
```
average(Cake\Chronos\ChronosInterface $dt = null): static
```
Modify the current instance to the average of a given instance (default now) and the current instance.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt optional The instance to compare with.
#### Returns
`static`
### between() public
```
between(Cake\Chronos\ChronosInterface $dt1, Cake\Chronos\ChronosInterface $dt2, bool $equal = true): bool
```
Determines if the instance is between two others
#### Parameters
`Cake\Chronos\ChronosInterface` $dt1 The instance to compare with.
`Cake\Chronos\ChronosInterface` $dt2 The instance to compare with.
`bool` $equal optional Indicates if a > and < comparison should be used or <= or >=
#### Returns
`bool`
### closest() public
```
closest(Cake\Chronos\ChronosInterface $dt1, Cake\Chronos\ChronosInterface $dt2): static
```
Get the closest date from the instance.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt1 The instance to compare with.
`Cake\Chronos\ChronosInterface` $dt2 The instance to compare with.
#### Returns
`static`
### copy() public
```
copy(): static
```
Get a copy of the instance
#### Returns
`static`
### create() public static
```
create(int|null $year = null, int|null $month = null, int|null $day = null, int|null $hour = null, int|null $minute = null, int|null $second = null, int|null $microsecond = null, DateTimeZone|string|null $tz = null): static
```
Create a new ChronosInterface instance from a specific date and time.
If any of $year, $month or $day are set to null their now() values will be used.
If $hour is null it will be set to its now() value and the default values for $minute, $second and $microsecond will be their now() values. If $hour is not null then the default values for $minute, $second and $microsecond will be 0.
#### Parameters
`int|null` $year optional The year to create an instance with.
`int|null` $month optional The month to create an instance with.
`int|null` $day optional The day to create an instance with.
`int|null` $hour optional The hour to create an instance with.
`int|null` $minute optional The minute to create an instance with.
`int|null` $second optional The second to create an instance with.
`int|null` $microsecond optional The microsecond to create an instance with.
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
### createFromArray() public static
```
createFromArray((int|string)[] $values): static
```
Creates a ChronosInterface instance from an array of date and time values.
The 'year', 'month' and 'day' values must all be set for a date. The time values all default to 0.
The 'timezone' value can be any format supported by `\DateTimeZone`.
Allowed values:
* year
* month
* day
* hour
* minute
* second
* microsecond
* meridian ('am' or 'pm')
* timezone
#### Parameters
`(int|string)[]` $values Array of date and time values.
#### Returns
`static`
### createFromDate() public static
```
createFromDate(int|null $year = null, int|null $month = null, int|null $day = null, DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance from just a date. The time portion is set to now.
#### Parameters
`int|null` $year optional The year to create an instance with.
`int|null` $month optional The month to create an instance with.
`int|null` $day optional The day to create an instance with.
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
### createFromFormat() public static
```
createFromFormat(string $format, string $time, DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance from a specific format
#### Parameters
`string` $format The date() compatible format string.
`string` $time The formatted date string to interpret.
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
#### Throws
`InvalidArgumentException`
### createFromTime() public static
```
createFromTime(int|null $hour = null, int|null $minute = null, int|null $second = null, int|null $microsecond = null, DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance from just a time. The date portion is set to today.
#### Parameters
`int|null` $hour optional The hour to create an instance with.
`int|null` $minute optional The minute to create an instance with.
`int|null` $second optional The second to create an instance with.
`int|null` $microsecond optional The microsecond to create an instance with.
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
### createFromTimestamp() public static
```
createFromTimestamp(int $timestamp, DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance from a timestamp
#### Parameters
`int` $timestamp The timestamp to create an instance from.
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
### createFromTimestampUTC() public static
```
createFromTimestampUTC(int $timestamp): static
```
Create a ChronosInterface instance from an UTC timestamp
#### Parameters
`int` $timestamp The UTC timestamp to create an instance from.
#### Returns
`static`
### day() public
```
day(int $value): static
```
Set the instance's day
#### Parameters
`int` $value The day value.
#### Returns
`static`
### diffFiltered() public
```
diffFiltered(Cake\Chronos\ChronosInterval $ci, callable $callback, Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference by the given interval using a filter callable
#### Parameters
`Cake\Chronos\ChronosInterval` $ci An interval to traverse by
`callable` $callback The callback to use for filtering.
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffForHumans() public
```
diffForHumans(Cake\Chronos\ChronosInterface|null $other = null, bool $absolute = false): string
```
Get the difference in a human readable format.
When comparing a value in the past to default now: 1 hour ago 5 months ago
When comparing a value in the future to default now: 1 hour from now 5 months from now
When comparing a value in the past to another value: 1 hour before 5 months before
When comparing a value in the future to another value: 1 hour after 5 months after
#### Parameters
`Cake\Chronos\ChronosInterface|null` $other optional The datetime to compare with.
`bool` $absolute optional removes time difference modifiers ago, after, etc
#### Returns
`string`
### diffFormatter() public static
```
diffFormatter(Cake\Chronos\DifferenceFormatterInterface|null $formatter = null): Cake\Chronos\DifferenceFormatterInterface
```
Get the difference formatter instance or overwrite the current one.
#### Parameters
`Cake\Chronos\DifferenceFormatterInterface|null` $formatter optional The formatter instance when setting.
#### Returns
`Cake\Chronos\DifferenceFormatterInterface`
### diffInDays() public
```
diffInDays(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in days
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInDaysFiltered() public
```
diffInDaysFiltered(callable $callback, Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in days using a filter callable
#### Parameters
`callable` $callback The callback to use for filtering.
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInHours() public
```
diffInHours(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in hours
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInHoursFiltered() public
```
diffInHoursFiltered(callable $callback, Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in hours using a filter callable
#### Parameters
`callable` $callback The callback to use for filtering.
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInMinutes() public
```
diffInMinutes(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in minutes
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInMonths() public
```
diffInMonths(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in months
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInMonthsIgnoreTimezone() public
```
diffInMonthsIgnoreTimezone(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in months ignoring the timezone. This means the months are calculated in the specified timezone without converting to UTC first. This prevents the day from changing which can change the month.
For example, if comparing `2019-06-01 Asia/Tokyo` and `2019-10-01 Asia/Tokyo`, the result would be 4 months instead of 3 when using normal `DateTime::diff()`.
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInSeconds() public
```
diffInSeconds(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in seconds
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInWeekdays() public
```
diffInWeekdays(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in weekdays
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInWeekendDays() public
```
diffInWeekendDays(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in weekend days using a filter
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInWeeks() public
```
diffInWeeks(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in weeks
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### diffInYears() public
```
diffInYears(Cake\Chronos\ChronosInterface|null $dt = null, bool $abs = true): int
```
Get the difference in years
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to difference from.
`bool` $abs optional Get the absolute of the difference
#### Returns
`int`
### disableLenientParsing() public static
```
disableLenientParsing(): void
```
Enables lenient parsing for locale formats.
#### Returns
`void`
### enableLenientParsing() public static
```
enableLenientParsing(): void
```
Enables lenient parsing for locale formats.
#### Returns
`void`
### endOfCentury() public
```
endOfCentury(): static
```
Resets the date to end of the century and time to 23:59:59
#### Returns
`static`
### endOfDay() public
```
endOfDay(): static
```
Resets the time to 23:59:59
#### Returns
`static`
### endOfDecade() public
```
endOfDecade(): static
```
Resets the date to end of the decade and time to 23:59:59
#### Returns
`static`
### endOfMonth() public
```
endOfMonth(): static
```
Resets the date to end of the month and time to 23:59:59
#### Returns
`static`
### endOfWeek() public
```
endOfWeek(): static
```
Resets the date to end of week (defined in $weekEndsAt) and time to 23:59:59
#### Returns
`static`
### endOfYear() public
```
endOfYear(): static
```
Resets the date to end of the year and time to 23:59:59
#### Returns
`static`
### eq() public
```
eq(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
equals ### equals() public
```
equals(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### farthest() public
```
farthest(Cake\Chronos\ChronosInterface $dt1, Cake\Chronos\ChronosInterface $dt2): static
```
Get the farthest date from the instance.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt1 The instance to compare with.
`Cake\Chronos\ChronosInterface` $dt2 The instance to compare with.
#### Returns
`static`
### firstOfMonth() public
```
firstOfMonth(int|null $dayOfWeek = null): mixed
```
Modify to the first occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the first day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### firstOfQuarter() public
```
firstOfQuarter(int|null $dayOfWeek = null): mixed
```
Modify to the first occurrence of a given day of the week in the current quarter. If no dayOfWeek is provided, modify to the first day of the current quarter. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### firstOfYear() public
```
firstOfYear(int|null $dayOfWeek = null): mixed
```
Modify to the first occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the first day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### fromNow() public static
```
fromNow(DateTimeDateTimeImmutable $datetime): DateInterval|bool
```
Convenience method for getting the remaining time from a given time.
#### Parameters
`DateTimeDateTimeImmutable` $datetime The date to get the remaining time from.
#### Returns
`DateInterval|bool`
### getDefaultLocale() public static
```
getDefaultLocale(): string|null
```
Gets the default locale.
#### Returns
`string|null`
### getDiffFormatter() public static
```
getDiffFormatter(): Cake\Chronos\DifferenceFormatterInterface
```
Get the difference formatter instance.
#### Returns
`Cake\Chronos\DifferenceFormatterInterface`
### getLastErrors() public static
```
getLastErrors(): array
```
Returns any errors or warnings that were found during the parsing of the last object created by this class.
#### Returns
`array`
### getTestNow() public static
```
getTestNow(): Cake\Chronos\ChronosInterface|null
```
Get the test instance stored in Chronos
#### Returns
`Cake\Chronos\ChronosInterface|null`
#### See Also
\Cake\Chronos\Chronos::getTestNow() ### getWeekEndsAt() public static
```
getWeekEndsAt(): int
```
Get the last day of week
#### Returns
`int`
### getWeekStartsAt() public static
```
getWeekStartsAt(): int
```
Get the first day of week
#### Returns
`int`
### getWeekendDays() public static
```
getWeekendDays(): array
```
Get weekend days
#### Returns
`array`
### greaterThan() public
```
greaterThan(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is greater (after) than another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### greaterThanOrEquals() public
```
greaterThanOrEquals(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is greater (after) than or equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### gt() public
```
gt(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is greater (after) than another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
greaterThan ### gte() public
```
gte(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is greater (after) than or equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
greaterThanOrEquals ### hasRelativeKeywords() public static
```
hasRelativeKeywords(string|null $time): bool
```
Determine if there is a relative keyword in the time string, this is to create dates relative to now for test instances. e.g.: next tuesday
#### Parameters
`string|null` $time The time string to check.
#### Returns
`bool`
### hasTestNow() public static
```
hasTestNow(): bool
```
Get whether or not Chronos has a test instance set.
#### Returns
`bool`
#### See Also
\Cake\Chronos\Chronos::hasTestNow() ### hour() public
```
hour(int $value): static
```
Set the instance's hour
#### Parameters
`int` $value The hour value.
#### Returns
`static`
### i18nFormat() public
```
i18nFormat(string|int|null $format = null, DateTimeZone|string|null $timezone = null, string|null $locale = null): string|int
```
Returns a formatted string for this time object using the preferred format and language for the specified locale.
It is possible to specify the desired format for the string to be displayed. You can either pass `IntlDateFormatter` constants as the first argument of this function, or pass a full ICU date formatting string as specified in the following resource: <https://unicode-org.github.io/icu/userguide/format_parse/datetime/#datetime-format-syntax>.
Additional to `IntlDateFormatter` constants and date formatting string you can use Time::UNIX\_TIMESTAMP\_FORMAT to get a unix timestamp
### Examples
```
$time = new Time('2014-04-20 22:10');
$time->i18nFormat(); // outputs '4/20/14, 10:10 PM' for the en-US locale
$time->i18nFormat(\IntlDateFormatter::FULL); // Use the full date and time format
$time->i18nFormat([\IntlDateFormatter::FULL, \IntlDateFormatter::SHORT]); // Use full date but short time format
$time->i18nFormat('yyyy-MM-dd HH:mm:ss'); // outputs '2014-04-20 22:10'
$time->i18nFormat(Time::UNIX_TIMESTAMP_FORMAT); // outputs '1398031800'
```
You can control the default format used through `Time::setToStringFormat()`.
You can read about the available IntlDateFormatter constants at <https://secure.php.net/manual/en/class.intldateformatter.php>
If you need to display the date in a different timezone than the one being used for this Time object without altering its internal state, you can pass a timezone string or object as the second parameter.
Finally, should you need to use a different locale for displaying this time object, pass a locale string as the third parameter to this function.
### Examples
```
$time = new Time('2014-04-20 22:10');
$time->i18nFormat(null, null, 'de-DE');
$time->i18nFormat(\IntlDateFormatter::FULL, 'Europe/Berlin', 'de-DE');
```
You can control the default locale used through `Time::setDefaultLocale()`. If empty, the default will be taken from the `intl.default_locale` ini config.
#### Parameters
`string|int|null` $format optional Format string.
`DateTimeZone|string|null` $timezone optional Timezone string or DateTimeZone object in which the date will be displayed. The timezone stored for this object will not be changed.
`string|null` $locale optional The locale name in which the date should be displayed (e.g. pt-BR)
#### Returns
`string|int`
### instance() public static
```
instance(DateTimeInterface $dt): static
```
Create a ChronosInterface instance from a DateTimeInterface one
#### Parameters
`DateTimeInterface` $dt The datetime instance to convert.
#### Returns
`static`
### isBirthday() public
```
isBirthday(Cake\Chronos\ChronosInterface $dt): bool
```
Check if its the birthday. Compares the date/month values of the two dates.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### isFriday() public
```
isFriday(): bool
```
Checks if this day is a Friday.
#### Returns
`bool`
### isFuture() public
```
isFuture(): bool
```
Determines if the instance is in the future, ie. greater (after) than now
#### Returns
`bool`
### isLastMonth() public
```
isLastMonth(): bool
```
Determines if the instance is within the last month
#### Returns
`bool`
### isLastWeek() public
```
isLastWeek(): bool
```
Determines if the instance is within the last week
#### Returns
`bool`
### isLastYear() public
```
isLastYear(): bool
```
Determines if the instance is within the last year
#### Returns
`bool`
### isLeapYear() public
```
isLeapYear(): bool
```
Determines if the instance is a leap year
#### Returns
`bool`
### isMonday() public
```
isMonday(): bool
```
Checks if this day is a Monday.
#### Returns
`bool`
### isMutable() public
```
isMutable(): bool
```
Check if instance of ChronosInterface is mutable.
#### Returns
`bool`
### isNextMonth() public
```
isNextMonth(): bool
```
Determines if the instance is within the next month
#### Returns
`bool`
### isNextWeek() public
```
isNextWeek(): bool
```
Determines if the instance is within the next week
#### Returns
`bool`
### isNextYear() public
```
isNextYear(): bool
```
Determines if the instance is within the next year
#### Returns
`bool`
### isPast() public
```
isPast(): bool
```
Determines if the instance is in the past, ie. less (before) than now
#### Returns
`bool`
### isSameDay() public
```
isSameDay(Cake\Chronos\ChronosInterface $dt): bool
```
Checks if the passed in date is the same day as the instance current day.
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to check against.
#### Returns
`bool`
### isSaturday() public
```
isSaturday(): bool
```
Checks if this day is a Saturday.
#### Returns
`bool`
### isSunday() public
```
isSunday(): bool
```
Checks if this day is a Sunday.
#### Returns
`bool`
### isThisMonth() public
```
isThisMonth(): bool
```
Returns true if this object represents a date within the current month
#### Returns
`bool`
### isThisWeek() public
```
isThisWeek(): bool
```
Returns true if this object represents a date within the current week
#### Returns
`bool`
### isThisYear() public
```
isThisYear(): bool
```
Returns true if this object represents a date within the current year
#### Returns
`bool`
### isThursday() public
```
isThursday(): bool
```
Checks if this day is a Thursday.
#### Returns
`bool`
### isToday() public
```
isToday(): bool
```
Determines if the instance is today
#### Returns
`bool`
### isTomorrow() public
```
isTomorrow(): bool
```
Determines if the instance is tomorrow
#### Returns
`bool`
### isTuesday() public
```
isTuesday(): bool
```
Checks if this day is a Tuesday.
#### Returns
`bool`
### isWednesday() public
```
isWednesday(): bool
```
Checks if this day is a Wednesday.
#### Returns
`bool`
### isWeekday() public
```
isWeekday(): bool
```
Determines if the instance is a weekday
#### Returns
`bool`
### isWeekend() public
```
isWeekend(): bool
```
Determines if the instance is a weekend day
#### Returns
`bool`
### isWithinNext() public
```
isWithinNext(string|int $timeInterval): bool
```
Returns true this instance will happen within the specified interval
#### Parameters
`string|int` $timeInterval the numeric value with space then time type. Example of valid types: 6 hours, 2 days, 1 minute.
#### Returns
`bool`
### isYesterday() public
```
isYesterday(): bool
```
Determines if the instance is yesterday
#### Returns
`bool`
### jsonSerialize() public
```
jsonSerialize(): string|int
```
Returns a string that should be serialized when converting this object to JSON
#### Returns
`string|int`
### lastOfMonth() public
```
lastOfMonth(int|null $dayOfWeek = null): mixed
```
Modify to the last occurrence of a given day of the week in the current month. If no dayOfWeek is provided, modify to the last day of the current month. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### lastOfQuarter() public
```
lastOfQuarter(int|null $dayOfWeek = null): mixed
```
Modify to the last occurrence of a given day of the week in the current quarter. If no dayOfWeek is provided, modify to the last day of the current quarter. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### lastOfYear() public
```
lastOfYear(int|null $dayOfWeek = null): mixed
```
Modify to the last occurrence of a given day of the week in the current year. If no dayOfWeek is provided, modify to the last day of the current year. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### lenientParsingEnabled() public static
```
lenientParsingEnabled(): bool
```
Gets whether locale format parsing is set to lenient.
#### Returns
`bool`
### lessThan() public
```
lessThan(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is less (before) than another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### lessThanOrEquals() public
```
lessThanOrEquals(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is less (before) or equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### listTimezones() public static
```
listTimezones(string|int|null $filter = null, string|null $country = null, array<string, mixed>|bool $options = []): array
```
Get list of timezone identifiers
#### Parameters
`string|int|null` $filter optional A regex to filter identifier Or one of DateTimeZone class constants
`string|null` $country optional A two-letter ISO 3166-1 compatible country code. This option is only used when $filter is set to DateTimeZone::PER\_COUNTRY
`array<string, mixed>|bool` $options optional If true (default value) groups the identifiers list by primary region. Otherwise, an array containing `group`, `abbr`, `before`, and `after` keys. Setting `group` and `abbr` to true will group results and append timezone abbreviation in the display value. Set `before` and `after` to customize the abbreviation wrapper.
#### Returns
`array`
### lt() public
```
lt(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is less (before) than another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
lessThan ### lte() public
```
lte(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is less (before) or equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
lessThanOrEquals ### max() public
```
max(Cake\Chronos\ChronosInterface|null $dt = null): static
```
Get the maximum instance between a given instance (default now) and the current instance.
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to compare with.
#### Returns
`static`
### maxValue() public static
```
maxValue(): Cake\Chronos\ChronosInterface
```
Create a ChronosInterface instance for the greatest supported date.
#### Returns
`Cake\Chronos\ChronosInterface`
### microsecond() public
```
microsecond(int $value): static
```
Set the instance's microsecond
#### Parameters
`int` $value The microsecond value.
#### Returns
`static`
### min() public
```
min(Cake\Chronos\ChronosInterface|null $dt = null): static
```
Get the minimum instance between a given instance (default now) and the current instance.
#### Parameters
`Cake\Chronos\ChronosInterface|null` $dt optional The instance to compare with.
#### Returns
`static`
### minValue() public static
```
minValue(): Cake\Chronos\ChronosInterface
```
Create a ChronosInterface instance for the lowest supported date.
#### Returns
`Cake\Chronos\ChronosInterface`
### minute() public
```
minute(int $value): static
```
Set the instance's minute
#### Parameters
`int` $value The minute value.
#### Returns
`static`
### modify() public @method
```
modify(string $relative): Cake\Chronos\ChronosInterface
```
#### Parameters
`string` $relative #### Returns
`Cake\Chronos\ChronosInterface`
### month() public
```
month(int $value): static
```
Set the instance's month
#### Parameters
`int` $value The month value.
#### Returns
`static`
### ne() public
```
ne(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is not equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
#### See Also
notEquals ### next() public
```
next(int|null $dayOfWeek = null): mixed
```
Modify to the next occurrence of a given day of the week. If no dayOfWeek is provided, modify to the next occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### nice() public
```
nice(DateTimeZone|string|null $timezone = null, string|null $locale = null): string
```
Returns a nicely formatted date string for this object.
The format to be used is stored in the static property `Time::niceFormat`.
#### Parameters
`DateTimeZone|string|null` $timezone optional Timezone string or DateTimeZone object in which the date will be displayed. The timezone stored for this object will not be changed.
`string|null` $locale optional The locale name in which the date should be displayed (e.g. pt-BR)
#### Returns
`string`
### notEquals() public
```
notEquals(Cake\Chronos\ChronosInterface $dt): bool
```
Determines if the instance is not equal to another
#### Parameters
`Cake\Chronos\ChronosInterface` $dt The instance to compare with.
#### Returns
`bool`
### now() public static
```
now(DateTimeZone|string|null $tz): static
```
Get a ChronosInterface instance for the current date and time
#### Parameters
`DateTimeZone|string|null` $tz The DateTimeZone object or timezone name.
#### Returns
`static`
### nthOfMonth() public
```
nthOfMonth(int $nth, int $dayOfWeek): mixed
```
Modify to the given occurrence of a given day of the week in the current month. If the calculated occurrence is outside the scope of the current month, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int` $nth The offset to use.
`int` $dayOfWeek The day of the week to move to.
#### Returns
`mixed`
### nthOfQuarter() public
```
nthOfQuarter(int $nth, int $dayOfWeek): mixed
```
Modify to the given occurrence of a given day of the week in the current quarter. If the calculated occurrence is outside the scope of the current quarter, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int` $nth The offset to use.
`int` $dayOfWeek The day of the week to move to.
#### Returns
`mixed`
### nthOfYear() public
```
nthOfYear(int $nth, int $dayOfWeek): mixed
```
Modify to the given occurrence of a given day of the week in the current year. If the calculated occurrence is outside the scope of the current year, then return false and no modifications are made. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int` $nth The offset to use.
`int` $dayOfWeek The day of the week to move to.
#### Returns
`mixed`
### parse() public static
```
parse(DateTimeInterface|string|int $time = 'now', DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance from a string. This is an alias for the constructor that allows better fluent syntax as it allows you to do ChronosInterface::parse('Monday next week')->fn() rather than (new Chronos('Monday next week'))->fn()
#### Parameters
`DateTimeInterface|string|int` $time optional The strtotime compatible string to parse
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name.
#### Returns
`static`
### parseDate() public static
```
parseDate(string $date, array|string|int|null $format = null): static|null
```
Returns a new Time object after parsing the provided $date string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
When no $format is provided, the `wordFormat` format will be used.
If it was impossible to parse the provided time, null will be returned.
Example:
```
$time = Time::parseDate('10/13/2013');
$time = Time::parseDate('13 Oct, 2013', 'dd MMM, y');
$time = Time::parseDate('13 Oct, 2013', IntlDateFormatter::SHORT);
```
#### Parameters
`string` $date The date string to parse.
`array|string|int|null` $format optional Any format accepted by IntlDateFormatter.
#### Returns
`static|null`
### parseDateTime() public static
```
parseDateTime(string $time, array<int>|string|null $format = null, DateTimeZone|string|null $tz = null): static|null
```
Returns a new Time object after parsing the provided time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
When no $format is provided, the `toString` format will be used.
Unlike DateTime, the time zone of the returned instance is always converted to `$tz` (default time zone if null) even if the `$time` string specified a time zone. This is a limitation of IntlDateFormatter.
If it was impossible to parse the provided time, null will be returned.
Example:
```
$time = Time::parseDateTime('10/13/2013 12:54am');
$time = Time::parseDateTime('13 Oct, 2013 13:54', 'dd MMM, y H:mm');
$time = Time::parseDateTime('10/10/2015', [IntlDateFormatter::SHORT, IntlDateFormatter::NONE]);
```
#### Parameters
`string` $time The time string to parse.
`array<int>|string|null` $format optional Any format accepted by IntlDateFormatter.
`DateTimeZone|string|null` $tz optional The timezone for the instance
#### Returns
`static|null`
### parseTime() public static
```
parseTime(string $time, string|int|null $format = null): static|null
```
Returns a new Time object after parsing the provided $time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
When no $format is provided, the IntlDateFormatter::SHORT format will be used.
If it was impossible to parse the provided time, null will be returned.
Example:
```
$time = Time::parseTime('11:23pm');
```
#### Parameters
`string` $time The time string to parse.
`string|int|null` $format optional Any format accepted by IntlDateFormatter.
#### Returns
`static|null`
### previous() public
```
previous(int|null $dayOfWeek = null): mixed
```
Modify to the previous occurrence of a given day of the week. If no dayOfWeek is provided, modify to the previous occurrence of the current day of the week. Use the supplied consts to indicate the desired dayOfWeek, ex. static::MONDAY.
#### Parameters
`int|null` $dayOfWeek optional The day of the week to move to.
#### Returns
`mixed`
### resetToStringFormat() public static
```
resetToStringFormat(): void
```
Resets the format used to the default when converting an instance of this type to a string
#### Returns
`void`
### safeCreateDateTimeZone() protected static
```
safeCreateDateTimeZone(DateTimeZone|string|null $object): DateTimeZone
```
Creates a DateTimeZone from a string or a DateTimeZone
#### Parameters
`DateTimeZone|string|null` $object The value to convert.
#### Returns
`DateTimeZone`
#### Throws
`InvalidArgumentException`
### second() public
```
second(int $value): static
```
Set the instance's second
#### Parameters
`int` $value The seconds value.
#### Returns
`static`
### secondsSinceMidnight() public
```
secondsSinceMidnight(): int
```
The number of seconds since midnight.
#### Returns
`int`
### secondsUntilEndOfDay() public
```
secondsUntilEndOfDay(): int
```
The number of seconds until 23:59:59.
#### Returns
`int`
### setDate() public
```
setDate(int $year, int $month, int $day): static
```
Set the date to a different date.
Workaround for a PHP bug related to the first day of a month
#### Parameters
`int` $year The year to set.
`int` $month The month to set.
`int` $day The day to set.
#### Returns
`static`
### setDateTime() public
```
setDateTime(int $year, int $month, int $day, int $hour, int $minute, int $second = 0): static
```
Set the date and time all together
#### Parameters
`int` $year The year to set.
`int` $month The month to set.
`int` $day The day to set.
`int` $hour The hour to set.
`int` $minute The minute to set.
`int` $second optional The second to set.
#### Returns
`static`
### setDefaultLocale() public static
```
setDefaultLocale(string|null $locale = null): void
```
Sets the default locale.
Set to null to use IntlDateFormatter default.
#### Parameters
`string|null` $locale optional The default locale string to be used.
#### Returns
`void`
### setDiffFormatter() public static
```
setDiffFormatter(Cake\Chronos\DifferenceFormatterInterface $formatter): void
```
Set the difference formatter instance.
#### Parameters
`Cake\Chronos\DifferenceFormatterInterface` $formatter The formatter instance when setting.
#### Returns
`void`
### setJsonEncodeFormat() public static
```
setJsonEncodeFormat(Closure|array|string|int $format): void
```
Sets the default format used when converting this object to JSON
The format should be either the formatting constants from IntlDateFormatter as described in (<https://secure.php.net/manual/en/class.intldateformatter.php>) or a pattern as specified in (<https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details>)
It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.
Alternatively, the format can provide a callback. In this case, the callback can receive this datetime object and return a formatted string.
#### Parameters
`Closure|array|string|int` $format #### Returns
`void`
### setTestNow() public static
```
setTestNow(Cake\Chronos\ChronosInterface|string|null $testNow = null): void
```
Set the test now used by Date and Time classes provided by Chronos
#### Parameters
`Cake\Chronos\ChronosInterface|string|null` $testNow optional The instance to use for all future instances.
#### Returns
`void`
#### See Also
\Cake\Chronos\Chronos::setTestNow() ### setTimeFromTimeString() public
```
setTimeFromTimeString(string $time): static
```
Set the time by time string
#### Parameters
`string` $time Time as string.
#### Returns
`static`
### setTimezone() public
```
setTimezone(DateTimeZone|string $value): static
```
Set the instance's timezone from a string or object
#### Parameters
`DateTimeZone|string` $value The DateTimeZone object or timezone name to use.
#### Returns
`static`
### setToStringFormat() public static
```
setToStringFormat(string $format): void
```
Sets the default format used when type converting instances of this type to string
The format should be either the formatting constants from IntlDateFormatter as described in (<https://secure.php.net/manual/en/class.intldateformatter.php>) or a pattern as specified in (<https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details>)
It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.
#### Parameters
`string` $format Format.
#### Returns
`void`
### setWeekEndsAt() public static
```
setWeekEndsAt(int $day): void
```
Set the last day of week
#### Parameters
`int` $day The day the week ends with.
#### Returns
`void`
### setWeekStartsAt() public static
```
setWeekStartsAt(int $day): void
```
Set the first day of week
#### Parameters
`int` $day The day the week starts with.
#### Returns
`void`
### setWeekendDays() public static
```
setWeekendDays(array $days): void
```
Set weekend days
#### Parameters
`array` $days Which days are 'weekends'.
#### Returns
`void`
### startOfCentury() public
```
startOfCentury(): static
```
Resets the date to the first day of the century and the time to 00:00:00
#### Returns
`static`
### startOfDay() public
```
startOfDay(): static
```
Resets the time to 00:00:00
#### Returns
`static`
### startOfDecade() public
```
startOfDecade(): static
```
Resets the date to the first day of the decade and the time to 00:00:00
#### Returns
`static`
### startOfMonth() public
```
startOfMonth(): static
```
Resets the date to the first day of the month and the time to 00:00:00
#### Returns
`static`
### startOfWeek() public
```
startOfWeek(): static
```
Resets the date to the first day of week (defined in $weekStartsAt) and the time to 00:00:00
#### Returns
`static`
### startOfYear() public
```
startOfYear(): static
```
Resets the date to the first day of the year and the time to 00:00:00
#### Returns
`static`
### subDay() public
```
subDay(int $value = 1): static
```
Remove a day from the instance
#### Parameters
`int` $value optional The number of days to remove.
#### Returns
`static`
### subDays() public
```
subDays(int $value): static
```
Remove days from the instance
#### Parameters
`int` $value The number of days to remove.
#### Returns
`static`
### subHour() public
```
subHour(int $value = 1): static
```
Remove an hour from the instance
#### Parameters
`int` $value optional The number of hours to remove.
#### Returns
`static`
### subHours() public
```
subHours(int $value): static
```
Remove hours from the instance
#### Parameters
`int` $value The number of hours to remove.
#### Returns
`static`
### subMinute() public
```
subMinute(int $value = 1): static
```
Remove a minute from the instance
#### Parameters
`int` $value optional The number of minutes to remove.
#### Returns
`static`
### subMinutes() public
```
subMinutes(int $value): static
```
Remove minutes from the instance
#### Parameters
`int` $value The number of minutes to remove.
#### Returns
`static`
### subMonth() public
```
subMonth(int $value = 1): static
```
Remove a month from the instance
Has the same behavior as `addMonths()`.
#### Parameters
`int` $value optional The number of months to remove.
#### Returns
`static`
### subMonthWithOverflow() public
```
subMonthWithOverflow(int $value = 1): static
```
Remove a month with overflow from the instance.
Has the same behavior as `addMonthsWithOverflow()`.
#### Parameters
`int` $value optional The number of months to remove.
#### Returns
`static`
### subMonths() public
```
subMonths(int $value): static
```
Remove months from the instance.
Has the same behavior as `addMonths()`.
#### Parameters
`int` $value The number of months to remove.
#### Returns
`static`
### subMonthsWithOverflow() public
```
subMonthsWithOverflow(int $value): static
```
Remove months with overflow from the instance.
Has the same behavior as `addMonthsWithOverflow()`.
#### Parameters
`int` $value The number of months to remove.
#### Returns
`static`
### subSecond() public
```
subSecond(int $value = 1): static
```
Remove a second from the instance
#### Parameters
`int` $value optional The number of seconds to remove.
#### Returns
`static`
### subSeconds() public
```
subSeconds(int $value): static
```
Remove seconds from the instance
#### Parameters
`int` $value The number of seconds to remove.
#### Returns
`static`
### subWeek() public
```
subWeek(int $value = 1): static
```
Remove a week from the instance
#### Parameters
`int` $value optional The number of weeks to remove.
#### Returns
`static`
### subWeekday() public
```
subWeekday(int $value = 1): static
```
Remove a weekday from the instance
#### Parameters
`int` $value optional The number of weekdays to remove.
#### Returns
`static`
### subWeekdays() public
```
subWeekdays(int $value): static
```
Remove weekdays from the instance
#### Parameters
`int` $value The number of weekdays to remove.
#### Returns
`static`
### subWeeks() public
```
subWeeks(int $value): static
```
Remove weeks to the instance
#### Parameters
`int` $value The number of weeks to remove.
#### Returns
`static`
### subYear() public
```
subYear(int $value = 1): static
```
Remove a year from the instance.
Has the same behavior as `addYears()`.
#### Parameters
`int` $value optional The number of years to remove.
#### Returns
`static`
### subYearWithOverflow() public
```
subYearWithOverflow(int $value = 1): static
```
Remove a year with overflow from the instance
Has the same behavior as `addYearsWithOverflow()`.
#### Parameters
`int` $value optional The number of years to remove.
#### Returns
`static`
### subYears() public
```
subYears(int $value): static
```
Remove years from the instance.
Has the same behavior as `addYears()`.
#### Parameters
`int` $value The number of years to remove.
#### Returns
`static`
### subYearsWithOverflow() public
```
subYearsWithOverflow(int $value): static
```
Remove years with overflow from the instance
Has the same behavior as `addYearsWithOverflow()`.
#### Parameters
`int` $value The number of years to remove.
#### Returns
`static`
### timeAgoInWords() public
```
timeAgoInWords(array<string, mixed> $options = []): string
```
Returns either a relative or a formatted absolute date depending on the difference between the current time and this object.
### Options:
* `from` => another Time object representing the "now" time
* `format` => a fall back format if the relative time is longer than the duration specified by end
* `accuracy` => Specifies how accurate the date should be described (array)
+ year => The format if years > 0 (default "day")
+ month => The format if months > 0 (default "day")
+ week => The format if weeks > 0 (default "day")
+ day => The format if weeks > 0 (default "hour")
+ hour => The format if hours > 0 (default "minute")
+ minute => The format if minutes > 0 (default "minute")
+ second => The format if seconds > 0 (default "second")
* `end` => The end of relative time telling
* `relativeString` => The `printf` compatible string when outputting relative time
* `absoluteString` => The `printf` compatible string when outputting absolute time
* `timezone` => The user timezone the timestamp should be formatted in.
Relative dates look something like this:
* 3 weeks, 4 days ago
* 15 seconds ago
Default date formatting is d/M/YY e.g: on 18/2/09. Formatting is done internally using `i18nFormat`, see the method for the valid formatting strings
The returned string includes 'ago' or 'on' and assumes you'll properly add a word like 'Posted ' before the function output.
NOTE: If the difference is one week or more, the lowest level of accuracy is day
#### Parameters
`array<string, mixed>` $options optional Array of options.
#### Returns
`string`
### timestamp() public
```
timestamp(int $value): static
```
Set the instance's timestamp
#### Parameters
`int` $value The timestamp value to set.
#### Returns
`static`
### timezone() public
```
timezone(DateTimeZone|string $value): static
```
Alias for setTimezone()
#### Parameters
`DateTimeZone|string` $value The DateTimeZone object or timezone name to use.
#### Returns
`static`
### toAtomString() public
```
toAtomString(): string
```
Format the instance as ATOM
#### Returns
`string`
### toCookieString() public
```
toCookieString(): string
```
Format the instance as COOKIE
#### Returns
`string`
### toDateString() public
```
toDateString(): string
```
Format the instance as date
#### Returns
`string`
### toDateTimeString() public
```
toDateTimeString(): string
```
Format the instance as date and time
#### Returns
`string`
### toDayDateTimeString() public
```
toDayDateTimeString(): string
```
Format the instance with day, date and time
#### Returns
`string`
### toFormattedDateString() public
```
toFormattedDateString(): string
```
Format the instance as a readable date
#### Returns
`string`
### toImmutable() public
```
toImmutable(): Cake\Chronos\Chronos
```
Create a new immutable instance from current mutable instance.
#### Returns
`Cake\Chronos\Chronos`
### toIso8601String() public
```
toIso8601String(): string
```
Format the instance as ISO8601
#### Returns
`string`
### toQuarter() public
```
toQuarter(bool $range = false): array<string>|int
```
Returns the quarter
#### Parameters
`bool` $range optional Range.
#### Returns
`array<string>|int`
### toRfc1036String() public
```
toRfc1036String(): string
```
Format the instance as RFC1036
#### Returns
`string`
### toRfc1123String() public
```
toRfc1123String(): string
```
Format the instance as RFC1123
#### Returns
`string`
### toRfc2822String() public
```
toRfc2822String(): string
```
Format the instance as RFC2822
#### Returns
`string`
### toRfc3339String() public
```
toRfc3339String(): string
```
Format the instance as RFC3339
#### Returns
`string`
### toRfc822String() public
```
toRfc822String(): string
```
Format the instance as RFC822
#### Returns
`string`
### toRfc850String() public
```
toRfc850String(): string
```
Format the instance as RFC850
#### Returns
`string`
### toRssString() public
```
toRssString(): string
```
Format the instance as RSS
#### Returns
`string`
### toTimeString() public
```
toTimeString(): string
```
Format the instance as time
#### Returns
`string`
### toUnixString() public
```
toUnixString(): string
```
Returns a UNIX timestamp.
#### Returns
`string`
### toW3cString() public
```
toW3cString(): string
```
Format the instance as W3C
#### Returns
`string`
### toWeek() public
```
toWeek(): int
```
#### Returns
`int`
### today() public static
```
today(DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance for today
#### Parameters
`DateTimeZone|string|null` $tz optional The timezone to use.
#### Returns
`static`
### tomorrow() public static
```
tomorrow(DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance for tomorrow
#### Parameters
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
### tz() public
```
tz(DateTimeZone|string $value): static
```
Alias for setTimezone()
#### Parameters
`DateTimeZone|string` $value The DateTimeZone object or timezone name to use.
#### Returns
`static`
### wasWithinLast() public
```
wasWithinLast(string|int $timeInterval): bool
```
Returns true this instance happened within the specified interval
#### Parameters
`string|int` $timeInterval the numeric value with space then time type. Example of valid types: 6 hours, 2 days, 1 minute.
#### Returns
`bool`
### year() public
```
year(int $value): static
```
Set the instance's year
#### Parameters
`int` $value The year value.
#### Returns
`static`
### yesterday() public static
```
yesterday(DateTimeZone|string|null $tz = null): static
```
Create a ChronosInterface instance for yesterday
#### Parameters
`DateTimeZone|string|null` $tz optional The DateTimeZone object or timezone name the new instance should use.
#### Returns
`static`
Property Detail
---------------
### $\_formatters protected static
In-memory cache of date formatters
#### Type
`arrayIntlDateFormatter>`
### $\_jsonEncodeFormat protected static
The format to use when converting this object to JSON.
The format should be either the formatting constants from IntlDateFormatter as described in (<https://secure.php.net/manual/en/class.intldateformatter.php>) or a pattern as specified in (<https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details>)
It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.
#### Type
`Closure|array<int>|string|int`
### $\_lastErrors protected static
Holds the last error generated by createFromFormat
#### Type
`array`
### $\_toStringFormat protected static
The format to use when formatting a time using `Cake\I18n\Time::i18nFormat()` and `__toString`. This format is also used by `parseDateTime()`.
The format should be either the formatting constants from IntlDateFormatter as described in (<https://secure.php.net/manual/en/class.intldateformatter.php>) or a pattern as specified in (<https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details>)
It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.
#### Type
`array<int>|string|int`
### $age public @property-read
does a diffInYears() with default parameters
#### Type
`int`
### $day public @property-read
#### Type
`int`
### $dayOfWeek public @property-read
1 (for Monday) through 7 (for Sunday)
#### Type
`int`
### $dayOfWeekName public @property-read
#### Type
`string`
### $dayOfYear public @property-read
0 through 365
#### Type
`int`
### $days protected static
Names of days of the week.
#### Type
`array`
### $daysInMonth public @property-read
number of days in the given month
#### Type
`int`
### $defaultLocale protected static
The default locale to be used for displaying formatted date strings.
Use static::setDefaultLocale() and static::getDefaultLocale() instead.
#### Type
`string|null`
### $diffFormatter protected static
Instance of the diff formatting object.
#### Type
`Cake\Chronos\DifferenceFormatterInterface`
### $dst public @property-read
daylight savings time indicator, true if DST, false otherwise
#### Type
`bool`
### $hour public @property-read
#### Type
`int`
### $lenientParsing protected static
Whether lenient parsing is enabled for IntlDateFormatter.
Defaults to true which is the default for IntlDateFormatter.
#### Type
`bool`
### $local public @property-read
checks if the timezone is local, true if local, false otherwise
#### Type
`bool`
### $micro public @property-read
#### Type
`int`
### $microsecond public @property-read
#### Type
`int`
### $minute public @property-read
#### Type
`int`
### $month public @property-read
#### Type
`int`
### $niceFormat public static
The format to use when formatting a time using `Cake\I18n\Time::nice()`
The format should be either the formatting constants from IntlDateFormatter as described in (<https://secure.php.net/manual/en/class.intldateformatter.php>) or a pattern as specified in (<https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details>)
It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.
#### Type
`array<int>|string|int`
### $offset public @property-read
the timezone offset in seconds from UTC
#### Type
`int`
### $offsetHours public @property-read
the timezone offset in hours from UTC
#### Type
`int`
### $quarter public @property-read
the quarter of this instance, 1 - 4
#### Type
`int`
### $relativePattern protected static
Regex for relative period.
#### Type
`string`
### $second public @property-read
#### Type
`int`
### $timestamp public @property-read
seconds since the Unix Epoch
#### Type
`int`
### $timezone public @property-read
the current timezone
#### Type
`DateTimeZone|string`
### $timezoneName public @property-read
#### Type
`string`
### $toStringFormat protected static
Format to use for \_\_toString method when type juggling occurs.
#### Type
`string`
### $tz public @property-read
alias of timezone
#### Type
`DateTimeZone|string`
### $tzName public @property-read
#### Type
`string`
### $utc public @property-read
checks if the timezone is UTC, true if UTC, false otherwise
#### Type
`bool`
### $weekEndsAt protected static
Last day of week
#### Type
`int`
### $weekOfMonth public @property-read
1 through 5
#### Type
`int`
### $weekOfYear public @property-read
ISO-8601 week number of year, weeks starting on Monday
#### Type
`int`
### $weekStartsAt protected static
First day of week
#### Type
`int`
### $weekendDays protected static
Days of weekend
#### Type
`array`
### $wordAccuracy public static
The format to use when formatting a time using `Time::timeAgoInWords()` and the difference is less than `Time::$wordEnd`
#### Type
`array<string>`
### $wordEnd public static
The end of relative time telling
#### Type
`string`
### $wordFormat public static
The format to use when formatting a time using `Cake\I18n\Time::timeAgoInWords()` and the difference is more than `Cake\I18n\Time::$wordEnd`
#### Type
`array<int>|string|int`
### $year public @property-read
#### Type
`int`
### $yearIso public @property-read
#### Type
`int`
| programming_docs |
cakephp Class CommandTask Class CommandTask
==================
Base class for Shell Command reflection.
**Namespace:** [Cake\Shell\Task](namespace-cake.shell.task)
Constants
---------
* `int` **CODE\_ERROR**
```
1
```
Default error code
* `int` **CODE\_SUCCESS**
```
0
```
Default success code
* `int` **NORMAL**
```
ConsoleIo::NORMAL
```
Output constant for making normal shells.
* `int` **QUIET**
```
ConsoleIo::QUIET
```
Output constants for making quiet shells.
* `int` **VERBOSE**
```
ConsoleIo::VERBOSE
```
Output constant making verbose shells.
Property Summary
----------------
* [$OptionParser](#%24OptionParser) public `Cake\Console\ConsoleOptionParser` An instance of ConsoleOptionParser that has been configured for this class.
* [$Tasks](#%24Tasks) public `Cake\Console\TaskRegistry` Task Collection for the command, used to create Tasks.
* [$\_io](#%24_io) protected `Cake\Console\ConsoleIo` ConsoleIo instance.
* [$\_modelFactories](#%24_modelFactories) protected `array<callableCake\Datasource\Locator\LocatorInterface>` A list of overridden model factory functions.
* [$\_modelType](#%24_modelType) protected `string` The model type to use.
* [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance
* [$\_taskMap](#%24_taskMap) protected `array<string, array>` Normalized map of tasks.
* [$args](#%24args) public `array` Contains arguments parsed from the command line.
* [$command](#%24command) public `string|null` The command (method/task) that is being run.
* [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias.
* [$interactive](#%24interactive) public `bool` If true, the script will ask for permission to perform actions.
* [$modelClass](#%24modelClass) protected deprecated `string|null` This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
* [$name](#%24name) public `string` The name of the shell in camelized.
* [$params](#%24params) public `array` Contains command switches parsed from the command line.
* [$plugin](#%24plugin) public `string` The name of the plugin the shell belongs to. Is automatically set by ShellDispatcher when a shell is constructed.
* [$rootName](#%24rootName) protected `string` The root command name used when generating help output.
* [$taskNames](#%24taskNames) public `array<string>` Contains the loaded tasks
* [$tasks](#%24tasks) public `array|bool` Contains tasks to load and instantiate
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructs this Shell instance.
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_get()](#__get()) public
Overload get for lazy building of tasks
* ##### [\_appendShells()](#_appendShells()) protected
Scan the provided paths for shells, and append them into $shellList
* ##### [\_displayHelp()](#_displayHelp()) protected
Display the help in the correct format
* ##### [\_findShells()](#_findShells()) protected
Find shells in $path and add them to $shellList
* ##### [\_mergeProperty()](#_mergeProperty()) protected
Merge a single property with the values declared in all parent classes.
* ##### [\_mergePropertyData()](#_mergePropertyData()) protected
Merge each of the keys in a property together.
* ##### [\_mergeVars()](#_mergeVars()) protected
Merge the list of $properties with all parent classes of the current class.
* ##### [\_scanDir()](#_scanDir()) protected
Scan a directory for .php files and return the class names that should be within them.
* ##### [\_setModelClass()](#_setModelClass()) protected
Set the modelClass property based on conventions.
* ##### [\_setOutputLevel()](#_setOutputLevel()) protected
Set the output level based on the parameters.
* ##### [\_stop()](#_stop()) protected
Stop execution of the current script. Raises a StopException to try and halt the execution.
* ##### [\_validateTasks()](#_validateTasks()) protected
Checks that the tasks in the task map are actually available
* ##### [\_welcome()](#_welcome()) protected
Displays a header for the shell
* ##### [abort()](#abort()) public
Displays a formatted error message and exits the application with an error code.
* ##### [clear()](#clear()) public
Clear the console
* ##### [createFile()](#createFile()) public
Creates a file at given path
* ##### [dispatchShell()](#dispatchShell()) public
Dispatch a command to another Shell. Similar to Object::requestAction() but intended for running shells from other shells.
* ##### [err()](#err()) public
Outputs a single or multiple error messages to stderr. If no parameters are passed outputs just a newline.
* ##### [fetchTable()](#fetchTable()) public
Convenience method to get a table instance.
* ##### [getIo()](#getIo()) public
Get the io object for this shell.
* ##### [getModelType()](#getModelType()) public
Get the model type to be used by this class
* ##### [getOptionParser()](#getOptionParser()) public
Gets the option parser instance and configures it.
* ##### [getShellList()](#getShellList()) public
Gets the shell command listing.
* ##### [getTableLocator()](#getTableLocator()) public
Gets the table locator.
* ##### [hasMethod()](#hasMethod()) public
Check to see if this shell has a callable method by the given name.
* ##### [hasTask()](#hasTask()) public
Check to see if this shell has a task with the provided name.
* ##### [helper()](#helper()) public
Render a Console Helper
* ##### [hr()](#hr()) public
Outputs a series of minus characters to the standard output, acts as a visual separator.
* ##### [in()](#in()) public
Prompts the user for input, and returns it.
* ##### [info()](#info()) public
Convenience method for out() that wraps message between tag
* ##### [initialize()](#initialize()) public
Initializes the Shell acts as constructor for subclasses allows configuration of tasks prior to shell execution
* ##### [loadModel()](#loadModel()) public deprecated
Loads and constructs repository objects required by this object
* ##### [loadTasks()](#loadTasks()) public
Loads tasks defined in public $tasks
* ##### [log()](#log()) public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
* ##### [main()](#main()) public @method
Main entry method for the shell.
* ##### [modelFactory()](#modelFactory()) public
Override a existing callable to generate repositories of a given type.
* ##### [nl()](#nl()) public
Returns a single or multiple linefeeds sequences.
* ##### [out()](#out()) public
Outputs a single or multiple messages to stdout. If no parameters are passed outputs just a newline.
* ##### [param()](#param()) public
Safely access the values in $this->params.
* ##### [parseDispatchArguments()](#parseDispatchArguments()) public
Parses the arguments for the dispatchShell() method.
* ##### [quiet()](#quiet()) public
Output at all levels.
* ##### [runCommand()](#runCommand()) public
Runs the Shell with the provided argv.
* ##### [setIo()](#setIo()) public
Set the io object for this shell.
* ##### [setModelType()](#setModelType()) public
Set the model type to be used by this class
* ##### [setRootName()](#setRootName()) public
Set the root command name for help output.
* ##### [setTableLocator()](#setTableLocator()) public
Sets the table locator.
* ##### [shortPath()](#shortPath()) public
Makes absolute file path easier to read
* ##### [startup()](#startup()) public
Starts up the Shell and displays the welcome message. Allows for checking and configuring prior to command or main execution
* ##### [success()](#success()) public
Convenience method for out() that wraps message between tag
* ##### [verbose()](#verbose()) public
Output at the verbose level.
* ##### [warn()](#warn()) public
Convenience method for err() that wraps message between tag
* ##### [wrapText()](#wrapText()) public
Wrap a block of text. Allows you to set the width, and indenting on a block of text.
Method Detail
-------------
### \_\_construct() public
```
__construct(Cake\Console\ConsoleIo|null $io = null, Cake\ORM\Locator\LocatorInterface|null $locator = null)
```
Constructs this Shell instance.
#### Parameters
`Cake\Console\ConsoleIo|null` $io optional An io instance.
`Cake\ORM\Locator\LocatorInterface|null` $locator optional Table locator instance.
#### Links
https://book.cakephp.org/4/en/console-commands/shells.html
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_get() public
```
__get(string $name): Cake\Console\Shell
```
Overload get for lazy building of tasks
#### Parameters
`string` $name The task to get.
#### Returns
`Cake\Console\Shell`
### \_appendShells() protected
```
_appendShells(string $type, array<string> $shells, array<string, mixed> $shellList, array<string> $skip): array<string, mixed>
```
Scan the provided paths for shells, and append them into $shellList
#### Parameters
`string` $type The type of object.
`array<string>` $shells The shell names.
`array<string, mixed>` $shellList List of shells.
`array<string>` $skip List of command names to skip.
#### Returns
`array<string, mixed>`
### \_displayHelp() protected
```
_displayHelp(string|null $command = null): int|null
```
Display the help in the correct format
#### Parameters
`string|null` $command optional The command to get help for.
#### Returns
`int|null`
### \_findShells() protected
```
_findShells(array<string, mixed> $shellList, string $path, string $key, array<string> $skip): array<string, mixed>
```
Find shells in $path and add them to $shellList
#### Parameters
`array<string, mixed>` $shellList The shell listing array.
`string` $path The path to look in.
`string` $key The key to add shells to
`array<string>` $skip A list of commands to exclude.
#### Returns
`array<string, mixed>`
### \_mergeProperty() protected
```
_mergeProperty(string $property, array<string> $parentClasses, array<string, mixed> $options): void
```
Merge a single property with the values declared in all parent classes.
#### Parameters
`string` $property The name of the property being merged.
`array<string>` $parentClasses An array of classes you want to merge with.
`array<string, mixed>` $options Options for merging the property, see \_mergeVars()
#### Returns
`void`
### \_mergePropertyData() protected
```
_mergePropertyData(array $current, array $parent, bool $isAssoc): array
```
Merge each of the keys in a property together.
#### Parameters
`array` $current The current merged value.
`array` $parent The parent class' value.
`bool` $isAssoc Whether the merging should be done in associative mode.
#### Returns
`array`
### \_mergeVars() protected
```
_mergeVars(array<string> $properties, array<string, mixed> $options = []): void
```
Merge the list of $properties with all parent classes of the current class.
### Options:
* `associative` - A list of properties that should be treated as associative arrays. Properties in this list will be passed through Hash::normalize() before merging.
#### Parameters
`array<string>` $properties An array of properties and the merge strategy for them.
`array<string, mixed>` $options optional The options to use when merging properties.
#### Returns
`void`
### \_scanDir() protected
```
_scanDir(string $dir): array<string>
```
Scan a directory for .php files and return the class names that should be within them.
#### Parameters
`string` $dir The directory to read.
#### Returns
`array<string>`
### \_setModelClass() protected
```
_setModelClass(string $name): void
```
Set the modelClass property based on conventions.
If the property is already set it will not be overwritten
#### Parameters
`string` $name Class name.
#### Returns
`void`
### \_setOutputLevel() protected
```
_setOutputLevel(): void
```
Set the output level based on the parameters.
This reconfigures both the output level for out() and the configured stdout/stderr logging
#### Returns
`void`
### \_stop() protected
```
_stop(int $status = self::CODE_SUCCESS): void
```
Stop execution of the current script. Raises a StopException to try and halt the execution.
#### Parameters
`int` $status optional see <https://secure.php.net/exit> for values
#### Returns
`void`
#### Throws
`Cake\Console\Exception\StopException`
### \_validateTasks() protected
```
_validateTasks(): void
```
Checks that the tasks in the task map are actually available
#### Returns
`void`
#### Throws
`RuntimeException`
### \_welcome() protected
```
_welcome(): void
```
Displays a header for the shell
#### Returns
`void`
### abort() public
```
abort(string $message, int $exitCode = self::CODE_ERROR): void
```
Displays a formatted error message and exits the application with an error code.
#### Parameters
`string` $message The error message
`int` $exitCode optional The exit code for the shell task.
#### Returns
`void`
#### Throws
`Cake\Console\Exception\StopException`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#styling-output
### clear() public
```
clear(): void
```
Clear the console
#### Returns
`void`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#console-output
### createFile() public
```
createFile(string $path, string $contents): bool
```
Creates a file at given path
#### Parameters
`string` $path Where to put the file.
`string` $contents Content to put in the file.
#### Returns
`bool`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#creating-files
### dispatchShell() public
```
dispatchShell(): int
```
Dispatch a command to another Shell. Similar to Object::requestAction() but intended for running shells from other shells.
### Usage:
With a string command:
```
return $this->dispatchShell('schema create DbAcl');
```
Avoid using this form if you have string arguments, with spaces in them. The dispatched will be invoked incorrectly. Only use this form for simple command dispatching.
With an array command:
```
return $this->dispatchShell('schema', 'create', 'i18n', '--dry');
```
With an array having two key / value pairs:
* `command` can accept either a string or an array. Represents the command to dispatch
+ `extra` can accept an array of extra parameters to pass on to the dispatcher. This parameters will be available in the `param` property of the called `Shell`
`return $this->dispatchShell([ 'command' => 'schema create DbAcl', 'extra' => ['param' => 'value'] ]);`
or
`return $this->dispatchShell([ 'command' => ['schema', 'create', 'DbAcl'], 'extra' => ['param' => 'value'] ]);`
#### Returns
`int`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#invoking-other-shells-from-your-shell
### err() public
```
err(array<string>|string $message, int $newlines = 1): int
```
Outputs a single or multiple error messages to stderr. If no parameters are passed outputs just a newline.
#### Parameters
`array<string>|string` $message A string or an array of strings to output
`int` $newlines optional Number of newlines to append
#### Returns
`int`
### fetchTable() public
```
fetchTable(string|null $alias = null, array<string, mixed> $options = []): Cake\ORM\Table
```
Convenience method to get a table instance.
#### Parameters
`string|null` $alias optional The alias name you want to get. Should be in CamelCase format. If `null` then the value of $defaultTable property is used.
`array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the registry options will be ignored.
#### Returns
`Cake\ORM\Table`
#### Throws
`Cake\Core\Exception\CakeException`
If `$alias` argument and `$defaultTable` property both are `null`. #### See Also
\Cake\ORM\TableLocator::get() ### getIo() public
```
getIo(): Cake\Console\ConsoleIo
```
Get the io object for this shell.
#### Returns
`Cake\Console\ConsoleIo`
### getModelType() public
```
getModelType(): string
```
Get the model type to be used by this class
#### Returns
`string`
### getOptionParser() public
```
getOptionParser(): Cake\Console\ConsoleOptionParser
```
Gets the option parser instance and configures it.
By overriding this method you can configure the ConsoleOptionParser before returning it.
#### Returns
`Cake\Console\ConsoleOptionParser`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#configuring-options-and-generating-help
### getShellList() public
```
getShellList(): array
```
Gets the shell command listing.
#### Returns
`array`
### getTableLocator() public
```
getTableLocator(): Cake\ORM\Locator\LocatorInterface
```
Gets the table locator.
#### Returns
`Cake\ORM\Locator\LocatorInterface`
### hasMethod() public
```
hasMethod(string $name): bool
```
Check to see if this shell has a callable method by the given name.
#### Parameters
`string` $name The method name to check.
#### Returns
`bool`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#shell-tasks
### hasTask() public
```
hasTask(string $task): bool
```
Check to see if this shell has a task with the provided name.
#### Parameters
`string` $task The task name to check.
#### Returns
`bool`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#shell-tasks
### helper() public
```
helper(string $name, array<string, mixed> $config = []): Cake\Console\Helper
```
Render a Console Helper
Create and render the output for a helper object. If the helper object has not already been loaded, it will be loaded and constructed.
#### Parameters
`string` $name The name of the helper to render
`array<string, mixed>` $config optional Configuration data for the helper.
#### Returns
`Cake\Console\Helper`
### hr() public
```
hr(int $newlines = 0, int $width = 63): void
```
Outputs a series of minus characters to the standard output, acts as a visual separator.
#### Parameters
`int` $newlines optional Number of newlines to pre- and append
`int` $width optional Width of the line, defaults to 63
#### Returns
`void`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#Shell::hr
### in() public
```
in(string $prompt, array<string>|string|null $options = null, string|null $default = null): string|null
```
Prompts the user for input, and returns it.
#### Parameters
`string` $prompt Prompt text.
`array<string>|string|null` $options optional Array or string of options.
`string|null` $default optional Default input value.
#### Returns
`string|null`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#Shell::in
### info() public
```
info(array<string>|string $message, int $newlines = 1, int $level = Shell::NORMAL): int|null
```
Convenience method for out() that wraps message between tag
#### Parameters
`array<string>|string` $message A string or an array of strings to output
`int` $newlines optional Number of newlines to append
`int` $level optional The message's output level, see above.
#### Returns
`int|null`
#### See Also
https://book.cakephp.org/4/en/console-and-shells.html#Shell::out ### initialize() public
```
initialize(): void
```
Initializes the Shell acts as constructor for subclasses allows configuration of tasks prior to shell execution
#### Returns
`void`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#Cake\Console\ConsoleOptionParser::initialize
### loadModel() public
```
loadModel(string|null $modelClass = null, string|null $modelType = null): Cake\Datasource\RepositoryInterface
```
Loads and constructs repository objects required by this object
Typically used to load ORM Table objects as required. Can also be used to load other types of repository objects your application uses.
If a repository provider does not return an object a MissingModelException will be thrown.
#### Parameters
`string|null` $modelClass optional Name of model class to load. Defaults to $this->modelClass. The name can be an alias like `'Post'` or FQCN like `App\Model\Table\PostsTable::class`.
`string|null` $modelType optional The type of repository to load. Defaults to the getModelType() value.
#### Returns
`Cake\Datasource\RepositoryInterface`
#### Throws
`Cake\Datasource\Exception\MissingModelException`
If the model class cannot be found.
`UnexpectedValueException`
If $modelClass argument is not provided and ModelAwareTrait::$modelClass property value is empty. ### loadTasks() public
```
loadTasks(): true
```
Loads tasks defined in public $tasks
#### Returns
`true`
### log() public
```
log(string $message, string|int $level = LogLevel::ERROR, array|string $context = []): bool
```
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
#### Parameters
`string` $message Log message.
`string|int` $level optional Error level.
`array|string` $context optional Additional log data relevant to this message.
#### Returns
`bool`
### main() public @method
```
main(mixed ...$args): int|bool|null|void
```
Main entry method for the shell.
#### Parameters
...$args #### Returns
`int|bool|null|void`
### modelFactory() public
```
modelFactory(string $type, Cake\Datasource\Locator\LocatorInterface|callable $factory): void
```
Override a existing callable to generate repositories of a given type.
#### Parameters
`string` $type The name of the repository type the factory function is for.
`Cake\Datasource\Locator\LocatorInterface|callable` $factory The factory function used to create instances.
#### Returns
`void`
### nl() public
```
nl(int $multiplier = 1): string
```
Returns a single or multiple linefeeds sequences.
#### Parameters
`int` $multiplier optional Number of times the linefeed sequence should be repeated
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#Shell::nl
### out() public
```
out(array<string>|string $message, int $newlines = 1, int $level = Shell::NORMAL): int|null
```
Outputs a single or multiple messages to stdout. If no parameters are passed outputs just a newline.
### Output levels
There are 3 built-in output level. Shell::QUIET, Shell::NORMAL, Shell::VERBOSE. The verbose and quiet output levels, map to the `verbose` and `quiet` output switches present in most shells. Using Shell::QUIET for a message means it will always display. While using Shell::VERBOSE means it will only display when verbose output is toggled.
#### Parameters
`array<string>|string` $message A string or an array of strings to output
`int` $newlines optional Number of newlines to append
`int` $level optional The message's output level, see above.
#### Returns
`int|null`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#Shell::out
### param() public
```
param(string $name): string|bool|null
```
Safely access the values in $this->params.
#### Parameters
`string` $name The name of the parameter to get.
#### Returns
`string|bool|null`
### parseDispatchArguments() public
```
parseDispatchArguments(array $args): array
```
Parses the arguments for the dispatchShell() method.
#### Parameters
`array` $args Arguments fetch from the dispatchShell() method with func\_get\_args()
#### Returns
`array`
### quiet() public
```
quiet(array<string>|string $message, int $newlines = 1): int|null
```
Output at all levels.
#### Parameters
`array<string>|string` $message A string or an array of strings to output
`int` $newlines optional Number of newlines to append
#### Returns
`int|null`
### runCommand() public
```
runCommand(array $argv, bool $autoMethod = false, array $extra = []): int|bool|null
```
Runs the Shell with the provided argv.
Delegates calls to Tasks and resolves methods inside the class. Commands are looked up with the following order:
* Method on the shell.
* Matching task name.
* `main()` method.
If a shell implements a `main()` method, all missing method calls will be sent to `main()` with the original method name in the argv.
For tasks to be invoked they *must* be exposed as subcommands. If you define any subcommands, you must define all the subcommands your shell needs, whether they be methods on this class or methods on tasks.
#### Parameters
`array` $argv Array of arguments to run the shell with. This array should be missing the shell name.
`bool` $autoMethod optional Set to true to allow any public method to be called even if it was not defined as a subcommand. This is used by ShellDispatcher to make building simple shells easy.
`array` $extra optional Extra parameters that you can manually pass to the Shell to be dispatched. Built-in extra parameter is :
#### Returns
`int|bool|null`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#the-cakephp-console
### setIo() public
```
setIo(Cake\Console\ConsoleIo $io): void
```
Set the io object for this shell.
#### Parameters
`Cake\Console\ConsoleIo` $io The ConsoleIo object to use.
#### Returns
`void`
### setModelType() public
```
setModelType(string $modelType): $this
```
Set the model type to be used by this class
#### Parameters
`string` $modelType The model type
#### Returns
`$this`
### setRootName() public
```
setRootName(string $name): $this
```
Set the root command name for help output.
#### Parameters
`string` $name The name of the root command.
#### Returns
`$this`
### setTableLocator() public
```
setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this
```
Sets the table locator.
#### Parameters
`Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance.
#### Returns
`$this`
### shortPath() public
```
shortPath(string $file): string
```
Makes absolute file path easier to read
#### Parameters
`string` $file Absolute file path
#### Returns
`string`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#Shell::shortPath
### startup() public
```
startup(): void
```
Starts up the Shell and displays the welcome message. Allows for checking and configuring prior to command or main execution
Override this method if you want to remove the welcome information, or otherwise modify the pre-command flow.
#### Returns
`void`
#### Links
https://book.cakephp.org/4/en/console-and-shells.html#Cake\Console\ConsoleOptionParser::startup
### success() public
```
success(array<string>|string $message, int $newlines = 1, int $level = Shell::NORMAL): int|null
```
Convenience method for out() that wraps message between tag
#### Parameters
`array<string>|string` $message A string or an array of strings to output
`int` $newlines optional Number of newlines to append
`int` $level optional The message's output level, see above.
#### Returns
`int|null`
#### See Also
https://book.cakephp.org/4/en/console-and-shells.html#Shell::out ### verbose() public
```
verbose(array<string>|string $message, int $newlines = 1): int|null
```
Output at the verbose level.
#### Parameters
`array<string>|string` $message A string or an array of strings to output
`int` $newlines optional Number of newlines to append
#### Returns
`int|null`
### warn() public
```
warn(array<string>|string $message, int $newlines = 1): int
```
Convenience method for err() that wraps message between tag
#### Parameters
`array<string>|string` $message A string or an array of strings to output
`int` $newlines optional Number of newlines to append
#### Returns
`int`
#### See Also
https://book.cakephp.org/4/en/console-and-shells.html#Shell::err ### wrapText() public
```
wrapText(string $text, array<string, mixed>|int $options = []): string
```
Wrap a block of text. Allows you to set the width, and indenting on a block of text.
### Options
* `width` The width to wrap to. Defaults to 72
* `wordWrap` Only wrap on words breaks (spaces) Defaults to true.
* `indent` Indent the text with the string provided. Defaults to null.
#### Parameters
`string` $text Text the text to format.
`array<string, mixed>|int` $options optional Array of options to use, or an integer to wrap the text to.
#### Returns
`string`
#### See Also
\Cake\Utility\Text::wrap() #### Links
https://book.cakephp.org/4/en/console-and-shells.html#Shell::wrapText
Property Detail
---------------
### $OptionParser public
An instance of ConsoleOptionParser that has been configured for this class.
#### Type
`Cake\Console\ConsoleOptionParser`
### $Tasks public
Task Collection for the command, used to create Tasks.
#### Type
`Cake\Console\TaskRegistry`
### $\_io protected
ConsoleIo instance.
#### Type
`Cake\Console\ConsoleIo`
### $\_modelFactories protected
A list of overridden model factory functions.
#### Type
`array<callableCake\Datasource\Locator\LocatorInterface>`
### $\_modelType protected
The model type to use.
#### Type
`string`
### $\_tableLocator protected
Table locator instance
#### Type
`Cake\ORM\Locator\LocatorInterface|null`
### $\_taskMap protected
Normalized map of tasks.
#### Type
`array<string, array>`
### $args public
Contains arguments parsed from the command line.
#### Type
`array`
### $command public
The command (method/task) that is being run.
#### Type
`string|null`
### $defaultTable protected
This object's default table alias.
#### Type
`string|null`
### $interactive public
If true, the script will ask for permission to perform actions.
#### Type
`bool`
### $modelClass protected deprecated
This object's primary model class name. Should be a plural form. CakePHP will not inflect the name.
Example: For an object named 'Comments', the modelClass would be 'Comments'. Plugin classes should use `Plugin.Comments` style names to correctly load models from the correct plugin.
Use empty string to not use auto-loading on this object. Null auto-detects based on controller name.
#### Type
`string|null`
### $name public
The name of the shell in camelized.
#### Type
`string`
### $params public
Contains command switches parsed from the command line.
#### Type
`array`
### $plugin public
The name of the plugin the shell belongs to. Is automatically set by ShellDispatcher when a shell is constructed.
#### Type
`string`
### $rootName protected
The root command name used when generating help output.
#### Type
`string`
### $taskNames public
Contains the loaded tasks
#### Type
`array<string>`
### $tasks public
Contains tasks to load and instantiate
#### Type
`array|bool`
| programming_docs |
cakephp Class ValuesExpression Class ValuesExpression
=======================
An expression object to contain values being inserted.
Helps generate SQL with the correct number of placeholders and bind values correctly into the statement.
**Namespace:** [Cake\Database\Expression](namespace-cake.database.expression)
Property Summary
----------------
* [$\_castedExpressions](#%24_castedExpressions) protected `bool` Whether values have been casted to expressions already.
* [$\_columns](#%24_columns) protected `array` List of columns to ensure are part of the insert.
* [$\_query](#%24_query) protected `Cake\Database\Query|null` The Query object to use as a values expression
* [$\_typeMap](#%24_typeMap) protected `Cake\Database\TypeMap|null`
* [$\_values](#%24_values) protected `array` Array of values to insert.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_castToExpression()](#_castToExpression()) protected
Conditionally converts the passed value to an ExpressionInterface object if the type class implements the ExpressionTypeInterface. Otherwise, returns the value unmodified.
* ##### [\_columnNames()](#_columnNames()) protected
Get the bare column names.
* ##### [\_processExpressions()](#_processExpressions()) protected
Converts values that need to be casted to expressions
* ##### [\_requiresToExpressionCasting()](#_requiresToExpressionCasting()) protected
Returns an array with the types that require values to be casted to expressions, out of the list of type names passed as parameter.
* ##### [add()](#add()) public
Add a row of data to be inserted.
* ##### [getColumns()](#getColumns()) public
Gets the columns to be inserted.
* ##### [getDefaultTypes()](#getDefaultTypes()) public
Gets default types of current type map.
* ##### [getQuery()](#getQuery()) public
Gets the query object to be used as the values expression to be evaluated to insert records in the table.
* ##### [getTypeMap()](#getTypeMap()) public
Returns the existing type map.
* ##### [getValues()](#getValues()) public
Gets the values to be inserted.
* ##### [setColumns()](#setColumns()) public
Sets the columns to be inserted.
* ##### [setDefaultTypes()](#setDefaultTypes()) public
Overwrite the default type mappings for fields in the implementing object.
* ##### [setQuery()](#setQuery()) public
Sets the query object to be used as the values expression to be evaluated to insert records in the table.
* ##### [setTypeMap()](#setTypeMap()) public
Creates a new TypeMap if $typeMap is an array, otherwise exchanges it for the given one.
* ##### [setValues()](#setValues()) public
Sets the values to be inserted.
* ##### [sql()](#sql()) public
Converts the Node into a SQL string fragment.
* ##### [traverse()](#traverse()) public
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
Method Detail
-------------
### \_\_construct() public
```
__construct(array $columns, Cake\Database\TypeMap $typeMap)
```
Constructor
#### Parameters
`array` $columns The list of columns that are going to be part of the values.
`Cake\Database\TypeMap` $typeMap A dictionary of column -> type names
### \_castToExpression() protected
```
_castToExpression(mixed $value, string|null $type = null): mixed
```
Conditionally converts the passed value to an ExpressionInterface object if the type class implements the ExpressionTypeInterface. Otherwise, returns the value unmodified.
#### Parameters
`mixed` $value The value to convert to ExpressionInterface
`string|null` $type optional The type name
#### Returns
`mixed`
### \_columnNames() protected
```
_columnNames(): array
```
Get the bare column names.
Because column names could be identifier quoted, we need to strip the identifiers off of the columns.
#### Returns
`array`
### \_processExpressions() protected
```
_processExpressions(): void
```
Converts values that need to be casted to expressions
#### Returns
`void`
### \_requiresToExpressionCasting() protected
```
_requiresToExpressionCasting(array $types): array
```
Returns an array with the types that require values to be casted to expressions, out of the list of type names passed as parameter.
#### Parameters
`array` $types List of type names
#### Returns
`array`
### add() public
```
add(Cake\Database\Query|array $values): void
```
Add a row of data to be inserted.
#### Parameters
`Cake\Database\Query|array` $values Array of data to append into the insert, or a query for doing INSERT INTO .. SELECT style commands
#### Returns
`void`
#### Throws
`Cake\Database\Exception\DatabaseException`
When mixing array + Query data types. ### getColumns() public
```
getColumns(): array
```
Gets the columns to be inserted.
#### Returns
`array`
### getDefaultTypes() public
```
getDefaultTypes(): array<int|string, string>
```
Gets default types of current type map.
#### Returns
`array<int|string, string>`
### getQuery() public
```
getQuery(): Cake\Database\Query|null
```
Gets the query object to be used as the values expression to be evaluated to insert records in the table.
#### Returns
`Cake\Database\Query|null`
### getTypeMap() public
```
getTypeMap(): Cake\Database\TypeMap
```
Returns the existing type map.
#### Returns
`Cake\Database\TypeMap`
### getValues() public
```
getValues(): array
```
Gets the values to be inserted.
#### Returns
`array`
### setColumns() public
```
setColumns(array $columns): $this
```
Sets the columns to be inserted.
#### Parameters
`array` $columns Array with columns to be inserted.
#### Returns
`$this`
### setDefaultTypes() public
```
setDefaultTypes(array<int|string, string> $types): $this
```
Overwrite the default type mappings for fields in the implementing object.
This method is useful if you need to set type mappings that are shared across multiple functions/expressions in a query.
To add a default without overwriting existing ones use `getTypeMap()->addDefaults()`
#### Parameters
`array<int|string, string>` $types The array of types to set.
#### Returns
`$this`
#### See Also
\Cake\Database\TypeMap::setDefaults() ### setQuery() public
```
setQuery(Cake\Database\Query $query): $this
```
Sets the query object to be used as the values expression to be evaluated to insert records in the table.
#### Parameters
`Cake\Database\Query` $query The query to set
#### Returns
`$this`
### setTypeMap() public
```
setTypeMap(Cake\Database\TypeMap|array $typeMap): $this
```
Creates a new TypeMap if $typeMap is an array, otherwise exchanges it for the given one.
#### Parameters
`Cake\Database\TypeMap|array` $typeMap Creates a TypeMap if array, otherwise sets the given TypeMap
#### Returns
`$this`
### setValues() public
```
setValues(array $values): $this
```
Sets the values to be inserted.
#### Parameters
`array` $values Array with values to be inserted.
#### Returns
`$this`
### sql() public
```
sql(Cake\Database\ValueBinder $binder): string
```
Converts the Node into a SQL string fragment.
#### Parameters
`Cake\Database\ValueBinder` $binder #### Returns
`string`
### traverse() public
```
traverse(Closure $callback): $this
```
Iterates over each part of the expression recursively for every level of the expressions tree and executes the $callback callable passing as first parameter the instance of the expression currently being iterated.
#### Parameters
`Closure` $callback #### Returns
`$this`
Property Detail
---------------
### $\_castedExpressions protected
Whether values have been casted to expressions already.
#### Type
`bool`
### $\_columns protected
List of columns to ensure are part of the insert.
#### Type
`array`
### $\_query protected
The Query object to use as a values expression
#### Type
`Cake\Database\Query|null`
### $\_typeMap protected
#### Type
`Cake\Database\TypeMap|null`
### $\_values protected
Array of values to insert.
#### Type
`array`
cakephp Namespace Transport Namespace Transport
===================
### Classes
* ##### [DebugTransport](class-cake.mailer.transport.debugtransport)
Debug Transport class, useful for emulating the email sending process and inspecting the resultant email message before actually sending it during development
* ##### [MailTransport](class-cake.mailer.transport.mailtransport)
Send mail using mail() function
* ##### [SmtpTransport](class-cake.mailer.transport.smtptransport)
Send mail using SMTP protocol
cakephp Namespace Loader Namespace Loader
================
### Classes
* ##### [SelectLoader](class-cake.orm.association.loader.selectloader)
Implements the logic for loading an association using a SELECT query
* ##### [SelectWithPivotLoader](class-cake.orm.association.loader.selectwithpivotloader)
Implements the logic for loading an association using a SELECT query and a pivot table
cakephp Class MissingEntityException Class MissingEntityException
=============================
Exception raised when an Entity could not be found.
**Namespace:** [Cake\ORM\Exception](namespace-cake.orm.exception)
Property Summary
----------------
* [$\_attributes](#%24_attributes) protected `array` Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
* [$\_defaultCode](#%24_defaultCode) protected `int` Default exception code
* [$\_messageTemplate](#%24_messageTemplate) protected `string` Template string that has attributes sprintf()'ed into it.
* [$\_responseHeaders](#%24_responseHeaders) protected `array|null` Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor.
* ##### [getAttributes()](#getAttributes()) public
Get the passed in attributes
* ##### [getCode()](#getCode()) public @method
Gets the Exception code.
* ##### [responseHeader()](#responseHeader()) public deprecated
Get/set the response header to be used
Method Detail
-------------
### \_\_construct() public
```
__construct(array|string $message = '', int|null $code = null, Throwable|null $previous = null)
```
Constructor.
Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off.
#### Parameters
`array|string` $message optional 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
`int|null` $code optional The error code
`Throwable|null` $previous optional the previous exception.
### getAttributes() public
```
getAttributes(): array
```
Get the passed in attributes
#### Returns
`array`
### getCode() public @method
```
getCode(): int
```
Gets the Exception code.
#### Returns
`int`
### responseHeader() public
```
responseHeader(array|string|null $header = null, string|null $value = null): array|null
```
Get/set the response header to be used
See also {@link \Cake\Http\Response::withHeader()}
#### Parameters
`array|string|null` $header optional A single header string or an associative array of "header name" => "header value"
`string|null` $value optional The header value.
#### Returns
`array|null`
Property Detail
---------------
### $\_attributes protected
Array of attributes that are passed in from the constructor, and made available in the view when a development error is displayed.
#### Type
`array`
### $\_defaultCode protected
Default exception code
#### Type
`int`
### $\_messageTemplate protected
Template string that has attributes sprintf()'ed into it.
#### Type
`string`
### $\_responseHeaders protected
Array of headers to be passed to {@link \Cake\Http\Response::withHeader()}
#### Type
`array|null`
cakephp Class ValidationSet Class ValidationSet
====================
ValidationSet object. Holds all validation rules for a field and exposes methods to dynamically add or remove validation rules
**Namespace:** [Cake\Validation](namespace-cake.validation)
Property Summary
----------------
* [$\_allowEmpty](#%24_allowEmpty) protected `callable|string|bool` Denotes if a field is allowed to be empty
* [$\_rules](#%24_rules) protected `arrayCake\Validation\ValidationRule>` Holds the ValidationRule objects
* [$\_validatePresent](#%24_validatePresent) protected `callable|string|bool` Denotes whether the fieldname key must be present in data array
Method Summary
--------------
* ##### [add()](#add()) public
Sets a ValidationRule $rule with a $name
* ##### [allowEmpty()](#allowEmpty()) public
Sets whether a field value is allowed to be empty.
* ##### [count()](#count()) public
Returns the number of rules in this set
* ##### [getIterator()](#getIterator()) public
Returns an iterator for each of the rules to be applied
* ##### [isEmptyAllowed()](#isEmptyAllowed()) public
Returns whether a field can be left empty.
* ##### [isPresenceRequired()](#isPresenceRequired()) public
Returns whether a field can be left out.
* ##### [offsetExists()](#offsetExists()) public
Returns whether an index exists in the rule set
* ##### [offsetGet()](#offsetGet()) public
Returns a rule object by its index
* ##### [offsetSet()](#offsetSet()) public
Sets or replace a validation rule
* ##### [offsetUnset()](#offsetUnset()) public
Unsets a validation rule
* ##### [remove()](#remove()) public
Removes a validation rule from the set
* ##### [requirePresence()](#requirePresence()) public
Sets whether a field is required to be present in data array.
* ##### [rule()](#rule()) public
Gets a rule for a given name if exists
* ##### [rules()](#rules()) public
Returns all rules for this validation set
Method Detail
-------------
### add() public
```
add(string $name, Cake\Validation\ValidationRule|array $rule): $this
```
Sets a ValidationRule $rule with a $name
### Example:
```
$set
->add('notBlank', ['rule' => 'notBlank'])
->add('inRange', ['rule' => ['between', 4, 10])
```
#### Parameters
`string` $name The name under which the rule should be set
`Cake\Validation\ValidationRule|array` $rule The validation rule to be set
#### Returns
`$this`
### allowEmpty() public
```
allowEmpty(callable|string|bool $allowEmpty): $this
```
Sets whether a field value is allowed to be empty.
#### Parameters
`callable|string|bool` $allowEmpty Valid values are true, false, 'create', 'update' or a callable.
#### Returns
`$this`
### count() public
```
count(): int
```
Returns the number of rules in this set
#### Returns
`int`
### getIterator() public
```
getIterator(): Traversable<string,Cake\Validation\ValidationRule>
```
Returns an iterator for each of the rules to be applied
#### Returns
`Traversable<string,Cake\Validation\ValidationRule>`
### isEmptyAllowed() public
```
isEmptyAllowed(): callable|string|bool
```
Returns whether a field can be left empty.
#### Returns
`callable|string|bool`
### isPresenceRequired() public
```
isPresenceRequired(): callable|string|bool
```
Returns whether a field can be left out.
#### Returns
`callable|string|bool`
### offsetExists() public
```
offsetExists(string $index): bool
```
Returns whether an index exists in the rule set
#### Parameters
`string` $index name of the rule
#### Returns
`bool`
### offsetGet() public
```
offsetGet(string $index): Cake\Validation\ValidationRule
```
Returns a rule object by its index
#### Parameters
`string` $index name of the rule
#### Returns
`Cake\Validation\ValidationRule`
### offsetSet() public
```
offsetSet(string $index, Cake\Validation\ValidationRule|array $rule): void
```
Sets or replace a validation rule
#### Parameters
`string` $index name of the rule
`Cake\Validation\ValidationRule|array` $rule Rule to add to $index
#### Returns
`void`
### offsetUnset() public
```
offsetUnset(string $index): void
```
Unsets a validation rule
#### Parameters
`string` $index name of the rule
#### Returns
`void`
### remove() public
```
remove(string $name): $this
```
Removes a validation rule from the set
### Example:
```
$set
->remove('notBlank')
->remove('inRange')
```
#### Parameters
`string` $name The name under which the rule should be unset
#### Returns
`$this`
### requirePresence() public
```
requirePresence(callable|string|bool $validatePresent): $this
```
Sets whether a field is required to be present in data array.
#### Parameters
`callable|string|bool` $validatePresent Valid values are true, false, 'create', 'update' or a callable.
#### Returns
`$this`
### rule() public
```
rule(string $name): Cake\Validation\ValidationRule|null
```
Gets a rule for a given name if exists
#### Parameters
`string` $name The name under which the rule is set.
#### Returns
`Cake\Validation\ValidationRule|null`
### rules() public
```
rules(): arrayCake\Validation\ValidationRule>
```
Returns all rules for this validation set
#### Returns
`arrayCake\Validation\ValidationRule>`
Property Detail
---------------
### $\_allowEmpty protected
Denotes if a field is allowed to be empty
#### Type
`callable|string|bool`
### $\_rules protected
Holds the ValidationRule objects
#### Type
`arrayCake\Validation\ValidationRule>`
### $\_validatePresent protected
Denotes whether the fieldname key must be present in data array
#### Type
`callable|string|bool`
cakephp Class Driver Class Driver
=============
Represents a database driver containing all specificities for a database engine including its SQL dialect.
**Abstract**
**Namespace:** [Cake\Database](namespace-cake.database)
Constants
---------
* `string` **FEATURE\_CTE**
```
'cte'
```
Common Table Expressions (with clause) support.
* `string` **FEATURE\_DISABLE\_CONSTRAINT\_WITHOUT\_TRANSACTION**
```
'disable-constraint-without-transaction'
```
Disabling constraints without being in transaction support.
* `string` **FEATURE\_JSON**
```
'json'
```
Native JSON data type support.
* `string` **FEATURE\_QUOTE**
```
'quote'
```
PDO::quote() support.
* `string` **FEATURE\_SAVEPOINT**
```
'savepoint'
```
Transaction savepoint support.
* `string` **FEATURE\_TRUNCATE\_WITH\_CONSTRAINTS**
```
'truncate-with-constraints'
```
Truncate with foreign keys attached support.
* `string` **FEATURE\_WINDOW**
```
'window'
```
Window function support (all or partial clauses).
* `int|null` **MAX\_ALIAS\_LENGTH**
```
null
```
* `array<int>` **RETRY\_ERROR\_CODES**
```
[]
```
Property Summary
----------------
* [$\_autoQuoting](#%24_autoQuoting) protected `bool` Indicates whether the driver is doing automatic identifier quoting for all queries
* [$\_baseConfig](#%24_baseConfig) protected `array<string, mixed>` Base configuration that is merged into the user supplied configuration data.
* [$\_config](#%24_config) protected `array<string, mixed>` Configuration data.
* [$\_connection](#%24_connection) protected `PDO` Instance of PDO.
* [$\_version](#%24_version) protected `string|null` The server version
* [$connectRetries](#%24connectRetries) protected `int` The last number of connection retry attempts.
Method Summary
--------------
* ##### [\_\_construct()](#__construct()) public
Constructor
* ##### [\_\_debugInfo()](#__debugInfo()) public
Returns an array that can be used to describe the internal state of this object.
* ##### [\_\_destruct()](#__destruct()) public
Destructor
* ##### [\_connect()](#_connect()) protected
Establishes a connection to the database server
* ##### [beginTransaction()](#beginTransaction()) public
Starts a transaction.
* ##### [commitTransaction()](#commitTransaction()) public
Commits a transaction.
* ##### [compileQuery()](#compileQuery()) public
Transforms the passed query to this Driver's dialect and returns an instance of the transformed query and the full compiled SQL string.
* ##### [connect()](#connect()) abstract public
Establishes a connection to the database server.
* ##### [disableAutoQuoting()](#disableAutoQuoting()) public
Disable auto quoting of identifiers in queries.
* ##### [disableForeignKeySQL()](#disableForeignKeySQL()) public
Get the SQL for disabling foreign keys.
* ##### [disconnect()](#disconnect()) public
Disconnects from database server.
* ##### [enableAutoQuoting()](#enableAutoQuoting()) public
Sets whether this driver should automatically quote identifiers in queries.
* ##### [enableForeignKeySQL()](#enableForeignKeySQL()) public
Get the SQL for enabling foreign keys.
* ##### [enabled()](#enabled()) abstract public
Returns whether php is able to use this driver for connecting to database.
* ##### [getConnectRetries()](#getConnectRetries()) public
Returns the number of connection retry attempts made.
* ##### [getConnection()](#getConnection()) public
Get the internal PDO connection instance.
* ##### [getMaxAliasLength()](#getMaxAliasLength()) public
Returns the maximum alias length allowed. This can be different from the maximum identifier length for columns.
* ##### [inTransaction()](#inTransaction()) public
Returns whether a transaction is active for connection.
* ##### [isAutoQuotingEnabled()](#isAutoQuotingEnabled()) public
Returns whether this driver should automatically quote identifiers in queries.
* ##### [isConnected()](#isConnected()) public
Checks whether the driver is connected.
* ##### [lastInsertId()](#lastInsertId()) public
Returns last id generated for a table or sequence in database.
* ##### [newCompiler()](#newCompiler()) public
Returns an instance of a QueryCompiler.
* ##### [newTableSchema()](#newTableSchema()) public
Constructs new TableSchema.
* ##### [prepare()](#prepare()) public
Prepares a sql statement to be executed.
* ##### [queryTranslator()](#queryTranslator()) abstract public
Returns a callable function that will be used to transform a passed Query object. This function, in turn, will return an instance of a Query object that has been transformed to accommodate any specificities of the SQL dialect in use.
* ##### [quote()](#quote()) public
Returns a value in a safe representation to be used in a query string
* ##### [quoteIdentifier()](#quoteIdentifier()) abstract public
Quotes a database identifier (a column name, table name, etc..) to be used safely in queries without the risk of using reserved words.
* ##### [releaseSavePointSQL()](#releaseSavePointSQL()) public
Get the SQL for releasing a save point.
* ##### [rollbackSavePointSQL()](#rollbackSavePointSQL()) public
Get the SQL for rollingback a save point.
* ##### [rollbackTransaction()](#rollbackTransaction()) public
Rollbacks a transaction.
* ##### [savePointSQL()](#savePointSQL()) public
Get the SQL for creating a save point.
* ##### [schema()](#schema()) public
Returns the schema name that's being used.
* ##### [schemaDialect()](#schemaDialect()) abstract public
Get the schema dialect.
* ##### [schemaValue()](#schemaValue()) public
Escapes values for use in schema definitions.
* ##### [setConnection()](#setConnection()) public
Set the internal PDO connection instance.
* ##### [supports()](#supports()) public
Returns whether the driver supports the feature.
* ##### [supportsCTEs()](#supportsCTEs()) public deprecated
Returns true if the server supports common table expressions.
* ##### [supportsDynamicConstraints()](#supportsDynamicConstraints()) public deprecated
Returns whether the driver supports adding or dropping constraints to already created tables.
* ##### [supportsQuoting()](#supportsQuoting()) public deprecated
Checks if the driver supports quoting, as PDO\_ODBC does not support it.
* ##### [supportsSavePoints()](#supportsSavePoints()) public
Returns whether this driver supports save points for nested transactions.
* ##### [version()](#version()) public
Returns connected server version.
Method Detail
-------------
### \_\_construct() public
```
__construct(array<string, mixed> $config = [])
```
Constructor
#### Parameters
`array<string, mixed>` $config optional The configuration for the driver.
#### Throws
`InvalidArgumentException`
### \_\_debugInfo() public
```
__debugInfo(): array<string, mixed>
```
Returns an array that can be used to describe the internal state of this object.
#### Returns
`array<string, mixed>`
### \_\_destruct() public
```
__destruct()
```
Destructor
### \_connect() protected
```
_connect(string $dsn, array<string, mixed> $config): bool
```
Establishes a connection to the database server
#### Parameters
`string` $dsn A Driver-specific PDO-DSN
`array<string, mixed>` $config configuration to be used for creating connection
#### Returns
`bool`
### beginTransaction() public
```
beginTransaction(): bool
```
Starts a transaction.
#### Returns
`bool`
### commitTransaction() public
```
commitTransaction(): bool
```
Commits a transaction.
#### Returns
`bool`
### compileQuery() public
```
compileQuery(Cake\Database\Query $query, Cake\Database\ValueBinder $binder): array
```
Transforms the passed query to this Driver's dialect and returns an instance of the transformed query and the full compiled SQL string.
#### Parameters
`Cake\Database\Query` $query `Cake\Database\ValueBinder` $binder #### Returns
`array`
### connect() abstract public
```
connect(): bool
```
Establishes a connection to the database server.
#### Returns
`bool`
### disableAutoQuoting() public
```
disableAutoQuoting(): $this
```
Disable auto quoting of identifiers in queries.
#### Returns
`$this`
### disableForeignKeySQL() public
```
disableForeignKeySQL(): string
```
Get the SQL for disabling foreign keys.
#### Returns
`string`
### disconnect() public
```
disconnect(): void
```
Disconnects from database server.
#### Returns
`void`
### enableAutoQuoting() public
```
enableAutoQuoting(bool $enable = true): $this
```
Sets whether this driver should automatically quote identifiers in queries.
#### Parameters
`bool` $enable optional #### Returns
`$this`
### enableForeignKeySQL() public
```
enableForeignKeySQL(): string
```
Get the SQL for enabling foreign keys.
#### Returns
`string`
### enabled() abstract public
```
enabled(): bool
```
Returns whether php is able to use this driver for connecting to database.
#### Returns
`bool`
### getConnectRetries() public
```
getConnectRetries(): int
```
Returns the number of connection retry attempts made.
#### Returns
`int`
### getConnection() public
```
getConnection(): PDO
```
Get the internal PDO connection instance.
#### Returns
`PDO`
### getMaxAliasLength() public
```
getMaxAliasLength(): int|null
```
Returns the maximum alias length allowed. This can be different from the maximum identifier length for columns.
#### Returns
`int|null`
### inTransaction() public
```
inTransaction(): bool
```
Returns whether a transaction is active for connection.
#### Returns
`bool`
### isAutoQuotingEnabled() public
```
isAutoQuotingEnabled(): bool
```
Returns whether this driver should automatically quote identifiers in queries.
#### Returns
`bool`
### isConnected() public
```
isConnected(): bool
```
Checks whether the driver is connected.
#### Returns
`bool`
### lastInsertId() public
```
lastInsertId(string|null $table = null, string|null $column = null): string|int
```
Returns last id generated for a table or sequence in database.
#### Parameters
`string|null` $table optional `string|null` $column optional #### Returns
`string|int`
### newCompiler() public
```
newCompiler(): Cake\Database\QueryCompiler
```
Returns an instance of a QueryCompiler.
#### Returns
`Cake\Database\QueryCompiler`
### newTableSchema() public
```
newTableSchema(string $table, array $columns = []): Cake\Database\Schema\TableSchema
```
Constructs new TableSchema.
#### Parameters
`string` $table `array` $columns optional #### Returns
`Cake\Database\Schema\TableSchema`
### prepare() public
```
prepare(Cake\Database\Query|string $query): Cake\Database\StatementInterface
```
Prepares a sql statement to be executed.
#### Parameters
`Cake\Database\Query|string` $query #### Returns
`Cake\Database\StatementInterface`
### queryTranslator() abstract public
```
queryTranslator(string $type): Closure
```
Returns a callable function that will be used to transform a passed Query object. This function, in turn, will return an instance of a Query object that has been transformed to accommodate any specificities of the SQL dialect in use.
#### Parameters
`string` $type #### Returns
`Closure`
### quote() public
```
quote(mixed $value, int $type = PDO::PARAM_STR): string
```
Returns a value in a safe representation to be used in a query string
#### Parameters
`mixed` $value `int` $type optional #### Returns
`string`
### quoteIdentifier() abstract public
```
quoteIdentifier(string $identifier): string
```
Quotes a database identifier (a column name, table name, etc..) to be used safely in queries without the risk of using reserved words.
#### Parameters
`string` $identifier #### Returns
`string`
### releaseSavePointSQL() public
```
releaseSavePointSQL(string|int $name): string
```
Get the SQL for releasing a save point.
#### Parameters
`string|int` $name Save point name or id
#### Returns
`string`
### rollbackSavePointSQL() public
```
rollbackSavePointSQL(string|int $name): string
```
Get the SQL for rollingback a save point.
#### Parameters
`string|int` $name Save point name or id
#### Returns
`string`
### rollbackTransaction() public
```
rollbackTransaction(): bool
```
Rollbacks a transaction.
#### Returns
`bool`
### savePointSQL() public
```
savePointSQL(string|int $name): string
```
Get the SQL for creating a save point.
#### Parameters
`string|int` $name Save point name or id
#### Returns
`string`
### schema() public
```
schema(): string
```
Returns the schema name that's being used.
#### Returns
`string`
### schemaDialect() abstract public
```
schemaDialect(): Cake\Database\Schema\SchemaDialect
```
Get the schema dialect.
Used by {@link \Cake\Database\Schema} package to reflect schema and generate schema.
If all the tables that use this Driver specify their own schemas, then this may return null.
#### Returns
`Cake\Database\Schema\SchemaDialect`
### schemaValue() public
```
schemaValue(mixed $value): string
```
Escapes values for use in schema definitions.
#### Parameters
`mixed` $value #### Returns
`string`
### setConnection() public
```
setConnection(object $connection): $this
```
Set the internal PDO connection instance.
#### Parameters
`object` $connection PDO instance.
#### Returns
`$this`
### supports() public
```
supports(string $feature): bool
```
Returns whether the driver supports the feature.
Defaults to true for FEATURE\_QUOTE and FEATURE\_SAVEPOINT.
#### Parameters
`string` $feature Driver feature name
#### Returns
`bool`
### supportsCTEs() public
```
supportsCTEs(): bool
```
Returns true if the server supports common table expressions.
#### Returns
`bool`
### supportsDynamicConstraints() public
```
supportsDynamicConstraints(): bool
```
Returns whether the driver supports adding or dropping constraints to already created tables.
#### Returns
`bool`
### supportsQuoting() public
```
supportsQuoting(): bool
```
Checks if the driver supports quoting, as PDO\_ODBC does not support it.
#### Returns
`bool`
### supportsSavePoints() public
```
supportsSavePoints(): bool
```
Returns whether this driver supports save points for nested transactions.
#### Returns
`bool`
### version() public
```
version(): string
```
Returns connected server version.
#### Returns
`string`
Property Detail
---------------
### $\_autoQuoting protected
Indicates whether the driver is doing automatic identifier quoting for all queries
#### Type
`bool`
### $\_baseConfig protected
Base configuration that is merged into the user supplied configuration data.
#### Type
`array<string, mixed>`
### $\_config protected
Configuration data.
#### Type
`array<string, mixed>`
### $\_connection protected
Instance of PDO.
#### Type
`PDO`
### $\_version protected
The server version
#### Type
`string|null`
### $connectRetries protected
The last number of connection retry attempts.
#### Type
`int`
| programming_docs |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.