code
stringlengths
2.5k
150k
kind
stringclasses
1 value
cakephp Namespace Log Namespace Log ============= ### Namespaces * [Cake\Log\Engine](namespace-cake.log.engine) * [Cake\Log\Formatter](namespace-cake.log.formatter) ### Classes * ##### [Log](class-cake.log.log) Logs messages to configured Log adapters. One or more adapters can be configured using Cake Logs's methods. If you don't configure any adapters, and write to Log, the messages will be ignored. * ##### [LogEngineRegistry](class-cake.log.logengineregistry) Registry of loaded log engines ### Traits * ##### [LogTrait](trait-cake.log.logtrait) A trait providing an object short-cut method to logging. cakephp Class FormProtectionComponent Class FormProtectionComponent ============================== 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\Controller\Component](namespace-cake.controller.component) Constants --------- * `string` **DEFAULT\_EXCEPTION\_MESSAGE** ``` 'Form tampering protection token validation failed.' ``` Default message used for exceptions thrown. 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 * [$\_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 -------------- * ##### [\_\_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. * ##### [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. * ##### [executeCallback()](#executeCallback()) protected Execute callback. * ##### [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. * ##### [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. * ##### [setConfig()](#setConfig()) public Sets the config. * ##### [startup()](#startup()) public Component startup. * ##### [validationFailure()](#validationFailure()) protected Throws a 400 - Bad request exception or calls custom callback. 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): 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 ### 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` ### executeCallback() protected ``` executeCallback(Closure $callback, Cake\Http\Exception\BadRequestException $exception): Cake\Http\Response|null ``` Execute callback. #### Parameters `Closure` $callback A valid callable `Cake\Http\Exception\BadRequestException` $exception Exception instance. #### Returns `Cake\Http\Response|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` ### 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` ### 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. ### startup() public ``` startup(Cake\Event\EventInterface $event): Cake\Http\Response|null ``` Component startup. Token check happens here. #### Parameters `Cake\Event\EventInterface` $event An Event instance #### Returns `Cake\Http\Response|null` ### validationFailure() protected ``` validationFailure(Cake\Form\FormProtector $formProtector): Cake\Http\Response|null ``` Throws a 400 - Bad request exception or calls custom callback. If `validationFailureCallback` config is specified, it will use this callback by executing the method passing the argument as exception. #### Parameters `Cake\Form\FormProtector` $formProtector Form Protector instance. #### Returns `Cake\Http\Response|null` #### Throws `Cake\Http\Exception\BadRequestException` 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 * `validate` - Whether to validate request body / data. Set to false to disable for data coming from 3rd party services, etc. * `unlockedFields` - Form fields to exclude from validation. Fields can be unlocked either in the Component, or with FormHelper::unlockField(). Fields that have been unlocked are not required to be part of the POST and hidden unlocked fields do not have their values checked. * `unlockedActions` - Actions to exclude from POST validation checks. * `validationFailureCallback` - Callback to call in case of validation failure. Must be a valid Closure. Unset by default in which case exception is thrown on validation failure. #### Type `array<string, mixed>` ### $\_registry protected Component registry class used to lazy load components. #### Type `Cake\Controller\ComponentRegistry` ### $components protected Other Components this component uses. #### Type `array` cakephp Class TimeType Class TimeType =============== Time type converter. Use to convert time instances to strings & back. **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 #### 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 Trait ValidatorAwareTrait Trait ValidatorAwareTrait ========================== A trait that provides methods for building and interacting with Validators. This trait is useful when building ORM like features where the implementing class wants to build and customize a variety of validator instances. This trait expects that classes including it define three constants: * `DEFAULT_VALIDATOR` - The default validator name. * `VALIDATOR_PROVIDER_NAME` - The provider name the including class is assigned in validators. * `BUILD_VALIDATOR_EVENT` - The name of the event to be triggred when validators are built. If the including class also implements events the `Model.buildValidator` event will be triggered when validators are created. **Namespace:** [Cake\Validation](namespace-cake.validation) Property Summary ---------------- * [$\_validatorClass](#%24_validatorClass) protected `string` Validator class. * [$\_validators](#%24_validators) protected `arrayCake\Validation\Validator>` A list of validation objects indexed by name Method Summary -------------- * ##### [createValidator()](#createValidator()) protected Creates a validator using a custom method inside your class. * ##### [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. * ##### [setValidator()](#setValidator()) public This method stores a custom validator under the given name. * ##### [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 ------------- ### 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` ### 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` ### 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` ### 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 --------------- ### $\_validatorClass protected Validator class. #### Type `string` ### $\_validators protected A list of validation objects indexed by name #### Type `arrayCake\Validation\Validator>` cakephp Namespace Form Namespace Form ============== ### Classes * ##### [Form](class-cake.form.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. * ##### [FormProtector](class-cake.form.formprotector) Protects against form tampering. It ensures that: * ##### [Schema](class-cake.form.schema) Contains the schema information for Form instances. cakephp Class LogEngineRegistry Class LogEngineRegistry ======================== Registry of loaded log engines **Namespace:** [Cake\Log](namespace-cake.log) 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 logger instance. * ##### [\_resolveClassName()](#_resolveClassName()) protected Resolve a logger classname. * ##### [\_throwMissingClassError()](#_throwMissingClassError()) protected Throws an exception when a logger 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 logger 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): Psr\Log\LoggerInterface ``` Create the logger 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 logger. #### Returns `Psr\Log\LoggerInterface` #### Throws `RuntimeException` when an object doesn't implement the correct interface. ### \_resolveClassName() protected ``` _resolveClassName(string $class): string|null ``` Resolve a logger 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 logger 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 logger is missing in. #### Returns `void` #### Throws `RuntimeException` ### 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 logger from the registry. If this registry has an event manager, the object will be detached from any events as well. #### Parameters `string` $name The logger name. #### Returns `$this` Property Detail --------------- ### $\_loaded protected Map of loaded objects. #### Type `array<object>` cakephp Class MethodNotAllowedException Class MethodNotAllowedException ================================ Represents an HTTP 405 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 'Method Not Allowed' will be the message `int|null` $code optional Status code, defaults to 405 `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 NotFoundException Class NotFoundException ======================== Represents an HTTP 404 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 Found' will be the message `int|null` $code optional Status code, 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` ### 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 Class Mysql Class Mysql ============ MySQL Driver **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** ``` 256 ``` * `array<int>` **RETRY\_ERROR\_CODES** ``` [] ``` * `string` **SERVER\_TYPE\_MARIADB** ``` 'mariadb' ``` Server type MariaDB * `string` **SERVER\_TYPE\_MYSQL** ``` 'mysql' ``` Server type MySQL 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 MySQL driver * [$\_config](#%24_config) protected `array<string, mixed>` Configuration data. * [$\_connection](#%24_connection) protected `PDO` Instance of PDO. * [$\_endQuote](#%24_endQuote) protected `string` String used to end a database identifier quoting to make it safe * [$\_schemaDialect](#%24_schemaDialect) protected `Cake\Database\Schema\MysqlSchemaDialect|null` The schema dialect for this driver * [$\_startQuote](#%24_startQuote) protected `string` String used to start a database identifier quoting to make it safe * [$\_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, array<string, string>>` Mapping of feature to db server version for feature availability checks. * [$serverType](#%24serverType) protected `string` Server type. 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 * ##### [\_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. * ##### [isMariadb()](#isMariadb()) public Returns true if the connected server is MariaDB. * ##### [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. * ##### [supportsNativeJson()](#supportsNativeJson()) public deprecated Returns true if the server supports native JSON columns * ##### [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` ### \_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` ### isMariadb() public ``` isMariadb(): bool ``` Returns true if the connected server is MariaDB. #### 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` ### supportsNativeJson() public ``` supportsNativeJson(): bool ``` Returns true if the server supports native JSON columns #### 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 MySQL driver #### Type `array<string, mixed>` ### $\_config protected Configuration data. #### Type `array<string, mixed>` ### $\_connection protected Instance of PDO. #### Type `PDO` ### $\_endQuote protected String used to end a database identifier quoting to make it safe #### Type `string` ### $\_schemaDialect protected The schema dialect for this driver #### Type `Cake\Database\Schema\MysqlSchemaDialect|null` ### $\_startQuote protected String used to start a database identifier quoting to make it safe #### Type `string` ### $\_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, array<string, string>>` ### $serverType protected Server type. If the underlying server is MariaDB, its value will get set to `'mariadb'` after `version()` method is called. #### Type `string`
programming_docs
cakephp Class Container Class Container ================ Dependency Injection container Based on the container out of League\Container **Namespace:** [Cake\Core](namespace-cake.core) Property Summary ---------------- * [$defaultToShared](#%24defaultToShared) protected `boolean` * [$definitions](#%24definitions) protected `DefinitionAggregateInterface` * [$delegates](#%24delegates) protected `ContainerInterface[]` * [$inflectors](#%24inflectors) protected `InflectorAggregateInterface` * [$providers](#%24providers) protected `ServiceProviderAggregateInterface` Method Summary -------------- * ##### [\_\_construct()](#__construct()) public * ##### [add()](#add()) public * ##### [addServiceProvider()](#addServiceProvider()) public * ##### [addShared()](#addShared()) public * ##### [defaultToShared()](#defaultToShared()) public * ##### [delegate()](#delegate()) 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 * ##### [resolve()](#resolve()) protected Method Detail ------------- ### \_\_construct() public ``` __construct(DefinitionAggregateInterface $definitions = null, ServiceProviderAggregateInterface $providers = null, InflectorAggregateInterface $inflectors = null) ``` #### Parameters `DefinitionAggregateInterface` $definitions optional `ServiceProviderAggregateInterface` $providers optional `InflectorAggregateInterface` $inflectors optional ### 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` ### defaultToShared() public ``` defaultToShared(bool $shared = true): ContainerInterface ``` #### Parameters `bool` $shared optional #### Returns `ContainerInterface` ### delegate() public ``` delegate(ContainerInterface $container): self ``` #### Parameters `ContainerInterface` $container #### Returns `self` ### 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` ### resolve() protected ``` resolve(mixed $id, bool $new = false) ``` #### Parameters $id `bool` $new optional Property Detail --------------- ### $defaultToShared protected #### Type `boolean` ### $definitions protected #### Type `DefinitionAggregateInterface` ### $delegates protected #### Type `ContainerInterface[]` ### $inflectors protected #### Type `InflectorAggregateInterface` ### $providers protected #### Type `ServiceProviderAggregateInterface` cakephp Class TransactionStrategy Class TransactionStrategy ========================== Fixture strategy that wraps fixtures in a transaction that is rolled back after each test. Any test that calls Connection::rollback(true) will break this strategy. **Namespace:** [Cake\TestSuite\Fixture](namespace-cake.testsuite.fixture) Property Summary ---------------- * [$fixtures](#%24fixtures) protected `arrayCake\Datasource\FixtureInterface>` * [$helper](#%24helper) protected `Cake\TestSuite\Fixture\FixtureHelper` Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Initialize strategy. * ##### [setupTest()](#setupTest()) public Called before each test run in each TestCase. * ##### [teardownTest()](#teardownTest()) public Called after each test run in each TestCase. Method Detail ------------- ### \_\_construct() public ``` __construct() ``` Initialize strategy. ### setupTest() public ``` setupTest(array<string> $fixtureNames): void ``` Called before each test run in each TestCase. #### Parameters `array<string>` $fixtureNames #### Returns `void` ### teardownTest() public ``` teardownTest(): void ``` Called after each test run in each TestCase. #### Returns `void` Property Detail --------------- ### $fixtures protected #### Type `arrayCake\Datasource\FixtureInterface>` ### $helper protected #### Type `Cake\TestSuite\Fixture\FixtureHelper` cakephp Trait TupleComparisonTranslatorTrait Trait TupleComparisonTranslatorTrait ===================================== Provides a translator method for tuple comparisons **Namespace:** [Cake\Database\Driver](namespace-cake.database.driver) Method Summary -------------- * ##### [\_transformTupleComparison()](#_transformTupleComparison()) protected Receives a TupleExpression and changes it so that it conforms to this SQL dialect. Method Detail ------------- ### \_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` cakephp Namespace Datasource Namespace Datasource ==================== ### Namespaces * [Cake\Datasource\Exception](namespace-cake.datasource.exception) * [Cake\Datasource\Locator](namespace-cake.datasource.locator) * [Cake\Datasource\Paging](namespace-cake.datasource.paging) ### Interfaces * ##### [ConnectionInterface](interface-cake.datasource.connectioninterface) This interface defines the methods you can depend on in a connection. * ##### [EntityInterface](interface-cake.datasource.entityinterface) Describes the methods that any class representing a data storage should comply with. * ##### [FixtureInterface](interface-cake.datasource.fixtureinterface) Defines the interface that testing fixtures use. * ##### [InvalidPropertyInterface](interface-cake.datasource.invalidpropertyinterface) Describes the methods that any class representing a data storage should comply with. * ##### [QueryInterface](interface-cake.datasource.queryinterface) The basis for every query object * ##### [RepositoryInterface](interface-cake.datasource.repositoryinterface) Describes the methods that any class representing a data storage should comply with. * ##### [ResultSetInterface](interface-cake.datasource.resultsetinterface) Describes how a collection of datasource results should look like * ##### [SchemaInterface](interface-cake.datasource.schemainterface) An interface used by TableSchema objects. ### Classes * ##### [ConnectionManager](class-cake.datasource.connectionmanager) Manages and loads instances of Connection * ##### [ConnectionRegistry](class-cake.datasource.connectionregistry) A registry object for connection instances. * ##### [FactoryLocator](class-cake.datasource.factorylocator) Class FactoryLocator * ##### [QueryCacher](class-cake.datasource.querycacher) Handles caching queries and loading results from the cache. * ##### [ResultSetDecorator](class-cake.datasource.resultsetdecorator) Generic ResultSet decorator. This will make any traversable object appear to be a database result * ##### [RuleInvoker](class-cake.datasource.ruleinvoker) Contains logic for invoking an application rule. * ##### [RulesChecker](class-cake.datasource.ruleschecker) Contains logic for storing and checking rules on entities ### Traits * ##### [ModelAwareTrait](trait-cake.datasource.modelawaretrait) Provides functionality for loading table classes and other repositories onto properties of the host object. * ##### [RulesAwareTrait](trait-cake.datasource.rulesawaretrait) A trait that allows a class to build and apply application. rules. cakephp Class RadioWidget Class RadioWidget ================== Input widget class for generating a set of radio buttons. This class is usually used internally by `Cake\View\Helper\FormHelper`, it but can be used to generate standalone radio buttons. **Namespace:** [Cake\View\Widget](namespace-cake.view.widget) 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. * [$\_label](#%24_label) protected `Cake\View\Widget\LabelWidget` Label instance. * [$\_templates](#%24_templates) protected `Cake\View\StringTemplate` StringTemplate instance. * [$defaults](#%24defaults) protected `array<string, mixed>` Data defaults. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [\_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. * ##### [\_isDisabled()](#_isDisabled()) protected Disabled attribute detection. * ##### [\_renderInput()](#_renderInput()) protected Renders a single radio input and label. * ##### [\_renderLabel()](#_renderLabel()) protected Renders a label element for a given radio button. * ##### [mergeDefaults()](#mergeDefaults()) protected Merge default values with supplied data. * ##### [render()](#render()) public Render a set of radio buttons. * ##### [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, Cake\View\Widget\LabelWidget $label) ``` Constructor This class uses a few templates: * `radio` Used to generate the input for a radio button. Can use the following variables `name`, `value`, `attrs`. * `radioWrapper` Used to generate the container element for the radio + input element. Can use the `input` and `label` variables. #### Parameters `Cake\View\StringTemplate` $templates Templates list. `Cake\View\Widget\LabelWidget` $label Label widget instance. ### \_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` ### \_isDisabled() protected ``` _isDisabled(array<string, mixed> $radio, array|true|null $disabled): bool ``` Disabled attribute detection. #### Parameters `array<string, mixed>` $radio Radio info. `array|true|null` $disabled The disabled values. #### Returns `bool` ### \_renderInput() protected ``` _renderInput(string|int $val, array<string, mixed>|string $text, array<string, mixed> $data, Cake\View\Form\ContextInterface $context): string ``` Renders a single radio input and label. #### Parameters `string|int` $val The value of the radio input. `array<string, mixed>|string` $text The label text, or complex radio type. `array<string, mixed>` $data Additional options for input generation. `Cake\View\Form\ContextInterface` $context The form context #### Returns `string` ### \_renderLabel() protected ``` _renderLabel(array<string, mixed> $radio, array<string, mixed>|string|false $label, string $input, Cake\View\Form\ContextInterface $context, bool $escape): string|false ``` Renders a label element for a given radio button. In the future this might be refactored into a separate widget as other input types (multi-checkboxes) will also need labels generated. #### Parameters `array<string, mixed>` $radio The input properties. `array<string, mixed>|string|false` $label The properties for a label. `string` $input The input widget. `Cake\View\Form\ContextInterface` $context The form context. `bool` $escape Whether to HTML escape the label. #### Returns `string|false` ### 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 set of radio buttons. Data supports the following keys: * `name` - Set the input name. * `options` - An array of options. See below for more information. * `disabled` - Either true or an array of inputs to disable. When true, the select element will be disabled. * `val` - A string of the option to mark as selected. * `label` - Either false to disable label generation, or an array of attributes for all labels. * `required` - Set to true to add the required attribute on all generated radios. * `idPrefix` Prefix for generated ID attributes. #### Parameters `array<string, mixed>` $data The data to build radio buttons 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 --------------- ### $\_idPrefix protected Prefix for id attribute. #### Type `string|null` ### $\_idSuffixes protected A list of id suffixes used in the current rendering. #### Type `array<string>` ### $\_label protected Label instance. #### Type `Cake\View\Widget\LabelWidget` ### $\_templates protected StringTemplate instance. #### Type `Cake\View\StringTemplate` ### $defaults protected Data defaults. #### Type `array<string, mixed>` cakephp Interface SqlGeneratorInterface Interface SqlGeneratorInterface ================================ An interface used by TableSchema objects. **Namespace:** [Cake\Database\Schema](namespace-cake.database.schema) Method Summary -------------- * ##### [addConstraintSql()](#addConstraintSql()) public Generate the SQL statements to add the constraints to the table * ##### [createSql()](#createSql()) public Generate the SQL to create the Table. * ##### [dropConstraintSql()](#dropConstraintSql()) public Generate the SQL statements to drop the constraints to the table * ##### [dropSql()](#dropSql()) public Generate the SQL to drop a table. * ##### [truncateSql()](#truncateSql()) public Generate the SQL statements to truncate a table Method Detail ------------- ### addConstraintSql() public ``` addConstraintSql(Cake\Database\Connection $connection): array ``` Generate the SQL statements to add the constraints to the table #### Parameters `Cake\Database\Connection` $connection The connection to generate SQL for. #### Returns `array` ### 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 The connection to generate SQL for. #### Returns `array` ### dropConstraintSql() public ``` dropConstraintSql(Cake\Database\Connection $connection): array ``` Generate the SQL statements to drop the constraints to the table #### Parameters `Cake\Database\Connection` $connection The connection to generate SQL for. #### 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 The connection to generate SQL for. #### Returns `array` ### truncateSql() public ``` truncateSql(Cake\Database\Connection $connection): array ``` Generate the SQL statements to truncate a table #### Parameters `Cake\Database\Connection` $connection The connection to generate SQL for. #### Returns `array`
programming_docs
cakephp Class Plugin Class Plugin ============= Plugin is used to load and locate plugins. It also can retrieve plugin paths and load their bootstrap and routes files. **Namespace:** [Cake\Core](namespace-cake.core) **Link:** https://book.cakephp.org/4/en/plugins.html Property Summary ---------------- * [$plugins](#%24plugins) protected static `Cake\Core\PluginCollection|null` Holds a list of all loaded plugins and their configuration Method Summary -------------- * ##### [classPath()](#classPath()) public static Returns the filesystem path for plugin's folder containing class files. * ##### [configPath()](#configPath()) public static Returns the filesystem path for plugin's folder containing config files. * ##### [getCollection()](#getCollection()) public static Get the shared plugin collection. * ##### [isLoaded()](#isLoaded()) public static Returns true if the plugin $plugin is already loaded. * ##### [loaded()](#loaded()) public static Return a list of loaded plugins. * ##### [path()](#path()) public static Returns the filesystem path for a plugin * ##### [templatePath()](#templatePath()) public static Returns the filesystem path for plugin's folder containing template files. Method Detail ------------- ### classPath() public static ``` classPath(string $name): string ``` Returns the filesystem path for plugin's folder containing class files. #### Parameters `string` $name name of the plugin in CamelCase format. #### Returns `string` #### Throws `Cake\Core\Exception\MissingPluginException` If plugin has not been loaded. ### configPath() public static ``` configPath(string $name): string ``` Returns the filesystem path for plugin's folder containing config files. #### Parameters `string` $name name of the plugin in CamelCase format. #### Returns `string` #### Throws `Cake\Core\Exception\MissingPluginException` If plugin has not been loaded. ### getCollection() public static ``` getCollection(): Cake\Core\PluginCollection ``` Get the shared plugin collection. This method should generally not be used during application runtime as plugins should be set during Application startup. #### Returns `Cake\Core\PluginCollection` ### isLoaded() public static ``` isLoaded(string $plugin): bool ``` Returns true if the plugin $plugin is already loaded. #### Parameters `string` $plugin Plugin name. #### Returns `bool` ### loaded() public static ``` loaded(): array<string> ``` Return a list of loaded plugins. #### Returns `array<string>` ### path() public static ``` path(string $name): string ``` Returns the filesystem path for a plugin #### Parameters `string` $name name of the plugin in CamelCase format #### Returns `string` #### Throws `Cake\Core\Exception\MissingPluginException` If the folder for plugin was not found or plugin has not been loaded. ### templatePath() public static ``` templatePath(string $name): string ``` Returns the filesystem path for plugin's folder containing template files. #### Parameters `string` $name name of the plugin in CamelCase format. #### Returns `string` #### Throws `Cake\Core\Exception\MissingPluginException` If plugin has not been loaded. Property Detail --------------- ### $plugins protected static Holds a list of all loaded plugins and their configuration #### Type `Cake\Core\PluginCollection|null` cakephp Interface FixtureStrategyInterface Interface FixtureStrategyInterface =================================== Base interface for strategies used to manage fixtures for TestCase. **Namespace:** [Cake\TestSuite\Fixture](namespace-cake.testsuite.fixture) Method Summary -------------- * ##### [setupTest()](#setupTest()) public Called before each test run in each TestCase. * ##### [teardownTest()](#teardownTest()) public Called after each test run in each TestCase. Method Detail ------------- ### setupTest() public ``` setupTest(array<string> $fixtureNames): void ``` Called before each test run in each TestCase. #### Parameters `array<string>` $fixtureNames Name of fixtures used by test. #### Returns `void` ### teardownTest() public ``` teardownTest(): void ``` Called after each test run in each TestCase. #### Returns `void` cakephp Trait IntegrationTestTrait Trait IntegrationTestTrait =========================== A trait 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. **Namespace:** [Cake\TestSuite](namespace-cake.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. * [$\_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. * [$\_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 Method Summary -------------- * ##### [\_addTokens()](#_addTokens()) protected Add the CSRF and Security Component tokens if necessary. * ##### [\_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. * ##### [\_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. * ##### [\_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() * ##### [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 * ##### [assertFileResponse()](#assertFileResponse()) public Asserts that a file with the given name was sent in the response * ##### [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 * ##### [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 * ##### [assertLayout()](#assertLayout()) public Asserts that the search string was in the layout name. * ##### [assertNoRedirect()](#assertNoRedirect()) public Asserts that the Location header is not set. * ##### [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 * ##### [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. * ##### [assertSession()](#assertSession()) public Asserts session contents * ##### [assertSessionHasKey()](#assertSessionHasKey()) public Asserts session key exists. * ##### [assertSessionNotHasKey()](#assertSessionNotHasKey()) public Asserts a session key does not exist. * ##### [assertTemplate()](#assertTemplate()) public Asserts that the search string was in the template name. * ##### [cleanup()](#cleanup()) public Clears the state used for requests. * ##### [cleanupContainer()](#cleanupContainer()) public Clears any mocks that were defined and cleans up application class configuration. * ##### [configApplication()](#configApplication()) public Configure the application class to use in integration tests. * ##### [configRequest()](#configRequest()) public Configures the data for the *next* request. * ##### [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. * ##### [createApp()](#createApp()) protected Create an application instance. * ##### [delete()](#delete()) public Performs a DELETE request using the current request data. * ##### [disableErrorHandlerMiddleware()](#disableErrorHandlerMiddleware()) public Disable the error handler middleware. * ##### [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. * ##### [extractExceptionMessage()](#extractExceptionMessage()) protected Extract verbose message for existing exception * ##### [extractVerboseMessage()](#extractVerboseMessage()) protected Inspect controller to extract possible causes of the failed assertion * ##### [get()](#get()) public Performs a GET request using the current request data. * ##### [getSession()](#getSession()) protected * ##### [head()](#head()) public Performs a HEAD request using the current request data. * ##### [mockService()](#mockService()) public Add a mocked service to the container. * ##### [modifyContainer()](#modifyContainer()) public Wrap the application's container with one containing mocks. * ##### [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. * ##### [put()](#put()) public Performs a PUT request using the current request data. * ##### [removeMockService()](#removeMockService()) public Remove a mocked service to the container. * ##### [session()](#session()) public Sets session data. * ##### [setUnlockedFields()](#setUnlockedFields()) public Set list of fields that are excluded from field validation. * ##### [viewVariable()](#viewVariable()) public Fetches a view variable by name. Method Detail ------------- ### \_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` ### \_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` ### \_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` ### \_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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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() ### createApp() protected ``` createApp(): Cake\Core\HttpApplicationInterfaceCake\Core\ConsoleApplicationInterface ``` Create an application instance. Uses the configuration set in `configApplication()`. #### Returns `Cake\Core\HttpApplicationInterfaceCake\Core\ConsoleApplicationInterface` ### 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` ### 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` ### 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` ### 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` ### 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` ### getSession() protected ``` getSession(): Cake\TestSuite\TestSession ``` #### Returns `Cake\TestSuite\TestSession` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` Property Detail --------------- ### $\_appArgs protected The customized application constructor arguments. #### Type `array|null` ### $\_appClass protected The customized application class name. #### Type `string|null` ### $\_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` ### $\_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`
programming_docs
cakephp Namespace Engine Namespace Engine ================ ### Classes * ##### [IniConfig](class-cake.core.configure.engine.iniconfig) Ini file configuration engine. * ##### [JsonConfig](class-cake.core.configure.engine.jsonconfig) JSON engine allows Configure to load configuration values from files containing JSON strings. * ##### [PhpConfig](class-cake.core.configure.engine.phpconfig) PHP engine allows Configure to load configuration values from files containing simple PHP arrays. cakephp Class DebugContext Class DebugContext =================== Context tracking for Debugger::exportVar() This class is used by Debugger to track element depth, and prevent cyclic references from being traversed multiple times. **Namespace:** [Cake\Error\Debug](namespace-cake.error.debug) Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [getReferenceId()](#getReferenceId()) public Get the reference ID for an object. * ##### [hasReference()](#hasReference()) public Check whether an object has been seen before. * ##### [remainingDepth()](#remainingDepth()) public Get the remaining depth levels * ##### [withAddedDepth()](#withAddedDepth()) public Return a clone with increased depth. Method Detail ------------- ### \_\_construct() public ``` __construct(int $maxDepth) ``` Constructor #### Parameters `int` $maxDepth The desired depth of dump output. ### getReferenceId() public ``` getReferenceId(object $object): int ``` Get the reference ID for an object. If this object does not exist in the reference storage, it will be added and the id will be returned. #### Parameters `object` $object The object to get a reference for. #### Returns `int` ### hasReference() public ``` hasReference(object $object): bool ``` Check whether an object has been seen before. #### Parameters `object` $object The object to get a reference for. #### Returns `bool` ### remainingDepth() public ``` remainingDepth(): int ``` Get the remaining depth levels #### Returns `int` ### withAddedDepth() public ``` withAddedDepth(): static ``` Return a clone with increased depth. #### Returns `static` cakephp Namespace Exception Namespace Exception =================== ### Classes * ##### [SocketException](class-cake.network.exception.socketexception) Exception class for Socket. This exception will be thrown from Socket, Email, HttpSocket SmtpTransport, MailTransport and HttpResponse when it encounters an error. cakephp Namespace Translate Namespace Translate =================== ### Interfaces * ##### [TranslateStrategyInterface](interface-cake.orm.behavior.translate.translatestrategyinterface) This interface describes the methods for translate behavior strategies. ### Classes * ##### [EavStrategy](class-cake.orm.behavior.translate.eavstrategy) This class 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. * ##### [ShadowTableStrategy](class-cake.orm.behavior.translate.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. ### Traits * ##### [TranslateStrategyTrait](trait-cake.orm.behavior.translate.translatestrategytrait) Contains common code needed by TranslateBehavior strategy classes. * ##### [TranslateTrait](trait-cake.orm.behavior.translate.translatetrait) Contains a translation method aimed to help managing multiple translations for an entity. cakephp Class DebugTransport Class DebugTransport ===================== Debug Transport class, useful for emulating the email sending process and inspecting the resultant email message before actually sending it during development **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. * ##### [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 ### 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 Class I18nExtractCommand Class I18nExtractCommand ========================= Language string extractor **Namespace:** [Cake\Command](namespace-cake.command) Constants --------- * `int` **CODE\_ERROR** ``` 1 ``` Default error code * `int` **CODE\_SUCCESS** ``` 0 ``` Default success code Property Summary ---------------- * [$\_countMarkerError](#%24_countMarkerError) protected `int` Count number of marker errors found * [$\_exclude](#%24_exclude) protected `array<string>` An array of directories to exclude. * [$\_extractCore](#%24_extractCore) protected `bool` Holds whether this call should extract the CakePHP Lib messages * [$\_file](#%24_file) protected `string` Current file being processed * [$\_files](#%24_files) protected `array<string>` Files from where to extract * [$\_markerError](#%24_markerError) protected `bool` Displays marker error(s) if true * [$\_merge](#%24_merge) protected `bool` Merge all domain strings into the default.pot file * [$\_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. * [$\_output](#%24_output) protected `string` Destination path * [$\_paths](#%24_paths) protected `array<string>` Paths to use when looking for strings * [$\_storage](#%24_storage) protected `array<string, mixed>` Contains all content waiting to be written * [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance * [$\_tokens](#%24_tokens) protected `array` Extracted tokens * [$\_translations](#%24_translations) protected `array<string, mixed>` Extracted strings indexed by domain. * [$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 * ##### [\_addTranslation()](#_addTranslation()) protected Add a translation to the internal translations property * ##### [\_buildFiles()](#_buildFiles()) protected Build the translate template file contents out of obtained strings * ##### [\_extract()](#_extract()) protected Extract text * ##### [\_extractTokens()](#_extractTokens()) protected Extract tokens out of all files to be processed * ##### [\_formatString()](#_formatString()) protected Format a string to be added as a translatable string * ##### [\_getPaths()](#_getPaths()) protected Method to interact with the user and get path selections. * ##### [\_getStrings()](#_getStrings()) protected Get the strings from the position forward * ##### [\_isExtractingApp()](#_isExtractingApp()) protected Returns whether this execution is meant to extract string only from directories in folder represented by the APP constant, i.e. this task is extracting strings from same application. * ##### [\_isPathUsable()](#_isPathUsable()) protected Checks whether a given path is usable for writing. * ##### [\_markerError()](#_markerError()) protected Indicate an invalid marker on a processed file * ##### [\_parse()](#_parse()) protected Parse tokens * ##### [\_searchFiles()](#_searchFiles()) protected Search files that may contain translatable strings * ##### [\_setModelClass()](#_setModelClass()) protected Set the modelClass property based on conventions. * ##### [\_store()](#_store()) protected Prepare a file to be stored * ##### [\_writeFiles()](#_writeFiles()) protected Write the files that need to be stored * ##### [\_writeHeader()](#_writeHeader()) protected Build the translation template header * ##### [abort()](#abort()) public Halt the the current process with a StopException. * ##### [buildOptionParser()](#buildOptionParser()) public Gets the option parser instance and configures it. * ##### [checkUnchanged()](#checkUnchanged()) protected Check whether the old and new output are the same, thus unchanged * ##### [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. ### \_addTranslation() protected ``` _addTranslation(string $domain, string $msgid, array $details = []): void ``` Add a translation to the internal translations property Takes care of duplicate translations #### Parameters `string` $domain The domain `string` $msgid The message string `array` $details optional Context and plural form if any, file and line references #### Returns `void` ### \_buildFiles() protected ``` _buildFiles(Cake\Console\Arguments $args): void ``` Build the translate template file contents out of obtained strings #### Parameters `Cake\Console\Arguments` $args Console arguments #### Returns `void` ### \_extract() protected ``` _extract(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void ``` Extract text #### Parameters `Cake\Console\Arguments` $args The Arguments instance `Cake\Console\ConsoleIo` $io The io instance #### Returns `void` ### \_extractTokens() protected ``` _extractTokens(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void ``` Extract tokens out of all files to be processed #### Parameters `Cake\Console\Arguments` $args The io instance `Cake\Console\ConsoleIo` $io The io instance #### Returns `void` ### \_formatString() protected ``` _formatString(string $string): string ``` Format a string to be added as a translatable string #### Parameters `string` $string String to format #### Returns `string` ### \_getPaths() protected ``` _getPaths(Cake\Console\ConsoleIo $io): void ``` Method to interact with the user and get path selections. #### Parameters `Cake\Console\ConsoleIo` $io The io instance. #### Returns `void` ### \_getStrings() protected ``` _getStrings(int $position, int $target): array ``` Get the strings from the position forward #### Parameters `int` $position Actual position on tokens array `int` $target Number of strings to extract #### Returns `array` ### \_isExtractingApp() protected ``` _isExtractingApp(): bool ``` Returns whether this execution is meant to extract string only from directories in folder represented by the APP constant, i.e. this task is extracting strings from same application. #### Returns `bool` ### \_isPathUsable() protected ``` _isPathUsable(string $path): bool ``` Checks whether a given path is usable for writing. #### Parameters `string` $path Path to folder #### Returns `bool` ### \_markerError() protected ``` _markerError(Cake\Console\ConsoleIo $io, string $file, int $line, string $marker, int $count): void ``` Indicate an invalid marker on a processed file #### Parameters `Cake\Console\ConsoleIo` $io The io instance. `string` $file File where invalid marker resides `int` $line Line number `string` $marker Marker found `int` $count Count #### Returns `void` ### \_parse() protected ``` _parse(Cake\Console\ConsoleIo $io, string $functionName, array $map): void ``` Parse tokens #### Parameters `Cake\Console\ConsoleIo` $io The io instance `string` $functionName Function name that indicates translatable string (e.g: '\_\_') `array` $map Array containing what variables it will find (e.g: domain, singular, plural) #### Returns `void` ### \_searchFiles() protected ``` _searchFiles(): void ``` Search files that may contain translatable strings #### 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` ### \_store() protected ``` _store(string $domain, string $header, string $sentence): void ``` Prepare a file to be stored #### Parameters `string` $domain The domain `string` $header The header content. `string` $sentence The sentence to store. #### Returns `void` ### \_writeFiles() protected ``` _writeFiles(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void ``` Write the files that need to be stored #### Parameters `Cake\Console\Arguments` $args The command arguments. `Cake\Console\ConsoleIo` $io The console io #### Returns `void` ### \_writeHeader() protected ``` _writeHeader(string $domain): string ``` Build the translation template header #### Parameters `string` $domain Domain #### Returns `string` ### 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 configure #### Returns `Cake\Console\ConsoleOptionParser` ### checkUnchanged() protected ``` checkUnchanged(string $oldFile, int $headerLength, string $newFileContent): bool ``` Check whether the old and new output are the same, thus unchanged Compares the sha1 hashes of the old and new file without header. #### Parameters `string` $oldFile The existing file. `int` $headerLength The length of the file header in bytes. `string` $newFileContent The content of the new file. #### Returns `bool` ### 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 --------------- ### $\_countMarkerError protected Count number of marker errors found #### Type `int` ### $\_exclude protected An array of directories to exclude. #### Type `array<string>` ### $\_extractCore protected Holds whether this call should extract the CakePHP Lib messages #### Type `bool` ### $\_file protected Current file being processed #### Type `string` ### $\_files protected Files from where to extract #### Type `array<string>` ### $\_markerError protected Displays marker error(s) if true #### Type `bool` ### $\_merge protected Merge all domain strings into the default.pot file #### Type `bool` ### $\_modelFactories protected A list of overridden model factory functions. #### Type `array<callableCake\Datasource\Locator\LocatorInterface>` ### $\_modelType protected The model type to use. #### Type `string` ### $\_output protected Destination path #### Type `string` ### $\_paths protected Paths to use when looking for strings #### Type `array<string>` ### $\_storage protected Contains all content waiting to be written #### Type `array<string, mixed>` ### $\_tableLocator protected Table locator instance #### Type `Cake\ORM\Locator\LocatorInterface|null` ### $\_tokens protected Extracted tokens #### Type `array` ### $\_translations protected Extracted strings indexed by domain. #### Type `array<string, mixed>` ### $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 CommandScanner Class CommandScanner ===================== Used by CommandCollection and CommandTask to scan the filesystem for command classes. **Namespace:** [Cake\Console](namespace-cake.console) Method Summary -------------- * ##### [scanApp()](#scanApp()) public Scan the application for shells & commands. * ##### [scanCore()](#scanCore()) public Scan CakePHP internals for shells & commands. * ##### [scanDir()](#scanDir()) protected Scan a directory for .php files and return the class names that should be within them. * ##### [scanPlugin()](#scanPlugin()) public Scan the named plugin for shells and commands Method Detail ------------- ### scanApp() public ``` scanApp(): array ``` Scan the application for shells & commands. #### Returns `array` ### scanCore() public ``` scanCore(): array ``` Scan CakePHP internals for shells & commands. #### Returns `array` ### scanDir() protected ``` scanDir(string $path, string $namespace, string $prefix, array<string> $hide): array ``` Scan a directory for .php files and return the class names that should be within them. #### Parameters `string` $path The directory to read. `string` $namespace The namespace the shells live in. `string` $prefix The prefix to apply to commands for their full name. `array<string>` $hide A list of command names to hide as they are internal commands. #### Returns `array` ### scanPlugin() public ``` scanPlugin(string $plugin): array ``` Scan the named plugin for shells and commands #### Parameters `string` $plugin The named plugin. #### Returns `array` cakephp Class Schema Class Schema ============= Contains the schema information for Form instances. **Namespace:** [Cake\Form](namespace-cake.form) Property Summary ---------------- * [$\_fieldDefaults](#%24_fieldDefaults) protected `array<string, mixed>` The default values for fields. * [$\_fields](#%24_fields) protected `array<string, array<string, mixed>>` The fields in this schema. Method Summary -------------- * ##### [\_\_debugInfo()](#__debugInfo()) public Get the printable version of this object * ##### [addField()](#addField()) public Adds a field to the schema. * ##### [addFields()](#addFields()) public Add multiple fields to the schema. * ##### [field()](#field()) public Get the attributes for a given field. * ##### [fieldType()](#fieldType()) public Get the type of the named field. * ##### [fields()](#fields()) public Get the list of fields in the schema. * ##### [removeField()](#removeField()) public Removes a field to the schema. Method Detail ------------- ### \_\_debugInfo() public ``` __debugInfo(): array<string, mixed> ``` Get the printable version of this object #### Returns `array<string, mixed>` ### addField() public ``` addField(string $name, array<string, mixed>|string $attrs): $this ``` Adds a field to the schema. #### Parameters `string` $name The field name. `array<string, mixed>|string` $attrs The attributes for the field, or the type as a string. #### Returns `$this` ### addFields() public ``` addFields(array<string, array<string, mixed>|string> $fields): $this ``` Add multiple fields to the schema. #### Parameters `array<string, array<string, mixed>|string>` $fields The fields to add. #### Returns `$this` ### field() public ``` field(string $name): array<string, mixed>|null ``` Get the attributes for a given field. #### Parameters `string` $name The field name. #### Returns `array<string, mixed>|null` ### fieldType() public ``` fieldType(string $name): string|null ``` Get the type of the named field. #### Parameters `string` $name The name of the field. #### Returns `string|null` ### fields() public ``` fields(): array<string> ``` Get the list of fields in the schema. #### Returns `array<string>` ### removeField() public ``` removeField(string $name): $this ``` Removes a field to the schema. #### Parameters `string` $name The field to remove. #### Returns `$this` Property Detail --------------- ### $\_fieldDefaults protected The default values for fields. #### Type `array<string, mixed>` ### $\_fields protected The fields in this schema. #### Type `array<string, array<string, mixed>>` cakephp Class BaseType Class BaseType =============== Base type class. **Abstract** **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 Casts given value from a PHP type to one acceptable by a database. * ##### [toPHP()](#toPHP()) public Casts given value from a database type to a PHP equivalent. * ##### [toStatement()](#toStatement()) public Casts given value to its Statement equivalent. 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): mixed ``` Casts given value from a PHP type to one acceptable by a database. #### Parameters `mixed` $value Value to be converted to a database equivalent. `Cake\Database\DriverInterface` $driver Object from which database preferences and configuration will be extracted. #### Returns `mixed` ### toPHP() public ``` toPHP(mixed $value, Cake\Database\DriverInterface $driver): mixed ``` 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 `mixed` ### toStatement() public ``` toStatement(mixed $value, Cake\Database\DriverInterface $driver): mixed ``` Casts given value to its Statement equivalent. #### Parameters `mixed` $value `Cake\Database\DriverInterface` $driver #### Returns `mixed` Property Detail --------------- ### $\_name protected Identifier name for this type #### Type `string|null` cakephp Class Query Class Query ============ This class represents a Relational database SQL Query. A query can be of different types like select, update, insert and delete. Exposes the methods for dynamically constructing each query part, execute it and transform it to a specific SQL dialect. **Namespace:** [Cake\Database](namespace-cake.database) Constants --------- * `string` **JOIN\_TYPE\_INNER** ``` 'INNER' ``` * `string` **JOIN\_TYPE\_LEFT** ``` 'LEFT' ``` * `string` **JOIN\_TYPE\_RIGHT** ``` 'RIGHT' ``` Property Summary ---------------- * [$\_connection](#%24_connection) protected `Cake\Database\Connection` Connection instance to be used to execute this query. * [$\_deleteParts](#%24_deleteParts) protected deprecated `array<string>` The list of query clauses to traverse for generating a DELETE statement * [$\_dirty](#%24_dirty) protected `bool` Indicates whether internal state of this query was changed, this is used to discard internal cached objects such as the transformed query or the reference to the executed statement. * [$\_functionsBuilder](#%24_functionsBuilder) protected `Cake\Database\FunctionsBuilder|null` Instance of functions builder object used for generating arbitrary SQL functions. * [$\_insertParts](#%24_insertParts) protected deprecated `array<string>` The list of query clauses to traverse for generating an INSERT statement * [$\_iterator](#%24_iterator) protected `Cake\Database\StatementInterface|null` Statement object resulting from executing this query. * [$\_parts](#%24_parts) protected `array<string, mixed>` List of SQL parts that will be used to build this query. * [$\_resultDecorators](#%24_resultDecorators) protected `array<callable>` A list of callback functions to be called to alter each row from resulting statement upon retrieval. Each one of the callback function will receive the row array as first argument. * [$\_selectParts](#%24_selectParts) protected deprecated `array<string>` The list of query clauses to traverse for generating a SELECT statement * [$\_selectTypeMap](#%24_selectTypeMap) protected `Cake\Database\TypeMap|null` The Type map for fields in the select clause * [$\_type](#%24_type) protected `string` Type of this query (select, insert, update, delete). * [$\_typeMap](#%24_typeMap) protected `Cake\Database\TypeMap|null` * [$\_updateParts](#%24_updateParts) protected deprecated `array<string>` The list of query clauses to traverse for generating an UPDATE statement * [$\_useBufferedResults](#%24_useBufferedResults) protected `bool` Boolean for tracking whether buffered results are enabled. * [$\_valueBinder](#%24_valueBinder) protected `Cake\Database\ValueBinder|null` The object responsible for generating query placeholders and temporarily store values associated to each of those. * [$typeCastEnabled](#%24typeCastEnabled) protected `bool` Tracking flag to disable casting Method Summary -------------- * ##### [\_\_clone()](#__clone()) public Handles clearing iterator and cloning all expressions and value binders. * ##### [\_\_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 Returns string representation of this query (complete SQL statement). * ##### [\_conjugate()](#_conjugate()) protected Helper function used to build conditions by composing QueryExpression objects. * ##### [\_decorateStatement()](#_decorateStatement()) protected Auxiliary function used to wrap the original statement from the driver with any registered callbacks. * ##### [\_dirty()](#_dirty()) protected Marks a query as dirty, removing any preprocessed information from in memory caching. * ##### [\_expressionsVisitor()](#_expressionsVisitor()) protected Query parts traversal method used by traverseExpressions() * ##### [\_makeJoin()](#_makeJoin()) protected Returns an array that can be passed to the join method describing a single join clause * ##### [andHaving()](#andHaving()) public Connects any previously defined set of conditions to the provided list using the AND operator in the HAVING clause. This method operates in exactly the same way as the method `andWhere()` does. Please refer to its documentation for an insight on how to using each parameter. * ##### [andWhere()](#andWhere()) public Connects any previously defined set of conditions to the provided list using the AND operator. This function accepts the conditions list in the same format as the method `where` does, hence you can use arrays, expression objects callback functions or strings. * ##### [bind()](#bind()) public Associates a query placeholder to a value and a type. * ##### [clause()](#clause()) public Returns any data that was stored in the specified clause. This is useful for modifying any internal part of the query and it is used by the SQL dialects to transform the query accordingly before it is executed. The valid clauses that can be retrieved are: delete, update, set, insert, values, select, distinct, from, join, set, where, group, having, order, limit, offset and union. * ##### [decorateResults()](#decorateResults()) public Registers a callback to be executed for each result that is fetched from the result set, the callback function will receive as first parameter an array with the raw data from the database for every row that is fetched and must return the row with any possible modifications. * ##### [delete()](#delete()) public Create a delete query. * ##### [disableBufferedResults()](#disableBufferedResults()) public Disables buffered results. * ##### [disableResultsCasting()](#disableResultsCasting()) public Disables result casting. * ##### [distinct()](#distinct()) public Adds a `DISTINCT` clause to the query to remove duplicates from the result set. This clause can only be used for select statements. * ##### [enableBufferedResults()](#enableBufferedResults()) public Enables/Disables buffered results. * ##### [enableResultsCasting()](#enableResultsCasting()) public Enables result casting. * ##### [epilog()](#epilog()) public A string or expression that will be appended to the generated query * ##### [execute()](#execute()) public Compiles the SQL representation of this query and executes it using the configured connection object. Returns the resulting statement object. * ##### [expr()](#expr()) public Returns a new QueryExpression object. This is a handy function when building complex queries using a fluent interface. You can also override this function in subclasses to use a more specialized QueryExpression class if required. * ##### [from()](#from()) public Adds a single or multiple tables to be used in the FROM clause for this query. Tables can be passed as an array of strings, array of expression objects, a single expression or a single string. * ##### [func()](#func()) public Returns an instance of a functions builder object that can be used for generating arbitrary SQL functions. * ##### [getConnection()](#getConnection()) public Gets the connection instance to be used for executing and transforming this query. * ##### [getDefaultTypes()](#getDefaultTypes()) public Gets default types of current type map. * ##### [getIterator()](#getIterator()) public Executes this query and returns a results iterator. This function is required for implementing the IteratorAggregate interface and allows the query to be iterated without having to call execute() manually, thus making it look like a result set instead of the query itself. * ##### [getSelectTypeMap()](#getSelectTypeMap()) public Gets the TypeMap class where the types for each of the fields in the select clause are stored. * ##### [getTypeMap()](#getTypeMap()) public Returns the existing type map. * ##### [getValueBinder()](#getValueBinder()) public Returns the currently used ValueBinder instance. * ##### [group()](#group()) public Adds a single or multiple fields to be used in the GROUP BY clause for this query. Fields can be passed as an array of strings, array of expression objects, a single expression or a single string. * ##### [having()](#having()) public Adds a condition or set of conditions to be used in the `HAVING` clause for this query. This method operates in exactly the same way as the method `where()` does. Please refer to its documentation for an insight on how to using each parameter. * ##### [identifier()](#identifier()) public Creates an expression that refers to an identifier. Identifiers are used to refer to field names and allow the SQL compiler to apply quotes or escape the identifier. * ##### [innerJoin()](#innerJoin()) public Adds a single `INNER JOIN` clause to the query. * ##### [insert()](#insert()) public Create an insert query. * ##### [into()](#into()) public Set the table name for insert queries. * ##### [isBufferedResultsEnabled()](#isBufferedResultsEnabled()) public Returns whether buffered results are enabled/disabled. * ##### [isResultsCastingEnabled()](#isResultsCastingEnabled()) public Returns whether result casting is enabled/disabled. * ##### [join()](#join()) public Adds a single or multiple tables to be used as JOIN clauses to this query. Tables can be passed as an array of strings, an array describing the join parts, an array with multiple join descriptions, or a single string. * ##### [leftJoin()](#leftJoin()) public Adds a single `LEFT JOIN` clause to the query. * ##### [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. * ##### [modifier()](#modifier()) public Adds a single or multiple `SELECT` modifiers to be used in the `SELECT`. * ##### [newExpr()](#newExpr()) public Returns a new QueryExpression object. This is a handy function when building complex queries using a fluent interface. You can also override this function in subclasses to use a more specialized QueryExpression class if required. * ##### [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. * ##### [orderAsc()](#orderAsc()) public Add an ORDER BY clause with an ASC direction. * ##### [orderDesc()](#orderDesc()) public Add an ORDER BY clause with a DESC direction. * ##### [page()](#page()) public Set the page of results you want. * ##### [removeJoin()](#removeJoin()) public Remove a join if it has been defined. * ##### [rightJoin()](#rightJoin()) public Adds a single `RIGHT JOIN` clause to the query. * ##### [rowCountAndClose()](#rowCountAndClose()) public Executes the SQL of this query and immediately closes the statement before returning the row count of records changed. * ##### [select()](#select()) public Adds new fields to be returned by a `SELECT` statement when this query is executed. Fields can be passed as an array of strings, array of expression objects, a single expression or a single string. * ##### [set()](#set()) public Set one or many fields to update. * ##### [setConnection()](#setConnection()) public Sets the connection instance to be used for executing and transforming this query. * ##### [setDefaultTypes()](#setDefaultTypes()) public Overwrite the default type mappings for fields in the implementing object. * ##### [setSelectTypeMap()](#setSelectTypeMap()) public Sets the TypeMap class where the types for each of the fields in the select clause are stored. * ##### [setTypeMap()](#setTypeMap()) public Creates a new TypeMap if $typeMap is an array, otherwise exchanges it for the given one. * ##### [setValueBinder()](#setValueBinder()) public Overwrite the current value binder * ##### [sql()](#sql()) public Returns the SQL representation of this object. * ##### [traverse()](#traverse()) public Will iterate over every specified part. Traversing functions can aggregate results using variables in the closure or instance variables. This function is commonly used as a way for traversing all query parts that are going to be used for constructing a query. * ##### [traverseExpressions()](#traverseExpressions()) public This function works similar to the traverse() function, with the difference that it does a full depth traversal of the entire expression tree. This will execute the provided callback function for each ExpressionInterface object that is stored inside this query at any nesting depth in any part of the query. * ##### [traverseParts()](#traverseParts()) public Will iterate over the provided parts. * ##### [type()](#type()) public Returns the type of this query (select, insert, update, delete) * ##### [union()](#union()) public Adds a complete query to be used in conjunction with an UNION operator with this query. This is used to combine the result set of this query with the one that will be returned by the passed query. You can add as many queries as you required by calling multiple times this method with different queries. * ##### [unionAll()](#unionAll()) public Adds a complete query to be used in conjunction with the UNION ALL operator with this query. This is used to combine the result set of this query with the one that will be returned by the passed query. You can add as many queries as you required by calling multiple times this method with different queries. * ##### [update()](#update()) public Create an update query. * ##### [values()](#values()) public Set the values for an insert 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. * ##### [whereInList()](#whereInList()) public Adds an IN condition or set of conditions to be used in the WHERE clause for this query. * ##### [whereNotInList()](#whereNotInList()) public Adds a NOT IN condition or set of conditions to be used in the WHERE clause for this query. * ##### [whereNotInListOrNull()](#whereNotInListOrNull()) public Adds a NOT IN condition or set of conditions to be used in the WHERE clause for this query. This also allows the field to be null with a IS NULL condition since the null value would cause the NOT IN condition to always fail. * ##### [whereNotNull()](#whereNotNull()) public Convenience method that adds a NOT NULL condition to the query * ##### [whereNull()](#whereNull()) public Convenience method that adds a IS NULL condition to the query * ##### [window()](#window()) public Adds a named window expression. * ##### [with()](#with()) public Adds a new common table expression (CTE) to the query. Method Detail ------------- ### \_\_clone() public ``` __clone(): void ``` Handles clearing iterator and cloning all expressions and value binders. #### Returns `void` ### \_\_construct() public ``` __construct(Cake\Database\Connection $connection) ``` Constructor. #### Parameters `Cake\Database\Connection` $connection The connection object to be used for transforming and executing this query ### \_\_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 ``` Returns string representation of this query (complete SQL statement). #### Returns `string` ### \_conjugate() protected ``` _conjugate(string $part, Cake\Database\ExpressionInterfaceClosure|array|string|null $append, string $conjunction, array<string, string> $types): void ``` Helper function used to build conditions by composing QueryExpression objects. #### Parameters `string` $part Name of the query part to append the new part to `Cake\Database\ExpressionInterfaceClosure|array|string|null` $append Expression or builder function to append. to append. `string` $conjunction type of conjunction to be used to operate part `array<string, string>` $types Associative array of type names used to bind values to query #### Returns `void` ### \_decorateStatement() protected ``` _decorateStatement(Cake\Database\StatementInterface $statement): Cake\Database\Statement\CallbackStatementCake\Database\StatementInterface ``` Auxiliary function used to wrap the original statement from the driver with any registered callbacks. #### Parameters `Cake\Database\StatementInterface` $statement to be decorated #### Returns `Cake\Database\Statement\CallbackStatementCake\Database\StatementInterface` ### \_dirty() protected ``` _dirty(): void ``` Marks a query as dirty, removing any preprocessed information from in memory caching. #### Returns `void` ### \_expressionsVisitor() protected ``` _expressionsVisitor(Cake\Database\ExpressionInterface|arrayCake\Database\ExpressionInterface> $expression, Closure $callback): void ``` Query parts traversal method used by traverseExpressions() #### Parameters `Cake\Database\ExpressionInterface|arrayCake\Database\ExpressionInterface>` $expression Query expression or array of expressions. `Closure` $callback The callback to be executed for each ExpressionInterface found inside this query. #### Returns `void` ### \_makeJoin() protected ``` _makeJoin(array<string, mixed>|string $table, Cake\Database\ExpressionInterface|array|string $conditions, string $type): array ``` Returns an array that can be passed to the join method describing a single join clause #### Parameters `array<string, mixed>|string` $table The table to join with `Cake\Database\ExpressionInterface|array|string` $conditions The conditions to use for joining. `string` $type the join type to use #### Returns `array` ### andHaving() public ``` andHaving(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): $this ``` Connects any previously defined set of conditions to the provided list using the AND operator in the HAVING clause. This method operates in exactly the same way as the method `andWhere()` does. Please refer to its documentation for an insight on how to using each parameter. Having fields are not suitable for use with user supplied data as they are not sanitized by the query builder. #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions The AND conditions for HAVING. `array<string, string>` $types optional Associative array of type names used to bind values to query #### Returns `$this` #### See Also \Cake\Database\Query::andWhere() ### andWhere() public ``` andWhere(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): $this ``` Connects any previously defined set of conditions to the provided list using the AND operator. This function accepts the conditions list in the same format as the method `where` does, hence you can use arrays, expression objects callback functions or strings. It is important to notice that when calling this function, any previous set of conditions defined for this query will be treated as a single argument for the AND operator. This function will not only operate the most recently defined condition, but all the conditions as a whole. When using an array for defining conditions, creating constraints form each array entry will use the same logic as with the `where()` function. This means that each array entry will be joined to the other using the AND operator, unless you nest the conditions in the array using other operator. ### Examples: ``` $query->where(['title' => 'Hello World')->andWhere(['author_id' => 1]); ``` Will produce: `WHERE title = 'Hello World' AND author_id = 1` ``` $query ->where(['OR' => ['published' => false, 'published is NULL']]) ->andWhere(['author_id' => 1, 'comments_count >' => 10]) ``` Produces: `WHERE (published = 0 OR published IS NULL) AND author_id = 1 AND comments_count > 10` ``` $query ->where(['title' => 'Foo']) ->andWhere(function ($exp, $query) { return $exp ->or(['author_id' => 1]) ->add(['author_id' => 2]); }); ``` Generates the following conditions: `WHERE (title = 'Foo') AND (author_id = 1 OR author_id = 2)` #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions The conditions to add with AND. `array<string, string>` $types optional Associative array of type names used to bind values to query #### Returns `$this` #### See Also \Cake\Database\Query::where() \Cake\Database\TypeFactory ### bind() public ``` bind(string|int $param, mixed $value, string|int|null $type = null): $this ``` Associates a query placeholder to a value and a type. ``` $query->bind(':id', 1, 'integer'); ``` #### 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 `$this` ### clause() public ``` clause(string $name): mixed ``` Returns any data that was stored in the specified clause. This is useful for modifying any internal part of the query and it is used by the SQL dialects to transform the query accordingly before it is executed. The valid clauses that can be retrieved are: delete, update, set, insert, values, select, distinct, from, join, set, where, group, having, order, limit, offset and union. The return value for each of those parts may vary. Some clauses use QueryExpression to internally store their state, some use arrays and others may use booleans or integers. This is summary of the return types for each clause. * update: string The name of the table to update * set: QueryExpression * insert: array, will return an array containing the table + columns. * values: ValuesExpression * select: array, will return empty array when no fields are set * distinct: boolean * from: array of tables * join: array * set: array * where: QueryExpression, returns null when not set * group: array * having: QueryExpression, returns null when not set * order: OrderByExpression, returns null when not set * limit: integer or QueryExpression, null when not set * offset: integer or QueryExpression, null when not set * union: array #### Parameters `string` $name name of the clause to be returned #### Returns `mixed` #### Throws `InvalidArgumentException` When the named clause does not exist. ### decorateResults() public ``` decorateResults(callable|null $callback, bool $overwrite = false): $this ``` Registers a callback to be executed for each result that is fetched from the result set, the callback function will receive as first parameter an array with the raw data from the database for every row that is fetched and must return the row with any possible modifications. Callbacks will be executed lazily, if only 3 rows are fetched for database it will called 3 times, event though there might be more rows to be fetched in the cursor. Callbacks are stacked in the order they are registered, if you wish to reset the stack the call this function with the second parameter set to true. If you wish to remove all decorators from the stack, set the first parameter to null and the second to true. ### Example ``` $query->decorateResults(function ($row) { $row['order_total'] = $row['subtotal'] + ($row['subtotal'] * $row['tax']); return $row; }); ``` #### Parameters `callable|null` $callback The callback to invoke when results are fetched. `bool` $overwrite optional Whether this should append or replace all existing decorators. #### Returns `$this` ### delete() public ``` delete(string|null $table = null): $this ``` Create a delete query. Can be combined with from(), where() and other methods to create delete queries with specific conditions. #### Parameters `string|null` $table optional The table to use when deleting. #### Returns `$this` ### disableBufferedResults() public ``` disableBufferedResults(): $this ``` Disables buffered results. Disabling buffering will consume less memory as fetched results are not remembered for future iterations. #### Returns `$this` ### disableResultsCasting() public ``` disableResultsCasting(): $this ``` Disables result casting. When disabled, the fields will be returned as received from the database driver (which in most environments means they are being returned as strings), which can improve performance with larger datasets. #### Returns `$this` ### distinct() public ``` distinct(Cake\Database\ExpressionInterface|array|string|bool $on = [], bool $overwrite = false): $this ``` Adds a `DISTINCT` clause to the query to remove duplicates from the result set. This clause can only be used for select statements. If you wish to filter duplicates based of those rows sharing a particular field or set of fields, you may pass an array of fields to filter on. Beware that this option might not be fully supported in all database systems. ### Examples: ``` // Filters products with the same name and city $query->select(['name', 'city'])->from('products')->distinct(); // Filters products in the same city $query->distinct(['city']); $query->distinct('city'); // Filter products with the same name $query->distinct(['name'], true); $query->distinct('name', true); ``` #### Parameters `Cake\Database\ExpressionInterface|array|string|bool` $on optional Enable/disable distinct class or list of fields to be filtered on `bool` $overwrite optional whether to reset fields with passed list or not #### Returns `$this` ### enableBufferedResults() public ``` enableBufferedResults(bool $enable = true): $this ``` Enables/Disables buffered results. When enabled the results returned by this Query will be buffered. This enables you to iterate a result set multiple times, or both cache and iterate it. When disabled it will consume less memory as fetched results are not remembered for future iterations. #### Parameters `bool` $enable optional Whether to enable buffering #### Returns `$this` ### enableResultsCasting() public ``` enableResultsCasting(): $this ``` Enables result casting. When enabled, the fields in the results returned by this Query will be cast to their corresponding PHP data type. #### Returns `$this` ### epilog() public ``` epilog(Cake\Database\ExpressionInterface|string|null $expression = null): $this ``` A string or expression that will be appended to the generated query ### Examples: ``` $query->select('id')->where(['author_id' => 1])->epilog('FOR UPDATE'); $query ->insert('articles', ['title']) ->values(['author_id' => 1]) ->epilog('RETURNING id'); ``` Epliog content is raw SQL and not suitable for use with user supplied data. #### Parameters `Cake\Database\ExpressionInterface|string|null` $expression optional The expression to be appended #### Returns `$this` ### execute() public ``` execute(): Cake\Database\StatementInterface ``` Compiles the SQL representation of this query and executes it using the configured connection object. Returns the resulting statement object. Executing a query internally executes several steps, the first one is letting the connection transform this object to fit its particular dialect, this might result in generating a different Query object that will be the one to actually be executed. Immediately after, literal values are passed to the connection so they are bound to the query in a safe way. Finally, the resulting statement is decorated with custom objects to execute callbacks for each row retrieved if necessary. Resulting statement is traversable, so it can be used in any loop as you would with an array. This method can be overridden in query subclasses to decorate behavior around query execution. #### Returns `Cake\Database\StatementInterface` ### expr() public ``` expr(Cake\Database\ExpressionInterface|array|string|null $rawExpression = null): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object. This is a handy function when building complex queries using a fluent interface. You can also override this function in subclasses to use a more specialized QueryExpression class if required. You can optionally pass a single raw SQL string or an array or expressions in any format accepted by \Cake\Database\Expression\QueryExpression: ``` $expression = $query->expr(); // Returns an empty expression object $expression = $query->expr('Table.column = Table2.column'); // Return a raw SQL expression ``` #### Parameters `Cake\Database\ExpressionInterface|array|string|null` $rawExpression optional A string, array or anything you want wrapped in an expression object #### Returns `Cake\Database\Expression\QueryExpression` ### from() public ``` from(array|string $tables = [], bool $overwrite = false): $this ``` Adds a single or multiple tables to be used in the FROM clause for this query. Tables 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 to alias tables using the value as the real field to be aliased. It is possible to alias strings, ExpressionInterface objects or even other Query objects. By default this function will append any passed argument to the list of tables to be selected from, unless the second argument is set to true. This method can be used for select, update and delete statements. ### Examples: ``` $query->from(['p' => 'posts']); // Produces FROM posts p $query->from('authors'); // Appends authors: FROM posts p, authors $query->from(['products'], true); // Resets the list: FROM products $query->from(['sub' => $countQuery]); // FROM (SELECT ...) sub ``` #### Parameters `array|string` $tables optional tables to be added to the list. This argument, can be passed as an array of strings, array of expression objects, or a single string. See the examples above for the valid call types. `bool` $overwrite optional whether to reset tables with passed list or not #### Returns `$this` ### func() public ``` func(): Cake\Database\FunctionsBuilder ``` Returns an instance of a functions builder object that can be used for generating arbitrary SQL functions. ### Example: ``` $query->func()->count('*'); $query->func()->dateDiff(['2012-01-05', '2012-01-02']) ``` #### Returns `Cake\Database\FunctionsBuilder` ### getConnection() public ``` getConnection(): Cake\Database\Connection ``` Gets the connection instance to be used for executing and transforming this query. #### Returns `Cake\Database\Connection` ### getDefaultTypes() public ``` getDefaultTypes(): array<int|string, string> ``` Gets default types of current type map. #### Returns `array<int|string, string>` ### getIterator() public ``` getIterator(): Cake\Database\StatementInterface ``` Executes this query and returns a results iterator. This function is required for implementing the IteratorAggregate interface and allows the query to be iterated without having to call execute() manually, thus making it look like a result set instead of the query itself. #### Returns `Cake\Database\StatementInterface` ### getSelectTypeMap() public ``` getSelectTypeMap(): Cake\Database\TypeMap ``` Gets the TypeMap class where the types for each of the fields in the select clause are stored. #### Returns `Cake\Database\TypeMap` ### getTypeMap() public ``` getTypeMap(): Cake\Database\TypeMap ``` Returns the existing type map. #### Returns `Cake\Database\TypeMap` ### getValueBinder() public ``` getValueBinder(): Cake\Database\ValueBinder ``` Returns the currently used ValueBinder instance. A ValueBinder is responsible for generating query placeholders and temporarily associate values to those placeholders so that they can be passed correctly to the statement object. #### Returns `Cake\Database\ValueBinder` ### group() public ``` group(Cake\Database\ExpressionInterface|array|string $fields, bool $overwrite = false): $this ``` Adds a single or multiple fields to be used in the GROUP BY clause for this query. Fields can be passed as an array of strings, array of expression objects, a single expression or a single string. By default this function will append any passed argument to the list of fields to be grouped, unless the second argument is set to true. ### Examples: ``` // Produces GROUP BY id, title $query->group(['id', 'title']); // Produces GROUP BY title $query->group('title'); ``` Group fields are not suitable for use with user supplied data as they are not sanitized by the query builder. #### Parameters `Cake\Database\ExpressionInterface|array|string` $fields fields to be added to the list `bool` $overwrite optional whether to reset fields with passed list or not #### Returns `$this` ### having() public ``` having(Cake\Database\ExpressionInterfaceClosure|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 `HAVING` clause for this query. This method operates in exactly the same way as the method `where()` does. Please refer to its documentation for an insight on how to using each parameter. Having fields are not suitable for use with user supplied data as they are not sanitized by the query builder. #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string|null` $conditions optional The having conditions. `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` #### See Also \Cake\Database\Query::where() ### identifier() public ``` identifier(string $identifier): Cake\Database\ExpressionInterface ``` Creates an expression that refers to an identifier. Identifiers are used to refer to field names and allow the SQL compiler to apply quotes or escape the identifier. The value is used as is, and you might be required to use aliases or include the table reference in the identifier. Do not use this method to inject SQL methods or logical statements. ### Example ``` $query->newExpr()->lte('count', $query->identifier('total')); ``` #### Parameters `string` $identifier The identifier for an expression #### Returns `Cake\Database\ExpressionInterface` ### innerJoin() public ``` innerJoin(array<string, mixed>|string $table, Cake\Database\ExpressionInterface|array|string $conditions = [], array<string, string> $types = []): $this ``` Adds a single `INNER JOIN` clause to the query. This is a shorthand method for building joins via `join()`. The arguments of this method are identical to the `leftJoin()` shorthand, please refer to that method's description for further details. #### Parameters `array<string, mixed>|string` $table The table to join with `Cake\Database\ExpressionInterface|array|string` $conditions optional The conditions to use for joining. `array<string, string>` $types optional a list of types associated to the conditions used for converting values to the corresponding database representation. #### Returns `$this` ### insert() public ``` insert(array $columns, array<int|string, string> $types = []): $this ``` Create an insert query. Note calling this method will reset any data previously set with Query::values(). #### Parameters `array` $columns The columns to insert into. `array<int|string, string>` $types optional A map between columns & their datatypes. #### Returns `$this` #### Throws `RuntimeException` When there are 0 columns. ### into() public ``` into(string $table): $this ``` Set the table name for insert queries. #### Parameters `string` $table The table name to insert into. #### Returns `$this` ### isBufferedResultsEnabled() public ``` isBufferedResultsEnabled(): bool ``` Returns whether buffered results are enabled/disabled. When enabled the results returned by this Query will be buffered. This enables you to iterate a result set multiple times, or both cache and iterate it. When disabled it will consume less memory as fetched results are not remembered for future iterations. #### Returns `bool` ### isResultsCastingEnabled() public ``` isResultsCastingEnabled(): bool ``` Returns whether result casting is enabled/disabled. When enabled, the fields in the results returned by this Query will be casted to their corresponding PHP data type. When disabled, the fields will be returned as received from the database driver (which in most environments means they are being returned as strings), which can improve performance with larger datasets. #### Returns `bool` ### join() public ``` join(array<string, mixed>|string $tables, array<string, string> $types = [], bool $overwrite = false): $this ``` Adds a single or multiple tables to be used as JOIN clauses to this query. Tables can be passed as an array of strings, an array describing the join parts, an array with multiple join descriptions, or a single string. By default this function will append any passed argument to the list of tables to be joined, unless the third argument is set to true. When no join type is specified an `INNER JOIN` is used by default: `$query->join(['authors'])` will produce `INNER JOIN authors ON 1 = 1` It is also possible to alias joins using the array key: `$query->join(['a' => 'authors'])` will produce `INNER JOIN authors a ON 1 = 1` A join can be fully described and aliased using the array notation: ``` $query->join([ 'a' => [ 'table' => 'authors', 'type' => 'LEFT', 'conditions' => 'a.id = b.author_id' ] ]); // Produces LEFT JOIN authors a ON a.id = b.author_id ``` You can even specify multiple joins in an array, including the full description: ``` $query->join([ 'a' => [ 'table' => 'authors', 'type' => 'LEFT', 'conditions' => 'a.id = b.author_id' ], 'p' => [ 'table' => 'publishers', 'type' => 'INNER', 'conditions' => 'p.id = b.publisher_id AND p.name = "Cake Software Foundation"' ] ]); // LEFT JOIN authors a ON a.id = b.author_id // INNER JOIN publishers p ON p.id = b.publisher_id AND p.name = "Cake Software Foundation" ``` ### Using conditions and types Conditions can be expressed, as in the examples above, using a string for comparing columns, or string with already quoted literal values. Additionally it is possible to use conditions expressed in arrays or expression objects. When using arrays for expressing conditions, it is often desirable to convert the literal values to the correct database representation. This is achieved using the second parameter of this function. ``` $query->join(['a' => [ 'table' => 'articles', 'conditions' => [ 'a.posted >=' => new DateTime('-3 days'), 'a.published' => true, 'a.author_id = authors.id' ] ]], ['a.posted' => 'datetime', 'a.published' => 'boolean']) ``` ### Overwriting joins When creating aliased joins using the array notation, you can override previous join definitions by using the same alias in consequent calls to this function or you can replace all previously defined joins with another list if the third parameter for this function is set to true. ``` $query->join(['alias' => 'table']); // joins table with as alias $query->join(['alias' => 'another_table']); // joins another_table with as alias $query->join(['something' => 'different_table'], [], true); // resets joins list ``` #### Parameters `array<string, mixed>|string` $tables list of tables to be joined in the query `array<string, string>` $types optional Associative array of type names used to bind values to query `bool` $overwrite optional whether to reset joins with passed list or not #### Returns `$this` #### See Also \Cake\Database\TypeFactory ### leftJoin() public ``` leftJoin(array<string, mixed>|string $table, Cake\Database\ExpressionInterface|array|string $conditions = [], array $types = []): $this ``` Adds a single `LEFT JOIN` clause to the query. This is a shorthand method for building joins via `join()`. The table name can be passed as a string, or as an array in case it needs to be aliased: ``` // LEFT JOIN authors ON authors.id = posts.author_id $query->leftJoin('authors', 'authors.id = posts.author_id'); // LEFT JOIN authors a ON a.id = posts.author_id $query->leftJoin(['a' => 'authors'], 'a.id = posts.author_id'); ``` Conditions can be passed as strings, arrays, or expression objects. When using arrays it is possible to combine them with the `$types` parameter in order to define how to convert the values: ``` $query->leftJoin(['a' => 'articles'], [ 'a.posted >=' => new DateTime('-3 days'), 'a.published' => true, 'a.author_id = authors.id' ], ['a.posted' => 'datetime', 'a.published' => 'boolean']); ``` See `join()` for further details on conditions and types. #### Parameters `array<string, mixed>|string` $table The table to join with `Cake\Database\ExpressionInterface|array|string` $conditions optional The conditions to use for joining. `array` $types optional a list of types associated to the conditions used for converting values to the corresponding database representation. #### Returns `$this` ### 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` ### modifier() public ``` modifier(Cake\Database\ExpressionInterface|array|string $modifiers, bool $overwrite = false): $this ``` Adds a single or multiple `SELECT` modifiers to be used in the `SELECT`. By default this function will append any passed argument to the list of modifiers to be applied, unless the second argument is set to true. ### Example: ``` // Ignore cache query in MySQL $query->select(['name', 'city'])->from('products')->modifier('SQL_NO_CACHE'); // It will produce the SQL: SELECT SQL_NO_CACHE name, city FROM products // Or with multiple modifiers $query->select(['name', 'city'])->from('products')->modifier(['HIGH_PRIORITY', 'SQL_NO_CACHE']); // It will produce the SQL: SELECT HIGH_PRIORITY SQL_NO_CACHE name, city FROM products ``` #### Parameters `Cake\Database\ExpressionInterface|array|string` $modifiers modifiers to be applied to the query `bool` $overwrite optional whether to reset order with field list or not #### Returns `$this` ### newExpr() public ``` newExpr(Cake\Database\ExpressionInterface|array|string|null $rawExpression = null): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object. This is a handy function when building complex queries using a fluent interface. You can also override this function in subclasses to use a more specialized QueryExpression class if required. You can optionally pass a single raw SQL string or an array or expressions in any format accepted by \Cake\Database\Expression\QueryExpression: ``` $expression = $query->expr(); // Returns an empty expression object $expression = $query->expr('Table.column = Table2.column'); // Return a raw SQL expression ``` #### Parameters `Cake\Database\ExpressionInterface|array|string|null` $rawExpression optional A string, array or anything you want wrapped in an expression object #### Returns `Cake\Database\Expression\QueryExpression` ### 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']); ``` and ``` $query->order(function ($exp, $query) { return [$exp->add(['id % 2 = 0']), 'title' => 'ASC']; }); ``` Will both become: `ORDER BY (id %2 = 0), title ASC` Order fields/directions are not sanitized by the query builder. You should use an allowed list of fields/directions when passing in user-supplied data to `order()`. 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` ### orderAsc() public ``` orderAsc(Cake\Database\ExpressionInterfaceClosure|string $field, bool $overwrite = false): $this ``` Add an ORDER BY clause with an ASC direction. This method allows you to set complex expressions as order conditions unlike order() Order fields are not suitable for use with user supplied data as they are not sanitized by the query builder. #### Parameters `Cake\Database\ExpressionInterfaceClosure|string` $field The field to order on. `bool` $overwrite optional Whether to reset the order clauses. #### Returns `$this` ### orderDesc() public ``` orderDesc(Cake\Database\ExpressionInterfaceClosure|string $field, bool $overwrite = false): $this ``` Add an ORDER BY clause with a DESC direction. This method allows you to set complex expressions as order conditions unlike order() Order fields are not suitable for use with user supplied data as they are not sanitized by the query builder. #### Parameters `Cake\Database\ExpressionInterfaceClosure|string` $field The field to order on. `bool` $overwrite optional Whether to reset the order clauses. #### 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. ### removeJoin() public ``` removeJoin(string $name): $this ``` Remove a join if it has been defined. Useful when you are redefining joins or want to re-order the join clauses. #### Parameters `string` $name The alias/name of the join to remove. #### Returns `$this` ### rightJoin() public ``` rightJoin(array<string, mixed>|string $table, Cake\Database\ExpressionInterface|array|string $conditions = [], array $types = []): $this ``` Adds a single `RIGHT JOIN` clause to the query. This is a shorthand method for building joins via `join()`. The arguments of this method are identical to the `leftJoin()` shorthand, please refer to that methods description for further details. #### Parameters `array<string, mixed>|string` $table The table to join with `Cake\Database\ExpressionInterface|array|string` $conditions optional The conditions to use for joining. `array` $types optional a list of types associated to the conditions used for converting values to the corresponding database representation. #### Returns `$this` ### rowCountAndClose() public ``` rowCountAndClose(): int ``` Executes the SQL of this query and immediately closes the statement before returning the row count of records changed. This method can be used with UPDATE and DELETE queries, but is not recommended for SELECT queries and is not used to count records. Example ------- ``` $rowCount = $query->update('articles') ->set(['published'=>true]) ->where(['published'=>false]) ->rowCountAndClose(); ``` The above example will change the published column to true for all false records, and return the number of records that were updated. #### Returns `int` ### select() public ``` select(Cake\Database\ExpressionInterface|callable|array|string $fields = [], bool $overwrite = false): $this ``` Adds new fields to be returned by a `SELECT` statement when this query is executed. 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 to alias fields using the value as the real field to be aliased. It is possible to alias strings, Expression objects or even other Query objects. If a callable function is passed, the returning array of the function will be used as the list of fields. 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->select(['id', 'title']); // Produces SELECT id, title $query->select(['author' => 'author_id']); // Appends author: SELECT id, title, author_id as author $query->select('id', true); // Resets the list: SELECT id $query->select(['total' => $countQuery]); // SELECT id, (SELECT ...) AS total $query->select(function ($query) { return ['article_id', 'total' => $query->count('*')]; }) ``` By default no fields are selected, if you have an instance of `Cake\ORM\Query` and try to append fields you should also call `Cake\ORM\Query::enableAutoFields()` to select the default fields from the table. #### Parameters `Cake\Database\ExpressionInterface|callable|array|string` $fields optional fields to be added to the list. `bool` $overwrite optional whether to reset fields with passed list or not #### Returns `$this` ### set() public ``` set(Cake\Database\Expression\QueryExpressionClosure|array|string $key, mixed $value = null, array<string, string>|string $types = []): $this ``` Set one or many fields to update. ### Examples Passing a string: ``` $query->update('articles')->set('title', 'The Title'); ``` Passing an array: ``` $query->update('articles')->set(['title' => 'The Title'], ['title' => 'string']); ``` Passing a callable: ``` $query->update('articles')->set(function ($exp) { return $exp->eq('title', 'The title', 'string'); }); ``` #### Parameters `Cake\Database\Expression\QueryExpressionClosure|array|string` $key The column name or array of keys * values to set. This can also be a QueryExpression containing a SQL fragment. It can also be a Closure, that is required to return an expression object. `mixed` $value optional The value to update $key to. Can be null if $key is an array or QueryExpression. When $key is an array, this parameter will be used as $types instead. `array<string, string>|string` $types optional The column types to treat data as. #### Returns `$this` ### setConnection() public ``` setConnection(Cake\Database\Connection $connection): $this ``` Sets the connection instance to be used for executing and transforming this query. #### Parameters `Cake\Database\Connection` $connection Connection instance #### 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() ### setSelectTypeMap() public ``` setSelectTypeMap(Cake\Database\TypeMap $typeMap): $this ``` Sets the TypeMap class where the types for each of the fields in the select clause are stored. #### Parameters `Cake\Database\TypeMap` $typeMap The map object 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` ### setValueBinder() public ``` setValueBinder(Cake\Database\ValueBinder|null $binder): $this ``` Overwrite the current value binder A ValueBinder is responsible for generating query placeholders and temporarily associate values to those placeholders so that they can be passed correctly to the statement object. #### Parameters `Cake\Database\ValueBinder|null` $binder The binder or null to disable binding. #### Returns `$this` ### sql() public ``` sql(Cake\Database\ValueBinder|null $binder = null): string ``` Returns the SQL representation of this object. This function will compile this query to make it compatible with the SQL dialect that is used by the connection, This process might add, remove or alter any query part or internal expression to make it executable in the target platform. The resulting query may have placeholders that will be replaced with the actual values when the query is executed, hence it is most suitable to use with prepared statements. #### Parameters `Cake\Database\ValueBinder|null` $binder optional Value binder that generates parameter placeholders #### Returns `string` ### traverse() public ``` traverse(callable $callback): $this ``` Will iterate over every specified part. Traversing functions can aggregate results using variables in the closure or instance variables. This function is commonly used as a way for traversing all query parts that are going to be used for constructing a query. The callback will receive 2 parameters, the first one is the value of the query part that is being iterated and the second the name of such part. ### Example ``` $query->select(['title'])->from('articles')->traverse(function ($value, $clause) { if ($clause === 'select') { var_dump($value); } }); ``` #### Parameters `callable` $callback A function or callable to be executed for each part #### Returns `$this` ### traverseExpressions() public ``` traverseExpressions(callable $callback): $this ``` This function works similar to the traverse() function, with the difference that it does a full depth traversal of the entire expression tree. This will execute the provided callback function for each ExpressionInterface object that is stored inside this query at any nesting depth in any part of the query. Callback will receive as first parameter the currently visited expression. #### Parameters `callable` $callback the function to be executed for each ExpressionInterface found inside this query. #### Returns `$this` ### traverseParts() public ``` traverseParts(callable $visitor, array<string> $parts): $this ``` Will iterate over the provided parts. Traversing functions can aggregate results using variables in the closure or instance variables. This method can be used to traverse a subset of query parts in order to render a SQL query. The callback will receive 2 parameters, the first one is the value of the query part that is being iterated and the second the name of such part. ### Example ``` $query->select(['title'])->from('articles')->traverse(function ($value, $clause) { if ($clause === 'select') { var_dump($value); } }, ['select', 'from']); ``` #### Parameters `callable` $visitor A function or callable to be executed for each part `array<string>` $parts The list of query parts to traverse #### Returns `$this` ### type() public ``` type(): string ``` Returns the type of this query (select, insert, update, delete) #### Returns `string` ### union() public ``` union(Cake\Database\Query|string $query, bool $overwrite = false): $this ``` Adds a complete query to be used in conjunction with an UNION operator with this query. This is used to combine the result set of this query with the one that will be returned by the passed query. You can add as many queries as you required by calling multiple times this method with different queries. By default, the UNION operator will remove duplicate rows, if you wish to include every row for all queries, use unionAll(). ### Examples ``` $union = (new Query($conn))->select(['id', 'title'])->from(['a' => 'articles']); $query->select(['id', 'name'])->from(['d' => 'things'])->union($union); ``` Will produce: `SELECT id, name FROM things d UNION SELECT id, title FROM articles a` #### Parameters `Cake\Database\Query|string` $query full SQL query to be used in UNION operator `bool` $overwrite optional whether to reset the list of queries to be operated or not #### Returns `$this` ### unionAll() public ``` unionAll(Cake\Database\Query|string $query, bool $overwrite = false): $this ``` Adds a complete query to be used in conjunction with the UNION ALL operator with this query. This is used to combine the result set of this query with the one that will be returned by the passed query. You can add as many queries as you required by calling multiple times this method with different queries. Unlike UNION, UNION ALL will not remove duplicate rows. ``` $union = (new Query($conn))->select(['id', 'title'])->from(['a' => 'articles']); $query->select(['id', 'name'])->from(['d' => 'things'])->unionAll($union); ``` Will produce: `SELECT id, name FROM things d UNION ALL SELECT id, title FROM articles a` #### Parameters `Cake\Database\Query|string` $query full SQL query to be used in UNION operator `bool` $overwrite optional whether to reset the list of queries to be operated or not #### Returns `$this` ### update() public ``` update(Cake\Database\ExpressionInterface|string $table): $this ``` Create an update query. Can be combined with set() and where() methods to create update queries. #### Parameters `Cake\Database\ExpressionInterface|string` $table The table you want to update. #### Returns `$this` ### values() public ``` values(Cake\Database\Expression\ValuesExpressionCake\Database\Query|array $data): $this ``` Set the values for an insert query. Multi inserts can be performed by calling values() more than one time, or by providing an array of value sets. Additionally $data can be a Query instance to insert data from another SELECT statement. #### Parameters `Cake\Database\Expression\ValuesExpressionCake\Database\Query|array` $data The data to insert. #### Returns `$this` #### Throws `Cake\Database\Exception\DatabaseException` if you try to set values before declaring columns. Or if you try to set values on non-insert queries. ### where() public ``` where(Cake\Database\ExpressionInterfaceClosure|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]])` Would result in: `WHERE (published = false) OR (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. The keys however, are not treated as unsafe input, and should be validated/sanitized. 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 `Cake\Database\ExpressionInterfaceClosure|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` #### See Also \Cake\Database\TypeFactory \Cake\Database\Expression\QueryExpression ### whereInList() public ``` whereInList(string $field, array $values, array<string, mixed> $options = []): $this ``` Adds an IN condition or set of conditions to be used in the WHERE clause for this query. This method does allow empty inputs in contrast to where() if you set 'allowEmpty' to true. Be careful about using it without proper sanity checks. Options: * `types` - Associative array of type names used to bind values to query * `allowEmpty` - Allow empty array. #### Parameters `string` $field Field `array` $values Array of values `array<string, mixed>` $options optional Options #### Returns `$this` ### whereNotInList() public ``` whereNotInList(string $field, array $values, array<string, mixed> $options = []): $this ``` Adds a NOT IN condition or set of conditions to be used in the WHERE clause for this query. This method does allow empty inputs in contrast to where() if you set 'allowEmpty' to true. Be careful about using it without proper sanity checks. #### Parameters `string` $field Field `array` $values Array of values `array<string, mixed>` $options optional Options #### Returns `$this` ### whereNotInListOrNull() public ``` whereNotInListOrNull(string $field, array $values, array<string, mixed> $options = []): $this ``` Adds a NOT IN condition or set of conditions to be used in the WHERE clause for this query. This also allows the field to be null with a IS NULL condition since the null value would cause the NOT IN condition to always fail. This method does allow empty inputs in contrast to where() if you set 'allowEmpty' to true. Be careful about using it without proper sanity checks. #### Parameters `string` $field Field `array` $values Array of values `array<string, mixed>` $options optional Options #### Returns `$this` ### whereNotNull() public ``` whereNotNull(Cake\Database\ExpressionInterface|array|string $fields): $this ``` Convenience method that adds a NOT NULL condition to the query #### Parameters `Cake\Database\ExpressionInterface|array|string` $fields A single field or expressions or a list of them that should be not null. #### Returns `$this` ### whereNull() public ``` whereNull(Cake\Database\ExpressionInterface|array|string $fields): $this ``` Convenience method that adds a IS NULL condition to the query #### Parameters `Cake\Database\ExpressionInterface|array|string` $fields A single field or expressions or a list of them that should be null. #### Returns `$this` ### window() public ``` window(string $name, Cake\Database\Expression\WindowExpressionClosure $window, bool $overwrite = false): $this ``` Adds a named window expression. You are responsible for adding windows in the order your database requires. #### Parameters `string` $name Window name `Cake\Database\Expression\WindowExpressionClosure` $window Window expression `bool` $overwrite optional Clear all previous query window expressions #### Returns `$this` ### with() public ``` with(Cake\Database\Expression\CommonTableExpressionClosure $cte, bool $overwrite = false): $this ``` Adds a new common table expression (CTE) to the query. ### Examples: Common table expressions can either be passed as preconstructed expression objects: ``` $cte = new \Cake\Database\Expression\CommonTableExpression( 'cte', $connection ->newQuery() ->select('*') ->from('articles') ); $query->with($cte); ``` or returned from a closure, which will receive a new common table expression object as the first argument, and a new blank query object as the second argument: ``` $query->with(function ( \Cake\Database\Expression\CommonTableExpression $cte, \Cake\Database\Query $query ) { $cteQuery = $query ->select('*') ->from('articles'); return $cte ->name('cte') ->query($cteQuery); }); ``` #### Parameters `Cake\Database\Expression\CommonTableExpressionClosure` $cte The CTE to add. `bool` $overwrite optional Whether to reset the list of CTEs. #### Returns `$this` Property Detail --------------- ### $\_connection protected Connection instance to be used to execute this query. #### Type `Cake\Database\Connection` ### $\_deleteParts protected deprecated The list of query clauses to traverse for generating a DELETE statement #### Type `array<string>` ### $\_dirty protected Indicates whether internal state of this query was changed, this is used to discard internal cached objects such as the transformed query or the reference to the executed statement. #### Type `bool` ### $\_functionsBuilder protected Instance of functions builder object used for generating arbitrary SQL functions. #### Type `Cake\Database\FunctionsBuilder|null` ### $\_insertParts protected deprecated The list of query clauses to traverse for generating an INSERT statement #### Type `array<string>` ### $\_iterator protected Statement object resulting from executing this query. #### Type `Cake\Database\StatementInterface|null` ### $\_parts protected List of SQL parts that will be used to build this query. #### Type `array<string, mixed>` ### $\_resultDecorators protected A list of callback functions to be called to alter each row from resulting statement upon retrieval. Each one of the callback function will receive the row array as first argument. #### Type `array<callable>` ### $\_selectParts protected deprecated The list of query clauses to traverse for generating a SELECT statement #### Type `array<string>` ### $\_selectTypeMap protected The Type map for fields in the select clause #### Type `Cake\Database\TypeMap|null` ### $\_type protected Type of this query (select, insert, update, delete). #### Type `string` ### $\_typeMap protected #### Type `Cake\Database\TypeMap|null` ### $\_updateParts protected deprecated The list of query clauses to traverse for generating an UPDATE statement #### Type `array<string>` ### $\_useBufferedResults protected Boolean for tracking whether buffered results are enabled. #### Type `bool` ### $\_valueBinder protected The object responsible for generating query placeholders and temporarily store values associated to each of those. #### Type `Cake\Database\ValueBinder|null` ### $typeCastEnabled protected Tracking flag to disable casting #### Type `bool`
programming_docs
cakephp Class WincacheEngine Class WincacheEngine ===================== Wincache storage engine for cache Supports wincache 1.1.0 and higher. **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 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 item in the cache matching the cache config prefix. * ##### [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 item in the cache matching the cache config prefix. #### 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 #### 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` ### 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` cakephp Class AggregateExpression Class 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. **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 ---------------- * [$\_conditions](#%24_conditions) protected `array` A list of strings or other expression objects that represent the "branches" of the expression tree. For example one key of the array might look like "sum > :value" * [$\_conjunction](#%24_conjunction) protected `string` String to be used for joining each of the internal expressions this object internally stores for example "AND", "OR", etc. * [$\_name](#%24_name) protected `string` The name of the function to be constructed when generating the SQL string * [$\_returnType](#%24_returnType) protected `string` The type name this expression will return when executed * [$\_typeMap](#%24_typeMap) protected `Cake\Database\TypeMap|null` * [$filter](#%24filter) protected `Cake\Database\Expression\QueryExpression` * [$window](#%24window) protected `Cake\Database\Expression\WindowExpression` Method Summary -------------- * ##### [\_\_clone()](#__clone()) public Clone this object and its subtree of expressions. * ##### [\_\_construct()](#__construct()) public Constructor. Takes a name for the function to be invoked and a list of params to be passed into the function. Optionally you can pass a list of types to be used for each bound param. * ##### [\_addConditions()](#_addConditions()) protected Auxiliary function used for decomposing a nested array of conditions and build a tree structure inside this object to represent the full SQL expression. String conditions are stored directly in the conditions, while any other representation is wrapped around an adequate instance or of this class. * ##### [\_calculateType()](#_calculateType()) protected Returns the type name for the passed field if it was stored in the typeMap * ##### [\_castToExpression()](#_castToExpression()) protected Conditionally converts the passed value to an ExpressionInterface object if the type class implements the ExpressionTypeInterface. Otherwise, returns the value unmodified. * ##### [\_parseCondition()](#_parseCondition()) protected Parses a string conditions by trying to extract the operator inside it if any and finally returning either an adequate QueryExpression object or a plain string representation of the condition. This function is responsible for generating the placeholders and replacing the values by them, while storing the value elsewhere for future binding. * ##### [\_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 arguments for the function call. * ##### [addCase()](#addCase()) public deprecated Adds a new case expression to the expression object * ##### [and()](#and()) public Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "AND" * ##### [and\_()](#and_()) public deprecated Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "AND" * ##### [between()](#between()) public Adds a new condition to the expression object in the form "field BETWEEN from AND to". * ##### [case()](#case()) public Returns a new case expression object. * ##### [count()](#count()) public The name of the function is in itself an expression to generate, thus always adding 1 to the amount of expressions stored in this object. * ##### [eq()](#eq()) public Adds a new condition to the expression object in the form "field = value". * ##### [equalFields()](#equalFields()) public Builds equal condition or assignment with identifier wrapping. * ##### [excludeCurrent()](#excludeCurrent()) public Adds current row frame exclusion. * ##### [excludeGroup()](#excludeGroup()) public Adds group frame exclusion. * ##### [excludeTies()](#excludeTies()) public Adds ties frame exclusion. * ##### [exists()](#exists()) public Adds a new condition to the expression object in the form "EXISTS (...)". * ##### [filter()](#filter()) public Adds conditions to the FILTER clause. The conditions are the same format as `Query::where()`. * ##### [frame()](#frame()) public Adds a frame to the window. * ##### [getConjunction()](#getConjunction()) public Gets the currently configured conjunction for the conditions at this level of the expression tree. * ##### [getDefaultTypes()](#getDefaultTypes()) public Gets default types of current type map. * ##### [getName()](#getName()) public Gets the name of the SQL function to be invoke in this expression. * ##### [getReturnType()](#getReturnType()) public Gets the type of the value this object will generate. * ##### [getTypeMap()](#getTypeMap()) public Returns the existing type map. * ##### [groups()](#groups()) public Adds a simple groups frame to the window. * ##### [gt()](#gt()) public Adds a new condition to the expression object in the form "field > value". * ##### [gte()](#gte()) public Adds a new condition to the expression object in the form "field >= value". * ##### [hasNestedExpression()](#hasNestedExpression()) public Returns true if this expression contains any other nested ExpressionInterface objects * ##### [in()](#in()) public Adds a new condition to the expression object in the form "field IN (value1, value2)". * ##### [isCallable()](#isCallable()) public deprecated Check whether a callable is acceptable. * ##### [isNotNull()](#isNotNull()) public Adds a new condition to the expression object in the form "field IS NOT NULL". * ##### [isNull()](#isNull()) public Adds a new condition to the expression object in the form "field IS NULL". * ##### [iterateParts()](#iterateParts()) public Executes a callable function for each of the parts that form this expression. * ##### [like()](#like()) public Adds a new condition to the expression object in the form "field LIKE value". * ##### [lt()](#lt()) public Adds a new condition to the expression object in the form "field < value". * ##### [lte()](#lte()) public Adds a new condition to the expression object in the form "field <= value". * ##### [not()](#not()) public Adds a new set of conditions to this level of the tree and negates the final result by prepending a NOT, it will look like "NOT ( (condition1) AND (conditions2) )" conjunction depends on the one currently configured for this object. * ##### [notEq()](#notEq()) public Adds a new condition to the expression object in the form "field != value". * ##### [notExists()](#notExists()) public Adds a new condition to the expression object in the form "NOT EXISTS (...)". * ##### [notIn()](#notIn()) public Adds a new condition to the expression object in the form "field NOT IN (value1, value2)". * ##### [notInOrNull()](#notInOrNull()) public Adds a new condition to the expression object in the form "(field NOT IN (value1, value2) OR field IS NULL". * ##### [notLike()](#notLike()) public Adds a new condition to the expression object in the form "field NOT LIKE value". * ##### [or()](#or()) public Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "OR" * ##### [or\_()](#or_()) public deprecated Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "OR" * ##### [order()](#order()) public Adds one or more order clauses to the window. * ##### [over()](#over()) public Adds an empty `OVER()` window expression or a named window epression. * ##### [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. * ##### [setConjunction()](#setConjunction()) public Changes the conjunction for the conditions at this level of the expression tree. * ##### [setDefaultTypes()](#setDefaultTypes()) public Overwrite the default type mappings for fields in the implementing object. * ##### [setName()](#setName()) public Sets the name of the SQL function to be invoke in this expression. * ##### [setReturnType()](#setReturnType()) public Sets the type of the value this object will generate. * ##### [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. * ##### [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, array $params = [], array<string, string>|array<string|null> $types = [], string $returnType = 'string') ``` Constructor. Takes a name for the function to be invoked and a list of params to be passed into the function. Optionally you can pass a list of types to be used for each bound param. By default, all params that are passed will be quoted. If you wish to use literal arguments, you need to explicitly hint this function. ### Examples: `$f = new FunctionExpression('CONCAT', ['CakePHP', ' rules']);` Previous line will generate `CONCAT('CakePHP', ' rules')` `$f = new FunctionExpression('CONCAT', ['name' => 'literal', ' rules']);` Will produce `CONCAT(name, ' rules')` #### Parameters `string` $name the name of the function to be constructed `array` $params optional list of arguments to be passed to the function If associative the key would be used as argument when value is 'literal' `array<string, string>|array<string|null>` $types optional Associative array of types to be associated with the passed arguments `string` $returnType optional The return type of this expression ### \_addConditions() protected ``` _addConditions(array $conditions, array<int|string, string> $types): void ``` Auxiliary function used for decomposing a nested array of conditions and build a tree structure inside this object to represent the full SQL expression. String conditions are stored directly in the conditions, while any other representation is wrapped around an adequate instance or of this class. #### Parameters `array` $conditions list of conditions to be stored in this object `array<int|string, string>` $types list of types associated on fields referenced in $conditions #### Returns `void` ### \_calculateType() protected ``` _calculateType(Cake\Database\ExpressionInterface|string $field): string|null ``` Returns the type name for the passed field if it was stored in the typeMap #### Parameters `Cake\Database\ExpressionInterface|string` $field The field name to get a type for. #### Returns `string|null` ### \_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` ### \_parseCondition() protected ``` _parseCondition(string $field, mixed $value): Cake\Database\ExpressionInterface ``` Parses a string conditions by trying to extract the operator inside it if any and finally returning either an adequate QueryExpression object or a plain string representation of the condition. This function is responsible for generating the placeholders and replacing the values by them, while storing the value elsewhere for future binding. #### Parameters `string` $field The value from which the actual field and operator will be extracted. `mixed` $value The value to be bound to a placeholder for the field #### Returns `Cake\Database\ExpressionInterface` #### Throws `InvalidArgumentException` If operator is invalid or missing on NULL usage. ### \_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(array $conditions, array<string, string> $types = [], bool $prepend = false): $this ``` Adds one or more arguments for the function call. #### Parameters `array` $conditions list of arguments to be passed to the function If associative the key would be used as argument when value is 'literal' `array<string, string>` $types optional Associative array of types to be associated with the passed arguments `bool` $prepend optional Whether to prepend or append to the list of arguments #### Returns `$this` #### See Also \Cake\Database\Expression\FunctionExpression::\_\_construct() for more details. ### addCase() public ``` addCase(Cake\Database\ExpressionInterface|array $conditions, Cake\Database\ExpressionInterface|array $values = [], array<string> $types = []): $this ``` Adds a new case expression to the expression object #### Parameters `Cake\Database\ExpressionInterface|array` $conditions 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 #### Returns `$this` ### and() public ``` and(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "AND" #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be joined with AND `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `Cake\Database\Expression\QueryExpression` ### and\_() public ``` and_(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "AND" #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be joined with AND `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `Cake\Database\Expression\QueryExpression` ### between() public ``` between(Cake\Database\ExpressionInterface|string $field, mixed $from, mixed $to, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field BETWEEN from AND to". #### 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 type name for $value as configured using the Type map. #### Returns `$this` ### case() public ``` case(Cake\Database\ExpressionInterface|object|scalar|null $value = null, string|null $type = null): Cake\Database\Expression\CaseStatementExpression ``` Returns a new case expression object. 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. #### Returns `Cake\Database\Expression\CaseStatementExpression` ### count() public ``` count(): int ``` The name of the function is in itself an expression to generate, thus always adding 1 to the amount of expressions stored in this object. #### Returns `int` ### eq() public ``` eq(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field = value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. If it is suffixed with "[]" and the value is an array then multiple placeholders will be created, one per each value in the array. #### Returns `$this` ### equalFields() public ``` equalFields(string $leftField, string $rightField): $this ``` Builds equal condition or assignment with identifier wrapping. #### Parameters `string` $leftField Left join condition field name. `string` $rightField Right join condition field name. #### Returns `$this` ### 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` ### exists() public ``` exists(Cake\Database\ExpressionInterface $expression): $this ``` Adds a new condition to the expression object in the form "EXISTS (...)". #### Parameters `Cake\Database\ExpressionInterface` $expression the inner query #### Returns `$this` ### filter() public ``` filter(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): $this ``` Adds conditions to the FILTER clause. The conditions are the same format as `Query::where()`. #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions The conditions to filter on. `array<string, string>` $types optional Associative array of type names used to bind values to query #### Returns `$this` #### See Also \Cake\Database\Query::where() ### 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` ### getConjunction() public ``` getConjunction(): string ``` Gets the currently configured conjunction for the conditions at this level of the expression tree. #### Returns `string` ### getDefaultTypes() public ``` getDefaultTypes(): array<int|string, string> ``` Gets default types of current type map. #### Returns `array<int|string, string>` ### getName() public ``` getName(): string ``` Gets the name of the SQL function to be invoke in this expression. #### Returns `string` ### getReturnType() public ``` getReturnType(): string ``` Gets the type of the value this object will generate. #### Returns `string` ### getTypeMap() public ``` getTypeMap(): Cake\Database\TypeMap ``` Returns the existing type map. #### Returns `Cake\Database\TypeMap` ### 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` ### gt() public ``` gt(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field > value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### gte() public ``` gte(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field >= value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### hasNestedExpression() public ``` hasNestedExpression(): bool ``` Returns true if this expression contains any other nested ExpressionInterface objects #### Returns `bool` ### in() public ``` in(Cake\Database\ExpressionInterface|string $field, Cake\Database\ExpressionInterface|array|string $values, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field IN (value1, value2)". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `Cake\Database\ExpressionInterface|array|string` $values the value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### isCallable() public ``` isCallable(Cake\Database\ExpressionInterface|callable|array|string $callable): bool ``` Check whether a callable is acceptable. We don't accept ['class', 'method'] style callbacks, as they often contain user input and arrays of strings are easy to sneak in. #### Parameters `Cake\Database\ExpressionInterface|callable|array|string` $callable The callable to check. #### Returns `bool` ### isNotNull() public ``` isNotNull(Cake\Database\ExpressionInterface|string $field): $this ``` Adds a new condition to the expression object in the form "field IS NOT NULL". #### Parameters `Cake\Database\ExpressionInterface|string` $field database field to be tested for not null #### Returns `$this` ### isNull() public ``` isNull(Cake\Database\ExpressionInterface|string $field): $this ``` Adds a new condition to the expression object in the form "field IS NULL". #### Parameters `Cake\Database\ExpressionInterface|string` $field database field to be tested for null #### Returns `$this` ### iterateParts() public ``` iterateParts(callable $callback): $this ``` Executes a callable function for each of the parts that form this expression. The callable function is required to return a value with which the currently visited part will be replaced. If the callable function returns null then the part will be discarded completely from this expression. The callback function will receive each of the conditions as first param and the key as second param. It is possible to declare the second parameter as passed by reference, this will enable you to change the key under which the modified part is stored. #### Parameters `callable` $callback The callable to apply to each part. #### Returns `$this` ### like() public ``` like(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field LIKE value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### lt() public ``` lt(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field < value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### lte() public ``` lte(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field <= value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### not() public ``` not(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): $this ``` Adds a new set of conditions to this level of the tree and negates the final result by prepending a NOT, it will look like "NOT ( (condition1) AND (conditions2) )" conjunction depends on the one currently configured for this object. #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be added and negated `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `$this` ### notEq() public ``` notEq(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field != value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. If it is suffixed with "[]" and the value is an array then multiple placeholders will be created, one per each value in the array. #### Returns `$this` ### notExists() public ``` notExists(Cake\Database\ExpressionInterface $expression): $this ``` Adds a new condition to the expression object in the form "NOT EXISTS (...)". #### Parameters `Cake\Database\ExpressionInterface` $expression the inner query #### Returns `$this` ### notIn() public ``` notIn(Cake\Database\ExpressionInterface|string $field, Cake\Database\ExpressionInterface|array|string $values, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field NOT IN (value1, value2)". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `Cake\Database\ExpressionInterface|array|string` $values the value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### notInOrNull() public ``` notInOrNull(Cake\Database\ExpressionInterface|string $field, Cake\Database\ExpressionInterface|array|string $values, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "(field NOT IN (value1, value2) OR field IS NULL". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `Cake\Database\ExpressionInterface|array|string` $values the value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### notLike() public ``` notLike(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field NOT LIKE value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### or() public ``` or(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "OR" #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be joined with OR `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `Cake\Database\Expression\QueryExpression` ### or\_() public ``` or_(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "OR" #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be joined with OR `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `Cake\Database\Expression\QueryExpression` ### 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` ### over() public ``` over(string|null $name = null): $this ``` Adds an empty `OVER()` window expression or a named window epression. #### Parameters `string|null` $name optional Window name #### 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` ### setConjunction() public ``` setConjunction(string $conjunction): $this ``` Changes the conjunction for the conditions at this level of the expression tree. #### Parameters `string` $conjunction Value to be used for joining conditions #### 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() ### setName() public ``` setName(string $name): $this ``` Sets the name of the SQL function to be invoke in this expression. #### Parameters `string` $name The name of the function #### Returns `$this` ### setReturnType() public ``` setReturnType(string $type): $this ``` Sets the type of the value this object will generate. #### Parameters `string` $type The name of the type that is to be returned #### 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` ### 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 "branches" of the expression tree. For example one key of the array might look like "sum > :value" #### Type `array` ### $\_conjunction protected String to be used for joining each of the internal expressions this object internally stores for example "AND", "OR", etc. #### Type `string` ### $\_name protected The name of the function to be constructed when generating the SQL string #### Type `string` ### $\_returnType protected The type name this expression will return when executed #### Type `string` ### $\_typeMap protected #### Type `Cake\Database\TypeMap|null` ### $filter protected #### Type `Cake\Database\Expression\QueryExpression` ### $window protected #### Type `Cake\Database\Expression\WindowExpression`
programming_docs
cakephp Class IcuFormatter Class IcuFormatter =================== A formatter that will interpolate variables using the MessageFormatter class **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 MessageFormatter class. 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 MessageFormatter class. #### 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` #### Throws `Cake\I18n\Exception\I18nException` cakephp Class ServerRequest Class 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. **Namespace:** [Cake\Http](namespace-cake.http) Property Summary ---------------- * [$\_detectorCache](#%24_detectorCache) protected `array<string, bool>` Instance cache for results of is(something) calls * [$\_detectors](#%24_detectors) protected static `array<callable|array>` The built in detectors used with `is()` can be modified with `addDetector()`. * [$\_environment](#%24_environment) protected `array<string, mixed>` Array of environment data. * [$attributes](#%24attributes) protected `array<string, mixed>` Store the additional attributes attached to the request. * [$base](#%24base) protected `string` Base URL path. * [$cookies](#%24cookies) protected `array<string, mixed>` Array of cookie data. * [$data](#%24data) protected `object|array|null` Array of POST data. Will contain form data as well as uploaded files. In PUT/PATCH/DELETE requests this property will contain the form-urlencoded data. * [$emulatedAttributes](#%24emulatedAttributes) protected `array<string>` A list of properties that emulated by the PSR7 attribute methods. * [$flash](#%24flash) protected `Cake\Http\FlashMessage` Instance of a FlashMessage object relative to this request * [$params](#%24params) protected `array` Array of parameters parsed from the URL. * [$protocol](#%24protocol) protected `string|null` The HTTP protocol version used. * [$query](#%24query) protected `array` Array of query string arguments * [$requestTarget](#%24requestTarget) protected `string|null` The request target if overridden * [$session](#%24session) protected `Cake\Http\Session` Instance of a Session object relative to this request * [$stream](#%24stream) protected `Psr\Http\Message\StreamInterface` Request body stream. Contains php://input unless `input` constructor option is used. * [$trustProxy](#%24trustProxy) public `bool` Whether to trust HTTP\_X headers set by most load balancers. Only set to true if your application runs behind load balancers/proxies that you control. * [$trustedProxies](#%24trustedProxies) protected `array<string>` Trusted proxies list * [$uploadedFiles](#%24uploadedFiles) protected `array` Array of Psr\Http\Message\UploadedFileInterface objects. * [$uri](#%24uri) protected `Psr\Http\Message\UriInterface` Uri instance * [$webroot](#%24webroot) protected `string` webroot path segment for the request. Method Summary -------------- * ##### [\_\_call()](#__call()) public Missing method handler, handles wrapping older style isAjax() type methods * ##### [\_\_construct()](#__construct()) public Create a new request object. * ##### [\_acceptHeaderDetector()](#_acceptHeaderDetector()) protected Detects if a specific accept header is present. * ##### [\_environmentDetector()](#_environmentDetector()) protected Detects if a specific environment variable is present. * ##### [\_headerDetector()](#_headerDetector()) protected Detects if a specific header is present. * ##### [\_is()](#_is()) protected Worker for the public is() function * ##### [\_paramDetector()](#_paramDetector()) protected Detects if a specific request parameter is present. * ##### [\_setConfig()](#_setConfig()) protected Process the config/settings data into properties. * ##### [acceptLanguage()](#acceptLanguage()) public Get the languages accepted by the client, or check if a specific language is accepted. * ##### [accepts()](#accepts()) public Find out which content types the client accepts or check if they accept a particular type of content. * ##### [addDetector()](#addDetector()) public static Add a new detector to the list of detectors that a request can use. There are several different types of detectors that can be set. * ##### [allowMethod()](#allowMethod()) public Allow only certain HTTP request methods, if the request method does not match a 405 error will be shown and the required "Allow" response header will be set. * ##### [clearDetectorCache()](#clearDetectorCache()) public Clears the instance detector cache, used by the is() function * ##### [clientIp()](#clientIp()) public Get the IP the client is using, or says they are using. * ##### [contentType()](#contentType()) public Get the content type used in this request. * ##### [domain()](#domain()) public Get the domain name and include $tldLength segments of the tld. * ##### [getAttribute()](#getAttribute()) public Read an attribute from the request, or get the default * ##### [getAttributes()](#getAttributes()) public Get all the attributes in the request. * ##### [getBody()](#getBody()) public Gets the body of the message. * ##### [getCookie()](#getCookie()) public Read cookie data from the request's cookie data. * ##### [getCookieCollection()](#getCookieCollection()) public Get a cookie collection based on the request's cookies * ##### [getCookieParams()](#getCookieParams()) public Get all the cookie data from the request. * ##### [getData()](#getData()) public Provides a safe accessor for request data. Allows you to use Hash::get() compatible paths. * ##### [getEnv()](#getEnv()) public Get a value from the request's environment data. Fallback to using env() if the key is not set in the $environment property. * ##### [getFlash()](#getFlash()) public Returns the instance of the FlashMessage object for this request * ##### [getHeader()](#getHeader()) public Get a single header from the request. * ##### [getHeaderLine()](#getHeaderLine()) public Get a single header as a string from the request. * ##### [getHeaders()](#getHeaders()) public Get all headers in the request. * ##### [getMethod()](#getMethod()) public Get the HTTP method used for this request. There are a few ways to specify a method. * ##### [getParam()](#getParam()) public Safely access the values in $this->params. * ##### [getParsedBody()](#getParsedBody()) public Get the parsed request body data. * ##### [getPath()](#getPath()) public Get the path of current request. * ##### [getProtocolVersion()](#getProtocolVersion()) public Retrieves the HTTP protocol version as a string. * ##### [getQuery()](#getQuery()) public Read a specific query value or dotted path. * ##### [getQueryParams()](#getQueryParams()) public Get all the query parameters in accordance to the PSR-7 specifications. To read specific query values use the alternative getQuery() method. * ##### [getRequestTarget()](#getRequestTarget()) public Retrieves the request's target. * ##### [getServerParams()](#getServerParams()) public Get all the server environment parameters. * ##### [getSession()](#getSession()) public Returns the instance of the Session object for this request * ##### [getTrustedProxies()](#getTrustedProxies()) public Get trusted proxies * ##### [getUploadedFile()](#getUploadedFile()) public Get the uploaded file from a dotted path. * ##### [getUploadedFiles()](#getUploadedFiles()) public Get the array of uploaded files from the request. * ##### [getUri()](#getUri()) public Retrieves the URI instance. * ##### [hasHeader()](#hasHeader()) public Check if a header is set in the request. * ##### [host()](#host()) public Get the host that the request was handled on. * ##### [input()](#input()) public deprecated Read data from `php://input`. Useful when interacting with XML or JSON request body content. * ##### [is()](#is()) public Check whether a Request is a certain type. * ##### [isAll()](#isAll()) public Check that a request matches all the given types. * ##### [normalizeHeaderName()](#normalizeHeaderName()) protected Normalize a header name into the SERVER version. * ##### [parseAccept()](#parseAccept()) public deprecated Parse the HTTP\_ACCEPT header and return a sorted array with content types as the keys, and pref values as the values. * ##### [port()](#port()) public Get the port the request was handled on. * ##### [processUrlOption()](#processUrlOption()) protected Set environment vars based on `url` option to facilitate UriInterface instance generation. * ##### [referer()](#referer()) public Returns the referer that referred this request. * ##### [scheme()](#scheme()) public Get the current url scheme used for the request. * ##### [setTrustedProxies()](#setTrustedProxies()) public register trusted proxies * ##### [subdomains()](#subdomains()) public Get the subdomains for a host. * ##### [validateUploadedFiles()](#validateUploadedFiles()) protected Recursively validate uploaded file data. * ##### [withAddedHeader()](#withAddedHeader()) public Get a modified request with the provided header. * ##### [withAttribute()](#withAttribute()) public Return an instance with the specified request attribute. * ##### [withBody()](#withBody()) public Return an instance with the specified message body. * ##### [withCookieCollection()](#withCookieCollection()) public Replace the cookies in the request with those contained in the provided CookieCollection. * ##### [withCookieParams()](#withCookieParams()) public Replace the cookies and get a new request instance. * ##### [withData()](#withData()) public Update the request with a new request data element. * ##### [withEnv()](#withEnv()) public Update the request with a new environment data element. * ##### [withHeader()](#withHeader()) public Get a modified request with the provided header. * ##### [withMethod()](#withMethod()) public Update the request method and get a new instance. * ##### [withParam()](#withParam()) public Update the request with a new routing parameter * ##### [withParsedBody()](#withParsedBody()) public Update the parsed body and get a new instance. * ##### [withProtocolVersion()](#withProtocolVersion()) public Return an instance with the specified HTTP protocol version. * ##### [withQueryParams()](#withQueryParams()) public Update the query string data and get a new instance. * ##### [withRequestTarget()](#withRequestTarget()) public Create a new instance with a specific request-target. * ##### [withUploadedFiles()](#withUploadedFiles()) public Update the request replacing the files, and creating a new instance. * ##### [withUri()](#withUri()) public Return an instance with the specified uri * ##### [withoutAttribute()](#withoutAttribute()) public Return an instance without the specified request attribute. * ##### [withoutData()](#withoutData()) public Update the request removing a data element. * ##### [withoutHeader()](#withoutHeader()) public Get a modified request without a provided header. Method Detail ------------- ### \_\_call() public ``` __call(string $name, array $params): bool ``` Missing method handler, handles wrapping older style isAjax() type methods #### Parameters `string` $name The method called `array` $params Array of parameters for the method call #### Returns `bool` #### Throws `BadMethodCallException` when an invalid method is called. ### \_\_construct() public ``` __construct(array<string, mixed> $config = []) ``` Create a new request object. You can supply the data as either an array or as a string. If you use a string you can only supply the URL for the request. Using an array will let you provide the following keys: * `post` POST data or non query string data * `query` Additional data from the query string. * `files` Uploaded files in a normalized structure, with each leaf an instance of UploadedFileInterface. * `cookies` Cookies for this request. * `environment` $\_SERVER and $\_ENV data. * `url` The URL without the base path for the request. * `uri` The PSR7 UriInterface object. If null, one will be created from `url` or `environment`. * `base` The base URL for the request. * `webroot` The webroot directory for the request. * `input` The data that would come from php://input this is useful for simulating requests with put, patch or delete data. * `session` An instance of a Session object #### Parameters `array<string, mixed>` $config optional An array of request data to create a request with. ### \_acceptHeaderDetector() protected ``` _acceptHeaderDetector(array $detect): bool ``` Detects if a specific accept header is present. #### Parameters `array` $detect Detector options array. #### Returns `bool` ### \_environmentDetector() protected ``` _environmentDetector(array $detect): bool ``` Detects if a specific environment variable is present. #### Parameters `array` $detect Detector options array. #### Returns `bool` ### \_headerDetector() protected ``` _headerDetector(array $detect): bool ``` Detects if a specific header is present. #### Parameters `array` $detect Detector options array. #### Returns `bool` ### \_is() protected ``` _is(string $type, array $args): bool ``` Worker for the public is() function #### Parameters `string` $type The type of request you want to check. `array` $args Array of custom detector arguments. #### Returns `bool` ### \_paramDetector() protected ``` _paramDetector(array $detect): bool ``` Detects if a specific request parameter is present. #### Parameters `array` $detect Detector options array. #### Returns `bool` ### \_setConfig() protected ``` _setConfig(array<string, mixed> $config): void ``` Process the config/settings data into properties. #### Parameters `array<string, mixed>` $config The config data to use. #### Returns `void` ### acceptLanguage() public ``` acceptLanguage(string|null $language = null): array|bool ``` Get the languages accepted by the client, or check if a specific language is accepted. Get the list of accepted languages: `$request->acceptLanguage();` Check if a specific language is accepted: `$request->acceptLanguage('es-es');` #### Parameters `string|null` $language optional The language to test. #### Returns `array|bool` ### accepts() public ``` accepts(string|null $type = null): array<string>|bool ``` Find out which content types the client accepts or check if they accept a particular type of content. #### Get all types: ``` $this->request->accepts(); ``` #### Check for a single type: ``` $this->request->accepts('application/json'); ``` This method will order the returned content types by the preference values indicated by the client. #### Parameters `string|null` $type optional The content type to check for. Leave null to get all types a client accepts. #### Returns `array<string>|bool` ### addDetector() public static ``` addDetector(string $name, callable|array $detector): void ``` Add a new detector to the list of detectors that a request can use. There are several different types of detectors that can be set. ### Callback comparison Callback detectors allow you to provide a callable to handle the check. The callback will receive the request object as its only parameter. ``` addDetector('custom', function ($request) { //Return a boolean }); ``` ### Environment value comparison An environment value comparison, compares a value fetched from `env()` to a known value the environment value is equality checked against the provided value. ``` addDetector('post', ['env' => 'REQUEST_METHOD', 'value' => 'POST']); ``` ### Request parameter comparison Allows for custom detectors on the request parameters. ``` addDetector('admin', ['param' => 'prefix', 'value' => 'admin']); ``` ### Accept comparison Allows for detector to compare against Accept header value. ``` addDetector('csv', ['accept' => 'text/csv']); ``` ### Header comparison Allows for one or more headers to be compared. ``` addDetector('fancy', ['header' => ['X-Fancy' => 1]); ``` The `param`, `env` and comparison types allow the following value comparison options: ### Pattern value comparison Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression. ``` addDetector('iphone', ['env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i']); ``` ### Option based comparison Option based comparisons use a list of options to create a regular expression. Subsequent calls to add an already defined options detector will merge the options. ``` addDetector('mobile', ['env' => 'HTTP_USER_AGENT', 'options' => ['Fennec']]); ``` You can also make compare against multiple values using the `options` key. This is useful when you want to check if a request value is in a list of options. `addDetector('extension', ['param' => '_ext', 'options' => ['pdf', 'csv']]` #### Parameters `string` $name The name of the detector. `callable|array` $detector A callable or options array for the detector definition. #### Returns `void` ### allowMethod() public ``` allowMethod(array<string>|string $methods): true ``` Allow only certain HTTP request methods, if the request method does not match a 405 error will be shown and the required "Allow" response header will be set. Example: $this->request->allowMethod('post'); or $this->request->allowMethod(['post', 'delete']); If the request would be GET, response header "Allow: POST, DELETE" will be set and a 405 error will be returned. #### Parameters `array<string>|string` $methods Allowed HTTP request methods. #### Returns `true` #### Throws `Cake\Http\Exception\MethodNotAllowedException` ### clearDetectorCache() public ``` clearDetectorCache(): void ``` Clears the instance detector cache, used by the is() function #### Returns `void` ### clientIp() public ``` clientIp(): string ``` Get the IP the client is using, or says they are using. #### Returns `string` ### contentType() public ``` contentType(): string|null ``` Get the content type used in this request. #### Returns `string|null` ### domain() public ``` domain(int $tldLength = 1): string ``` Get the domain name and include $tldLength segments of the tld. #### Parameters `int` $tldLength optional Number of segments your tld contains. For example: `example.com` contains 1 tld. While `example.co.uk` contains 2. #### Returns `string` ### getAttribute() public ``` getAttribute(string $name, mixed $default = null): mixed ``` Read an attribute from the request, or get the default Retrieves a single derived request attribute as described in getAttributes(). If the attribute has not been previously set, returns the default value as provided. This method obviates the need for a hasAttribute() method, as it allows specifying a default value to return if the attribute is not found. #### Parameters `string` $name The attribute name. `mixed` $default optional The default value if the attribute has not been set. #### Returns `mixed` ### getAttributes() public ``` getAttributes(): array<string, mixed> ``` Get all the attributes in the request. This will include the params, webroot, base, and here attributes that CakePHP provides. #### Returns `array<string, mixed>` ### getBody() public ``` getBody(): Psr\Http\Message\StreamInterface ``` Gets the body of the message. #### Returns `Psr\Http\Message\StreamInterface` ### getCookie() public ``` getCookie(string $key, array|string|null $default = null): array|string|null ``` Read cookie data from the request's cookie data. #### Parameters `string` $key The key or dotted path you want to read. `array|string|null` $default optional The default value if the cookie is not set. #### Returns `array|string|null` ### getCookieCollection() public ``` getCookieCollection(): Cake\Http\Cookie\CookieCollection ``` Get a cookie collection based on the request's cookies The CookieCollection lets you interact with request cookies using `\Cake\Http\Cookie\Cookie` objects and can make converting request cookies into response cookies easier. This method will create a new cookie collection each time it is called. This is an optimization that allows fewer objects to be allocated until the more complex CookieCollection is needed. In general you should prefer `getCookie()` and `getCookieParams()` over this method. Using a CookieCollection is ideal if your cookies contain complex JSON encoded data. #### Returns `Cake\Http\Cookie\CookieCollection` ### getCookieParams() public ``` getCookieParams(): array<string, mixed> ``` Get all the cookie data from the request. Retrieves cookies sent by the client to the server. The data MUST be compatible with the structure of the $\_COOKIE superglobal. #### Returns `array<string, mixed>` ### getData() public ``` getData(string|null $name = null, mixed $default = null): mixed ``` Provides a safe accessor for request data. Allows you to use Hash::get() compatible paths. ### Reading values. ``` // get all data $request->getData(); // Read a specific field. $request->getData('Post.title'); // With a default value. $request->getData('Post.not there', 'default value'); ``` When reading values you will get `null` for keys/values that do not exist. Developers are encouraged to use getParsedBody() if they need the whole data array, as it is PSR-7 compliant, and this method is not. Using Hash::get() you can also get single params. ### PSR-7 Alternative ``` $value = Hash::get($request->getParsedBody(), 'Post.id'); ``` #### Parameters `string|null` $name optional Dot separated name of the value to read. Or null to read all data. `mixed` $default optional The default data. #### Returns `mixed` ### getEnv() public ``` getEnv(string $key, string|null $default = null): string|null ``` Get a value from the request's environment data. Fallback to using env() if the key is not set in the $environment property. #### Parameters `string` $key The key you want to read from. `string|null` $default optional Default value when trying to retrieve an environment variable's value that does not exist. #### Returns `string|null` ### getFlash() public ``` getFlash(): Cake\Http\FlashMessage ``` Returns the instance of the FlashMessage object for this request #### Returns `Cake\Http\FlashMessage` ### getHeader() public ``` getHeader(string $name): array<string> ``` Get a single header from the request. Return the header value as an array. If the header is not present an empty array will be returned. #### Parameters `string` $name The header you want to get (case-insensitive) #### Returns `array<string>` #### Links https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface. ### getHeaderLine() public ``` getHeaderLine(string $name): string ``` Get a single header as a string from the request. 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 The header you want to get (case-insensitive) #### Returns `string` #### Links https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface. ### getHeaders() public ``` getHeaders(): array<string[]> ``` Get all headers in the request. Returns an associative array where the header names are the keys and the values are a list of header values. While header names are not case-sensitive, getHeaders() will normalize the headers. #### Returns `array<string[]>` #### Links https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface. ### getMethod() public ``` getMethod(): string ``` Get the HTTP method used for this request. There are a few ways to specify a method. * If your client supports it you can use native HTTP methods. * You can set the HTTP-X-Method-Override header. * You can submit an input with the name `_method` Any of these 3 approaches can be used to set the HTTP method used by CakePHP internally, and will effect the result of this method. #### Returns `string` #### Links https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface. ### getParam() public ``` getParam(string $name, mixed $default = null): mixed ``` Safely access the values in $this->params. #### Parameters `string` $name The name or dotted path to parameter. `mixed` $default optional The default value if `$name` is not set. Default `null`. #### Returns `mixed` ### getParsedBody() public ``` getParsedBody(): object|array|null ``` Get the parsed request body data. If the request Content-Type is either application/x-www-form-urlencoded or multipart/form-data, and the request method is POST, this will be the post data. For other content types, it may be the deserialized request body. #### Returns `object|array|null` ### getPath() public ``` getPath(): string ``` Get the path of current request. #### Returns `string` ### 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` ### getQuery() public ``` getQuery(string|null $name = null, mixed $default = null): array|string|null ``` Read a specific query value or dotted path. Developers are encouraged to use getQueryParams() if they need the whole query array, as it is PSR-7 compliant, and this method is not. Using Hash::get() you can also get single params. ### PSR-7 Alternative ``` $value = Hash::get($request->getQueryParams(), 'Post.id'); ``` #### Parameters `string|null` $name optional The name or dotted path to the query param or null to read all. `mixed` $default optional The default value if the named parameter is not set, and $name is not null. #### Returns `array|string|null` #### See Also ServerRequest::getQueryParams() ### getQueryParams() public ``` getQueryParams(): array ``` Get all the query parameters in accordance to the PSR-7 specifications. To read specific query values use the alternative getQuery() method. Retrieves the deserialized query string arguments, if any. Note: the query params might not be in sync with the URI or server params. If you need to ensure you are only getting the original values, you may need to parse the query string from `getUri()->getQuery()` or from the `QUERY_STRING` server param. #### Returns `array` #### Links https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface. ### getRequestTarget() public ``` getRequestTarget(): string ``` Retrieves the request's target. Retrieves the message's request-target either as it was requested, or as set with `withRequestTarget()`. By default this will return the application relative path without base directory, and the query string defined in the SERVER environment. #### Returns `string` ### getServerParams() public ``` getServerParams(): array ``` Get all the server environment parameters. Read all of the 'environment' or 'server' data that was used to create this request. #### Returns `array` #### Links https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface. ### getSession() public ``` getSession(): Cake\Http\Session ``` Returns the instance of the Session object for this request #### Returns `Cake\Http\Session` ### getTrustedProxies() public ``` getTrustedProxies(): array<string> ``` Get trusted proxies #### Returns `array<string>` ### getUploadedFile() public ``` getUploadedFile(string $path): Psr\Http\Message\UploadedFileInterface|null ``` Get the uploaded file from a dotted path. #### Parameters `string` $path The dot separated path to the file you want. #### Returns `Psr\Http\Message\UploadedFileInterface|null` ### getUploadedFiles() public ``` getUploadedFiles(): array ``` Get the array of uploaded files from the request. This method returns upload metadata in a normalized tree, with each leaf an instance of Psr\Http\Message\UploadedFileInterface. These values MAY be prepared from $\_FILES or the message body during instantiation, or MAY be injected via withUploadedFiles(). #### Returns `array` ### getUri() public ``` getUri(): Psr\Http\Message\UriInterface ``` Retrieves the URI instance. This method MUST return a UriInterface instance. #### Returns `Psr\Http\Message\UriInterface` ### hasHeader() public ``` hasHeader(string $name): bool ``` Check if a header is set in the request. #### Parameters `string` $name The header you want to get (case-insensitive) #### Returns `bool` #### Links https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface. ### host() public ``` host(): string|null ``` Get the host that the request was handled on. #### Returns `string|null` ### input() public ``` input(callable|null $callback = null, mixed ...$args): mixed ``` Read data from `php://input`. Useful when interacting with XML or JSON request body content. Getting input with a decoding function: ``` $this->request->input('json_decode'); ``` Getting input using a decoding function, and additional params: ``` $this->request->input('Xml::build', ['return' => 'DOMDocument']); ``` Any additional parameters are applied to the callback in the order they are given. #### Parameters `callable|null` $callback optional A decoding callback that will convert the string data to another representation. Leave empty to access the raw input data. You can also supply additional parameters for the decoding callback using var args, see above. `mixed` ...$args The additional arguments #### Returns `mixed` ### is() public ``` is(array<string>|string $type, mixed ...$args): bool ``` Check whether a Request is a certain type. Uses the built-in detection rules as well as additional rules defined with {@link \Cake\Http\ServerRequest::addDetector()}. Any detector can be called as `is($type)` or `is$Type()`. #### Parameters `array<string>|string` $type The type of request you want to check. If an array this method will return true if the request matches any type. `mixed` ...$args List of arguments #### Returns `bool` ### isAll() public ``` isAll(array<string> $types): bool ``` Check that a request matches all the given types. Allows you to test multiple types and union the results. See Request::is() for how to add additional types and the built-in types. #### Parameters `array<string>` $types The types to check. #### Returns `bool` #### See Also \Cake\Http\ServerRequest::is() ### normalizeHeaderName() protected ``` normalizeHeaderName(string $name): string ``` Normalize a header name into the SERVER version. #### Parameters `string` $name The header name. #### Returns `string` ### parseAccept() public ``` parseAccept(): array ``` Parse the HTTP\_ACCEPT header and return a sorted array with content types as the keys, and pref values as the values. Generally you want to use {@link \Cake\Http\ServerRequest::accepts()} to get a simple list of the accepted content types. #### Returns `array` ### port() public ``` port(): string|null ``` Get the port the request was handled on. #### Returns `string|null` ### processUrlOption() protected ``` processUrlOption(array<string, mixed> $config): array<string, mixed> ``` Set environment vars based on `url` option to facilitate UriInterface instance generation. `query` option is also updated based on URL's querystring. #### Parameters `array<string, mixed>` $config Config array. #### Returns `array<string, mixed>` ### referer() public ``` referer(bool $local = true): string|null ``` Returns the referer that referred this request. #### Parameters `bool` $local optional Attempt to return a local address. Local addresses do not contain hostnames. #### Returns `string|null` ### scheme() public ``` scheme(): string|null ``` Get the current url scheme used for the request. e.g. 'http', or 'https' #### Returns `string|null` ### setTrustedProxies() public ``` setTrustedProxies(array<string> $proxies): void ``` register trusted proxies #### Parameters `array<string>` $proxies ips list of trusted proxies #### Returns `void` ### subdomains() public ``` subdomains(int $tldLength = 1): array<string> ``` Get the subdomains for a host. #### Parameters `int` $tldLength optional Number of segments your tld contains. For example: `example.com` contains 1 tld. While `example.co.uk` contains 2. #### Returns `array<string>` ### validateUploadedFiles() protected ``` validateUploadedFiles(array $uploadedFiles, string $path): void ``` Recursively validate uploaded file data. #### Parameters `array` $uploadedFiles The new files array to validate. `string` $path The path thus far. #### Returns `void` #### Throws `InvalidArgumentException` If any leaf elements are not valid files. ### withAddedHeader() public ``` withAddedHeader(string $name, string|string[] $value): static ``` Get a modified request with the provided header. Existing header values will be retained. The provided value will be appended into the existing values. #### Parameters `string` $name The header name. `string|string[]` $value The header value #### Returns `static` #### Links https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface. ### withAttribute() public ``` withAttribute(string $name, mixed $value): static ``` Return an instance with the specified request attribute. This method allows setting a single derived request attribute as described in getAttributes(). 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 attribute. #### Parameters `string` $name The attribute name. `mixed` $value The value of the attribute. #### 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 The new request body #### Returns `static` ### withCookieCollection() public ``` withCookieCollection(Cake\Http\Cookie\CookieCollection $cookies): static ``` Replace the cookies in the request with those contained in the provided CookieCollection. #### Parameters `Cake\Http\Cookie\CookieCollection` $cookies The cookie collection #### Returns `static` ### withCookieParams() public ``` withCookieParams(array $cookies): static ``` Replace the cookies and get a new request instance. The data IS NOT REQUIRED to come from the $\_COOKIE superglobal, but MUST be compatible with the structure of $\_COOKIE. Typically, this data will be injected at instantiation. This method MUST NOT update the related Cookie header of the request instance, nor related values in the server params. 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 cookie values. #### Parameters `array` $cookies The new cookie data to use. #### Returns `static` ### withData() public ``` withData(string $name, mixed $value): static ``` Update the request with a new request data element. Returns an updated request object. This method returns a *new* request object and does not mutate the request in-place. Use `withParsedBody()` if you need to replace the all request data. #### Parameters `string` $name The dot separated path to insert $value at. `mixed` $value The value to insert into the request data. #### Returns `static` ### withEnv() public ``` withEnv(string $key, string $value): static ``` Update the request with a new environment data element. Returns an updated request object. This method returns a *new* request object and does not mutate the request in-place. #### Parameters `string` $key The key you want to write to. `string` $value Value to set #### Returns `static` ### withHeader() public ``` withHeader(string $name, string|string[] $value): static ``` Get a modified request with the provided header. 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 The header name. `string|string[]` $value The header value #### Returns `static` #### Links https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface. ### withMethod() public ``` withMethod(string $method): static ``` Update the request method and get a new instance. While HTTP method names are typically all uppercase characters, HTTP method names are case-sensitive and thus implementations SHOULD NOT modify the given string. 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 changed request method. #### Parameters `string` $method The HTTP method to use. #### Returns `static` #### Links https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface. ### withParam() public ``` withParam(string $name, mixed $value): static ``` Update the request with a new routing parameter Returns an updated request object. This method returns a *new* request object and does not mutate the request in-place. #### Parameters `string` $name The dot separated path to insert $value at. `mixed` $value The value to insert into the the request parameters. #### Returns `static` ### withParsedBody() public ``` withParsedBody(null|array|object $data): static ``` Update the parsed body and get a new instance. These MAY be injected during instantiation. If the request Content-Type is either application/x-www-form-urlencoded or multipart/form-data, and the request method is POST, use this method ONLY to inject the contents of $\_POST. The data IS NOT REQUIRED to come from $\_POST, but MUST be the results of deserializing the request body content. Deserialization/parsing returns structured data, and, as such, this method ONLY accepts arrays or objects, or a null value if nothing was available to parse. As an example, if content negotiation determines that the request data is a JSON payload, this method could be used to create a request instance with the deserialized parameters. 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 body parameters. #### Parameters `null|array|object` $data The deserialized body data. This will typically be in an array or object. #### 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"). #### Parameters `string` $version HTTP protocol version #### Returns `static` ### withQueryParams() public ``` withQueryParams(array $query): static ``` Update the query string data and get a new instance. These values SHOULD remain immutable over the course of the incoming request. They MAY be injected during instantiation, such as from PHP's $\_GET superglobal, or MAY be derived from some other value such as the URI. In cases where the arguments are parsed from the URI, the data MUST be compatible with what PHP's parse\_str() would return for purposes of how duplicate query parameters are handled, and how nested sets are handled. Setting query string arguments MUST NOT change the URI stored by the request, nor the values in the server params. 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 query string arguments. #### Parameters `array` $query The query string data to use #### Returns `static` #### Links https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface. ### withRequestTarget() public ``` withRequestTarget(mixed $requestTarget): static ``` Create a new instance with a specific request-target. You can use this method to overwrite the request target that is inferred from the request's Uri. This also lets you change the request target's form to an absolute-form, authority-form or asterisk-form #### Parameters `mixed` $requestTarget The request target. #### Returns `static` #### Links https://tools.ietf.org/html/rfc7230#section-2.7 (for the various request-target forms allowed in request messages) ### withUploadedFiles() public ``` withUploadedFiles(array $uploadedFiles): static ``` Update the request replacing the files, and creating a new instance. 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 body parameters. #### Parameters `array` $uploadedFiles An array of uploaded file objects. #### Returns `static` #### Throws `InvalidArgumentException` when $files contains an invalid object. ### withUri() public ``` withUri(UriInterface $uri, bool $preserveHost = false): static ``` Return an instance with the specified uri *Warning* Replacing the Uri will not update the `base`, `webroot`, and `url` attributes. #### Parameters `UriInterface` $uri The new request uri `bool` $preserveHost optional Whether the host should be retained. #### Returns `static` ### withoutAttribute() public ``` withoutAttribute(string $name): static ``` Return an instance without the specified request attribute. This method allows removing a single derived request attribute as described in getAttributes(). 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 attribute. #### Parameters `string` $name The attribute name. #### Returns `static` #### Throws `InvalidArgumentException` ### withoutData() public ``` withoutData(string $name): static ``` Update the request removing a data element. Returns an updated request object. This method returns a *new* request object and does not mutate the request in-place. #### Parameters `string` $name The dot separated path to remove. #### Returns `static` ### withoutHeader() public ``` withoutHeader(string $name): static ``` Get a modified request without a provided 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 The header name to remove. #### Returns `static` #### Links https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface. Property Detail --------------- ### $\_detectorCache protected Instance cache for results of is(something) calls #### Type `array<string, bool>` ### $\_detectors protected static The built in detectors used with `is()` can be modified with `addDetector()`. There are several ways to specify a detector, see \Cake\Http\ServerRequest::addDetector() for the various formats and ways to define detectors. #### Type `array<callable|array>` ### $\_environment protected Array of environment data. #### Type `array<string, mixed>` ### $attributes protected Store the additional attributes attached to the request. #### Type `array<string, mixed>` ### $base protected Base URL path. #### Type `string` ### $cookies protected Array of cookie data. #### Type `array<string, mixed>` ### $data protected Array of POST data. Will contain form data as well as uploaded files. In PUT/PATCH/DELETE requests this property will contain the form-urlencoded data. #### Type `object|array|null` ### $emulatedAttributes protected A list of properties that emulated by the PSR7 attribute methods. #### Type `array<string>` ### $flash protected Instance of a FlashMessage object relative to this request #### Type `Cake\Http\FlashMessage` ### $params protected Array of parameters parsed from the URL. #### Type `array` ### $protocol protected The HTTP protocol version used. #### Type `string|null` ### $query protected Array of query string arguments #### Type `array` ### $requestTarget protected The request target if overridden #### Type `string|null` ### $session protected Instance of a Session object relative to this request #### Type `Cake\Http\Session` ### $stream protected Request body stream. Contains php://input unless `input` constructor option is used. #### Type `Psr\Http\Message\StreamInterface` ### $trustProxy public Whether to trust HTTP\_X headers set by most load balancers. Only set to true if your application runs behind load balancers/proxies that you control. #### Type `bool` ### $trustedProxies protected Trusted proxies list #### Type `array<string>` ### $uploadedFiles protected Array of Psr\Http\Message\UploadedFileInterface objects. #### Type `array` ### $uri protected Uri instance #### Type `Psr\Http\Message\UriInterface` ### $webroot protected webroot path segment for the request. #### Type `string`
programming_docs
cakephp Class Marshaller Class Marshaller ================= Contains logic to convert array data into entities. Useful when converting request data into entities. **Namespace:** [Cake\ORM](namespace-cake.orm) **See:** \Cake\ORM\Table::newEntity() **See:** \Cake\ORM\Table::newEntities() **See:** \Cake\ORM\Table::patchEntity() **See:** \Cake\ORM\Table::patchEntities() Property Summary ---------------- * [$\_table](#%24_table) protected `Cake\ORM\Table` The table instance this marshaller is for. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [\_belongsToMany()](#_belongsToMany()) protected Marshals data for belongsToMany associations. * ##### [\_buildPropertyMap()](#_buildPropertyMap()) protected Build the map of property => marshalling callable. * ##### [\_loadAssociatedByIds()](#_loadAssociatedByIds()) protected Loads a list of belongs to many from ids. * ##### [\_marshalAssociation()](#_marshalAssociation()) protected Create a new sub-marshaller and marshal the associated data. * ##### [\_mergeAssociation()](#_mergeAssociation()) protected Creates a new sub-marshaller and merges the associated data. * ##### [\_mergeBelongsToMany()](#_mergeBelongsToMany()) protected Creates a new sub-marshaller and merges the associated data for a BelongstoMany association. * ##### [\_mergeJoinData()](#_mergeJoinData()) protected Merge the special \_joinData property into the entity set. * ##### [\_normalizeAssociations()](#_normalizeAssociations()) protected Returns an array out of the original passed associations list where dot notation is transformed into nested arrays so that they can be parsed by other routines * ##### [\_prepareDataAndOptions()](#_prepareDataAndOptions()) protected Returns data and options prepared to validate and marshall. * ##### [\_validate()](#_validate()) protected Returns the validation errors for a data set based on the passed options * ##### [dispatchAfterMarshal()](#dispatchAfterMarshal()) protected dispatch Model.afterMarshal event. * ##### [many()](#many()) public Hydrate many entities and their associated data. * ##### [merge()](#merge()) public Merges `$data` into `$entity` and recursively does the same for each one of the association names passed in `$options`. When merging associations, if an entity is not present in the parent entity for a given association, a new one will be created. * ##### [mergeMany()](#mergeMany()) public Merges each of the elements from `$data` into each of the entities in `$entities` and recursively does the same for each of the association names passed in `$options`. When merging associations, if an entity is not present in the parent entity for a given association, a new one will be created. * ##### [one()](#one()) public Hydrate one entity and its associated data. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\ORM\Table $table) ``` Constructor. #### Parameters `Cake\ORM\Table` $table The table this marshaller is for. ### \_belongsToMany() protected ``` _belongsToMany(Cake\ORM\Association\BelongsToMany $assoc, array $data, array<string, mixed> $options = []): arrayCake\Datasource\EntityInterface> ``` Marshals data for belongsToMany associations. Builds the related entities and handles the special casing for junction table entities. #### Parameters `Cake\ORM\Association\BelongsToMany` $assoc The association to marshal. `array` $data The data to convert into entities. `array<string, mixed>` $options optional List of options. #### Returns `arrayCake\Datasource\EntityInterface>` #### Throws `BadMethodCallException` `InvalidArgumentException` `RuntimeException` ### \_buildPropertyMap() protected ``` _buildPropertyMap(array $data, array<string, mixed> $options): array ``` Build the map of property => marshalling callable. #### Parameters `array` $data The data being marshalled. `array<string, mixed>` $options List of options containing the 'associated' key. #### Returns `array` #### Throws `InvalidArgumentException` When associations do not exist. ### \_loadAssociatedByIds() protected ``` _loadAssociatedByIds(Cake\ORM\Association $assoc, array $ids): arrayCake\Datasource\EntityInterface> ``` Loads a list of belongs to many from ids. #### Parameters `Cake\ORM\Association` $assoc The association class for the belongsToMany association. `array` $ids The list of ids to load. #### Returns `arrayCake\Datasource\EntityInterface>` ### \_marshalAssociation() protected ``` _marshalAssociation(Cake\ORM\Association $assoc, mixed $value, array<string, mixed> $options): Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface>|null ``` Create a new sub-marshaller and marshal the associated data. #### Parameters `Cake\ORM\Association` $assoc The association to marshall `mixed` $value The data to hydrate. If not an array, this method will return null. `array<string, mixed>` $options List of options. #### Returns `Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface>|null` ### \_mergeAssociation() protected ``` _mergeAssociation(Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface> $original, Cake\ORM\Association $assoc, mixed $value, array<string, mixed> $options): Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface>|null ``` Creates a new sub-marshaller and merges the associated data. #### Parameters `Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface>` $original The original entity `Cake\ORM\Association` $assoc The association to merge `mixed` $value The array of data to hydrate. If not an array, this method will return null. `array<string, mixed>` $options List of options. #### Returns `Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface>|null` ### \_mergeBelongsToMany() protected ``` _mergeBelongsToMany(arrayCake\Datasource\EntityInterface> $original, Cake\ORM\Association\BelongsToMany $assoc, array $value, array<string, mixed> $options): arrayCake\Datasource\EntityInterface> ``` Creates a new sub-marshaller and merges the associated data for a BelongstoMany association. #### Parameters `arrayCake\Datasource\EntityInterface>` $original The original entities list. `Cake\ORM\Association\BelongsToMany` $assoc The association to marshall `array` $value The data to hydrate `array<string, mixed>` $options List of options. #### Returns `arrayCake\Datasource\EntityInterface>` ### \_mergeJoinData() protected ``` _mergeJoinData(arrayCake\Datasource\EntityInterface> $original, Cake\ORM\Association\BelongsToMany $assoc, array $value, array<string, mixed> $options): arrayCake\Datasource\EntityInterface> ``` Merge the special \_joinData property into the entity set. #### Parameters `arrayCake\Datasource\EntityInterface>` $original The original entities list. `Cake\ORM\Association\BelongsToMany` $assoc The association to marshall `array` $value The data to hydrate `array<string, mixed>` $options List of options. #### Returns `arrayCake\Datasource\EntityInterface>` ### \_normalizeAssociations() protected ``` _normalizeAssociations(array|string $associations): array ``` Returns an array out of the original passed associations list where dot notation is transformed into nested arrays so that they can be parsed by other routines #### Parameters `array|string` $associations The array of included associations. #### Returns `array` ### \_prepareDataAndOptions() protected ``` _prepareDataAndOptions(array $data, array<string, mixed> $options): array ``` Returns data and options prepared to validate and marshall. #### Parameters `array` $data The data to prepare. `array<string, mixed>` $options The options passed to this marshaller. #### Returns `array` ### \_validate() protected ``` _validate(array $data, array<string, mixed> $options, bool $isNew): array ``` Returns the validation errors for a data set based on the passed options #### Parameters `array` $data The data to validate. `array<string, mixed>` $options The options passed to this marshaller. `bool` $isNew Whether it is a new entity or one to be updated. #### Returns `array` #### Throws `RuntimeException` If no validator can be created. ### dispatchAfterMarshal() protected ``` dispatchAfterMarshal(Cake\Datasource\EntityInterface $entity, array $data, array<string, mixed> $options = []): void ``` dispatch Model.afterMarshal event. #### Parameters `Cake\Datasource\EntityInterface` $entity The entity that was marshaled. `array` $data readOnly $data to use. `array<string, mixed>` $options optional List of options that are readOnly. #### Returns `void` ### many() public ``` many(array $data, array<string, mixed> $options = []): arrayCake\Datasource\EntityInterface> ``` Hydrate many entities and their associated data. ### Options: * validate: Set to false to disable validation. Can also be a string of the validator ruleset to be applied. Defaults to true/default. * associated: Associations listed here will be marshalled as well. Defaults to null. * fields: An allowed list of fields to be assigned to the entity. If not present, the accessible fields list in the entity will be used. Defaults to null. * accessibleFields: A list of fields to allow or deny in entity accessible fields. Defaults to null * forceNew: When enabled, belongsToMany associations will have 'new' entities created when primary key values are set, and a record does not already exist. Normally primary key on missing entities would be ignored. Defaults to false. #### Parameters `array` $data The data to hydrate. `array<string, mixed>` $options optional List of options #### Returns `arrayCake\Datasource\EntityInterface>` #### See Also \Cake\ORM\Table::newEntities() \Cake\ORM\Entity::$\_accessible ### merge() public ``` merge(Cake\Datasource\EntityInterface $entity, array $data, array<string, mixed> $options = []): Cake\Datasource\EntityInterface ``` Merges `$data` into `$entity` and recursively does the same for each one of the association names passed in `$options`. When merging associations, if an entity is not present in the parent entity for a given association, a new one will be created. When merging HasMany or BelongsToMany associations, all the entities in the `$data` array will appear, those that can be matched by primary key will get the data merged, but those that cannot, will be discarded. `ids` option can be used to determine whether the association must use the `_ids` format. ### Options: * associated: Associations listed here will be marshalled as well. * validate: Whether to validate data before hydrating the entities. Can also be set to a string to use a specific validator. Defaults to true/default. * fields: An allowed list of fields to be assigned to the entity. If not present the accessible fields list in the entity will be used. * accessibleFields: A list of fields to allow or deny in entity accessible fields. The above options can be used in each nested `associated` array. In addition to the above options you can also use the `onlyIds` option for HasMany and BelongsToMany associations. When true this option restricts the request data to only be read from `_ids`. ``` $result = $marshaller->merge($entity, $data, [ 'associated' => ['Tags' => ['onlyIds' => true]] ]); ``` #### 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 List of options. #### Returns `Cake\Datasource\EntityInterface` #### See Also \Cake\ORM\Entity::$\_accessible ### mergeMany() public ``` mergeMany(iterableCake\Datasource\EntityInterface> $entities, array $data, array<string, mixed> $options = []): arrayCake\Datasource\EntityInterface> ``` Merges each of the elements from `$data` into each of the entities in `$entities` and recursively does the same for each of the association names passed in `$options`. When merging associations, if an entity is not present in the parent entity for a given association, a new one will be created. Records in `$data` are matched against the entities using the primary key column. Entries in `$entities` that cannot be matched to any record in `$data` will be discarded. Records in `$data` that could not be matched will be marshalled as a new entity. When merging HasMany or BelongsToMany associations, all the entities in the `$data` array will appear, those that can be matched by primary key will get the data merged, but those that cannot, will be discarded. ### Options: * validate: Whether to validate data before hydrating the entities. Can also be set to a string to use a specific validator. Defaults to true/default. * associated: Associations listed here will be marshalled as well. * fields: An allowed list of fields to be assigned to the entity. If not present, the accessible fields list in the entity will be used. * accessibleFields: A list of fields to allow or deny in entity accessible fields. #### 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 List of options. #### Returns `arrayCake\Datasource\EntityInterface>` #### See Also \Cake\ORM\Entity::$\_accessible ### one() public ``` one(array $data, array<string, mixed> $options = []): Cake\Datasource\EntityInterface ``` Hydrate one entity and its associated data. ### Options: * validate: Set to false to disable validation. Can also be a string of the validator ruleset to be applied. Defaults to true/default. * associated: Associations listed here will be marshalled as well. Defaults to null. * fields: An allowed list of fields to be assigned to the entity. If not present, the accessible fields list in the entity will be used. Defaults to null. * accessibleFields: A list of fields to allow or deny in entity accessible fields. Defaults to null * forceNew: When enabled, belongsToMany associations will have 'new' entities created when primary key values are set, and a record does not already exist. Normally primary key on missing entities would be ignored. Defaults to false. The above options can be used in each nested `associated` array. In addition to the above options you can also use the `onlyIds` option for HasMany and BelongsToMany associations. When true this option restricts the request data to only be read from `_ids`. ``` $result = $marshaller->one($data, [ 'associated' => ['Tags' => ['onlyIds' => true]] ]); ``` ``` $result = $marshaller->one($data, [ 'associated' => [ 'Tags' => ['accessibleFields' => ['*' => true]] ] ]); ``` #### Parameters `array` $data The data to hydrate. `array<string, mixed>` $options optional List of options #### Returns `Cake\Datasource\EntityInterface` #### See Also \Cake\ORM\Table::newEntity() \Cake\ORM\Entity::$\_accessible Property Detail --------------- ### $\_table protected The table instance this marshaller is for. #### Type `Cake\ORM\Table` cakephp Class FunctionExpression Class 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. **Namespace:** [Cake\Database\Expression](namespace-cake.database.expression) Property Summary ---------------- * [$\_conditions](#%24_conditions) protected `array` A list of strings or other expression objects that represent the "branches" of the expression tree. For example one key of the array might look like "sum > :value" * [$\_conjunction](#%24_conjunction) protected `string` String to be used for joining each of the internal expressions this object internally stores for example "AND", "OR", etc. * [$\_name](#%24_name) protected `string` The name of the function to be constructed when generating the SQL string * [$\_returnType](#%24_returnType) protected `string` The type name this expression will return when executed * [$\_typeMap](#%24_typeMap) protected `Cake\Database\TypeMap|null` Method Summary -------------- * ##### [\_\_clone()](#__clone()) public Clone this object and its subtree of expressions. * ##### [\_\_construct()](#__construct()) public Constructor. Takes a name for the function to be invoked and a list of params to be passed into the function. Optionally you can pass a list of types to be used for each bound param. * ##### [\_addConditions()](#_addConditions()) protected Auxiliary function used for decomposing a nested array of conditions and build a tree structure inside this object to represent the full SQL expression. String conditions are stored directly in the conditions, while any other representation is wrapped around an adequate instance or of this class. * ##### [\_calculateType()](#_calculateType()) protected Returns the type name for the passed field if it was stored in the typeMap * ##### [\_castToExpression()](#_castToExpression()) protected Conditionally converts the passed value to an ExpressionInterface object if the type class implements the ExpressionTypeInterface. Otherwise, returns the value unmodified. * ##### [\_parseCondition()](#_parseCondition()) protected Parses a string conditions by trying to extract the operator inside it if any and finally returning either an adequate QueryExpression object or a plain string representation of the condition. This function is responsible for generating the placeholders and replacing the values by them, while storing the value elsewhere for future binding. * ##### [\_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 arguments for the function call. * ##### [addCase()](#addCase()) public deprecated Adds a new case expression to the expression object * ##### [and()](#and()) public Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "AND" * ##### [and\_()](#and_()) public deprecated Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "AND" * ##### [between()](#between()) public Adds a new condition to the expression object in the form "field BETWEEN from AND to". * ##### [case()](#case()) public Returns a new case expression object. * ##### [count()](#count()) public The name of the function is in itself an expression to generate, thus always adding 1 to the amount of expressions stored in this object. * ##### [eq()](#eq()) public Adds a new condition to the expression object in the form "field = value". * ##### [equalFields()](#equalFields()) public Builds equal condition or assignment with identifier wrapping. * ##### [exists()](#exists()) public Adds a new condition to the expression object in the form "EXISTS (...)". * ##### [getConjunction()](#getConjunction()) public Gets the currently configured conjunction for the conditions at this level of the expression tree. * ##### [getDefaultTypes()](#getDefaultTypes()) public Gets default types of current type map. * ##### [getName()](#getName()) public Gets the name of the SQL function to be invoke in this expression. * ##### [getReturnType()](#getReturnType()) public Gets the type of the value this object will generate. * ##### [getTypeMap()](#getTypeMap()) public Returns the existing type map. * ##### [gt()](#gt()) public Adds a new condition to the expression object in the form "field > value". * ##### [gte()](#gte()) public Adds a new condition to the expression object in the form "field >= value". * ##### [hasNestedExpression()](#hasNestedExpression()) public Returns true if this expression contains any other nested ExpressionInterface objects * ##### [in()](#in()) public Adds a new condition to the expression object in the form "field IN (value1, value2)". * ##### [isCallable()](#isCallable()) public deprecated Check whether a callable is acceptable. * ##### [isNotNull()](#isNotNull()) public Adds a new condition to the expression object in the form "field IS NOT NULL". * ##### [isNull()](#isNull()) public Adds a new condition to the expression object in the form "field IS NULL". * ##### [iterateParts()](#iterateParts()) public Executes a callable function for each of the parts that form this expression. * ##### [like()](#like()) public Adds a new condition to the expression object in the form "field LIKE value". * ##### [lt()](#lt()) public Adds a new condition to the expression object in the form "field < value". * ##### [lte()](#lte()) public Adds a new condition to the expression object in the form "field <= value". * ##### [not()](#not()) public Adds a new set of conditions to this level of the tree and negates the final result by prepending a NOT, it will look like "NOT ( (condition1) AND (conditions2) )" conjunction depends on the one currently configured for this object. * ##### [notEq()](#notEq()) public Adds a new condition to the expression object in the form "field != value". * ##### [notExists()](#notExists()) public Adds a new condition to the expression object in the form "NOT EXISTS (...)". * ##### [notIn()](#notIn()) public Adds a new condition to the expression object in the form "field NOT IN (value1, value2)". * ##### [notInOrNull()](#notInOrNull()) public Adds a new condition to the expression object in the form "(field NOT IN (value1, value2) OR field IS NULL". * ##### [notLike()](#notLike()) public Adds a new condition to the expression object in the form "field NOT LIKE value". * ##### [or()](#or()) public Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "OR" * ##### [or\_()](#or_()) public deprecated Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "OR" * ##### [setConjunction()](#setConjunction()) public Changes the conjunction for the conditions at this level of the expression tree. * ##### [setDefaultTypes()](#setDefaultTypes()) public Overwrite the default type mappings for fields in the implementing object. * ##### [setName()](#setName()) public Sets the name of the SQL function to be invoke in this expression. * ##### [setReturnType()](#setReturnType()) public Sets the type of the value this object will generate. * ##### [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. * ##### [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, array $params = [], array<string, string>|array<string|null> $types = [], string $returnType = 'string') ``` Constructor. Takes a name for the function to be invoked and a list of params to be passed into the function. Optionally you can pass a list of types to be used for each bound param. By default, all params that are passed will be quoted. If you wish to use literal arguments, you need to explicitly hint this function. ### Examples: `$f = new FunctionExpression('CONCAT', ['CakePHP', ' rules']);` Previous line will generate `CONCAT('CakePHP', ' rules')` `$f = new FunctionExpression('CONCAT', ['name' => 'literal', ' rules']);` Will produce `CONCAT(name, ' rules')` #### Parameters `string` $name the name of the function to be constructed `array` $params optional list of arguments to be passed to the function If associative the key would be used as argument when value is 'literal' `array<string, string>|array<string|null>` $types optional Associative array of types to be associated with the passed arguments `string` $returnType optional The return type of this expression ### \_addConditions() protected ``` _addConditions(array $conditions, array<int|string, string> $types): void ``` Auxiliary function used for decomposing a nested array of conditions and build a tree structure inside this object to represent the full SQL expression. String conditions are stored directly in the conditions, while any other representation is wrapped around an adequate instance or of this class. #### Parameters `array` $conditions list of conditions to be stored in this object `array<int|string, string>` $types list of types associated on fields referenced in $conditions #### Returns `void` ### \_calculateType() protected ``` _calculateType(Cake\Database\ExpressionInterface|string $field): string|null ``` Returns the type name for the passed field if it was stored in the typeMap #### Parameters `Cake\Database\ExpressionInterface|string` $field The field name to get a type for. #### Returns `string|null` ### \_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` ### \_parseCondition() protected ``` _parseCondition(string $field, mixed $value): Cake\Database\ExpressionInterface ``` Parses a string conditions by trying to extract the operator inside it if any and finally returning either an adequate QueryExpression object or a plain string representation of the condition. This function is responsible for generating the placeholders and replacing the values by them, while storing the value elsewhere for future binding. #### Parameters `string` $field The value from which the actual field and operator will be extracted. `mixed` $value The value to be bound to a placeholder for the field #### Returns `Cake\Database\ExpressionInterface` #### Throws `InvalidArgumentException` If operator is invalid or missing on NULL usage. ### \_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(array $conditions, array<string, string> $types = [], bool $prepend = false): $this ``` Adds one or more arguments for the function call. #### Parameters `array` $conditions list of arguments to be passed to the function If associative the key would be used as argument when value is 'literal' `array<string, string>` $types optional Associative array of types to be associated with the passed arguments `bool` $prepend optional Whether to prepend or append to the list of arguments #### Returns `$this` #### See Also \Cake\Database\Expression\FunctionExpression::\_\_construct() for more details. ### addCase() public ``` addCase(Cake\Database\ExpressionInterface|array $conditions, Cake\Database\ExpressionInterface|array $values = [], array<string> $types = []): $this ``` Adds a new case expression to the expression object #### Parameters `Cake\Database\ExpressionInterface|array` $conditions 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 #### Returns `$this` ### and() public ``` and(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "AND" #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be joined with AND `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `Cake\Database\Expression\QueryExpression` ### and\_() public ``` and_(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "AND" #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be joined with AND `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `Cake\Database\Expression\QueryExpression` ### between() public ``` between(Cake\Database\ExpressionInterface|string $field, mixed $from, mixed $to, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field BETWEEN from AND to". #### 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 type name for $value as configured using the Type map. #### Returns `$this` ### case() public ``` case(Cake\Database\ExpressionInterface|object|scalar|null $value = null, string|null $type = null): Cake\Database\Expression\CaseStatementExpression ``` Returns a new case expression object. 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. #### Returns `Cake\Database\Expression\CaseStatementExpression` ### count() public ``` count(): int ``` The name of the function is in itself an expression to generate, thus always adding 1 to the amount of expressions stored in this object. #### Returns `int` ### eq() public ``` eq(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field = value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. If it is suffixed with "[]" and the value is an array then multiple placeholders will be created, one per each value in the array. #### Returns `$this` ### equalFields() public ``` equalFields(string $leftField, string $rightField): $this ``` Builds equal condition or assignment with identifier wrapping. #### Parameters `string` $leftField Left join condition field name. `string` $rightField Right join condition field name. #### Returns `$this` ### exists() public ``` exists(Cake\Database\ExpressionInterface $expression): $this ``` Adds a new condition to the expression object in the form "EXISTS (...)". #### Parameters `Cake\Database\ExpressionInterface` $expression the inner query #### Returns `$this` ### getConjunction() public ``` getConjunction(): string ``` Gets the currently configured conjunction for the conditions at this level of the expression tree. #### Returns `string` ### getDefaultTypes() public ``` getDefaultTypes(): array<int|string, string> ``` Gets default types of current type map. #### Returns `array<int|string, string>` ### getName() public ``` getName(): string ``` Gets the name of the SQL function to be invoke in this expression. #### Returns `string` ### getReturnType() public ``` getReturnType(): string ``` Gets the type of the value this object will generate. #### Returns `string` ### getTypeMap() public ``` getTypeMap(): Cake\Database\TypeMap ``` Returns the existing type map. #### Returns `Cake\Database\TypeMap` ### gt() public ``` gt(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field > value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### gte() public ``` gte(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field >= value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### hasNestedExpression() public ``` hasNestedExpression(): bool ``` Returns true if this expression contains any other nested ExpressionInterface objects #### Returns `bool` ### in() public ``` in(Cake\Database\ExpressionInterface|string $field, Cake\Database\ExpressionInterface|array|string $values, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field IN (value1, value2)". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `Cake\Database\ExpressionInterface|array|string` $values the value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### isCallable() public ``` isCallable(Cake\Database\ExpressionInterface|callable|array|string $callable): bool ``` Check whether a callable is acceptable. We don't accept ['class', 'method'] style callbacks, as they often contain user input and arrays of strings are easy to sneak in. #### Parameters `Cake\Database\ExpressionInterface|callable|array|string` $callable The callable to check. #### Returns `bool` ### isNotNull() public ``` isNotNull(Cake\Database\ExpressionInterface|string $field): $this ``` Adds a new condition to the expression object in the form "field IS NOT NULL". #### Parameters `Cake\Database\ExpressionInterface|string` $field database field to be tested for not null #### Returns `$this` ### isNull() public ``` isNull(Cake\Database\ExpressionInterface|string $field): $this ``` Adds a new condition to the expression object in the form "field IS NULL". #### Parameters `Cake\Database\ExpressionInterface|string` $field database field to be tested for null #### Returns `$this` ### iterateParts() public ``` iterateParts(callable $callback): $this ``` Executes a callable function for each of the parts that form this expression. The callable function is required to return a value with which the currently visited part will be replaced. If the callable function returns null then the part will be discarded completely from this expression. The callback function will receive each of the conditions as first param and the key as second param. It is possible to declare the second parameter as passed by reference, this will enable you to change the key under which the modified part is stored. #### Parameters `callable` $callback The callable to apply to each part. #### Returns `$this` ### like() public ``` like(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field LIKE value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### lt() public ``` lt(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field < value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### lte() public ``` lte(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field <= value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### not() public ``` not(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): $this ``` Adds a new set of conditions to this level of the tree and negates the final result by prepending a NOT, it will look like "NOT ( (condition1) AND (conditions2) )" conjunction depends on the one currently configured for this object. #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be added and negated `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `$this` ### notEq() public ``` notEq(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field != value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. If it is suffixed with "[]" and the value is an array then multiple placeholders will be created, one per each value in the array. #### Returns `$this` ### notExists() public ``` notExists(Cake\Database\ExpressionInterface $expression): $this ``` Adds a new condition to the expression object in the form "NOT EXISTS (...)". #### Parameters `Cake\Database\ExpressionInterface` $expression the inner query #### Returns `$this` ### notIn() public ``` notIn(Cake\Database\ExpressionInterface|string $field, Cake\Database\ExpressionInterface|array|string $values, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field NOT IN (value1, value2)". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `Cake\Database\ExpressionInterface|array|string` $values the value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### notInOrNull() public ``` notInOrNull(Cake\Database\ExpressionInterface|string $field, Cake\Database\ExpressionInterface|array|string $values, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "(field NOT IN (value1, value2) OR field IS NULL". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `Cake\Database\ExpressionInterface|array|string` $values the value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### notLike() public ``` notLike(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field NOT LIKE value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### or() public ``` or(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "OR" #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be joined with OR `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `Cake\Database\Expression\QueryExpression` ### or\_() public ``` or_(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "OR" #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be joined with OR `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `Cake\Database\Expression\QueryExpression` ### setConjunction() public ``` setConjunction(string $conjunction): $this ``` Changes the conjunction for the conditions at this level of the expression tree. #### Parameters `string` $conjunction Value to be used for joining conditions #### 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() ### setName() public ``` setName(string $name): $this ``` Sets the name of the SQL function to be invoke in this expression. #### Parameters `string` $name The name of the function #### Returns `$this` ### setReturnType() public ``` setReturnType(string $type): $this ``` Sets the type of the value this object will generate. #### Parameters `string` $type The name of the type that is to be returned #### 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` ### 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 "branches" of the expression tree. For example one key of the array might look like "sum > :value" #### Type `array` ### $\_conjunction protected String to be used for joining each of the internal expressions this object internally stores for example "AND", "OR", etc. #### Type `string` ### $\_name protected The name of the function to be constructed when generating the SQL string #### Type `string` ### $\_returnType protected The type name this expression will return when executed #### Type `string` ### $\_typeMap protected #### Type `Cake\Database\TypeMap|null`
programming_docs
cakephp Class SerializedView Class SerializedView ===================== Parent class for view classes generating serialized outputs like JsonView and XmlView. **Abstract** **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` The name of the layouts subfolder containing layouts for this View. * [$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` Sub-directory for this template file. This is often used for extension based routing. Eg. With an `xml` extension, $subDir would be `xml/` * [$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()) abstract 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() abstract protected ``` _serialize(array|string $serialize): string ``` Serialize view vars. #### Parameters `array|string` $serialize The name(s) of the view variable(s) that need(s) to be serialized #### 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 controlle 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. #### 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 The name of the layouts subfolder containing layouts for this View. #### 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 Sub-directory for this template file. This is often used for extension based routing. Eg. With an `xml` extension, $subDir would be `xml/` #### 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 CheckboxWidget Class CheckboxWidget ===================== Input widget for creating checkbox widgets. This class is usually used internally by `Cake\View\Helper\FormHelper`, it but can be used to generate standalone checkboxes. **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. * ##### [\_isChecked()](#_isChecked()) protected Checks whether the checkbox should be checked. * ##### [mergeDefaults()](#mergeDefaults()) protected Merge default values with supplied data. * ##### [render()](#render()) public Render a checkbox element. * ##### [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. ### \_isChecked() protected ``` _isChecked(array<string, mixed> $data): bool ``` Checks whether the checkbox should be checked. #### Parameters `array<string, mixed>` $data Data to look at and determine checked state. #### Returns `bool` ### 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 checkbox element. Data supports the following keys: * `name` - The name of the input. * `value` - The value attribute. Defaults to '1'. * `val` - The current value. If it matches `value` the checkbox will be checked. You can also use the 'checked' attribute to make the checkbox checked. * `disabled` - Whether the checkbox should be disabled. Any other attributes passed in will be treated as HTML attributes. #### Parameters `array<string, mixed>` $data The data to create a checkbox 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 CspMiddleware Class CspMiddleware ==================== Content Security Policy Middleware ### Options * `scriptNonce` Enable to have a nonce policy added to the script-src directive. * `styleNonce` Enable to have a nonce policy added to the style-src directive. **Namespace:** [Cake\Http\Middleware](namespace-cake.http.middleware) 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. * [$csp](#%24csp) protected `ParagonIE\CSPBuilder\CSPBuilder` CSP Builder 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. * ##### [getConfig()](#getConfig()) public Returns the config. * ##### [getConfigOrFail()](#getConfigOrFail()) public Returns the config for this specific key. * ##### [process()](#process()) public Add nonces (if enabled) to the request and apply the CSP header to the response. * ##### [setConfig()](#setConfig()) public Sets the config. Method Detail ------------- ### \_\_construct() public ``` __construct(ParagonIE\CSPBuilder\CSPBuilder|array $csp, array<string, mixed> $config = []) ``` Constructor #### Parameters `ParagonIE\CSPBuilder\CSPBuilder|array` $csp CSP object or config array `array<string, mixed>` $config optional Configuration options. #### Throws `RuntimeException` ### \_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` ### 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` ### process() public ``` process(ServerRequestInterface $request, RequestHandlerInterface $handler): Psr\Http\Message\ResponseInterface ``` Add nonces (if enabled) to the request and apply the CSP header to the response. 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` ### 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 Configuration options. #### Type `array<string, mixed>` ### $csp protected CSP Builder #### Type `ParagonIE\CSPBuilder\CSPBuilder` cakephp Class YearWidget Class YearWidget ================= Input widget class for generating a calendar year select box. This class is usually used internally by `Cake\View\Helper\FormHelper`, it but can be used to generate standalone calendar year select boxes. **Namespace:** [Cake\View\Widget](namespace-cake.view.widget) Property Summary ---------------- * [$\_select](#%24_select) protected `Cake\View\Widget\SelectBoxWidget` Select box widget. * [$\_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 Renders a year select box. * ##### [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, Cake\View\Widget\SelectBoxWidget $selectBox) ``` Constructor #### Parameters `Cake\View\StringTemplate` $templates Templates list. `Cake\View\Widget\SelectBoxWidget` $selectBox Selectbox widget instance. ### 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 ``` Renders a year select box. This method accepts a number of keys: * `name` The name attribute. * `val` The value attribute. * `escape` Set to false to disable escaping on all attributes. Any other keys provided in $data will be converted into HTML attributes. #### Parameters `array<string, mixed>` $data Data to render 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 --------------- ### $\_select protected Select box widget. #### Type `Cake\View\Widget\SelectBoxWidget` ### $\_templates protected StringTemplate instance. #### Type `Cake\View\StringTemplate` ### $defaults protected Data defaults. #### Type `array<string, mixed>` cakephp Class HelperRegistry Class HelperRegistry ===================== Registry for Helpers. Provides features for lazily loading helpers. **Namespace:** [Cake\Console](namespace-cake.console) Property Summary ---------------- * [$\_io](#%24_io) protected `Cake\Console\ConsoleIo` Shell to use to set params to tasks. * [$\_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 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. * ##### [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. * ##### [setIo()](#setIo()) public Sets The IO instance that should be passed to the shell helpers * ##### [unload()](#unload()) public Remove an object 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\Console\Helper ``` Create the helper 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 helper. `array<string, mixed>` $config An array of settings to use for the helper. #### Returns `Cake\Console\Helper` ### \_resolveClassName() protected ``` _resolveClassName(string $class): string|null ``` Resolve a helper classname. Will prefer helpers defined in Command\Helper over those defined in Shell\Helper. 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 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\Console\Exception\MissingHelperException` ### 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` ### setIo() public ``` setIo(Cake\Console\ConsoleIo $io): void ``` Sets The IO instance that should be passed to the shell helpers #### Parameters `Cake\Console\ConsoleIo` $io An io instance. #### 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 --------------- ### $\_io protected Shell to use to set params to tasks. #### Type `Cake\Console\ConsoleIo` ### $\_loaded protected Map of loaded objects. #### Type `array<object>`
programming_docs
cakephp Class MissingCellException Class MissingCellException =========================== Used when a cell class 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()} 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 BinaryUuidType Class BinaryUuidType ===================== Binary UUID type converter. Use to convert binary uuid 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 * ##### [convertBinaryUuidToString()](#convertBinaryUuidToString()) protected Converts a binary uuid to a string representation * ##### [convertStringToBinaryUuid()](#convertStringToBinaryUuid()) protected Converts a string UUID (36 or 32 char) to a binary representation. * ##### [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 binary UUID * ##### [toDatabase()](#toDatabase()) public Convert binary uuid data into the database format. * ##### [toPHP()](#toPHP()) public Convert binary uuid 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 ### convertBinaryUuidToString() protected ``` convertBinaryUuidToString(mixed $binary): string ``` Converts a binary uuid to a string representation #### Parameters `mixed` $binary The value to convert. #### Returns `string` ### convertStringToBinaryUuid() protected ``` convertStringToBinaryUuid(string $string): string ``` Converts a string UUID (36 or 32 char) to a binary representation. #### Parameters `string` $string The value to convert. #### 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` ### 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(): string ``` Generate a new binary UUID This method can be used by types to create new primary key values when entities are inserted. #### Returns `string` ### toDatabase() public ``` toDatabase(mixed $value, Cake\Database\DriverInterface $driver): resource|string|null ``` Convert binary uuid 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|null` ### toPHP() public ``` toPHP(mixed $value, Cake\Database\DriverInterface $driver): resource|string|null ``` Convert binary uuid into resource handles #### Parameters `mixed` $value The value to convert. `Cake\Database\DriverInterface` $driver The driver instance to convert with. #### Returns `resource|string|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 ComparisonExpression Class 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` **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 `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 * ##### [getField()](#getField()) public Returns the field name * ##### [getOperator()](#getOperator()) public Returns the operator used for comparison * ##### [getValue()](#getValue()) public Returns the value used for comparison * ##### [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|string $field, mixed $value, string|null $type = null, string $operator = '=') ``` Constructor #### Parameters `Cake\Database\ExpressionInterface|string` $field the field name to compare to a value `mixed` $value The value to be used in comparison `string|null` $type optional the type name used to cast the value `string` $operator 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 The value to bind `Cake\Database\ValueBinder` $binder The value binder to use `string|null` $type optional 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` ### \_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` ### 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` ### getValue() public ``` getValue(): mixed ``` Returns the value used for comparison #### Returns `mixed` ### 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 `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 ErrorHandlerMiddleware Class ErrorHandlerMiddleware ============================= Error handling middleware. Traps exceptions and converts them into HTML or content-type appropriate error pages using the CakePHP ExceptionRenderer. **Namespace:** [Cake\Error\Middleware](namespace-cake.error.middleware) 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 values. * [$errorHandler](#%24errorHandler) protected `Cake\Error\ErrorHandler|null` Error handler instance. * [$exceptionTrap](#%24exceptionTrap) protected `Cake\Error\ExceptionTrap|null` ExceptionTrap 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. * ##### [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. * ##### [getErrorHandler()](#getErrorHandler()) protected Get a error handler instance * ##### [getExceptionTrap()](#getExceptionTrap()) protected Get a exception trap instance * ##### [handleException()](#handleException()) public Handle an exception and generate an error response * ##### [handleInternalError()](#handleInternalError()) protected Handle internal errors. * ##### [handleRedirect()](#handleRedirect()) public Convert a redirect exception into a response. * ##### [process()](#process()) public Wrap the remaining middleware with error handling. * ##### [setConfig()](#setConfig()) public Sets the config. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\Error\ErrorHandlerCake\Error\ExceptionTrap|array $errorHandler = []) ``` Constructor #### Parameters `Cake\Error\ErrorHandlerCake\Error\ExceptionTrap|array` $errorHandler optional The error handler instance or config array. #### 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 ### 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` ### getErrorHandler() protected ``` getErrorHandler(): Cake\Error\ErrorHandler ``` Get a error handler instance #### Returns `Cake\Error\ErrorHandler` ### getExceptionTrap() protected ``` getExceptionTrap(): Cake\Error\ExceptionTrap ``` Get a exception trap instance #### Returns `Cake\Error\ExceptionTrap` ### handleException() public ``` handleException(Throwable $exception, Psr\Http\Message\ServerRequestInterface $request): Psr\Http\Message\ResponseInterface ``` Handle an exception and generate an error response #### Parameters `Throwable` $exception The exception to handle. `Psr\Http\Message\ServerRequestInterface` $request The request. #### Returns `Psr\Http\Message\ResponseInterface` ### handleInternalError() protected ``` handleInternalError(): Psr\Http\Message\ResponseInterface ``` Handle internal errors. #### Returns `Psr\Http\Message\ResponseInterface` ### handleRedirect() public ``` handleRedirect(Cake\Http\Exception\RedirectException $exception): Psr\Http\Message\ResponseInterface ``` Convert a redirect exception into a response. #### Parameters `Cake\Http\Exception\RedirectException` $exception The exception to handle #### Returns `Psr\Http\Message\ResponseInterface` ### process() public ``` process(ServerRequestInterface $request, RequestHandlerInterface $handler): Psr\Http\Message\ResponseInterface ``` Wrap the remaining middleware with error handling. 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` ### 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 configuration values. Ignored if contructor is passed an ExceptionTrap instance. Configuration keys and values are shared with `ExceptionTrap`. This class will pass its configuration onto the ExceptionTrap class if you are using the array style constructor. #### Type `array<string, mixed>` ### $errorHandler protected Error handler instance. #### Type `Cake\Error\ErrorHandler|null` ### $exceptionTrap protected ExceptionTrap instance #### Type `Cake\Error\ExceptionTrap|null`
programming_docs
cakephp Class ServiceProvider Class ServiceProvider ====================== Container ServiceProvider Service provider bundle related services together helping to organize your application's dependencies. They also help improve performance of applications with many services by allowing service registration to be deferred until services are needed. **Abstract** **Namespace:** [Cake\Core](namespace-cake.core) Property Summary ---------------- * [$container](#%24container) protected `?DefinitionContainerInterface` * [$identifier](#%24identifier) protected `string` * [$provides](#%24provides) protected `array<string>` List of ids of services this provider provides. Method Summary -------------- * ##### [boot()](#boot()) public Delegate to the bootstrap() method * ##### [bootstrap()](#bootstrap()) public Bootstrap hook for ServiceProviders * ##### [getContainer()](#getContainer()) public Get the container. * ##### [getIdentifier()](#getIdentifier()) public * ##### [provides()](#provides()) public The provides method is a way to let the container know that a service is provided by this service provider. * ##### [register()](#register()) public Call the abstract services() method. * ##### [services()](#services()) abstract public Register the services in a provider. * ##### [setContainer()](#setContainer()) public * ##### [setIdentifier()](#setIdentifier()) public Method Detail ------------- ### boot() public ``` boot(): void ``` Delegate to the bootstrap() method This method wraps the league/container function so users only need to use the CakePHP bootstrap() interface. #### Returns `void` ### bootstrap() public ``` bootstrap(Cake\Core\ContainerInterface $container): void ``` Bootstrap hook for ServiceProviders This hook should be implemented if your service provider needs to register additional service providers, load configuration files or do any other work when the service provider is added to the container. #### Parameters `Cake\Core\ContainerInterface` $container The container to add services to. #### Returns `void` ### getContainer() public ``` getContainer(): Cake\Core\ContainerInterface ``` Get the container. This method's actual return type and documented return type differ because PHP 7.2 doesn't support return type narrowing. #### Returns `Cake\Core\ContainerInterface` ### getIdentifier() public ``` getIdentifier(): string ``` #### Returns `string` ### provides() public ``` provides(string $id): bool ``` The provides method is a way to let the container know that a service is provided by this service provider. Every service that is registered via this service provider must have an alias added to this array or it will be ignored. #### Parameters `string` $id Identifier. #### Returns `bool` ### register() public ``` register(): void ``` Call the abstract services() method. This method primarily exists as a shim between the interface that league/container has and the one we want to offer in CakePHP. #### Returns `void` ### services() abstract public ``` services(Cake\Core\ContainerInterface $container): void ``` Register the services in a provider. All services registered in this method should also be included in the $provides property so that services can be located. #### Parameters `Cake\Core\ContainerInterface` $container The container to add services to. #### Returns `void` ### setContainer() public ``` setContainer(DefinitionContainerInterface $container): ContainerAwareInterface ``` #### Parameters `DefinitionContainerInterface` $container #### Returns `ContainerAwareInterface` ### setIdentifier() public ``` setIdentifier(string $id): ServiceProviderInterface ``` #### Parameters `string` $id #### Returns `ServiceProviderInterface` Property Detail --------------- ### $container protected #### Type `?DefinitionContainerInterface` ### $identifier protected #### Type `string` ### $provides protected List of ids of services this provider provides. #### Type `array<string>` cakephp Class ClassLoader Class ClassLoader ================== ClassLoader **Namespace:** [Cake\Core](namespace-cake.core) **Deprecated:** 4.0.3 Use composer to generate autoload files instead. Property Summary ---------------- * [$\_prefixes](#%24_prefixes) protected `array<string, array>` An associative array where the key is a namespace prefix and the value is an array of base directories for classes in that namespace. Method Summary -------------- * ##### [\_loadMappedFile()](#_loadMappedFile()) protected Load the mapped file for a namespace prefix and relative class. * ##### [\_requireFile()](#_requireFile()) protected If a file exists, require it from the file system. * ##### [addNamespace()](#addNamespace()) public Adds a base directory for a namespace prefix. * ##### [loadClass()](#loadClass()) public Loads the class file for a given class name. * ##### [register()](#register()) public Register loader with SPL autoloader stack. Method Detail ------------- ### \_loadMappedFile() protected ``` _loadMappedFile(string $prefix, string $relativeClass): string|false ``` Load the mapped file for a namespace prefix and relative class. #### Parameters `string` $prefix The namespace prefix. `string` $relativeClass The relative class name. #### Returns `string|false` ### \_requireFile() protected ``` _requireFile(string $file): bool ``` If a file exists, require it from the file system. #### Parameters `string` $file The file to require. #### Returns `bool` ### addNamespace() public ``` addNamespace(string $prefix, string $baseDir, bool $prepend = false): void ``` Adds a base directory for a namespace prefix. #### Parameters `string` $prefix The namespace prefix. `string` $baseDir A base directory for class files in the namespace. `bool` $prepend optional If true, prepend the base directory to the stack instead of appending it; this causes it to be searched first rather than last. #### Returns `void` ### loadClass() public ``` loadClass(string $class): string|false ``` Loads the class file for a given class name. #### Parameters `string` $class The fully-qualified class name. #### Returns `string|false` ### register() public ``` register(): void ``` Register loader with SPL autoloader stack. #### Returns `void` Property Detail --------------- ### $\_prefixes protected An associative array where the key is a namespace prefix and the value is an array of base directories for classes in that namespace. #### Type `array<string, array>` cakephp Class ConsoleIo Class ConsoleIo ================ A wrapper around the various IO operations shell tasks need to do. Packages up the stdout, stderr, and stdin streams providing a simple consistent interface for shells to use. This class also makes mocking streams easy to do in unit tests. **Namespace:** [Cake\Console](namespace-cake.console) Constants --------- * `int` **NORMAL** ``` 1 ``` Output constant for making normal shells. * `int` **QUIET** ``` 0 ``` Output constants for making quiet shells. * `int` **VERBOSE** ``` 2 ``` Output constant making verbose shells. Property Summary ---------------- * [$\_err](#%24_err) protected `Cake\Console\ConsoleOutput` The error stream * [$\_helpers](#%24_helpers) protected `Cake\Console\HelperRegistry` The helper registry. * [$\_in](#%24_in) protected `Cake\Console\ConsoleInput` The input stream * [$\_lastWritten](#%24_lastWritten) protected `int` The number of bytes last written to the output stream used when overwriting the previous message. * [$\_level](#%24_level) protected `int` The current output level. * [$\_out](#%24_out) protected `Cake\Console\ConsoleOutput` The output stream * [$forceOverwrite](#%24forceOverwrite) protected `bool` Whether files should be overwritten * [$interactive](#%24interactive) protected `bool` Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [\_getInput()](#_getInput()) protected Prompts the user for input, and returns it. * ##### [abort()](#abort()) public Halts the the current process with a StopException. * ##### [ask()](#ask()) public Prompts the user for input, and returns it. * ##### [askChoice()](#askChoice()) public Prompts the user for input based on a list of options, and returns it. * ##### [comment()](#comment()) public Convenience method for out() that wraps message between tag * ##### [createFile()](#createFile()) public Create a file at the given path. * ##### [err()](#err()) public Outputs a single or multiple error messages to stderr. If no parameters are passed outputs just a newline. * ##### [error()](#error()) public Convenience method for err() that wraps message between tag * ##### [getStyle()](#getStyle()) public Get defined style. * ##### [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. * ##### [info()](#info()) public Convenience method for out() that wraps message between tag * ##### [level()](#level()) public Get/set the current output level. * ##### [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. * ##### [overwrite()](#overwrite()) public Overwrite some already output text. * ##### [quiet()](#quiet()) public Output at all levels. * ##### [setInteractive()](#setInteractive()) public * ##### [setLoggers()](#setLoggers()) public Connects or disconnects the loggers to the console output. * ##### [setOutputAs()](#setOutputAs()) public Change the output mode of the stdout stream * ##### [setStyle()](#setStyle()) public Adds a new output style. * ##### [styles()](#styles()) public Gets defined styles. * ##### [success()](#success()) public Convenience method for out() that wraps message between tag * ##### [verbose()](#verbose()) public Output at the verbose level. * ##### [warning()](#warning()) public Convenience method for err() that wraps message between tag * ##### [wrapMessageWithType()](#wrapMessageWithType()) protected Wraps a message with a given message type, e.g. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\Console\ConsoleOutput|null $out = null, Cake\Console\ConsoleOutput|null $err = null, Cake\Console\ConsoleInput|null $in = null, Cake\Console\HelperRegistry|null $helpers = null) ``` Constructor #### Parameters `Cake\Console\ConsoleOutput|null` $out optional A ConsoleOutput object for stdout. `Cake\Console\ConsoleOutput|null` $err optional A ConsoleOutput object for stderr. `Cake\Console\ConsoleInput|null` $in optional A ConsoleInput object for stdin. `Cake\Console\HelperRegistry|null` $helpers optional A HelperRegistry instance ### \_getInput() protected ``` _getInput(string $prompt, string|null $options, string|null $default): string ``` Prompts the user for input, and returns it. #### Parameters `string` $prompt Prompt text. `string|null` $options String of options. Pass null to omit. `string|null` $default Default input value. Pass null to omit. #### Returns `string` ### abort() public ``` abort(string $message, int $code = CommandInterface::CODE_ERROR): void ``` Halts the the current process with a StopException. #### Parameters `string` $message Error message. `int` $code optional Error code. #### Returns `void` #### Throws `Cake\Console\Exception\StopException` ### ask() public ``` ask(string $prompt, string|null $default = null): string ``` Prompts the user for input, and returns it. #### Parameters `string` $prompt Prompt text. `string|null` $default optional Default input value. #### Returns `string` ### askChoice() public ``` askChoice(string $prompt, array<string>|string $options, string|null $default = null): string ``` Prompts the user for input based on a list of options, and returns it. #### Parameters `string` $prompt Prompt text. `array<string>|string` $options Array or string of options. `string|null` $default optional Default input value. #### Returns `string` ### comment() public ``` comment(array<string>|string $message, int $newlines = 1, int $level = self::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#ConsoleIo::out ### createFile() public ``` createFile(string $path, string $contents, bool $forceOverwrite = false): bool ``` Create a file at the given path. This method will prompt the user if a file will be overwritten. Setting `forceOverwrite` to true will suppress this behavior and always overwrite the file. If the user replies `a` subsequent `forceOverwrite` parameters will be coerced to true and all files will be overwritten. #### Parameters `string` $path The path to create the file at. `string` $contents The contents to put into the file. `bool` $forceOverwrite optional Whether the file should be overwritten. If true, no question will be asked about whether to overwrite existing files. #### Returns `bool` #### Throws `Cake\Console\Exception\StopException` When `q` is given as an answer to whether a file should be overwritten. ### 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 optional A string or an array of strings to output `int` $newlines optional Number of newlines to append #### Returns `int` ### error() public ``` error(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#ConsoleIo::err ### getStyle() public ``` getStyle(string $style): array ``` Get defined style. #### Parameters `string` $style The style to get. #### Returns `array` #### See Also \Cake\Console\ConsoleOutput::getStyle() ### 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 = 79): 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 79 #### Returns `void` ### info() public ``` info(array<string>|string $message, int $newlines = 1, int $level = self::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#ConsoleIo::out ### level() public ``` level(int|null $level = null): int ``` Get/set the current output level. #### Parameters `int|null` $level optional The current output level. #### Returns `int` ### 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` ### out() public ``` out(array<string>|string $message = '', int $newlines = 1, int $level = self::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. ConsoleIo::QUIET, ConsoleIo::NORMAL, ConsoleIo::VERBOSE. The verbose and quiet output levels, map to the `verbose` and `quiet` output switches present in most shells. Using ConsoleIo::QUIET for a message means it will always display. While using ConsoleIo::VERBOSE means it will only display when verbose output is toggled. #### Parameters `array<string>|string` $message optional 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` ### overwrite() public ``` overwrite(array<string>|string $message, int $newlines = 1, int|null $size = null): void ``` Overwrite some already output text. Useful for building progress bars, or when you want to replace text already output to the screen with new text. **Warning** You cannot overwrite text that contains newlines. #### Parameters `array<string>|string` $message The message to output. `int` $newlines optional Number of newlines to append. `int|null` $size optional The number of bytes to overwrite. Defaults to the length of the last message output. #### Returns `void` ### 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` ### setInteractive() public ``` setInteractive(bool $value): void ``` #### Parameters `bool` $value Value #### Returns `void` ### setLoggers() public ``` setLoggers(int|bool $enable): void ``` Connects or disconnects the loggers to the console output. Used to enable or disable logging stream output to stdout and stderr If you don't wish all log output in stdout or stderr through Cake's Log class, call this function with `$enable=false`. #### Parameters `int|bool` $enable Use a boolean to enable/toggle all logging. Use one of the verbosity constants (self::VERBOSE, self::QUIET, self::NORMAL) to control logging levels. VERBOSE enables debug logs, NORMAL does not include debug logs, QUIET disables notice, info and debug logs. #### Returns `void` ### setOutputAs() public ``` setOutputAs(int $mode): void ``` Change the output mode of the stdout stream #### Parameters `int` $mode The output mode. #### Returns `void` #### See Also \Cake\Console\ConsoleOutput::setOutputAs() ### setStyle() public ``` setStyle(string $style, array $definition): void ``` Adds a new output style. #### Parameters `string` $style The style to set. `array` $definition The array definition of the style to change or create. #### Returns `void` #### See Also \Cake\Console\ConsoleOutput::setStyle() ### styles() public ``` styles(): array ``` Gets defined styles. #### Returns `array` #### See Also \Cake\Console\ConsoleOutput::styles() ### success() public ``` success(array<string>|string $message, int $newlines = 1, int $level = self::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#ConsoleIo::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` ### warning() public ``` warning(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#ConsoleIo::err ### wrapMessageWithType() protected ``` wrapMessageWithType(string $messageType, array<string>|string $message): array<string>|string ``` Wraps a message with a given message type, e.g. #### Parameters `string` $messageType The message type, e.g. "warning". `array<string>|string` $message The message to wrap. #### Returns `array<string>|string` Property Detail --------------- ### $\_err protected The error stream #### Type `Cake\Console\ConsoleOutput` ### $\_helpers protected The helper registry. #### Type `Cake\Console\HelperRegistry` ### $\_in protected The input stream #### Type `Cake\Console\ConsoleInput` ### $\_lastWritten protected The number of bytes last written to the output stream used when overwriting the previous message. #### Type `int` ### $\_level protected The current output level. #### Type `int` ### $\_out protected The output stream #### Type `Cake\Console\ConsoleOutput` ### $forceOverwrite protected Whether files should be overwritten #### Type `bool` ### $interactive protected #### Type `bool`
programming_docs
cakephp Namespace Console Namespace Console ================= ### Namespaces * [Cake\Console\Command](namespace-cake.console.command) * [Cake\Console\Exception](namespace-cake.console.exception) * [Cake\Console\TestSuite](namespace-cake.console.testsuite) ### Interfaces * ##### [CommandCollectionAwareInterface](interface-cake.console.commandcollectionawareinterface) An interface for shells that take a CommandCollection during initialization. * ##### [CommandFactoryInterface](interface-cake.console.commandfactoryinterface) An interface for abstracting creation of command and shell instances. * ##### [CommandInterface](interface-cake.console.commandinterface) Describe the interface between a command and the surrounding console libraries. ### Classes * ##### [Arguments](class-cake.console.arguments) Provides an interface for interacting with a command's options and arguments. * ##### [BaseCommand](class-cake.console.basecommand) Base class for console commands. * ##### [CommandCollection](class-cake.console.commandcollection) Collection for Commands. * ##### [CommandFactory](class-cake.console.commandfactory) This is a factory for creating Command and Shell instances. * ##### [CommandRunner](class-cake.console.commandrunner) Run CLI commands for the provided application. * ##### [CommandScanner](class-cake.console.commandscanner) Used by CommandCollection and CommandTask to scan the filesystem for command classes. * ##### [ConsoleInput](class-cake.console.consoleinput) Object wrapper for interacting with stdin * ##### [ConsoleInputArgument](class-cake.console.consoleinputargument) An object to represent a single argument used in the command line. ConsoleOptionParser creates these when you use addArgument() * ##### [ConsoleInputOption](class-cake.console.consoleinputoption) An object to represent a single option used in the command line. ConsoleOptionParser creates these when you use addOption() * ##### [ConsoleInputSubcommand](class-cake.console.consoleinputsubcommand) An object to represent a single subcommand used in the command line. Created when you call ConsoleOptionParser::addSubcommand() * ##### [ConsoleIo](class-cake.console.consoleio) A wrapper around the various IO operations shell tasks need to do. * ##### [ConsoleOptionParser](class-cake.console.consoleoptionparser) Handles parsing the ARGV in the command line and provides support for GetOpt compatible option definition. Provides a builder pattern implementation for creating shell option parsers. * ##### [ConsoleOutput](class-cake.console.consoleoutput) Object wrapper for outputting information from a shell application. Can be connected to any stream resource that can be used with fopen() * ##### [HelpFormatter](class-cake.console.helpformatter) HelpFormatter formats help for console shells. Can format to either text or XML formats. Uses ConsoleOptionParser methods to generate help. * ##### [Helper](class-cake.console.helper) Base class for Helpers. * ##### [HelperRegistry](class-cake.console.helperregistry) Registry for Helpers. Provides features for lazily loading helpers. * ##### [Shell](class-cake.console.shell) Base class for command-line utilities for automating programmer chores. * ##### [ShellDispatcher](class-cake.console.shelldispatcher) Shell dispatcher handles dispatching CLI commands. * ##### [TaskRegistry](class-cake.console.taskregistry) Registry for Tasks. Provides features for lazily loading tasks. cakephp Class Cell Class Cell =========== Cell base. **Abstract** **Namespace:** [Cake\View](namespace-cake.view) Constants --------- * `string` **TEMPLATE\_FOLDER** ``` 'cell' ``` Constant for folder name containing cell templates. Property Summary ---------------- * [$View](#%24View) protected `Cake\View\View` Instance of the View created during rendering. Won't be set until after Cell::\_\_toString()/render() is called. * [$\_cache](#%24_cache) protected `array|bool` Caching setup. * [$\_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. * [$\_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 * [$\_validCellOptions](#%24_validCellOptions) protected `array<string>` List of valid options (constructor's fourth arguments) Override this property in subclasses to allow which options you want set as properties in your Cell. * [$\_viewBuilder](#%24_viewBuilder) protected `Cake\View\ViewBuilder|null` The view builder instance being used. * [$action](#%24action) protected `string` The cell's action to invoke. * [$args](#%24args) protected `array` Arguments to pass to cell's action. * [$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. * [$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` An instance of a Response object that contains information about the impending response Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [\_\_debugInfo()](#__debugInfo()) public Debug info. * ##### [\_\_toString()](#__toString()) public Magic method. * ##### [\_cacheConfig()](#_cacheConfig()) protected Generate the cache key to use for this cell. * ##### [\_setModelClass()](#_setModelClass()) protected Set the modelClass property based on conventions. * ##### [createView()](#createView()) public Constructs the view class instance based on the current configuration. * ##### [dispatchEvent()](#dispatchEvent()) public Wrapper for creating and dispatching events. * ##### [fetchTable()](#fetchTable()) public Convenience method to get a table instance. * ##### [getEventManager()](#getEventManager()) public Returns the Cake\Event\EventManager manager instance for this object. * ##### [getModelType()](#getModelType()) public Get the model type to be used by this class * ##### [getTableLocator()](#getTableLocator()) public Gets the table locator. * ##### [initialize()](#initialize()) public Initialization hook method. * ##### [loadModel()](#loadModel()) public deprecated Loads and constructs repository objects required by this object * ##### [modelFactory()](#modelFactory()) public Override a existing callable to generate repositories of a given type. * ##### [render()](#render()) public Render the cell. * ##### [set()](#set()) public Saves a variable or an associative array of variables for use inside a template. * ##### [setEventManager()](#setEventManager()) public Returns the Cake\Event\EventManagerInterface instance for this object. * ##### [setModelType()](#setModelType()) public Set the model type to be used by this class * ##### [setTableLocator()](#setTableLocator()) public Sets the table locator. * ##### [viewBuilder()](#viewBuilder()) public Get the view builder being used. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\Http\ServerRequest $request, Cake\Http\Response $response, Cake\Event\EventManagerInterface|null $eventManager = null, array<string, mixed> $cellOptions = []) ``` Constructor. #### Parameters `Cake\Http\ServerRequest` $request The request to use in the cell. `Cake\Http\Response` $response The response to use in the cell. `Cake\Event\EventManagerInterface|null` $eventManager optional The eventManager to bind events to. `array<string, mixed>` $cellOptions optional Cell options to apply. ### \_\_debugInfo() public ``` __debugInfo(): array<string, mixed> ``` Debug info. #### Returns `array<string, mixed>` ### \_\_toString() public ``` __toString(): string ``` Magic method. Starts the rendering process when Cell is echoed. *Note* This method will trigger an error when view rendering has a problem. This is because PHP will not allow a \_\_toString() method to throw an exception. #### Returns `string` #### Throws `Error` Include error details for PHP 7 fatal errors. ### \_cacheConfig() protected ``` _cacheConfig(string $action, string|null $template = null): array ``` Generate the cache key to use for this cell. If the key is undefined, the cell class and action name will be used. #### Parameters `string` $action The action invoked. `string|null` $template optional The name of the template to be rendered. #### Returns `array` ### \_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` ### createView() public ``` createView(string|null $viewClass = null): Cake\View\View ``` Constructs the view class instance based on the current configuration. #### Parameters `string|null` $viewClass optional Optional namespaced class name of the View class to instantiate. #### Returns `Cake\View\View` #### Throws `Cake\View\Exception\MissingViewException` If view class was not found. ### 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` ### 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() ### 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` ### getModelType() public ``` getModelType(): string ``` Get the model type to be used by this class #### Returns `string` ### getTableLocator() public ``` getTableLocator(): Cake\ORM\Locator\LocatorInterface ``` Gets the table locator. #### Returns `Cake\ORM\Locator\LocatorInterface` ### initialize() public ``` initialize(): void ``` Initialization hook method. Implement this method to avoid having to overwrite the constructor and calling parent::\_\_construct(). #### 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. ### 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` ### render() public ``` render(string|null $template = null): string ``` Render the cell. #### Parameters `string|null` $template optional Custom template name to render. If not provided (null), the last value will be used. This value is automatically set by `CellTrait::cell()`. #### Returns `string` #### Throws `Cake\View\Exception\MissingCellTemplateException` `BadMethodCallException` ### 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` ### 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` ### setModelType() public ``` setModelType(string $modelType): $this ``` Set the model type to be used by this class #### Parameters `string` $modelType The model type #### 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` ### viewBuilder() public ``` viewBuilder(): Cake\View\ViewBuilder ``` Get the view builder being used. #### Returns `Cake\View\ViewBuilder` Property Detail --------------- ### $View protected Instance of the View created during rendering. Won't be set until after Cell::\_\_toString()/render() is called. #### Type `Cake\View\View` ### $\_cache protected Caching setup. #### Type `array|bool` ### $\_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` ### $\_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` ### $\_validCellOptions protected List of valid options (constructor's fourth arguments) Override this property in subclasses to allow which options you want set as properties in your Cell. #### Type `array<string>` ### $\_viewBuilder protected The view builder instance being used. #### Type `Cake\View\ViewBuilder|null` ### $action protected The cell's action to invoke. #### Type `string` ### $args protected Arguments to pass to cell's action. #### Type `array` ### $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` ### $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 An instance of a Response object that contains information about the impending response #### Type `Cake\Http\Response` cakephp Class TemplateFileEquals Class TemplateFileEquals ========================= TemplateFileEquals **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`
programming_docs
cakephp Interface ErrorRendererInterface Interface ErrorRendererInterface ================================= Interface for PHP error rendering implementations The core provided implementations of this interface are used by Debugger and ErrorTrap to render PHP errors. **Namespace:** [Cake\Error](namespace-cake.error) 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 The error to be rendered. `bool` $debug Whether or not the application is in debug mode. #### Returns `string` ### write() public ``` write(string $out): void ``` Write output to the renderer's output stream #### Parameters `string` $out The content to output. #### Returns `void` cakephp Class BodyEquals Class BodyEquals ================= BodyEquals **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 VersionCommand Class VersionCommand ===================== Print out the version of CakePHP in use. **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()) protected 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 Print out the version of CakePHP in use. * ##### [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() protected ``` 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` ### 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 ``` Print out the version of CakePHP in use. #### Parameters `Cake\Console\Arguments` $args The command arguments. `Cake\Console\ConsoleIo` $io The console io #### Returns `int` ### 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 Oauth Class Oauth ============ Oauth 1 authentication strategy for Cake\Http\Client This object does not handle getting Oauth access tokens from the service provider. It only handles make client requests *after* you have obtained the Oauth tokens. Generally not directly constructed, but instead used by {@link \Cake\Http\Client} when $options['auth']['type'] is 'oauth' **Namespace:** [Cake\Http\Client\Auth](namespace-cake.http.client.auth) Method Summary -------------- * ##### [\_buildAuth()](#_buildAuth()) protected Builds the Oauth Authorization header value. * ##### [\_encode()](#_encode()) protected URL Encodes a value based on rules of rfc3986 * ##### [\_hmacSha1()](#_hmacSha1()) protected Use HMAC-SHA1 signing. * ##### [\_normalizeData()](#_normalizeData()) protected Recursively convert request data into the normalized form. * ##### [\_normalizedParams()](#_normalizedParams()) protected Sorts and normalizes request data and oauthValues * ##### [\_normalizedUrl()](#_normalizedUrl()) protected Builds a normalized URL * ##### [\_plaintext()](#_plaintext()) protected Plaintext signing * ##### [\_rsaSha1()](#_rsaSha1()) protected Use RSA-SHA1 signing. * ##### [authentication()](#authentication()) public Add headers for Oauth authorization. * ##### [baseString()](#baseString()) public Generate the Oauth basestring * ##### [checkSslError()](#checkSslError()) protected Check for SSL errors and raise if one is encountered. Method Detail ------------- ### \_buildAuth() protected ``` _buildAuth(array $data): string ``` Builds the Oauth Authorization header value. #### Parameters `array` $data The oauth\_\* values to build #### Returns `string` ### \_encode() protected ``` _encode(string $value): string ``` URL Encodes a value based on rules of rfc3986 #### Parameters `string` $value Value to encode. #### Returns `string` ### \_hmacSha1() protected ``` _hmacSha1(Cake\Http\Client\Request $request, array $credentials): string ``` Use HMAC-SHA1 signing. This method is suitable for plain HTTP or HTTPS. #### Parameters `Cake\Http\Client\Request` $request The request object. `array` $credentials Authentication credentials. #### Returns `string` ### \_normalizeData() protected ``` _normalizeData(array $args, string $path = ''): array ``` Recursively convert request data into the normalized form. #### Parameters `array` $args The arguments to normalize. `string` $path optional The current path being converted. #### Returns `array` #### See Also https://tools.ietf.org/html/rfc5849#section-3.4.1.3.2 ### \_normalizedParams() protected ``` _normalizedParams(Cake\Http\Client\Request $request, array $oauthValues): string ``` Sorts and normalizes request data and oauthValues Section 9.1.1 of Oauth spec. * URL encode keys + values. * Sort keys & values by byte value. #### Parameters `Cake\Http\Client\Request` $request The request object. `array` $oauthValues Oauth values. #### Returns `string` ### \_normalizedUrl() protected ``` _normalizedUrl(Psr\Http\Message\UriInterface $uri): string ``` Builds a normalized URL Section 9.1.2. of the Oauth spec #### Parameters `Psr\Http\Message\UriInterface` $uri Uri object to build a normalized version of. #### Returns `string` ### \_plaintext() protected ``` _plaintext(Cake\Http\Client\Request $request, array $credentials): string ``` Plaintext signing This method is **not** suitable for plain HTTP. You should only ever use PLAINTEXT when dealing with SSL services. #### Parameters `Cake\Http\Client\Request` $request The request object. `array` $credentials Authentication credentials. #### Returns `string` ### \_rsaSha1() protected ``` _rsaSha1(Cake\Http\Client\Request $request, array $credentials): string ``` Use RSA-SHA1 signing. This method is suitable for plain HTTP or HTTPS. #### Parameters `Cake\Http\Client\Request` $request The request object. `array` $credentials Authentication credentials. #### Returns `string` #### Throws `RuntimeException` ### authentication() public ``` authentication(Cake\Http\Client\Request $request, array $credentials): Cake\Http\Client\Request ``` Add headers for Oauth authorization. #### Parameters `Cake\Http\Client\Request` $request The request object. `array` $credentials Authentication credentials. #### Returns `Cake\Http\Client\Request` #### Throws `Cake\Core\Exception\CakeException` On invalid signature types. ### baseString() public ``` baseString(Cake\Http\Client\Request $request, array $oauthValues): string ``` Generate the Oauth basestring * Querystring, request data and oauth\_\* parameters are combined. * Values are sorted by name and then value. * Request values are concatenated and urlencoded. * The request URL (without querystring) is normalized. * The HTTP method, URL and request parameters are concatenated and returned. #### Parameters `Cake\Http\Client\Request` $request The request object. `array` $oauthValues Oauth values. #### Returns `string` ### checkSslError() protected ``` checkSslError(): void ``` Check for SSL errors and raise if one is encountered. #### Returns `void` cakephp Trait TranslateStrategyTrait Trait TranslateStrategyTrait ============================= Contains common code needed by TranslateBehavior strategy classes. **Namespace:** [Cake\ORM\Behavior\Translate](namespace-cake.orm.behavior.translate) Property Summary ---------------- * [$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 -------------- * ##### [afterSave()](#afterSave()) public Unsets the temporary `_i18n` property after the entity has been saved * ##### [buildMarshalMap()](#buildMarshalMap()) public Build a set of properties that should be included in the marshalling process. * ##### [getLocale()](#getLocale()) public Returns the current locale. * ##### [getTranslationTable()](#getTranslationTable()) public Return translation table instance. * ##### [setLocale()](#setLocale()) public Sets the locale to be used. * ##### [unsetEmptyFields()](#unsetEmptyFields()) protected Unset empty translations to avoid persistence. Method Detail ------------- ### 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` ### 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` ### 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() ### getTranslationTable() public ``` getTranslationTable(): Cake\ORM\Table ``` Return translation table instance. #### Returns `Cake\ORM\Table` ### 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` ### 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 --------------- ### $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` cakephp Namespace Behavior Namespace Behavior ================== ### Namespaces * [Cake\ORM\Behavior\Translate](namespace-cake.orm.behavior.translate) ### Classes * ##### [CounterCacheBehavior](class-cake.orm.behavior.countercachebehavior) CounterCache behavior * ##### [TimestampBehavior](class-cake.orm.behavior.timestampbehavior) Class TimestampBehavior * ##### [TranslateBehavior](class-cake.orm.behavior.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. * ##### [TreeBehavior](class-cake.orm.behavior.treebehavior) Makes the table to which this is attached to behave like a nested set and provides methods for managing and retrieving information out of the derived hierarchical structure. cakephp Namespace Session Namespace Session ================= ### Classes * ##### [FlashParamEquals](class-cake.testsuite.constraint.session.flashparamequals) FlashParamEquals * ##### [SessionEquals](class-cake.testsuite.constraint.session.sessionequals) SessionEquals * ##### [SessionHasKey](class-cake.testsuite.constraint.session.sessionhaskey) SessionHasKey cakephp Interface ConnectionInterface Interface ConnectionInterface ============================== This interface defines the methods you can depend on in a connection. **Namespace:** [Cake\Datasource](namespace-cake.datasource) Method Summary -------------- * ##### [config()](#config()) public Get the configuration data used to create the connection. * ##### [configName()](#configName()) public Get the configuration name for this connection. * ##### [disableConstraints()](#disableConstraints()) public Run an operation with constraints disabled. * ##### [disableQueryLogging()](#disableQueryLogging()) public Disable query logging * ##### [enableQueryLogging()](#enableQueryLogging()) public Enable/disable query logging * ##### [execute()](#execute()) public @method Executes a query using `$params` for interpolating values and $types as a hint for each those params. {@see \Cake\Database\Connnection::execute()} * ##### [getCacher()](#getCacher()) public Get a cacher. * ##### [getDriver()](#getDriver()) public @method Gets the driver instance. {@see \Cake\Database\Connnection::getDriver()} * ##### [getLogger()](#getLogger()) public Gets the current logger object. * ##### [getSchemaCollection()](#getSchemaCollection()) public @method Gets a Schema\Collection object for this connection. {@see \Cake\Database\Connnection::getSchemaCollection()} * ##### [isQueryLoggingEnabled()](#isQueryLoggingEnabled()) public Check if query logging is enabled. * ##### [newQuery()](#newQuery()) public @method Create a new Query instance for this connection. {@see \Cake\Database\Connnection::newQuery()} * ##### [prepare()](#prepare()) public @method Prepares a SQL statement to be executed. {@see \Cake\Database\Connnection::prepare()} * ##### [query()](#query()) public @method Executes a SQL statement and returns the Statement object as result. {@see \Cake\Database\Connnection::query()} * ##### [setCacher()](#setCacher()) public Set a cacher. * ##### [setLogger()](#setLogger()) public @method Set the current logger. {@see \Cake\Database\Connnection::setLogger()} * ##### [supportsDynamicConstraints()](#supportsDynamicConstraints()) public @method Returns whether the driver supports adding or dropping constraints to already created tables. {@see \Cake\Database\Connnection::supportsDynamicConstraints()} * ##### [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. Method Detail ------------- ### 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` ### 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 The callback to execute within a transaction. #### Returns `mixed` #### Throws `Exception` Will re-throw any exception raised in $callback after rolling back the transaction. ### disableQueryLogging() public ``` disableQueryLogging(): $this ``` Disable query logging #### Returns `$this` ### enableQueryLogging() public ``` enableQueryLogging(bool $enable = true): $this ``` Enable/disable query logging #### Parameters `bool` $enable optional Enable/disable query logging #### Returns `$this` ### execute() public @method ``` execute(mixed $query, mixed $params = [], array $types = []): Cake\Database\StatementInterface ``` Executes a query using `$params` for interpolating values and $types as a hint for each those params. {@see \Cake\Database\Connnection::execute()} #### Parameters $query $params optional `array` $types optional #### Returns `Cake\Database\StatementInterface` ### getCacher() public ``` getCacher(): Psr\SimpleCache\CacheInterface ``` Get a cacher. #### Returns `Psr\SimpleCache\CacheInterface` ### getDriver() public @method ``` getDriver(): object ``` Gets the driver instance. {@see \Cake\Database\Connnection::getDriver()} #### Returns `object` ### getLogger() public ``` getLogger(): Psr\Log\LoggerInterface ``` Gets the current logger object. #### Returns `Psr\Log\LoggerInterface` ### getSchemaCollection() public @method ``` getSchemaCollection(): Cake\Database\Schema\Collection ``` Gets a Schema\Collection object for this connection. {@see \Cake\Database\Connnection::getSchemaCollection()} #### Returns `Cake\Database\Schema\Collection` ### isQueryLoggingEnabled() public ``` isQueryLoggingEnabled(): bool ``` Check if query logging is enabled. #### Returns `bool` ### newQuery() public @method ``` newQuery(): Cake\Database\Query ``` Create a new Query instance for this connection. {@see \Cake\Database\Connnection::newQuery()} #### Returns `Cake\Database\Query` ### prepare() public @method ``` prepare(mixed $sql): Cake\Database\StatementInterface ``` Prepares a SQL statement to be executed. {@see \Cake\Database\Connnection::prepare()} #### Parameters $sql #### Returns `Cake\Database\StatementInterface` ### query() public @method ``` query(string $sql): Cake\Database\StatementInterface ``` Executes a SQL statement and returns the Statement object as result. {@see \Cake\Database\Connnection::query()} #### Parameters `string` $sql #### Returns `Cake\Database\StatementInterface` ### setCacher() public ``` setCacher(Psr\SimpleCache\CacheInterface $cacher): $this ``` Set a cacher. #### Parameters `Psr\SimpleCache\CacheInterface` $cacher Cacher object #### Returns `$this` ### setLogger() public @method ``` setLogger(LoggerInterface $logger): void ``` Set the current logger. {@see \Cake\Database\Connnection::setLogger()} #### Parameters `LoggerInterface` $logger #### Returns `void` ### supportsDynamicConstraints() public @method ``` supportsDynamicConstraints(): bool ``` Returns whether the driver supports adding or dropping constraints to already created tables. {@see \Cake\Database\Connnection::supportsDynamicConstraints()} #### 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 The callback to execute within a transaction. #### Returns `mixed` #### Throws `Exception` Will re-throw any exception raised in $callback after rolling back the transaction. cakephp Class Log Class Log ========== Logs messages to configured Log adapters. One or more adapters can be configured using Cake Logs's methods. If you don't configure any adapters, and write to Log, the messages will be ignored. ### Configuring Log adapters You can configure log adapters in your applications `config/app.php` file. A sample configuration would look like: ``` Log::setConfig('my_log', ['className' => 'FileLog']); ``` You can define the className as any fully namespaced classname or use a short hand classname to use loggers in the `App\Log\Engine` & `Cake\Log\Engine` namespaces. You can also use plugin short hand to use logging classes provided by plugins. Log adapters are required to implement `Psr\Log\LoggerInterface`, and there is a built-in base class (`Cake\Log\Engine\BaseLog`) that can be used for custom loggers. Outside of the `className` key, all other configuration values will be passed to the logging adapter's constructor as an array. ### Logging levels When configuring loggers, you can set which levels a logger will handle. This allows you to disable debug messages in production for example: ``` Log::setConfig('default', [ 'className' => 'File', 'path' => LOGS, 'levels' => ['error', 'critical', 'alert', 'emergency'] ]); ``` The above logger would only log error messages or higher. Any other log messages would be discarded. ### Logging scopes When configuring loggers you can define the active scopes the logger is for. If defined, only the listed scopes will be handled by the logger. If you don't define any scopes an adapter will catch all scopes that match the handled levels. ``` Log::setConfig('payments', [ 'className' => 'File', 'scopes' => ['payment', 'order'] ]); ``` The above logger will only capture log entries made in the `payment` and `order` scopes. All other scopes including the undefined scope will be ignored. ### Writing to the log You write to the logs using Log::write(). See its documentation for more information. ### Logging Levels By default Cake Log supports all the log levels defined in RFC 5424. When logging messages you can either use the named methods, or the correct constants with `write()`: ``` Log::error('Something horrible happened'); Log::write(LOG_ERR, 'Something horrible happened'); ``` ### Logging scopes When logging messages and configuring log adapters, you can specify 'scopes' that the logger will handle. You can think of scopes as subsystems in your application that may require different logging setups. For example in an e-commerce application you may want to handle logged errors in the cart and ordering subsystems differently than the rest of the application. By using scopes you can control logging for each part of your application and also use standard log levels. **Namespace:** [Cake\Log](namespace-cake.log) Property Summary ---------------- * [$\_config](#%24_config) protected static `array<string, mixed>` Configuration sets. * [$\_dirtyConfig](#%24_dirtyConfig) protected static `bool` Internal flag for tracking whether configuration has been changed. * [$\_dsnClassMap](#%24_dsnClassMap) protected static `array<string, string>` An array mapping url schemes to fully qualified Log engine class names * [$\_levelMap](#%24_levelMap) protected static `array<string, int>` Log levels as detailed in RFC 5424 <https://tools.ietf.org/html/rfc5424> * [$\_levels](#%24_levels) protected static `array<string>` Handled log levels * [$\_registry](#%24_registry) protected static `Cake\Log\LogEngineRegistry` LogEngineRegistry class Method Summary -------------- * ##### [\_init()](#_init()) protected static Initializes registry and configurations * ##### [\_loadConfig()](#_loadConfig()) protected static Load the defined configuration and create all the defined logging adapters. * ##### [alert()](#alert()) public static Convenience method to log alert messages * ##### [configured()](#configured()) public static Returns an array containing the named configurations * ##### [critical()](#critical()) public static Convenience method to log critical messages * ##### [debug()](#debug()) public static Convenience method to log debug messages * ##### [drop()](#drop()) public static Drops a constructed adapter. * ##### [emergency()](#emergency()) public static Convenience method to log emergency messages * ##### [engine()](#engine()) public static Get a logging engine. * ##### [error()](#error()) public static Convenience method to log error messages * ##### [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. * ##### [info()](#info()) public static Convenience method to log info messages * ##### [levels()](#levels()) public static Gets log levels * ##### [notice()](#notice()) public static Convenience method to log notice messages * ##### [parseDsn()](#parseDsn()) public static Parses a DSN into a valid connection configuration * ##### [reset()](#reset()) public static Reset all the connected loggers. This is useful to do when changing the logging configuration or during testing when you want to reset the internal state of the Log class. * ##### [setConfig()](#setConfig()) public static This method can be used to define logging adapters for an application or read existing configuration. * ##### [setDsnClassMap()](#setDsnClassMap()) public static Updates the DSN class map for this class. * ##### [warning()](#warning()) public static Convenience method to log warning messages * ##### [write()](#write()) public static Writes the given message and type to all the configured log adapters. Configured adapters are passed both the $level and $message variables. $level is one of the following strings/values. Method Detail ------------- ### \_init() protected static ``` _init(): void ``` Initializes registry and configurations #### Returns `void` ### \_loadConfig() protected static ``` _loadConfig(): void ``` Load the defined configuration and create all the defined logging adapters. #### Returns `void` ### alert() public static ``` alert(string $message, array|string $context = []): bool ``` Convenience method to log alert messages #### Parameters `string` $message log message `array|string` $context optional Additional data to be used for logging the message. The special `scope` key can be passed to be used for further filtering of the log engines to be used. If a string or a numerically index array is passed, it will be treated as the `scope` key. See {@link \Cake\Log\Log::setConfig()} for more information on logging scopes. #### Returns `bool` ### configured() public static ``` configured(): array<string> ``` Returns an array containing the named configurations #### Returns `array<string>` ### critical() public static ``` critical(string $message, array|string $context = []): bool ``` Convenience method to log critical messages #### Parameters `string` $message log message `array|string` $context optional Additional data to be used for logging the message. The special `scope` key can be passed to be used for further filtering of the log engines to be used. If a string or a numerically index array is passed, it will be treated as the `scope` key. See {@link \Cake\Log\Log::setConfig()} for more information on logging scopes. #### Returns `bool` ### debug() public static ``` debug(string $message, array|string $context = []): bool ``` Convenience method to log debug messages #### Parameters `string` $message log message `array|string` $context optional Additional data to be used for logging the message. The special `scope` key can be passed to be used for further filtering of the log engines to be used. If a string or a numerically index array is passed, it will be treated as the `scope` key. See {@link \Cake\Log\Log::setConfig()} for more information on logging scopes. #### Returns `bool` ### 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` ### emergency() public static ``` emergency(string $message, array|string $context = []): bool ``` Convenience method to log emergency messages #### Parameters `string` $message log message `array|string` $context optional Additional data to be used for logging the message. The special `scope` key can be passed to be used for further filtering of the log engines to be used. If a string or a numerically index array is passed, it will be treated as the `scope` key. See {@link \Cake\Log\Log::setConfig()} for more information on logging scopes. #### Returns `bool` ### engine() public static ``` engine(string $name): Psr\Log\LoggerInterface|null ``` Get a logging engine. #### Parameters `string` $name Key name of a configured adapter to get. #### Returns `Psr\Log\LoggerInterface|null` ### error() public static ``` error(string $message, array|string $context = []): bool ``` Convenience method to log error messages #### Parameters `string` $message log message `array|string` $context optional Additional data to be used for logging the message. The special `scope` key can be passed to be used for further filtering of the log engines to be used. If a string or a numerically index array is passed, it will be treated as the `scope` key. See {@link \Cake\Log\Log::setConfig()} for more information on logging scopes. #### Returns `bool` ### 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>` ### info() public static ``` info(string $message, array|string $context = []): bool ``` Convenience method to log info messages #### Parameters `string` $message log message `array|string` $context optional Additional data to be used for logging the message. The special `scope` key can be passed to be used for further filtering of the log engines to be used. If a string or a numerically indexed array is passed, it will be treated as the `scope` key. See {@link \Cake\Log\Log::setConfig()} for more information on logging scopes. #### Returns `bool` ### levels() public static ``` levels(): array<string> ``` Gets log levels Call this method to obtain current level configuration. #### Returns `array<string>` ### notice() public static ``` notice(string $message, array|string $context = []): bool ``` Convenience method to log notice messages #### Parameters `string` $message log message `array|string` $context optional Additional data to be used for logging the message. The special `scope` key can be passed to be used for further filtering of the log engines to be used. If a string or a numerically index array is passed, it will be treated as the `scope` key. See {@link \Cake\Log\Log::setConfig()} for more information on logging scopes. #### Returns `bool` ### 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 ### reset() public static ``` reset(): void ``` Reset all the connected loggers. This is useful to do when changing the logging configuration or during testing when you want to reset the internal state of the Log class. Resets the configured logging adapters, as well as any custom logging levels. This will also clear the configuration data. #### Returns `void` ### setConfig() public static ``` setConfig(array<string, mixed>|string $key, object|array<string, mixed>|null $config = null): void ``` This method can be used to define logging adapters for an application or read existing configuration. To change an adapter's configuration at runtime, first drop the adapter and then reconfigure it. Loggers will not be constructed until the first log message is written. ### Usage Setting a cache engine up. ``` Log::setConfig('default', $settings); ``` Injecting a constructed adapter in: ``` Log::setConfig('default', $instance); ``` Using a factory function to get an adapter: ``` Log::setConfig('default', function () { return new FileLog(); }); ``` Configure multiple adapters at once: ``` Log::setConfig($arrayOfConfig); ``` #### Parameters `array<string, mixed>|string` $key The name of the logger config, or an array of multiple configs. `object|array<string, mixed>|null` $config optional An array of name => config data for adapter. #### Returns `void` #### Throws `BadMethodCallException` When trying to modify an existing config. ### 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` ### warning() public static ``` warning(string $message, array|string $context = []): bool ``` Convenience method to log warning messages #### Parameters `string` $message log message `array|string` $context optional Additional data to be used for logging the message. The special `scope` key can be passed to be used for further filtering of the log engines to be used. If a string or a numerically index array is passed, it will be treated as the `scope` key. See {@link \Cake\Log\Log::setConfig()} for more information on logging scopes. #### Returns `bool` ### write() public static ``` write(string|int $level, string $message, array|string $context = []): bool ``` Writes the given message and type to all the configured log adapters. Configured adapters are passed both the $level and $message variables. $level is one of the following strings/values. ### Levels: * `LOG_EMERG` => 'emergency', * `LOG_ALERT` => 'alert', * `LOG_CRIT` => 'critical', * `LOG_ERR` => 'error', * `LOG_WARNING` => 'warning', * `LOG_NOTICE` => 'notice', * `LOG_INFO` => 'info', * `LOG_DEBUG` => 'debug', ### Basic usage Write a 'warning' message to the logs: ``` Log::write('warning', 'Stuff is broken here'); ``` ### Using scopes When writing a log message you can define one or many scopes for the message. This allows you to handle messages differently based on application section/feature. ``` Log::write('warning', 'Payment failed', ['scope' => 'payment']); ``` When configuring loggers you can configure the scopes a particular logger will handle. When using scopes, you must ensure that the level of the message, and the scope of the message intersect with the defined levels & scopes for a logger. ### Unhandled log messages If no configured logger can handle a log message (because of level or scope restrictions) then the logged message will be ignored and silently dropped. You can check if this has happened by inspecting the return of write(). If false the message was not handled. #### Parameters `string|int` $level The severity level of the message being written. The value must be an integer or string matching a known level. `string` $message Message content to log `array|string` $context optional Additional data to be used for logging the message. The special `scope` key can be passed to be used for further filtering of the log engines to be used. If a string or a numerically index array is passed, it will be treated as the `scope` key. See {@link \Cake\Log\Log::setConfig()} for more information on logging scopes. #### Returns `bool` #### Throws `InvalidArgumentException` If invalid level is passed. Property Detail --------------- ### $\_config protected static Configuration sets. #### Type `array<string, mixed>` ### $\_dirtyConfig protected static Internal flag for tracking whether configuration has been changed. #### Type `bool` ### $\_dsnClassMap protected static An array mapping url schemes to fully qualified Log engine class names #### Type `array<string, string>` ### $\_levelMap protected static Log levels as detailed in RFC 5424 <https://tools.ietf.org/html/rfc5424> #### Type `array<string, int>` ### $\_levels protected static Handled log levels #### Type `array<string>` ### $\_registry protected static LogEngineRegistry class #### Type `Cake\Log\LogEngineRegistry`
programming_docs
cakephp Class BodyEmpty Class BodyEmpty ================ BodyEmpty **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 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 `Psr\Http\Message\ResponseInterface` cakephp Class LegacyShellDispatcher Class LegacyShellDispatcher ============================ Allows injecting mock IO into shells **Namespace:** [Cake\Console\TestSuite](namespace-cake.console.testsuite) Property Summary ---------------- * [$\_aliases](#%24_aliases) protected static `array<string, string>` List of connected aliases. * [$\_io](#%24_io) protected `Cake\Console\ConsoleIo` * [$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 Injects mock and stub io components into the shell * ##### [\_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, Cake\Console\ConsoleIo|null $io = null) ``` Constructor #### Parameters `array` $args optional Argument array `bool` $bootstrap optional Initialize environment `Cake\Console\ConsoleIo|null` $io optional ConsoleIo ### \_bootstrap() protected ``` _bootstrap(): void ``` Initializes the environment and loads the CakePHP core. #### Returns `void` ### \_createShell() protected ``` _createShell(string $className, string $shortName): Cake\Console\Shell ``` Injects mock and stub io components into the shell #### Parameters `string` $className Class name `string` $shortName Short 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>` ### $\_io protected #### Type `Cake\Console\ConsoleIo` ### $args public Contains arguments parsed from the command line. #### Type `array` cakephp Class ServerCommand Class ServerCommand ==================== built-in Server command **Namespace:** [Cake\Command](namespace-cake.command) Constants --------- * `int` **CODE\_ERROR** ``` 1 ``` Default error code * `int` **CODE\_SUCCESS** ``` 0 ``` Default success code * `string` **DEFAULT\_HOST** ``` 'localhost' ``` Default ServerHost * `int` **DEFAULT\_PORT** ``` 8765 ``` Default ListenPort Property Summary ---------------- * [$\_documentRoot](#%24_documentRoot) protected `string` document root * [$\_host](#%24_host) protected `string` server host * [$\_iniPath](#%24_iniPath) protected `string` ini path * [$\_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. * [$\_port](#%24_port) protected `int` listen port * [$\_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 Execute. * ##### [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. * ##### [startup()](#startup()) protected Starts up the Command and displays the welcome message. Allows for checking and configuring prior to command or main execution 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 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. #### 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` ### startup() protected ``` startup(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): void ``` Starts up the Command and displays the welcome message. Allows for checking and configuring prior to command or main execution #### Parameters `Cake\Console\Arguments` $args The command arguments. `Cake\Console\ConsoleIo` $io The console io #### Returns `void` #### Links https://book.cakephp.org/4/en/console-and-shells.html#hook-methods Property Detail --------------- ### $\_documentRoot protected document root #### Type `string` ### $\_host protected server host #### Type `string` ### $\_iniPath protected ini path #### Type `string` ### $\_modelFactories protected A list of overridden model factory functions. #### Type `array<callableCake\Datasource\Locator\LocatorInterface>` ### $\_modelType protected The model type to use. #### Type `string` ### $\_port protected listen port #### Type `int` ### $\_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 Renderer Class Renderer =============== Class for rendering email message. **Namespace:** [Cake\Mailer](namespace-cake.mailer) Constants --------- * `string` **TEMPLATE\_FOLDER** ``` 'email' ``` Constant for folder name containing email templates. Property Summary ---------------- * [$\_viewBuilder](#%24_viewBuilder) protected `Cake\View\ViewBuilder|null` The view builder instance being used. Method Summary -------------- * ##### [\_\_clone()](#__clone()) public Clone ViewBuilder instance when renderer is cloned. * ##### [\_\_construct()](#__construct()) public Constructor * ##### [createView()](#createView()) public Constructs the view class instance based on the current configuration. * ##### [render()](#render()) public Render text/HTML content. * ##### [reset()](#reset()) public Reset view builder to defaults. * ##### [set()](#set()) public Saves a variable or an associative array of variables for use inside a template. * ##### [viewBuilder()](#viewBuilder()) public Get the view builder being used. Method Detail ------------- ### \_\_clone() public ``` __clone(): void ``` Clone ViewBuilder instance when renderer is cloned. #### Returns `void` ### \_\_construct() public ``` __construct() ``` Constructor ### createView() public ``` createView(string|null $viewClass = null): Cake\View\View ``` Constructs the view class instance based on the current configuration. #### Parameters `string|null` $viewClass optional Optional namespaced class name of the View class to instantiate. #### Returns `Cake\View\View` #### Throws `Cake\View\Exception\MissingViewException` If view class was not found. ### render() public ``` render(string $content, array<string> $types = []): array<string, string> ``` Render text/HTML content. If there is no template set, the $content will be returned in a hash of the specified content types for the email. #### Parameters `string` $content The content. `array<string>` $types optional Content types to render. Valid array values are Message::MESSAGE\_HTML, Message::MESSAGE\_TEXT. #### Returns `array<string, string>` ### reset() public ``` reset(): $this ``` Reset view builder to defaults. #### Returns `$this` ### 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` ### viewBuilder() public ``` viewBuilder(): Cake\View\ViewBuilder ``` Get the view builder being used. #### Returns `Cake\View\ViewBuilder` Property Detail --------------- ### $\_viewBuilder protected The view builder instance being used. #### Type `Cake\View\ViewBuilder|null` cakephp Class MailContainsHtml Class MailContainsHtml ======================= MailContainsHtml **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 BasicAuthenticate Class BasicAuthenticate ======================== Basic Authentication adapter for AuthComponent. Provides Basic HTTP authentication support for AuthComponent. Basic Auth will authenticate users against the configured userModel and verify the username and passwords match. ### Using Basic auth Load `AuthComponent` in your controller's `initialize()` and add 'Basic' in 'authenticate' key ``` $this->loadComponent('Auth', [ 'authenticate' => ['Basic'] 'storage' => 'Memory', 'unauthorizedRedirect' => false, ]); ``` You should set `storage` to `Memory` to prevent CakePHP from sending a session cookie to the client. You should set `unauthorizedRedirect` to `false`. This causes `AuthComponent` to throw a `ForbiddenException` exception instead of redirecting to another page. Since HTTP Basic Authentication is stateless you don't need call `setUser()` in your controller. The user credentials will be checked on each request. If valid credentials are not provided, required authentication headers will be sent by this authentication provider which triggers the login dialog in the browser/client. **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 * ##### [\_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 Authenticate a user using HTTP auth. Will use the configured User model and attempt a login using HTTP auth. * ##### [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. Used by cookie-less auth for stateless clients. * ##### [implementedEvents()](#implementedEvents()) public Returns a list of all events that this authenticate class will listen to. * ##### [loginHeaders()](#loginHeaders()) public Generate the login headers * ##### [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 Handles an unauthenticated access attempt by sending appropriate login headers 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() public ``` authenticate(Cake\Http\ServerRequest $request, Cake\Http\Response $response): array<string, mixed>|false ``` Authenticate a user using HTTP auth. Will use the configured User model and attempt a login using HTTP auth. #### Parameters `Cake\Http\ServerRequest` $request The request to authenticate with. `Cake\Http\Response` $response The response to add headers to. #### 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. Used by cookie-less auth for stateless clients. #### 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>` ### loginHeaders() public ``` loginHeaders(Cake\Http\ServerRequest $request): array<string, string> ``` Generate the login headers #### Parameters `Cake\Http\ServerRequest` $request Request object. #### Returns `array<string, string>` ### 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 ``` Handles an unauthenticated access attempt by sending appropriate login headers * 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` #### Throws `Cake\Http\Exception\UnauthorizedException` 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 Trait PluginAssetsTrait Trait PluginAssetsTrait ======================== trait for symlinking / copying plugin assets to app's webroot. **Namespace:** [Cake\Command](namespace-cake.command) Property Summary ---------------- * [$args](#%24args) protected `Cake\Console\Arguments` Arguments * [$io](#%24io) protected `Cake\Console\ConsoleIo` Console IO Method Summary -------------- * ##### [\_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. Method Detail ------------- ### \_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` Property Detail --------------- ### $args protected Arguments #### Type `Cake\Console\Arguments` ### $io protected Console IO #### Type `Cake\Console\ConsoleIo` cakephp Class ConsoleIntegrationTestCase Class ConsoleIntegrationTestCase ================================= A test case class intended to make integration tests of cake console commands easier. **Abstract** **Namespace:** [Cake\TestSuite](namespace-cake.testsuite) **Deprecated:** 3.7.0 Will be removed in 5.0.0. Use {@link \Cake\TestSuite\ConsoleIntegrationTestTrait} 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. * [$\_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 * [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance * [$\_useCommandRunner](#%24_useCommandRunner) protected `bool` Whether to use the CommandRunner * [$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 * ##### [\_assertAttributes()](#_assertAttributes()) protected Check the attributes as part of an assertTags() check. * ##### [\_getTableClassName()](#_getTableClassName()) protected Gets the class name for the table. * ##### [\_normalizePath()](#_normalizePath()) protected Normalize a path for comparison. * ##### [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. * ##### [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). * ##### [assertErrorContains()](#assertErrorContains()) public Asserts `stderr` contains expected output * ##### [assertErrorEmpty()](#assertErrorEmpty()) public Asserts that `stderr` is empty * ##### [assertErrorRegExp()](#assertErrorRegExp()) public Asserts `stderr` contains expected regexp * ##### [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 * ##### [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 * ##### [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. * ##### [assertFinite()](#assertFinite()) public static Asserts that a variable is finite. * ##### [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. * ##### [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. * ##### [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. * ##### [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. * ##### [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 * ##### [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. * ##### [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 * ##### [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. * ##### [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. * ##### [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 * ##### [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. * ##### [clearPlugins()](#clearPlugins()) public Clear all plugins from the global plugin collection. * ##### [commandStringToArgs()](#commandStringToArgs()) protected Creates an $argv array from a command string * ##### [configApplication()](#configApplication()) public Configure the application class to use in integration tests. * ##### [containsEqual()](#containsEqual()) public static * ##### [containsIdentical()](#containsIdentical()) public static * ##### [containsOnly()](#containsOnly()) public static * ##### [containsOnlyInstancesOf()](#containsOnlyInstancesOf()) public static * ##### [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 * ##### [deprecated()](#deprecated()) public Helper method for check deprecation methods * ##### [directoryExists()](#directoryExists()) public static * ##### [doesNotPerformAssertions()](#doesNotPerformAssertions()) public * ##### [doubledTypes()](#doubledTypes()) public * ##### [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. * ##### [exec()](#exec()) public Runs CLI integration test * ##### [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 * ##### [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 * ##### [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 * ##### [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 * ##### [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 * ##### [makeRunner()](#makeRunner()) protected Builds the appropriate command dispatcher * ##### [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. * ##### [prophesize()](#prophesize()) protected * ##### [provides()](#provides()) public Returns the normalized test name as class::method. * ##### [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. * ##### [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 * ##### [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. * ##### [useCommandRunner()](#useCommandRunner()) public Set this test case to use the CommandRunner rather than the legacy ShellDispatcher * ##### [usesDataProvider()](#usesDataProvider()) public * ##### [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 ### \_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` ### \_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` ### \_normalizePath() protected ``` _normalizePath(string $path): string ``` Normalize a path for comparison. #### Parameters `string` $path Path separated by "/" slash. #### Returns `string` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### clearPlugins() public ``` clearPlugins(): void ``` Clear all plugins from the global plugin collection. Useful in test case teardown methods. #### 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` ### 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` ### 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` ### 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` ### doesNotPerformAssertions() public ``` doesNotPerformAssertions(): bool ``` #### Returns `bool` ### doubledTypes() public ``` doubledTypes(): string[] ``` #### Returns `string[]` ### 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` ### 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` ### 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` ### 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` ### 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() ``` ### 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` ### 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` ### makeRunner() protected ``` makeRunner(): Cake\Console\CommandRunnerCake\Console\TestSuite\LegacyCommandRunner ``` Builds the appropriate command dispatcher #### Returns `Cake\Console\CommandRunnerCake\Console\TestSuite\LegacyCommandRunner` ### 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` ### 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>` ### 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` ### 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` ### 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` ### useCommandRunner() public ``` useCommandRunner(): void ``` Set this test case to use the CommandRunner rather than the legacy ShellDispatcher #### Returns `void` ### usesDataProvider() public ``` usesDataProvider(): bool ``` #### Returns `bool` ### 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` ### $\_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` ### $\_tableLocator protected Table locator instance #### Type `Cake\ORM\Locator\LocatorInterface|null` ### $\_useCommandRunner protected Whether to use the CommandRunner #### Type `bool` ### $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 Namespace Schema Namespace Schema ================ ### Interfaces * ##### [CollectionInterface](interface-cake.database.schema.collectioninterface) Represents a database schema collection * ##### [SqlGeneratorInterface](interface-cake.database.schema.sqlgeneratorinterface) An interface used by TableSchema objects. * ##### [TableSchemaAwareInterface](interface-cake.database.schema.tableschemaawareinterface) Defines the interface for getting the schema. * ##### [TableSchemaInterface](interface-cake.database.schema.tableschemainterface) An interface used by database TableSchema objects. ### Classes * ##### [CachedCollection](class-cake.database.schema.cachedcollection) Decorates a schema collection and adds caching * ##### [Collection](class-cake.database.schema.collection) Represents a database schema collection * ##### [MysqlSchemaDialect](class-cake.database.schema.mysqlschemadialect) Schema generation/reflection features for MySQL * ##### [PostgresSchemaDialect](class-cake.database.schema.postgresschemadialect) Schema management/reflection features for Postgres. * ##### [SchemaDialect](class-cake.database.schema.schemadialect) Base class for schema implementations. * ##### [SqliteSchemaDialect](class-cake.database.schema.sqliteschemadialect) Schema management/reflection features for Sqlite * ##### [SqlserverSchemaDialect](class-cake.database.schema.sqlserverschemadialect) Schema management/reflection features for SQLServer. * ##### [TableSchema](class-cake.database.schema.tableschema) Represents a single table in a database schema. cakephp Class RequestHandlerComponent Class RequestHandlerComponent ============================== Request object handling for alternative HTTP requests. This Component checks for requests for different content types like JSON, XML, XMLHttpRequest(AJAX) and configures the response object and view builder accordingly. It can also check for HTTP caching headers like `Last-Modified`, `If-Modified-Since` etc. and return a response accordingly. **Namespace:** [Cake\Controller\Component](namespace-cake.controller.component) **Deprecated:** 4.4.0 See the 4.4 migration guide for how to upgrade. https://book.cakephp.org/4/en/appendices/4-4-migration-guide.html#requesthandlercomponent **Link:** https://book.cakephp.org/4/en/controllers/components/request-handling.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 * [$\_registry](#%24_registry) protected `Cake\Controller\ComponentRegistry` Component registry class used to lazy load components. * [$\_renderType](#%24_renderType) protected `string|null` The template type to use when rendering the given content type. * [$components](#%24components) protected `array` Other Components this component uses. * [$ext](#%24ext) protected `string|null` Contains the file extension parsed out by the Router Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. Parses the accepted content types accepted by the client using HTTP\_ACCEPT * ##### [\_\_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. * ##### [\_setExtension()](#_setExtension()) protected Set the extension based on the `Accept` header or URL extension. * ##### [accepts()](#accepts()) public deprecated Determines which content types the client accepts. Acceptance is based on the file extension parsed by the Router (if present), and by the HTTP\_ACCEPT header. Unlike {@link \Cake\Http\ServerRequest::accepts()} this method deals entirely with mapped content types. * ##### [beforeRender()](#beforeRender()) public Checks if the response can be considered different according to the request headers, and the caching response headers. If it was not modified, then the render process is skipped. And the client will get a blank response with a "304 Not Modified" header. * ##### [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. * ##### [getController()](#getController()) public Get the controller this component is bound to. * ##### [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. * ##### [mapAlias()](#mapAlias()) public Maps a content type alias back to its mime-type(s) * ##### [prefers()](#prefers()) public deprecated Determines which content-types the client prefers. If no parameters are given, the single content-type that the client most likely prefers is returned. If $type is an array, the first item in the array that the client accepts is returned. Preference is determined primarily by the file extension parsed by the Router if provided, and secondarily by the list of content-types provided in HTTP\_ACCEPT. * ##### [renderAs()](#renderAs()) public Sets either the view class if one exists or the layout and template path of the view. The names of these are derived from the $type input parameter. * ##### [requestedWith()](#requestedWith()) public Determines the content type of the data the client has sent (i.e. in a POST request) * ##### [respondAs()](#respondAs()) public Sets the response header based on type map index name. This wraps several methods available on {@link \Cake\Http\Response}. It also allows you to use Content-Type aliases. * ##### [setConfig()](#setConfig()) public Sets the config. * ##### [startup()](#startup()) public The startup method of the RequestHandler enables several automatic behaviors related to the detection of certain properties of the HTTP request, including: Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\Controller\ComponentRegistry $registry, array<string, mixed> $config = []) ``` Constructor. Parses the accepted content types accepted by the client using HTTP\_ACCEPT #### Parameters `Cake\Controller\ComponentRegistry` $registry ComponentRegistry object. `array<string, mixed>` $config optional Array of config. ### \_\_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 ### \_setExtension() protected ``` _setExtension(Cake\Http\ServerRequest $request, Cake\Http\Response $response): void ``` Set the extension based on the `Accept` header or URL extension. Compares the accepted types and configured extensions. If there is one common type, that is assigned as the ext/content type for the response. The type with the highest weight will be set. If the highest weight has more than one type matching the extensions, the order in which extensions are specified determines which type will be set. If html is one of the preferred types, no content type will be set, this is to avoid issues with browsers that prefer HTML and several other content types. #### Parameters `Cake\Http\ServerRequest` $request The request instance. `Cake\Http\Response` $response The response instance. #### Returns `void` ### accepts() public ``` accepts(array<string>|string|null $type = null): array|bool|string|null ``` Determines which content types the client accepts. Acceptance is based on the file extension parsed by the Router (if present), and by the HTTP\_ACCEPT header. Unlike {@link \Cake\Http\ServerRequest::accepts()} this method deals entirely with mapped content types. Usage: ``` $this->RequestHandler->accepts(['xml', 'html', 'json']); ``` Returns true if the client accepts any of the supplied types. ``` $this->RequestHandler->accepts('xml'); ``` Returns true if the client accepts XML. #### Parameters `array<string>|string|null` $type optional Can be null (or no parameter), a string type name, or an array of types #### Returns `array|bool|string|null` ### beforeRender() public ``` beforeRender(Cake\Event\EventInterface $event): void ``` Checks if the response can be considered different according to the request headers, and the caching response headers. If it was not modified, then the render process is skipped. And the client will get a blank response with a "304 Not Modified" header. * If Router::extensions() is enabled, the layout and template type are switched based on the parsed extension or `Accept` header. For example, if `controller/action.xml` is requested, the view path becomes `templates/Controller/xml/action.php`. Also, if `controller/action` is requested with `Accept: application/xml` in the headers the view path will become `templates/Controller/xml/action.php`. Layout and template types will only switch to mime-types recognized by \Cake\Http\Response. If you need to declare additional mime-types, you can do so using {@link \Cake\Http\Response::setTypeMap()} in your controller's beforeFilter() method. * If a helper with the same name as the extension exists, it is added to the controller. * If the extension is of a type that RequestHandler understands, it will set that Content-type in the response header. #### Parameters `Cake\Event\EventInterface` $event The Controller.beforeRender event. #### Returns `void` #### Throws `Cake\Http\Exception\NotFoundException` If invoked extension is not configured. ### 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` ### getController() public ``` getController(): Cake\Controller\Controller ``` Get the controller this component is bound to. #### Returns `Cake\Controller\Controller` ### 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` ### mapAlias() public ``` mapAlias(array|string $alias): array|string|null ``` Maps a content type alias back to its mime-type(s) #### Parameters `array|string` $alias String alias to convert back into a content type. Or an array of aliases to map. #### Returns `array|string|null` ### prefers() public ``` prefers(array<string>|string|null $type = null): string|bool|null ``` Determines which content-types the client prefers. If no parameters are given, the single content-type that the client most likely prefers is returned. If $type is an array, the first item in the array that the client accepts is returned. Preference is determined primarily by the file extension parsed by the Router if provided, and secondarily by the list of content-types provided in HTTP\_ACCEPT. #### Parameters `array<string>|string|null` $type optional An optional array of 'friendly' content-type names, i.e. 'html', 'xml', 'js', etc. #### Returns `string|bool|null` ### renderAs() public ``` renderAs(Cake\Controller\Controller $controller, string $type, array<string, mixed> $options = []): void ``` Sets either the view class if one exists or the layout and template path of the view. The names of these are derived from the $type input parameter. ### Usage: Render the response as an 'ajax' response. ``` $this->RequestHandler->renderAs($this, 'ajax'); ``` Render the response as an XML file and force the result as a file download. ``` $this->RequestHandler->renderAs($this, 'xml', ['attachment' => 'myfile.xml']; ``` #### Parameters `Cake\Controller\Controller` $controller A reference to a controller object `string` $type Type of response to send (e.g: 'ajax') `array<string, mixed>` $options optional Array of options to use #### Returns `void` #### See Also \Cake\Controller\Component\RequestHandlerComponent::respondAs() ### requestedWith() public ``` requestedWith(array<string>|string|null $type = null): mixed ``` Determines the content type of the data the client has sent (i.e. in a POST request) #### Parameters `array<string>|string|null` $type optional Can be null (or no parameter), a string type name, or an array of types #### Returns `mixed` ### respondAs() public ``` respondAs(string $type, array<string, mixed> $options = []): bool ``` Sets the response header based on type map index name. This wraps several methods available on {@link \Cake\Http\Response}. It also allows you to use Content-Type aliases. #### Parameters `string` $type Friendly type name, i.e. 'html' or 'xml', or a full content-type, like 'application/x-shockwave'. `array<string, mixed>` $options optional If $type is a friendly type name that is associated with more than one type of content, $index is used to select which content-type to use. #### 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. ### startup() public ``` startup(Cake\Event\EventInterface $event): void ``` The startup method of the RequestHandler enables several automatic behaviors related to the detection of certain properties of the HTTP request, including: If the XML data is POSTed, the data is parsed into an XML object, which is assigned to the $data property of the controller, which can then be saved to a model object. #### Parameters `Cake\Event\EventInterface` $event The startup event that was fired. #### Returns `void` 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. * `checkHttpCache` - Whether to check for HTTP cache. Default `true`. * `viewClassMap` - Mapping between type and view classes. If undefined JSON, XML, and AJAX will be mapped. Defining any types will omit the defaults. #### Type `array<string, mixed>` ### $\_registry protected Component registry class used to lazy load components. #### Type `Cake\Controller\ComponentRegistry` ### $\_renderType protected The template type to use when rendering the given content type. #### Type `string|null` ### $components protected Other Components this component uses. #### Type `array` ### $ext protected Contains the file extension parsed out by the Router #### Type `string|null`
programming_docs
cakephp Class MissingResponseException Class MissingResponseException =============================== Used to indicate that a request did not have a matching mock response. **Namespace:** [Cake\Http\Client\Exception](namespace-cake.http.client.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 TextareaWidget Class TextareaWidget ===================== Input widget class for generating a textarea control. This class is usually used internally by `Cake\View\Helper\FormHelper`, it but can be used to generate standalone text areas. **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 text area 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 text area form widget. Data supports the following keys: * `name` - Set the input name. * `val` - A string of the option to mark as selected. * `escape` - Set to false to disable HTML escaping. All other keys will be converted into HTML attributes. #### Parameters `array<string, mixed>` $data The data to build a textarea 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 Namespace Engine Namespace Engine ================ ### Classes * ##### [ArrayLog](class-cake.log.engine.arraylog) Array logger. * ##### [BaseLog](class-cake.log.engine.baselog) Base log engine class. * ##### [ConsoleLog](class-cake.log.engine.consolelog) Console logging. Writes logs to console output. * ##### [FileLog](class-cake.log.engine.filelog) File Storage stream for Logging. Writes logs to different files based on the level of log it is. * ##### [SyslogLog](class-cake.log.engine.sysloglog) Syslog stream for Logging. Writes logs to the system logger cakephp Class TestSuite Class TestSuite ================ A class to contain test cases and run them with shared fixtures **Namespace:** [Cake\TestSuite](namespace-cake.testsuite) Property Summary ---------------- * [$backupGlobals](#%24backupGlobals) protected `bool` Enable or disable the backup and restoration of the $GLOBALS array. * [$backupStaticAttributes](#%24backupStaticAttributes) protected `bool` Enable or disable the backup and restoration of static attributes. * [$foundClasses](#%24foundClasses) protected `string[]` * [$groups](#%24groups) protected The test groups of the test suite. * [$name](#%24name) protected `string` The name of the test suite. * [$numTests](#%24numTests) protected `int` The number of tests in the test suite. * [$providedTests](#%24providedTests) protected `null|list<ExecutionOrderDependency>` * [$requiredTests](#%24requiredTests) protected `null|list<ExecutionOrderDependency>` * [$runTestInSeparateProcess](#%24runTestInSeparateProcess) protected `bool` * [$testCase](#%24testCase) protected `bool` * [$tests](#%24tests) protected `Test[]` The tests in the test suite. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructs a new TestSuite. * ##### [addTest()](#addTest()) public Adds a test to the suite. * ##### [addTestDirectory()](#addTestDirectory()) public Adds all the files in a directory to the test suite. Does not recursive through directories. * ##### [addTestDirectoryRecursive()](#addTestDirectoryRecursive()) public Recursively adds all the files in a directory to the test suite. * ##### [addTestFile()](#addTestFile()) public Wraps both `addTest()` and `addTestSuite` as well as the separate import statements for the user's convenience. * ##### [addTestFiles()](#addTestFiles()) public Wrapper for addTestFile() that adds multiple test files. * ##### [addTestMethod()](#addTestMethod()) protected * ##### [addTestSuite()](#addTestSuite()) public Adds the tests from the given class to the suite. * ##### [addWarning()](#addWarning()) public * ##### [count()](#count()) public Counts the number of test cases that will be run by this test. * ##### [createResult()](#createResult()) protected Creates a default TestResult object. * ##### [getGroupDetails()](#getGroupDetails()) public * ##### [getGroups()](#getGroups()) public Returns the test groups of the suite. * ##### [getIterator()](#getIterator()) public Returns an iterator for this test suite. * ##### [getName()](#getName()) public Returns the name of the suite. * ##### [injectFilter()](#injectFilter()) public * ##### [markTestSuiteSkipped()](#markTestSuiteSkipped()) public Mark the test suite as skipped. * ##### [provides()](#provides()) public * ##### [requires()](#requires()) public * ##### [run()](#run()) public Runs the tests and collects their result in a TestResult. * ##### [setBackupGlobals()](#setBackupGlobals()) public * ##### [setBackupStaticAttributes()](#setBackupStaticAttributes()) public * ##### [setBeStrictAboutChangesToGlobalState()](#setBeStrictAboutChangesToGlobalState()) public * ##### [setGroupDetails()](#setGroupDetails()) public Set tests groups of the test case. * ##### [setName()](#setName()) public * ##### [setRunTestInSeparateProcess()](#setRunTestInSeparateProcess()) public * ##### [setTests()](#setTests()) public Set tests of the test suite. * ##### [sortId()](#sortId()) public * ##### [tests()](#tests()) public Returns the tests as an enumeration. * ##### [toString()](#toString()) public Returns a string representation of the test suite. * ##### [warnings()](#warnings()) public Method Detail ------------- ### \_\_construct() public ``` __construct(ReflectionClass|string $theClass = '', string $name = '') ``` Constructs a new TestSuite. * PHPUnit\Framework\TestSuite() constructs an empty TestSuite. * PHPUnit\Framework\TestSuite(ReflectionClass) constructs a TestSuite from the given class. * PHPUnit\Framework\TestSuite(ReflectionClass, String) constructs a TestSuite from the given class with the given name. * PHPUnit\Framework\TestSuite(String) either constructs a TestSuite from the given class (if the passed string is the name of an existing class) or constructs an empty TestSuite with the given name. #### Parameters `ReflectionClass|string` $theClass optional `string` $name optional #### Throws `Exception` ### addTest() public ``` addTest(Test $test, array $groups = []): void ``` Adds a test to the suite. #### Parameters `Test` $test `array` $groups optional #### Returns `void` ### addTestDirectory() public ``` addTestDirectory(string $directory = '.'): void ``` Adds all the files in a directory to the test suite. Does not recursive through directories. #### Parameters `string` $directory optional The directory to add tests from. #### Returns `void` ### addTestDirectoryRecursive() public ``` addTestDirectoryRecursive(string $directory = '.'): void ``` Recursively adds all the files in a directory to the test suite. #### Parameters `string` $directory optional The directory subtree to add tests from. #### Returns `void` ### addTestFile() public ``` addTestFile(string $filename): void ``` Wraps both `addTest()` and `addTestSuite` as well as the separate import statements for the user's convenience. If the named file cannot be read or there are no new tests that can be added, a `PHPUnit\Framework\WarningTestCase` will be created instead, leaving the current test run untouched. #### Parameters `string` $filename #### Returns `void` #### Throws `Exception` ### addTestFiles() public ``` addTestFiles(iterable $fileNames): void ``` Wrapper for addTestFile() that adds multiple test files. #### Parameters `iterable` $fileNames #### Returns `void` #### Throws `Exception` ### addTestMethod() protected ``` addTestMethod(ReflectionClass $class, ReflectionMethod $method): void ``` #### Parameters `ReflectionClass` $class `ReflectionMethod` $method #### Returns `void` #### Throws `Exception` ### addTestSuite() public ``` addTestSuite(mixed $testClass): void ``` Adds the tests from the given class to the suite. #### Parameters $testClass #### Returns `void` #### Throws `Exception` ### addWarning() public ``` addWarning(string $warning): void ``` #### Parameters `string` $warning #### Returns `void` ### count() public ``` count(): int ``` Counts the number of test cases that will be run by this test. #### Returns `int` ### createResult() protected ``` createResult(): TestResult ``` Creates a default TestResult object. #### Returns `TestResult` ### getGroupDetails() public ``` getGroupDetails(): array ``` #### Returns `array` ### getGroups() public ``` getGroups(): array ``` Returns the test groups of the suite. #### Returns `array` ### getIterator() public ``` getIterator(): Iterator ``` Returns an iterator for this test suite. #### Returns `Iterator` ### getName() public ``` getName(): string ``` Returns the name of the suite. #### Returns `string` ### injectFilter() public ``` injectFilter(Factory $filter): void ``` #### Parameters `Factory` $filter #### Returns `void` ### markTestSuiteSkipped() public ``` markTestSuiteSkipped(string $message = ''): void ``` Mark the test suite as skipped. #### Parameters `string` $message optional #### Returns `void` #### Throws `SkippedTestSuiteError` ### provides() public ``` provides(): list<ExecutionOrderDependency> ``` #### Returns `list<ExecutionOrderDependency>` ### requires() public ``` requires(): list<ExecutionOrderDependency> ``` #### Returns `list<ExecutionOrderDependency>` ### run() public ``` run(TestResult $result = null): TestResult ``` Runs the tests and collects their result in a TestResult. #### Parameters `TestResult` $result optional #### Returns `TestResult` #### Throws `PHPUnit\Framework\CodeCoverageException` `SebastianBergmann\CodeCoverage\InvalidArgumentException` `SebastianBergmann\CodeCoverage\UnintentionallyCoveredCodeException` `SebastianBergmann\RecursionContext\InvalidArgumentException` `Warning` ### 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` ### setGroupDetails() public ``` setGroupDetails(array $groups): void ``` Set tests groups of the test case. #### Parameters `array` $groups #### Returns `void` ### setName() public ``` setName(string $name): void ``` #### Parameters `string` $name #### Returns `void` ### setRunTestInSeparateProcess() public ``` setRunTestInSeparateProcess(bool $runTestInSeparateProcess): void ``` #### Parameters `bool` $runTestInSeparateProcess #### Returns `void` ### setTests() public ``` setTests(Test[] $tests): void ``` Set tests of the test suite. #### Parameters `Test[]` $tests #### Returns `void` ### sortId() public ``` sortId(): string ``` #### Returns `string` ### tests() public ``` tests(): Test[] ``` Returns the tests as an enumeration. #### Returns `Test[]` ### toString() public ``` toString(): string ``` Returns a string representation of the test suite. #### Returns `string` ### warnings() public ``` warnings(): array ``` #### Returns `array` Property Detail --------------- ### $backupGlobals protected Enable or disable the backup and restoration of the $GLOBALS array. #### Type `bool` ### $backupStaticAttributes protected Enable or disable the backup and restoration of static attributes. #### Type `bool` ### $foundClasses protected #### Type `string[]` ### $groups protected The test groups of the test suite. #### Type ### $name protected The name of the test suite. #### Type `string` ### $numTests protected The number of tests in the test suite. #### Type `int` ### $providedTests protected #### Type `null|list<ExecutionOrderDependency>` ### $requiredTests protected #### Type `null|list<ExecutionOrderDependency>` ### $runTestInSeparateProcess protected #### Type `bool` ### $testCase protected #### Type `bool` ### $tests protected The tests in the test suite. #### Type `Test[]` cakephp Interface TranslateStrategyInterface Interface TranslateStrategyInterface ===================================== This interface describes the methods for translate behavior strategies. **Namespace:** [Cake\ORM\Behavior\Translate](namespace-cake.orm.behavior.translate) Method Summary -------------- * ##### [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. * ##### [getLocale()](#getLocale()) public Returns the current locale. * ##### [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 * ##### [setLocale()](#setLocale()) public Sets the locale to be used. * ##### [translationField()](#translationField()) public Returns a fully aliased field name for translated fields. Method Detail ------------- ### 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. #### 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` ### 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` ### 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` ### 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` ### 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`
programming_docs
cakephp Class HttpsEnforcerMiddleware Class HttpsEnforcerMiddleware ============================== Enforces use of HTTPS (SSL) for requests. **Namespace:** [Cake\Http\Middleware](namespace-cake.http.middleware) Property Summary ---------------- * [$config](#%24config) protected `array<string, mixed>` Configuration. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [addHsts()](#addHsts()) protected Adds Strict-Transport-Security header to response. * ##### [process()](#process()) public Check whether request has been made using HTTPS. Method Detail ------------- ### \_\_construct() public ``` __construct(array<string, mixed> $config = []) ``` Constructor #### Parameters `array<string, mixed>` $config optional The options to use. #### See Also \Cake\Http\Middleware\HttpsEnforcerMiddleware::$config ### addHsts() protected ``` addHsts(Psr\Http\Message\ResponseInterface $response): Psr\Http\Message\ResponseInterface ``` Adds Strict-Transport-Security header to response. #### Parameters `Psr\Http\Message\ResponseInterface` $response Response #### Returns `Psr\Http\Message\ResponseInterface` ### process() public ``` process(ServerRequestInterface $request, RequestHandlerInterface $handler): Psr\Http\Message\ResponseInterface ``` Check whether request has been made using HTTPS. Depending on the configuration and request method, either redirects to same URL with https or throws an exception. #### Parameters `ServerRequestInterface` $request The request. `RequestHandlerInterface` $handler The request handler. #### Returns `Psr\Http\Message\ResponseInterface` #### Throws `Cake\Http\Exception\BadRequestException` Property Detail --------------- ### $config protected Configuration. ### Options * `redirect` - If set to true (default) redirects GET requests to same URL with https. * `statusCode` - Status code to use in case of redirect, defaults to 301 - Permanent redirect. * `headers` - Array of response headers in case of redirect. * `disableOnDebug` - Whether HTTPS check should be disabled when debug is on. Default `true`. * 'hsts' - Strict-Transport-Security header for HTTPS response configuration. Defaults to `null`. If enabled, an array of config options: * 'maxAge' - `max-age` directive value in seconds. + 'includeSubDomains' - Whether to include `includeSubDomains` directive. Defaults to `false`. + 'preload' - Whether to include 'preload' directive. Defauls to `false`. #### Type `array<string, mixed>` cakephp Class SaveOptionsBuilder Class SaveOptionsBuilder ========================= OOP style Save Option Builder. This allows you to build options to save entities in a OOP style and helps you to avoid mistakes by validating the options as you build them. **Namespace:** [Cake\ORM](namespace-cake.orm) **Deprecated:** 4.4.0 Use a normal array for options instead. **See:** \Cake\Datasource\RulesChecker Property Summary ---------------- * [$\_options](#%24_options) protected `array<string, mixed>` Options * [$\_table](#%24_table) protected `Cake\ORM\Table` Table object. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [\_associated()](#_associated()) protected Checks that the associations exists recursively. * ##### [\_checkAssociation()](#_checkAssociation()) protected Checks if an association exists. * ##### [\_normalizeAssociations()](#_normalizeAssociations()) protected Returns an array out of the original passed associations list where dot notation is transformed into nested arrays so that they can be parsed by other routines * ##### [associated()](#associated()) public Set associated options. * ##### [atomic()](#atomic()) public Sets the atomic option. * ##### [checkExisting()](#checkExisting()) public Set check existing option. * ##### [checkRules()](#checkRules()) public Option to check the rules. * ##### [guard()](#guard()) public Set the guard option. * ##### [parseArrayOptions()](#parseArrayOptions()) public Takes an options array and populates the option object with the data. * ##### [set()](#set()) public Setting custom options. * ##### [toArray()](#toArray()) public * ##### [validate()](#validate()) public Set the validation rule set to use. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\ORM\Table $table, array<string, mixed> $options = []) ``` Constructor. #### Parameters `Cake\ORM\Table` $table A table instance. `array<string, mixed>` $options optional Options to parse when instantiating. ### \_associated() protected ``` _associated(Cake\ORM\Table $table, array $associations): void ``` Checks that the associations exists recursively. #### Parameters `Cake\ORM\Table` $table Table object. `array` $associations An associations array. #### Returns `void` ### \_checkAssociation() protected ``` _checkAssociation(Cake\ORM\Table $table, string $association): void ``` Checks if an association exists. #### Parameters `Cake\ORM\Table` $table Table object. `string` $association Association name. #### Returns `void` #### Throws `RuntimeException` If no such association exists for the given table. ### \_normalizeAssociations() protected ``` _normalizeAssociations(array|string $associations): array ``` Returns an array out of the original passed associations list where dot notation is transformed into nested arrays so that they can be parsed by other routines #### Parameters `array|string` $associations The array of included associations. #### Returns `array` ### associated() public ``` associated(array|string $associated): $this ``` Set associated options. #### Parameters `array|string` $associated String or array of associations. #### Returns `$this` ### atomic() public ``` atomic(bool $atomic): $this ``` Sets the atomic option. #### Parameters `bool` $atomic Atomic or not. #### Returns `$this` ### checkExisting() public ``` checkExisting(bool $checkExisting): $this ``` Set check existing option. #### Parameters `bool` $checkExisting Guard the properties or not. #### Returns `$this` ### checkRules() public ``` checkRules(bool $checkRules): $this ``` Option to check the rules. #### Parameters `bool` $checkRules Check the rules or not. #### Returns `$this` ### guard() public ``` guard(bool $guard): $this ``` Set the guard option. #### Parameters `bool` $guard Guard the properties or not. #### Returns `$this` ### parseArrayOptions() public ``` parseArrayOptions(array<string, mixed> $array): $this ``` Takes an options array and populates the option object with the data. This can be used to turn an options array into the object. #### Parameters `array<string, mixed>` $array Options array. #### Returns `$this` #### Throws `InvalidArgumentException` If a given option key does not exist. ### set() public ``` set(string $option, mixed $value): $this ``` Setting custom options. #### Parameters `string` $option Option key. `mixed` $value Option value. #### Returns `$this` ### toArray() public ``` toArray(): array<string, mixed> ``` #### Returns `array<string, mixed>` ### validate() public ``` validate(string $validate): $this ``` Set the validation rule set to use. #### Parameters `string` $validate Name of the validation rule set to use. #### Returns `$this` Property Detail --------------- ### $\_options protected Options #### Type `array<string, mixed>` ### $\_table protected Table object. #### Type `Cake\ORM\Table` cakephp Trait TestListenerTrait Trait TestListenerTrait ======================== Implements empty default methods for PHPUnit\Framework\TestListener. **Namespace:** [Cake\TestSuite](namespace-cake.testsuite) Method Summary -------------- * ##### [addError()](#addError()) public * ##### [addFailure()](#addFailure()) public * ##### [addIncompleteTest()](#addIncompleteTest()) public * ##### [addRiskyTest()](#addRiskyTest()) public * ##### [addSkippedTest()](#addSkippedTest()) public * ##### [addWarning()](#addWarning()) public * ##### [endTest()](#endTest()) public * ##### [endTestSuite()](#endTestSuite()) public * ##### [startTest()](#startTest()) public * ##### [startTestSuite()](#startTestSuite()) public Method Detail ------------- ### addError() public ``` addError(Test $test, Throwable $t, float $time): void ``` #### Parameters `Test` $test `Throwable` $t `float` $time #### Returns `void` ### addFailure() public ``` addFailure(Test $test, AssertionFailedError $e, float $time): void ``` #### Parameters `Test` $test `AssertionFailedError` $e `float` $time #### Returns `void` ### addIncompleteTest() public ``` addIncompleteTest(Test $test, Throwable $t, float $time): void ``` #### Parameters `Test` $test `Throwable` $t `float` $time #### Returns `void` ### addRiskyTest() public ``` addRiskyTest(Test $test, Throwable $t, float $time): void ``` #### Parameters `Test` $test `Throwable` $t `float` $time #### Returns `void` ### addSkippedTest() public ``` addSkippedTest(Test $test, Throwable $t, float $time): void ``` #### Parameters `Test` $test `Throwable` $t `float` $time #### Returns `void` ### addWarning() public ``` addWarning(Test $test, Warning $e, float $time): void ``` #### Parameters `Test` $test `Warning` $e `float` $time #### Returns `void` ### endTest() public ``` endTest(Test $test, float $time): void ``` #### Parameters `Test` $test `float` $time #### Returns `void` ### endTestSuite() public ``` endTestSuite(TestSuite $suite): void ``` #### Parameters `TestSuite` $suite #### Returns `void` ### startTest() public ``` startTest(Test $test): void ``` #### Parameters `Test` $test #### Returns `void` ### startTestSuite() public ``` startTestSuite(TestSuite $suite): void ``` #### Parameters `TestSuite` $suite #### Returns `void` cakephp Interface ContainerApplicationInterface Interface ContainerApplicationInterface ======================================== Interface for applications that configure and use a dependency injection container. **Namespace:** [Cake\Core](namespace-cake.core) Method Summary -------------- * ##### [getContainer()](#getContainer()) public Create a new container and register services. * ##### [services()](#services()) public Register services to the container Method Detail ------------- ### getContainer() public ``` getContainer(): Cake\Core\ContainerInterface ``` Create a new container and register services. This will `register()` services provided by both the application and any plugins if the application has plugin support. #### Returns `Cake\Core\ContainerInterface` ### services() public ``` services(Cake\Core\ContainerInterface $container): void ``` Register services to the container Registered services can have instances fetched out of the container using `get()`. Dependencies and parameters will be resolved based on service definitions. #### Parameters `Cake\Core\ContainerInterface` $container The container to add services to #### Returns `void` cakephp Namespace Auth Namespace Auth ============== ### Namespaces * [Cake\Auth\Storage](namespace-cake.auth.storage) ### Classes * ##### [AbstractPasswordHasher](class-cake.auth.abstractpasswordhasher) Abstract password hashing class * ##### [BaseAuthenticate](class-cake.auth.baseauthenticate) Base Authentication class with common methods and properties. * ##### [BaseAuthorize](class-cake.auth.baseauthorize) Abstract base authorization adapter for AuthComponent. * ##### [BasicAuthenticate](class-cake.auth.basicauthenticate) Basic Authentication adapter for AuthComponent. * ##### [ControllerAuthorize](class-cake.auth.controllerauthorize) An authorization adapter for AuthComponent. Provides the ability to authorize using a controller callback. Your controller's isAuthorized() method should return a boolean to indicate whether the user is authorized. * ##### [DefaultPasswordHasher](class-cake.auth.defaultpasswordhasher) Default password hashing class. * ##### [DigestAuthenticate](class-cake.auth.digestauthenticate) Digest Authentication adapter for AuthComponent. * ##### [FallbackPasswordHasher](class-cake.auth.fallbackpasswordhasher) A password hasher that can use multiple different hashes where only one is the preferred one. This is useful when trying to migrate an existing database of users from one password type to another. * ##### [FormAuthenticate](class-cake.auth.formauthenticate) Form authentication adapter for AuthComponent. * ##### [PasswordHasherFactory](class-cake.auth.passwordhasherfactory) Builds password hashing objects * ##### [WeakPasswordHasher](class-cake.auth.weakpasswordhasher) Password hashing class that use weak hashing algorithms. This class is intended only to be used with legacy databases where passwords have not been migrated to a stronger algorithm yet. cakephp Class WhenThenExpression Class WhenThenExpression ========================= Represents a SQL when/then clause with a fluid API **Namespace:** [Cake\Database\Expression](namespace-cake.database.expression) Property Summary ---------------- * [$\_typeMap](#%24_typeMap) protected `Cake\Database\TypeMap` The type map to use when using an array of conditions for the `WHEN` value. * [$hasThenBeenDefined](#%24hasThenBeenDefined) protected `bool` Whether the `THEN` value has been defined, eg whether `then()` has been invoked. * [$then](#%24then) protected `Cake\Database\ExpressionInterface|object|scalar|null` The `THEN` value. * [$thenType](#%24thenType) protected `string|null` The `THEN` result type. * [$validClauseNames](#%24validClauseNames) protected `array<string>` The names of the clauses that are valid for use with the `clause()` method. * [$when](#%24when) protected `Cake\Database\ExpressionInterface|object|scalar|null` Then `WHEN` value. * [$whenType](#%24whenType) protected `array|string|null` The `WHEN` value type. 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. * ##### [getResultType()](#getResultType()) public Returns the expression's result value type. * ##### [inferType()](#inferType()) protected Infers the abstract type for the given value. * ##### [sql()](#sql()) public Converts the Node into a SQL string fragment. * ##### [then()](#then()) public Sets the `THEN` result value. * ##### [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. Method Detail ------------- ### \_\_clone() public ``` __clone(): void ``` Clones the inner expression objects. #### Returns `void` ### \_\_construct() public ``` __construct(Cake\Database\TypeMap|null $typeMap = null) ``` Constructor. #### Parameters `Cake\Database\TypeMap|null` $typeMap optional The type map to use when using an array of conditions for the `WHEN` 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|scalar|null ``` Returns the available data for the given clause. ### Available clauses The following clause names are available: * `when`: The `WHEN` value. * `then`: The `THEN` result value. #### Parameters `string` $clause The name of the clause to obtain. #### Returns `Cake\Database\ExpressionInterface|object|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` ### getResultType() public ``` getResultType(): string|null ``` Returns the expression's result value type. #### Returns `string|null` #### See Also WhenThenExpression::then() ### 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` ### 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. #### 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 inferred from the given result value. #### Returns `$this` ### 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\ExpressionInterface|object|array|scalar $when, array<string, string>|string|null $type = null): $this ``` Sets the `WHEN` value. #### Parameters `Cake\Database\ExpressionInterface|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 `InvalidArgumentException` In case the `$when` argument is neither a non-empty array, nor a scalar value, an object, or an instance of `\Cake\Database\ExpressionInterface`. `InvalidArgumentException` In case the `$type` argument is neither an array, a string, nor null. `InvalidArgumentException` In case the `$when` argument is an array, and the `$type` argument is neither an array, nor null. `InvalidArgumentException` In case the `$when` argument is a non-array value, and the `$type` argument is neither a string, nor null. #### See Also CaseStatementExpression::when() for a more detailed usage explanation. Property Detail --------------- ### $\_typeMap protected The type map to use when using an array of conditions for the `WHEN` value. #### Type `Cake\Database\TypeMap` ### $hasThenBeenDefined protected Whether the `THEN` value has been defined, eg whether `then()` has been invoked. #### Type `bool` ### $then protected The `THEN` value. #### Type `Cake\Database\ExpressionInterface|object|scalar|null` ### $thenType protected The `THEN` result type. #### Type `string|null` ### $validClauseNames protected The names of the clauses that are valid for use with the `clause()` method. #### Type `array<string>` ### $when protected Then `WHEN` value. #### Type `Cake\Database\ExpressionInterface|object|scalar|null` ### $whenType protected The `WHEN` value type. #### Type `array|string|null`
programming_docs
cakephp Namespace Exception Namespace Exception =================== ### Classes * ##### [I18nException](class-cake.i18n.exception.i18nexception) I18n exception. cakephp Class RelativeTimeFormatter Class RelativeTimeFormatter ============================ Helper class for formatting relative dates & times. **Namespace:** [Cake\I18n](namespace-cake.i18n) Method Summary -------------- * ##### [\_diffData()](#_diffData()) protected Calculate the data needed to format a relative difference string. * ##### [\_options()](#_options()) protected Build the options for relative date formatting. * ##### [dateAgoInWords()](#dateAgoInWords()) public Format a into a relative date string. * ##### [diffForHumans()](#diffForHumans()) public Get the difference in a human readable format. * ##### [timeAgoInWords()](#timeAgoInWords()) public Format a into a relative timestring. Method Detail ------------- ### \_diffData() protected ``` _diffData(string|int $futureTime, string|int $pastTime, bool $backwards, array<string, mixed> $options): array ``` Calculate the data needed to format a relative difference string. #### Parameters `string|int` $futureTime The timestamp from the future. `string|int` $pastTime The timestamp from the past. `bool` $backwards Whether the difference was backwards. `array<string, mixed>` $options An array of options. #### Returns `array` ### \_options() protected ``` _options(array<string, mixed> $options, string $class): array<string, mixed> ``` Build the options for relative date formatting. #### Parameters `array<string, mixed>` $options The options provided by the user. `string` $class The class name to use for defaults. #### Returns `array<string, mixed>` ### dateAgoInWords() public ``` dateAgoInWords(Cake\I18n\I18nDateTimeInterface $date, array<string, mixed> $options = []): string ``` Format a into a relative date string. #### Parameters `Cake\I18n\I18nDateTimeInterface` $date The date to format. `array<string, mixed>` $options optional Array of options. #### Returns `string` #### See Also \Cake\I18n\Date::timeAgoInWords() ### diffForHumans() public ``` diffForHumans(Cake\Chronos\ChronosInterface $date, Cake\Chronos\ChronosInterface|null $other = null, bool $absolute = false): string ``` Get the difference in a human readable format. #### Parameters `Cake\Chronos\ChronosInterface` $date The datetime to start with. `Cake\Chronos\ChronosInterface|null` $other optional The datetime to compare against. `bool` $absolute optional Removes time difference modifiers ago, after, etc. #### Returns `string` #### See Also \Cake\Chronos\ChronosInterface::diffForHumans ### timeAgoInWords() public ``` timeAgoInWords(Cake\I18n\I18nDateTimeInterface $time, array<string, mixed> $options = []): string ``` Format a into a relative timestring. #### Parameters `Cake\I18n\I18nDateTimeInterface` $time The time instance to format. `array<string, mixed>` $options optional Array of options. #### Returns `string` #### See Also \Cake\I18n\Time::timeAgoInWords() cakephp Class MemcachedEngine Class MemcachedEngine ====================== Memcached storage engine for cache. Memcached has some limitations in the amount of control you have over expire times far in the future. See MemcachedEngine::write() for more information. Memcached engine supports binary protocol and igbinary serialization (if memcached extension is compiled with --enable-igbinary). Compressed keys can also be incremented/decremented. **Namespace:** [Cake\Cache\Engine](namespace-cake.cache.engine) Constants --------- * `string` **CHECK\_KEY** ``` 'key' ``` * `string` **CHECK\_VALUE** ``` 'value' ``` Property Summary ---------------- * [$\_Memcached](#%24_Memcached) protected `Memcached` memcached wrapper. * [$\_compiledGroupNames](#%24_compiledGroupNames) protected `array<string>` * [$\_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 config used unless overridden by runtime configuration * [$\_groupPrefix](#%24_groupPrefix) protected `string` Contains the compiled string with all group prefixes to be prepended to every key in this cache engine * [$\_serializers](#%24_serializers) protected `array<string, int>` List of available serializer engines 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. * ##### [\_setOptions()](#_setOptions()) protected Settings the memcached instance * ##### [add()](#add()) public Add a key to the cache if it does not already exist. * ##### [clear()](#clear()) public Delete all keys from the cache * ##### [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 Delete many keys from the cache at once * ##### [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 Read many keys from the cache at once * ##### [getOption()](#getOption()) public Read an option value from the memcached connection. * ##### [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 * ##### [parseServerString()](#parseServerString()) public Parses the server address into the host/port. Handles both IPv6 and IPv4 addresses and Unix sockets * ##### [set()](#set()) public Write data for key into cache. When using memcached as your cache engine remember that the Memcached pecl extension does not support cache expiry times greater than 30 days in the future. Any duration greater than 30 days will be treated as real Unix time value rather than an offset from current time. * ##### [setConfig()](#setConfig()) public Sets the config. * ##### [setMultiple()](#setMultiple()) public Write many cache entries to the cache at once * ##### [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. ### \_setOptions() protected ``` _setOptions(): void ``` Settings the memcached instance #### Returns `void` #### Throws `InvalidArgumentException` When the Memcached extension is not built with the desired serializer engine. ### 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 #### 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 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() 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 ``` Delete many keys from the cache at once 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 An array of identifiers for the data #### Returns `bool` ### 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): array ``` Read many keys from the cache at once #### Parameters `iterable` $keys An array of identifiers for the data `mixed` $default optional Default value to return for keys that do not exist. #### Returns `array` ### getOption() public ``` getOption(int $name): string|int|bool|null ``` Read an option value from the memcached connection. #### Parameters `int` $name The option name to read. #### Returns `string|int|bool|null` #### See Also https://secure.php.net/manual/en/memcached.getoption.php ### 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 #### Parameters `array<string, mixed>` $config optional array of setting for the engine #### Returns `bool` #### Throws `InvalidArgumentException` When you try use authentication without Memcached compiled with SASL support ### parseServerString() public ``` parseServerString(string $server): array ``` Parses the server address into the host/port. Handles both IPv6 and IPv4 addresses and Unix sockets #### Parameters `string` $server The server address string. #### Returns `array` ### set() public ``` set(string $key, mixed $value, null|intDateInterval $ttl = null): bool ``` Write data for key into cache. When using memcached as your cache engine remember that the Memcached pecl extension does not support cache expiry times greater than 30 days in the future. Any duration greater than 30 days will be treated as real Unix time value rather than an offset from current time. #### 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` #### See Also https://www.php.net/manual/en/memcached.set.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 ``` Write many cache entries to the cache at once #### Parameters `iterable` $values An array of data to be stored in the cache `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` ### 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 --------------- ### $\_Memcached protected memcached wrapper. #### Type `Memcached` ### $\_compiledGroupNames protected #### 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 config used unless overridden by runtime configuration * `compress` Whether to compress data * `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. * `username` Login to access the Memcache server * `password` Password to access the Memcache server * `persistent` The name of the persistent connection. All configurations using the same persistent value will share a single underlying connection. * `prefix` Prepended to all entries. Good for when you need to share a keyspace with either another cache config or another application. * `serialize` The serializer engine used to serialize data. Available engines are 'php', 'igbinary' and 'json'. Beside 'php', the memcached extension must be compiled with the appropriate serializer support. * `servers` String or array of memcached servers. If an array MemcacheEngine will use them as a pool. * `options` - Additional options for the memcached client. Should be an array of option => value. Use the \Memcached::OPT\_\* constants as keys. #### 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` ### $\_serializers protected List of available serializer engines Memcached must be compiled with JSON and igbinary support to use these engines #### Type `array<string, int>`
programming_docs
cakephp Namespace TestSuite Namespace TestSuite =================== ### Traits * ##### [ContainerStubTrait](trait-cake.core.testsuite.containerstubtrait) A set of methods used for defining container services in test cases. cakephp Class PDOStatement Class PDOStatement =================== Decorator for \PDOStatement class mainly used for converting human readable fetch modes into PDO constants. **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. You can pass PDO compatible constants for binding values with a type or optionally any type name registered in the Type class. Any value will be converted to the valid type representation if needed. It is not allowed to combine positional and named variables in the same statement ### Examples: ``` $statement->bindValue(1, 'a title'); $statement->bindValue(2, 5, PDO::INT); $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 ``` 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 Namespace Driver Namespace Driver ================ ### Classes * ##### [Mysql](class-cake.database.driver.mysql) MySQL Driver * ##### [Postgres](class-cake.database.driver.postgres) Class Postgres * ##### [Sqlite](class-cake.database.driver.sqlite) Class Sqlite * ##### [Sqlserver](class-cake.database.driver.sqlserver) SQLServer driver. ### Traits * ##### [SqlDialectTrait](trait-cake.database.driver.sqldialecttrait) Sql dialect trait * ##### [TupleComparisonTranslatorTrait](trait-cake.database.driver.tuplecomparisontranslatortrait) Provides a translator method for tuple comparisons cakephp Class InvalidParameterException Class InvalidParameterException ================================ Used when a passed parameter or action parameter type declaration is missing or invalid. **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()} * [$templates](#%24templates) protected `array<string, string>` Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Switches message template based on `template` key in message array. * ##### [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) ``` Switches message template based on `template` key in message array. 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` ### $templates protected #### Type `array<string, string>` cakephp Class RedirectException Class RedirectException ======================== An exception subclass used by routing and application code to trigger a redirect. The URL and status code are provided as constructor arguments. ``` throw new RedirectException('http://example.com/some/path', 301); ``` Additional headers can also be provided in the constructor, or using the addHeaders() method. **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 * ##### [addHeaders()](#addHeaders()) public deprecated Add headers to be included in the response generated from this exception * ##### [getAttributes()](#getAttributes()) public Get the passed in attributes * ##### [getCode()](#getCode()) public @method Gets the Exception code. * ##### [getHeaders()](#getHeaders()) public Returns array of response headers. * ##### [removeHeader()](#removeHeader()) public deprecated Remove a header from the exception. * ##### [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 $target, int $code = 302, array $headers = []) ``` Constructor Allows you to create exceptions that are treated as framework errors and disabled when debug mode is off. #### Parameters `string` $target The URL to redirect to. `int` $code optional The exception code that will be used as a HTTP status code `array` $headers optional The headers that should be sent in the unauthorized challenge response. ### addHeaders() public ``` addHeaders(array $headers): $this ``` Add headers to be included in the response generated from this exception #### Parameters `array` $headers An array of `header => value` to append to the exception. If a header already exists, the new values will be appended to the existing ones. #### Returns `$this` ### 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>` ### removeHeader() public ``` removeHeader(string $key): $this ``` Remove a header from the exception. #### Parameters `string` $key The header to remove. #### Returns `$this` ### 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 Class MailSentWith Class MailSentWith =================== MailSentWith **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 HttpException Class 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. You may also use this as a meaningful bridge to {@link \Cake\Core\Exception\CakeException}, e.g.: throw new \Cake\Network\Exception\HttpException('HTTP Version Not Supported', 505); **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 DatabaseException Class DatabaseException ======================== Exception for the database package. **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 Class PaginatorHelper Class PaginatorHelper ====================== Pagination Helper class for easy generation of pagination links. PaginationHelper encloses all methods needed when working with pagination. **Namespace:** [Cake\View\Helper](namespace-cake.view.helper) **Link:** https://book.cakephp.org/4/en/views/helpers/paginator.html Property Summary ---------------- * [$Form](#%24Form) public @property `Cake\View\Helper\FormHelper` * [$Html](#%24Html) public @property `Cake\View\Helper\HtmlHelper` * [$Number](#%24Number) public @property `Cake\View\Helper\NumberHelper` * [$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 * [$\_defaultModel](#%24_defaultModel) protected `string|null` Default model of the paged sets * [$\_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 Constructor. Overridden to merge passed args with URL options. * ##### [\_\_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. * ##### [\_firstNumber()](#_firstNumber()) protected Generates the first number for the paginator numbers() method. * ##### [\_formatNumber()](#_formatNumber()) protected Formats a number for the paginator number output. * ##### [\_getNumbersStartAndEnd()](#_getNumbersStartAndEnd()) protected Calculates the start and end for the pagination numbers. * ##### [\_hasPage()](#_hasPage()) protected Does $model have $page in its range? * ##### [\_lastNumber()](#_lastNumber()) protected Generates the last number for the paginator numbers() method. * ##### [\_modulusNumbers()](#_modulusNumbers()) protected Generates the numbers for the paginator numbers() method. * ##### [\_numbers()](#_numbers()) protected Generates the numbers for the paginator numbers() method. * ##### [\_removeAlias()](#_removeAlias()) protected Remove alias if needed. * ##### [\_toggledLink()](#_toggledLink()) protected Generate an active/inactive link for next/prev methods. * ##### [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. * ##### [counter()](#counter()) public Returns a counter string for the paged result set. * ##### [current()](#current()) public Gets the current page of the recordset for the given model * ##### [defaultModel()](#defaultModel()) public Gets or sets the default model of the paged sets * ##### [first()](#first()) public Returns a first or set of numbers for the first pages. * ##### [formatTemplate()](#formatTemplate()) public Formats a template string with $data * ##### [generateUrl()](#generateUrl()) public Merges passed URL options with current pagination state to generate a pagination URL. * ##### [generateUrlParams()](#generateUrlParams()) public Merges passed URL options with current pagination state to generate a pagination URL. * ##### [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. * ##### [hasNext()](#hasNext()) public Returns true if the given result set is not at the last page * ##### [hasPage()](#hasPage()) public Returns true if the given result set has the page number given by $page * ##### [hasPrev()](#hasPrev()) public Returns true if the given result set is not at the first page * ##### [implementedEvents()](#implementedEvents()) public Event listeners. * ##### [initialize()](#initialize()) public Constructor hook method. * ##### [last()](#last()) public Returns a last or set of numbers for the last pages. * ##### [limitControl()](#limitControl()) public Dropdown select for pagination limit. This will generate a wrapping form. * ##### [meta()](#meta()) public Returns the meta-links for a paginated result set. * ##### [next()](#next()) public Generates a "next" link for a set of paged records * ##### [numbers()](#numbers()) public Returns a set of numbers for the paged result set uses a modulus to decide how many numbers to show on each side of the current page (default: 8). * ##### [options()](#options()) public Sets default options for all pagination links * ##### [param()](#param()) public Convenience access to any of the paginator params. * ##### [params()](#params()) public Gets the current paging parameters from the resultset for the given model * ##### [prev()](#prev()) public Generates a "previous" link for a set of paged records * ##### [setConfig()](#setConfig()) public Sets the config. * ##### [setTemplates()](#setTemplates()) public Sets templates to use. * ##### [sort()](#sort()) public Generates a sorting link. Sets named parameters for the sort and direction. Handles direction switching automatically. * ##### [sortDir()](#sortDir()) public Gets the current direction the recordset is sorted * ##### [sortKey()](#sortKey()) public Gets the current key by which the recordset is sorted * ##### [templater()](#templater()) public Returns the templater instance. * ##### [total()](#total()) public Gets the total number of pages in the recordset for the given model. 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 = []) ``` Constructor. Overridden to merge passed args with URL options. #### 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` ### \_firstNumber() protected ``` _firstNumber(string $ellipsis, array<string, mixed> $params, int $start, array<string, mixed> $options): string ``` Generates the first number for the paginator numbers() method. #### Parameters `string` $ellipsis Ellipsis character. `array<string, mixed>` $params Params from the numbers() method. `int` $start Start number. `array<string, mixed>` $options Options from the numbers() method. #### Returns `string` ### \_formatNumber() protected ``` _formatNumber(Cake\View\StringTemplate $templater, array<string, mixed> $options): string ``` Formats a number for the paginator number output. #### Parameters `Cake\View\StringTemplate` $templater StringTemplate instance. `array<string, mixed>` $options Options from the numbers() method. #### Returns `string` ### \_getNumbersStartAndEnd() protected ``` _getNumbersStartAndEnd(array<string, mixed> $params, array<string, mixed> $options): array ``` Calculates the start and end for the pagination numbers. #### Parameters `array<string, mixed>` $params Params from the numbers() method. `array<string, mixed>` $options Options from the numbers() method. #### Returns `array` ### \_hasPage() protected ``` _hasPage(string|null $model, string $dir): bool ``` Does $model have $page in its range? #### Parameters `string|null` $model Model name to get parameters for. `string` $dir Direction #### Returns `bool` ### \_lastNumber() protected ``` _lastNumber(string $ellipsis, array<string, mixed> $params, int $end, array<string, mixed> $options): string ``` Generates the last number for the paginator numbers() method. #### Parameters `string` $ellipsis Ellipsis character. `array<string, mixed>` $params Params from the numbers() method. `int` $end End number. `array<string, mixed>` $options Options from the numbers() method. #### Returns `string` ### \_modulusNumbers() protected ``` _modulusNumbers(Cake\View\StringTemplate $templater, array<string, mixed> $params, array<string, mixed> $options): string ``` Generates the numbers for the paginator numbers() method. #### Parameters `Cake\View\StringTemplate` $templater StringTemplate instance. `array<string, mixed>` $params Params from the numbers() method. `array<string, mixed>` $options Options from the numbers() method. #### Returns `string` ### \_numbers() protected ``` _numbers(Cake\View\StringTemplate $templater, array<string, mixed> $params, array<string, mixed> $options): string ``` Generates the numbers for the paginator numbers() method. #### Parameters `Cake\View\StringTemplate` $templater StringTemplate instance. `array<string, mixed>` $params Params from the numbers() method. `array<string, mixed>` $options Options from the numbers() method. #### Returns `string` ### \_removeAlias() protected ``` _removeAlias(string $field, string|null $model = null): string ``` Remove alias if needed. #### Parameters `string` $field Current field `string|null` $model optional Current model alias #### Returns `string` ### \_toggledLink() protected ``` _toggledLink(string|false $text, bool $enabled, array<string, mixed> $options, array<string, mixed> $templates): string ``` Generate an active/inactive link for next/prev methods. #### Parameters `string|false` $text The enabled text for the link. `bool` $enabled Whether the enabled/disabled version should be created. `array<string, mixed>` $options An array of options from the calling method. `array<string, mixed>` $templates An array of templates with the 'active' and 'disabled' keys. #### 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` ### counter() public ``` counter(string $format = 'pages', array<string, mixed> $options = []): string ``` Returns a counter string for the paged result set. ### Options * `model` The model to use, defaults to PaginatorHelper::defaultModel(); #### Parameters `string` $format optional The format string you want to use, defaults to 'pages' Which generates output like '1 of 5' set to 'range' to generate output like '1 - 3 of 13'. Can also be set to a custom string, containing the following placeholders `{{page}}`, `{{pages}}`, `{{current}}`, `{{count}}`, `{{model}}`, `{{start}}`, `{{end}}` and any custom content you would like. `array<string, mixed>` $options optional Options for the counter string. See #options for list of keys. If string it will be used as format. #### Returns `string` #### Links https://book.cakephp.org/4/en/views/helpers/paginator.html#creating-a-page-counter ### current() public ``` current(string|null $model = null): int ``` Gets the current page of the recordset for the given model #### Parameters `string|null` $model optional Optional model name. Uses the default if none is specified. #### Returns `int` #### Links https://book.cakephp.org/4/en/views/helpers/paginator.html#checking-the-pagination-state ### defaultModel() public ``` defaultModel(string|null $model = null): string|null ``` Gets or sets the default model of the paged sets #### Parameters `string|null` $model optional Model name to set #### Returns `string|null` ### first() public ``` first(string|int $first = '<< first', array<string, mixed> $options = []): string ``` Returns a first or set of numbers for the first pages. ``` echo $this->Paginator->first('< first'); ``` Creates a single link for the first page. Will output nothing if you are on the first page. ``` echo $this->Paginator->first(3); ``` Will create links for the first 3 pages, once you get to the third or greater page. Prior to that nothing will be output. ### Options: * `model` The model to use defaults to PaginatorHelper::defaultModel() * `escape` Whether to HTML escape the text. * `url` An array of additional URL options to use for link generation. #### Parameters `string|int` $first optional if string use as label for the link. If numeric, the number of page links you want at the beginning of the range. `array<string, mixed>` $options optional An array of options. #### Returns `string` #### Links https://book.cakephp.org/4/en/views/helpers/paginator.html#creating-jump-links ### 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` ### generateUrl() public ``` generateUrl(array<string, mixed> $options = [], string|null $model = null, array $url = [], array<string, mixed> $urlOptions = []): string ``` Merges passed URL options with current pagination state to generate a pagination URL. ### Url options: * `escape`: If false, the URL will be returned unescaped, do only use if it is manually escaped afterwards before being displayed. * `fullBase`: If true, the full base URL will be prepended to the result #### Parameters `array<string, mixed>` $options optional Pagination options. `string|null` $model optional Which model to paginate on `array` $url optional URL. `array<string, mixed>` $urlOptions optional Array of options #### Returns `string` #### Links https://book.cakephp.org/4/en/views/helpers/paginator.html#generating-pagination-urls ### generateUrlParams() public ``` generateUrlParams(array<string, mixed> $options = [], string|null $model = null, array $url = []): array ``` Merges passed URL options with current pagination state to generate a pagination URL. #### Parameters `array<string, mixed>` $options optional Pagination/URL options array `string|null` $model optional Which model to paginate on `array` $url optional URL. #### Returns `array` ### 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` ### hasNext() public ``` hasNext(string|null $model = null): bool ``` Returns true if the given result set is not at the last page #### Parameters `string|null` $model optional Optional model name. Uses the default if none is specified. #### Returns `bool` #### Links https://book.cakephp.org/4/en/views/helpers/paginator.html#checking-the-pagination-state ### hasPage() public ``` hasPage(int $page = 1, string|null $model = null): bool ``` Returns true if the given result set has the page number given by $page #### Parameters `int` $page optional The page number - if not set defaults to 1. `string|null` $model optional Optional model name. Uses the default if none is specified. #### Returns `bool` #### Throws `InvalidArgumentException` #### Links https://book.cakephp.org/4/en/views/helpers/paginator.html#checking-the-pagination-state ### hasPrev() public ``` hasPrev(string|null $model = null): bool ``` Returns true if the given result set is not at the first page #### Parameters `string|null` $model optional Optional model name. Uses the default if none is specified. #### Returns `bool` #### Links https://book.cakephp.org/4/en/views/helpers/paginator.html#checking-the-pagination-state ### 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` ### last() public ``` last(string|int $last = 'last >>', array<string, mixed> $options = []): string ``` Returns a last or set of numbers for the last pages. ``` echo $this->Paginator->last('last >'); ``` Creates a single link for the last page. Will output nothing if you are on the last page. ``` echo $this->Paginator->last(3); ``` Will create links for the last 3 pages. Once you enter the page range, no output will be created. ### Options: * `model` The model to use defaults to PaginatorHelper::defaultModel() * `escape` Whether to HTML escape the text. * `url` An array of additional URL options to use for link generation. #### Parameters `string|int` $last optional if string use as label for the link, if numeric print page numbers `array<string, mixed>` $options optional Array of options #### Returns `string` #### Links https://book.cakephp.org/4/en/views/helpers/paginator.html#creating-jump-links ### limitControl() public ``` limitControl(array<string, string> $limits = [], int|null $default = null, array<string, mixed> $options = []): string ``` Dropdown select for pagination limit. This will generate a wrapping form. #### Parameters `array<string, string>` $limits optional The options array. `int|null` $default optional Default option for pagination limit. Defaults to `$this->param('perPage')`. `array<string, mixed>` $options optional Options for Select tag attributes like class, id or event #### Returns `string` ### meta() public ``` meta(array<string, mixed> $options = []): string|null ``` Returns the meta-links for a paginated result set. ``` echo $this->Paginator->meta(); ``` Echos the links directly, will output nothing if there is neither a previous nor next page. ``` $this->Paginator->meta(['block' => true]); ``` Will append the output of the meta function to the named block - if true is passed the "meta" block is used. ### Options: * `model` The model to use defaults to PaginatorHelper::defaultModel() * `block` The block name to append the output to, or false/absent to return as a string * `prev` (default True) True to generate meta for previous page * `next` (default True) True to generate meta for next page * `first` (default False) True to generate meta for first page * `last` (default False) True to generate meta for last page #### Parameters `array<string, mixed>` $options optional Array of options #### Returns `string|null` ### next() public ``` next(string $title = 'Next >>', array<string, mixed> $options = []): string ``` Generates a "next" link for a set of paged records ### Options: * `disabledTitle` The text to used when the link is disabled. This defaults to the same text at the active link. Setting to false will cause this method to return ''. * `escape` Whether you want the contents html entity encoded, defaults to true * `model` The model to use, defaults to PaginatorHelper::defaultModel() * `url` An array of additional URL options to use for link generation. * `templates` An array of templates, or template file name containing the templates you'd like to use when generating the link for next page. The helper's original templates will be restored once next() is done. #### Parameters `string` $title optional Title for the link. Defaults to 'Next >>'. `array<string, mixed>` $options optional Options for pagination link. See above for list of keys. #### Returns `string` #### Links https://book.cakephp.org/4/en/views/helpers/paginator.html#creating-jump-links ### numbers() public ``` numbers(array<string, mixed> $options = []): string ``` Returns a set of numbers for the paged result set uses a modulus to decide how many numbers to show on each side of the current page (default: 8). ``` $this->Paginator->numbers(['first' => 2, 'last' => 2]); ``` Using the first and last options you can create links to the beginning and end of the page set. ### Options * `before` Content to be inserted before the numbers, but after the first links. * `after` Content to be inserted after the numbers, but before the last links. * `model` Model to create numbers for, defaults to PaginatorHelper::defaultModel() * `modulus` How many numbers to include on either side of the current page, defaults to 8. Set to `false` to disable and to show all numbers. * `first` Whether you want first links generated, set to an integer to define the number of 'first' links to generate. If a string is set a link to the first page will be generated with the value as the title. * `last` Whether you want last links generated, set to an integer to define the number of 'last' links to generate. If a string is set a link to the last page will be generated with the value as the title. * `templates` An array of templates, or template file name containing the templates you'd like to use when generating the numbers. The helper's original templates will be restored once numbers() is done. * `url` An array of additional URL options to use for link generation. The generated number links will include the 'ellipsis' template when the `first` and `last` options and the number of pages exceed the modulus. For example if you have 25 pages, and use the first/last options and a modulus of 8, ellipsis content will be inserted after the first and last link sets. #### Parameters `array<string, mixed>` $options optional Options for the numbers. #### Returns `string` #### Links https://book.cakephp.org/4/en/views/helpers/paginator.html#creating-page-number-links ### options() public ``` options(array<string, mixed> $options = []): void ``` Sets default options for all pagination links #### Parameters `array<string, mixed>` $options optional Default options for pagination links. See PaginatorHelper::$options for list of keys. #### Returns `void` ### param() public ``` param(string $key, string|null $model = null): mixed ``` Convenience access to any of the paginator params. #### Parameters `string` $key Key of the paginator params array to retrieve. `string|null` $model optional Optional model name. Uses the default if none is specified. #### Returns `mixed` ### params() public ``` params(string|null $model = null): array ``` Gets the current paging parameters from the resultset for the given model #### Parameters `string|null` $model optional Optional model name. Uses the default if none is specified. #### Returns `array` ### prev() public ``` prev(string $title = '<< Previous', array<string, mixed> $options = []): string ``` Generates a "previous" link for a set of paged records ### Options: * `disabledTitle` The text to used when the link is disabled. This defaults to the same text at the active link. Setting to false will cause this method to return ''. * `escape` Whether you want the contents html entity encoded, defaults to true * `model` The model to use, defaults to PaginatorHelper::defaultModel() * `url` An array of additional URL options to use for link generation. * `templates` An array of templates, or template file name containing the templates you'd like to use when generating the link for previous page. The helper's original templates will be restored once prev() is done. #### Parameters `string` $title optional Title for the link. Defaults to '<< Previous'. `array<string, mixed>` $options optional Options for pagination link. See above for list of keys. #### Returns `string` #### Links https://book.cakephp.org/4/en/views/helpers/paginator.html#creating-jump-links ### 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` ### sort() public ``` sort(string $key, array<string, mixed>|string|null $title = null, array<string, mixed> $options = []): string ``` Generates a sorting link. Sets named parameters for the sort and direction. Handles direction switching automatically. ### Options: * `escape` Whether you want the contents html entity encoded, defaults to true. * `model` The model to use, defaults to PaginatorHelper::defaultModel(). * `direction` The default direction to use when this link isn't active. * `lock` Lock direction. Will only use the default direction then, defaults to false. #### Parameters `string` $key The name of the key that the recordset should be sorted. `array<string, mixed>|string|null` $title optional Title for the link. If $title is null $key will be used for the title and will be generated by inflection. It can also be an array with keys `asc` and `desc` for specifying separate titles based on the direction. `array<string, mixed>` $options optional Options for sorting link. See above for list of keys. #### Returns `string` #### Links https://book.cakephp.org/4/en/views/helpers/paginator.html#creating-sort-links ### sortDir() public ``` sortDir(string|null $model = null, array<string, mixed> $options = []): string ``` Gets the current direction the recordset is sorted #### Parameters `string|null` $model optional Optional model name. Uses the default if none is specified. `array<string, mixed>` $options optional Options for pagination links. #### Returns `string` #### Links https://book.cakephp.org/4/en/views/helpers/paginator.html#creating-sort-links ### sortKey() public ``` sortKey(string|null $model = null, array<string, mixed> $options = []): string|null ``` Gets the current key by which the recordset is sorted #### Parameters `string|null` $model optional Optional model name. Uses the default if none is specified. `array<string, mixed>` $options optional Options for pagination links. #### Returns `string|null` #### Links https://book.cakephp.org/4/en/views/helpers/paginator.html#creating-sort-links ### templater() public ``` templater(): Cake\View\StringTemplate ``` Returns the templater instance. #### Returns `Cake\View\StringTemplate` ### total() public ``` total(string|null $model = null): int ``` Gets the total number of pages in the recordset for the given model. #### Parameters `string|null` $model optional Optional model name. Uses the default if none is specified. #### Returns `int` Property Detail --------------- ### $Form public @property #### Type `Cake\View\Helper\FormHelper` ### $Html public @property #### Type `Cake\View\Helper\HtmlHelper` ### $Number public @property #### Type `Cake\View\Helper\NumberHelper` ### $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 Options: Holds the default options for pagination links The values that may be specified are: * `url` Url of the action. See Router::url() * `url['?']['sort']` the key that the recordset is sorted. * `url['?']['direction']` Direction of the sorting (default: 'asc'). * `url['?']['page']` Page number to use in links. * `model` The name of the model. * `escape` Defines if the title field for the link should be escaped (default: true). * `routePlaceholders` An array specifying which paging params should be passed as route placeholders instead of query string parameters. The array can have values `'sort'`, `'direction'`, `'page'`. Templates: the templates used by this class #### Type `array<string, mixed>` ### $\_defaultModel protected Default model of the paged sets #### Type `string|null` ### $\_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 Trait StaticConfigTrait Trait StaticConfigTrait ======================== A trait that provides a set of static methods to manage configuration for classes that provide an adapter facade or need to have sets of configuration data registered and manipulated. Implementing objects are expected to declare a static `$_dsnClassMap` property. **Namespace:** [Cake\Core](namespace-cake.core) Property Summary ---------------- * [$\_config](#%24_config) protected static `array<string, mixed>` Configuration sets. Method Summary -------------- * ##### [configured()](#configured()) public static Returns an array containing the named configurations * ##### [drop()](#drop()) public static Drops a constructed adapter. * ##### [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. * ##### [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. Method Detail ------------- ### 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` ### 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>` ### 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` Property Detail --------------- ### $\_config protected static Configuration sets. #### Type `array<string, mixed>` cakephp Class CallbackStatement Class CallbackStatement ======================== Wraps a statement in a callback that allows row results to be modified when being fetched. This is used by CakePHP to eagerly load association data. **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 ---------------- * [$\_callback](#%24_callback) protected `callable` A callback function to be applied to results. * [$\_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 Fetch a row from the statement. * ##### [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, callable $callback) ``` Constructor #### Parameters `Cake\Database\StatementInterface` $statement The statement to decorate. `Cake\Database\DriverInterface` $driver The driver instance used by the statement. `callable` $callback The callback to apply to results before they are returned. ### \_\_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 = parent::FETCH_TYPE_NUM): array|false ``` Fetch a row from the statement. The result will be processed by the callback when it is not `false`. #### Parameters `string|int` $type optional Either 'num' or 'assoc' to indicate the result format you would like. #### Returns `array|false` ### fetchAll() public ``` fetchAll(string|int $type = parent::FETCH_TYPE_NUM): array|false ``` Returns an array with all rows resulting from executing this statement. Each row in the result will be processed by the callback when it is not `false. #### 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` ### 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 --------------- ### $\_callback protected A callback function to be applied to results. #### Type `callable` ### $\_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 Class ConditionDecorator Class ConditionDecorator ========================= Event Condition Decorator Use this decorator to allow your event listener to only be invoked if the `if` and/or `unless` conditions pass. **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. * ##### [\_evaluateCondition()](#_evaluateCondition()) protected Evaluates the filter conditions * ##### [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` ### \_evaluateCondition() protected ``` _evaluateCondition(string $condition, Cake\Event\EventInterface $event): bool ``` Evaluates the filter conditions #### Parameters `string` $condition Condition type `Cake\Event\EventInterface` $event Event object #### Returns `bool` ### 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 UnavailableForLegalReasonsException Class UnavailableForLegalReasonsException ========================================== Represents an HTTP 451 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 'Unavailable For Legal Reasons' will be the message `int|null` $code optional Status code, defaults to 451 `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 Class MissingTemplateException Class MissingTemplateException =============================== Used when a template 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 RolledbackTransactionException Class RolledbackTransactionException ===================================== Used when a transaction was rolled back from a callback event. **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 QueryCacher Class QueryCacher ================== Handles caching queries and loading results from the cache. Used by {@link \Cake\Datasource\QueryTrait} internally. **Namespace:** [Cake\Datasource](namespace-cake.datasource) **See:** \Cake\Datasource\QueryTrait::cache() for the public interface. Property Summary ---------------- * [$\_config](#%24_config) protected `Psr\SimpleCache\CacheInterface|string` Config for cache engine. * [$\_key](#%24_key) protected `Closure|string` The key or function to generate a key. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [\_resolveCacher()](#_resolveCacher()) protected Get the cache engine. * ##### [\_resolveKey()](#_resolveKey()) protected Get/generate the cache key. * ##### [fetch()](#fetch()) public Load the cached results from the cache or run the query. * ##### [store()](#store()) public Store the result set into the cache. Method Detail ------------- ### \_\_construct() public ``` __construct(Closure|string $key, Psr\SimpleCache\CacheInterface|string $config) ``` Constructor. #### Parameters `Closure|string` $key The key or function to generate a key. `Psr\SimpleCache\CacheInterface|string` $config The cache config name or cache engine instance. #### Throws `RuntimeException` ### \_resolveCacher() protected ``` _resolveCacher(): Psr\SimpleCache\CacheInterface ``` Get the cache engine. #### Returns `Psr\SimpleCache\CacheInterface` ### \_resolveKey() protected ``` _resolveKey(object $query): string ``` Get/generate the cache key. #### Parameters `object` $query The query to generate a key for. #### Returns `string` #### Throws `RuntimeException` ### fetch() public ``` fetch(object $query): mixed|null ``` Load the cached results from the cache or run the query. #### Parameters `object` $query The query the cache read is for. #### Returns `mixed|null` ### store() public ``` store(object $query, Traversable $results): bool ``` Store the result set into the cache. #### Parameters `object` $query The query the cache read is for. `Traversable` $results The result set to store. #### Returns `bool` Property Detail --------------- ### $\_config protected Config for cache engine. #### Type `Psr\SimpleCache\CacheInterface|string` ### $\_key protected The key or function to generate a key. #### Type `Closure|string` cakephp Class PluginCollection Class PluginCollection ======================= Plugin Collection Holds onto plugin objects loaded into an application, and provides methods for iterating, and finding plugins based on criteria. This class implements the Iterator interface to allow plugins to be iterated, handling the situation where a plugin's hook method (usually bootstrap) loads another plugin during iteration. While its implementation supported nested iteration it does not support using `continue` or `break` inside loops. **Namespace:** [Cake\Core](namespace-cake.core) Property Summary ---------------- * [$loopDepth](#%24loopDepth) protected `int` Loop depth * [$names](#%24names) protected `array<string>` Names of plugins * [$plugins](#%24plugins) protected `arrayCake\Core\PluginInterface>` Plugin list * [$positions](#%24positions) protected `array<int>` Iterator position stack. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [add()](#add()) public Add a plugin to the collection * ##### [clear()](#clear()) public Remove all plugins from the collection * ##### [count()](#count()) public Implementation of Countable. * ##### [create()](#create()) public Create a plugin instance from a name/classname and configuration. * ##### [current()](#current()) public Part of Iterator Interface * ##### [findPath()](#findPath()) public Locate a plugin path by looking at configuration data. * ##### [get()](#get()) public Get the a plugin by name. * ##### [has()](#has()) public Check whether the named plugin exists in the collection. * ##### [key()](#key()) public Part of Iterator Interface * ##### [loadConfig()](#loadConfig()) protected Load the path information stored in vendor/cakephp-plugins.php * ##### [next()](#next()) public Part of Iterator Interface * ##### [remove()](#remove()) public Remove a plugin from the collection if it exists. * ##### [rewind()](#rewind()) public Part of Iterator Interface * ##### [valid()](#valid()) public Part of Iterator Interface * ##### [with()](#with()) public Filter the plugins to those with the named hook enabled. Method Detail ------------- ### \_\_construct() public ``` __construct(arrayCake\Core\PluginInterface> $plugins = []) ``` Constructor #### Parameters `arrayCake\Core\PluginInterface>` $plugins optional The map of plugins to add to the collection. ### add() public ``` add(Cake\Core\PluginInterface $plugin): $this ``` Add a plugin to the collection Plugins will be keyed by their names. #### Parameters `Cake\Core\PluginInterface` $plugin The plugin to load. #### Returns `$this` ### clear() public ``` clear(): $this ``` Remove all plugins from the collection #### Returns `$this` ### count() public ``` count(): int ``` Implementation of Countable. Get the number of plugins in the collection. #### Returns `int` ### create() public ``` create(string $name, array<string, mixed> $config = []): Cake\Core\PluginInterface ``` Create a plugin instance from a name/classname and configuration. #### Parameters `string` $name The plugin name or classname `array<string, mixed>` $config optional Configuration options for the plugin. #### Returns `Cake\Core\PluginInterface` #### Throws `Cake\Core\Exception\MissingPluginException` When plugin instance could not be created. ### current() public ``` current(): Cake\Core\PluginInterface ``` Part of Iterator Interface #### Returns `Cake\Core\PluginInterface` ### findPath() public ``` findPath(string $name): string ``` Locate a plugin path by looking at configuration data. This will use the `plugins` Configure key, and fallback to enumerating `App::path('plugins')` This method is not part of the official public API as plugins with no plugin class are being phased out. #### Parameters `string` $name The plugin name to locate a path for. #### Returns `string` #### Throws `Cake\Core\Exception\MissingPluginException` when a plugin path cannot be resolved. ### get() public ``` get(string $name): Cake\Core\PluginInterface ``` Get the a plugin by name. If a plugin isn't already loaded it will be autoloaded on first access and that plugins loaded this way may miss some hook methods. #### Parameters `string` $name The plugin to get. #### Returns `Cake\Core\PluginInterface` #### Throws `Cake\Core\Exception\MissingPluginException` when unknown plugins are fetched. ### has() public ``` has(string $name): bool ``` Check whether the named plugin exists in the collection. #### Parameters `string` $name The named plugin. #### Returns `bool` ### key() public ``` key(): string ``` Part of Iterator Interface #### Returns `string` ### loadConfig() protected ``` loadConfig(): void ``` Load the path information stored in vendor/cakephp-plugins.php This file is generated by the cakephp/plugin-installer package and used to locate plugins on the filesystem as applications can use `extra.plugin-paths` in their composer.json file to move plugin outside of vendor/ #### Returns `void` ### next() public ``` next(): void ``` Part of Iterator Interface #### Returns `void` ### remove() public ``` remove(string $name): $this ``` Remove a plugin from the collection if it exists. #### Parameters `string` $name The named plugin. #### Returns `$this` ### rewind() public ``` rewind(): void ``` Part of Iterator Interface #### Returns `void` ### valid() public ``` valid(): bool ``` Part of Iterator Interface #### Returns `bool` ### with() public ``` with(string $hook): GeneratorCake\Core\PluginInterface> ``` Filter the plugins to those with the named hook enabled. #### Parameters `string` $hook The hook to filter plugins by #### Returns `GeneratorCake\Core\PluginInterface>` #### Throws `InvalidArgumentException` on invalid hooks Property Detail --------------- ### $loopDepth protected Loop depth #### Type `int` ### $names protected Names of plugins #### Type `array<string>` ### $plugins protected Plugin list #### Type `arrayCake\Core\PluginInterface>` ### $positions protected Iterator position stack. #### Type `array<int>` cakephp Interface ErrorLoggerInterface Interface ErrorLoggerInterface =============================== Interface for error logging handlers. Used by the ErrorHandlerMiddleware and global error handlers to log exceptions and errors. **Namespace:** [Cake\Error](namespace-cake.error) Method Summary -------------- * ##### [log()](#log()) public deprecated Log an error for an exception with optional request context. * ##### [logError()](#logError()) public @method * ##### [logException()](#logException()) public @method * ##### [logMessage()](#logMessage()) public deprecated Log a an error message to the error logger. Method Detail ------------- ### log() public ``` log(Throwable $exception, Psr\Http\Message\ServerRequestInterface|null $request = null): bool ``` Log an error for an exception with optional request context. #### Parameters `Throwable` $exception The exception to log a message for. `Psr\Http\Message\ServerRequestInterface|null` $request optional The current request if available. #### Returns `bool` ### logError() public @method ``` logError(Cake\Error\PhpError $error, Psr\Http\Message\ServerRequestInterface $request = null, bool $includeTrace = false): void ``` #### Parameters `Cake\Error\PhpError` $error `Psr\Http\Message\ServerRequestInterface` $request optional `bool` $includeTrace optional #### Returns `void` ### logException() public @method ``` logException(Throwable $exception, Psr\Http\Message\ServerRequestInterface $request = null, bool $includeTrace = false): void ``` #### Parameters `Throwable` $exception `Psr\Http\Message\ServerRequestInterface` $request optional `bool` $includeTrace optional #### Returns `void` ### logMessage() public ``` logMessage(string|int $level, string $message, array $context = []): bool ``` Log a an error message to the error logger. #### Parameters `string|int` $level The logging level `string` $message The message to be logged. `array` $context optional Context. #### Returns `bool` cakephp Class MissingActionException Class MissingActionException ============================= Missing Action exception - used when a mailer action 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`
programming_docs
cakephp Class TextFormatter Class TextFormatter ==================== A Debugger formatter for generating unstyled plain text output. Provides backwards compatible output with the historical output of `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. * ##### [export()](#export()) protected Convert a tree of NodeInterface objects into a plain text string. * ##### [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. 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` ### export() protected ``` export(Cake\Error\Debug\NodeInterface $var, int $indent): string ``` Convert a tree of NodeInterface objects into a plain text string. #### 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 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` cakephp Class Translator Class Translator ================= Translator to translate the message. **Namespace:** [Cake\I18n](namespace-cake.i18n) Constants --------- * `string` **PLURAL\_PREFIX** ``` 'p:' ``` Property Summary ---------------- * [$fallback](#%24fallback) protected `Cake\I18n\Translator|null` A fallback translator. * [$formatter](#%24formatter) protected `Cake\I18n\FormatterInterface` The formatter to use when translating messages. * [$locale](#%24locale) protected `string` The locale being used for translations. * [$package](#%24package) protected `Cake\I18n\Package` The Package containing keys and translations. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [getMessage()](#getMessage()) protected Gets the message translation by its key. * ##### [getPackage()](#getPackage()) public Returns the translator package * ##### [resolveContext()](#resolveContext()) protected Resolve a message's context structure. * ##### [translate()](#translate()) public Translates the message formatting any placeholders Method Detail ------------- ### \_\_construct() public ``` __construct(string $locale, Cake\I18n\Package $package, Cake\I18n\FormatterInterface $formatter, Cake\I18n\Translator|null $fallback = null) ``` Constructor #### Parameters `string` $locale The locale being used. `Cake\I18n\Package` $package The Package containing keys and translations. `Cake\I18n\FormatterInterface` $formatter A message formatter. `Cake\I18n\Translator|null` $fallback optional A fallback translator. ### getMessage() protected ``` getMessage(string $key): mixed ``` Gets the message translation by its key. #### Parameters `string` $key The message key. #### Returns `mixed` ### getPackage() public ``` getPackage(): Cake\I18n\Package ``` Returns the translator package #### Returns `Cake\I18n\Package` ### resolveContext() protected ``` resolveContext(string $key, array $message, array $vars): array|string ``` Resolve a message's context structure. #### Parameters `string` $key The message key being handled. `array` $message The message content. `array` $vars The variables containing the `_context` key. #### Returns `array|string` ### translate() public ``` translate(string $key, array $tokensValues = []): string ``` Translates the message formatting any placeholders #### Parameters `string` $key The message key. `array` $tokensValues optional Token values to interpolate into the message. #### Returns `string` Property Detail --------------- ### $fallback protected A fallback translator. #### Type `Cake\I18n\Translator|null` ### $formatter protected The formatter to use when translating messages. #### Type `Cake\I18n\FormatterInterface` ### $locale protected The locale being used for translations. #### Type `string` ### $package protected The Package containing keys and translations. #### Type `Cake\I18n\Package` cakephp Class StubConsoleOutput Class StubConsoleOutput ======================== StubOutput makes testing shell commands/shell helpers easier. You can use this class by injecting it into a ConsoleIo instance that your command/task/helper uses: ``` use Cake\Console\ConsoleIo; use Cake\Console\TestSuite\StubConsoleOutput; $output = new StubConsoleOutput(); $io = new ConsoleIo($output); ``` **Namespace:** [Cake\Console\TestSuite](namespace-cake.console.testsuite) Constants --------- * `int` **COLOR** ``` 2 ``` Color output - Convert known tags in to ANSI color escape codes. * `string` **LF** ``` PHP_EOL ``` Constant for a newline. * `int` **PLAIN** ``` 1 ``` Plain output - tags will be stripped. * `int` **RAW** ``` 0 ``` Raw output constant - no modification of output text. Property Summary ---------------- * [$\_backgroundColors](#%24_backgroundColors) protected static `array<string, int>` background colors used in colored output. * [$\_foregroundColors](#%24_foregroundColors) protected static `array<string, int>` text colors used in colored output. * [$\_options](#%24_options) protected static `array<string, int>` Formatting options for colored output. * [$\_out](#%24_out) protected `array<string>` Buffered messages. * [$\_output](#%24_output) protected `resource` File handle for output. * [$\_outputAs](#%24_outputAs) protected `int` The current output type. * [$\_styles](#%24_styles) protected static `array<string, array>` Styles that are available as tags in console output. You can modify these styles with ConsoleOutput::styles() Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Construct the output object. * ##### [\_\_destruct()](#__destruct()) public Clean up and close handles * ##### [\_replaceTags()](#_replaceTags()) protected Replace tags with color codes. * ##### [\_write()](#_write()) protected Writes a message to the output stream. * ##### [getOutputAs()](#getOutputAs()) public Get the output type on how formatting tags are treated. * ##### [getStyle()](#getStyle()) public Gets the current styles offered * ##### [messages()](#messages()) public Get the buffered output. * ##### [output()](#output()) public Get the output as a string * ##### [setOutputAs()](#setOutputAs()) public Set the output type on how formatting tags are treated. * ##### [setStyle()](#setStyle()) public Sets style. * ##### [styleText()](#styleText()) public Apply styling to text. * ##### [styles()](#styles()) public Gets all the style definitions. * ##### [write()](#write()) public Write output to the buffer. Method Detail ------------- ### \_\_construct() public ``` __construct(string $stream = 'php://stdout') ``` Construct the output object. Checks for a pretty console environment. Ansicon and ConEmu allows pretty consoles on Windows, and is supported. #### Parameters `string` $stream optional The identifier of the stream to write output to. ### \_\_destruct() public ``` __destruct() ``` Clean up and close handles ### \_replaceTags() protected ``` _replaceTags(array<string, string> $matches): string ``` Replace tags with color codes. #### Parameters `array<string, string>` $matches An array of matches to replace. #### Returns `string` ### \_write() protected ``` _write(string $message): int ``` Writes a message to the output stream. #### Parameters `string` $message Message to write. #### Returns `int` ### getOutputAs() public ``` getOutputAs(): int ``` Get the output type on how formatting tags are treated. #### Returns `int` ### getStyle() public ``` getStyle(string $style): array ``` Gets the current styles offered #### Parameters `string` $style The style to get. #### Returns `array` ### messages() public ``` messages(): array<string> ``` Get the buffered output. #### Returns `array<string>` ### output() public ``` output(): string ``` Get the output as a string #### Returns `string` ### setOutputAs() public ``` setOutputAs(int $type): void ``` Set the output type on how formatting tags are treated. #### Parameters `int` $type The output type to use. Should be one of the class constants. #### Returns `void` #### Throws `InvalidArgumentException` in case of a not supported output type. ### setStyle() public ``` setStyle(string $style, array $definition): void ``` Sets style. ### Creates or modifies an existing style. ``` $output->setStyle('annoy', ['text' => 'purple', 'background' => 'yellow', 'blink' => true]); ``` ### Remove a style ``` $this->output->setStyle('annoy', []); ``` #### Parameters `string` $style The style to set. `array` $definition The array definition of the style to change or create.. #### Returns `void` ### styleText() public ``` styleText(string $text): string ``` Apply styling to text. #### Parameters `string` $text Text with styling tags. #### Returns `string` ### styles() public ``` styles(): array<string, mixed> ``` Gets all the style definitions. #### Returns `array<string, mixed>` ### write() public ``` write(array<string>|string $message, int $newlines = 1): int ``` Write output to the buffer. #### Parameters `array<string>|string` $message A string or an array of strings to output `int` $newlines optional Number of newlines to append #### Returns `int` Property Detail --------------- ### $\_backgroundColors protected static background colors used in colored output. #### Type `array<string, int>` ### $\_foregroundColors protected static text colors used in colored output. #### Type `array<string, int>` ### $\_options protected static Formatting options for colored output. #### Type `array<string, int>` ### $\_out protected Buffered messages. #### Type `array<string>` ### $\_output protected File handle for output. #### Type `resource` ### $\_outputAs protected The current output type. #### Type `int` ### $\_styles protected static Styles that are available as tags in console output. You can modify these styles with ConsoleOutput::styles() #### Type `array<string, array>` cakephp Interface TypeInterface Interface TypeInterface ======================== Encapsulates all conversion functions for values coming from a database into PHP and going from PHP into a database. **Namespace:** [Cake\Database](namespace-cake.database) Method Summary -------------- * ##### [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 Casts given value from a PHP type to one acceptable by a database. * ##### [toPHP()](#toPHP()) public Casts given value from a database type to a PHP equivalent. * ##### [toStatement()](#toStatement()) public Casts given value to its Statement equivalent. Method Detail ------------- ### 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` #### See Also \Cake\Database\Type\UuidType ### toDatabase() public ``` toDatabase(mixed $value, Cake\Database\DriverInterface $driver): mixed ``` Casts given value from a PHP type to one acceptable by a database. #### Parameters `mixed` $value Value to be converted to a database equivalent. `Cake\Database\DriverInterface` $driver Object from which database preferences and configuration will be extracted. #### Returns `mixed` ### toPHP() public ``` toPHP(mixed $value, Cake\Database\DriverInterface $driver): mixed ``` 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 `mixed` ### toStatement() public ``` toStatement(mixed $value, Cake\Database\DriverInterface $driver): mixed ``` Casts given value to its 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` cakephp Class BodyRegExp Class BodyRegExp ================= BodyRegExp **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`
programming_docs
cakephp Trait ViewVarsTrait Trait ViewVarsTrait ==================== Provides the set() method for collecting template context. Once collected context data can be passed to another object. This is done in Controller, TemplateTask and View for example. **Namespace:** [Cake\View](namespace-cake.view) Property Summary ---------------- * [$\_viewBuilder](#%24_viewBuilder) protected `Cake\View\ViewBuilder|null` The view builder instance being used. Method Summary -------------- * ##### [createView()](#createView()) public Constructs the view class instance based on the current configuration. * ##### [set()](#set()) public Saves a variable or an associative array of variables for use inside a template. * ##### [viewBuilder()](#viewBuilder()) public Get the view builder being used. Method Detail ------------- ### createView() public ``` createView(string|null $viewClass = null): Cake\View\View ``` Constructs the view class instance based on the current configuration. #### Parameters `string|null` $viewClass optional Optional namespaced class name of the View class to instantiate. #### Returns `Cake\View\View` #### Throws `Cake\View\Exception\MissingViewException` If view class was not found. ### 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` ### viewBuilder() public ``` viewBuilder(): Cake\View\ViewBuilder ``` Get the view builder being used. #### Returns `Cake\View\ViewBuilder` Property Detail --------------- ### $\_viewBuilder protected The view builder instance being used. #### Type `Cake\View\ViewBuilder|null` cakephp Class MysqlSchemaDialect Class MysqlSchemaDialect ========================= Schema generation/reflection features for MySQL **Namespace:** [Cake\Database\Schema](namespace-cake.database.schema) Property Summary ---------------- * [$\_driver](#%24_driver) protected `Cake\Database\Driver\Mysql` 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 MySQL column type into an abstract type. * ##### [\_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. * ##### [\_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 MySQL column type into an abstract type. 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 type cannot be parsed. ### \_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` ### \_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 `array` $row #### 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 `array<string, mixed>` $config #### 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<mixed> ``` 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<mixed>` ### 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\Driver\Mysql` cakephp Class DateType Class DateType =============== Class DateType **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` In this class we want Date objects to have their time set to the beginning 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 FrozenDate 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 Date implementation. Method Detail ------------- ### \_\_construct() public ``` __construct(string|null $name = null) ``` Constructor #### Parameters `string|null` $name optional ### \_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 #### 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 FrozenDate 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 Date 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 In this class we want Date objects to have their time set to the beginning 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 MailConstraintBase Class MailConstraintBase ========================= Base class for all mail assertion constraints **Abstract** **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()) protected Evaluates the constraint for parameter $other. Returns true if the constraint is met, false otherwise. * ##### [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 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(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() protected ``` matches(mixed $other): bool ``` Evaluates the constraint for parameter $other. Returns true if the constraint is met, false otherwise. This method can be overridden to implement the evaluation algorithm. #### Parameters `mixed` $other value or object to evaluate #### 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 ``` 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 --------------- ### $at protected #### Type `int|null` cakephp Namespace View Namespace View ============== ### Classes * ##### [LayoutFileEquals](class-cake.testsuite.constraint.view.layoutfileequals) LayoutFileEquals * ##### [TemplateFileEquals](class-cake.testsuite.constraint.view.templatefileequals) TemplateFileEquals cakephp Trait StringTemplateTrait Trait StringTemplateTrait ========================== Adds string template functionality to any class by providing methods to load and parse string templates. This trait requires the implementing class to provide a `config()` method for reading/updating templates. An implementation of this method is provided by `Cake\Core\InstanceConfigTrait` **Namespace:** [Cake\View](namespace-cake.view) Property Summary ---------------- * [$\_templater](#%24_templater) protected `Cake\View\StringTemplate|null` StringTemplate instance. Method Summary -------------- * ##### [formatTemplate()](#formatTemplate()) public Formats a template string with $data * ##### [getTemplates()](#getTemplates()) public Gets templates to use or a specific template. * ##### [setTemplates()](#setTemplates()) public Sets templates to use. * ##### [templater()](#templater()) public Returns the templater instance. Method Detail ------------- ### 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` ### 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` ### 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` Property Detail --------------- ### $\_templater protected StringTemplate instance. #### Type `Cake\View\StringTemplate|null` cakephp Class DashedRoute Class 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']` **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 * ##### [\_camelizePlugin()](#_camelizePlugin()) protected Camelizes the previously dashed plugin route taking into account plugin vendors * ##### [\_dasherize()](#_dasherize()) protected Helper method for dasherizing keys in a URL array. * ##### [\_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 Dasherizes the controller, action 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 controller and plugin keys to their CamelCased form and action key to camelBacked 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` ### \_camelizePlugin() protected ``` _camelizePlugin(string $plugin): string ``` Camelizes the previously dashed plugin route taking into account plugin vendors #### Parameters `string` $plugin Plugin name #### Returns `string` ### \_dasherize() protected ``` _dasherize(array $url): array ``` Helper method for dasherizing keys in a URL array. #### Parameters `array` $url An array of URL keys. #### Returns `array` ### \_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 ``` Dasherizes the controller, action 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 controller and plugin keys to their CamelCased form and action key to camelBacked 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. #### 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`
programming_docs
cakephp Class Server Class Server ============= Runs an application invoking all the PSR7 middleware and the registered application. **Namespace:** [Cake\Http](namespace-cake.http) 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. * [$app](#%24app) protected `Cake\Core\HttpApplicationInterface` * [$runner](#%24runner) protected `Cake\Http\Runner` Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [bootstrap()](#bootstrap()) protected Application bootstrap wrapper. * ##### [dispatchEvent()](#dispatchEvent()) public Wrapper for creating and dispatching events. * ##### [emit()](#emit()) public Emit the response using the PHP SAPI. * ##### [getApp()](#getApp()) public Get the current application. * ##### [getEventManager()](#getEventManager()) public Get the application's event manager or the global one. * ##### [run()](#run()) public Run the request/response through the Application and its middleware. * ##### [setEventManager()](#setEventManager()) public Set the application's event manager. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\Core\HttpApplicationInterface $app, Cake\Http\Runner|null $runner = null) ``` Constructor #### Parameters `Cake\Core\HttpApplicationInterface` $app The application to use. `Cake\Http\Runner|null` $runner optional Application runner. ### bootstrap() protected ``` bootstrap(): void ``` Application bootstrap wrapper. Calls the application's `bootstrap()` hook. After the application the plugins are bootstrapped. #### Returns `void` ### 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` ### emit() public ``` emit(Psr\Http\Message\ResponseInterface $response, Laminas\HttpHandlerRunner\Emitter\EmitterInterface|null $emitter = null): void ``` Emit the response using the PHP SAPI. #### Parameters `Psr\Http\Message\ResponseInterface` $response The response to emit `Laminas\HttpHandlerRunner\Emitter\EmitterInterface|null` $emitter optional The emitter to use. When null, a SAPI Stream Emitter will be used. #### Returns `void` ### getApp() public ``` getApp(): Cake\Core\HttpApplicationInterface ``` Get the current application. #### Returns `Cake\Core\HttpApplicationInterface` ### 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` ### run() public ``` run(Psr\Http\Message\ServerRequestInterface|null $request = null, Cake\Http\MiddlewareQueue|null $middlewareQueue = null): Psr\Http\Message\ResponseInterface ``` Run the request/response through the Application and its middleware. This will invoke the following methods: * App->bootstrap() - Perform any bootstrapping logic for your application here. * App->middleware() - Attach any application middleware here. * Trigger the 'Server.buildMiddleware' event. You can use this to modify the from event listeners. * Run the middleware queue including the application. #### Parameters `Psr\Http\Message\ServerRequestInterface|null` $request optional The request to use or null. `Cake\Http\MiddlewareQueue|null` $middlewareQueue optional MiddlewareQueue or null. #### Returns `Psr\Http\Message\ResponseInterface` #### Throws `RuntimeException` When the application does not make a response. ### setEventManager() public ``` setEventManager(Cake\Event\EventManagerInterface $eventManager): $this ``` Set the application's event manager. If the application does not support events, 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` ### $app protected #### Type `Cake\Core\HttpApplicationInterface` ### $runner protected #### Type `Cake\Http\Runner` cakephp Class SelectWithPivotLoader Class SelectWithPivotLoader ============================ Implements the logic for loading an association using a SELECT query and a pivot table **Namespace:** [Cake\ORM\Association\Loader](namespace-cake.orm.association.loader) Property Summary ---------------- * [$alias](#%24alias) protected `string` The alias of the association loading the results * [$associationType](#%24associationType) protected `string` The type of the association triggering the load * [$bindingKey](#%24bindingKey) protected `string` The binding key for the source association. * [$finder](#%24finder) protected `callable` A callable that will return a query object used for loading the association results * [$foreignKey](#%24foreignKey) protected `array|string` The foreignKey to the target association * [$junctionAssoc](#%24junctionAssoc) protected `Cake\ORM\Association\HasMany` The junction association instance * [$junctionAssociationName](#%24junctionAssociationName) protected `string` The name of the junction association * [$junctionConditions](#%24junctionConditions) protected `Cake\Database\ExpressionInterfaceClosure|array|string|null` Custom conditions for the junction association * [$junctionProperty](#%24junctionProperty) protected `string` The property name for the junction association, where its results should be nested at. * [$sort](#%24sort) protected `string` The sorting options for loading the association * [$sourceAlias](#%24sourceAlias) protected `string` The alias of the source association * [$strategy](#%24strategy) protected `string` The strategy to use for loading, either select or subquery * [$targetAlias](#%24targetAlias) protected `string` The alias of the target association Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Copies the options array to properties in this class. The keys in the array correspond to properties in this class. * ##### [\_addFilteringCondition()](#_addFilteringCondition()) protected Appends any conditions required to load the relevant set of records in the target table query given a filter key and some filtering values. * ##### [\_addFilteringJoin()](#_addFilteringJoin()) protected Appends any conditions required to load the relevant set of records in the target table query given a filter key and some filtering values when the filtering needs to be done using a subquery. * ##### [\_assertFieldsPresent()](#_assertFieldsPresent()) protected Checks that the fetching query either has auto fields on or has the foreignKey fields selected. If the required fields are missing, throws an exception. * ##### [\_buildQuery()](#_buildQuery()) protected Auxiliary function to construct a new Query object to return all the records in the target table that are associated to those specified in $options from the source table. * ##### [\_buildResultMap()](#_buildResultMap()) protected Builds an array containing the results from fetchQuery indexed by the foreignKey value corresponding to this association. * ##### [\_buildSubquery()](#_buildSubquery()) protected Builds a query to be used as a condition for filtering records in the target table, it is constructed by cloning the original query that was used to load records in the source table. * ##### [\_createTupleCondition()](#_createTupleCondition()) protected Returns a TupleComparison object that can be used for matching all the fields from $keys with the tuple values in $filter using the provided operator. * ##### [\_defaultOptions()](#_defaultOptions()) protected Returns the default options to use for the eagerLoader * ##### [\_extractFinder()](#_extractFinder()) protected Helper method to infer the requested finder and its options. * ##### [\_linkField()](#_linkField()) protected Generates a string used as a table field that contains the values upon which the filter should be applied * ##### [\_multiKeysInjector()](#_multiKeysInjector()) protected Returns a callable to be used for each row in a query result set for injecting the eager loaded rows when the matching needs to be done with multiple foreign keys * ##### [\_resultInjector()](#_resultInjector()) protected Returns a callable to be used for each row in a query result set for injecting the eager loaded rows * ##### [\_subqueryFields()](#_subqueryFields()) protected Calculate the fields that need to participate in a subquery. * ##### [buildEagerLoader()](#buildEagerLoader()) public Returns a callable that can be used for injecting association results into a given iterator. The options accepted by this method are the same as `Association::eagerLoader()` Method Detail ------------- ### \_\_construct() public ``` __construct(array<string, mixed> $options) ``` Copies the options array to properties in this class. The keys in the array correspond to properties in this class. #### Parameters `array<string, mixed>` $options ### \_addFilteringCondition() protected ``` _addFilteringCondition(Cake\ORM\Query $query, array<string>|string $key, mixed $filter): Cake\ORM\Query ``` Appends any conditions required to load the relevant set of records in the target table query given a filter key and some filtering values. #### Parameters `Cake\ORM\Query` $query Target table's query `array<string>|string` $key The fields that should be used for filtering `mixed` $filter The value that should be used to match for $key #### Returns `Cake\ORM\Query` ### \_addFilteringJoin() protected ``` _addFilteringJoin(Cake\ORM\Query $query, array<string>|string $key, Cake\ORM\Query $subquery): Cake\ORM\Query ``` Appends any conditions required to load the relevant set of records in the target table query given a filter key and some filtering values when the filtering needs to be done using a subquery. #### Parameters `Cake\ORM\Query` $query Target table's query `array<string>|string` $key the fields that should be used for filtering `Cake\ORM\Query` $subquery The Subquery to use for filtering #### Returns `Cake\ORM\Query` ### \_assertFieldsPresent() protected ``` _assertFieldsPresent(Cake\ORM\Query $fetchQuery, array<string> $key): void ``` Checks that the fetching query either has auto fields on or has the foreignKey fields selected. If the required fields are missing, throws an exception. #### Parameters `Cake\ORM\Query` $fetchQuery `array<string>` $key #### Returns `void` ### \_buildQuery() protected ``` _buildQuery(array<string, mixed> $options): Cake\ORM\Query ``` Auxiliary function to construct a new Query object to return all the records in the target table that are associated to those specified in $options from the source table. This is used for eager loading records on the target table based on conditions. #### Parameters `array<string, mixed>` $options options accepted by eagerLoader() #### Returns `Cake\ORM\Query` #### Throws `InvalidArgumentException` When a key is required for associations but not selected. ### \_buildResultMap() protected ``` _buildResultMap(Cake\ORM\Query $fetchQuery, array<string, mixed> $options): array<string, mixed> ``` Builds an array containing the results from fetchQuery indexed by the foreignKey value corresponding to this association. #### Parameters `Cake\ORM\Query` $fetchQuery The query to get results from `array<string, mixed>` $options The options passed to the eager loader #### Returns `array<string, mixed>` #### Throws `RuntimeException` when the association property is not part of the results set. ### \_buildSubquery() protected ``` _buildSubquery(Cake\ORM\Query $query): Cake\ORM\Query ``` Builds a query to be used as a condition for filtering records in the target table, it is constructed by cloning the original query that was used to load records in the source table. #### Parameters `Cake\ORM\Query` $query the original query used to load source records #### Returns `Cake\ORM\Query` ### \_createTupleCondition() protected ``` _createTupleCondition(Cake\ORM\Query $query, array<string> $keys, mixed $filter, string $operator): Cake\Database\Expression\TupleComparison ``` Returns a TupleComparison object that can be used for matching all the fields from $keys with the tuple values in $filter using the provided operator. #### Parameters `Cake\ORM\Query` $query Target table's query `array<string>` $keys the fields that should be used for filtering `mixed` $filter the value that should be used to match for $key `string` $operator The operator for comparing the tuples #### Returns `Cake\Database\Expression\TupleComparison` ### \_defaultOptions() protected ``` _defaultOptions(): array<string, mixed> ``` Returns the default options to use for the eagerLoader #### Returns `array<string, mixed>` ### \_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` ### \_linkField() protected ``` _linkField(array<string, mixed> $options): array<string>|string ``` Generates a string used as a table field that contains the values upon which the filter should be applied #### Parameters `array<string, mixed>` $options the options to use for getting the link field. #### Returns `array<string>|string` ### \_multiKeysInjector() protected ``` _multiKeysInjector(array<string, mixed> $resultMap, array<string> $sourceKeys, string $nestKey): Closure ``` Returns a callable to be used for each row in a query result set for injecting the eager loaded rows when the matching needs to be done with multiple foreign keys #### Parameters `array<string, mixed>` $resultMap A keyed arrays containing the target table `array<string>` $sourceKeys An array with aliased keys to match `string` $nestKey The key under which results should be nested #### Returns `Closure` ### \_resultInjector() protected ``` _resultInjector(Cake\ORM\Query $fetchQuery, array<string, mixed> $resultMap, array<string, mixed> $options): Closure ``` Returns a callable to be used for each row in a query result set for injecting the eager loaded rows #### Parameters `Cake\ORM\Query` $fetchQuery the Query used to fetch results `array<string, mixed>` $resultMap an array with the foreignKey as keys and the corresponding target table results as value. `array<string, mixed>` $options The options passed to the eagerLoader method #### Returns `Closure` ### \_subqueryFields() protected ``` _subqueryFields(Cake\ORM\Query $query): array<string, array> ``` Calculate the fields that need to participate in a subquery. Normally this includes the binding key columns. If there is a an ORDER BY, those columns are also included as the fields may be calculated or constant values, that need to be present to ensure the correct association data is loaded. #### Parameters `Cake\ORM\Query` $query The query to get fields from. #### Returns `array<string, array>` ### buildEagerLoader() public ``` buildEagerLoader(array<string, mixed> $options): Closure ``` Returns a callable that can be used for injecting association results into a given iterator. The options accepted by this method are the same as `Association::eagerLoader()` #### Parameters `array<string, mixed>` $options Same options as `Association::eagerLoader()` #### Returns `Closure` Property Detail --------------- ### $alias protected The alias of the association loading the results #### Type `string` ### $associationType protected The type of the association triggering the load #### Type `string` ### $bindingKey protected The binding key for the source association. #### Type `string` ### $finder protected A callable that will return a query object used for loading the association results #### Type `callable` ### $foreignKey protected The foreignKey to the target association #### Type `array|string` ### $junctionAssoc protected The junction association instance #### Type `Cake\ORM\Association\HasMany` ### $junctionAssociationName protected The name of the junction association #### Type `string` ### $junctionConditions protected Custom conditions for the junction association #### Type `Cake\Database\ExpressionInterfaceClosure|array|string|null` ### $junctionProperty protected The property name for the junction association, where its results should be nested at. #### Type `string` ### $sort protected The sorting options for loading the association #### Type `string` ### $sourceAlias protected The alias of the source association #### Type `string` ### $strategy protected The strategy to use for loading, either select or subquery #### Type `string` ### $targetAlias protected The alias of the target association #### Type `string` cakephp Class IntegerType Class IntegerType ================== Integer type converter. Use to convert integer 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 * ##### [checkNumeric()](#checkNumeric()) protected Checks if the value is not a numeric value * ##### [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 integer data. Method Detail ------------- ### \_\_construct() public ``` __construct(string|null $name = null) ``` Constructor #### Parameters `string|null` $name optional The name identifying this type ### checkNumeric() protected ``` checkNumeric(mixed $value): void ``` Checks if the value is not a numeric value #### Parameters `mixed` $value Value to check #### Returns `void` #### Throws `InvalidArgumentException` ### 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): int|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 `int|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): int|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 `int|null` ### toPHP() public ``` toPHP(mixed $value, Cake\Database\DriverInterface $driver): int|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 `int|null` ### toStatement() public ``` toStatement(mixed $value, Cake\Database\DriverInterface $driver): int ``` Get the correct PDO binding type for integer 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`
programming_docs
cakephp Class Entity Class Entity ============= An entity represents a single result row from a repository. It exposes the methods for retrieving and storing properties associated in this row. **Namespace:** [Cake\ORM](namespace-cake.orm) Property Summary ---------------- * [$\_accessible](#%24_accessible) protected `array<string, bool>` Map of fields in this entity that can be safely assigned, each field name points to a boolean indicating its status. An empty array means no fields are accessible * [$\_accessors](#%24_accessors) protected static `array<string, array<string, array<string, string>>>` Holds a cached list of getters/setters per class * [$\_dirty](#%24_dirty) protected `array<bool>` Holds a list of the fields that were modified or added after this object was originally created. * [$\_errors](#%24_errors) protected `array<string, mixed>` List of errors per field as stored in this object. * [$\_fields](#%24_fields) protected `array<string, mixed>` Holds all fields and their values for this entity. * [$\_hidden](#%24_hidden) protected `array<string>` List of field names that should **not** be included in JSON or Array representations of this Entity. * [$\_invalid](#%24_invalid) protected `array<string, mixed>` List of invalid fields and their data for errors upon validation/patching. * [$\_new](#%24_new) protected `bool` Indicates whether this entity is yet to be persisted. Entities default to assuming they are new. You can use Table::persisted() to set the new flag on an entity based on records in the database. * [$\_original](#%24_original) protected `array<string, mixed>` Holds all fields that have been changed and their original values for this entity. * [$\_registryAlias](#%24_registryAlias) protected `string` The alias of the repository this entity came from * [$\_virtual](#%24_virtual) protected `array<string>` List of computed or virtual fields that **should** be included in JSON or array representations of this Entity. If a field is present in both \_hidden and \_virtual the field will **not** be in the array/JSON versions of the entity. * [$id](#%24id) public @property `mixed` Alias for commonly used primary key. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Initializes the internal properties of this entity out of the keys in an array. The following list of options can be used: * ##### [\_\_debugInfo()](#__debugInfo()) public Returns an array that can be used to describe the internal state of this object. * ##### [\_\_get()](#__get()) public Magic getter to access fields that have been set in this entity * ##### [\_\_isset()](#__isset()) public Returns whether this entity contains a field named $field and is not set to null. * ##### [\_\_set()](#__set()) public Magic setter to add or edit a field in this entity * ##### [\_\_toString()](#__toString()) public Returns a string representation of this object in a human readable format. * ##### [\_\_unset()](#__unset()) public Removes a field from this entity * ##### [\_accessor()](#_accessor()) protected static Fetch accessor method name Accessor methods (available or not) are cached in $\_accessors * ##### [\_nestedErrors()](#_nestedErrors()) protected Auxiliary method for getting errors in nested entities * ##### [\_readError()](#_readError()) protected Read the error(s) from one or many objects. * ##### [\_readHasErrors()](#_readHasErrors()) protected Reads if there are errors for one or many objects. * ##### [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 Returns the raw accessible configuration for this entity. The `*` wildcard refers to all fields. * ##### [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. * ##### [getInvalid()](#getInvalid()) public Get a list of invalid fields and their data for errors upon validation/patching * ##### [getInvalidField()](#getInvalidField()) public Get a single value of an invalid field. Returns null if not set. * ##### [getOriginal()](#getOriginal()) public Returns the value of an original field by name * ##### [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 Gets the list of visible fields. * ##### [has()](#has()) public Returns whether this entity contains a field named $field that contains a non-null value. * ##### [hasErrors()](#hasErrors()) public Returns whether this entity has errors. * ##### [hasValue()](#hasValue()) public Checks that a field has a value. * ##### [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. * ##### [isEmpty()](#isEmpty()) public Checks that a field is empty * ##### [isNew()](#isNew()) public Returns whether this entity has already been persisted. * ##### [jsonSerialize()](#jsonSerialize()) public Returns the fields that will be serialized as JSON * ##### [offsetExists()](#offsetExists()) public Implements isset($entity); * ##### [offsetGet()](#offsetGet()) public Implements $entity[$offset]; * ##### [offsetSet()](#offsetSet()) public Implements $entity[$offset] = $value; * ##### [offsetUnset()](#offsetUnset()) public Implements unset($result[$offset]); * ##### [set()](#set()) public Sets a single field inside this entity. * ##### [setAccess()](#setAccess()) public Stores whether a field value can be changed or set in this entity. The special field `*` can also be marked as accessible or protected, meaning that any other field specified before will take its value. For example `$entity->setAccess('*', true)` means that any field not specified already will be accessible by default. * ##### [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. * ##### [setInvalid()](#setInvalid()) public Set fields as invalid and not patchable into the entity. * ##### [setInvalidField()](#setInvalidField()) public Sets a field as invalid and not patchable into the entity. * ##### [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 fields that have been set to this entity * ##### [unset()](#unset()) public Removes a field or list of fields from this entity * ##### [unsetProperty()](#unsetProperty()) public deprecated Removes a field or list of fields from this entity Method Detail ------------- ### \_\_construct() public ``` __construct(array<string, mixed> $properties = [], array<string, mixed> $options = []) ``` Initializes the internal properties of this entity out of the keys in an array. The following list of options can be used: * useSetters: whether use internal setters for properties or not * markClean: whether to mark all properties as clean after setting them * markNew: whether this instance has not yet been persisted * guard: whether to prevent inaccessible properties from being set (default: false) * source: A string representing the alias of the repository this entity came from ### Example: ``` $entity = new Entity(['id' => 1, 'name' => 'Andrew']) ``` #### Parameters `array<string, mixed>` $properties optional hash of properties to set in this entity `array<string, mixed>` $options optional list of options to use when creating this entity ### \_\_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 $field): mixed ``` Magic getter to access fields that have been set in this entity #### Parameters `string` $field Name of the field to access #### Returns `mixed` ### \_\_isset() public ``` __isset(string $field): bool ``` Returns whether this entity contains a field named $field and is not set to null. #### Parameters `string` $field The field to check. #### Returns `bool` #### See Also \Cake\ORM\Entity::has() ### \_\_set() public ``` __set(string $field, mixed $value): void ``` Magic setter to add or edit a field in this entity #### Parameters `string` $field The name of the field to set `mixed` $value The value to set to the field #### Returns `void` ### \_\_toString() public ``` __toString(): string ``` Returns a string representation of this object in a human readable format. #### Returns `string` ### \_\_unset() public ``` __unset(string $field): void ``` Removes a field from this entity #### Parameters `string` $field The field to unset #### Returns `void` ### \_accessor() protected static ``` _accessor(string $property, string $type): string ``` Fetch accessor method name Accessor methods (available or not) are cached in $\_accessors #### Parameters `string` $property the field name to derive getter name from `string` $type the accessor type ('get' or 'set') #### Returns `string` ### \_nestedErrors() protected ``` _nestedErrors(string $field): array ``` Auxiliary method for getting errors in nested entities #### Parameters `string` $field the field in this entity to check for errors #### Returns `array` ### \_readError() protected ``` _readError(Cake\Datasource\EntityInterface|iterable $object, string|null $path = null): array ``` Read the error(s) from one or many objects. #### Parameters `Cake\Datasource\EntityInterface|iterable` $object The object to read errors from. `string|null` $path optional The field name for errors. #### Returns `array` ### \_readHasErrors() protected ``` _readHasErrors(Cake\Datasource\EntityInterface|array $object): bool ``` Reads if there are errors for one or many objects. #### Parameters `Cake\Datasource\EntityInterface|array` $object The object to read errors from. #### Returns `bool` ### 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. Fields that are unchanged from their original value will be included in the return of this method. #### 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. This method will only return fields that have been modified since the entity was built. Unchanged fields will be omitted. #### 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` #### Throws `InvalidArgumentException` if an empty field name is passed ### getAccessible() public ``` getAccessible(): array<bool> ``` Returns the raw accessible configuration for this entity. The `*` wildcard refers to all fields. #### Returns `array<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>` ### getInvalid() public ``` getInvalid(): array<string, mixed> ``` Get a list of invalid fields and their data for errors upon validation/patching #### Returns `array<string, mixed>` ### getInvalidField() public ``` getInvalidField(string $field): mixed|null ``` Get a single value of an invalid field. Returns null if not set. #### Parameters `string` $field The name of the field. #### Returns `mixed|null` ### getOriginal() public ``` getOriginal(string $field): mixed ``` Returns the value of an original field by name #### Parameters `string` $field the name of the field for which original value is retrieved. #### Returns `mixed` #### Throws `InvalidArgumentException` if an empty field name is passed. ### 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> ``` Gets the list of visible fields. The list of visible fields is all standard fields plus virtual fields minus hidden fields. #### Returns `array<string>` ### has() public ``` has(array<string>|string $field): bool ``` Returns whether this entity contains a field named $field that contains a non-null value. ### Example: ``` $entity = new Entity(['id' => 1, 'name' => null]); $entity->has('id'); // true $entity->has('name'); // false $entity->has('last_name'); // false ``` You can check multiple fields by passing an array: ``` $entity->has(['name', 'last_name']); ``` All fields must not be null to get a truthy result. When checking multiple fields. All fields must not be null in order for true to be returned. #### Parameters `array<string>|string` $field The field or fields 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` ### hasValue() public ``` hasValue(string $field): bool ``` Checks that a field has a value. This method will return true for * Non-empty strings * Non-empty arrays * Any object * Integer, even `0` * Float, even 0.0 and false in all other cases. #### Parameters `string` $field The field to check. #### Returns `bool` ### isAccessible() public ``` isAccessible(string $field): bool ``` Checks if a field is accessible ### Example: ``` $entity->isAccessible('id'); // Returns whether it can be set or not ``` #### 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` ### isEmpty() public ``` isEmpty(string $field): bool ``` Checks that a field is empty This is not working like the PHP `empty()` function. The method will return true for: * `''` (empty string) * `null` * `[]` and false in all other cases. #### Parameters `string` $field The field to check. #### Returns `bool` ### isNew() public ``` isNew(): bool ``` Returns whether this entity has already been persisted. #### Returns `bool` ### jsonSerialize() public ``` jsonSerialize(): array ``` Returns the fields that will be serialized as JSON #### Returns `array` ### offsetExists() public ``` offsetExists(string $offset): bool ``` Implements isset($entity); #### Parameters `string` $offset The offset to check. #### Returns `bool` ### offsetGet() public ``` offsetGet(string $offset): mixed ``` Implements $entity[$offset]; #### Parameters `string` $offset The offset to get. #### Returns `mixed` ### offsetSet() public ``` offsetSet(string $offset, mixed $value): void ``` Implements $entity[$offset] = $value; #### Parameters `string` $offset The offset to set. `mixed` $value The value to set. #### Returns `void` ### offsetUnset() public ``` offsetUnset(string $offset): void ``` Implements unset($result[$offset]); #### Parameters `string` $offset The offset to remove. #### Returns `void` ### set() public ``` set(array<string, mixed>|string $field, mixed $value = null, array<string, mixed> $options = []): $this ``` Sets a single field inside this entity. ### Example: ``` $entity->set('name', 'Andrew'); ``` It is also possible to mass-assign multiple fields to this entity with one call by passing a hashed array as fields in the form of field => value pairs ### Example: ``` $entity->set(['name' => 'andrew', 'id' => 1]); echo $entity->name // prints andrew echo $entity->id // prints 1 ``` Some times it is handy to bypass setter functions in this entity when assigning fields. You can achieve this by disabling the `setter` option using the `$options` parameter: ``` $entity->set('name', 'Andrew', ['setter' => false]); $entity->set(['name' => 'Andrew', 'id' => 1], ['setter' => false]); ``` Mass assignment should be treated carefully when accepting user input, by default entities will guard all fields when fields are assigned in bulk. You can disable the guarding for a single set call with the `guard` option: ``` $entity->set(['name' => 'Andrew', 'id' => 1], ['guard' => false]); ``` You do not need to use the guard option when assigning fields individually: ``` // No need to use the guard option. $entity->set('name', 'Andrew'); ``` #### 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` #### Throws `InvalidArgumentException` ### setAccess() public ``` setAccess(array<string>|string $field, bool $set): $this ``` Stores whether a field value can be changed or set in this entity. The special field `*` can also be marked as accessible or protected, meaning that any other field specified before will take its value. For example `$entity->setAccess('*', true)` means that any field not specified already will be accessible by default. You can also call this method with an array of fields, in which case they will each take the accessibility value specified in the second argument. ### Example: ``` $entity->setAccess('id', true); // Mark id as not protected $entity->setAccess('author_id', false); // Mark author_id as protected $entity->setAccess(['id', 'user_id'], true); // Mark both fields as accessible $entity->setAccess('*', false); // Mark all fields as protected ``` #### 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. Defaults to true. #### Returns `$this` ### setError() public ``` setError(string $field, array|string $errors, bool $overwrite = false): $this ``` Sets errors for a single field ### Example ``` // Sets the error messages for a single field $entity->setError('salary', ['must be numeric', 'must be a positive number']); ``` #### 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 Example ------- ``` // Sets the error messages for multiple fields at once $entity->setErrors(['salary' => ['message'], 'name' => ['another message']]); ``` #### 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` ### setInvalid() public ``` setInvalid(array<string, mixed> $fields, bool $overwrite = false): $this ``` Set fields as invalid and not patchable into the entity. This is useful for batch operations when one needs to get the original value for an error message after patching. This value could not be patched into the entity and is simply copied into the \_invalid property for debugging purposes or to be able to log it away. #### Parameters `array<string, mixed>` $fields The values to set. `bool` $overwrite optional Whether to overwrite pre-existing values for $field. #### Returns `$this` ### setInvalidField() public ``` setInvalidField(string $field, mixed $value): $this ``` Sets a field as invalid and not patchable into the entity. #### Parameters `string` $field The value to set. `mixed` $value The invalid value to be set for $field. #### 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` that it already is. #### 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 fields that have been set to this entity This method will recursively transform entities assigned to fields into arrays as well. #### Returns `array` ### unset() public ``` unset(array<string>|string $field): $this ``` Removes a field or list of fields from this entity ### Examples: ``` $entity->unset('name'); $entity->unset(['name', 'last_name']); ``` #### Parameters `array<string>|string` $field The field to unset. #### Returns `$this` ### unsetProperty() public ``` unsetProperty(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 --------------- ### $\_accessible protected Map of fields in this entity that can be safely assigned, each field name points to a boolean indicating its status. An empty array means no fields are accessible The special field '\*' can also be mapped, meaning that any other field not defined in the map will take its value. For example, `'*' => true` means that any field not defined in the map will be accessible by default #### Type `array<string, bool>` ### $\_accessors protected static Holds a cached list of getters/setters per class #### Type `array<string, array<string, array<string, string>>>` ### $\_dirty protected Holds a list of the fields that were modified or added after this object was originally created. #### Type `array<bool>` ### $\_errors protected List of errors per field as stored in this object. #### Type `array<string, mixed>` ### $\_fields protected Holds all fields and their values for this entity. #### Type `array<string, mixed>` ### $\_hidden protected List of field names that should **not** be included in JSON or Array representations of this Entity. #### Type `array<string>` ### $\_invalid protected List of invalid fields and their data for errors upon validation/patching. #### Type `array<string, mixed>` ### $\_new protected Indicates whether this entity is yet to be persisted. Entities default to assuming they are new. You can use Table::persisted() to set the new flag on an entity based on records in the database. #### Type `bool` ### $\_original protected Holds all fields that have been changed and their original values for this entity. #### Type `array<string, mixed>` ### $\_registryAlias protected The alias of the repository this entity came from #### Type `string` ### $\_virtual protected List of computed or virtual fields that **should** be included in JSON or array representations of this Entity. If a field is present in both \_hidden and \_virtual the field will **not** be in the array/JSON versions of the entity. #### Type `array<string>` ### $id public @property Alias for commonly used primary key. #### Type `mixed`
programming_docs
cakephp Interface FormatterInterface Interface FormatterInterface ============================= Formatter Interface **Namespace:** [Cake\I18n](namespace-cake.i18n) 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 Namespace TestSuite Namespace TestSuite =================== ### Traits * ##### [HttpClientTrait](trait-cake.http.testsuite.httpclienttrait) Define mock responses and have mocks automatically cleared. cakephp Class FlashParamEquals Class FlashParamEquals ======================= FlashParamEquals **Namespace:** [Cake\TestSuite\Constraint\Session](namespace-cake.testsuite.constraint.session) Property Summary ---------------- * [$at](#%24at) protected `int|null` * [$key](#%24key) protected `string` * [$param](#%24param) protected `string` * [$session](#%24session) protected `Cake\Http\Session` 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 to flash message(s) * ##### [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\Http\Session|null $session, string $key, string $param, int|null $at = null) ``` Constructor #### Parameters `Cake\Http\Session|null` $session Session `string` $key Flash key `string` $param Param to check `int|null` $at optional Expected index ### 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 to flash message(s) 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 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` ### $key protected #### Type `string` ### $param protected #### Type `string` ### $session protected #### Type `Cake\Http\Session` cakephp Class RequestException Class RequestException ======================= Exception for when a request failed. Examples: * Request is invalid (e.g. method is missing) + Runtime request errors (e.g. the body stream is not seekable) **Namespace:** [Cake\Http\Client\Exception](namespace-cake.http.client.exception) Property Summary ---------------- * [$request](#%24request) protected `Psr\Http\Message\RequestInterface` Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [getRequest()](#getRequest()) public Returns the request. Method Detail ------------- ### \_\_construct() public ``` __construct(string $message, Psr\Http\Message\RequestInterface $request, Throwable|null $previous = null) ``` Constructor. #### Parameters `string` $message Exeception message. `Psr\Http\Message\RequestInterface` $request Request instance. `Throwable|null` $previous optional Previous Exception ### getRequest() public ``` getRequest(): Psr\Http\Message\RequestInterface ``` Returns the request. The request object MAY be a different object from the one passed to ClientInterface::sendRequest() #### Returns `Psr\Http\Message\RequestInterface` Property Detail --------------- ### $request protected #### Type `Psr\Http\Message\RequestInterface` cakephp Class ZipIterator Class ZipIterator ================== Creates an iterator that returns elements grouped in pairs ### Example ``` $iterator = new ZipIterator([[1, 2], [3, 4]]); $iterator->toList(); // Returns [[1, 3], [2, 4]] ``` You can also chose a custom function to zip the elements together, such as doing a sum by index: ### Example ``` $iterator = new ZipIterator([[1, 2], [3, 4]], function ($a, $b) { return $a + $b; }); $iterator->toList(); // Returns [4, 6] ``` **Namespace:** [Cake\Collection\Iterator](namespace-cake.collection.iterator) Property Summary ---------------- * [$\_callback](#%24_callback) protected `callable|null` The function to use for zipping items together * [$\_iterators](#%24_iterators) protected `array` Contains the original iterator objects that were attached Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Creates the iterator to merge together the values by for all the passed iterators by their corresponding index. * ##### [\_\_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 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 resulting out of zipping all the elements for all the iterators with the same positional index. * ##### [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 ZipIterator 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(array $sets, callable|null $callable = null) ``` Creates the iterator to merge together the values by for all the passed iterators by their corresponding index. #### Parameters `array` $sets The list of array or iterators to be zipped. `callable|null` $callable optional The function to use for zipping the elements of each iterator. ### \_\_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 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(): array ``` Returns the value resulting out of zipping all the elements for all the iterators with the same positional index. #### Returns `array` ### 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 $iterators): void ``` Unserializes the passed string and rebuilds the ZipIterator instance #### Parameters `string` $iterators The serialized iterators #### 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 function to use for zipping items together #### Type `callable|null` ### $\_iterators protected Contains the original iterator objects that were attached #### Type `array`
programming_docs
cakephp Class EagerLoader Class 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. **Namespace:** [Cake\ORM](namespace-cake.orm) Property Summary ---------------- * [$\_aliasList](#%24_aliasList) protected `array` Contains a list of the association names that are to be eagerly loaded * [$\_autoFields](#%24_autoFields) protected `bool` Controls whether fields from associated tables will be eagerly loaded. When set to false, no fields will be loaded from associations. * [$\_containOptions](#%24_containOptions) protected `array<string, int>` List of options accepted by associations in contain() index by key for faster access * [$\_containments](#%24_containments) protected `array<string, mixed>` Nested array describing the association to be fetched and the options to apply for each of them, if any * [$\_joinsMap](#%24_joinsMap) protected `array<string,Cake\ORM\EagerLoadable>` A map of table aliases pointing to the association objects they represent for the query. * [$\_loadExternal](#%24_loadExternal) protected `arrayCake\ORM\EagerLoadable>` A list of associations that should be loaded with a separate query * [$\_matching](#%24_matching) protected `Cake\ORM\EagerLoader|null` Another EagerLoader instance that will be used for 'matching' associations. * [$\_normalized](#%24_normalized) protected `Cake\ORM\EagerLoadable|arrayCake\ORM\EagerLoadable>|null` Contains a nested array with the compiled containments tree This is a normalized version of the user provided containments array. Method Summary -------------- * ##### [\_\_clone()](#__clone()) public Handles cloning eager loaders and eager loadables. * ##### [\_buildAssociationsMap()](#_buildAssociationsMap()) protected An internal method to build a map which is used for the return value of the associationsMap() method. * ##### [\_collectKeys()](#_collectKeys()) protected Helper function used to return the keys from the query records that will be used to eagerly load associations. * ##### [\_correctStrategy()](#_correctStrategy()) protected Changes the association fetching strategy if required because of duplicate under the same direct associations chain * ##### [\_fixStrategies()](#_fixStrategies()) protected Iterates over the joinable aliases list and corrects the fetching strategies in order to avoid aliases collision in the generated queries. * ##### [\_groupKeys()](#_groupKeys()) protected Helper function used to iterate a statement and extract the columns defined in $collectKeys * ##### [\_normalizeContain()](#_normalizeContain()) protected Auxiliary function responsible for fully normalizing deep associations defined using `contain()` * ##### [\_reformatContain()](#_reformatContain()) protected Formats the containments array so that associations are always set as keys in the array. This function merges the original associations array with the new associations provided * ##### [\_resolveJoins()](#_resolveJoins()) protected Helper function used to compile a list of all associations that can be joined in the query. * ##### [addToJoinsMap()](#addToJoinsMap()) public Registers a table alias, typically loaded as a join in a query, as belonging to an association. This helps hydrators know what to do with the columns coming from such joined table. * ##### [associationsMap()](#associationsMap()) public Returns an array having as keys a dotted path of associations that participate in this eager loader. The values of the array will contain the following keys * ##### [attachAssociations()](#attachAssociations()) public Modifies the passed query to apply joins or any other transformation required in order to eager load the associations described in the `contain` array. This method will not modify the query for loading external associations, i.e. those that cannot be loaded without executing a separate query. * ##### [attachableAssociations()](#attachableAssociations()) public Returns an array with the associations that can be fetched using a single query, the array keys are the association aliases and the values will contain an array with Cake\ORM\EagerLoadable objects. * ##### [clearContain()](#clearContain()) public Remove any existing non-matching based containments. * ##### [contain()](#contain()) public Sets the list of associations that should be eagerly loaded along for a specific table using when a query is provided. The list of associated tables passed to this method must have been previously set as associations using the Table API. * ##### [disableAutoFields()](#disableAutoFields()) public Disable auto loading fields of contained associations. * ##### [enableAutoFields()](#enableAutoFields()) public Sets whether contained associations will load fields automatically. * ##### [externalAssociations()](#externalAssociations()) public Returns an array with the associations that need to be fetched using a separate query, each array value will contain a {@link \Cake\ORM\EagerLoadable} object. * ##### [getContain()](#getContain()) public Gets the list of associations that should be eagerly loaded along for a specific table using when a query is provided. The list of associated tables passed to this method must have been previously set as associations using the Table API. * ##### [getMatching()](#getMatching()) public Returns the current tree of associations to be matched. * ##### [isAutoFieldsEnabled()](#isAutoFieldsEnabled()) public Gets whether contained associations will load fields automatically. * ##### [loadExternal()](#loadExternal()) public Decorates the passed statement object in order to inject data from associations that cannot be joined directly. * ##### [normalized()](#normalized()) public Returns the fully normalized array of associations that should be eagerly loaded for a table. The normalized array will restructure the original array by sorting all associations under one key and special options under another. * ##### [setMatching()](#setMatching()) public Adds a new association to the list that will be used to filter the results of any given query based on the results of finding records for that association. You can pass a dot separated path of associations to this method as its first parameter, this will translate in setting all those associations with the `matching` option. Method Detail ------------- ### \_\_clone() public ``` __clone(): void ``` Handles cloning eager loaders and eager loadables. #### Returns `void` ### \_buildAssociationsMap() protected ``` _buildAssociationsMap(array $map, arrayCake\ORM\EagerLoadable> $level, bool $matching = false): array ``` An internal method to build a map which is used for the return value of the associationsMap() method. #### Parameters `array` $map An initial array for the map. `arrayCake\ORM\EagerLoadable>` $level An array of EagerLoadable instances. `bool` $matching optional Whether it is an association loaded through `matching()`. #### Returns `array` ### \_collectKeys() protected ``` _collectKeys(arrayCake\ORM\EagerLoadable> $external, Cake\ORM\Query $query, Cake\Database\StatementInterface $statement): array ``` Helper function used to return the keys from the query records that will be used to eagerly load associations. #### Parameters `arrayCake\ORM\EagerLoadable>` $external the list of external associations to be loaded `Cake\ORM\Query` $query The query from which the results where generated `Cake\Database\StatementInterface` $statement The statement to work on #### Returns `array` ### \_correctStrategy() protected ``` _correctStrategy(Cake\ORM\EagerLoadable $loadable): void ``` Changes the association fetching strategy if required because of duplicate under the same direct associations chain #### Parameters `Cake\ORM\EagerLoadable` $loadable The association config #### Returns `void` ### \_fixStrategies() protected ``` _fixStrategies(): void ``` Iterates over the joinable aliases list and corrects the fetching strategies in order to avoid aliases collision in the generated queries. This function operates on the array references that were generated by the \_normalizeContain() function. #### Returns `void` ### \_groupKeys() protected ``` _groupKeys(Cake\Database\Statement\BufferedStatement $statement, array<string, array> $collectKeys): array ``` Helper function used to iterate a statement and extract the columns defined in $collectKeys #### Parameters `Cake\Database\Statement\BufferedStatement` $statement The statement to read from. `array<string, array>` $collectKeys The keys to collect #### Returns `array` ### \_normalizeContain() protected ``` _normalizeContain(Cake\ORM\Table $parent, string $alias, array<string, mixed> $options, array<string, mixed> $paths): Cake\ORM\EagerLoadable ``` Auxiliary function responsible for fully normalizing deep associations defined using `contain()` #### Parameters `Cake\ORM\Table` $parent owning side of the association `string` $alias name of the association to be loaded `array<string, mixed>` $options list of extra options to use for this association `array<string, mixed>` $paths An array with two values, the first one is a list of dot separated strings representing associations that lead to this `$alias` in the chain of associations to be loaded. The second value is the path to follow in entities' properties to fetch a record of the corresponding association. #### Returns `Cake\ORM\EagerLoadable` #### Throws `InvalidArgumentException` When containments refer to associations that do not exist. ### \_reformatContain() protected ``` _reformatContain(array $associations, array $original): array ``` Formats the containments array so that associations are always set as keys in the array. This function merges the original associations array with the new associations provided #### Parameters `array` $associations user provided containments array `array` $original The original containments array to merge with the new one #### Returns `array` ### \_resolveJoins() protected ``` _resolveJoins(arrayCake\ORM\EagerLoadable> $associations, arrayCake\ORM\EagerLoadable> $matching = []): arrayCake\ORM\EagerLoadable> ``` Helper function used to compile a list of all associations that can be joined in the query. #### Parameters `arrayCake\ORM\EagerLoadable>` $associations list of associations from which to obtain joins. `arrayCake\ORM\EagerLoadable>` $matching optional list of associations that should be forcibly joined. #### Returns `arrayCake\ORM\EagerLoadable>` ### addToJoinsMap() public ``` addToJoinsMap(string $alias, Cake\ORM\Association $assoc, bool $asMatching = false, string|null $targetProperty = null): void ``` Registers a table alias, typically loaded as a join in a query, as belonging to an association. This helps hydrators know what to do with the columns coming from such joined table. #### Parameters `string` $alias The table alias as it appears in the query. `Cake\ORM\Association` $assoc The association object the alias represents; will be normalized `bool` $asMatching optional Whether this join results should be treated as a 'matching' association. `string|null` $targetProperty optional The property name where the results of the join should be nested at. If not passed, the default property for the association will be used. #### Returns `void` ### associationsMap() public ``` associationsMap(Cake\ORM\Table $table): array ``` Returns an array having as keys a dotted path of associations that participate in this eager loader. The values of the array will contain the following keys * alias: The association alias * instance: The association instance * canBeJoined: Whether the association will be loaded using a JOIN * entityClass: The entity that should be used for hydrating the results * nestKey: A dotted path that can be used to correctly insert the data into the results. * matching: Whether it is an association loaded through `matching()`. #### Parameters `Cake\ORM\Table` $table The table containing the association that will be normalized #### Returns `array` ### attachAssociations() public ``` attachAssociations(Cake\ORM\Query $query, Cake\ORM\Table $repository, bool $includeFields): void ``` Modifies the passed query to apply joins or any other transformation required in order to eager load the associations described in the `contain` array. This method will not modify the query for loading external associations, i.e. those that cannot be loaded without executing a separate query. #### Parameters `Cake\ORM\Query` $query The query to be modified `Cake\ORM\Table` $repository The repository containing the associations `bool` $includeFields whether to append all fields from the associations to the passed query. This can be overridden according to the settings defined per association in the containments array #### Returns `void` ### attachableAssociations() public ``` attachableAssociations(Cake\ORM\Table $repository): arrayCake\ORM\EagerLoadable> ``` Returns an array with the associations that can be fetched using a single query, the array keys are the association aliases and the values will contain an array with Cake\ORM\EagerLoadable objects. #### Parameters `Cake\ORM\Table` $repository The table containing the associations to be attached #### Returns `arrayCake\ORM\EagerLoadable>` ### clearContain() public ``` clearContain(): void ``` Remove any existing non-matching based containments. This will reset/clear out any contained associations that were not added via matching(). #### Returns `void` ### contain() public ``` contain(array|string $associations, callable|null $queryBuilder = null): array ``` Sets the list of associations that should be eagerly loaded along for a specific table using when a query is provided. The list of associated tables passed to this method must have been previously set as associations using the Table API. Associations can be arbitrarily nested using dot notation or nested arrays, this allows this object to calculate joins or any additional queries that must be executed to bring the required associated data. Accepted options per passed association: * foreignKey: Used to set a different field to match both tables, if set to false no join conditions will be generated automatically * fields: An array with the fields that should be fetched from the association * queryBuilder: Equivalent to passing a callable instead of an options array * matching: Whether to inform the association class that it should filter the main query by the results fetched by that class. * joinType: For joinable associations, the SQL join type to use. * strategy: The loading strategy to use (join, select, subquery) #### Parameters `array|string` $associations list of table aliases to be queried. When this method is called multiple times it will merge previous list with the new one. `callable|null` $queryBuilder optional The query builder callable #### Returns `array` #### Throws `InvalidArgumentException` When using $queryBuilder with an array of $associations ### disableAutoFields() public ``` disableAutoFields(): $this ``` Disable auto loading fields of contained associations. #### Returns `$this` ### enableAutoFields() public ``` enableAutoFields(bool $enable = true): $this ``` Sets whether contained associations will load fields automatically. #### Parameters `bool` $enable optional The value to set. #### Returns `$this` ### externalAssociations() public ``` externalAssociations(Cake\ORM\Table $repository): arrayCake\ORM\EagerLoadable> ``` Returns an array with the associations that need to be fetched using a separate query, each array value will contain a {@link \Cake\ORM\EagerLoadable} object. #### Parameters `Cake\ORM\Table` $repository The table containing the associations to be loaded #### Returns `arrayCake\ORM\EagerLoadable>` ### getContain() public ``` getContain(): array ``` Gets the list of associations that should be eagerly loaded along for a specific table using when a query is provided. The list of associated tables passed to this method must have been previously set as associations using the Table API. #### Returns `array` ### getMatching() public ``` getMatching(): array ``` Returns the current tree of associations to be matched. #### Returns `array` ### isAutoFieldsEnabled() public ``` isAutoFieldsEnabled(): bool ``` Gets whether contained associations will load fields automatically. #### Returns `bool` ### loadExternal() public ``` loadExternal(Cake\ORM\Query $query, Cake\Database\StatementInterface $statement): Cake\Database\StatementInterface ``` Decorates the passed statement object in order to inject data from associations that cannot be joined directly. #### Parameters `Cake\ORM\Query` $query The query for which to eager load external associations `Cake\Database\StatementInterface` $statement The statement created after executing the $query #### Returns `Cake\Database\StatementInterface` #### Throws `RuntimeException` ### normalized() public ``` normalized(Cake\ORM\Table $repository): array ``` Returns the fully normalized array of associations that should be eagerly loaded for a table. The normalized array will restructure the original array by sorting all associations under one key and special options under another. Each of the levels of the associations tree will be converted to a {@link \Cake\ORM\EagerLoadable} object, that contains all the information required for the association objects to load the information from the database. Additionally, it will set an 'instance' key per association containing the association instance from the corresponding source table #### Parameters `Cake\ORM\Table` $repository The table containing the association that will be normalized #### Returns `array` ### setMatching() public ``` setMatching(string $associationPath, callable|null $builder = null, array<string, mixed> $options = []): $this ``` Adds a new association to the list that will be used to filter the results of any given query based on the results of finding records for that association. You can pass a dot separated path of associations to this method as its first parameter, this will translate in setting all those associations with the `matching` option. ### Options * `joinType`: INNER, OUTER, ... + `fields`: Fields to contain + `negateMatch`: Whether to add conditions negate match on target association #### Parameters `string` $associationPath Dot separated association path, 'Name1.Name2.Name3' `callable|null` $builder optional the callback function to be used for setting extra options to the filtering query `array<string, mixed>` $options optional Extra options for the association matching. #### Returns `$this` Property Detail --------------- ### $\_aliasList protected Contains a list of the association names that are to be eagerly loaded #### Type `array` ### $\_autoFields protected Controls whether fields from associated tables will be eagerly loaded. When set to false, no fields will be loaded from associations. #### Type `bool` ### $\_containOptions protected List of options accepted by associations in contain() index by key for faster access #### Type `array<string, int>` ### $\_containments protected Nested array describing the association to be fetched and the options to apply for each of them, if any #### Type `array<string, mixed>` ### $\_joinsMap protected A map of table aliases pointing to the association objects they represent for the query. #### Type `array<string,Cake\ORM\EagerLoadable>` ### $\_loadExternal protected A list of associations that should be loaded with a separate query #### Type `arrayCake\ORM\EagerLoadable>` ### $\_matching protected Another EagerLoader instance that will be used for 'matching' associations. #### Type `Cake\ORM\EagerLoader|null` ### $\_normalized protected Contains a nested array with the compiled containments tree This is a normalized version of the user provided containments array. #### Type `Cake\ORM\EagerLoadable|arrayCake\ORM\EagerLoadable>|null`
programming_docs
cakephp Interface ValidatorAwareInterface Interface ValidatorAwareInterface ================================== Provides methods for managing multiple validators. **Namespace:** [Cake\Validation](namespace-cake.validation) Method Summary -------------- * ##### [getValidator()](#getValidator()) public Returns the validation rules tagged with $name. * ##### [hasValidator()](#hasValidator()) public Checks whether a validator has been set. * ##### [setValidator()](#setValidator()) public This method stores a custom validator under the given name. Method Detail ------------- ### getValidator() public ``` getValidator(string|null $name = null): Cake\Validation\Validator ``` Returns the validation rules tagged with $name. 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` ### setValidator() public ``` setValidator(string $name, Cake\Validation\Validator $validator): $this ``` This method stores a custom validator under the given name. #### Parameters `string` $name The name of a validator to be set. `Cake\Validation\Validator` $validator Validator object to be set. #### Returns `$this` cakephp Class SecurityHeadersMiddleware Class SecurityHeadersMiddleware ================================ Handles common security headers in a convenient way **Namespace:** [Cake\Http\Middleware](namespace-cake.http.middleware) **Link:** https://book.cakephp.org/4/en/controllers/middleware.html#security-header-middleware Constants --------- * `string` **ALL** ``` 'all' ``` * `string` **ALLOW\_FROM** ``` 'allow-from' ``` * `string` **BY\_CONTENT\_TYPE** ``` 'by-content-type' ``` * `string` **BY\_FTP\_FILENAME** ``` 'by-ftp-filename' ``` * `string` **DENY** ``` 'deny' ``` * `string` **MASTER\_ONLY** ``` 'master-only' ``` * `string` **NONE** ``` 'none' ``` * `string` **NOOPEN** ``` 'noopen' ``` * `string` **NOSNIFF** ``` 'nosniff' ``` * `string` **NO\_REFERRER** ``` 'no-referrer' ``` * `string` **NO\_REFERRER\_WHEN\_DOWNGRADE** ``` 'no-referrer-when-downgrade' ``` * `string` **ORIGIN** ``` 'origin' ``` * `string` **ORIGIN\_WHEN\_CROSS\_ORIGIN** ``` 'origin-when-cross-origin' ``` * `string` **SAMEORIGIN** ``` 'sameorigin' ``` * `string` **SAME\_ORIGIN** ``` 'same-origin' ``` * `string` **STRICT\_ORIGIN** ``` 'strict-origin' ``` * `string` **STRICT\_ORIGIN\_WHEN\_CROSS\_ORIGIN** ``` 'strict-origin-when-cross-origin' ``` * `string` **UNSAFE\_URL** ``` 'unsafe-url' ``` * `string` **XSS\_BLOCK** ``` 'block' ``` * `string` **XSS\_DISABLED** ``` '0' ``` * `string` **XSS\_ENABLED** ``` '1' ``` * `string` **XSS\_ENABLED\_BLOCK** ``` '1; mode=block' ``` Property Summary ---------------- * [$headers](#%24headers) protected `array<string, mixed>` Security related headers to set Method Summary -------------- * ##### [checkValues()](#checkValues()) protected Convenience method to check if a value is in the list of allowed args * ##### [noOpen()](#noOpen()) public X-Download-Options * ##### [noSniff()](#noSniff()) public X-Content-Type-Options * ##### [process()](#process()) public Serve assets if the path matches one. * ##### [setCrossDomainPolicy()](#setCrossDomainPolicy()) public X-Permitted-Cross-Domain-Policies * ##### [setReferrerPolicy()](#setReferrerPolicy()) public Referrer-Policy * ##### [setXFrameOptions()](#setXFrameOptions()) public X-Frame-Options * ##### [setXssProtection()](#setXssProtection()) public X-XSS-Protection Method Detail ------------- ### checkValues() protected ``` checkValues(string $value, array<string> $allowed): void ``` Convenience method to check if a value is in the list of allowed args #### Parameters `string` $value Value to check `array<string>` $allowed List of allowed values #### Returns `void` #### Throws `InvalidArgumentException` Thrown when a value is invalid. ### noOpen() public ``` noOpen(): $this ``` X-Download-Options Sets the header value for it to 'noopen' #### Returns `$this` #### Links https://msdn.microsoft.com/en-us/library/jj542450(v=vs.85).aspx ### noSniff() public ``` noSniff(): $this ``` X-Content-Type-Options Sets the header value for it to 'nosniff' #### Returns `$this` #### Links https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options ### process() public ``` process(ServerRequestInterface $request, RequestHandlerInterface $handler): Psr\Http\Message\ResponseInterface ``` Serve assets if the path matches one. 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` ### setCrossDomainPolicy() public ``` setCrossDomainPolicy(string $policy = self::ALL): $this ``` X-Permitted-Cross-Domain-Policies #### Parameters `string` $policy optional Policy value. Available Values: 'all', 'none', 'master-only', 'by-content-type', 'by-ftp-filename' #### Returns `$this` #### Links https://www.adobe.com/devnet/adobe-media-server/articles/cross-domain-xml-for-streaming.html ### setReferrerPolicy() public ``` setReferrerPolicy(string $policy = self::SAME_ORIGIN): $this ``` Referrer-Policy #### Parameters `string` $policy optional Policy value. Available Value: 'no-referrer', 'no-referrer-when-downgrade', 'origin', 'origin-when-cross-origin', 'same-origin', 'strict-origin', 'strict-origin-when-cross-origin', 'unsafe-url' #### Returns `$this` #### Links https://w3c.github.io/webappsec-referrer-policy ### setXFrameOptions() public ``` setXFrameOptions(string $option = self::SAMEORIGIN, string|null $url = null): $this ``` X-Frame-Options #### Parameters `string` $option optional Option value. Available Values: 'deny', 'sameorigin', 'allow-from ' `string|null` $url optional URL if mode is `allow-from` #### Returns `$this` #### Links https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options ### setXssProtection() public ``` setXssProtection(string $mode = self::XSS_BLOCK): $this ``` X-XSS-Protection #### Parameters `string` $mode optional Mode value. Available Values: '1', '0', 'block' #### Returns `$this` #### Links https://blogs.msdn.microsoft.com/ieinternals/2011/01/31/controlling-the-xss-filter Property Detail --------------- ### $headers protected Security related headers to set #### Type `array<string, mixed>` cakephp Class FrozenDate Class FrozenDate ================= Extends the Date class provided by Chronos. Adds handy methods and locale-aware formatting helpers This object provides an immutable variant of {@link \Cake\I18n\Date} **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 ``` * `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\Date::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\Date::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` 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 `Date::timeAgoInWords()` and the difference is less than `Date::$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\Date::timeAgoInWords()` and the difference is more than `Cake\I18n\Date::$wordEnd` * [$year](#%24year) public @property-read `int` * [$yearIso](#%24yearIso) public @property-read `int` Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Create a new Date 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+ * ##### [add()](#add()) public Add an Interval to a Date * ##### [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 * ##### [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 Overloaded to ignore time changes. * ##### [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 * ##### [setTime()](#setTime()) public Modify the time on the Date. * ##### [setTimeFromTimeString()](#setTimeFromTimeString()) public Set the time by time string * ##### [setTimestamp()](#setTimestamp()) public Set the timestamp value and get a new object back. * ##### [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 * ##### [stripRelativeTime()](#stripRelativeTime()) protected Remove time components from strtotime relative strings. * ##### [stripTime()](#stripTime()) protected Removes the time components from an input string. * ##### [sub()](#sub()) public Subtract an Interval from a Date. * ##### [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 date 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 = 'now', DateTimeZone|string|null $tz = null) ``` Create a new Date instance. You can specify the timezone for the $time parameter. This timezone will not be used in any future modifications to the Date instance. The `$timezone` parameter is ignored if `$time` is a DateTimeInterface instance. Date instances lack time components, however due to limitations in PHP's internal Datetime object the time will always be set to 00:00:00, and the timezone will always be the server local time. Normalizing the timezone allows for subtraction/addition to have deterministic results. #### Parameters `DateTimeInterface|string|int|null` $time optional Fixed or relative time `DateTimeZone|string|null` $tz optional The timezone in which the date is taken. Ignored if `$time` is a DateTimeInterface 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` ### add() public ``` add(DateInterval $interval): static ``` Add an Interval to a Date Any changes to the time will be ignored and reset to 00:00:00 #### Parameters `DateInterval` $interval The interval to modify this date by. #### Returns `static` ### 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` ### 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 ``` Overloaded to ignore time changes. Changing any aspect of the time will be ignored, and the resulting object will have its time frozen to 00:00:00. #### 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() ### setTime() public ``` setTime(int $hours, int $minutes, int $seconds = null, int $microseconds = null): static ``` Modify the time on the Date. This method ignores all inputs and forces all inputs to 0. #### Parameters `int` $hours The hours to set (ignored) `int` $minutes The minutes to set (ignored) `int` $seconds optional The seconds to set (ignored) `int` $microseconds optional The microseconds to set (ignored) #### Returns `static` ### setTimeFromTimeString() public ``` setTimeFromTimeString(string $time): static ``` Set the time by time string #### Parameters `string` $time Time as string. #### Returns `static` ### setTimestamp() public ``` setTimestamp(int $value): static ``` Set the timestamp value and get a new object back. This method will discard the time aspects of the timestamp and only apply the date portions #### Parameters `int` $value The timestamp value to set. #### Returns `static` ### setTimezone() public ``` setTimezone(DateTimeZone|string $value): static ``` Set the instance's timezone from a string or object Timezones have no effect on calendar dates. #### 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` ### stripRelativeTime() protected ``` stripRelativeTime(string $time): string ``` Remove time components from strtotime relative strings. #### Parameters `string` $time The input expression #### Returns `string` ### stripTime() protected ``` stripTime(DateTimeDateTimeImmutable|string|int|null $time, DateTimeZone|null $tz): string ``` Removes the time components from an input string. Used to ensure constructed objects always lack time. #### Parameters `DateTimeDateTimeImmutable|string|int|null` $time The input time. Integer values will be assumed to be in UTC. The 'now' and '' values will use the current local time. `DateTimeZone|null` $tz The timezone in which the date is taken #### Returns `string` ### sub() public ``` sub(DateInterval $interval): static ``` Subtract an Interval from a Date. Any changes to the time will be ignored and reset to 00:00:00 #### Parameters `DateInterval` $interval The interval to modify this date by. #### 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 date and this object. ### Options: * `from` => another Date object representing the "now" date * `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 "day") * `end` => The end of relative date telling * `relativeString` => The printf compatible string when outputting relative date * `absoluteString` => The printf compatible string when outputting absolute date * `timezone` => The user timezone the timestamp should be formatted in. Relative dates look something like this: * 3 weeks, 4 days ago * 1 day 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() Timezones have no effect on calendar dates. #### 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\MutableDate ``` Create a new mutable instance from current immutable instance. #### Returns `Cake\Chronos\MutableDate` ### 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() Timezones have no effect on calendar dates. #### 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\Date::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\Date::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` ### $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 `Date::timeAgoInWords()` and the difference is less than `Date::$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\Date::timeAgoInWords()` and the difference is more than `Cake\I18n\Date::$wordEnd` #### Type `array<int>|string|int` ### $year public @property-read #### Type `int` ### $yearIso public @property-read #### Type `int`
programming_docs
cakephp Class ControllerFactory Class ControllerFactory ======================== Factory method for building controllers for request. **Namespace:** [Cake\Controller](namespace-cake.controller) Property Summary ---------------- * [$container](#%24container) protected `Cake\Core\ContainerInterface` * [$controller](#%24controller) protected `Cake\Controller\Controller` Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [coerceStringToType()](#coerceStringToType()) protected Coerces string argument to primitive type. * ##### [create()](#create()) public Create a controller for a given request. * ##### [getActionArgs()](#getActionArgs()) protected Get the arguments for the controller action invocation. * ##### [getControllerClass()](#getControllerClass()) public Determine the controller class name based on current request and controller param * ##### [handle()](#handle()) public Invoke the action. * ##### [invoke()](#invoke()) public Invoke a controller's action and wrapping methods. * ##### [missingController()](#missingController()) protected Throws an exception when a controller is missing. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\Core\ContainerInterface $container) ``` Constructor #### Parameters `Cake\Core\ContainerInterface` $container The container to build controllers with. ### coerceStringToType() protected ``` coerceStringToType(string $argument, ReflectionNamedType $type): array|string|float|int|bool|null ``` Coerces string argument to primitive type. #### Parameters `string` $argument Argument to coerce `ReflectionNamedType` $type Parameter type #### Returns `array|string|float|int|bool|null` ### create() public ``` create(Psr\Http\Message\ServerRequestInterface $request): Cake\Controller\Controller ``` Create a controller for a given request. #### Parameters `Psr\Http\Message\ServerRequestInterface` $request The request to build a controller for. #### Returns `Cake\Controller\Controller` #### Throws `Cake\Http\Exception\MissingControllerException` ### getActionArgs() protected ``` getActionArgs(Closure $action, array $passedParams): array ``` Get the arguments for the controller action invocation. #### Parameters `Closure` $action Controller action. `array` $passedParams Params passed by the router. #### Returns `array` ### getControllerClass() public ``` getControllerClass(Cake\Http\ServerRequest $request): string|null ``` Determine the controller class name based on current request and controller param #### Parameters `Cake\Http\ServerRequest` $request The request to build a controller for. #### Returns `string|null` ### handle() public ``` handle(ServerRequestInterface $request): Psr\Http\Message\ResponseInterface ``` Invoke the action. May call other collaborating code to generate the response. #### Parameters `ServerRequestInterface` $request Request instance. #### Returns `Psr\Http\Message\ResponseInterface` ### invoke() public ``` invoke(mixed $controller): Psr\Http\Message\ResponseInterface ``` Invoke a controller's action and wrapping methods. #### Parameters `mixed` $controller The controller to invoke. #### Returns `Psr\Http\Message\ResponseInterface` #### Throws `Cake\Controller\Exception\MissingActionException` If controller action is not found. `UnexpectedValueException` If return value of action method is not null or ResponseInterface instance. ### missingController() protected ``` missingController(Cake\Http\ServerRequest $request): Cake\Http\Exception\MissingControllerException ``` Throws an exception when a controller is missing. #### Parameters `Cake\Http\ServerRequest` $request The request. #### Returns `Cake\Http\Exception\MissingControllerException` Property Detail --------------- ### $container protected #### Type `Cake\Core\ContainerInterface` ### $controller protected #### Type `Cake\Controller\Controller` cakephp Class ConsoleFormatter Class ConsoleFormatter ======================= A Debugger formatter for generating output with ANSI escape codes **Namespace:** [Cake\Error\Debug](namespace-cake.error.debug) Property Summary ---------------- * [$styles](#%24styles) protected `array<string, string>` text colors used in colored output. Method Summary -------------- * ##### [dump()](#dump()) public Convert a tree of NodeInterface objects into a plain text string. * ##### [environmentMatches()](#environmentMatches()) public static Check if the current environment supports ANSI output. * ##### [export()](#export()) protected Convert a tree of NodeInterface objects into a plain text string. * ##### [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 ANSI escape codes. 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` ### environmentMatches() public static ``` environmentMatches(): bool ``` Check if the current environment supports ANSI output. #### Returns `bool` ### export() protected ``` export(Cake\Error\Debug\NodeInterface $var, int $indent): string ``` Convert a tree of NodeInterface objects into a plain text string. #### 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 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 ANSI escape codes. #### Parameters `string` $style The style name to use. `string` $text The text to style. #### Returns `string` Property Detail --------------- ### $styles protected text colors used in colored output. #### Type `array<string, string>` cakephp Class SerializationFailureException Class SerializationFailureException ==================================== Used when a SerializedView class fails to serialize data. **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()} 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 ClientException Class ClientException ====================== Thrown when a request cannot be sent or response cannot be parsed into a PSR-7 response object. **Namespace:** [Cake\Http\Client\Exception](namespace-cake.http.client.exception) cakephp Class SelectLoader Class SelectLoader =================== Implements the logic for loading an association using a SELECT query **Namespace:** [Cake\ORM\Association\Loader](namespace-cake.orm.association.loader) Property Summary ---------------- * [$alias](#%24alias) protected `string` The alias of the association loading the results * [$associationType](#%24associationType) protected `string` The type of the association triggering the load * [$bindingKey](#%24bindingKey) protected `string` The binding key for the source association. * [$finder](#%24finder) protected `callable` A callable that will return a query object used for loading the association results * [$foreignKey](#%24foreignKey) protected `array|string` The foreignKey to the target association * [$sort](#%24sort) protected `string` The sorting options for loading the association * [$sourceAlias](#%24sourceAlias) protected `string` The alias of the source association * [$strategy](#%24strategy) protected `string` The strategy to use for loading, either select or subquery * [$targetAlias](#%24targetAlias) protected `string` The alias of the target association Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Copies the options array to properties in this class. The keys in the array correspond to properties in this class. * ##### [\_addFilteringCondition()](#_addFilteringCondition()) protected Appends any conditions required to load the relevant set of records in the target table query given a filter key and some filtering values. * ##### [\_addFilteringJoin()](#_addFilteringJoin()) protected Appends any conditions required to load the relevant set of records in the target table query given a filter key and some filtering values when the filtering needs to be done using a subquery. * ##### [\_assertFieldsPresent()](#_assertFieldsPresent()) protected Checks that the fetching query either has auto fields on or has the foreignKey fields selected. If the required fields are missing, throws an exception. * ##### [\_buildQuery()](#_buildQuery()) protected Auxiliary function to construct a new Query object to return all the records in the target table that are associated to those specified in $options from the source table * ##### [\_buildResultMap()](#_buildResultMap()) protected Builds an array containing the results from fetchQuery indexed by the foreignKey value corresponding to this association. * ##### [\_buildSubquery()](#_buildSubquery()) protected Builds a query to be used as a condition for filtering records in the target table, it is constructed by cloning the original query that was used to load records in the source table. * ##### [\_createTupleCondition()](#_createTupleCondition()) protected Returns a TupleComparison object that can be used for matching all the fields from $keys with the tuple values in $filter using the provided operator. * ##### [\_defaultOptions()](#_defaultOptions()) protected Returns the default options to use for the eagerLoader * ##### [\_extractFinder()](#_extractFinder()) protected Helper method to infer the requested finder and its options. * ##### [\_linkField()](#_linkField()) protected Generates a string used as a table field that contains the values upon which the filter should be applied * ##### [\_multiKeysInjector()](#_multiKeysInjector()) protected Returns a callable to be used for each row in a query result set for injecting the eager loaded rows when the matching needs to be done with multiple foreign keys * ##### [\_resultInjector()](#_resultInjector()) protected Returns a callable to be used for each row in a query result set for injecting the eager loaded rows * ##### [\_subqueryFields()](#_subqueryFields()) protected Calculate the fields that need to participate in a subquery. * ##### [buildEagerLoader()](#buildEagerLoader()) public Returns a callable that can be used for injecting association results into a given iterator. The options accepted by this method are the same as `Association::eagerLoader()` Method Detail ------------- ### \_\_construct() public ``` __construct(array<string, mixed> $options) ``` Copies the options array to properties in this class. The keys in the array correspond to properties in this class. #### Parameters `array<string, mixed>` $options Properties to be copied to this class ### \_addFilteringCondition() protected ``` _addFilteringCondition(Cake\ORM\Query $query, array<string>|string $key, mixed $filter): Cake\ORM\Query ``` Appends any conditions required to load the relevant set of records in the target table query given a filter key and some filtering values. #### Parameters `Cake\ORM\Query` $query Target table's query `array<string>|string` $key The fields that should be used for filtering `mixed` $filter The value that should be used to match for $key #### Returns `Cake\ORM\Query` ### \_addFilteringJoin() protected ``` _addFilteringJoin(Cake\ORM\Query $query, array<string>|string $key, Cake\ORM\Query $subquery): Cake\ORM\Query ``` Appends any conditions required to load the relevant set of records in the target table query given a filter key and some filtering values when the filtering needs to be done using a subquery. #### Parameters `Cake\ORM\Query` $query Target table's query `array<string>|string` $key the fields that should be used for filtering `Cake\ORM\Query` $subquery The Subquery to use for filtering #### Returns `Cake\ORM\Query` ### \_assertFieldsPresent() protected ``` _assertFieldsPresent(Cake\ORM\Query $fetchQuery, array<string> $key): void ``` Checks that the fetching query either has auto fields on or has the foreignKey fields selected. If the required fields are missing, throws an exception. #### Parameters `Cake\ORM\Query` $fetchQuery The association fetching query `array<string>` $key The foreign key fields to check #### Returns `void` #### Throws `InvalidArgumentException` ### \_buildQuery() protected ``` _buildQuery(array<string, mixed> $options): Cake\ORM\Query ``` Auxiliary function to construct a new Query object to return all the records in the target table that are associated to those specified in $options from the source table #### Parameters `array<string, mixed>` $options options accepted by eagerLoader() #### Returns `Cake\ORM\Query` #### Throws `InvalidArgumentException` When a key is required for associations but not selected. ### \_buildResultMap() protected ``` _buildResultMap(Cake\ORM\Query $fetchQuery, array<string, mixed> $options): array<string, mixed> ``` Builds an array containing the results from fetchQuery indexed by the foreignKey value corresponding to this association. #### Parameters `Cake\ORM\Query` $fetchQuery The query to get results from `array<string, mixed>` $options The options passed to the eager loader #### Returns `array<string, mixed>` ### \_buildSubquery() protected ``` _buildSubquery(Cake\ORM\Query $query): Cake\ORM\Query ``` Builds a query to be used as a condition for filtering records in the target table, it is constructed by cloning the original query that was used to load records in the source table. #### Parameters `Cake\ORM\Query` $query the original query used to load source records #### Returns `Cake\ORM\Query` ### \_createTupleCondition() protected ``` _createTupleCondition(Cake\ORM\Query $query, array<string> $keys, mixed $filter, string $operator): Cake\Database\Expression\TupleComparison ``` Returns a TupleComparison object that can be used for matching all the fields from $keys with the tuple values in $filter using the provided operator. #### Parameters `Cake\ORM\Query` $query Target table's query `array<string>` $keys the fields that should be used for filtering `mixed` $filter the value that should be used to match for $key `string` $operator The operator for comparing the tuples #### Returns `Cake\Database\Expression\TupleComparison` ### \_defaultOptions() protected ``` _defaultOptions(): array<string, mixed> ``` Returns the default options to use for the eagerLoader #### Returns `array<string, mixed>` ### \_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` ### \_linkField() protected ``` _linkField(array<string, mixed> $options): array<string>|string ``` Generates a string used as a table field that contains the values upon which the filter should be applied #### Parameters `array<string, mixed>` $options The options for getting the link field. #### Returns `array<string>|string` #### Throws `RuntimeException` ### \_multiKeysInjector() protected ``` _multiKeysInjector(array<string, mixed> $resultMap, array<string> $sourceKeys, string $nestKey): Closure ``` Returns a callable to be used for each row in a query result set for injecting the eager loaded rows when the matching needs to be done with multiple foreign keys #### Parameters `array<string, mixed>` $resultMap A keyed arrays containing the target table `array<string>` $sourceKeys An array with aliased keys to match `string` $nestKey The key under which results should be nested #### Returns `Closure` ### \_resultInjector() protected ``` _resultInjector(Cake\ORM\Query $fetchQuery, array<string, mixed> $resultMap, array<string, mixed> $options): Closure ``` Returns a callable to be used for each row in a query result set for injecting the eager loaded rows #### Parameters `Cake\ORM\Query` $fetchQuery the Query used to fetch results `array<string, mixed>` $resultMap an array with the foreignKey as keys and the corresponding target table results as value. `array<string, mixed>` $options The options passed to the eagerLoader method #### Returns `Closure` ### \_subqueryFields() protected ``` _subqueryFields(Cake\ORM\Query $query): array<string, array> ``` Calculate the fields that need to participate in a subquery. Normally this includes the binding key columns. If there is a an ORDER BY, those columns are also included as the fields may be calculated or constant values, that need to be present to ensure the correct association data is loaded. #### Parameters `Cake\ORM\Query` $query The query to get fields from. #### Returns `array<string, array>` ### buildEagerLoader() public ``` buildEagerLoader(array<string, mixed> $options): Closure ``` Returns a callable that can be used for injecting association results into a given iterator. The options accepted by this method are the same as `Association::eagerLoader()` #### Parameters `array<string, mixed>` $options Same options as `Association::eagerLoader()` #### Returns `Closure` Property Detail --------------- ### $alias protected The alias of the association loading the results #### Type `string` ### $associationType protected The type of the association triggering the load #### Type `string` ### $bindingKey protected The binding key for the source association. #### Type `string` ### $finder protected A callable that will return a query object used for loading the association results #### Type `callable` ### $foreignKey protected The foreignKey to the target association #### Type `array|string` ### $sort protected The sorting options for loading the association #### Type `string` ### $sourceAlias protected The alias of the source association #### Type `string` ### $strategy protected The strategy to use for loading, either select or subquery #### Type `string` ### $targetAlias protected The alias of the target association #### Type `string`
programming_docs
cakephp Class CacheClearCommand Class CacheClearCommand ======================== CacheClear 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` cakephp Trait TypedResultTrait Trait TypedResultTrait ======================= Implements the TypedResultInterface **Namespace:** [Cake\Database](namespace-cake.database) Property Summary ---------------- * [$\_returnType](#%24_returnType) protected `string` The type name this expression will return when executed Method Summary -------------- * ##### [getReturnType()](#getReturnType()) public Gets the type of the value this object will generate. * ##### [setReturnType()](#setReturnType()) public Sets the type of the value this object will generate. Method Detail ------------- ### getReturnType() public ``` getReturnType(): string ``` Gets the type of the value this object will generate. #### Returns `string` ### setReturnType() public ``` setReturnType(string $type): $this ``` Sets the type of the value this object will generate. #### Parameters `string` $type The name of the type that is to be returned #### Returns `$this` Property Detail --------------- ### $\_returnType protected The type name this expression will return when executed #### Type `string` cakephp Class ArrayNode Class ArrayNode ================ Dump node for Array values. **Namespace:** [Cake\Error\Debug](namespace-cake.error.debug) Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [add()](#add()) public Add an item * ##### [getChildren()](#getChildren()) public Get Item nodes * ##### [getValue()](#getValue()) public Get the contained items Method Detail ------------- ### \_\_construct() public ``` __construct(arrayCake\Error\Debug\ArrayItemNode> $items = []) ``` Constructor #### Parameters `arrayCake\Error\Debug\ArrayItemNode>` $items optional The items for the array ### add() public ``` add(Cake\Error\Debug\ArrayItemNode $node): void ``` Add an item #### Parameters `Cake\Error\Debug\ArrayItemNode` $node The item to add. #### Returns `void` ### getChildren() public ``` getChildren(): arrayCake\Error\Debug\ArrayItemNode> ``` Get Item nodes #### Returns `arrayCake\Error\Debug\ArrayItemNode>` ### getValue() public ``` getValue(): arrayCake\Error\Debug\ArrayItemNode> ``` Get the contained items #### Returns `arrayCake\Error\Debug\ArrayItemNode>` cakephp Class Stream Class Stream ============= Implements sending Cake\Http\Client\Request via php's stream API. This approach and implementation is partly inspired by Aura.Http **Namespace:** [Cake\Http\Client\Adapter](namespace-cake.http.client.adapter) Property Summary ---------------- * [$\_connectionErrors](#%24_connectionErrors) protected `array` Connection error list. * [$\_context](#%24_context) protected `resource|null` Context resource used by the stream API. * [$\_contextOptions](#%24_contextOptions) protected `array<string, mixed>` Array of options/content for the HTTP stream context. * [$\_sslContextOptions](#%24_sslContextOptions) protected `array<string, mixed>` Array of options/content for the SSL stream context. * [$\_stream](#%24_stream) protected `resource|null` The stream resource. Method Summary -------------- * ##### [\_buildContent()](#_buildContent()) protected Builds the request content based on the request object. * ##### [\_buildContext()](#_buildContext()) protected Build the stream context out of the request object. * ##### [\_buildHeaders()](#_buildHeaders()) protected Build the header context for the request. * ##### [\_buildOptions()](#_buildOptions()) protected Build miscellaneous options for the request. * ##### [\_buildResponse()](#_buildResponse()) protected Build a response object * ##### [\_buildSslContext()](#_buildSslContext()) protected Build SSL options for the request. * ##### [\_open()](#_open()) protected Open the socket and handle any connection errors. * ##### [\_send()](#_send()) protected Open the stream and send the request. * ##### [contextOptions()](#contextOptions()) public Get the context options * ##### [createResponses()](#createResponses()) public Create the response list based on the headers & content * ##### [send()](#send()) public Send a request and get a response back. Method Detail ------------- ### \_buildContent() protected ``` _buildContent(Psr\Http\Message\RequestInterface $request, array<string, mixed> $options): void ``` Builds the request content based on the request object. If the $request->body() is a string, it will be used as is. Array data will be processed with {@link \Cake\Http\Client\FormData} #### Parameters `Psr\Http\Message\RequestInterface` $request The request being sent. `array<string, mixed>` $options Array of options to use. #### Returns `void` ### \_buildContext() protected ``` _buildContext(Psr\Http\Message\RequestInterface $request, array<string, mixed> $options): void ``` Build the stream context out of the request object. #### Parameters `Psr\Http\Message\RequestInterface` $request The request to build context from. `array<string, mixed>` $options Additional request options. #### Returns `void` ### \_buildHeaders() protected ``` _buildHeaders(Psr\Http\Message\RequestInterface $request, array<string, mixed> $options): void ``` Build the header context for the request. Creates cookies & headers. #### Parameters `Psr\Http\Message\RequestInterface` $request The request being sent. `array<string, mixed>` $options Array of options to use. #### Returns `void` ### \_buildOptions() protected ``` _buildOptions(Psr\Http\Message\RequestInterface $request, array<string, mixed> $options): void ``` Build miscellaneous options for the request. #### Parameters `Psr\Http\Message\RequestInterface` $request The request being sent. `array<string, mixed>` $options Array of options to use. #### Returns `void` ### \_buildResponse() protected ``` _buildResponse(array $headers, string $body): Cake\Http\Client\Response ``` Build a response object #### Parameters `array` $headers Unparsed headers. `string` $body The response body. #### Returns `Cake\Http\Client\Response` ### \_buildSslContext() protected ``` _buildSslContext(Psr\Http\Message\RequestInterface $request, array<string, mixed> $options): void ``` Build SSL options for the request. #### Parameters `Psr\Http\Message\RequestInterface` $request The request being sent. `array<string, mixed>` $options Array of options to use. #### Returns `void` ### \_open() protected ``` _open(string $url, Psr\Http\Message\RequestInterface $request): void ``` Open the socket and handle any connection errors. #### Parameters `string` $url The url to connect to. `Psr\Http\Message\RequestInterface` $request The request object. #### Returns `void` #### Throws `Psr\Http\Client\RequestExceptionInterface` ### \_send() protected ``` _send(Psr\Http\Message\RequestInterface $request): array ``` Open the stream and send the request. #### Parameters `Psr\Http\Message\RequestInterface` $request The request object. #### Returns `array` #### Throws `Psr\Http\Client\NetworkExceptionInterface` ### contextOptions() public ``` contextOptions(): array<string, mixed> ``` Get the context options Useful for debugging and testing context creation. #### Returns `array<string, mixed>` ### createResponses() public ``` createResponses(array $headers, string $content): arrayCake\Http\Client\Response> ``` Create the response list based on the headers & content Creates one or many response objects based on the number of redirects that occurred. #### Parameters `array` $headers The list of headers from the request(s) `string` $content The response content. #### Returns `arrayCake\Http\Client\Response>` ### send() public ``` send(Psr\Http\Message\RequestInterface $request, array<string, mixed> $options): arrayCake\Http\Client\Response> ``` Send a request and get a response back. #### Parameters `Psr\Http\Message\RequestInterface` $request `array<string, mixed>` $options #### Returns `arrayCake\Http\Client\Response>` Property Detail --------------- ### $\_connectionErrors protected Connection error list. #### Type `array` ### $\_context protected Context resource used by the stream API. #### Type `resource|null` ### $\_contextOptions protected Array of options/content for the HTTP stream context. #### Type `array<string, mixed>` ### $\_sslContextOptions protected Array of options/content for the SSL stream context. #### Type `array<string, mixed>` ### $\_stream protected The stream resource. #### Type `resource|null`
programming_docs
cakephp Interface ConfigEngineInterface Interface ConfigEngineInterface ================================ An interface for creating objects compatible with Configure::load() **Namespace:** [Cake\Core\Configure](namespace-cake.core.configure) Method Summary -------------- * ##### [dump()](#dump()) public Dumps the configure data into the storage key/file of the given `$key`. * ##### [read()](#read()) public Read a configuration file/storage key Method Detail ------------- ### dump() public ``` dump(string $key, array $data): bool ``` Dumps the configure data into the storage key/file of the given `$key`. #### Parameters `string` $key The identifier to write to. `array` $data The data to dump. #### Returns `bool` ### read() public ``` read(string $key): array ``` Read a configuration file/storage key 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 Key to read. #### Returns `array` cakephp Trait AssociationsNormalizerTrait Trait AssociationsNormalizerTrait ================================== Contains methods for parsing the associated tables array that is typically passed to a save operation **Namespace:** [Cake\ORM](namespace-cake.orm) Method Summary -------------- * ##### [\_normalizeAssociations()](#_normalizeAssociations()) protected Returns an array out of the original passed associations list where dot notation is transformed into nested arrays so that they can be parsed by other routines Method Detail ------------- ### \_normalizeAssociations() protected ``` _normalizeAssociations(array|string $associations): array ``` Returns an array out of the original passed associations list where dot notation is transformed into nested arrays so that they can be parsed by other routines #### Parameters `array|string` $associations The array of included associations. #### Returns `array` cakephp Class CacheSession Class CacheSession =================== CacheSession provides method for saving sessions into a Cache engine. Used with Session **Namespace:** [Cake\Http\Session](namespace-cake.http.session) **See:** \Cake\Http\Session for configuration information. Property Summary ---------------- * [$\_options](#%24_options) protected `array<string, mixed>` Options for this session engine Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [close()](#close()) public Method called on close of a database session. * ##### [destroy()](#destroy()) public Method called on the destruction of a cache session. * ##### [gc()](#gc()) public No-op method. Always returns 0 since cache engine don't have garbage collection. * ##### [open()](#open()) public Method called on open of a database session. * ##### [read()](#read()) public Method used to read from a cache session. * ##### [write()](#write()) public Helper function called on write for cache sessions. Method Detail ------------- ### \_\_construct() public ``` __construct(array<string, mixed> $config = []) ``` Constructor. #### Parameters `array<string, mixed>` $config optional The configuration to use for this engine It requires the key 'config' which is the name of the Cache config to use for storing the session #### Throws `InvalidArgumentException` if the 'config' key is not provided ### close() public ``` close(): bool ``` Method called on close of a database session. #### Returns `bool` ### destroy() public ``` destroy(string $id): bool ``` Method called on the destruction of a cache session. #### Parameters `string` $id ID that uniquely identifies session in cache. #### Returns `bool` ### gc() public ``` gc(int $maxlifetime): int|false ``` No-op method. Always returns 0 since cache engine don't have garbage collection. #### Parameters `int` $maxlifetime Sessions that have not updated for the last maxlifetime seconds will be removed. #### Returns `int|false` ### open() public ``` open(string $path, string $name): bool ``` Method called on open of a database session. #### Parameters `string` $path The path where to store/retrieve the session. `string` $name The session name. #### Returns `bool` ### read() public ``` read(string $id): string|false ``` Method used to read from a cache session. #### Parameters `string` $id ID that uniquely identifies session in cache. #### Returns `string|false` ### write() public ``` write(string $id, string $data): bool ``` Helper function called on write for cache sessions. #### Parameters `string` $id ID that uniquely identifies session in cache. `string` $data The data to be saved. #### Returns `bool` Property Detail --------------- ### $\_options protected Options for this session engine #### Type `array<string, mixed>` cakephp Trait CellTrait Trait CellTrait ================ Provides cell() method for usage in Controller and View classes. **Namespace:** [Cake\View](namespace-cake.view) Method Summary -------------- * ##### [\_createCell()](#_createCell()) protected Create and configure the cell instance. * ##### [cell()](#cell()) protected Renders the given cell. Method Detail ------------- ### \_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` ### 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. cakephp Interface BatchCastingInterface Interface BatchCastingInterface ================================ Denotes type objects capable of converting many values from their original database representation to php values. **Namespace:** [Cake\Database\Type](namespace-cake.database.type) Method Summary -------------- * ##### [manyToPHP()](#manyToPHP()) public Returns an array of the values converted to the PHP representation of this type. Method Detail ------------- ### 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 The original array of values containing the fields to be casted `array<string>` $fields The field keys to cast `Cake\Database\DriverInterface` $driver Object from which database preferences and configuration will be extracted. #### Returns `array<string, mixed>` cakephp Interface CommandInterface Interface CommandInterface =========================== Describe the interface between a command and the surrounding console libraries. **Namespace:** [Cake\Console](namespace-cake.console) Constants --------- * `int` **CODE\_ERROR** ``` 1 ``` Default error code * `int` **CODE\_SUCCESS** ``` 0 ``` Default success code Method Summary -------------- * ##### [run()](#run()) public Run the command. * ##### [setName()](#setName()) public Set the name this command uses in the collection. Method Detail ------------- ### run() public ``` run(array $argv, Cake\Console\ConsoleIo $io): int|null ``` Run the command. #### Parameters `array` $argv Arguments from the CLI environment. `Cake\Console\ConsoleIo` $io The console io #### Returns `int|null` ### 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 The name the command uses in the collection. #### Returns `$this` #### Throws `InvalidArgumentException` cakephp Namespace Retry Namespace Retry =============== ### Interfaces * ##### [RetryStrategyInterface](interface-cake.core.retry.retrystrategyinterface) Used to instruct a CommandRetry object on whether a retry for an action should be performed ### Classes * ##### [CommandRetry](class-cake.core.retry.commandretry) Allows any action to be retried in case of an exception. cakephp Class MiddlewareApplication Class MiddlewareApplication ============================ Base class for standalone HTTP applications Provides a base class to inherit from for applications using only the http package. This class defines a fallback handler that renders a simple 404 response. You can overload the `handle` method to provide your own logic to run when no middleware generates a response. **Abstract** **Namespace:** [Cake\Http](namespace-cake.http) Method Summary -------------- * ##### [bootstrap()](#bootstrap()) abstract public Load all the application configuration and bootstrap logic. * ##### [handle()](#handle()) public Generate a 404 response as no middleware handled the request. * ##### [middleware()](#middleware()) abstract public Define the HTTP middleware layers for an application. Method Detail ------------- ### bootstrap() abstract 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): Psr\Http\Message\ResponseInterface ``` Generate a 404 response as no middleware handled the request. May call other collaborating code to generate the response. #### Parameters `ServerRequestInterface` $request The request #### Returns `Psr\Http\Message\ResponseInterface` ### middleware() abstract public ``` middleware(Cake\Http\MiddlewareQueue $middlewareQueue): Cake\Http\MiddlewareQueue ``` Define the HTTP middleware layers for an application. #### Parameters `Cake\Http\MiddlewareQueue` $middlewareQueue #### Returns `Cake\Http\MiddlewareQueue` cakephp Class RouteCollection Class RouteCollection ====================== Contains a collection of routes. Provides an interface for adding/removing routes and parsing/generating URLs with the routes it contains. **Namespace:** [Cake\Routing](namespace-cake.routing) Property Summary ---------------- * [$\_extensions](#%24_extensions) protected `array<string>` Route extensions * [$\_middleware](#%24_middleware) protected `array` A map of middleware names and the related objects. * [$\_middlewareGroups](#%24_middlewareGroups) protected `array` A map of middleware group names and the related middleware names. * [$\_named](#%24_named) protected `arrayCake\Routing\Route\Route>` The hash map of named routes that are in this collection. * [$\_paths](#%24_paths) protected `array<string, arrayCake\Routing\Route\Route>>` Routes indexed by path prefix. * [$\_routeTable](#%24_routeTable) protected `array<string, arrayCake\Routing\Route\Route>>` The routes connected to this collection. Method Summary -------------- * ##### [\_getNames()](#_getNames()) protected Get the set of names from the $url. Accepts both older style array urls, and newer style urls containing '\_name' * ##### [add()](#add()) public Add a route to the collection. * ##### [getExtensions()](#getExtensions()) public Get the extensions that can be handled. * ##### [getMiddleware()](#getMiddleware()) public Get an array of middleware given a list of names * ##### [hasMiddleware()](#hasMiddleware()) public Check if the named middleware has been registered. * ##### [hasMiddlewareGroup()](#hasMiddlewareGroup()) public Check if the named middleware group has been created. * ##### [match()](#match()) public Reverse route or match a $url array with the connected routes. * ##### [middlewareExists()](#middlewareExists()) public Check if the named middleware or middleware group has been registered. * ##### [middlewareGroup()](#middlewareGroup()) public Add middleware to a middleware group * ##### [named()](#named()) public Get the connected named routes. * ##### [parse()](#parse()) public Takes the URL string and iterates the routes until one is able to parse the route. * ##### [parseRequest()](#parseRequest()) public Takes the ServerRequestInterface, iterates the routes until one is able to parse the route. * ##### [registerMiddleware()](#registerMiddleware()) public Register a middleware with the RouteCollection. * ##### [routes()](#routes()) public Get all the connected routes as a flat list. * ##### [setExtensions()](#setExtensions()) public Set the extensions that the route collection can handle. Method Detail ------------- ### \_getNames() protected ``` _getNames(array $url): array<string> ``` Get the set of names from the $url. Accepts both older style array urls, and newer style urls containing '\_name' #### Parameters `array` $url The url to match. #### Returns `array<string>` ### add() public ``` add(Cake\Routing\Route\Route $route, array<string, mixed> $options = []): void ``` Add a route to the collection. #### Parameters `Cake\Routing\Route\Route` $route The route object to add. `array<string, mixed>` $options optional Additional options for the route. Primarily for the `_name` option, which enables named routes. #### Returns `void` ### getExtensions() public ``` getExtensions(): array<string> ``` Get the extensions that can be handled. #### Returns `array<string>` ### getMiddleware() public ``` getMiddleware(array<string> $names): array ``` Get an array of middleware given a list of names #### Parameters `array<string>` $names The names of the middleware or groups to fetch #### Returns `array` #### Throws `RuntimeException` when a requested middleware does not exist. ### hasMiddleware() public ``` hasMiddleware(string $name): bool ``` Check if the named middleware has been registered. #### Parameters `string` $name The name of the middleware to check. #### Returns `bool` ### hasMiddlewareGroup() public ``` hasMiddlewareGroup(string $name): bool ``` Check if the named middleware group has been created. #### Parameters `string` $name The name of the middleware group to check. #### Returns `bool` ### match() public ``` match(array $url, array $context): string ``` Reverse route or match a $url array with the connected routes. Returns either the URL string generated by the route, or throws an exception on failure. #### Parameters `array` $url The URL to match. `array` $context The request context to use. Contains \_base, \_port, \_host, \_scheme and params keys. #### Returns `string` #### Throws `Cake\Routing\Exception\MissingRouteException` When no route could be matched. ### middlewareExists() public ``` middlewareExists(string $name): bool ``` Check if the named middleware or middleware group has been registered. #### Parameters `string` $name The name of the middleware to check. #### Returns `bool` ### middlewareGroup() public ``` middlewareGroup(string $name, array<string> $middlewareNames): $this ``` Add middleware to a middleware group #### Parameters `string` $name Name of the middleware group `array<string>` $middlewareNames Names of the middleware #### Returns `$this` #### Throws `RuntimeException` ### named() public ``` named(): arrayCake\Routing\Route\Route> ``` Get the connected named routes. #### Returns `arrayCake\Routing\Route\Route>` ### parse() public ``` parse(string $url, string $method = ''): array ``` Takes the URL string and iterates the routes until one is able to parse the route. #### Parameters `string` $url URL to parse. `string` $method optional The HTTP method to use. #### Returns `array` #### Throws `Cake\Routing\Exception\MissingRouteException` When a URL has no matching route. ### parseRequest() public ``` parseRequest(Psr\Http\Message\ServerRequestInterface $request): array ``` Takes the ServerRequestInterface, iterates the routes until one is able to parse the route. #### Parameters `Psr\Http\Message\ServerRequestInterface` $request The request to parse route data from. #### Returns `array` #### Throws `Cake\Routing\Exception\MissingRouteException` When a URL has no matching route. ### registerMiddleware() public ``` registerMiddleware(string $name, Psr\Http\Server\MiddlewareInterfaceClosure|string $middleware): $this ``` Register a middleware with the RouteCollection. Once middleware has been registered, it can be applied to the current routing scope or any child scopes that share the same RouteCollection. #### Parameters `string` $name The name of the middleware. Used when applying middleware to a scope. `Psr\Http\Server\MiddlewareInterfaceClosure|string` $middleware The middleware to register. #### Returns `$this` #### Throws `RuntimeException` ### routes() public ``` routes(): arrayCake\Routing\Route\Route> ``` Get all the connected routes as a flat list. #### Returns `arrayCake\Routing\Route\Route>` ### setExtensions() public ``` setExtensions(array<string> $extensions, bool $merge = true): $this ``` Set the extensions that the route collection can handle. #### Parameters `array<string>` $extensions The list of extensions to set. `bool` $merge optional Whether to merge with or override existing extensions. Defaults to `true`. #### Returns `$this` Property Detail --------------- ### $\_extensions protected Route extensions #### Type `array<string>` ### $\_middleware protected A map of middleware names and the related objects. #### Type `array` ### $\_middlewareGroups protected A map of middleware group names and the related middleware names. #### Type `array` ### $\_named protected The hash map of named routes that are in this collection. #### Type `arrayCake\Routing\Route\Route>` ### $\_paths protected Routes indexed by path prefix. #### Type `array<string, arrayCake\Routing\Route\Route>>` ### $\_routeTable protected The routes connected to this collection. #### Type `array<string, arrayCake\Routing\Route\Route>>`
programming_docs
cakephp Class PoFileParser Class PoFileParser =================== Parses file in PO format **Namespace:** [Cake\I18n\Parser](namespace-cake.i18n.parser) Method Summary -------------- * ##### [\_addMessage()](#_addMessage()) protected Saves a translation item to the messages. * ##### [parse()](#parse()) public Parses portable object (PO) format. Method Detail ------------- ### \_addMessage() protected ``` _addMessage(array $messages, array $item): void ``` Saves a translation item to the messages. #### Parameters `array` $messages The messages array being collected from the file `array` $item The current item being inspected #### Returns `void` ### parse() public ``` parse(string $resource): array ``` Parses portable object (PO) format. From <https://www.gnu.org/software/gettext/manual/gettext.html#PO-Files> we should be able to parse files having: white-space translator-comments =================== . extracted-comments ==================== : reference... ============== , flag... ========= | msgid previous-untranslated-string ==================================== msgid untranslated-string msgstr translated-string extra or different lines are: | msgctxt previous-context ========================== | msgid previous-untranslated-string ==================================== msgctxt context | msgid previous-untranslated-string-singular ============================================= | msgid\_plural previous-untranslated-string-plural =================================================== msgid untranslated-string-singular msgid\_plural untranslated-string-plural msgstr[0] translated-string-case-0 ... msgstr[N] translated-string-case-n The definition states: * white-space and comments are optional. * msgid "" that an empty singleline defines a header. This parser sacrifices some features of the reference implementation the differences to that implementation are as follows. * Translator and extracted comments are treated as being the same type. * Message IDs are allowed to have other encodings as just US-ASCII. Items with an empty id are ignored. #### Parameters `string` $resource The file name to parse #### Returns `array` cakephp Class TableLocator Class TableLocator =================== Provides a default registry/factory for Table objects. **Namespace:** [Cake\ORM\Locator](namespace-cake.orm.locator) Property Summary ---------------- * [$\_config](#%24_config) protected `array<string, array|null>` Configuration for aliases. * [$\_fallbacked](#%24_fallbacked) protected `arrayCake\ORM\Table>` Contains a list of Table objects that were created out of the built-in Table class. The list is indexed by table alias * [$allowFallbackClass](#%24allowFallbackClass) protected `bool` Whether fallback class should be used if a table class could not be found. * [$fallbackClassName](#%24fallbackClassName) protected `string` Fallback class to use * [$instances](#%24instances) protected `array<string,Cake\ORM\Table>` Instances that belong to the registry. * [$locations](#%24locations) protected `array<string>` Contains a list of locations where table classes should be looked for. * [$options](#%24options) protected `array<string, array>` Contains a list of options that were passed to get() method. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [\_create()](#_create()) protected Wrapper for creating table instances * ##### [\_getClassName()](#_getClassName()) protected Gets the table class name. * ##### [addLocation()](#addLocation()) public Adds a location where tables should be looked for. * ##### [allowFallbackClass()](#allowFallbackClass()) public Set if fallback class should be used. * ##### [clear()](#clear()) public Clears the registry of configuration and instances. * ##### [createInstance()](#createInstance()) protected Create an instance of a given classname. * ##### [exists()](#exists()) public Check to see if an instance exists in the registry. * ##### [genericInstances()](#genericInstances()) public Returns the list of tables that were created by this registry that could not be instantiated from a specific subclass. This method is useful for debugging common mistakes when setting up associations or created new table classes. * ##### [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. * ##### [setFallbackClassName()](#setFallbackClassName()) public Set fallback class name. Method Detail ------------- ### \_\_construct() public ``` __construct(array<string>|null $locations = null) ``` Constructor. #### Parameters `array<string>|null` $locations optional Locations where tables should be looked for. If none provided, the default `Model\Table` under your app's namespace is used. ### \_create() protected ``` _create(array<string, mixed> $options): Cake\ORM\Table ``` Wrapper for creating table instances #### Parameters `array<string, mixed>` $options The alias to check for. #### Returns `Cake\ORM\Table` ### \_getClassName() protected ``` _getClassName(string $alias, array<string, mixed> $options = []): string|null ``` Gets the table class name. #### Parameters `string` $alias The alias name you want to get. Should be in CamelCase format. `array<string, mixed>` $options optional Table options array. #### Returns `string|null` ### addLocation() public ``` addLocation(string $location): $this ``` Adds a location where tables should be looked for. #### Parameters `string` $location Location to add. #### Returns `$this` ### allowFallbackClass() public ``` allowFallbackClass(bool $allow): $this ``` Set if fallback class should be used. Controls whether a fallback class should be used to create a table instance if a concrete class for alias used in `get()` could not be found. #### Parameters `bool` $allow Flag to enable or disable fallback #### Returns `$this` ### clear() public ``` clear(): void ``` Clears the registry of configuration and instances. #### Returns `void` ### createInstance() protected ``` createInstance(string $alias, array<string, mixed> $options): Cake\Datasource\RepositoryInterface ``` Create an instance of a given classname. #### Parameters `string` $alias `array<string, mixed>` $options #### Returns `Cake\Datasource\RepositoryInterface` ### 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` ### genericInstances() public ``` genericInstances(): arrayCake\ORM\Table> ``` Returns the list of tables that were created by this registry that could not be instantiated from a specific subclass. This method is useful for debugging common mistakes when setting up associations or created new table classes. #### Returns `arrayCake\ORM\Table>` ### get() public ``` get(string $alias, array<string, mixed> $options = []): Cake\ORM\Table ``` Get a table instance from the registry. Tables are only created once until the registry is flushed. This means that aliases must be unique across your application. This is important because table associations are resolved at runtime and cyclic references need to be handled correctly. The options that can be passed are the same as in {@link \Cake\ORM\Table::\_\_construct()}, but the `className` key is also recognized. ### Options * `className` Define the specific class name to use. If undefined, CakePHP will generate the class name based on the alias. For example 'Users' would result in `App\Model\Table\UsersTable` being used. If this class does not exist, then the default `Cake\ORM\Table` class will be used. By setting the `className` option you can define the specific class to use. The className option supports plugin short class references {@link \Cake\Core\App::shortName()}. * `table` Define the table name to use. If undefined, this option will default to the underscored version of the alias name. * `connection` Inject the specific connection object to use. If this option and `connectionName` are undefined, The table class' `defaultConnectionName()` method will be invoked to fetch the connection name. * `connectionName` Define the connection name to use. The named connection will be fetched from {@link \Cake\Datasource\ConnectionManager}. *Note* If your `$alias` uses plugin syntax only the name part will be used as key in the registry. This means that if two plugins, or a plugin and app provide the same alias, the registry will only store the first instance. #### Parameters `string` $alias The alias name you want to get. Should be in CamelCase format. `array<string, mixed>` $options optional The options you want to build the table with. If a table has already been loaded the options will be ignored. #### Returns `Cake\ORM\Table` #### Throws `RuntimeException` When you try to configure an alias that already exists. ### 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 #### Returns `array` ### 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\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 `array<string, mixed>|null` $options optional #### Returns `$this` ### setFallbackClassName() public ``` setFallbackClassName(string $className): $this ``` Set fallback class name. The class that should be used to create a table instance if a concrete class for alias used in `get()` could not be found. Defaults to `Cake\ORM\Table`. #### Parameters `string` $className Fallback class name #### Returns `$this` Property Detail --------------- ### $\_config protected Configuration for aliases. #### Type `array<string, array|null>` ### $\_fallbacked protected Contains a list of Table objects that were created out of the built-in Table class. The list is indexed by table alias #### Type `arrayCake\ORM\Table>` ### $allowFallbackClass protected Whether fallback class should be used if a table class could not be found. #### Type `bool` ### $fallbackClassName protected Fallback class to use #### Type `string` ### $instances protected Instances that belong to the registry. #### Type `array<string,Cake\ORM\Table>` ### $locations protected Contains a list of locations where table classes should be looked for. #### Type `array<string>` ### $options protected Contains a list of options that were passed to get() method. #### Type `array<string, array>` cakephp Namespace Cache Namespace Cache =============== ### Namespaces * [Cake\Cache\Engine](namespace-cake.cache.engine) ### Interfaces * ##### [CacheEngineInterface](interface-cake.cache.cacheengineinterface) Interface for cache engines that defines methods outside of the PSR16 interface that are used by `Cache`. ### Classes * ##### [Cache](class-cake.cache.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. * ##### [CacheEngine](class-cake.cache.cacheengine) Storage engine for CakePHP caching * ##### [CacheRegistry](class-cake.cache.cacheregistry) An object registry for cache engines. * ##### [InvalidArgumentException](class-cake.cache.invalidargumentexception) Exception raised when cache keys are invalid. cakephp Class FixtureHelper Class FixtureHelper ==================== Helper for managing fixtures. **Namespace:** [Cake\TestSuite\Fixture](namespace-cake.testsuite.fixture) Method Summary -------------- * ##### [getForeignReferences()](#getForeignReferences()) protected Gets array of foreign references for fixtures table. * ##### [insert()](#insert()) public Inserts fixture data. * ##### [insertConnection()](#insertConnection()) protected Inserts all fixtures for a connection and provides friendly errors for bad data. * ##### [loadFixtures()](#loadFixtures()) public Finds fixtures from their TestCase names such as 'core.Articles'. * ##### [runPerConnection()](#runPerConnection()) public Runs the callback once per connection. * ##### [sortByConstraint()](#sortByConstraint()) protected Sort fixtures with foreign constraints last if possible, otherwise returns null. * ##### [truncate()](#truncate()) public Truncates fixture tables. * ##### [truncateConnection()](#truncateConnection()) protected Truncates all fixtures for a connection and provides friendly errors for bad data. Method Detail ------------- ### getForeignReferences() protected ``` getForeignReferences(Cake\Database\Connection $connection, Cake\Datasource\FixtureInterface $fixture): array<string> ``` Gets array of foreign references for fixtures table. #### Parameters `Cake\Database\Connection` $connection Database connection `Cake\Datasource\FixtureInterface` $fixture Database fixture #### Returns `array<string>` ### insert() public ``` insert(arrayCake\Datasource\FixtureInterface> $fixtures): void ``` Inserts fixture data. #### Parameters `arrayCake\Datasource\FixtureInterface>` $fixtures Test fixtures #### Returns `void` ### insertConnection() protected ``` insertConnection(Cake\Datasource\ConnectionInterface $connection, arrayCake\Datasource\FixtureInterface> $fixtures): void ``` Inserts all fixtures for a connection and provides friendly errors for bad data. #### Parameters `Cake\Datasource\ConnectionInterface` $connection Fixture connection `arrayCake\Datasource\FixtureInterface>` $fixtures Connection fixtures #### Returns `void` ### loadFixtures() public ``` loadFixtures(array<string> $fixtureNames): arrayCake\Datasource\FixtureInterface> ``` Finds fixtures from their TestCase names such as 'core.Articles'. #### Parameters `array<string>` $fixtureNames Fixture names from test case #### Returns `arrayCake\Datasource\FixtureInterface>` ### runPerConnection() public ``` runPerConnection(Closure $callback, arrayCake\Datasource\FixtureInterface> $fixtures): void ``` Runs the callback once per connection. The callback signature: ``` function callback(ConnectionInterface $connection, array $fixtures) ``` #### Parameters `Closure` $callback Callback run per connection `arrayCake\Datasource\FixtureInterface>` $fixtures Test fixtures #### Returns `void` ### sortByConstraint() protected ``` sortByConstraint(Cake\Database\Connection $connection, arrayCake\Datasource\FixtureInterface> $fixtures): array|null ``` Sort fixtures with foreign constraints last if possible, otherwise returns null. #### Parameters `Cake\Database\Connection` $connection Database connection `arrayCake\Datasource\FixtureInterface>` $fixtures Database fixtures #### Returns `array|null` ### truncate() public ``` truncate(arrayCake\Datasource\FixtureInterface> $fixtures): void ``` Truncates fixture tables. #### Parameters `arrayCake\Datasource\FixtureInterface>` $fixtures Test fixtures #### Returns `void` ### truncateConnection() protected ``` truncateConnection(Cake\Datasource\ConnectionInterface $connection, arrayCake\Datasource\FixtureInterface> $fixtures): void ``` Truncates all fixtures for a connection and provides friendly errors for bad data. #### Parameters `Cake\Datasource\ConnectionInterface` $connection Fixture connection `arrayCake\Datasource\FixtureInterface>` $fixtures Connection fixtures #### Returns `void` cakephp Class SchemacacheBuildCommand Class SchemacacheBuildCommand ============================== Provides CLI tool for updating schema cache. **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`
programming_docs
cakephp Class EventFiredWith Class EventFiredWith ===================== EventFiredWith constraint **Namespace:** [Cake\TestSuite\Constraint](namespace-cake.testsuite.constraint) Property Summary ---------------- * [$\_dataKey](#%24_dataKey) protected `string` Event data key * [$\_dataValue](#%24_dataValue) protected `mixed` Event data value * [$\_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, string $dataKey, mixed $dataValue) ``` Constructor #### Parameters `Cake\Event\EventManager` $eventManager Event manager to check `string` $dataKey Data key `mixed` $dataValue Data value ### 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` #### Throws `PHPUnit\Framework\AssertionFailedError` ### 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 --------------- ### $\_dataKey protected Event data key #### Type `string` ### $\_dataValue protected Event data value #### Type `mixed` ### $\_eventManager protected Array of fired events #### Type `Cake\Event\EventManager` cakephp Interface EventInterface Interface 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. **Namespace:** [Cake\Event](namespace-cake.event) Method Summary -------------- * ##### [getData()](#getData()) public Accesses the event data/payload. * ##### [getName()](#getName()) public Returns the name of this event. This is usually used as the event identifier. * ##### [getResult()](#getResult()) public The result value of the event listeners. * ##### [getSubject()](#getSubject()) public Returns the subject of this event. * ##### [isStopped()](#isStopped()) public Checks if the event is stopped. * ##### [setData()](#setData()) public Assigns a value to the data/payload of this event. * ##### [setResult()](#setResult()) public Listeners can attach a result value to the event. * ##### [stopPropagation()](#stopPropagation()) public Stops the event from being used anymore. Method Detail ------------- ### getData() public ``` getData(string|null $key = null): mixed|array|null ``` Accesses the event data/payload. #### Parameters `string|null` $key optional The data payload element to return, or null to return all data. #### Returns `mixed|array|null` ### getName() public ``` getName(): string ``` Returns the name of this event. This is usually used as the event identifier. #### Returns `string` ### getResult() public ``` getResult(): mixed ``` The result value of the event listeners. #### Returns `mixed` ### getSubject() public ``` getSubject(): object ``` Returns the subject of this event. #### Returns `object` ### isStopped() public ``` isStopped(): bool ``` Checks if the event is stopped. #### Returns `bool` ### setData() public ``` setData(array|string $key, mixed $value = null): $this ``` Assigns a value to the data/payload of this event. #### Parameters `array|string` $key An array will replace all payload data, and a key will set just that array item. `mixed` $value optional The value to set. #### Returns `$this` ### setResult() public ``` setResult(mixed $value = null): $this ``` Listeners can attach a result value to the event. #### Parameters `mixed` $value optional The value to set. #### Returns `$this` ### stopPropagation() public ``` stopPropagation(): void ``` Stops the event from being used anymore. #### Returns `void` cakephp Class HeaderEquals Class HeaderEquals =================== HeaderEquals **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 StringExpression Class StringExpression ======================= String expression with collation. **Namespace:** [Cake\Database\Expression](namespace-cake.database.expression) Property Summary ---------------- * [$collation](#%24collation) protected `string` * [$string](#%24string) protected `string` Method Summary -------------- * ##### [\_\_construct()](#__construct()) public * ##### [getCollation()](#getCollation()) public Returns the string collation. * ##### [setCollation()](#setCollation()) public Sets the string collation. * ##### [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 $string, string $collation) ``` #### Parameters `string` $string String value `string` $collation String collation ### getCollation() public ``` getCollation(): string ``` Returns the string collation. #### Returns `string` ### setCollation() public ``` setCollation(string $collation): void ``` Sets the string collation. #### Parameters `string` $collation String collation #### 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 --------------- ### $collation protected #### Type `string` ### $string protected #### Type `string` cakephp Class ExistsIn Class ExistsIn =============== Checks that the value provided in a field exists as the primary key of another table. **Namespace:** [Cake\ORM\Rule](namespace-cake.orm.rule) Property Summary ---------------- * [$\_fields](#%24_fields) protected `array<string>` The list of fields to check * [$\_options](#%24_options) protected `array<string, mixed>` Options for the constructor * [$\_repository](#%24_repository) protected `Cake\ORM\TableCake\ORM\Association|string` The repository where the field will be looked for Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [\_\_invoke()](#__invoke()) public Performs the existence check * ##### [\_fieldsAreNull()](#_fieldsAreNull()) protected Checks whether the given entity fields are nullable and null. Method Detail ------------- ### \_\_construct() public ``` __construct(array<string>|string $fields, Cake\ORM\TableCake\ORM\Association|string $repository, array<string, mixed> $options = []) ``` Constructor. Available option for $options is 'allowNullableNulls' flag. Set to true to accept composite foreign keys where one or more nullable columns are null. #### Parameters `array<string>|string` $fields The field or fields to check existence as primary key. `Cake\ORM\TableCake\ORM\Association|string` $repository The repository where the field will be looked for, or the association name for the repository. `array<string, mixed>` $options optional The options that modify the rule's behavior. Options 'allowNullableNulls' will make the rule pass if given foreign keys are set to `null`. Notice: allowNullableNulls cannot pass by database columns set to `NOT NULL`. ### \_\_invoke() public ``` __invoke(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options): bool ``` Performs the existence check #### Parameters `Cake\Datasource\EntityInterface` $entity The entity from where to extract the fields `array<string, mixed>` $options Options passed to the check, where the `repository` key is required. #### Returns `bool` #### Throws `RuntimeException` When the rule refers to an undefined association. ### \_fieldsAreNull() protected ``` _fieldsAreNull(Cake\Datasource\EntityInterface $entity, Cake\ORM\Table $source): bool ``` Checks whether the given entity fields are nullable and null. #### Parameters `Cake\Datasource\EntityInterface` $entity The entity to check. `Cake\ORM\Table` $source The table to use schema from. #### Returns `bool` Property Detail --------------- ### $\_fields protected The list of fields to check #### Type `array<string>` ### $\_options protected Options for the constructor #### Type `array<string, mixed>` ### $\_repository protected The repository where the field will be looked for #### Type `Cake\ORM\TableCake\ORM\Association|string` cakephp Namespace Statement Namespace Statement =================== ### Classes * ##### [BufferedStatement](class-cake.database.statement.bufferedstatement) A statement decorator that implements buffered results. * ##### [CallbackStatement](class-cake.database.statement.callbackstatement) Wraps a statement in a callback that allows row results to be modified when being fetched. * ##### [MysqlStatement](class-cake.database.statement.mysqlstatement) Statement class meant to be used by a MySQL PDO driver * ##### [PDOStatement](class-cake.database.statement.pdostatement) Decorator for \PDOStatement class mainly used for converting human readable fetch modes into PDO constants. * ##### [SqliteStatement](class-cake.database.statement.sqlitestatement) Statement class meant to be used by an Sqlite driver * ##### [SqlserverStatement](class-cake.database.statement.sqlserverstatement) Statement class meant to be used by an Sqlserver driver * ##### [StatementDecorator](class-cake.database.statement.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. ### Traits * ##### [BufferResultsTrait](trait-cake.database.statement.bufferresultstrait) Contains a setter for marking a Statement as buffered cakephp Class ErrorTrap Class ErrorTrap ================ Entry point to CakePHP's error handling. Using the `register()` method you can attach an ErrorTrap to PHP's default error handler. When errors are trapped, errors are logged (if logging is enabled). Then the `Error.beforeRender` event is triggered. Finally, errors are 'rendered' using the defined renderer. If no error renderer is defined in configuration one of the default implementations will be chosen based on the PHP SAPI. **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 are defined in 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. 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. * ##### [chooseErrorRenderer()](#chooseErrorRenderer()) protected Choose an error 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. * ##### [handleError()](#handleError()) public Handle an error from PHP set\_error\_handler * ##### [logError()](#logError()) protected Logging helper method. * ##### [logger()](#logger()) public Get an instance of the logger. * ##### [register()](#register()) public Attach this ErrorTrap to PHP's default error 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. 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 ### chooseErrorRenderer() protected ``` chooseErrorRenderer(): class-stringCake\Error\ErrorRendererInterface> ``` Choose an error renderer based on config or the SAPI #### Returns `class-stringCake\Error\ErrorRendererInterface>` ### 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` ### handleError() public ``` handleError(int $code, string $description, string|null $file = null, int|null $line = null): bool ``` Handle an error from PHP set\_error\_handler Will use the configured renderer to generate output and output it. This method will dispatch the `Error.beforeRender` event which can be listened to on the global event manager. #### 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 #### Returns `bool` ### logError() protected ``` logError(Cake\Error\PhpError $error): void ``` Logging helper method. #### Parameters `Cake\Error\PhpError` $error The error object 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 ErrorTrap to PHP's default error handler. This will replace the existing error handler, and the previous error handler will be discarded. This method will also set the global error level via error\_reporting(). #### Returns `void` ### renderer() public ``` renderer(): Cake\Error\ErrorRendererInterface ``` Get an instance of the renderer. #### Returns `Cake\Error\ErrorRendererInterface` ### 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` 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 are defined in config/app.php * `errorLevel` - int - The level of errors you are interested in capturing. * `errorRenderer` - string - The class name of render errors with. Defaults to choosing between Html and Console based on the SAPI. * `log` - boolean - Whether or not you want errors logged. * `logger` - string - The class name of the error logger to use. * `trace` - boolean - Whether or not backtraces should be included in logged errors. #### 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` cakephp Trait LogTrait Trait LogTrait =============== A trait providing an object short-cut method to logging. **Namespace:** [Cake\Log](namespace-cake.log) Method Summary -------------- * ##### [log()](#log()) public Convenience method to write a message to Log. See Log::write() for more information on writing to logs. Method Detail ------------- ### 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` cakephp Class CommandFactory Class CommandFactory ===================== This is a factory for creating Command and Shell instances. This factory can be replaced or extended if you need to customize building your command and shell objects. **Namespace:** [Cake\Console](namespace-cake.console) Property Summary ---------------- * [$container](#%24container) protected `Cake\Core\ContainerInterface|null` Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [create()](#create()) public The factory method for creating Command and Shell instances. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\Core\ContainerInterface|null $container = null) ``` Constructor #### Parameters `Cake\Core\ContainerInterface|null` $container optional The container to use if available. ### create() public ``` create(string $className): Cake\Console\ShellCake\Console\CommandInterface ``` The factory method for creating Command and Shell instances. #### Parameters `string` $className #### Returns `Cake\Console\ShellCake\Console\CommandInterface` Property Detail --------------- ### $container protected #### Type `Cake\Core\ContainerInterface|null` cakephp Class WeakPasswordHasher Class WeakPasswordHasher ========================= Password hashing class that use weak hashing algorithms. This class is intended only to be used with legacy databases where passwords have not been migrated to a stronger algorithm yet. **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 ### \_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 #### 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 for this object. These are merged with user-provided config when the object is used. #### Type `array<string, mixed>`
programming_docs
cakephp Trait ContainerStubTrait Trait ContainerStubTrait ========================= A set of methods used for defining container services in test cases. This trait leverages the `Application.buildContainer` event to inject the mocked services into the container that the application uses. **Namespace:** [Cake\Core\TestSuite](namespace-cake.core.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. Method Summary -------------- * ##### [cleanupContainer()](#cleanupContainer()) public Clears any mocks that were defined and cleans up application class configuration. * ##### [configApplication()](#configApplication()) public Configure the application class to use in integration tests. * ##### [createApp()](#createApp()) protected Create an application instance. * ##### [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. Method Detail ------------- ### cleanupContainer() public ``` cleanupContainer(): void ``` Clears any mocks that were defined and cleans up application class configuration. #### 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` ### createApp() protected ``` createApp(): Cake\Core\HttpApplicationInterfaceCake\Core\ConsoleApplicationInterface ``` Create an application instance. Uses the configuration set in `configApplication()`. #### Returns `Cake\Core\HttpApplicationInterfaceCake\Core\ConsoleApplicationInterface` ### 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` Property Detail --------------- ### $\_appArgs protected The customized application constructor arguments. #### Type `array|null` ### $\_appClass protected The customized application class name. #### Type `string|null` cakephp Class Command Class Command ============== Base class for commands using the full stack CakePHP Framework. Includes traits that integrate logging and ORM models to console commands. **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()) protected 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() protected ``` 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` ### 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|void ``` 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|void` ### 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 Interface LocatorInterface Interface LocatorInterface =========================== Registries for repository objects should implement this interface. **Namespace:** [Cake\Datasource\Locator](namespace-cake.datasource.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 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` ### 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\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 The alias to remove. #### Returns `void` ### set() public ``` set(string $alias, Cake\Datasource\RepositoryInterface $repository): Cake\Datasource\RepositoryInterface ``` Set a repository instance. #### Parameters `string` $alias The alias to set. `Cake\Datasource\RepositoryInterface` $repository The repository to set. #### Returns `Cake\Datasource\RepositoryInterface` cakephp Namespace Exception Namespace Exception =================== ### Classes * ##### [PageOutOfBoundsException](class-cake.datasource.paging.exception.pageoutofboundsexception) Exception raised when requested page number does not exist. cakephp Class FactoryLocator Class FactoryLocator ===================== Class FactoryLocator **Namespace:** [Cake\Datasource](namespace-cake.datasource) Property Summary ---------------- * [$\_modelFactories](#%24_modelFactories) protected static `array<callableCake\Datasource\Locator\LocatorInterface>` A list of model factory functions. Method Summary -------------- * ##### [add()](#add()) public static Register a callable to generate repositories of a given type. * ##### [drop()](#drop()) public static Drop a model factory. * ##### [get()](#get()) public static Get the factory for the specified repository type. Method Detail ------------- ### add() public static ``` add(string $type, Cake\Datasource\Locator\LocatorInterface|callable $factory): void ``` Register a 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` ### drop() public static ``` drop(string $type): void ``` Drop a model factory. #### Parameters `string` $type The name of the repository type to drop the factory for. #### Returns `void` ### get() public static ``` get(string $type): Cake\Datasource\Locator\LocatorInterface|callable ``` Get the factory for the specified repository type. #### Parameters `string` $type The repository type to get the factory for. #### Returns `Cake\Datasource\Locator\LocatorInterface|callable` #### Throws `InvalidArgumentException` If the specified repository type has no factory. Property Detail --------------- ### $\_modelFactories protected static A list of model factory functions. #### Type `array<callableCake\Datasource\Locator\LocatorInterface>`
programming_docs
cakephp Class InsertIterator Class 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. **Namespace:** [Cake\Collection\Iterator](namespace-cake.collection.iterator) Property Summary ---------------- * [$\_path](#%24_path) protected `array<string>` An array containing each of the properties to be traversed to reach the point where the values should be inserted. * [$\_target](#%24_target) protected `string` The property name to which values will be assigned * [$\_validValues](#%24_validValues) protected `bool` Holds whether the values collection is still valid. (has more records) * [$\_values](#%24_values) protected `Cake\Collection\Collection` The collection from which to extract the values to be inserted Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructs a new collection that will dynamically add properties to it out of the values found in $values. * ##### [\_\_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 current element in the target collection after inserting the value from the source collection into the specified path. * ##### [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. * ##### [next()](#next()) public Advances the cursor to the next record * ##### [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 Resets the collection pointer. * ##### [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 $into, string $path, iterable $values) ``` Constructs a new collection that will dynamically add properties to it out of the values found in $values. #### Parameters `iterable` $into The target collection to which the values will be inserted at the specified path. `string` $path A dot separated list of properties that need to be traversed to insert the value into the target collection. `iterable` $values The source collection from which the values will be inserted at the specified path. ### \_\_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 current element in the target collection after inserting the value from the source collection into the specified path. #### 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` ### next() public ``` next(): void ``` Advances the cursor to the next record #### 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 ``` Resets the collection pointer. #### 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 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 --------------- ### $\_path protected An array containing each of the properties to be traversed to reach the point where the values should be inserted. #### Type `array<string>` ### $\_target protected The property name to which values will be assigned #### Type `string` ### $\_validValues protected Holds whether the values collection is still valid. (has more records) #### Type `bool` ### $\_values protected The collection from which to extract the values to be inserted #### Type `Cake\Collection\Collection`
programming_docs
cakephp Class Helper Class Helper ============= Base class for Helpers. Console Helpers allow you to package up reusable blocks of Console output logic. For example creating tables, progress bars or ascii art. **Abstract** **Namespace:** [Cake\Console](namespace-cake.console) 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. * ##### [\_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. * ##### [getConfig()](#getConfig()) public Returns the config. * ##### [getConfigOrFail()](#getConfigOrFail()) public Returns the config for this specific key. * ##### [output()](#output()) abstract public This method should output content using `$this->_io`. * ##### [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. ### \_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` ### 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() abstract public ``` output(array $args): void ``` This method should output content using `$this->_io`. #### Parameters `array` $args The arguments for the 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 --------------- ### $\_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` cakephp Class BufferedStatement Class BufferedStatement ======================== A statement decorator that implements buffered results. This statement decorator will save fetched results in memory, allowing the iterator to be rewound and reused. **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 ---------------- * [$\_allFetched](#%24_allFetched) protected `bool` If true, all rows were fetched * [$\_driver](#%24_driver) protected `Cake\Database\DriverInterface` The driver for the statement * [$\_hasExecuted](#%24_hasExecuted) protected `bool` Whether this statement has already been executed * [$buffer](#%24buffer) protected `array<int, array>` The in-memory cache containing results from previous iterators * [$index](#%24index) protected `int` The current iterator index. * [$queryString](#%24queryString) public @property-read `string` * [$statement](#%24statement) protected `Cake\Database\StatementInterface` The decorated statement Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [\_\_get()](#__get()) public Magic getter to return $queryString as read-only. * ##### [\_reset()](#_reset()) protected Reset all properties * ##### [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. * ##### [current()](#current()) public Returns the current record in the iterator * ##### [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 * ##### [fetchColumn()](#fetchColumn()) public Returns the value of the result at position. * ##### [getInnerStatement()](#getInnerStatement()) public Get the wrapped statement * ##### [key()](#key()) public Returns the current key in the iterator * ##### [lastInsertId()](#lastInsertId()) public Returns the latest primary inserted using this statement * ##### [matchTypes()](#matchTypes()) public Matches columns to corresponding types * ##### [next()](#next()) public Advances the iterator pointer to the next element * ##### [rewind()](#rewind()) public Rewinds the collection * ##### [rowCount()](#rowCount()) public Returns the number of rows affected by this SQL statement * ##### [valid()](#valid()) public Returns whether the iterator has more elements 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` ### \_reset() protected ``` _reset(): void ``` Reset all properties #### Returns `void` ### bind() public ``` bind(array $params, array $types): void ``` Binds a set of values to statement object with corresponding type #### Parameters `array` $params `array` $types #### 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 `mixed` $value `string|int|null` $type optional #### 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` ### current() public ``` current(): mixed ``` Returns the current record in the iterator #### Returns `mixed` ### 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 #### Returns `bool` ### fetch() public ``` fetch(string|int $type = self::FETCH_TYPE_NUM): array|false ``` 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 The type to fetch. #### Returns `array|false` ### 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 `array` ### fetchColumn() public ``` fetchColumn(int $position): mixed ``` Returns the value of the result at position. #### Parameters `int` $position #### Returns `mixed` ### getInnerStatement() public ``` getInnerStatement(): Cake\Database\StatementInterface ``` Get the wrapped statement #### Returns `Cake\Database\StatementInterface` ### key() public ``` key(): mixed ``` Returns the current key in the iterator #### 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 `string|null` $column optional #### 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` ### next() public ``` next(): void ``` Advances the iterator pointer to the next element #### Returns `void` ### rewind() public ``` rewind(): void ``` Rewinds the collection #### Returns `void` ### 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` ### valid() public ``` valid(): bool ``` Returns whether the iterator has more elements #### Returns `bool` Property Detail --------------- ### $\_allFetched protected If true, all rows were fetched #### Type `bool` ### $\_driver protected The driver for the statement #### Type `Cake\Database\DriverInterface` ### $\_hasExecuted protected Whether this statement has already been executed #### Type `bool` ### $buffer protected The in-memory cache containing results from previous iterators #### Type `array<int, array>` ### $index protected The current iterator index. #### Type `int` ### $queryString public @property-read #### Type `string` ### $statement protected The decorated statement #### Type `Cake\Database\StatementInterface` cakephp Class EavStrategy Class EavStrategy ================== This class 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` finder of `TranslateBehavior` that is exposed to the 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. * ##### [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. * ##### [findExistingTranslations()](#findExistingTranslations()) protected Returns the ids found for each of the condition arrays passed for the translations table. Each records is indexed by the corresponding position to the conditions array. * ##### [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. * ##### [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 Creates the associations between the bound table and every field passed to this method. * ##### [translationField()](#translationField()) public Returns a fully aliased field name for translated 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 The table this strategy is attached to. `array<string, mixed>` $config optional The config for this strategy. ### \_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 ### 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 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` ### 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() ### findExistingTranslations() protected ``` findExistingTranslations(array $ruleSet): array ``` Returns the ids found for each of the condition arrays passed for the translations table. Each records is indexed by the corresponding position to the conditions array. #### Parameters `array` $ruleSet An array of array of conditions to be used for finding each #### Returns `array` ### 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` ### 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 ``` Creates the associations between the bound table and every field passed to this method. Additionally it creates a `i18n` HasMany association that will be used for fetching all translations for each record in the bound table. #### Returns `void` ### 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` ### 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 Namespace Helper Namespace Helper ================ ### Classes * ##### [BreadcrumbsHelper](class-cake.view.helper.breadcrumbshelper) BreadcrumbsHelper to register and display a breadcrumb trail for your views * ##### [FlashHelper](class-cake.view.helper.flashhelper) FlashHelper class to render flash messages. * ##### [FormHelper](class-cake.view.helper.formhelper) Form helper library. * ##### [HtmlHelper](class-cake.view.helper.htmlhelper) Html Helper class for easy use of HTML widgets. * ##### [NumberHelper](class-cake.view.helper.numberhelper) Number helper library. * ##### [PaginatorHelper](class-cake.view.helper.paginatorhelper) Pagination Helper class for easy generation of pagination links. * ##### [TextHelper](class-cake.view.helper.texthelper) Text helper library. * ##### [TimeHelper](class-cake.view.helper.timehelper) Time Helper class for easy use of time data. * ##### [UrlHelper](class-cake.view.helper.urlhelper) UrlHelper class for generating URLs. ### Traits * ##### [IdGeneratorTrait](trait-cake.view.helper.idgeneratortrait) A trait that provides id generating methods to be used in various widget classes. cakephp Class TestCase Class TestCase =============== Cake TestCase class **Abstract** **Namespace:** [Cake\TestSuite](namespace-cake.testsuite) Property Summary ---------------- * [$\_configure](#%24_configure) protected `array` Configure values to restore at end of test. * [$\_tableLocator](#%24_tableLocator) protected `Cake\ORM\Locator\LocatorInterface|null` Table locator instance * [$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 * ##### [\_assertAttributes()](#_assertAttributes()) protected Check the attributes as part of an assertTags() check. * ##### [\_getTableClassName()](#_getTableClassName()) protected Gets the class name for the table. * ##### [\_normalizePath()](#_normalizePath()) protected Normalize a path for comparison. * ##### [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. * ##### [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. * ##### [assertFinite()](#assertFinite()) public static Asserts that a variable is finite. * ##### [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. * ##### [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. * ##### [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. * ##### [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. * ##### [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 * ##### [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. * ##### [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. * ##### [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 * ##### [clearPlugins()](#clearPlugins()) public Clear all plugins from the global plugin collection. * ##### [containsEqual()](#containsEqual()) public static * ##### [containsIdentical()](#containsIdentical()) public static * ##### [containsOnly()](#containsOnly()) public static * ##### [containsOnlyInstancesOf()](#containsOnlyInstancesOf()) public static * ##### [count()](#count()) public * ##### [countOf()](#countOf()) public static * ##### [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 * ##### [deprecated()](#deprecated()) public Helper method for check deprecation methods * ##### [directoryExists()](#directoryExists()) public static * ##### [doesNotPerformAssertions()](#doesNotPerformAssertions()) public * ##### [doubledTypes()](#doubledTypes()) public * ##### [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 * ##### [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 * ##### [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 * ##### [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 * ##### [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 * ##### [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. * ##### [prophesize()](#prophesize()) protected * ##### [provides()](#provides()) public Returns the normalized test name as class::method. * ##### [recordDoubledType()](#recordDoubledType()) protected * ##### [registerComparator()](#registerComparator()) public * ##### [registerMockObject()](#registerMockObject()) public * ##### [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. * ##### [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 * ##### [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. * ##### [usesDataProvider()](#usesDataProvider()) public * ##### [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 ### \_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` ### \_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` ### \_normalizePath() protected ``` _normalizePath(string $path): string ``` Normalize a path for comparison. #### Parameters `string` $path Path separated by "/" slash. #### Returns `string` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### 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` ### clearPlugins() public ``` clearPlugins(): void ``` Clear all plugins from the global plugin collection. Useful in test case teardown methods. #### 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` ### count() public ``` count(): int ``` #### Returns `int` ### countOf() public static ``` countOf(int $count): Count ``` #### Parameters `int` $count #### Returns `Count` ### 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` ### 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` ### doesNotPerformAssertions() public ``` doesNotPerformAssertions(): bool ``` #### Returns `bool` ### doubledTypes() public ``` doubledTypes(): string[] ``` #### Returns `string[]` ### 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` ### 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` ### 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() ``` ### 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` ### 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` ### 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` ### 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>` ### 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` ### 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` ### 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` ### 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` ### usesDataProvider() public ``` usesDataProvider(): bool ``` #### Returns `bool` ### 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 --------------- ### $\_configure protected Configure values to restore at end of test. #### Type `array` ### $\_tableLocator protected Table locator instance #### Type `Cake\ORM\Locator\LocatorInterface|null` ### $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 Asset Class Asset ============ Class for generating asset URLs. **Namespace:** [Cake\Routing](namespace-cake.routing) Property Summary ---------------- * [$inflectionType](#%24inflectionType) protected static `string` Inflection type. Method Summary -------------- * ##### [assetTimestamp()](#assetTimestamp()) public static Adds a timestamp to a file based resource based on the value of `Asset.timestamp` in Configure. If Asset.timestamp is true and debug is true, or Asset.timestamp === 'force' a timestamp will be added. * ##### [cssUrl()](#cssUrl()) public static Generates URL for given CSS file. * ##### [encodeUrl()](#encodeUrl()) protected static Encodes URL parts using rawurlencode(). * ##### [imageUrl()](#imageUrl()) public static Generates URL for given image file. * ##### [inflectString()](#inflectString()) protected static Inflect the theme/plugin name to type set using `Asset::setInflectionType()`. * ##### [pluginSplit()](#pluginSplit()) protected static 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. * ##### [requestWebroot()](#requestWebroot()) protected static Get webroot from request. * ##### [scriptUrl()](#scriptUrl()) public static Generates URL for given javascript file. * ##### [setInflectionType()](#setInflectionType()) public static Set inflection type to use when inflecting plugin/theme name. * ##### [url()](#url()) public static Generates URL for given asset file. * ##### [webroot()](#webroot()) public static Checks if a file exists when theme is used, if no file is found default location is returned. Method Detail ------------- ### assetTimestamp() public static ``` assetTimestamp(string $path, string|bool $timestamp = null): string ``` Adds a timestamp to a file based resource based on the value of `Asset.timestamp` in Configure. If Asset.timestamp is true and debug is true, or Asset.timestamp === 'force' a timestamp will be added. #### Parameters `string` $path The file path to timestamp, the path must be inside `App.wwwRoot` in Configure. `string|bool` $timestamp optional If set will overrule the value of `Asset.timestamp` in Configure. #### Returns `string` ### cssUrl() public static ``` cssUrl(string $path, array<string, mixed> $options = []): string ``` Generates URL for given CSS file. Depending on options passed provides full URL with domain name. Also calls `Asset::assetTimestamp()` to add timestamp to local files. #### Parameters `string` $path Path string. `array<string, mixed>` $options optional Options array. Possible keys: `fullBase` Return full URL with domain name `pathPrefix` Path prefix for relative URLs `ext` Asset extension to append `plugin` False value will prevent parsing path as a plugin `timestamp` Overrides the value of `Asset.timestamp` in Configure. Set to false to skip timestamp generation. Set to true to apply timestamps when debug is true. Set to 'force' to always enable timestamping regardless of debug value. #### Returns `string` ### encodeUrl() protected static ``` encodeUrl(string $url): string ``` Encodes URL parts using rawurlencode(). #### Parameters `string` $url The URL to encode. #### Returns `string` ### imageUrl() public static ``` imageUrl(string $path, array<string, mixed> $options = []): string ``` Generates URL for given image file. Depending on options passed provides full URL with domain name. Also calls `Asset::assetTimestamp()` to add timestamp to local files. #### Parameters `string` $path Path string. `array<string, mixed>` $options optional Options array. Possible keys: `fullBase` Return full URL with domain name `pathPrefix` Path prefix for relative URLs `plugin` False value will prevent parsing path as a plugin `timestamp` Overrides the value of `Asset.timestamp` in Configure. Set to false to skip timestamp generation. Set to true to apply timestamps when debug is true. Set to 'force' to always enable timestamping regardless of debug value. #### Returns `string` ### inflectString() protected static ``` inflectString(string $string): string ``` Inflect the theme/plugin name to type set using `Asset::setInflectionType()`. #### Parameters `string` $string String inflected. #### Returns `string` ### pluginSplit() protected static ``` pluginSplit(string $name): 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. #### Returns `array` ### requestWebroot() protected static ``` requestWebroot(): string ``` Get webroot from request. #### Returns `string` ### scriptUrl() public static ``` scriptUrl(string $path, array<string, mixed> $options = []): string ``` Generates URL for given javascript file. Depending on options passed provides full URL with domain name. Also calls `Asset::assetTimestamp()` to add timestamp to local files. #### Parameters `string` $path Path string. `array<string, mixed>` $options optional Options array. Possible keys: `fullBase` Return full URL with domain name `pathPrefix` Path prefix for relative URLs `ext` Asset extension to append `plugin` False value will prevent parsing path as a plugin `timestamp` Overrides the value of `Asset.timestamp` in Configure. Set to false to skip timestamp generation. Set to true to apply timestamps when debug is true. Set to 'force' to always enable timestamping regardless of debug value. #### Returns `string` ### setInflectionType() public static ``` setInflectionType(string $inflectionType): void ``` Set inflection type to use when inflecting plugin/theme name. #### Parameters `string` $inflectionType Inflection type. Value should be a valid method name of `Inflector` class like `'dasherize'` or `'underscore`'`. #### Returns `void` ### url() public static ``` url(string $path, array<string, mixed> $options = []): string ``` Generates URL for given asset file. Depending on options passed provides full URL with domain name. Also calls `Asset::assetTimestamp()` to add timestamp to local files. ### Options: * `fullBase` Boolean true or a string (e.g. <https://example>) to return full URL with protocol and domain name. * `pathPrefix` Path prefix for relative URLs * `ext` Asset extension to append * `plugin` False value will prevent parsing path as a plugin * `theme` Optional theme name * `timestamp` Overrides the value of `Asset.timestamp` in Configure. Set to false to skip timestamp generation. Set to true to apply timestamps when debug is true. Set to 'force' to always enable timestamping regardless of debug value. #### Parameters `string` $path Path string or URL array `array<string, mixed>` $options optional Options array. #### Returns `string` ### webroot() public static ``` webroot(string $file, array<string, mixed> $options = []): string ``` Checks if a file exists when theme is used, if no file is found default location is returned. ### Options: * `theme` Optional theme name #### Parameters `string` $file The file to create a webroot path to. `array<string, mixed>` $options optional Options array. #### Returns `string` Property Detail --------------- ### $inflectionType protected static Inflection type. #### Type `string` cakephp Class ConnectionHelper Class ConnectionHelper ======================= Helper for managing test connections **Namespace:** [Cake\TestSuite](namespace-cake.testsuite) Method Summary -------------- * ##### [addTestAliases()](#addTestAliases()) public Adds `test_<connection name>` aliases for all non-test connections. * ##### [dropTables()](#dropTables()) public Drops all tables. * ##### [enableQueryLogging()](#enableQueryLogging()) public Enables query logging for all database connections. * ##### [runWithoutConstraints()](#runWithoutConstraints()) public Runs callback with constraints disabled correctly per-database * ##### [truncateTables()](#truncateTables()) public Truncates all tables. Method Detail ------------- ### addTestAliases() public ``` addTestAliases(): void ``` Adds `test_<connection name>` aliases for all non-test connections. This forces all models to use the test connection instead. For example, if a model is confused to use connection `files` then it will be aliased to `test_files`. The `default` connection is aliased to `test`. #### Returns `void` ### dropTables() public ``` dropTables(string $connectionName, array<string>|null $tables = null): void ``` Drops all tables. #### Parameters `string` $connectionName Connection name `array<string>|null` $tables optional List of tables names or null for all. #### Returns `void` ### enableQueryLogging() public ``` enableQueryLogging(array<int, string>|null $connections = null): void ``` Enables query logging for all database connections. #### Parameters `array<int, string>|null` $connections optional Connection names or null for all. #### Returns `void` ### runWithoutConstraints() public ``` runWithoutConstraints(Cake\Database\Connection $connection, Closure $callback): void ``` Runs callback with constraints disabled correctly per-database #### Parameters `Cake\Database\Connection` $connection Database connection `Closure` $callback callback #### Returns `void` ### truncateTables() public ``` truncateTables(string $connectionName, array<string>|null $tables = null): void ``` Truncates all tables. #### Parameters `string` $connectionName Connection name `array<string>|null` $tables optional List of tables names or null for all. #### Returns `void` cakephp Class ContentTypeNegotiation Class ContentTypeNegotiation ============================= Negotiates the prefered content type from what the application provides and what the request has in its Accept header. **Namespace:** [Cake\Http](namespace-cake.http) Method Summary -------------- * ##### [acceptLanguage()](#acceptLanguage()) public Check if the request accepts a given language code. * ##### [acceptedLanguages()](#acceptedLanguages()) public Get the normalized list of accepted languages * ##### [parseAccept()](#parseAccept()) public Parse Accept\* headers with qualifier options. * ##### [parseAcceptLanguage()](#parseAcceptLanguage()) public Parse the Accept-Language header * ##### [parseQualifiers()](#parseQualifiers()) protected Parse a header value into preference => value mapping * ##### [preferredType()](#preferredType()) public Get the most preferred content type from a request. Method Detail ------------- ### acceptLanguage() public ``` acceptLanguage(Psr\Http\Message\RequestInterface $request, string $lang): bool ``` Check if the request accepts a given language code. Language codes in the request will be normalized to lower case and have `_` replaced with `-`. #### Parameters `Psr\Http\Message\RequestInterface` $request The request to read headers from. `string` $lang The language code to check. #### Returns `bool` ### acceptedLanguages() public ``` acceptedLanguages(Psr\Http\Message\RequestInterface $request): array<string> ``` Get the normalized list of accepted languages Language codes in the request will be normalized to lower case and have `_` replaced with `-`. #### Parameters `Psr\Http\Message\RequestInterface` $request The request to read headers from. #### Returns `array<string>` ### parseAccept() public ``` parseAccept(Psr\Http\Message\RequestInterface $request): array<string, array<string>> ``` Parse Accept\* headers with qualifier options. Only qualifiers will be extracted, any other accept extensions will be discarded as they are not frequently used. #### Parameters `Psr\Http\Message\RequestInterface` $request The request to get an accept from. #### Returns `array<string, array<string>>` ### parseAcceptLanguage() public ``` parseAcceptLanguage(Psr\Http\Message\RequestInterface $request): array<string, array<string>> ``` Parse the Accept-Language header Only qualifiers will be extracted, other extensions will be ignored as they are not frequently used. #### Parameters `Psr\Http\Message\RequestInterface` $request The request to get an accept from. #### Returns `array<string, array<string>>` ### parseQualifiers() protected ``` parseQualifiers(string $header): array<string, array<string>> ``` Parse a header value into preference => value mapping #### Parameters `string` $header The header value to parse #### Returns `array<string, array<string>>` ### preferredType() public ``` preferredType(Psr\Http\Message\RequestInterface $request, array<string> $choices = []): string|null ``` Get the most preferred content type from a request. Parse the Accept header preferences and return the most preferred type. If multiple types are tied in preference the first type of that preference value will be returned. You can expect null when the request has no Accept header. #### Parameters `Psr\Http\Message\RequestInterface` $request The request to use. `array<string>` $choices optional The supported content type choices. #### Returns `string|null` cakephp Class BaseErrorHandler Class BaseErrorHandler ======================= Base error handler that provides logic common to the CLI + web error/exception handlers. Subclasses are required to implement the template methods to handle displaying the errors in their environment. **Abstract** **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` * [$logger](#%24logger) protected `Cake\Error\ErrorLoggerInterface|null` Exception logger instance. Method Summary -------------- * ##### [\_configDelete()](#_configDelete()) protected Deletes a single config key. * ##### [\_configRead()](#_configRead()) protected Reads a config key. * ##### [\_configWrite()](#_configWrite()) protected Writes a config key. * ##### [\_displayError()](#_displayError()) abstract protected Display an error message in an environment specific way. * ##### [\_displayException()](#_displayException()) abstract protected Display an exception in an environment specific way. * ##### [\_logError()](#_logError()) protected Log an error. * ##### [\_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. * ##### [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 ------------- ### \_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() abstract protected ``` _displayError(array $error, bool $debug): void ``` Display an error message in an environment specific way. Subclasses should implement this method to display the error as desired for the runtime they operate in. #### Parameters `array` $error An array of error data. `bool` $debug Whether the app is in debug mode. #### Returns `void` ### \_displayException() abstract protected ``` _displayException(Throwable $exception): void ``` Display an exception in an environment specific way. Subclasses should implement this method to display an uncaught exception as desired for the runtime they operate in. #### Parameters `Throwable` $exception The uncaught exception. #### 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 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` ### 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 Namespace Middleware Namespace Middleware ==================== ### Classes * ##### [AssetMiddleware](class-cake.routing.middleware.assetmiddleware) Handles serving plugin assets in development mode. * ##### [RoutingMiddleware](class-cake.routing.middleware.routingmiddleware) Applies routing rules to the request and creates the controller instance if possible. cakephp Class UuidType Class UuidType =============== Provides behavior for the UUID type **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 a PHP string * ##### [newId()](#newId()) public Generate a new UUID * ##### [requiresToPhpCast()](#requiresToPhpCast()) public Returns whether the cast to PHP is required to be invoked, since it is not a identity function. * ##### [toDatabase()](#toDatabase()) public Casts given value from a PHP type to one acceptable by database * ##### [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 a PHP string 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(): string ``` Generate a new UUID This method can be used by types to create new primary key values when entities are inserted. #### Returns `string` ### 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 ``` Casts given value from a PHP type to one acceptable by database #### Parameters `mixed` $value value to be converted to database equivalent `Cake\Database\DriverInterface` $driver object from which database preferences and configuration will be extracted #### 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 Class Collection Class Collection ================= A collection is an immutable list of elements with a handful of functions to iterate, group, transform and extract information from it. **Namespace:** [Cake\Collection](namespace-cake.collection) 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 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(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 #### 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`
programming_docs
cakephp Namespace Formatter Namespace Formatter =================== ### Classes * ##### [AbstractFormatter](class-cake.log.formatter.abstractformatter) * ##### [DefaultFormatter](class-cake.log.formatter.defaultformatter) * ##### [JsonFormatter](class-cake.log.formatter.jsonformatter) * ##### [LegacySyslogFormatter](class-cake.log.formatter.legacysyslogformatter) cakephp Class DigestAuthenticate Class DigestAuthenticate ========================= Digest Authentication adapter for AuthComponent. Provides Digest HTTP authentication support for AuthComponent. ### Using Digest auth Load `AuthComponent` in your controller's `initialize()` and add 'Digest' in 'authenticate' key ``` $this->loadComponent('Auth', [ 'authenticate' => ['Digest'], 'storage' => 'Memory', 'unauthorizedRedirect' => false, ]); ``` You should set `storage` to `Memory` to prevent CakePHP from sending a session cookie to the client. You should set `unauthorizedRedirect` to `false`. This causes `AuthComponent` to throw a `ForbiddenException` exception instead of redirecting to another page. Since HTTP Digest Authentication is stateless you don't need call `setUser()` in your controller. The user credentials will be checked on each request. If valid credentials are not provided, required authentication headers will be sent by this authentication provider which triggers the login dialog in the browser/client. ### Generating passwords compatible with Digest authentication. DigestAuthenticate requires a special password hash that conforms to RFC2617. You can generate this password using `DigestAuthenticate::password()` ``` $digestPass = DigestAuthenticate::password($username, $password, env('SERVER_NAME')); ``` If you wish to use digest authentication alongside other authentication methods, it's recommended that you store the digest authentication separately. For example `User.digest_pass` could be used for a digest password, while `User.password` would store the password hash for use with other methods like Basic or Form. **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 * ##### [\_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. * ##### [\_getDigest()](#_getDigest()) protected Gets the digest headers from the request/environment. * ##### [\_query()](#_query()) protected Get query object for fetching user from database. * ##### [authenticate()](#authenticate()) public Authenticate a user using HTTP auth. Will use the configured User model and attempt a login using HTTP auth. * ##### [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. * ##### [generateNonce()](#generateNonce()) protected Generate a nonce value that is validated in future requests. * ##### [generateResponseHash()](#generateResponseHash()) public Generate the response hash for a given digest array. * ##### [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. Used by cookie-less auth for stateless clients. * ##### [implementedEvents()](#implementedEvents()) public Returns a list of all events that this authenticate class will listen to. * ##### [loginHeaders()](#loginHeaders()) public Generate the login headers * ##### [needsPasswordRehash()](#needsPasswordRehash()) public Returns whether the password stored in the repository for the logged in user requires to be rehashed with another algorithm * ##### [parseAuthData()](#parseAuthData()) public Parse the digest authentication headers and split them up. * ##### [password()](#password()) public static Creates an auth digest password hash to store * ##### [passwordHasher()](#passwordHasher()) public Return password hasher object * ##### [setConfig()](#setConfig()) public Sets the config. * ##### [setTableLocator()](#setTableLocator()) public Sets the table locator. * ##### [unauthenticated()](#unauthenticated()) public Handles an unauthenticated access attempt by sending appropriate login headers * ##### [validNonce()](#validNonce()) protected Check the nonce to ensure it is valid and not expired. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\Controller\ComponentRegistry $registry, array<string, mixed> $config = []) ``` Constructor Besides the keys specified in BaseAuthenticate::$\_defaultConfig, DigestAuthenticate uses the following extra keys: * `secret` The secret to use for nonce validation. Defaults to Security::getSalt(). * `realm` The realm authentication is for, Defaults to the servername. * `qop` Defaults to 'auth', no other values are supported at this time. * `opaque` A string that must be returned unchanged by clients. Defaults to `md5($config['realm'])` * `nonceLifetime` The number of seconds that nonces are valid for. Defaults to 300. #### 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` ### \_getDigest() protected ``` _getDigest(Cake\Http\ServerRequest $request): array<string, mixed>|null ``` Gets the digest headers from the request/environment. #### Parameters `Cake\Http\ServerRequest` $request Request object. #### Returns `array<string, mixed>|null` ### \_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 ``` Authenticate a user using HTTP auth. Will use the configured User model and attempt a login using HTTP auth. #### Parameters `Cake\Http\ServerRequest` $request The request to authenticate with. `Cake\Http\Response` $response The response to add headers to. #### 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() ### generateNonce() protected ``` generateNonce(): string ``` Generate a nonce value that is validated in future requests. #### Returns `string` ### generateResponseHash() public ``` generateResponseHash(array<string, mixed> $digest, string $password, string $method): string ``` Generate the response hash for a given digest array. #### Parameters `array<string, mixed>` $digest Digest information containing data from DigestAuthenticate::parseAuthData(). `string` $password The digest hash password generated with DigestAuthenticate::password() `string` $method Request method #### 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` ### 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. Used by cookie-less auth for stateless clients. #### 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>` ### loginHeaders() public ``` loginHeaders(Cake\Http\ServerRequest $request): array<string, string> ``` Generate the login headers #### Parameters `Cake\Http\ServerRequest` $request Request object. #### Returns `array<string, string>` ### 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` ### parseAuthData() public ``` parseAuthData(string $digest): array|null ``` Parse the digest authentication headers and split them up. #### Parameters `string` $digest The raw digest authentication headers. #### Returns `array|null` ### password() public static ``` password(string $username, string $password, string $realm): string ``` Creates an auth digest password hash to store #### Parameters `string` $username The username to use in the digest hash. `string` $password The unhashed password to make a digest hash for. `string` $realm The realm the password is for. #### Returns `string` ### 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 ``` Handles an unauthenticated access attempt by sending appropriate login headers * 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` #### Throws `Cake\Http\Exception\UnauthorizedException` ### validNonce() protected ``` validNonce(string $nonce): bool ``` Check the nonce to ensure it is valid and not expired. #### Parameters `string` $nonce The nonce value to check. #### Returns `bool` 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 Class OrderByExpression Class OrderByExpression ======================== An expression object for ORDER BY clauses **Namespace:** [Cake\Database\Expression](namespace-cake.database.expression) Property Summary ---------------- * [$\_conditions](#%24_conditions) protected `array` A list of strings or other expression objects that represent the "branches" of the expression tree. For example one key of the array might look like "sum > :value" * [$\_conjunction](#%24_conjunction) protected `string` String to be used for joining each of the internal expressions this object internally stores for example "AND", "OR", etc. * [$\_typeMap](#%24_typeMap) protected `Cake\Database\TypeMap|null` Method Summary -------------- * ##### [\_\_clone()](#__clone()) public Clone this object and its subtree of expressions. * ##### [\_\_construct()](#__construct()) public Constructor * ##### [\_addConditions()](#_addConditions()) protected Auxiliary function used for decomposing a nested array of conditions and building a tree structure inside this object to represent the full SQL expression. * ##### [\_calculateType()](#_calculateType()) protected Returns the type name for the passed field if it was stored in the typeMap * ##### [\_parseCondition()](#_parseCondition()) protected Parses a string conditions by trying to extract the operator inside it if any and finally returning either an adequate QueryExpression object or a plain string representation of the condition. This function is responsible for generating the placeholders and replacing the values by them, while storing the value elsewhere for future binding. * ##### [add()](#add()) public Adds one or more conditions to this expression object. Conditions can be expressed in a one dimensional array, that will cause all conditions to be added directly at this level of the tree or they can be nested arbitrarily making it create more expression objects that will be nested inside and configured to use the specified conjunction. * ##### [addCase()](#addCase()) public deprecated Adds a new case expression to the expression object * ##### [and()](#and()) public Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "AND" * ##### [and\_()](#and_()) public deprecated Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "AND" * ##### [between()](#between()) public Adds a new condition to the expression object in the form "field BETWEEN from AND to". * ##### [case()](#case()) public Returns a new case expression object. * ##### [count()](#count()) public Returns the number of internal conditions that are stored in this expression. Useful to determine if this expression object is void or it will generate a non-empty string when compiled * ##### [eq()](#eq()) public Adds a new condition to the expression object in the form "field = value". * ##### [equalFields()](#equalFields()) public Builds equal condition or assignment with identifier wrapping. * ##### [exists()](#exists()) public Adds a new condition to the expression object in the form "EXISTS (...)". * ##### [getConjunction()](#getConjunction()) public Gets the currently configured conjunction for the conditions at this level of the expression tree. * ##### [getDefaultTypes()](#getDefaultTypes()) public Gets default types of current type map. * ##### [getTypeMap()](#getTypeMap()) public Returns the existing type map. * ##### [gt()](#gt()) public Adds a new condition to the expression object in the form "field > value". * ##### [gte()](#gte()) public Adds a new condition to the expression object in the form "field >= value". * ##### [hasNestedExpression()](#hasNestedExpression()) public Returns true if this expression contains any other nested ExpressionInterface objects * ##### [in()](#in()) public Adds a new condition to the expression object in the form "field IN (value1, value2)". * ##### [isCallable()](#isCallable()) public deprecated Check whether a callable is acceptable. * ##### [isNotNull()](#isNotNull()) public Adds a new condition to the expression object in the form "field IS NOT NULL". * ##### [isNull()](#isNull()) public Adds a new condition to the expression object in the form "field IS NULL". * ##### [iterateParts()](#iterateParts()) public Executes a callable function for each of the parts that form this expression. * ##### [like()](#like()) public Adds a new condition to the expression object in the form "field LIKE value". * ##### [lt()](#lt()) public Adds a new condition to the expression object in the form "field < value". * ##### [lte()](#lte()) public Adds a new condition to the expression object in the form "field <= value". * ##### [not()](#not()) public Adds a new set of conditions to this level of the tree and negates the final result by prepending a NOT, it will look like "NOT ( (condition1) AND (conditions2) )" conjunction depends on the one currently configured for this object. * ##### [notEq()](#notEq()) public Adds a new condition to the expression object in the form "field != value". * ##### [notExists()](#notExists()) public Adds a new condition to the expression object in the form "NOT EXISTS (...)". * ##### [notIn()](#notIn()) public Adds a new condition to the expression object in the form "field NOT IN (value1, value2)". * ##### [notInOrNull()](#notInOrNull()) public Adds a new condition to the expression object in the form "(field NOT IN (value1, value2) OR field IS NULL". * ##### [notLike()](#notLike()) public Adds a new condition to the expression object in the form "field NOT LIKE value". * ##### [or()](#or()) public Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "OR" * ##### [or\_()](#or_()) public deprecated Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "OR" * ##### [setConjunction()](#setConjunction()) public Changes the conjunction for the conditions at this level of the expression tree. * ##### [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. * ##### [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(Cake\Database\ExpressionInterface|array|string $conditions = [], Cake\Database\TypeMap|array $types = [], string $conjunction = '') ``` Constructor #### Parameters `Cake\Database\ExpressionInterface|array|string` $conditions optional The sort columns `Cake\Database\TypeMap|array` $types optional The types for each column. `string` $conjunction optional The glue used to join conditions together. ### \_addConditions() protected ``` _addConditions(array $conditions, array<int|string, string> $types): void ``` Auxiliary function used for decomposing a nested array of conditions and building a tree structure inside this object to represent the full SQL expression. New order by expressions are merged to existing ones #### Parameters `array` $conditions list of order by expressions `array<int|string, string>` $types list of types associated on fields referenced in $conditions #### Returns `void` ### \_calculateType() protected ``` _calculateType(Cake\Database\ExpressionInterface|string $field): string|null ``` Returns the type name for the passed field if it was stored in the typeMap #### Parameters `Cake\Database\ExpressionInterface|string` $field The field name to get a type for. #### Returns `string|null` ### \_parseCondition() protected ``` _parseCondition(string $field, mixed $value): Cake\Database\ExpressionInterface ``` Parses a string conditions by trying to extract the operator inside it if any and finally returning either an adequate QueryExpression object or a plain string representation of the condition. This function is responsible for generating the placeholders and replacing the values by them, while storing the value elsewhere for future binding. #### Parameters `string` $field The value from which the actual field and operator will be extracted. `mixed` $value The value to be bound to a placeholder for the field #### Returns `Cake\Database\ExpressionInterface` #### Throws `InvalidArgumentException` If operator is invalid or missing on NULL usage. ### add() public ``` add(Cake\Database\ExpressionInterface|array|string $conditions, array<int|string, string> $types = []): $this ``` Adds one or more conditions to this expression object. Conditions can be expressed in a one dimensional array, that will cause all conditions to be added directly at this level of the tree or they can be nested arbitrarily making it create more expression objects that will be nested inside and configured to use the specified conjunction. If the type passed for any of the fields is expressed "type[]" (note braces) then it will cause the placeholder to be re-written dynamically so if the value is an array, it will create as many placeholders as values are in it. #### Parameters `Cake\Database\ExpressionInterface|array|string` $conditions single or multiple conditions to be added. When using an array and the key is 'OR' or 'AND' a new expression object will be created with that conjunction and internal array value passed as conditions. `array<int|string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `$this` #### See Also \Cake\Database\Query::where() for examples on conditions ### addCase() public ``` addCase(Cake\Database\ExpressionInterface|array $conditions, Cake\Database\ExpressionInterface|array $values = [], array<string> $types = []): $this ``` Adds a new case expression to the expression object #### Parameters `Cake\Database\ExpressionInterface|array` $conditions 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 #### Returns `$this` ### and() public ``` and(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "AND" #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be joined with AND `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `Cake\Database\Expression\QueryExpression` ### and\_() public ``` and_(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "AND" #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be joined with AND `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `Cake\Database\Expression\QueryExpression` ### between() public ``` between(Cake\Database\ExpressionInterface|string $field, mixed $from, mixed $to, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field BETWEEN from AND to". #### 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 type name for $value as configured using the Type map. #### Returns `$this` ### case() public ``` case(Cake\Database\ExpressionInterface|object|scalar|null $value = null, string|null $type = null): Cake\Database\Expression\CaseStatementExpression ``` Returns a new case expression object. 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. #### Returns `Cake\Database\Expression\CaseStatementExpression` ### count() public ``` count(): int ``` Returns the number of internal conditions that are stored in this expression. Useful to determine if this expression object is void or it will generate a non-empty string when compiled #### Returns `int` ### eq() public ``` eq(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field = value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. If it is suffixed with "[]" and the value is an array then multiple placeholders will be created, one per each value in the array. #### Returns `$this` ### equalFields() public ``` equalFields(string $leftField, string $rightField): $this ``` Builds equal condition or assignment with identifier wrapping. #### Parameters `string` $leftField Left join condition field name. `string` $rightField Right join condition field name. #### Returns `$this` ### exists() public ``` exists(Cake\Database\ExpressionInterface $expression): $this ``` Adds a new condition to the expression object in the form "EXISTS (...)". #### Parameters `Cake\Database\ExpressionInterface` $expression the inner query #### Returns `$this` ### getConjunction() public ``` getConjunction(): string ``` Gets the currently configured conjunction for the conditions at this level of the expression tree. #### Returns `string` ### 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` ### gt() public ``` gt(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field > value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### gte() public ``` gte(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field >= value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### hasNestedExpression() public ``` hasNestedExpression(): bool ``` Returns true if this expression contains any other nested ExpressionInterface objects #### Returns `bool` ### in() public ``` in(Cake\Database\ExpressionInterface|string $field, Cake\Database\ExpressionInterface|array|string $values, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field IN (value1, value2)". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `Cake\Database\ExpressionInterface|array|string` $values the value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### isCallable() public ``` isCallable(Cake\Database\ExpressionInterface|callable|array|string $callable): bool ``` Check whether a callable is acceptable. We don't accept ['class', 'method'] style callbacks, as they often contain user input and arrays of strings are easy to sneak in. #### Parameters `Cake\Database\ExpressionInterface|callable|array|string` $callable The callable to check. #### Returns `bool` ### isNotNull() public ``` isNotNull(Cake\Database\ExpressionInterface|string $field): $this ``` Adds a new condition to the expression object in the form "field IS NOT NULL". #### Parameters `Cake\Database\ExpressionInterface|string` $field database field to be tested for not null #### Returns `$this` ### isNull() public ``` isNull(Cake\Database\ExpressionInterface|string $field): $this ``` Adds a new condition to the expression object in the form "field IS NULL". #### Parameters `Cake\Database\ExpressionInterface|string` $field database field to be tested for null #### Returns `$this` ### iterateParts() public ``` iterateParts(callable $callback): $this ``` Executes a callable function for each of the parts that form this expression. The callable function is required to return a value with which the currently visited part will be replaced. If the callable function returns null then the part will be discarded completely from this expression. The callback function will receive each of the conditions as first param and the key as second param. It is possible to declare the second parameter as passed by reference, this will enable you to change the key under which the modified part is stored. #### Parameters `callable` $callback The callable to apply to each part. #### Returns `$this` ### like() public ``` like(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field LIKE value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### lt() public ``` lt(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field < value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### lte() public ``` lte(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field <= value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### not() public ``` not(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): $this ``` Adds a new set of conditions to this level of the tree and negates the final result by prepending a NOT, it will look like "NOT ( (condition1) AND (conditions2) )" conjunction depends on the one currently configured for this object. #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be added and negated `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `$this` ### notEq() public ``` notEq(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field != value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. If it is suffixed with "[]" and the value is an array then multiple placeholders will be created, one per each value in the array. #### Returns `$this` ### notExists() public ``` notExists(Cake\Database\ExpressionInterface $expression): $this ``` Adds a new condition to the expression object in the form "NOT EXISTS (...)". #### Parameters `Cake\Database\ExpressionInterface` $expression the inner query #### Returns `$this` ### notIn() public ``` notIn(Cake\Database\ExpressionInterface|string $field, Cake\Database\ExpressionInterface|array|string $values, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field NOT IN (value1, value2)". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `Cake\Database\ExpressionInterface|array|string` $values the value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### notInOrNull() public ``` notInOrNull(Cake\Database\ExpressionInterface|string $field, Cake\Database\ExpressionInterface|array|string $values, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "(field NOT IN (value1, value2) OR field IS NULL". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `Cake\Database\ExpressionInterface|array|string` $values the value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### notLike() public ``` notLike(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field NOT LIKE value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### or() public ``` or(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "OR" #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be joined with OR `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `Cake\Database\Expression\QueryExpression` ### or\_() public ``` or_(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "OR" #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be joined with OR `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `Cake\Database\Expression\QueryExpression` ### setConjunction() public ``` setConjunction(string $conjunction): $this ``` Changes the conjunction for the conditions at this level of the expression tree. #### Parameters `string` $conjunction Value to be used for joining conditions #### 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() ### 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` ### 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 "branches" of the expression tree. For example one key of the array might look like "sum > :value" #### Type `array` ### $\_conjunction protected String to be used for joining each of the internal expressions this object internally stores for example "AND", "OR", etc. #### Type `string` ### $\_typeMap protected #### Type `Cake\Database\TypeMap|null`
programming_docs
cakephp Class AjaxView Class 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. **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 custom 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. * [$\_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` The name of the layouts subfolder containing layouts for this View. * [$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` Sub-directory for this template file. This is often used for extension based routing. Eg. With an `xml` extension, $subDir would be `xml/` * [$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 * ##### [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 Get content type for this view. * ##### [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 Interact with the HelperRegistry to load all the helpers. * ##### [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 Renders view for given template file and layout. * ##### [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` ### 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 ``` Get content type for this view. #### 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 ``` Interact with the HelperRegistry to load all the helpers. #### 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 ``` Renders view for given template file and layout. 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 Name of template file to use `string|false|null` $layout optional Layout to use. False to disable. #### Returns `string` #### Throws `Cake\Core\Exception\CakeException` If there is an error in the view. ### 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 custom config options. #### 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[]>` ### $\_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 The name of the layouts subfolder containing layouts for this View. #### 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 Sub-directory for this template file. This is often used for extension based routing. Eg. With an `xml` extension, $subDir would be `xml/` #### 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 BaseApplication Class BaseApplication ====================== Base class for full-stack applications This class serves as a base class for applications that are using CakePHP as a full stack framework. If you are only using the Http or Console libraries you should implement the relevant interfaces directly. The application class is responsible for bootstrapping the application, and ensuring that middleware is attached. It is also invoked as the last piece of middleware, and delegates request/response handling to the correct controller. **Abstract** **Namespace:** [Cake\Http](namespace-cake.http) 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. * [$configDir](#%24configDir) protected `string` * [$container](#%24container) protected `Cake\Core\ContainerInterface|null` Container * [$controllerFactory](#%24controllerFactory) protected `Cake\Http\ControllerFactoryInterface|null` Controller factory * [$plugins](#%24plugins) protected `Cake\Core\PluginCollection` Plugin Collection Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [addOptionalPlugin()](#addOptionalPlugin()) public Add an optional plugin * ##### [addPlugin()](#addPlugin()) public Add a plugin to the loaded plugin set. * ##### [bootstrap()](#bootstrap()) public Load all the application configuration and bootstrap logic. * ##### [buildContainer()](#buildContainer()) protected Build the service container * ##### [console()](#console()) public Define the console commands for an application. * ##### [dispatchEvent()](#dispatchEvent()) public Wrapper for creating and dispatching events. * ##### [getContainer()](#getContainer()) public Get the dependency injection container for the application. * ##### [getEventManager()](#getEventManager()) public Returns the Cake\Event\EventManager manager instance for this object. * ##### [getPlugins()](#getPlugins()) public Get the plugin collection in use. * ##### [handle()](#handle()) public Invoke the application. * ##### [middleware()](#middleware()) abstract public Define the HTTP middleware layers for an application. * ##### [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 * ##### [routes()](#routes()) public Define the routes for an application. * ##### [services()](#services()) public Register application container services. * ##### [setEventManager()](#setEventManager()) public Returns the Cake\Event\EventManagerInterface instance for this object. Method Detail ------------- ### \_\_construct() public ``` __construct(string $configDir, Cake\Event\EventManagerInterface|null $eventManager = null, Cake\Http\ControllerFactoryInterface|null $controllerFactory = null) ``` Constructor #### Parameters `string` $configDir The directory the bootstrap configuration is held in. `Cake\Event\EventManagerInterface|null` $eventManager optional Application event manager instance. `Cake\Http\ControllerFactoryInterface|null` $controllerFactory optional Controller factory. ### addOptionalPlugin() public ``` addOptionalPlugin(Cake\Core\PluginInterface|string $name, array<string, mixed> $config = []): $this ``` Add an optional plugin If it isn't available, ignore it. #### 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` ### 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 `array<string, mixed>` $config optional #### Returns `$this` ### 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` ### buildContainer() protected ``` buildContainer(): Cake\Core\ContainerInterface ``` Build the service container Override this method if you need to use a custom container or want to change how the container is built. #### Returns `Cake\Core\ContainerInterface` ### console() public ``` console(Cake\Console\CommandCollection $commands): Cake\Console\CommandCollection ``` Define the console commands for an application. By default, all commands in CakePHP, plugins and the application will be loaded using conventions based names. #### Parameters `Cake\Console\CommandCollection` $commands The CommandCollection to add commands into. #### Returns `Cake\Console\CommandCollection` ### 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` ### getContainer() public ``` getContainer(): Cake\Core\ContainerInterface ``` Get the dependency injection container for the application. The first time the container is fetched it will be constructed and stored for future calls. #### Returns `Cake\Core\ContainerInterface` ### 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` ### getPlugins() public ``` getPlugins(): Cake\Core\PluginCollection ``` Get the plugin collection in use. #### Returns `Cake\Core\PluginCollection` ### handle() public ``` handle(ServerRequestInterface $request): Psr\Http\Message\ResponseInterface ``` Invoke the application. * Add the request to the container, enabling its injection into other services. * Create the controller that will handle this request. * Invoke the controller. #### Parameters `ServerRequestInterface` $request The request #### Returns `Psr\Http\Message\ResponseInterface` ### middleware() abstract 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` ### 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 #### Returns `Cake\Console\CommandCollection` ### pluginMiddleware() public ``` pluginMiddleware(Cake\Http\MiddlewareQueue $middleware): Cake\Http\MiddlewareQueue ``` Run middleware hooks for plugins #### Parameters `Cake\Http\MiddlewareQueue` $middleware #### 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 #### Returns `Cake\Routing\RouteBuilder` ### routes() public ``` routes(Cake\Routing\RouteBuilder $routes): void ``` Define the routes for an application. By default, this will load `config/routes.php` for ease of use and backwards compatibility. #### Parameters `Cake\Routing\RouteBuilder` $routes A route builder to add routes into. #### Returns `void` ### services() public ``` services(Cake\Core\ContainerInterface $container): void ``` Register application container services. Registered services can have instances fetched out of the container using `get()`. Dependencies and parameters will be resolved based on service definitions. #### Parameters `Cake\Core\ContainerInterface` $container The Container to update. #### Returns `void` ### 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` ### $configDir protected #### Type `string` ### $container protected Container #### Type `Cake\Core\ContainerInterface|null` ### $controllerFactory protected Controller factory #### Type `Cake\Http\ControllerFactoryInterface|null` ### $plugins protected Plugin Collection #### Type `Cake\Core\PluginCollection` cakephp Class InternalErrorException Class InternalErrorException ============================= Represents an HTTP 500 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 'Internal Server Error' will be the message `int|null` $code optional Status code, defaults to 500 `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 StatusError Class StatusError ================== StatusError **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 EncryptedCookieMiddleware Class EncryptedCookieMiddleware ================================ Middleware for encrypting & decrypting cookies. This middleware layer will encrypt/decrypt the named cookies with the given key and cipher type. To support multiple keys/cipher types use this middleware multiple times. Cookies in request data will be decrypted, while cookies in response headers will be encrypted automatically. If the response is a {@link \Cake\Http\Response}, the cookie data set with `withCookie()` and `cookie()`` will also be encrypted. The encryption types and padding are compatible with those used by CookieComponent for backwards compatibility. **Namespace:** [Cake\Http\Middleware](namespace-cake.http.middleware) Property Summary ---------------- * [$\_validCiphers](#%24_validCiphers) protected `array<string>` Valid cipher names for encrypted cookies. * [$cipherType](#%24cipherType) protected `string` Encryption type. * [$cookieNames](#%24cookieNames) protected `array<string>` The list of cookies to encrypt/decrypt * [$key](#%24key) protected `string` Encryption key to use. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [\_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()) protected Fetch the cookie encryption key. * ##### [\_implode()](#_implode()) protected Implode method to keep keys are multidimensional arrays * ##### [decodeCookies()](#decodeCookies()) protected Decode cookies from the request. * ##### [encodeCookies()](#encodeCookies()) protected Encode cookies from a response's CookieCollection. * ##### [encodeSetCookieHeader()](#encodeSetCookieHeader()) protected Encode cookies from a response's Set-Cookie header * ##### [process()](#process()) public Apply cookie encryption/decryption. Method Detail ------------- ### \_\_construct() public ``` __construct(array<string> $cookieNames, string $key, string $cipherType = 'aes') ``` Constructor #### Parameters `array<string>` $cookieNames The list of cookie names that should have their values encrypted. `string` $key The encryption key to use. `string` $cipherType optional The cipher type to use. Defaults to 'aes'. ### \_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() protected ``` _getCookieEncryptionKey(): string ``` Fetch the cookie encryption key. Part of the CookieCryptTrait implementation. #### 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` ### decodeCookies() protected ``` decodeCookies(Psr\Http\Message\ServerRequestInterface $request): Psr\Http\Message\ServerRequestInterface ``` Decode cookies from the request. #### Parameters `Psr\Http\Message\ServerRequestInterface` $request The request to decode cookies from. #### Returns `Psr\Http\Message\ServerRequestInterface` ### encodeCookies() protected ``` encodeCookies(Cake\Http\Response $response): Cake\Http\Response ``` Encode cookies from a response's CookieCollection. #### Parameters `Cake\Http\Response` $response The response to encode cookies in. #### Returns `Cake\Http\Response` ### encodeSetCookieHeader() protected ``` encodeSetCookieHeader(Psr\Http\Message\ResponseInterface $response): Psr\Http\Message\ResponseInterface ``` Encode cookies from a response's Set-Cookie header #### Parameters `Psr\Http\Message\ResponseInterface` $response The response to encode cookies in. #### Returns `Psr\Http\Message\ResponseInterface` ### process() public ``` process(ServerRequestInterface $request, RequestHandlerInterface $handler): Psr\Http\Message\ResponseInterface ``` Apply cookie encryption/decryption. 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 --------------- ### $\_validCiphers protected Valid cipher names for encrypted cookies. #### Type `array<string>` ### $cipherType protected Encryption type. #### Type `string` ### $cookieNames protected The list of cookies to encrypt/decrypt #### Type `array<string>` ### $key protected Encryption key to use. #### Type `string` cakephp Trait StringCompareTrait Trait StringCompareTrait ========================= Compare a string to the contents of a file Implementing objects are expected to modify the `$_compareBasePath` property before use. **Namespace:** [Cake\TestSuite](namespace-cake.testsuite) Property Summary ---------------- * [$\_compareBasePath](#%24_compareBasePath) protected `string` The base path for output comparisons * [$\_updateComparisons](#%24_updateComparisons) protected `bool` Update comparisons to match test changes Method Summary -------------- * ##### [assertSameAsFile()](#assertSameAsFile()) public Compare the result to the contents of the file Method Detail ------------- ### assertSameAsFile() public ``` assertSameAsFile(string $path, string $result): void ``` Compare the result to the contents of the file #### Parameters `string` $path partial path to test comparison file `string` $result test result as a string #### Returns `void` Property Detail --------------- ### $\_compareBasePath protected The base path for output comparisons Must be initialized before use #### Type `string` ### $\_updateComparisons protected Update comparisons to match test changes Initialized with the env variable UPDATE\_TEST\_COMPARISON\_FILES #### Type `bool` cakephp Class SelectBoxWidget Class SelectBoxWidget ====================== Input widget class for generating a selectbox. This class is usually used internally by `Cake\View\Helper\FormHelper`, it but can be used to generate standalone select boxes. **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. * ##### [\_emptyValue()](#_emptyValue()) protected Generate the empty value based on the input. * ##### [\_isDisabled()](#_isDisabled()) protected Helper method for deciding what options are disabled. * ##### [\_isSelected()](#_isSelected()) protected Helper method for deciding what options are selected. * ##### [\_renderContent()](#_renderContent()) protected Render the contents of the select element. * ##### [\_renderOptgroup()](#_renderOptgroup()) protected Render the contents of an optgroup element. * ##### [\_renderOptions()](#_renderOptions()) protected Render a set of options. * ##### [mergeDefaults()](#mergeDefaults()) protected Merge default values with supplied data. * ##### [render()](#render()) public Render a select box form input. * ##### [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. ### \_emptyValue() protected ``` _emptyValue(array|string|bool $value): array ``` Generate the empty value based on the input. #### Parameters `array|string|bool` $value The provided empty value. #### Returns `array` ### \_isDisabled() protected ``` _isDisabled(string $key, array<string>|null $disabled): bool ``` Helper method for deciding what options are disabled. #### Parameters `string` $key The key to test. `array<string>|null` $disabled The disabled values. #### Returns `bool` ### \_isSelected() protected ``` _isSelected(string $key, array<string>|string|int|false|null $selected): bool ``` Helper method for deciding what options are selected. #### Parameters `string` $key The key to test. `array<string>|string|int|false|null` $selected The selected values. #### Returns `bool` ### \_renderContent() protected ``` _renderContent(array<string, mixed> $data): array<string> ``` Render the contents of the select element. #### Parameters `array<string, mixed>` $data The context for rendering a select. #### Returns `array<string>` ### \_renderOptgroup() protected ``` _renderOptgroup(string $label, ArrayAccess|array $optgroup, array|null $disabled, array|string|null $selected, array $templateVars, bool $escape): string ``` Render the contents of an optgroup element. #### Parameters `string` $label The optgroup label text `ArrayAccess|array` $optgroup The opt group data. `array|null` $disabled The options to disable. `array|string|null` $selected The options to select. `array` $templateVars Additional template variables. `bool` $escape Toggle HTML escaping #### Returns `string` ### \_renderOptions() protected ``` _renderOptions(iterable $options, array<string>|null $disabled, array|string|null $selected, array $templateVars, bool $escape): array<string> ``` Render a set of options. Will recursively call itself when option groups are in use. #### Parameters `iterable` $options The options to render. `array<string>|null` $disabled The options to disable. `array|string|null` $selected The options to select. `array` $templateVars Additional template variables. `bool` $escape Toggle HTML escaping. #### Returns `array<string>` ### 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 select box form input. Render a select box input given a set of data. Supported keys are: * `name` - Set the input name. * `options` - An array of options. * `disabled` - Either true or an array of options to disable. When true, the select element will be disabled. * `val` - Either a string or an array of options to mark as selected. * `empty` - Set to true to add an empty option at the top of the option elements. Set to a string to define the display text of the empty option. If an array is used the key will set the value of the empty option while, the value will set the display text. * `escape` - Set to false to disable HTML escaping. ### Options format The options option can take a variety of data format depending on the complexity of HTML you want generated. You can generate simple options using a basic associative array: ``` 'options' => ['elk' => 'Elk', 'beaver' => 'Beaver'] ``` If you need to define additional attributes on your option elements you can use the complex form for options: ``` 'options' => [ ['value' => 'elk', 'text' => 'Elk', 'data-foo' => 'bar'], ] ``` This form **requires** that both the `value` and `text` keys be defined. If either is not set options will not be generated correctly. If you need to define option groups you can do those using nested arrays: ``` 'options' => [ 'Mammals' => [ 'elk' => 'Elk', 'beaver' => 'Beaver' ] ] ``` And finally, if you need to put attributes on your optgroup elements you can do that with a more complex nested array form: ``` 'options' => [ [ 'text' => 'Mammals', 'data-id' => 1, 'options' => [ 'elk' => 'Elk', 'beaver' => 'Beaver' ] ], ] ``` You are free to mix each of the forms in the same option set, and nest complex types as required. #### Parameters `array<string, mixed>` $data Data to render with. `Cake\View\Form\ContextInterface` $context The current form context. #### Returns `string` #### Throws `RuntimeException` when the name attribute is empty. ### 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 Cookie Class Cookie ============= Cookie object to build a cookie and turn it into a header value An HTTP cookie (also called web cookie, Internet cookie, browser cookie or simply cookie) is a small piece of data sent from a website and stored on the user's computer by the user's web browser while the user is browsing. Cookies were designed to be a reliable mechanism for websites to remember stateful information (such as items added in the shopping cart in an online store) or to record the user's browsing activity (including clicking particular buttons, logging in, or recording which pages were visited in the past). They can also be used to remember arbitrary pieces of information that the user previously entered into form fields such as names, and preferences. Cookie objects are immutable, and you must re-assign variables when modifying cookie objects: ``` $cookie = $cookie->withValue('0'); ``` **Namespace:** [Cake\Http\Cookie](namespace-cake.http.cookie) **See:** \Cake\Http\Cookie\CookieCollection for working with collections of cookies. **See:** \Cake\Http\Response::getCookieCollection() for working with response cookies. **Link:** https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03 **Link:** https://en.wikipedia.org/wiki/HTTP\_cookie Constants --------- * `string` **EXPIRES\_FORMAT** ``` 'D, d-M-Y H:i:s T' ``` Expires attribute format. * `string` **SAMESITE\_LAX** ``` 'Lax' ``` SameSite attribute value: Lax * `string` **SAMESITE\_NONE** ``` 'None' ``` SameSite attribute value: None * `string` **SAMESITE\_STRICT** ``` 'Strict' ``` SameSite attribute value: Strict * `array<string>` **SAMESITE\_VALUES** ``` [self::SAMESITE_LAX, self::SAMESITE_STRICT, self::SAMESITE_NONE] ``` Valid values for "SameSite" attribute. Property Summary ---------------- * [$defaults](#%24defaults) protected static `array<string, mixed>` Default attributes for a cookie. * [$domain](#%24domain) protected `string` Domain * [$expiresAt](#%24expiresAt) protected `DateTimeDateTimeImmutable|null` Expiration time * [$httpOnly](#%24httpOnly) protected `bool` HTTP only * [$isExpanded](#%24isExpanded) protected `bool` Whether a JSON value has been expanded into an array. * [$name](#%24name) protected `string` Cookie name * [$path](#%24path) protected `string` Path * [$sameSite](#%24sameSite) protected `string|null` Samesite * [$secure](#%24secure) protected `bool` Secure * [$value](#%24value) protected `array|string` Raw Cookie value. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [\_expand()](#_expand()) protected Explode method to return array from string set in CookieComponent::\_flatten() Maintains reading backwards compatibility with 1.x CookieComponent::\_flatten(). * ##### [\_flatten()](#_flatten()) protected Implode method to keep keys are multidimensional arrays * ##### [\_setValue()](#_setValue()) protected Setter for the value attribute. * ##### [check()](#check()) public Checks if a value exists in the cookie data. * ##### [create()](#create()) public static Factory method to create Cookie instances. * ##### [createFromHeaderString()](#createFromHeaderString()) public static Create Cookie instance from "set-cookie" header string. * ##### [dateTimeInstance()](#dateTimeInstance()) protected static Converts non null expiry value into DateTimeInterface instance. * ##### [getDomain()](#getDomain()) public Get the domain attribute. * ##### [getExpiresTimestamp()](#getExpiresTimestamp()) public Get the timestamp from the expiration time * ##### [getExpiry()](#getExpiry()) public Get the current expiry time * ##### [getFormattedExpires()](#getFormattedExpires()) public Builds the expiration value part of the header string * ##### [getId()](#getId()) public Get the id for a cookie * ##### [getName()](#getName()) public Gets the cookie name * ##### [getOptions()](#getOptions()) public Get cookie options * ##### [getPath()](#getPath()) public Get the path attribute. * ##### [getSameSite()](#getSameSite()) public Get the SameSite attribute. * ##### [getScalarValue()](#getScalarValue()) public Gets the cookie value as scalar. * ##### [getStringValue()](#getStringValue()) public deprecated Gets the cookie value as a string. * ##### [getValue()](#getValue()) public Gets the cookie value * ##### [isExpanded()](#isExpanded()) public Checks if the cookie value was expanded * ##### [isExpired()](#isExpired()) public Check if a cookie is expired when compared to $time * ##### [isHttpOnly()](#isHttpOnly()) public Check if the cookie is HTTP only * ##### [isSecure()](#isSecure()) public Check if the cookie is secure * ##### [read()](#read()) public Read data from the cookie * ##### [setDefaults()](#setDefaults()) public static Set default options for the cookies. * ##### [toArray()](#toArray()) public Get cookie data as array. * ##### [toHeaderValue()](#toHeaderValue()) public Returns a header value as string * ##### [validateName()](#validateName()) protected Validates the cookie name * ##### [validateSameSiteValue()](#validateSameSiteValue()) protected static Check that value passed for SameSite is valid. * ##### [withAddedValue()](#withAddedValue()) public Create a new cookie with updated data. * ##### [withDomain()](#withDomain()) public Create a cookie with an updated domain * ##### [withExpired()](#withExpired()) public Create a new cookie that will expire/delete the cookie from the browser. * ##### [withExpiry()](#withExpiry()) public Create a cookie with an updated expiration date * ##### [withHttpOnly()](#withHttpOnly()) public Create a cookie with HTTP Only updated * ##### [withName()](#withName()) public Sets the cookie name * ##### [withNeverExpire()](#withNeverExpire()) public Create a new cookie that will virtually never expire. * ##### [withPath()](#withPath()) public Create a new cookie with an updated path * ##### [withSameSite()](#withSameSite()) public Create a cookie with an updated SameSite option. * ##### [withSecure()](#withSecure()) public Create a cookie with Secure updated * ##### [withValue()](#withValue()) public Create a cookie with an updated value. * ##### [withoutAddedValue()](#withoutAddedValue()) public Create a new cookie without a specific path Method Detail ------------- ### \_\_construct() public ``` __construct(string $name, array|string $value = '', DateTimeDateTimeImmutable|null $expiresAt = null, string|null $path = null, string|null $domain = null, bool|null $secure = null, bool|null $httpOnly = null, string|null $sameSite = null) ``` Constructor The constructors args are similar to the native PHP `setcookie()` method. The only difference is the 3rd argument which excepts null or an DateTime or DateTimeImmutable object instead an integer. #### Parameters `string` $name Cookie name `array|string` $value optional Value of the cookie `DateTimeDateTimeImmutable|null` $expiresAt optional Expiration time and date `string|null` $path optional Path `string|null` $domain optional Domain `bool|null` $secure optional Is secure `bool|null` $httpOnly optional HTTP Only `string|null` $sameSite optional Samesite #### Links https://php.net/manual/en/function.setcookie.php ### \_expand() protected ``` _expand(string $string): array|string ``` Explode method to return array from string set in CookieComponent::\_flatten() Maintains reading backwards compatibility with 1.x CookieComponent::\_flatten(). #### Parameters `string` $string A string containing JSON encoded data, or a bare string. #### Returns `array|string` ### \_flatten() protected ``` _flatten(array $array): string ``` Implode method to keep keys are multidimensional arrays #### Parameters `array` $array Map of key and values #### Returns `string` ### \_setValue() protected ``` _setValue(array|string $value): void ``` Setter for the value attribute. #### Parameters `array|string` $value The value to store. #### Returns `void` ### check() public ``` check(string $path): bool ``` Checks if a value exists in the cookie data. This method will expand serialized complex data, on first use. #### Parameters `string` $path Path to check #### Returns `bool` ### create() public static ``` create(string $name, array|string $value, array<string, mixed> $options = []): static ``` Factory method to create Cookie instances. #### Parameters `string` $name Cookie name `array|string` $value Value of the cookie `array<string, mixed>` $options optional Cookies options. #### Returns `static` #### See Also \Cake\Cookie\Cookie::setDefaults() ### createFromHeaderString() public static ``` createFromHeaderString(string $cookie, array<string, mixed> $defaults = []): static ``` Create Cookie instance from "set-cookie" header string. #### Parameters `string` $cookie Cookie header string. `array<string, mixed>` $defaults optional Default attributes. #### Returns `static` #### See Also \Cake\Http\Cookie\Cookie::setDefaults() ### dateTimeInstance() protected static ``` dateTimeInstance(mixed $expires): DateTimeDatetimeImmutable|null ``` Converts non null expiry value into DateTimeInterface instance. #### Parameters `mixed` $expires Expiry value. #### Returns `DateTimeDatetimeImmutable|null` ### getDomain() public ``` getDomain(): string ``` Get the domain attribute. #### Returns `string` ### getExpiresTimestamp() public ``` getExpiresTimestamp(): int|null ``` Get the timestamp from the expiration time #### Returns `int|null` ### getExpiry() public ``` getExpiry(): DateTimeDateTimeImmutable|null ``` Get the current expiry time #### Returns `DateTimeDateTimeImmutable|null` ### getFormattedExpires() public ``` getFormattedExpires(): string ``` Builds the expiration value part of the header string #### Returns `string` ### getId() public ``` getId(): string ``` Get the id for a cookie Cookies are unique across name, domain, path tuples. #### Returns `string` ### getName() public ``` getName(): string ``` Gets the cookie name #### Returns `string` ### getOptions() public ``` getOptions(): array<string, mixed> ``` Get cookie options #### Returns `array<string, mixed>` ### getPath() public ``` getPath(): string ``` Get the path attribute. #### Returns `string` ### getSameSite() public ``` getSameSite(): string|null ``` Get the SameSite attribute. #### Returns `string|null` ### getScalarValue() public ``` getScalarValue(): mixed ``` Gets the cookie value as scalar. This will collapse any complex data in the cookie with json\_encode() #### Returns `mixed` ### getStringValue() public ``` getStringValue(): mixed ``` Gets the cookie value as a string. This will collapse any complex data in the cookie with json\_encode() #### Returns `mixed` ### getValue() public ``` getValue(): array|string ``` Gets the cookie value #### Returns `array|string` ### isExpanded() public ``` isExpanded(): bool ``` Checks if the cookie value was expanded #### Returns `bool` ### isExpired() public ``` isExpired(DateTimeDateTimeImmutable $time = null): bool ``` Check if a cookie is expired when compared to $time Cookies without an expiration date always return false. #### Parameters `DateTimeDateTimeImmutable` $time optional #### Returns `bool` ### isHttpOnly() public ``` isHttpOnly(): bool ``` Check if the cookie is HTTP only #### Returns `bool` ### isSecure() public ``` isSecure(): bool ``` Check if the cookie is secure #### Returns `bool` ### read() public ``` read(string|null $path = null): mixed ``` Read data from the cookie This method will expand serialized complex data, on first use. #### Parameters `string|null` $path optional Path to read the data from #### Returns `mixed` ### setDefaults() public static ``` setDefaults(array<string, mixed> $options): void ``` Set default options for the cookies. Valid option keys are: * `expires`: Can be a UNIX timestamp or `strtotime()` compatible string or `DateTimeInterface` instance or `null`. * `path`: A path string. Defauts to `'/'`. * `domain`: Domain name string. Defaults to `''`. * `httponly`: Boolean. Defaults to `false`. * `secure`: Boolean. Defaults to `false`. * `samesite`: Can be one of `CookieInterface::SAMESITE_LAX`, `CookieInterface::SAMESITE_STRICT`, `CookieInterface::SAMESITE_NONE` or `null`. Defaults to `null`. #### Parameters `array<string, mixed>` $options Default options. #### Returns `void` ### toArray() public ``` toArray(): array<string, mixed> ``` Get cookie data as array. #### Returns `array<string, mixed>` ### toHeaderValue() public ``` toHeaderValue(): string ``` Returns a header value as string #### Returns `string` ### validateName() protected ``` validateName(string $name): void ``` Validates the cookie name #### Parameters `string` $name Name of the cookie #### Returns `void` #### Throws `InvalidArgumentException` #### Links https://tools.ietf.org/html/rfc2616#section-2.2 Rules for naming cookies. ### validateSameSiteValue() protected static ``` validateSameSiteValue(string $sameSite): void ``` Check that value passed for SameSite is valid. #### Parameters `string` $sameSite SameSite value #### Returns `void` #### Throws `InvalidArgumentException` ### withAddedValue() public ``` withAddedValue(string $path, mixed $value): static ``` Create a new cookie with updated data. #### Parameters `string` $path Path to write to `mixed` $value Value to write #### Returns `static` ### withDomain() public ``` withDomain(string $domain): static ``` Create a cookie with an updated domain #### Parameters `string` $domain #### Returns `static` ### withExpired() public ``` withExpired(): static ``` Create a new cookie that will expire/delete the cookie from the browser. This is done by setting the expiration time to 1 year ago #### Returns `static` ### withExpiry() public ``` withExpiry(DateTimeDateTimeImmutable $dateTime): static ``` Create a cookie with an updated expiration date #### Parameters `DateTimeDateTimeImmutable` $dateTime #### Returns `static` ### withHttpOnly() public ``` withHttpOnly(bool $httpOnly): static ``` Create a cookie with HTTP Only updated #### Parameters `bool` $httpOnly #### Returns `static` ### withName() public ``` withName(string $name): static ``` Sets the cookie name #### Parameters `string` $name #### Returns `static` ### withNeverExpire() public ``` withNeverExpire(): static ``` Create a new cookie that will virtually never expire. #### Returns `static` ### withPath() public ``` withPath(string $path): static ``` Create a new cookie with an updated path #### Parameters `string` $path #### Returns `static` ### withSameSite() public ``` withSameSite(string|null $sameSite): static ``` Create a cookie with an updated SameSite option. #### Parameters `string|null` $sameSite #### Returns `static` ### withSecure() public ``` withSecure(bool $secure): static ``` Create a cookie with Secure updated #### Parameters `bool` $secure #### Returns `static` ### withValue() public ``` withValue(array|string $value): static ``` Create a cookie with an updated value. #### Parameters `array|string` $value #### Returns `static` ### withoutAddedValue() public ``` withoutAddedValue(string $path): static ``` Create a new cookie without a specific path #### Parameters `string` $path Path to remove #### Returns `static` Property Detail --------------- ### $defaults protected static Default attributes for a cookie. #### Type `array<string, mixed>` ### $domain protected Domain #### Type `string` ### $expiresAt protected Expiration time #### Type `DateTimeDateTimeImmutable|null` ### $httpOnly protected HTTP only #### Type `bool` ### $isExpanded protected Whether a JSON value has been expanded into an array. #### Type `bool` ### $name protected Cookie name #### Type `string` ### $path protected Path #### Type `string` ### $sameSite protected Samesite #### Type `string|null` ### $secure protected Secure #### Type `bool` ### $value protected Raw Cookie value. #### Type `array|string`
programming_docs
cakephp Class Controller Class Controller ================= Application controller class for organization of business logic. Provides basic functionality, such as rendering views inside layouts, automatic model availability, redirection, callbacks, and more. Controllers should provide a number of 'action' methods. These are public methods on a controller that are not inherited from `Controller`. Each action serves as an endpoint for performing a specific action on a resource or collection of resources. For example adding or editing a new object, or listing a set of objects. You can access request parameters, using `$this->getRequest()`. The request object contains all the POST, GET and FILES that were part of the request. After performing the required action, controllers are responsible for creating a response. This usually takes the form of a generated `View`, or possibly a redirection to another URL. In either case `$this->getResponse()` allows you to manipulate all aspects of the response. Controllers are created based on request parameters and routing. By default controllers and actions use conventional names. For example `/posts/index` maps to `PostsController::index()`. You can re-map URLs using Router::connect() or RouteBuilder::connect(). ### Life cycle callbacks CakePHP fires a number of life cycle callbacks during each request. By implementing a method you can receive the related events. The available callbacks are: * `beforeFilter(EventInterface $event)` Called before each action. This is a good place to do general logic that applies to all actions. * `beforeRender(EventInterface $event)` Called before the view is rendered. * `beforeRedirect(EventInterface $event, $url, Response $response)` Called before a redirect is done. * `afterFilter(EventInterface $event)` Called after each action is complete and after the view is rendered. **Namespace:** [Cake\Controller](namespace-cake.controller) **Link:** https://book.cakephp.org/4/en/controllers.html Property Summary ---------------- * [$Auth](#%24Auth) public @property `Cake\Controller\Component\AuthComponent` * [$Flash](#%24Flash) public @property `Cake\Controller\Component\FlashComponent` * [$FormProtection](#%24FormProtection) public @property `Cake\Controller\Component\FormProtectionComponent` * [$Paginator](#%24Paginator) public @property `Cake\Controller\Component\PaginatorComponent` * [$RequestHandler](#%24RequestHandler) public @property `Cake\Controller\Component\RequestHandlerComponent` * [$Security](#%24Security) public @property `Cake\Controller\Component\SecurityComponent` * [$\_components](#%24_components) protected `Cake\Controller\ComponentRegistry|null` Instance of ComponentRegistry used to create Components * [$\_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. * [$\_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 * [$\_viewBuilder](#%24_viewBuilder) protected `Cake\View\ViewBuilder|null` The view builder instance being used. * [$autoRender](#%24autoRender) protected `bool` Set to true to automatically render the view after action logic. * [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias. * [$middlewares](#%24middlewares) protected `array` Middlewares list. * [$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 controller. Controller names are plural, named after the model they manipulate. * [$paginate](#%24paginate) public `array` Settings for pagination. * [$plugin](#%24plugin) protected `string|null` Automatically set to the name of a 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` An instance of a Response object that contains information about the impending response Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [\_\_get()](#__get()) public Magic accessor for model autoloading. * ##### [\_\_set()](#__set()) public Magic setter for removed properties. * ##### [\_setModelClass()](#_setModelClass()) protected Set the modelClass property based on conventions. * ##### [\_templatePath()](#_templatePath()) protected Get the templatePath based on controller name and request prefix. * ##### [afterFilter()](#afterFilter()) public Called after the controller action is run and rendered. * ##### [beforeFilter()](#beforeFilter()) public Called before the controller action. You can use this method to configure and customize components or perform logic that needs to happen before each controller action. * ##### [beforeRedirect()](#beforeRedirect()) public The beforeRedirect method is invoked when the controller's redirect method is called but before any further action. * ##### [beforeRender()](#beforeRender()) public Called after the controller action is run, but before the view is rendered. You can use this method to perform logic or set view variables that are required on every request. * ##### [chooseViewClass()](#chooseViewClass()) protected Use the view classes defined on this controller to view selection based on content-type negotiation. * ##### [components()](#components()) public Get the component registry for this controller. * ##### [createView()](#createView()) public Constructs the view class instance based on the current configuration. * ##### [disableAutoRender()](#disableAutoRender()) public Disable automatic action rendering. * ##### [dispatchEvent()](#dispatchEvent()) public Wrapper for creating and dispatching events. * ##### [enableAutoRender()](#enableAutoRender()) public Enable automatic action rendering. * ##### [fetchTable()](#fetchTable()) public Convenience method to get a table instance. * ##### [getAction()](#getAction()) public Get the closure for action to be invoked by ControllerFactory. * ##### [getEventManager()](#getEventManager()) public Returns the Cake\Event\EventManager manager instance for this object. * ##### [getMiddleware()](#getMiddleware()) public Get middleware to be applied for this controller. * ##### [getModelType()](#getModelType()) public Get the model type to be used by this class * ##### [getName()](#getName()) public Returns the controller name. * ##### [getPlugin()](#getPlugin()) public Returns the plugin name. * ##### [getRequest()](#getRequest()) public Gets the request instance. * ##### [getResponse()](#getResponse()) public Gets the response instance. * ##### [getTableLocator()](#getTableLocator()) public Gets the table locator. * ##### [implementedEvents()](#implementedEvents()) public Returns a list of all events that will fire in the controller during its lifecycle. You can override this function to add your own listener callbacks * ##### [initialize()](#initialize()) public Initialization hook method. * ##### [invokeAction()](#invokeAction()) public Dispatches the controller action. * ##### [isAction()](#isAction()) public Method to check that an action is accessible from a URL. * ##### [isAutoRenderEnabled()](#isAutoRenderEnabled()) public Returns true if an action should be rendered automatically. * ##### [loadComponent()](#loadComponent()) public Add a component to the controller's registry. * ##### [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. * ##### [middleware()](#middleware()) public Register middleware for the controller. * ##### [modelFactory()](#modelFactory()) public Override a existing callable to generate repositories of a given type. * ##### [paginate()](#paginate()) public Handles pagination of records in Table objects. * ##### [redirect()](#redirect()) public Redirects to given $url, after turning off $this->autoRender. * ##### [referer()](#referer()) public Returns the referring URL for this request. * ##### [render()](#render()) public Instantiates the correct view class, hands it its data, and uses it to render the view output. * ##### [set()](#set()) public Saves a variable or an associative array of variables for use inside a template. * ##### [setAction()](#setAction()) public deprecated Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect() * ##### [setEventManager()](#setEventManager()) public Returns the Cake\Event\EventManagerInterface instance for this object. * ##### [setModelType()](#setModelType()) public Set the model type to be used by this class * ##### [setName()](#setName()) public Sets the controller name. * ##### [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. Controller acts as a proxy for certain View variables which must also be updated here. The properties that get set are: * ##### [setResponse()](#setResponse()) public Sets the response instance. * ##### [setTableLocator()](#setTableLocator()) public Sets the table locator. * ##### [shutdownProcess()](#shutdownProcess()) public Perform the various shutdown processes for this controller. Fire the Components and Controller callbacks in the correct order. * ##### [startupProcess()](#startupProcess()) public Perform the startup process for this controller. Fire the Components and Controller callbacks in the correct order. * ##### [viewBuilder()](#viewBuilder()) public Get the view builder being used. * ##### [viewClasses()](#viewClasses()) public Get the View classes this controller can perform content negotiation with. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\Http\ServerRequest|null $request = null, Cake\Http\Response|null $response = null, string|null $name = null, Cake\Event\EventManagerInterface|null $eventManager = null, Cake\Controller\ComponentRegistry|null $components = null) ``` Constructor. Sets a number of properties based on conventions if they are empty. To override the conventions CakePHP uses you can define properties in your class declaration. #### Parameters `Cake\Http\ServerRequest|null` $request optional Request object for this controller. Can be null for testing, but expect that features that use the request parameters will not work. `Cake\Http\Response|null` $response optional Response object for this controller. `string|null` $name optional Override the name useful in testing when using mocks. `Cake\Event\EventManagerInterface|null` $eventManager optional The event manager. Defaults to a new instance. `Cake\Controller\ComponentRegistry|null` $components optional The component registry. Defaults to a new instance. ### \_\_get() public ``` __get(string $name): Cake\Datasource\RepositoryInterface|null ``` Magic accessor for model autoloading. #### Parameters `string` $name Property name #### Returns `Cake\Datasource\RepositoryInterface|null` ### \_\_set() public ``` __set(string $name, mixed $value): void ``` Magic setter for removed properties. #### Parameters `string` $name Property name. `mixed` $value Value to set. #### 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` ### \_templatePath() protected ``` _templatePath(): string ``` Get the templatePath based on controller name and request prefix. #### Returns `string` ### afterFilter() public ``` afterFilter(Cake\Event\EventInterface $event): Cake\Http\Response|null|void ``` Called after the controller action is run and rendered. #### Parameters `Cake\Event\EventInterface` $event An Event instance #### Returns `Cake\Http\Response|null|void` #### Links https://book.cakephp.org/4/en/controllers.html#request-life-cycle-callbacks ### beforeFilter() public ``` beforeFilter(Cake\Event\EventInterface $event): Cake\Http\Response|null|void ``` Called before the controller action. You can use this method to configure and customize components or perform logic that needs to happen before each controller action. #### Parameters `Cake\Event\EventInterface` $event An Event instance #### Returns `Cake\Http\Response|null|void` #### Links https://book.cakephp.org/4/en/controllers.html#request-life-cycle-callbacks ### beforeRedirect() public ``` beforeRedirect(Cake\Event\EventInterface $event, array|string $url, Cake\Http\Response $response): Cake\Http\Response|null|void ``` The beforeRedirect method is invoked when the controller's redirect method is called but before any further action. If the event is stopped the controller will not continue on to redirect the request. The $url and $status variables have same meaning as for the controller's method. You can set the event result to response instance or modify the redirect location using controller's response instance. #### Parameters `Cake\Event\EventInterface` $event An Event instance `array|string` $url A string or array-based URL pointing to another location within the app, or an absolute URL `Cake\Http\Response` $response The response object. #### Returns `Cake\Http\Response|null|void` #### Links https://book.cakephp.org/4/en/controllers.html#request-life-cycle-callbacks ### beforeRender() public ``` beforeRender(Cake\Event\EventInterface $event): Cake\Http\Response|null|void ``` Called after the controller action is run, but before the view is rendered. You can use this method to perform logic or set view variables that are required on every request. #### Parameters `Cake\Event\EventInterface` $event An Event instance #### Returns `Cake\Http\Response|null|void` #### Links https://book.cakephp.org/4/en/controllers.html#request-life-cycle-callbacks ### chooseViewClass() protected ``` chooseViewClass(): string|null ``` Use the view classes defined on this controller to view selection based on content-type negotiation. #### Returns `string|null` ### components() public ``` components(Cake\Controller\ComponentRegistry|null $components = null): Cake\Controller\ComponentRegistry ``` Get the component registry for this controller. If called with the first parameter, it will be set as the controller $this->\_components property #### Parameters `Cake\Controller\ComponentRegistry|null` $components optional Component registry. #### Returns `Cake\Controller\ComponentRegistry` ### createView() public ``` createView(string|null $viewClass = null): Cake\View\View ``` Constructs the view class instance based on the current configuration. #### Parameters `string|null` $viewClass optional Optional namespaced class name of the View class to instantiate. #### Returns `Cake\View\View` #### Throws `Cake\View\Exception\MissingViewException` If view class was not found. ### disableAutoRender() public ``` disableAutoRender(): $this ``` Disable automatic action rendering. #### 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` ### enableAutoRender() public ``` enableAutoRender(): $this ``` Enable automatic action rendering. #### 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() ### getAction() public ``` getAction(): Closure ``` Get the closure for action to be invoked by ControllerFactory. #### Returns `Closure` #### Throws `Cake\Controller\Exception\MissingActionException` ### 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` ### getMiddleware() public ``` getMiddleware(): array ``` Get middleware to be applied for this controller. #### Returns `array` ### getModelType() public ``` getModelType(): string ``` Get the model type to be used by this class #### Returns `string` ### getName() public ``` getName(): string ``` Returns the 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` ### getTableLocator() public ``` getTableLocator(): Cake\ORM\Locator\LocatorInterface ``` Gets the table locator. #### Returns `Cake\ORM\Locator\LocatorInterface` ### implementedEvents() public ``` implementedEvents(): array<string, mixed> ``` Returns a list of all events that will fire in the controller during its lifecycle. You can override this function to add your own listener callbacks ### Example: ``` public function implementedEvents() { return [ 'Order.complete' => 'sendEmail', 'Article.afterBuy' => 'decrementInventory', 'User.onRegister' => ['callable' => 'logRegistration', 'priority' => 20, 'passParams' => true] ]; } ``` #### Returns `array<string, mixed>` ### initialize() public ``` initialize(): void ``` Initialization hook method. Implement this method to avoid having to overwrite the constructor and call parent. #### Returns `void` ### invokeAction() public ``` invokeAction(Closure $action, array $args): void ``` Dispatches the controller action. #### Parameters `Closure` $action The action closure. `array` $args The arguments to be passed when invoking action. #### Returns `void` #### Throws `UnexpectedValueException` If return value of action is not `null` or `ResponseInterface` instance. ### isAction() public ``` isAction(string $action): bool ``` Method to check that an action is accessible from a URL. Override this method to change which controller methods can be reached. The default implementation disallows access to all methods defined on Cake\Controller\Controller, and allows all public methods on all subclasses of this class. #### Parameters `string` $action The action to check. #### Returns `bool` #### Throws `ReflectionException` ### isAutoRenderEnabled() public ``` isAutoRenderEnabled(): bool ``` Returns true if an action should be rendered automatically. #### Returns `bool` ### loadComponent() public ``` loadComponent(string $name, array<string, mixed> $config = []): Cake\Controller\Component ``` Add a component to the controller's registry. This method will also set the component to a property. For example: ``` $this->loadComponent('Authentication.Authentication'); ``` Will result in a `Authentication` property being set. #### Parameters `string` $name The name of the component to load. `array<string, mixed>` $config optional The config for the component. #### Returns `Cake\Controller\Component` #### Throws `Exception` ### 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` ### middleware() public ``` middleware(Psr\Http\Server\MiddlewareInterfaceClosure|string $middleware, array<string, mixed> $options = []): void ``` Register middleware for the controller. #### Parameters `Psr\Http\Server\MiddlewareInterfaceClosure|string` $middleware Middleware. `array<string, mixed>` $options optional Valid options: * `only`: (array|string) Only run the middleware for specified actions. * `except`: (array|string) Run the middleware for all actions except the specified ones. #### Returns `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` ### paginate() public ``` paginate(Cake\ORM\TableCake\ORM\Query|string|null $object = null, array<string, mixed> $settings = []): Cake\ORM\ResultSetCake\Datasource\ResultSetInterface ``` Handles pagination of records in Table objects. Will load the referenced Table object, and have the paginator paginate the query using the request date and settings defined in `$this->paginate`. This method will also make the PaginatorHelper available in the view. #### Parameters `Cake\ORM\TableCake\ORM\Query|string|null` $object optional Table to paginate (e.g: Table instance, 'TableName' or a Query object) `array<string, mixed>` $settings optional The settings/configuration used for pagination. #### Returns `Cake\ORM\ResultSetCake\Datasource\ResultSetInterface` #### Throws `RuntimeException` When no compatible table object can be found. #### Links https://book.cakephp.org/4/en/controllers.html#paginating-a-model ### redirect() public ``` redirect(Psr\Http\Message\UriInterface|array|string $url, int $status = 302): Cake\Http\Response|null ``` Redirects to given $url, after turning off $this->autoRender. #### Parameters `Psr\Http\Message\UriInterface|array|string` $url A string, array-based URL or UriInterface instance. `int` $status optional HTTP status code. Defaults to `302`. #### Returns `Cake\Http\Response|null` #### Links https://book.cakephp.org/4/en/controllers.html#Controller::redirect ### referer() public ``` referer(array|string|null $default = '/', bool $local = true): string ``` Returns the referring URL for this request. #### Parameters `array|string|null` $default optional Default URL to use if HTTP\_REFERER cannot be read from headers `bool` $local optional If false, do not restrict referring URLs to local server. Careful with trusting external sources. #### Returns `string` ### render() public ``` render(string|null $template = null, string|null $layout = null): Cake\Http\Response ``` Instantiates the correct view class, hands it its data, and uses it to render the view output. #### Parameters `string|null` $template optional Template to use for rendering `string|null` $layout optional Layout to use #### Returns `Cake\Http\Response` #### Links https://book.cakephp.org/4/en/controllers.html#rendering-a-view ### 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` ### setAction() public ``` setAction(string $action, mixed ...$args): mixed ``` Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect() Examples: ``` setAction('another_action'); setAction('action_with_parameters', $parameter1); ``` #### Parameters `string` $action The new action to be 'redirected' to. Any other parameters passed to this method will be passed as parameters to the new action. `mixed` ...$args Arguments passed to the action #### Returns `mixed` ### 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` ### 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 ``` Sets the controller name. #### Parameters `string` $name Controller name. #### 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. Controller acts as a proxy for certain View variables which must also be updated here. The properties that get set are: * $this->request - To the $request parameter #### 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` ### setTableLocator() public ``` setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this ``` Sets the table locator. #### Parameters `Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance. #### Returns `$this` ### shutdownProcess() public ``` shutdownProcess(): Psr\Http\Message\ResponseInterface|null ``` Perform the various shutdown processes for this controller. Fire the Components and Controller callbacks in the correct order. * triggers the component `shutdown` callback. * calls the Controller's `afterFilter` method. #### Returns `Psr\Http\Message\ResponseInterface|null` ### startupProcess() public ``` startupProcess(): Psr\Http\Message\ResponseInterface|null ``` Perform the startup process for this controller. Fire the Components and Controller callbacks in the correct order. * Initializes components, which fires their `initialize` callback * Calls the controller `beforeFilter`. * triggers Component `startup` methods. #### Returns `Psr\Http\Message\ResponseInterface|null` ### viewBuilder() public ``` viewBuilder(): Cake\View\ViewBuilder ``` Get the view builder being used. #### Returns `Cake\View\ViewBuilder` ### viewClasses() public ``` viewClasses(): array<string> ``` Get the View classes this controller can perform content negotiation with. Each view class must implement the `getContentType()` hook method to participate in negotiation. #### Returns `array<string>` #### See Also Cake\Http\ContentTypeNegotiation Property Detail --------------- ### $Auth public @property #### Type `Cake\Controller\Component\AuthComponent` ### $Flash public @property #### Type `Cake\Controller\Component\FlashComponent` ### $FormProtection public @property #### Type `Cake\Controller\Component\FormProtectionComponent` ### $Paginator public @property #### Type `Cake\Controller\Component\PaginatorComponent` ### $RequestHandler public @property #### Type `Cake\Controller\Component\RequestHandlerComponent` ### $Security public @property #### Type `Cake\Controller\Component\SecurityComponent` ### $\_components protected Instance of ComponentRegistry used to create Components #### Type `Cake\Controller\ComponentRegistry|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` ### $\_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` ### $\_viewBuilder protected The view builder instance being used. #### Type `Cake\View\ViewBuilder|null` ### $autoRender protected Set to true to automatically render the view after action logic. #### Type `bool` ### $defaultTable protected This object's default table alias. #### Type `string|null` ### $middlewares protected Middlewares list. #### Type `array` ### $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 controller. Controller names are plural, named after the model they manipulate. Set automatically using conventions in Controller::\_\_construct(). #### Type `string` ### $paginate public Settings for pagination. Used to pre-configure pagination preferences for the various tables your controller will be paginating. #### Type `array` ### $plugin protected Automatically set to the name of a 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 An instance of a Response object that contains information about the impending response #### Type `Cake\Http\Response`
programming_docs
cakephp Class RulesProvider Class 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 **Namespace:** [Cake\Validation](namespace-cake.validation) Property Summary ---------------- * [$\_class](#%24_class) protected `object|string` The class/object to proxy. * [$\_reflection](#%24_reflection) protected `ReflectionClass` The proxied class' reflection Method Summary -------------- * ##### [\_\_call()](#__call()) public Proxies validation method calls to the Validation class. * ##### [\_\_construct()](#__construct()) public Constructor, sets the default class to use for calling methods * ##### [extension()](#extension()) public @method Method Detail ------------- ### \_\_call() public ``` __call(string $method, array $arguments): bool ``` Proxies validation method calls to the Validation class. The last argument (context) will be sliced off, if the validation method's last parameter is not named 'context'. This lets the various wrapped validation methods to not receive the validation context unless they need it. #### Parameters `string` $method the validation method to call `array` $arguments the list of arguments to pass to the method #### Returns `bool` ### \_\_construct() public ``` __construct(object|string $class = Validation::class) ``` Constructor, sets the default class to use for calling methods #### Parameters `object|string` $class optional the default class to proxy #### Throws `ReflectionException` ### extension() public @method ``` extension(mixed $check, array $extensions, array $context = []): bool ``` #### Parameters `mixed` $check `array` $extensions `array` $context optional #### Returns `bool` Property Detail --------------- ### $\_class protected The class/object to proxy. #### Type `object|string` ### $\_reflection protected The proxied class' reflection #### Type `ReflectionClass` cakephp Class NumericPaginator Class NumericPaginator ======================= This class is used to handle automatic model data pagination. **Namespace:** [Cake\Datasource\Paging](namespace-cake.datasource.paging) 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 pagination settings. * [$\_pagingParams](#%24_pagingParams) protected `array<string, array>` Paging params after pagination operation is done. Method Summary -------------- * ##### [\_configDelete()](#_configDelete()) protected Deletes a single config key. * ##### [\_configRead()](#_configRead()) protected Reads a config key. * ##### [\_configWrite()](#_configWrite()) protected Writes a config key. * ##### [\_extractFinder()](#_extractFinder()) protected Extracts the finder name and options out of the provided pagination options. * ##### [\_prefix()](#_prefix()) protected Prefixes the field with the table alias if possible. * ##### [\_removeAliases()](#_removeAliases()) protected Remove alias if needed. * ##### [addPageCountParams()](#addPageCountParams()) protected Add "page" and "pageCount" params. * ##### [addPrevNextParams()](#addPrevNextParams()) protected Add "prevPage" and "nextPage" params. * ##### [addSortingParams()](#addSortingParams()) protected Add sorting / ordering params. * ##### [addStartEndParams()](#addStartEndParams()) protected Add "start" and "end" params. * ##### [buildParams()](#buildParams()) protected Build pagination params. * ##### [checkLimit()](#checkLimit()) public Check the limit parameter and ensure it's within the maxLimit bounds. * ##### [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. * ##### [extractData()](#extractData()) protected Extract pagination data needed * ##### [getAllowedParameters()](#getAllowedParameters()) protected Shim method for reading the deprecated whitelist or allowedParameters options * ##### [getConfig()](#getConfig()) public Returns the config. * ##### [getConfigOrFail()](#getConfigOrFail()) public Returns the config for this specific key. * ##### [getCount()](#getCount()) protected Get total count of records. * ##### [getDefaults()](#getDefaults()) public Get the settings for a $model. If there are no settings for a specific repository, the general settings will be used. * ##### [getPagingParams()](#getPagingParams()) public Get paging params after pagination operation. * ##### [getQuery()](#getQuery()) protected Get query for fetching paginated results. * ##### [getSortableFields()](#getSortableFields()) protected Shim method for reading the deprecated sortWhitelist or sortableFields options. * ##### [mergeOptions()](#mergeOptions()) public Merges the various options that Paginator uses. Pulls settings together from the following places: * ##### [paginate()](#paginate()) public Handles automatic pagination of model records. * ##### [setConfig()](#setConfig()) public Sets the config. * ##### [validateSort()](#validateSort()) public Validate that the desired sorting can be performed on the $object. 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 ### \_extractFinder() protected ``` _extractFinder(array<string, mixed> $options): array ``` Extracts the finder name and options out of the provided pagination options. #### Parameters `array<string, mixed>` $options the pagination options. #### Returns `array` ### \_prefix() protected ``` _prefix(Cake\Datasource\RepositoryInterface $object, array $order, bool $allowed = false): array ``` Prefixes the field with the table alias if possible. #### Parameters `Cake\Datasource\RepositoryInterface` $object Repository object. `array` $order Order array. `bool` $allowed optional Whether the field was allowed. #### Returns `array` ### \_removeAliases() protected ``` _removeAliases(array<string, mixed> $fields, string $model): array<string, mixed> ``` Remove alias if needed. #### Parameters `array<string, mixed>` $fields Current fields `string` $model Current model alias #### Returns `array<string, mixed>` ### addPageCountParams() protected ``` addPageCountParams(array<string, mixed> $params, array $data): array<string, mixed> ``` Add "page" and "pageCount" params. #### Parameters `array<string, mixed>` $params Paging params. `array` $data Paginator data. #### Returns `array<string, mixed>` ### addPrevNextParams() protected ``` addPrevNextParams(array<string, mixed> $params, array $data): array<string, mixed> ``` Add "prevPage" and "nextPage" params. #### Parameters `array<string, mixed>` $params Paginator params. `array` $data Paging data. #### Returns `array<string, mixed>` ### addSortingParams() protected ``` addSortingParams(array<string, mixed> $params, array $data): array<string, mixed> ``` Add sorting / ordering params. #### Parameters `array<string, mixed>` $params Paginator params. `array` $data Paging data. #### Returns `array<string, mixed>` ### addStartEndParams() protected ``` addStartEndParams(array<string, mixed> $params, array $data): array<string, mixed> ``` Add "start" and "end" params. #### Parameters `array<string, mixed>` $params Paging params. `array` $data Paginator data. #### Returns `array<string, mixed>` ### buildParams() protected ``` buildParams(array<string, mixed> $data): array<string, mixed> ``` Build pagination params. #### Parameters `array<string, mixed>` $data Paginator data containing keys 'options', 'count', 'defaults', 'finder', 'numResults'. #### Returns `array<string, mixed>` ### checkLimit() public ``` checkLimit(array<string, mixed> $options): array<string, mixed> ``` Check the limit parameter and ensure it's within the maxLimit bounds. #### Parameters `array<string, mixed>` $options An array of options with a limit key to be checked. #### 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` ### extractData() protected ``` extractData(Cake\Datasource\RepositoryInterface $object, array<string, mixed> $params, array<string, mixed> $settings): array ``` Extract pagination data needed #### Parameters `Cake\Datasource\RepositoryInterface` $object The repository object. `array<string, mixed>` $params Request params `array<string, mixed>` $settings The settings/configuration used for pagination. #### Returns `array` ### getAllowedParameters() protected ``` getAllowedParameters(): array<string> ``` Shim method for reading the deprecated whitelist or allowedParameters options #### Returns `array<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` ### getCount() protected ``` getCount(Cake\Datasource\QueryInterface $query, array $data): int|null ``` Get total count of records. #### Parameters `Cake\Datasource\QueryInterface` $query Query instance. `array` $data Pagination data. #### Returns `int|null` ### getDefaults() public ``` getDefaults(string $alias, array<string, mixed> $settings): array<string, mixed> ``` Get the settings for a $model. If there are no settings for a specific repository, the general settings will be used. #### Parameters `string` $alias Model name to get settings for. `array<string, mixed>` $settings The settings which is used for combining. #### Returns `array<string, mixed>` ### getPagingParams() public ``` getPagingParams(): array<string, array> ``` Get paging params after pagination operation. #### Returns `array<string, array>` ### getQuery() protected ``` getQuery(Cake\Datasource\RepositoryInterface $object, Cake\Datasource\QueryInterface|null $query, array<string, mixed> $data): Cake\Datasource\QueryInterface ``` Get query for fetching paginated results. #### Parameters `Cake\Datasource\RepositoryInterface` $object Repository instance. `Cake\Datasource\QueryInterface|null` $query Query Instance. `array<string, mixed>` $data Pagination data. #### Returns `Cake\Datasource\QueryInterface` ### getSortableFields() protected ``` getSortableFields(array<string, mixed> $config): array<string>|null ``` Shim method for reading the deprecated sortWhitelist or sortableFields options. #### Parameters `array<string, mixed>` $config The configuration data to coalesce and emit warnings on. #### Returns `array<string>|null` ### mergeOptions() public ``` mergeOptions(array<string, mixed> $params, array $settings): array<string, mixed> ``` Merges the various options that Paginator 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 `array<string, mixed>` $params Request params. `array` $settings The settings to merge with the request data. #### Returns `array<string, mixed>` ### paginate() public ``` paginate(Cake\Datasource\RepositoryInterfaceCake\Datasource\QueryInterface $object, array $params = [], array $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 repository. You can configure repository specific settings by keying the settings with the repository 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` repositories. ### Controlling sort fields By default CakePHP will automatically allow sorting on any column on the repository 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 all the columns you wish to allow sorting on. You can define the allowed sort fields in the `$settings` parameter: ``` $settings = [ 'Articles' => [ 'finder' => 'custom', 'sortableFields' => ['title', 'author_id', 'comment_count'], ] ]; ``` Passing an empty array as sortableFields 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 The repository or query to paginate. `array` $params optional Request params `array` $settings optional The settings/configuration used for pagination. #### Returns `Cake\Datasource\ResultSetInterface` #### Throws `Cake\Datasource\Paging\Exception\PageOutOfBoundsException` ### 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. ### validateSort() public ``` validateSort(Cake\Datasource\RepositoryInterface $object, array<string, mixed> $options): array<string, mixed> ``` Validate that the desired sorting can be performed on the $object. Only fields or virtualFields can be sorted on. The direction param will also be sanitized. Lastly sort + direction keys will be converted into the model friendly order key. You can use the allowedParameters option to control which columns/fields are available for sorting via URL parameters. This helps prevent users from ordering large result sets on un-indexed values. If you need to sort on associated columns or synthetic properties you will need to use the `sortableFields` option. Any columns listed in the allowed sort fields will be implicitly trusted. You can use this to sort on synthetic columns, or columns added in custom find operations that may not exist in the schema. The default order options provided to paginate() will be merged with the user's requested sorting field/direction. #### Parameters `Cake\Datasource\RepositoryInterface` $object Repository object. `array<string, mixed>` $options The pagination options being used for this request. #### Returns `array<string, mixed>` 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 pagination settings. When calling paginate() these settings will be merged with the configuration you provide. * `maxLimit` - The maximum limit users can choose to view. Defaults to 100 * `limit` - The initial number of items per page. Defaults to 20. * `page` - The starting page, defaults to 1. * `allowedParameters` - A list of parameters users are allowed to set using request parameters. Modifying this list will allow users to have more influence over pagination, be careful with what you permit. #### Type `array<string, mixed>` ### $\_pagingParams protected Paging params after pagination operation is done. #### Type `array<string, array>`
programming_docs
cakephp Namespace Response Namespace Response ================== ### Classes * ##### [BodyContains](class-cake.testsuite.constraint.response.bodycontains) BodyContains * ##### [BodyEmpty](class-cake.testsuite.constraint.response.bodyempty) BodyEmpty * ##### [BodyEquals](class-cake.testsuite.constraint.response.bodyequals) BodyEquals * ##### [BodyNotContains](class-cake.testsuite.constraint.response.bodynotcontains) BodyContains * ##### [BodyNotEmpty](class-cake.testsuite.constraint.response.bodynotempty) BodyNotEmpty * ##### [BodyNotEquals](class-cake.testsuite.constraint.response.bodynotequals) BodyNotEquals * ##### [BodyNotRegExp](class-cake.testsuite.constraint.response.bodynotregexp) BodyNotRegExp * ##### [BodyRegExp](class-cake.testsuite.constraint.response.bodyregexp) BodyRegExp * ##### [ContentType](class-cake.testsuite.constraint.response.contenttype) ContentType * ##### [CookieEncryptedEquals](class-cake.testsuite.constraint.response.cookieencryptedequals) CookieEncryptedEquals * ##### [CookieEquals](class-cake.testsuite.constraint.response.cookieequals) CookieEquals * ##### [CookieNotSet](class-cake.testsuite.constraint.response.cookienotset) CookieNotSet * ##### [CookieSet](class-cake.testsuite.constraint.response.cookieset) CookieSet * ##### [FileSent](class-cake.testsuite.constraint.response.filesent) FileSent * ##### [FileSentAs](class-cake.testsuite.constraint.response.filesentas) FileSentAs * ##### [HeaderContains](class-cake.testsuite.constraint.response.headercontains) HeaderContains * ##### [HeaderEquals](class-cake.testsuite.constraint.response.headerequals) HeaderEquals * ##### [HeaderNotContains](class-cake.testsuite.constraint.response.headernotcontains) Constraint for ensuring a header does not contain a value. * ##### [HeaderNotSet](class-cake.testsuite.constraint.response.headernotset) HeaderSet * ##### [HeaderSet](class-cake.testsuite.constraint.response.headerset) HeaderSet * ##### [ResponseBase](class-cake.testsuite.constraint.response.responsebase) Base constraint for response constraints * ##### [StatusCode](class-cake.testsuite.constraint.response.statuscode) StatusCode * ##### [StatusCodeBase](class-cake.testsuite.constraint.response.statuscodebase) StatusCodeBase * ##### [StatusError](class-cake.testsuite.constraint.response.statuserror) StatusError * ##### [StatusFailure](class-cake.testsuite.constraint.response.statusfailure) StatusFailure * ##### [StatusOk](class-cake.testsuite.constraint.response.statusok) StatusOk * ##### [StatusSuccess](class-cake.testsuite.constraint.response.statussuccess) StatusSuccess cakephp Class ContextFactory Class ContextFactory ===================== Factory for getting form context instance based on provided data. **Namespace:** [Cake\View\Form](namespace-cake.view.form) Property Summary ---------------- * [$providers](#%24providers) protected `array<string, array>` Context providers. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [addProvider()](#addProvider()) public Add a new context type. * ##### [createWithDefaults()](#createWithDefaults()) public static Create factory instance with providers "array", "form" and "orm". * ##### [get()](#get()) public Find the matching context for the data. Method Detail ------------- ### \_\_construct() public ``` __construct(array $providers = []) ``` Constructor. #### Parameters `array` $providers optional Array of provider callables. Each element should be of form `['type' => 'a-string', 'callable' => ..]` ### addProvider() public ``` addProvider(string $type, callable $check): $this ``` 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 `$this` ### createWithDefaults() public static ``` createWithDefaults(array $providers = []): static ``` Create factory instance with providers "array", "form" and "orm". #### Parameters `array` $providers optional Array of provider callables. Each element should be of form `['type' => 'a-string', 'callable' => ..]` #### Returns `static` ### get() public ``` get(Cake\Http\ServerRequest $request, array<string, mixed> $data = []): Cake\View\Form\ContextInterface ``` Find the matching context for the data. If no type can be matched a NullContext will be returned. #### Parameters `Cake\Http\ServerRequest` $request Request instance. `array<string, mixed>` $data optional The data to get a context provider for. #### Returns `Cake\View\Form\ContextInterface` #### Throws `RuntimeException` When a context instance cannot be generated for given entity. Property Detail --------------- ### $providers protected Context providers. #### Type `array<string, array>` cakephp Class FixtureInjector Class FixtureInjector ====================== Test listener used to inject a fixture manager in all tests that are composed inside a Test Suite **Namespace:** [Cake\TestSuite\Fixture](namespace-cake.testsuite.fixture) **Deprecated:** 4.3.0 Property Summary ---------------- * [$\_first](#%24_first) protected `PHPUnit\Framework\TestSuite|null` Holds a reference to the container test suite * [$\_fixtureManager](#%24_fixtureManager) protected `Cake\TestSuite\Fixture\FixtureManager` The instance of the fixture manager to use Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. Save internally the reference to the passed fixture manager * ##### [addError()](#addError()) public * ##### [addFailure()](#addFailure()) public * ##### [addIncompleteTest()](#addIncompleteTest()) public * ##### [addRiskyTest()](#addRiskyTest()) public * ##### [addSkippedTest()](#addSkippedTest()) public * ##### [addWarning()](#addWarning()) public * ##### [endTest()](#endTest()) public Unloads fixtures from the test case. * ##### [endTestSuite()](#endTestSuite()) public Destroys the fixtures created by the fixture manager at the end of the test suite run * ##### [startTest()](#startTest()) public Adds fixtures to a test case when it starts. * ##### [startTestSuite()](#startTestSuite()) public Iterates the tests inside a test suite and creates the required fixtures as they were expressed inside each test case. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\TestSuite\Fixture\FixtureManager $manager) ``` Constructor. Save internally the reference to the passed fixture manager #### Parameters `Cake\TestSuite\Fixture\FixtureManager` $manager The fixture manager ### addError() public ``` addError(Test $test, Throwable $t, float $time): void ``` #### Parameters `Test` $test `Throwable` $t `float` $time #### Returns `void` ### addFailure() public ``` addFailure(Test $test, AssertionFailedError $e, float $time): void ``` #### Parameters `Test` $test `AssertionFailedError` $e `float` $time #### Returns `void` ### addIncompleteTest() public ``` addIncompleteTest(Test $test, Throwable $t, float $time): void ``` #### Parameters `Test` $test `Throwable` $t `float` $time #### Returns `void` ### addRiskyTest() public ``` addRiskyTest(Test $test, Throwable $t, float $time): void ``` #### Parameters `Test` $test `Throwable` $t `float` $time #### Returns `void` ### addSkippedTest() public ``` addSkippedTest(Test $test, Throwable $t, float $time): void ``` #### Parameters `Test` $test `Throwable` $t `float` $time #### Returns `void` ### addWarning() public ``` addWarning(Test $test, Warning $e, float $time): void ``` #### Parameters `Test` $test `Warning` $e `float` $time #### Returns `void` ### endTest() public ``` endTest(Test $test, float $time): void ``` Unloads fixtures from the test case. #### Parameters `Test` $test The test case `float` $time current time #### Returns `void` ### endTestSuite() public ``` endTestSuite(TestSuite $suite): void ``` Destroys the fixtures created by the fixture manager at the end of the test suite run #### Parameters `TestSuite` $suite The test suite #### Returns `void` ### startTest() public ``` startTest(Test $test): void ``` Adds fixtures to a test case when it starts. #### Parameters `Test` $test The test case #### Returns `void` ### startTestSuite() public ``` startTestSuite(TestSuite $suite): void ``` Iterates the tests inside a test suite and creates the required fixtures as they were expressed inside each test case. #### Parameters `TestSuite` $suite The test suite #### Returns `void` Property Detail --------------- ### $\_first protected Holds a reference to the container test suite #### Type `PHPUnit\Framework\TestSuite|null` ### $\_fixtureManager protected The instance of the fixture manager to use #### Type `Cake\TestSuite\Fixture\FixtureManager` cakephp Class ArrayContext Class ArrayContext =================== Provides a basic array based context provider for FormHelper. This adapter is useful in testing or when you have forms backed by simple array data structures. Important keys: * `data` Holds the current values supplied for the fields. * `defaults` The default values for fields. These values will be used when there is no data set. Data should be nested following the dot separated paths you access your fields with. * `required` A nested array of fields, relationships and boolean flags to indicate a field is required. The value can also be a string to be used as the required error message * `schema` An array of data that emulate the column structures that Cake\Database\Schema\Schema uses. This array allows you to control the inferred type for fields and allows auto generation of attributes like maxlength, step and other HTML attributes. If you want primary key/id detection to work. Make sure you have provided a `_constraints` array that contains `primary`. See below for an example. * `errors` An array of validation errors. Errors should be nested following the dot separated paths you access your fields with. ### Example ``` $article = [ 'data' => [ 'id' => '1', 'title' => 'First post!', ], 'schema' => [ 'id' => ['type' => 'integer'], 'title' => ['type' => 'string', 'length' => 255], '_constraints' => [ 'primary' => ['type' => 'primary', 'columns' => ['id']] ] ], 'defaults' => [ 'title' => 'Default title', ], 'required' => [ 'id' => true, // will use default required message 'title' => 'Please enter a title', 'body' => false, ], ]; ``` **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. 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 field length from 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. * ##### [stripNesting()](#stripNesting()) protected Strips out any numeric nesting * ##### [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 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 field length from validation In this context class, this is simply defined by the 'length' array. #### Parameters `string` $field A dot separated path to check required-ness for. #### 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 A dot separated path to check errors on. #### Returns `bool` ### isCreate() public ``` isCreate(): bool ``` Returns whether this form is for a create operation. For this method to return true, both the primary key constraint must be defined in the 'schema' data, and the 'defaults' data must contain a value for all fields in the key. #### 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 A dot separated path to check required-ness for. #### Returns `bool|null` ### primaryKey() public ``` primaryKey(): array<string> ``` Get the fields used in the context as a primary key. #### Returns `array<string>` ### stripNesting() protected ``` stripNesting(string $field): string ``` Strips out any numeric nesting For example users.0.age will output as users.age #### Parameters `string` $field A dot separated path #### Returns `string` ### 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. This method will coalesce the current data and the 'defaults' array. #### Parameters `string` $field A dot separated path to the field a value is needed for. `array<string, mixed>` $options optional Options: #### Returns `mixed` Property Detail --------------- ### $\_context protected Context data for this object. #### Type `array<string, mixed>` cakephp Class Router Class Router ============= Parses the request URL into controller, action, and parameters. Uses the connected routes to match the incoming URL string to parameters that will allow the request to be dispatched. Also handles converting parameter lists into URL strings, using the connected routes. Routing allows you to decouple the way the world interacts with your application (URLs) and the implementation (controllers and actions). ### Connecting routes Connecting routes is done using Router::connect(). When parsing incoming requests or reverse matching parameters, routes are enumerated in the order they were connected. For more information on routes and how to connect them see Router::connect(). **Namespace:** [Cake\Routing](namespace-cake.routing) Constants --------- * `string` **ACTION** ``` 'index|show|add|create|edit|update|remove|del|delete|view|item' ``` Regular expression for action names * `string` **DAY** ``` '0[1-9]|[12][0-9]|3[01]' ``` Regular expression for days * `string` **ID** ``` '[0-9]+' ``` Regular expression for auto increment IDs * `string` **MONTH** ``` '0[1-9]|1[012]' ``` Regular expression for months * `string` **UUID** ``` '[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}' ``` Regular expression for UUIDs * `string` **YEAR** ``` '[12][0-9]{3}' ``` Regular expression for years Property Summary ---------------- * [$\_collection](#%24_collection) protected static `Cake\Routing\RouteCollection` The route collection routes would be added to. * [$\_defaultExtensions](#%24_defaultExtensions) protected static `array<string>` Default extensions defined with Router::extensions() * [$\_defaultRouteClass](#%24_defaultRouteClass) protected static `string` Default route class. * [$\_fullBaseUrl](#%24_fullBaseUrl) protected static `string|null` Contains the base string that will be applied to all generated URLs For example `https://example.com` * [$\_initialState](#%24_initialState) protected static `array` Initial state is populated the first time reload() is called which is at the bottom of this file. This is a cheat as get\_class\_vars() returns the value of static vars even if they have changed. * [$\_namedExpressions](#%24_namedExpressions) protected static `array<string, string>` Named expressions * [$\_request](#%24_request) protected static `Cake\Http\ServerRequest` Maintains the request object reference. * [$\_requestContext](#%24_requestContext) protected static `array<string, mixed>` A hash of request context data. * [$\_routePaths](#%24_routePaths) protected static `array<string, mixed>` Cache of parsed route paths * [$\_urlFilters](#%24_urlFilters) protected static `array<callable>` The stack of URL filters to apply against routing URLs before passing the parameters to the route collection. Method Summary -------------- * ##### [\_applyUrlFilters()](#_applyUrlFilters()) protected static Applies all the connected URL filters to the URL. * ##### [addUrlFilter()](#addUrlFilter()) public static Add a URL filter to Router. * ##### [connect()](#connect()) public static deprecated Connects a new Route in the router. * ##### [createRouteBuilder()](#createRouteBuilder()) public static Create a RouteBuilder for the provided path. * ##### [defaultRouteClass()](#defaultRouteClass()) public static Get or set default route class. * ##### [extensions()](#extensions()) public static Get or set valid extensions for all routes connected later. * ##### [fullBaseUrl()](#fullBaseUrl()) public static Sets the full base URL that will be used as a prefix for generating fully qualified URLs for this application. If no parameters are passed, the currently configured value is returned. * ##### [getNamedExpressions()](#getNamedExpressions()) public static Gets the named route patterns for use in config/routes.php * ##### [getRequest()](#getRequest()) public static Get the current request object. * ##### [getRouteCollection()](#getRouteCollection()) public static Get the RouteCollection inside the Router * ##### [normalize()](#normalize()) public static Normalizes a URL for purposes of comparison. * ##### [parseRequest()](#parseRequest()) public static Get the routing parameters for the request if possible. * ##### [parseRoutePath()](#parseRoutePath()) public static Parse a string route path * ##### [pathUrl()](#pathUrl()) public static Generate URL for route path. * ##### [plugin()](#plugin()) public static deprecated Add plugin routes. * ##### [prefix()](#prefix()) public static deprecated Create prefixed routes. * ##### [reload()](#reload()) public static Reloads default Router settings. Resets all class variables and removes all connected routes. * ##### [resetRoutes()](#resetRoutes()) public static Reset routes and related state. * ##### [reverse()](#reverse()) public static Reverses a parsed parameter array into a string. * ##### [reverseToArray()](#reverseToArray()) public static Reverses a parsed parameter array into an array. * ##### [routeExists()](#routeExists()) public static Finds URL for specified action. * ##### [routes()](#routes()) public static Get the route scopes and their connected routes. * ##### [scope()](#scope()) public static deprecated Create a routing scope. * ##### [setRequest()](#setRequest()) public static Set current request instance. * ##### [setRouteCollection()](#setRouteCollection()) public static Set the RouteCollection inside the Router * ##### [unwrapShortString()](#unwrapShortString()) protected static Inject route defaults from `_path` key * ##### [url()](#url()) public static Finds URL for specified action. Method Detail ------------- ### \_applyUrlFilters() protected static ``` _applyUrlFilters(array $url): array ``` Applies all the connected URL filters to the URL. #### Parameters `array` $url The URL array being modified. #### Returns `array` #### See Also \Cake\Routing\Router::url() \Cake\Routing\Router::addUrlFilter() ### addUrlFilter() public static ``` addUrlFilter(callable $function): void ``` Add a URL filter to Router. URL filter functions are applied to every array $url provided to Router::url() before the URLs are sent to the route collection. Callback functions should expect the following parameters: * `$params` The URL params being processed. * `$request` The current request. The URL filter function should *always* return the params even if unmodified. ### Usage URL filters allow you to easily implement features like persistent parameters. ``` Router::addUrlFilter(function ($params, $request) { if ($request->getParam('lang') && !isset($params['lang'])) { $params['lang'] = $request->getParam('lang'); } return $params; }); ``` #### Parameters `callable` $function The function to add #### Returns `void` ### connect() public static ``` connect(Cake\Routing\Route\Route|string $route, array|string $defaults = [], array<string, mixed> $options = []): void ``` Connects a new Route in the router. Compatibility proxy to \Cake\Routing\RouteBuilder::connect() in the `/` scope. #### Parameters `Cake\Routing\Route\Route|string` $route A string describing the template of the route `array|string` $defaults optional An array describing the default route parameters. These parameters will be used by default and can supply routing parameters that are not dynamic. See above. `array<string, mixed>` $options optional An array matching the named elements in the route to regular expressions which that element should match. Also contains additional parameters such as which routed parameters should be shifted into the passed arguments, supplying patterns for routing parameters and supplying the name of a custom routing class. #### Returns `void` #### Throws `Cake\Core\Exception\CakeException` #### See Also \Cake\Routing\RouteBuilder::connect() \Cake\Routing\Router::scope() ### createRouteBuilder() public static ``` createRouteBuilder(string $path, array<string, mixed> $options = []): Cake\Routing\RouteBuilder ``` Create a RouteBuilder for the provided path. #### Parameters `string` $path The path to set the builder to. `array<string, mixed>` $options optional The options for the builder #### Returns `Cake\Routing\RouteBuilder` ### defaultRouteClass() public static ``` defaultRouteClass(string|null $routeClass = null): string|null ``` Get or set default route class. #### Parameters `string|null` $routeClass optional Class name. #### Returns `string|null` ### extensions() public static ``` extensions(array<string>|string|null $extensions = null, bool $merge = true): array<string> ``` Get or set valid extensions for all routes connected later. Instructs the router to parse out file extensions from the URL. For example, <http://example.com/posts.rss> would yield a file extension of "rss". The file extension itself is made available in the controller as `$this->request->getParam('_ext')`, and is used by the RequestHandler component to automatically switch to alternate layouts and templates, and load helpers corresponding to the given content, i.e. RssHelper. Switching layouts and helpers requires that the chosen extension has a defined mime type in `Cake\Http\Response`. A string or an array of valid extensions can be passed to this method. If called without any parameters it will return current list of set extensions. #### Parameters `array<string>|string|null` $extensions optional List of extensions to be added. `bool` $merge optional Whether to merge with or override existing extensions. Defaults to `true`. #### Returns `array<string>` ### fullBaseUrl() public static ``` fullBaseUrl(string|null $base = null): string ``` Sets the full base URL that will be used as a prefix for generating fully qualified URLs for this application. If no parameters are passed, the currently configured value is returned. ### Note: If you change the configuration value `App.fullBaseUrl` during runtime and expect the router to produce links using the new setting, you are required to call this method passing such value again. #### Parameters `string|null` $base optional the prefix for URLs generated containing the domain. For example: `http://example.com` #### Returns `string` ### getNamedExpressions() public static ``` getNamedExpressions(): array<string, string> ``` Gets the named route patterns for use in config/routes.php #### Returns `array<string, string>` #### See Also \Cake\Routing\Router::$\_namedExpressions ### getRequest() public static ``` getRequest(): Cake\Http\ServerRequest|null ``` Get the current request object. #### Returns `Cake\Http\ServerRequest|null` ### getRouteCollection() public static ``` getRouteCollection(): Cake\Routing\RouteCollection ``` Get the RouteCollection inside the Router #### Returns `Cake\Routing\RouteCollection` ### normalize() public static ``` normalize(array|string $url = '/'): string ``` Normalizes a URL for purposes of comparison. Will strip the base path off and replace any double /'s. It will not unify the casing and underscoring of the input value. #### Parameters `array|string` $url optional URL to normalize Either an array or a string URL. #### Returns `string` ### parseRequest() public static ``` parseRequest(Cake\Http\ServerRequest $request): array ``` Get the routing parameters for the request if possible. #### Parameters `Cake\Http\ServerRequest` $request The request to parse request data from. #### Returns `array` #### Throws `Cake\Routing\Exception\MissingRouteException` When a route cannot be handled ### parseRoutePath() public static ``` parseRoutePath(string $url): array<string, string> ``` Parse a string route path String examples: * Bookmarks::view * Admin/Bookmarks::view * Cms.Articles::edit * Vendor/Cms.Management/Admin/Articles::view #### Parameters `string` $url Route path in [Plugin.][Prefix/]Controller::action format #### Returns `array<string, string>` ### pathUrl() public static ``` pathUrl(string $path, array $params = [], bool $full = false): string ``` Generate URL for route path. Route path examples: * Bookmarks::view * Admin/Bookmarks::view * Cms.Articles::edit * Vendor/Cms.Management/Admin/Articles::view #### Parameters `string` $path Route path specifying controller and action, optionally with plugin and prefix. `array` $params optional An array specifying any additional parameters. Can be also any special parameters supported by `Router::url()`. `bool` $full optional If true, the full base URL will be prepended to the result. Default is false. #### Returns `string` ### plugin() public static ``` plugin(string $name, callable|array $options = [], callable|null $callback = null): void ``` Add plugin routes. This method creates a scoped route collection that includes relevant plugin information. The plugin name will be inflected to the dasherized version to create the routing path. If you want a custom path name, use the `path` option. Routes connected in the scoped collection will have the correct path segment prepended, and have a matching plugin routing key set. #### Parameters `string` $name The plugin name to build routes for `callable|array` $options optional Either the options to use, or a callback `callable|null` $callback optional The callback to invoke that builds the plugin routes. Only required when $options is defined #### Returns `void` ### prefix() public static ``` prefix(string $name, callable|array $params = [], callable|null $callback = null): void ``` Create prefixed routes. This method creates a scoped route collection that includes relevant prefix information. The path parameter is used to generate the routing parameter name. For example a path of `admin` would result in `'prefix' => 'Admin'` being applied to all connected routes. The prefix name will be inflected to the dasherized version to create the routing path. If you want a custom path name, use the `path` option. You can re-open a prefix as many times as necessary, as well as nest prefixes. Nested prefixes will result in prefix values like `Admin/Api` which translates to the `Controller\Admin\Api\` namespace. #### Parameters `string` $name The prefix name to use. `callable|array` $params optional An array of routing defaults to add to each connected route. If you have no parameters, this argument can be a callable. `callable|null` $callback optional The callback to invoke that builds the prefixed routes. #### Returns `void` ### reload() public static ``` reload(): void ``` Reloads default Router settings. Resets all class variables and removes all connected routes. #### Returns `void` ### resetRoutes() public static ``` resetRoutes(): void ``` Reset routes and related state. Similar to reload() except that this doesn't reset all global state, as that leads to incorrect behavior in some plugin test case scenarios. This method will reset: * routes * URL Filters * the initialized property Extensions and default route classes will not be modified #### Returns `void` ### reverse() public static ``` reverse(Cake\Http\ServerRequest|array $params, bool $full = false): string ``` Reverses a parsed parameter array into a string. Works similarly to Router::url(), but since parsed URL's contain additional keys like 'pass', '\_matchedRoute' etc. those keys need to be specially handled in order to reverse a params array into a string URL. #### Parameters `Cake\Http\ServerRequest|array` $params The params array or Cake\Http\ServerRequest object that needs to be reversed. `bool` $full optional Set to true to include the full URL including the protocol when reversing the URL. #### Returns `string` ### reverseToArray() public static ``` reverseToArray(Cake\Http\ServerRequest|array $params): array ``` Reverses a parsed parameter array into an array. Works similarly to Router::url(), but since parsed URL's contain additional keys like 'pass', '\_matchedRoute' etc. those keys need to be specially handled in order to reverse a params array into a string URL. #### Parameters `Cake\Http\ServerRequest|array` $params The params array or Cake\Http\ServerRequest object that needs to be reversed. #### Returns `array` ### routeExists() public static ``` routeExists(array|string|null $url = null, bool $full = false): bool ``` Finds URL for specified action. Returns a bool if the url exists ### Usage #### Parameters `array|string|null` $url optional An array specifying any of the following: 'controller', 'action', 'plugin' additionally, you can provide routed elements or query string parameters. If string it can be name any valid url string. `bool` $full optional If true, the full base URL will be prepended to the result. Default is false. #### Returns `bool` #### See Also Router::url() ### routes() public static ``` routes(): arrayCake\Routing\Route\Route> ``` Get the route scopes and their connected routes. #### Returns `arrayCake\Routing\Route\Route>` ### scope() public static ``` scope(string $path, callable|array $params = [], callable|null $callback = null): void ``` Create a routing scope. Routing scopes allow you to keep your routes DRY and avoid repeating common path prefixes, and or parameter sets. Scoped collections will be indexed by path for faster route parsing. If you re-open or re-use a scope the connected routes will be merged with the existing ones. ### Options The `$params` array allows you to define options for the routing scope. The options listed below *are not* available to be used as routing defaults * `routeClass` The route class to use in this scope. Defaults to `Router::defaultRouteClass()` * `extensions` The extensions to enable in this scope. Defaults to the globally enabled extensions set with `Router::extensions()` ### Example ``` Router::scope('/blog', ['plugin' => 'Blog'], function ($routes) { $routes->connect('/', ['controller' => 'Articles']); }); ``` The above would result in a `/blog/` route being created, with both the plugin & controller default parameters set. You can use `Router::plugin()` and `Router::prefix()` as shortcuts to creating specific kinds of scopes. #### Parameters `string` $path The path prefix for the scope. This path will be prepended to all routes connected in the scoped collection. `callable|array` $params optional An array of routing defaults to add to each connected route. If you have no parameters, this argument can be a callable. `callable|null` $callback optional The callback to invoke with the scoped collection. #### Returns `void` #### Throws `InvalidArgumentException` When an invalid callable is provided. ### setRequest() public static ``` setRequest(Cake\Http\ServerRequest $request): void ``` Set current request instance. #### Parameters `Cake\Http\ServerRequest` $request request object. #### Returns `void` ### setRouteCollection() public static ``` setRouteCollection(Cake\Routing\RouteCollection $routeCollection): void ``` Set the RouteCollection inside the Router #### Parameters `Cake\Routing\RouteCollection` $routeCollection route collection #### Returns `void` ### unwrapShortString() protected static ``` unwrapShortString(array $url): array ``` Inject route defaults from `_path` key #### Parameters `array` $url Route array with `_path` key #### Returns `array` ### url() public static ``` url(Psr\Http\Message\UriInterface|array|string|null $url = null, bool $full = false): string ``` Finds URL for specified action. Returns a URL pointing to a combination of controller and action. ### Usage * `Router::url('/posts/edit/1');` Returns the string with the base dir prepended. This usage does not use reverser routing. * `Router::url(['controller' => 'Posts', 'action' => 'edit']);` Returns a URL generated through reverse routing. * `Router::url(['_name' => 'custom-name', ...]);` Returns a URL generated through reverse routing. This form allows you to leverage named routes. There are a few 'special' parameters that can change the final URL string that is generated * `_base` - Set to false to remove the base path from the generated URL. If your application is not in the root directory, this can be used to generate URLs that are 'cake relative'. cake relative URLs are required when using requestAction. * `_scheme` - Set to create links on different schemes like `webcal` or `ftp`. Defaults to the current scheme. * `_host` - Set the host to use for the link. Defaults to the current host. * `_port` - Set the port if you need to create links on non-standard ports. * `_full` - If true output of `Router::fullBaseUrl()` will be prepended to generated URLs. * `#` - Allows you to set URL hash fragments. * `_ssl` - Set to true to convert the generated URL to https, or false to force http. * `_name` - Name of route. If you have setup named routes you can use this key to specify it. #### Parameters `Psr\Http\Message\UriInterface|array|string|null` $url optional An array specifying any of the following: 'controller', 'action', 'plugin' additionally, you can provide routed elements or query string parameters. If string it can be name any valid url string or it can be an UriInterface instance. `bool` $full optional If true, the full base URL will be prepended to the result. Default is false. #### Returns `string` #### Throws `Cake\Core\Exception\CakeException` When the route name is not found Property Detail --------------- ### $\_collection protected static The route collection routes would be added to. #### Type `Cake\Routing\RouteCollection` ### $\_defaultExtensions protected static Default extensions defined with Router::extensions() #### Type `array<string>` ### $\_defaultRouteClass protected static Default route class. #### Type `string` ### $\_fullBaseUrl protected static Contains the base string that will be applied to all generated URLs For example `https://example.com` #### Type `string|null` ### $\_initialState protected static Initial state is populated the first time reload() is called which is at the bottom of this file. This is a cheat as get\_class\_vars() returns the value of static vars even if they have changed. #### Type `array` ### $\_namedExpressions protected static Named expressions #### Type `array<string, string>` ### $\_request protected static Maintains the request object reference. #### Type `Cake\Http\ServerRequest` ### $\_requestContext protected static A hash of request context data. #### Type `array<string, mixed>` ### $\_routePaths protected static Cache of parsed route paths #### Type `array<string, mixed>` ### $\_urlFilters protected static The stack of URL filters to apply against routing URLs before passing the parameters to the route collection. #### Type `array<callable>`
programming_docs
cakephp Interface ColumnSchemaAwareInterface Interface ColumnSchemaAwareInterface ===================================== **Namespace:** [Cake\Database\Type](namespace-cake.database.type) Method Summary -------------- * ##### [convertColumnDefinition()](#convertColumnDefinition()) public Convert a SQL column definition to an abstract type definition. * ##### [getColumnSql()](#getColumnSql()) public Generate the SQL fragment for a single column in a table. Method Detail ------------- ### convertColumnDefinition() public ``` convertColumnDefinition(array $definition, Cake\Database\DriverInterface $driver): array<string, mixed>|null ``` Convert a SQL column definition to an abstract type definition. #### Parameters `array` $definition The column definition. `Cake\Database\DriverInterface` $driver The driver instance being used. #### Returns `array<string, mixed>|null` ### getColumnSql() public ``` getColumnSql(Cake\Database\Schema\TableSchemaInterface $schema, string $column, Cake\Database\DriverInterface $driver): string|null ``` Generate the SQL fragment for a single column in a table. #### Parameters `Cake\Database\Schema\TableSchemaInterface` $schema The table schema instance the column is in. `string` $column The name of the column. `Cake\Database\DriverInterface` $driver The driver instance being used. #### Returns `string|null` cakephp Class BodyNotEmpty Class BodyNotEmpty =================== BodyNotEmpty **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 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 `Psr\Http\Message\ResponseInterface` cakephp Class Email Class Email ============ CakePHP Email class. This class is used for sending Internet Message Format based on the standard outlined in <https://www.rfc-editor.org/rfc/rfc2822.txt> ### Configuration Configuration for Email is managed by Email::config() and Email::configTransport(). Email::config() can be used to add or read a configuration profile for Email instances. Once made configuration profiles can be used to re-use across various email messages your application sends. **Namespace:** [Cake\Mailer](namespace-cake.mailer) **Deprecated:** 4.0.0 This class will be removed in CakePHP 5.0, use {@link \Cake\Mailer\Mailer} instead. Constants --------- * `string` **EMAIL\_PATTERN** ``` '/^((?:[\\p{L}0-9.!#$%&\'*+\\/=?^_`{|}~-]+)*@[\\p{L}0-9-._]+)$/ui' ``` Holds the regex pattern for email validation * `string` **MESSAGE\_BOTH** ``` 'both' ``` Type of message - BOTH * `string` **MESSAGE\_HTML** ``` 'html' ``` Type of message - HTML * `string` **MESSAGE\_TEXT** ``` 'text' ``` Type of message - TEXT Property Summary ---------------- * [$\_profile](#%24_profile) protected `array<string, mixed>` A copy of the configuration profile for this instance. This copy can be modified with Email::profile(). * [$\_transport](#%24_transport) protected `Cake\Mailer\AbstractTransport|null` The transport instance to use for sending mail. * [$message](#%24message) protected `Cake\Mailer\Message` Message instance. * [$messageClass](#%24messageClass) protected `string` Message class name. * [$renderer](#%24renderer) protected `Cake\Mailer\Renderer|null` Email Renderer Method Summary -------------- * ##### [\_\_call()](#__call()) public Magic method to forward method class to Email instance. * ##### [\_\_callStatic()](#__callStatic()) public static Proxy all static method calls (for methods provided by StaticConfigTrait) to Mailer. * ##### [\_\_clone()](#__clone()) public Clone Renderer instance when email object is cloned. * ##### [\_\_construct()](#__construct()) public Constructor * ##### [\_\_serialize()](#__serialize()) public Magic method used for serializing the Email object. * ##### [\_\_unserialize()](#__unserialize()) public Magic method used to rebuild the Email object. * ##### [\_logDelivery()](#_logDelivery()) protected Log the email message delivery. * ##### [createFromArray()](#createFromArray()) public Configures an email instance object from serialized config. * ##### [deliver()](#deliver()) public static Static method to fast create an instance of \Cake\Mailer\Email * ##### [flatten()](#flatten()) protected Converts given value to string * ##### [getMessage()](#getMessage()) public Get message instance. * ##### [getProfile()](#getProfile()) public Gets the configuration profile to use for this instance. * ##### [getRenderer()](#getRenderer()) public Get email renderer. * ##### [getTransport()](#getTransport()) public Gets the transport. * ##### [getViewRenderer()](#getViewRenderer()) public Gets view class for render. * ##### [getViewVars()](#getViewVars()) public Gets variables to be set on render. * ##### [jsonSerialize()](#jsonSerialize()) public Serializes the email object to a value that can be natively serialized and re-used to clone this email instance. * ##### [message()](#message()) public Get generated message (used by transport classes) * ##### [render()](#render()) public Render email. * ##### [reset()](#reset()) public Reset all the internal variables to be able to send out a new email. * ##### [send()](#send()) public Send an email using the specified content, template and layout * ##### [serialize()](#serialize()) public Serializes the Email object. * ##### [setProfile()](#setProfile()) public Sets the configuration profile to use for this instance. * ##### [setRenderer()](#setRenderer()) public Set email renderer. * ##### [setTransport()](#setTransport()) public Sets the transport. * ##### [setViewRenderer()](#setViewRenderer()) public Sets view class for render. * ##### [setViewVars()](#setViewVars()) public Sets variables to be set on render. * ##### [unserialize()](#unserialize()) public Unserializes the Email object. * ##### [viewBuilder()](#viewBuilder()) public Get view builder. Method Detail ------------- ### \_\_call() public ``` __call(string $method, array $args): $this|mixed ``` Magic method to forward method class to Email instance. #### Parameters `string` $method Method name. `array` $args Method arguments #### Returns `$this|mixed` ### \_\_callStatic() public static ``` __callStatic(string $name, array $arguments): mixed ``` Proxy all static method calls (for methods provided by StaticConfigTrait) to Mailer. #### Parameters `string` $name Method name. `array` $arguments Method argument. #### Returns `mixed` ### \_\_clone() public ``` __clone(): void ``` Clone Renderer instance when email object is cloned. #### Returns `void` ### \_\_construct() public ``` __construct(array<string, mixed>|string|null $config = null) ``` Constructor #### Parameters `array<string, mixed>|string|null` $config optional Array of configs, or string to load configs from app.php ### \_\_serialize() public ``` __serialize(): array ``` Magic method used for serializing the Email object. #### Returns `array` ### \_\_unserialize() public ``` __unserialize(array $data): void ``` Magic method used to rebuild the Email object. #### Parameters `array` $data Data array. #### Returns `void` ### \_logDelivery() protected ``` _logDelivery(array<string, string> $contents): void ``` Log the email message delivery. #### Parameters `array<string, string>` $contents The content with 'headers' and 'message' keys. #### Returns `void` ### createFromArray() public ``` createFromArray(array<string, mixed> $config): $this ``` Configures an email instance object from serialized config. #### Parameters `array<string, mixed>` $config Email configuration array. #### Returns `$this` ### deliver() public static ``` deliver(array|string|null $to = null, string|null $subject = null, array|string|null $message = null, array<string, mixed>|string $config = 'default', bool $send = true): Cake\Mailer\Email ``` Static method to fast create an instance of \Cake\Mailer\Email #### Parameters `array|string|null` $to optional Address to send ({@see \Cake\Mailer\Email::setTo()}). If null, will try to use 'to' from transport config `string|null` $subject optional String of subject or null to use 'subject' from transport config `array|string|null` $message optional String with message or array with variables to be used in render `array<string, mixed>|string` $config optional String to use Email delivery profile from app.php or array with configs `bool` $send optional Send the email or just return the instance pre-configured #### Returns `Cake\Mailer\Email` #### Throws `InvalidArgumentException` ### flatten() protected ``` flatten(array<string>|string $value): string ``` Converts given value to string #### Parameters `array<string>|string` $value The value to convert #### Returns `string` ### getMessage() public ``` getMessage(): Cake\Mailer\Message ``` Get message instance. #### Returns `Cake\Mailer\Message` ### getProfile() public ``` getProfile(): array<string, mixed> ``` Gets the configuration profile to use for this instance. #### Returns `array<string, mixed>` ### getRenderer() public ``` getRenderer(): Cake\Mailer\Renderer ``` Get email renderer. #### Returns `Cake\Mailer\Renderer` ### getTransport() public ``` getTransport(): Cake\Mailer\AbstractTransport|null ``` Gets the transport. #### Returns `Cake\Mailer\AbstractTransport|null` ### getViewRenderer() public ``` getViewRenderer(): string ``` Gets view class for render. #### Returns `string` ### getViewVars() public ``` getViewVars(): array<string, mixed> ``` Gets variables to be set on render. #### Returns `array<string, mixed>` ### jsonSerialize() public ``` jsonSerialize(): array ``` Serializes the email object to a value that can be natively serialized and re-used to clone this email instance. #### Returns `array` #### Throws `Exception` When a view var object can not be properly serialized. ### message() public ``` message(string|null $type = null): array|string ``` Get generated message (used by transport classes) #### Parameters `string|null` $type optional Use MESSAGE\_\* constants or null to return the full message as array #### Returns `array|string` ### render() public ``` render(array<string>|string|null $content = null): void ``` Render email. #### Parameters `array<string>|string|null` $content optional Content array or string #### Returns `void` ### reset() public ``` reset(): $this ``` Reset all the internal variables to be able to send out a new email. #### Returns `$this` ### send() public ``` send(array<string>|string|null $content = null): array ``` Send an email using the specified content, template and layout #### Parameters `array<string>|string|null` $content optional String with message or array with messages #### Returns `array` #### Throws `BadMethodCallException` ### serialize() public ``` serialize(): string ``` Serializes the Email object. #### Returns `string` ### setProfile() public ``` setProfile(array<string, mixed>|string $config): $this ``` Sets the configuration profile to use for this instance. #### Parameters `array<string, mixed>|string` $config String with configuration name, or an array with config. #### Returns `$this` ### setRenderer() public ``` setRenderer(Cake\Mailer\Renderer $renderer): $this ``` Set email renderer. #### Parameters `Cake\Mailer\Renderer` $renderer Render instance. #### Returns `$this` ### setTransport() public ``` setTransport(Cake\Mailer\AbstractTransport|string $name): $this ``` Sets the transport. When setting the transport you can either use the name of a configured transport or supply a constructed transport. #### Parameters `Cake\Mailer\AbstractTransport|string` $name Either the name of a configured transport, or a transport instance. #### Returns `$this` #### Throws `LogicException` When the chosen transport lacks a send method. `InvalidArgumentException` When $name is neither a string nor an object. ### setViewRenderer() public ``` setViewRenderer(string $viewClass): $this ``` Sets view class for render. #### Parameters `string` $viewClass View class name. #### Returns `$this` ### setViewVars() public ``` setViewVars(array<string, mixed> $viewVars): $this ``` Sets variables to be set on render. #### Parameters `array<string, mixed>` $viewVars Variables to set for view. #### Returns `$this` ### unserialize() public ``` unserialize(string $data): void ``` Unserializes the Email object. #### Parameters `string` $data Serialized string. #### Returns `void` ### viewBuilder() public ``` viewBuilder(): Cake\View\ViewBuilder ``` Get view builder. #### Returns `Cake\View\ViewBuilder` Property Detail --------------- ### $\_profile protected A copy of the configuration profile for this instance. This copy can be modified with Email::profile(). #### Type `array<string, mixed>` ### $\_transport protected The transport instance to use for sending mail. #### Type `Cake\Mailer\AbstractTransport|null` ### $message protected Message instance. #### Type `Cake\Mailer\Message` ### $messageClass protected Message class name. #### Type `string` ### $renderer protected Email Renderer #### Type `Cake\Mailer\Renderer|null`
programming_docs
cakephp Class Validation Class Validation ================= Validation Class. Used for validation of model data Offers different validation methods. **Namespace:** [Cake\Validation](namespace-cake.validation) Constants --------- * `string` **COMPARE\_EQUAL** ``` '==' ``` Equal to comparison operator. * `string` **COMPARE\_GREATER** ``` '>' ``` Greater than comparison operator. * `string` **COMPARE\_GREATER\_OR\_EQUAL** ``` '>=' ``` Greater than or equal to comparison operator. * `string` **COMPARE\_LESS** ``` '<' ``` Less than comparison operator. * `string` **COMPARE\_LESS\_OR\_EQUAL** ``` '<=' ``` Less than or equal to comparison operator. * `string` **COMPARE\_NOT\_EQUAL** ``` '!=' ``` Not equal to comparison operator. * `string` **COMPARE\_NOT\_SAME** ``` '!==' ``` Not same as comparison operator. * `string` **COMPARE\_SAME** ``` '===' ``` Same as operator. * `array<string>` **COMPARE\_STRING** ``` [self::COMPARE_EQUAL, self::COMPARE_NOT_EQUAL, self::COMPARE_SAME, self::COMPARE_NOT_SAME] ``` * `string` **DATETIME\_ISO8601** ``` 'iso8601' ``` Datetime ISO8601 format * `string` **DEFAULT\_LOCALE** ``` 'en_US' ``` Default locale Property Summary ---------------- * [$\_pattern](#%24_pattern) protected static `array<string, string>` Some complex patterns needed in multiple places * [$errors](#%24errors) public static `array` Holds an array of errors messages set in this class. These are used for debugging purposes Method Summary -------------- * ##### [\_check()](#_check()) protected static Runs a regular expression match. * ##### [\_getDateString()](#_getDateString()) protected static Converts an array representing a date or datetime into a ISO string. The arrays are typically sent for validation from a form generated by the CakePHP FormHelper. * ##### [\_populateIp()](#_populateIp()) protected static Lazily populate the IP address patterns used for validations * ##### [\_reset()](#_reset()) protected static Reset internal variables for another validation run. * ##### [alphaNumeric()](#alphaNumeric()) public static Checks that a string contains only integer or letters. * ##### [ascii()](#ascii()) public static Check that the input value is within the ascii byte range. * ##### [asciiAlphaNumeric()](#asciiAlphaNumeric()) public static Checks that a string contains only ascii integer or letters. * ##### [boolean()](#boolean()) public static Validates if passed value is boolean-like. * ##### [compareFields()](#compareFields()) public static Compare one field to another. * ##### [compareWith()](#compareWith()) public static Compare one field to another. * ##### [comparison()](#comparison()) public static Used to compare 2 numeric values. * ##### [containsNonAlphaNumeric()](#containsNonAlphaNumeric()) public static deprecated Checks if a string contains one or more non-alphanumeric characters. * ##### [creditCard()](#creditCard()) public static Validation of credit card numbers. Returns true if $check is in the proper credit card format. * ##### [custom()](#custom()) public static Used when a custom regular expression is needed. * ##### [date()](#date()) public static Date validation, determines if the string passed is a valid date. keys that expect full month, day and year will validate leap years. * ##### [datetime()](#datetime()) public static Validates a datetime value * ##### [decimal()](#decimal()) public static Checks that a value is a valid decimal. Both the sign and exponent are optional. * ##### [email()](#email()) public static Validates for an email address. * ##### [equalTo()](#equalTo()) public static Checks that value is exactly $comparedTo. * ##### [extension()](#extension()) public static Checks that value has a valid file extension. * ##### [falsey()](#falsey()) public static Validates if given value is falsey. * ##### [fileSize()](#fileSize()) public static Checks the filesize * ##### [geoCoordinate()](#geoCoordinate()) public static Validates a geographic coordinate. * ##### [getFilename()](#getFilename()) protected static Helper for reading the file out of the various file implementations we accept. * ##### [hexColor()](#hexColor()) public static Check that the input value is a 6 digits hex color. * ##### [iban()](#iban()) public static Check that the input value has a valid International Bank Account Number IBAN syntax Requirements are uppercase, no whitespaces, max length 34, country code and checksum exist at right spots, body matches against checksum via Mod97-10 algorithm * ##### [imageHeight()](#imageHeight()) public static Validates the image height. * ##### [imageSize()](#imageSize()) public static Validates the size of an uploaded image. * ##### [imageWidth()](#imageWidth()) public static Validates the image width. * ##### [inList()](#inList()) public static Checks if a value is in a given list. Comparison is case sensitive by default. * ##### [ip()](#ip()) public static Validation of an IP address. * ##### [isArray()](#isArray()) public static Check that the input value is an array. * ##### [isInteger()](#isInteger()) public static Check that the input value is an integer * ##### [isScalar()](#isScalar()) public static Check that the input value is a scalar. * ##### [iso8601()](#iso8601()) public static Validates an iso8601 datetime format ISO8601 recognize datetime like 2019 as a valid date. To validate and check date integrity, use @see \Cake\Validation\Validation::datetime() * ##### [latitude()](#latitude()) public static Convenience method for latitude validation. * ##### [lengthBetween()](#lengthBetween()) public static Checks that a string length is within specified range. Spaces are included in the character count. Returns true if string matches value min, max, or between min and max, * ##### [localizedTime()](#localizedTime()) public static Date and/or time string validation. Uses `I18n::Time` to parse the date. This means parsing is locale dependent. * ##### [longitude()](#longitude()) public static Convenience method for longitude validation. * ##### [luhn()](#luhn()) public static Luhn algorithm * ##### [maxLength()](#maxLength()) public static Checks whether the length of a string (in characters) is smaller or equal to a maximal length. * ##### [maxLengthBytes()](#maxLengthBytes()) public static Checks whether the length of a string (in bytes) is smaller or equal to a maximal length. * ##### [mimeType()](#mimeType()) public static Checks the mime type of a file. * ##### [minLength()](#minLength()) public static Checks whether the length of a string (in characters) is greater or equal to a minimal length. * ##### [minLengthBytes()](#minLengthBytes()) public static Checks whether the length of a string (in bytes) is greater or equal to a minimal length. * ##### [money()](#money()) public static Checks that a value is a monetary amount. * ##### [multiple()](#multiple()) public static Validates a multiple select. Comparison is case sensitive by default. * ##### [naturalNumber()](#naturalNumber()) public static Checks if a value is a natural number. * ##### [notAlphaNumeric()](#notAlphaNumeric()) public static Checks that a doesn't contain any alpha numeric characters * ##### [notAsciiAlphaNumeric()](#notAsciiAlphaNumeric()) public static Checks that a doesn't contain any non-ascii alpha numeric characters * ##### [notBlank()](#notBlank()) public static Checks that a string contains something other than whitespace * ##### [numElements()](#numElements()) public static Used to check the count of a given value of type array or Countable. * ##### [numeric()](#numeric()) public static Checks if a value is numeric. * ##### [range()](#range()) public static Validates that a number is in specified range. * ##### [time()](#time()) public static Time validation, determines if the string passed is a valid time. Validates time as 24hr (HH:MM[:SS][.FFFFFF]) or am/pm ([H]H:MM[a|p]m) * ##### [truthy()](#truthy()) public static Validates if given value is truthy. * ##### [uploadError()](#uploadError()) public static Checking for upload errors * ##### [uploadedFile()](#uploadedFile()) public static Validate an uploaded file. * ##### [url()](#url()) public static Checks that a value is a valid URL according to <https://www.w3.org/Addressing/URL/url-spec.txt> * ##### [utf8()](#utf8()) public static Check that the input value is a utf8 string. * ##### [uuid()](#uuid()) public static Checks that a value is a valid UUID - <https://tools.ietf.org/html/rfc4122> Method Detail ------------- ### \_check() protected static ``` _check(mixed $check, string $regex): bool ``` Runs a regular expression match. #### Parameters `mixed` $check Value to check against the $regex expression `string` $regex Regular expression #### Returns `bool` ### \_getDateString() protected static ``` _getDateString(array<string, mixed> $value): string ``` Converts an array representing a date or datetime into a ISO string. The arrays are typically sent for validation from a form generated by the CakePHP FormHelper. #### Parameters `array<string, mixed>` $value The array representing a date or datetime. #### Returns `string` ### \_populateIp() protected static ``` _populateIp(): void ``` Lazily populate the IP address patterns used for validations #### Returns `void` ### \_reset() protected static ``` _reset(): void ``` Reset internal variables for another validation run. #### Returns `void` ### alphaNumeric() public static ``` alphaNumeric(mixed $check): bool ``` Checks that a string contains only integer or letters. This method's definition of letters and integers includes unicode characters. Use `asciiAlphaNumeric()` if you want to exclude unicode. #### Parameters `mixed` $check Value to check #### Returns `bool` ### ascii() public static ``` ascii(mixed $value): bool ``` Check that the input value is within the ascii byte range. This method will reject all non-string values. #### Parameters `mixed` $value The value to check #### Returns `bool` ### asciiAlphaNumeric() public static ``` asciiAlphaNumeric(mixed $check): bool ``` Checks that a string contains only ascii integer or letters. #### Parameters `mixed` $check Value to check #### Returns `bool` ### boolean() public static ``` boolean(string|int|bool $check, array<string|int|bool> $booleanValues = []): bool ``` Validates if passed value is boolean-like. The list of what is considered to be boolean values, may be set via $booleanValues. #### Parameters `string|int|bool` $check Value to check. `array<string|int|bool>` $booleanValues optional List of valid boolean values, defaults to `[true, false, 0, 1, '0', '1']`. #### Returns `bool` ### compareFields() public static ``` compareFields(mixed $check, string $field, string $operator, array<string, mixed> $context): bool ``` Compare one field to another. Return true if the comparison matches the expected result. #### Parameters `mixed` $check The value to find in $field. `string` $field The field to check $check against. This field must be present in $context. `string` $operator Comparison operator. See Validation::comparison(). `array<string, mixed>` $context The validation context. #### Returns `bool` ### compareWith() public static ``` compareWith(mixed $check, string $field, array<string, mixed> $context): bool ``` Compare one field to another. If both fields have exactly the same value this method will return true. #### Parameters `mixed` $check The value to find in $field. `string` $field The field to check $check against. This field must be present in $context. `array<string, mixed>` $context The validation context. #### Returns `bool` ### comparison() public static ``` comparison(string|int $check1, string $operator, string|int $check2): bool ``` Used to compare 2 numeric values. #### Parameters `string|int` $check1 The left value to compare. `string` $operator Can be one of following operator strings: '>', '<', '>=', '<=', '==', '!=', '===' and '!=='. You can use one of the Validation::COMPARE\_\* constants. `string|int` $check2 The right value to compare. #### Returns `bool` ### containsNonAlphaNumeric() public static ``` containsNonAlphaNumeric(mixed $check, int $count = 1): bool ``` Checks if a string contains one or more non-alphanumeric characters. Returns true if string contains at least the specified number of non-alphanumeric characters #### Parameters `mixed` $check Value to check `int` $count optional Number of non-alphanumerics to check for #### Returns `bool` ### creditCard() public static ``` creditCard(mixed $check, array<string>|string $type = 'fast', bool $deep = false, string|null $regex = null): bool ``` Validation of credit card numbers. Returns true if $check is in the proper credit card format. #### Parameters `mixed` $check credit card number to validate `array<string>|string` $type optional 'all' may be passed as a string, defaults to fast which checks format of most major credit cards if an array is used only the values of the array are checked. Example: ['amex', 'bankcard', 'maestro'] `bool` $deep optional set to true this will check the Luhn algorithm of the credit card. `string|null` $regex optional A custom regex, this will be used instead of the defined regex values. #### Returns `bool` #### See Also \Cake\Validation\Validation::luhn() ### custom() public static ``` custom(mixed $check, string|null $regex = null): bool ``` Used when a custom regular expression is needed. #### Parameters `mixed` $check The value to check. `string|null` $regex optional If $check is passed as a string, $regex must also be set to valid regular expression #### Returns `bool` ### date() public static ``` date(mixed $check, array<string>|string $format = 'ymd', string|null $regex = null): bool ``` Date validation, determines if the string passed is a valid date. keys that expect full month, day and year will validate leap years. Years are valid from 0001 to 2999. ### Formats: * `dmy` 27-12-2006 or 27-12-06 separators can be a space, period, dash, forward slash * `mdy` 12-27-2006 or 12-27-06 separators can be a space, period, dash, forward slash * `ymd` 2006-12-27 or 06-12-27 separators can be a space, period, dash, forward slash * `dMy` 27 December 2006 or 27 Dec 2006 * `Mdy` December 27, 2006 or Dec 27, 2006 comma is optional * `My` December 2006 or Dec 2006 * `my` 12/2006 or 12/06 separators can be a space, period, dash, forward slash * `ym` 2006/12 or 06/12 separators can be a space, period, dash, forward slash * `y` 2006 just the year without any separators #### Parameters `mixed` $check a valid date string/object `array<string>|string` $format optional Use a string or an array of the keys above. Arrays should be passed as ['dmy', 'mdy', ...] `string|null` $regex optional If a custom regular expression is used this is the only validation that will occur. #### Returns `bool` ### datetime() public static ``` datetime(mixed $check, array|string $dateFormat = 'ymd', string|null $regex = null): bool ``` Validates a datetime value All values matching the "date" core validation rule, and the "time" one will be valid #### Parameters `mixed` $check Value to check `array|string` $dateFormat optional Format of the date part. See Validation::date() for more information. Or `Validation::DATETIME_ISO8601` to validate an ISO8601 datetime value. `string|null` $regex optional Regex for the date part. If a custom regular expression is used this is the only validation that will occur. #### Returns `bool` #### See Also \Cake\Validation\Validation::date() \Cake\Validation\Validation::time() ### decimal() public static ``` decimal(mixed $check, int|true|null $places = null, string|null $regex = null): bool ``` Checks that a value is a valid decimal. Both the sign and exponent are optional. Valid Places: * null => Any number of decimal places, including none. The '.' is not required. * true => Any number of decimal places greater than 0, or a float|double. The '.' is required. * 1..N => Exactly that many number of decimal places. The '.' is required. #### Parameters `mixed` $check The value the test for decimal. `int|true|null` $places optional Decimal places. `string|null` $regex optional If a custom regular expression is used, this is the only validation that will occur. #### Returns `bool` ### email() public static ``` email(mixed $check, bool $deep = false, string|null $regex = null): bool ``` Validates for an email address. Only uses getmxrr() checking for deep validation, or any PHP version on a non-windows distribution #### Parameters `mixed` $check Value to check `bool` $deep optional Perform a deeper validation (if true), by also checking availability of host `string|null` $regex optional Regex to use (if none it will use built in regex) #### Returns `bool` ### equalTo() public static ``` equalTo(mixed $check, mixed $comparedTo): bool ``` Checks that value is exactly $comparedTo. #### Parameters `mixed` $check Value to check `mixed` $comparedTo Value to compare #### Returns `bool` ### extension() public static ``` extension(Psr\Http\Message\UploadedFileInterface|array|string $check, array<string> $extensions = ['gif', 'jpeg', 'png', 'jpg']): bool ``` Checks that value has a valid file extension. #### Parameters `Psr\Http\Message\UploadedFileInterface|array|string` $check Value to check `array<string>` $extensions optional file extensions to allow. By default extensions are 'gif', 'jpeg', 'png', 'jpg' #### Returns `bool` ### falsey() public static ``` falsey(string|int|bool $check, array<string|int|bool> $falseyValues = []): bool ``` Validates if given value is falsey. The list of what is considered to be falsey values, may be set via $falseyValues. #### Parameters `string|int|bool` $check Value to check. `array<string|int|bool>` $falseyValues optional List of valid falsey values, defaults to `[false, 0, '0']`. #### Returns `bool` ### fileSize() public static ``` fileSize(Psr\Http\Message\UploadedFileInterface|array|string $check, string $operator, string|int $size): bool ``` Checks the filesize Will check the filesize of files/UploadedFileInterface instances by checking the filesize() on disk and not relying on the length reported by the client. #### Parameters `Psr\Http\Message\UploadedFileInterface|array|string` $check Value to check. `string` $operator See `Validation::comparison()`. `string|int` $size Size in bytes or human readable string like '5MB'. #### Returns `bool` ### geoCoordinate() public static ``` geoCoordinate(mixed $value, array<string, mixed> $options = []): bool ``` Validates a geographic coordinate. Supported formats: * `<latitude>, <longitude>` Example: `-25.274398, 133.775136` ### Options * `type` - A string of the coordinate format, right now only `latLong`. * `format` - By default `both`, can be `long` and `lat` as well to validate only a part of the coordinate. #### Parameters `mixed` $value Geographic location as string `array<string, mixed>` $options optional Options for the validation logic. #### Returns `bool` ### getFilename() protected static ``` getFilename(mixed $check): string|false ``` Helper for reading the file out of the various file implementations we accept. #### Parameters `mixed` $check The data to read a filename out of. #### Returns `string|false` ### hexColor() public static ``` hexColor(mixed $check): bool ``` Check that the input value is a 6 digits hex color. #### Parameters `mixed` $check The value to check #### Returns `bool` ### iban() public static ``` iban(mixed $check): bool ``` Check that the input value has a valid International Bank Account Number IBAN syntax Requirements are uppercase, no whitespaces, max length 34, country code and checksum exist at right spots, body matches against checksum via Mod97-10 algorithm #### Parameters `mixed` $check The value to check #### Returns `bool` ### imageHeight() public static ``` imageHeight(mixed $file, string $operator, int $height): bool ``` Validates the image height. #### Parameters `mixed` $file The uploaded file data from PHP. `string` $operator Comparison operator. `int` $height Min or max height. #### Returns `bool` ### imageSize() public static ``` imageSize(mixed $file, array<string, mixed> $options): bool ``` Validates the size of an uploaded image. #### Parameters `mixed` $file The uploaded file data from PHP. `array<string, mixed>` $options Options to validate width and height. #### Returns `bool` #### Throws `InvalidArgumentException` ### imageWidth() public static ``` imageWidth(mixed $file, string $operator, int $width): bool ``` Validates the image width. #### Parameters `mixed` $file The uploaded file data from PHP. `string` $operator Comparison operator. `int` $width Min or max width. #### Returns `bool` ### inList() public static ``` inList(mixed $check, array<string> $list, bool $caseInsensitive = false): bool ``` Checks if a value is in a given list. Comparison is case sensitive by default. #### Parameters `mixed` $check Value to check. `array<string>` $list List to check against. `bool` $caseInsensitive optional Set to true for case insensitive comparison. #### Returns `bool` ### ip() public static ``` ip(mixed $check, string $type = 'both'): bool ``` Validation of an IP address. #### Parameters `mixed` $check The string to test. `string` $type optional The IP Protocol version to validate against #### Returns `bool` ### isArray() public static ``` isArray(mixed $value): bool ``` Check that the input value is an array. #### Parameters `mixed` $value The value to check #### Returns `bool` ### isInteger() public static ``` isInteger(mixed $value): bool ``` Check that the input value is an integer This method will accept strings that contain only integer data as well. #### Parameters `mixed` $value The value to check #### Returns `bool` ### isScalar() public static ``` isScalar(mixed $value): bool ``` Check that the input value is a scalar. This method will accept integers, floats, strings and booleans, but not accept arrays, objects, resources and nulls. #### Parameters `mixed` $value The value to check #### Returns `bool` ### iso8601() public static ``` iso8601(mixed $check): bool ``` Validates an iso8601 datetime format ISO8601 recognize datetime like 2019 as a valid date. To validate and check date integrity, use @see \Cake\Validation\Validation::datetime() #### Parameters `mixed` $check Value to check #### Returns `bool` #### See Also Regex credits: https://www.myintervals.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/ ### latitude() public static ``` latitude(mixed $value, array<string, mixed> $options = []): bool ``` Convenience method for latitude validation. #### Parameters `mixed` $value Latitude as string `array<string, mixed>` $options optional Options for the validation logic. #### Returns `bool` #### See Also \Cake\Validation\Validation::geoCoordinate() #### Links https://en.wikipedia.org/wiki/Latitude ### lengthBetween() public static ``` lengthBetween(mixed $check, int $min, int $max): bool ``` Checks that a string length is within specified range. Spaces are included in the character count. Returns true if string matches value min, max, or between min and max, #### Parameters `mixed` $check Value to check for length `int` $min Minimum value in range (inclusive) `int` $max Maximum value in range (inclusive) #### Returns `bool` ### localizedTime() public static ``` localizedTime(mixed $check, string $type = 'datetime', string|int|null $format = null): bool ``` Date and/or time string validation. Uses `I18n::Time` to parse the date. This means parsing is locale dependent. #### Parameters `mixed` $check a date string or object (will always pass) `string` $type optional Parser type, one out of 'date', 'time', and 'datetime' `string|int|null` $format optional any format accepted by IntlDateFormatter #### Returns `bool` #### Throws `InvalidArgumentException` when unsupported $type given #### See Also \Cake\I18n\Time::parseDate() \Cake\I18n\Time::parseTime() \Cake\I18n\Time::parseDateTime() ### longitude() public static ``` longitude(mixed $value, array<string, mixed> $options = []): bool ``` Convenience method for longitude validation. #### Parameters `mixed` $value Latitude as string `array<string, mixed>` $options optional Options for the validation logic. #### Returns `bool` #### See Also \Cake\Validation\Validation::geoCoordinate() #### Links https://en.wikipedia.org/wiki/Longitude ### luhn() public static ``` luhn(mixed $check): bool ``` Luhn algorithm #### Parameters `mixed` $check Value to check. #### Returns `bool` #### See Also https://en.wikipedia.org/wiki/Luhn\_algorithm ### maxLength() public static ``` maxLength(mixed $check, int $max): bool ``` Checks whether the length of a string (in characters) is smaller or equal to a maximal length. #### Parameters `mixed` $check The string to test `int` $max The maximal string length #### Returns `bool` ### maxLengthBytes() public static ``` maxLengthBytes(mixed $check, int $max): bool ``` Checks whether the length of a string (in bytes) is smaller or equal to a maximal length. #### Parameters `mixed` $check The string to test `int` $max The maximal string length #### Returns `bool` ### mimeType() public static ``` mimeType(Psr\Http\Message\UploadedFileInterface|array|string $check, array|string $mimeTypes = []): bool ``` Checks the mime type of a file. Will check the mimetype of files/UploadedFileInterface instances by checking the using finfo on the file, not relying on the content-type sent by the client. #### Parameters `Psr\Http\Message\UploadedFileInterface|array|string` $check Value to check. `array|string` $mimeTypes optional Array of mime types or regex pattern to check. #### Returns `bool` #### Throws `RuntimeException` when mime type can not be determined. `LogicException` when ext/fileinfo is missing ### minLength() public static ``` minLength(mixed $check, int $min): bool ``` Checks whether the length of a string (in characters) is greater or equal to a minimal length. #### Parameters `mixed` $check The string to test `int` $min The minimal string length #### Returns `bool` ### minLengthBytes() public static ``` minLengthBytes(mixed $check, int $min): bool ``` Checks whether the length of a string (in bytes) is greater or equal to a minimal length. #### Parameters `mixed` $check The string to test `int` $min The minimal string length (in bytes) #### Returns `bool` ### money() public static ``` money(mixed $check, string $symbolPosition = 'left'): bool ``` Checks that a value is a monetary amount. #### Parameters `mixed` $check Value to check `string` $symbolPosition optional Where symbol is located (left/right) #### Returns `bool` ### multiple() public static ``` multiple(mixed $check, array<string, mixed> $options = [], bool $caseInsensitive = false): bool ``` Validates a multiple select. Comparison is case sensitive by default. Valid Options * in => provide a list of choices that selections must be made from * max => maximum number of non-zero choices that can be made * min => minimum number of non-zero choices that can be made #### Parameters `mixed` $check Value to check `array<string, mixed>` $options optional Options for the check. `bool` $caseInsensitive optional Set to true for case insensitive comparison. #### Returns `bool` ### naturalNumber() public static ``` naturalNumber(mixed $check, bool $allowZero = false): bool ``` Checks if a value is a natural number. #### Parameters `mixed` $check Value to check `bool` $allowZero optional Set true to allow zero, defaults to false #### Returns `bool` #### See Also https://en.wikipedia.org/wiki/Natural\_number ### notAlphaNumeric() public static ``` notAlphaNumeric(mixed $check): bool ``` Checks that a doesn't contain any alpha numeric characters This method's definition of letters and integers includes unicode characters. Use `notAsciiAlphaNumeric()` if you want to exclude ascii only. #### Parameters `mixed` $check Value to check #### Returns `bool` ### notAsciiAlphaNumeric() public static ``` notAsciiAlphaNumeric(mixed $check): bool ``` Checks that a doesn't contain any non-ascii alpha numeric characters #### Parameters `mixed` $check Value to check #### Returns `bool` ### notBlank() public static ``` notBlank(mixed $check): bool ``` Checks that a string contains something other than whitespace Returns true if string contains something other than whitespace #### Parameters `mixed` $check Value to check #### Returns `bool` ### numElements() public static ``` numElements(mixed $check, string $operator, int $expectedCount): bool ``` Used to check the count of a given value of type array or Countable. #### Parameters `mixed` $check The value to check the count on. `string` $operator Can be either a word or operand is greater >, is less <, greater or equal >= less or equal <=, is less <, equal to ==, not equal != `int` $expectedCount The expected count value. #### Returns `bool` ### numeric() public static ``` numeric(mixed $check): bool ``` Checks if a value is numeric. #### Parameters `mixed` $check Value to check #### Returns `bool` ### range() public static ``` range(mixed $check, float|null $lower = null, float|null $upper = null): bool ``` Validates that a number is in specified range. If $lower and $upper are set, the range is inclusive. If they are not set, will return true if $check is a legal finite on this platform. #### Parameters `mixed` $check Value to check `float|null` $lower optional Lower limit `float|null` $upper optional Upper limit #### Returns `bool` ### time() public static ``` time(mixed $check): bool ``` Time validation, determines if the string passed is a valid time. Validates time as 24hr (HH:MM[:SS][.FFFFFF]) or am/pm ([H]H:MM[a|p]m) Seconds and fractional seconds (microseconds) are allowed but optional in 24hr format. #### Parameters `mixed` $check a valid time string/object #### Returns `bool` ### truthy() public static ``` truthy(string|int|bool $check, array<string|int|bool> $truthyValues = []): bool ``` Validates if given value is truthy. The list of what is considered to be truthy values, may be set via $truthyValues. #### Parameters `string|int|bool` $check Value to check. `array<string|int|bool>` $truthyValues optional List of valid truthy values, defaults to `[true, 1, '1']`. #### Returns `bool` ### uploadError() public static ``` uploadError(Psr\Http\Message\UploadedFileInterface|array|string $check, bool $allowNoFile = false): bool ``` Checking for upload errors #### Parameters `Psr\Http\Message\UploadedFileInterface|array|string` $check Value to check. `bool` $allowNoFile optional Set to true to allow UPLOAD\_ERR\_NO\_FILE as a pass. #### Returns `bool` #### See Also https://secure.php.net/manual/en/features.file-upload.errors.php ### uploadedFile() public static ``` uploadedFile(mixed $file, array<string, mixed> $options = []): bool ``` Validate an uploaded file. Helps join `uploadError`, `fileSize` and `mimeType` into one higher level validation method. ### Options * `types` - An array of valid mime types. If empty all types will be accepted. The `type` will not be looked at, instead the file type will be checked with ext/finfo. * `minSize` - The minimum file size in bytes. Defaults to not checking. * `maxSize` - The maximum file size in bytes. Defaults to not checking. * `optional` - Whether this file is optional. Defaults to false. If true a missing file will pass the validator regardless of other constraints. #### Parameters `mixed` $file The uploaded file data from PHP. `array<string, mixed>` $options optional An array of options for the validation. #### Returns `bool` ### url() public static ``` url(mixed $check, bool $strict = false): bool ``` Checks that a value is a valid URL according to <https://www.w3.org/Addressing/URL/url-spec.txt> The regex checks for the following component parts: * a valid, optional, scheme * a valid IP address OR a valid domain name as defined by section 2.3.1 of <https://www.ietf.org/rfc/rfc1035.txt> with an optional port number * an optional valid path * an optional query string (get parameters) * an optional fragment (anchor tag) as defined in RFC 3986 #### Parameters `mixed` $check Value to check `bool` $strict optional Require URL to be prefixed by a valid scheme (one of http(s)/ftp(s)/file/news/gopher) #### Returns `bool` #### Links https://tools.ietf.org/html/rfc3986 ### utf8() public static ``` utf8(mixed $value, array<string, mixed> $options = []): bool ``` Check that the input value is a utf8 string. This method will reject all non-string values. Options ======= * `extended` - Disallow bytes higher within the basic multilingual plane. MySQL's older utf8 encoding type does not allow characters above the basic multilingual plane. Defaults to false. #### Parameters `mixed` $value The value to check `array<string, mixed>` $options optional An array of options. See above for the supported options. #### Returns `bool` ### uuid() public static ``` uuid(mixed $check): bool ``` Checks that a value is a valid UUID - <https://tools.ietf.org/html/rfc4122> #### Parameters `mixed` $check Value to check #### Returns `bool` Property Detail --------------- ### $\_pattern protected static Some complex patterns needed in multiple places #### Type `array<string, string>` ### $errors public static Holds an array of errors messages set in this class. These are used for debugging purposes #### Type `array`
programming_docs
cakephp Class MissingConnectionException Class MissingConnectionException ================================= Class MissingConnectionException **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 Utility Namespace Utility ================= ### Namespaces * [Cake\Utility\Crypto](namespace-cake.utility.crypto) * [Cake\Utility\Exception](namespace-cake.utility.exception) ### Classes * ##### [Hash](class-cake.utility.hash) Library of array functions for manipulating and extracting data from arrays or 'sets' of data. * ##### [Inflector](class-cake.utility.inflector) Pluralize and singularize English words. * ##### [Security](class-cake.utility.security) Security Library contains utility methods related to security * ##### [Text](class-cake.utility.text) Text handling methods. * ##### [Xml](class-cake.utility.xml) XML handling for CakePHP. ### Traits * ##### [CookieCryptTrait](trait-cake.utility.cookiecrypttrait) Cookie Crypt Trait. * ##### [MergeVariablesTrait](trait-cake.utility.mergevariablestrait) Provides features for merging object properties recursively with parent classes. cakephp Namespace Exception Namespace Exception =================== ### Classes * ##### [DatabaseException](class-cake.database.exception.databaseexception) Exception for the database package. * ##### [MissingConnectionException](class-cake.database.exception.missingconnectionexception) Class MissingConnectionException * ##### [MissingDriverException](class-cake.database.exception.missingdriverexception) Class MissingDriverException * ##### [MissingExtensionException](class-cake.database.exception.missingextensionexception) Class MissingExtensionException * ##### [NestedTransactionRollbackException](class-cake.database.exception.nestedtransactionrollbackexception) Class NestedTransactionRollbackException cakephp Class ErrorLogger Class ErrorLogger ================== Log errors and unhandled exceptions to `Cake\Log\Log` **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>` Default configuration values. 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. * ##### [getConfig()](#getConfig()) public Returns the config. * ##### [getConfigOrFail()](#getConfigOrFail()) public Returns the config for this specific key. * ##### [getMessage()](#getMessage()) protected Generate the message for the exception * ##### [getRequestContext()](#getRequestContext()) public Get the request context for an error/exception trace. * ##### [log()](#log()) public deprecated Log an error for an exception with optional request context. * ##### [logError()](#logError()) public Log an error to Cake's Log subsystem * ##### [logException()](#logException()) public Log an exception to Cake's Log subsystem * ##### [logMessage()](#logMessage()) public deprecated Log a an error message to the error logger. * ##### [setConfig()](#setConfig()) public Sets the config. Method Detail ------------- ### \_\_construct() public ``` __construct(array<string, mixed> $config = []) ``` Constructor #### Parameters `array<string, mixed>` $config optional Config 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 ### 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` ### getMessage() protected ``` getMessage(Throwable $exception, bool $isPrevious = false, bool $includeTrace = false): string ``` Generate the message for the exception #### Parameters `Throwable` $exception The exception to log a message for. `bool` $isPrevious optional False for original exception, true for previous `bool` $includeTrace optional Whether or not to include a stack trace. #### Returns `string` ### getRequestContext() public ``` getRequestContext(Psr\Http\Message\ServerRequestInterface $request): string ``` Get the request context for an error/exception trace. #### Parameters `Psr\Http\Message\ServerRequestInterface` $request The request to read from. #### Returns `string` ### log() public ``` log(Throwable $exception, Psr\Http\Message\ServerRequestInterface|null $request = null): bool ``` Log an error for an exception with optional request context. #### Parameters `Throwable` $exception The exception to log a message for. `Psr\Http\Message\ServerRequestInterface|null` $request optional The current request if available. #### Returns `bool` ### logError() public ``` logError(Cake\Error\PhpError $error, Psr\Http\Message\ServerRequestInterface $request = null, bool $includeTrace = false): void ``` Log an error to Cake's Log subsystem #### Parameters `Cake\Error\PhpError` $error The error to log `Psr\Http\Message\ServerRequestInterface` $request optional The request if in an HTTP context. `bool` $includeTrace optional Should the log message include a stacktrace #### Returns `void` ### logException() public ``` logException(Throwable $exception, Psr\Http\Message\ServerRequestInterface|null $request = null, bool $includeTrace = false): void ``` Log an exception to Cake's Log subsystem #### Parameters `Throwable` $exception The exception to log a message for. `Psr\Http\Message\ServerRequestInterface|null` $request optional The current request if available. `bool` $includeTrace optional Whether or not a stack trace should be logged. #### Returns `void` ### logMessage() public ``` logMessage(string|int $level, string $message, array $context = []): bool ``` Log a an error message to the error logger. #### Parameters `string|int` $level The logging level `string` $message The message to be logged. `array` $context optional Context. #### 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 configuration values. * `trace` Should error logs include stack traces? #### Type `array<string, mixed>` cakephp Class CachedCollection Class CachedCollection ======================= Decorates a schema collection and adds caching **Namespace:** [Cake\Database\Schema](namespace-cake.database.schema) Property Summary ---------------- * [$cacher](#%24cacher) protected `Psr\SimpleCache\CacheInterface` Cacher instance. * [$collection](#%24collection) protected `Cake\Database\Schema\CollectionInterface` The decorated schema collection * [$prefix](#%24prefix) protected `string` The cache key prefix Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [cacheKey()](#cacheKey()) public Get the cache key for a given name. * ##### [describe()](#describe()) public Get the column metadata for a table. * ##### [getCacher()](#getCacher()) public Get a cacher. * ##### [listTables()](#listTables()) public Get the list of tables available in the current connection. * ##### [listTablesWithoutViews()](#listTablesWithoutViews()) public Get the list of tables available in the current connection. This will exclude any views in the schema. * ##### [setCacher()](#setCacher()) public Set a cacher. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\Database\Schema\CollectionInterface $collection, string $prefix, Psr\SimpleCache\CacheInterface $cacher) ``` Constructor. #### Parameters `Cake\Database\Schema\CollectionInterface` $collection The collection to wrap. `string` $prefix The cache key prefix to use. Typically the connection name. `Psr\SimpleCache\CacheInterface` $cacher Cacher instance. ### cacheKey() public ``` cacheKey(string $name): string ``` Get the cache key for a given name. #### Parameters `string` $name The name to get a cache key for. #### Returns `string` ### describe() public ``` describe(string $name, array<string, mixed> $options = []): Cake\Database\Schema\TableSchemaInterface ``` Get the column metadata for a 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 `array<string, mixed>` $options optional #### Returns `Cake\Database\Schema\TableSchemaInterface` ### getCacher() public ``` getCacher(): Psr\SimpleCache\CacheInterface ``` Get a cacher. #### Returns `Psr\SimpleCache\CacheInterface` ### listTables() public ``` listTables(): array<string> ``` Get the list of tables available in the current connection. #### Returns `array<string>` ### listTablesWithoutViews() public ``` listTablesWithoutViews(): array ``` Get the list of tables available in the current connection. This will exclude any views in the schema. #### Returns `array` ### setCacher() public ``` setCacher(Psr\SimpleCache\CacheInterface $cacher): $this ``` Set a cacher. #### Parameters `Psr\SimpleCache\CacheInterface` $cacher Cacher object #### Returns `$this` Property Detail --------------- ### $cacher protected Cacher instance. #### Type `Psr\SimpleCache\CacheInterface` ### $collection protected The decorated schema collection #### Type `Cake\Database\Schema\CollectionInterface` ### $prefix protected The cache key prefix #### Type `string` cakephp Class PostgresCompiler Class PostgresCompiler ======================= Responsible for compiling a Query object into its SQL representation for Postgres **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` Indicate whether this query dialect supports ordered unions. * [$\_quotedSelectAliases](#%24_quotedSelectAliases) protected `bool` Always quote aliases in SELECT clause. * [$\_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 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` ### \_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 ``` 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 Indicate whether this query dialect supports ordered unions. Overridden in subclasses. #### Type `bool` ### $\_quotedSelectAliases protected Always quote aliases in SELECT clause. Postgres auto converts unquoted identifiers to lower case. #### 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 Namespace Database Namespace Database ================== ### Namespaces * [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) ### Interfaces * ##### [ConstraintsInterface](interface-cake.database.constraintsinterface) Defines the interface for a fixture that needs to manage constraints. * ##### [DriverInterface](interface-cake.database.driverinterface) Interface for database driver. * ##### [ExpressionInterface](interface-cake.database.expressioninterface) An interface used by Expression objects. * ##### [StatementInterface](interface-cake.database.statementinterface) Represents a database statement. Concrete implementations can either use PDOStatement or a native driver * ##### [TypeInterface](interface-cake.database.typeinterface) Encapsulates all conversion functions for values coming from a database into PHP and going from PHP into a database. * ##### [TypedResultInterface](interface-cake.database.typedresultinterface) Represents an expression that is known to return a specific type ### Classes * ##### [Connection](class-cake.database.connection) Represents a connection with a database server. * ##### [Driver](class-cake.database.driver) Represents a database driver containing all specificities for a database engine including its SQL dialect. * ##### [FieldTypeConverter](class-cake.database.fieldtypeconverter) A callable class to be used for processing each of the rows in a statement result, so that the values are converted to the right PHP types. * ##### [FunctionsBuilder](class-cake.database.functionsbuilder) Contains methods related to generating FunctionExpression objects with most commonly used SQL functions. This acts as a factory for FunctionExpression objects. * ##### [IdentifierQuoter](class-cake.database.identifierquoter) Contains all the logic related to quoting identifiers in a Query object * ##### [PostgresCompiler](class-cake.database.postgrescompiler) Responsible for compiling a Query object into its SQL representation for Postgres * ##### [Query](class-cake.database.query) This class represents a Relational database SQL Query. A query can be of different types like select, update, insert and delete. Exposes the methods for dynamically constructing each query part, execute it and transform it to a specific SQL dialect. * ##### [QueryCompiler](class-cake.database.querycompiler) Responsible for compiling a Query object into its SQL representation * ##### [SchemaCache](class-cake.database.schemacache) Schema Cache. * ##### [SqliteCompiler](class-cake.database.sqlitecompiler) Responsible for compiling a Query object into its SQL representation for SQLite * ##### [SqlserverCompiler](class-cake.database.sqlservercompiler) Responsible for compiling a Query object into its SQL representation for SQL Server * ##### [TypeFactory](class-cake.database.typefactory) Factory for building database type classes. * ##### [TypeMap](class-cake.database.typemap) Implements default and single-use mappings for columns to their associated types * ##### [ValueBinder](class-cake.database.valuebinder) Value binder class manages list of values bound to conditions. ### Traits * ##### [TypeConverterTrait](trait-cake.database.typeconvertertrait) Type converter trait * ##### [TypeMapTrait](trait-cake.database.typemaptrait) Trait TypeMapTrait * ##### [TypedResultTrait](trait-cake.database.typedresulttrait) Implements the TypedResultInterface cakephp Interface TableSchemaAwareInterface Interface TableSchemaAwareInterface ==================================== Defines the interface for getting the schema. **Namespace:** [Cake\Database\Schema](namespace-cake.database.schema) Method Summary -------------- * ##### [getTableSchema()](#getTableSchema()) public Get and set the schema for this fixture. * ##### [setTableSchema()](#setTableSchema()) public Get and set the schema for this fixture. Method Detail ------------- ### 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` ### 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 The table to set. #### Returns `$this` cakephp Interface CollectionInterface Interface CollectionInterface ============================== 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) Method Summary -------------- * ##### [describe()](#describe()) public Get the column metadata for a table. * ##### [listTables()](#listTables()) public Get the list of tables available in the current connection. * ##### [listTablesWithoutViews()](#listTablesWithoutViews()) public @method Get the list of tables available in the current connection. This will exclude any views in the schema. Method Detail ------------- ### describe() public ``` describe(string $name, array<string, mixed> $options = []): Cake\Database\Schema\TableSchemaInterface ``` Get the column metadata for a 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\TableSchemaInterface` #### Throws `Cake\Database\Exception\DatabaseException` when table cannot be described. ### listTables() public ``` listTables(): array<string> ``` Get the list of tables available in the current connection. #### Returns `array<string>` ### listTablesWithoutViews() public @method ``` listTablesWithoutViews(): array<string> ``` Get the list of tables available in the current connection. This will exclude any views in the schema. #### Returns `array<string>` cakephp Namespace Exception Namespace Exception =================== ### Classes * ##### [MissingActionException](class-cake.mailer.exception.missingactionexception) Missing Action exception - used when a mailer action cannot be found. * ##### [MissingMailerException](class-cake.mailer.exception.missingmailerexception) Used when a mailer cannot be found. cakephp Class NoChildrenIterator Class 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. **Namespace:** [Cake\Collection\Iterator](namespace-cake.collection.iterator) 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 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 self instance without any elements. * ##### [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 false as there are no children iterators in this collection * ##### [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 #### 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 self instance without any elements. #### 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 false as there are no children iterators in this collection #### 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`
programming_docs
cakephp Class ArrayItemNode Class ArrayItemNode ==================== Dump node for Array Items. **Namespace:** [Cake\Error\Debug](namespace-cake.error.debug) Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [getChildren()](#getChildren()) public Get the child nodes of this node. * ##### [getKey()](#getKey()) public Get the key * ##### [getValue()](#getValue()) public Get the value Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\Error\Debug\NodeInterface $key, Cake\Error\Debug\NodeInterface $value) ``` Constructor #### Parameters `Cake\Error\Debug\NodeInterface` $key The node for the item key `Cake\Error\Debug\NodeInterface` $value The node for the array value ### getChildren() public ``` getChildren(): arrayCake\Error\Debug\NodeInterface> ``` Get the child nodes of this node. #### Returns `arrayCake\Error\Debug\NodeInterface>` ### getKey() public ``` getKey(): Cake\Error\Debug\NodeInterface ``` Get the key #### Returns `Cake\Error\Debug\NodeInterface` ### getValue() public ``` getValue(): Cake\Error\Debug\NodeInterface ``` Get the value #### Returns `Cake\Error\Debug\NodeInterface` cakephp Interface CacheEngineInterface Interface CacheEngineInterface =============================== Interface for cache engines that defines methods outside of the PSR16 interface that are used by `Cache`. Internally Cache uses this interface when calling engine methods. **Namespace:** [Cake\Cache](namespace-cake.cache) Method Summary -------------- * ##### [add()](#add()) public Write data for key into a cache engine if it doesn't exist already. * ##### [clearGroup()](#clearGroup()) public Clear all values belonging to the named group. * ##### [decrement()](#decrement()) public Decrement a number under the key and return decremented value * ##### [increment()](#increment()) public Increment a number under the key and return incremented value Method Detail ------------- ### add() public ``` add(string $key, mixed $value): bool ``` Write data for key into a cache engine if it doesn't exist already. #### Parameters `string` $key Identifier for the data. `mixed` $value Data to be cached - anything except a resource. #### Returns `bool` ### clearGroup() public ``` clearGroup(string $group): bool ``` Clear all values belonging to the named group. 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` ### decrement() 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` ### increment() 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` cakephp Class RuleInvoker Class RuleInvoker ================== Contains logic for invoking an application rule. Combined with {@link \Cake\Datasource\RulesChecker} as an implementation detail to de-duplicate rule decoration and provide cleaner separation of duties. **Namespace:** [Cake\Datasource](namespace-cake.datasource) Property Summary ---------------- * [$name](#%24name) protected `string|null` The rule name * [$options](#%24options) protected `array<string, mixed>` Rule options * [$rule](#%24rule) protected `callable` Rule callable Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [\_\_invoke()](#__invoke()) public Invoke the rule. * ##### [setName()](#setName()) public Set the rule name. * ##### [setOptions()](#setOptions()) public Set options for the rule invocation. Method Detail ------------- ### \_\_construct() public ``` __construct(callable $rule, ?string $name, array<string, mixed> $options = []) ``` Constructor ### Options * `errorField` The field errors should be set onto. * `message` The error message. Individual rules may have additional options that can be set here. Any options will be passed into the rule as part of the rule $scope. #### Parameters `callable` $rule The rule to be invoked. `?string` $name The name of the rule. Used in error messages. `array<string, mixed>` $options optional The options for the rule. See above. ### \_\_invoke() public ``` __invoke(Cake\Datasource\EntityInterface $entity, array $scope): bool ``` Invoke the rule. #### Parameters `Cake\Datasource\EntityInterface` $entity The entity the rule should apply to. `array` $scope The rule's scope/options. #### Returns `bool` ### setName() public ``` setName(string|null $name): $this ``` Set the rule name. Only truthy names will be set. #### Parameters `string|null` $name The name to set. #### Returns `$this` ### setOptions() public ``` setOptions(array<string, mixed> $options): $this ``` Set options for the rule invocation. Old options will be merged with the new ones. #### Parameters `array<string, mixed>` $options The options to set. #### Returns `$this` Property Detail --------------- ### $name protected The rule name #### Type `string|null` ### $options protected Rule options #### Type `array<string, mixed>` ### $rule protected Rule callable #### Type `callable` cakephp Class ExceptionRenderer Class ExceptionRenderer ======================== Backwards compatible Exception Renderer. **Namespace:** [Cake\Error](namespace-cake.error) **Deprecated:** 4.4.0 Use `Cake\Error\Renderer\WebExceptionRenderer` instead. Property Summary ---------------- * [$controller](#%24controller) protected `Cake\Controller\Controller` Controller instance. * [$error](#%24error) protected `Throwable` The exception being handled. * [$exceptionHttpCodes](#%24exceptionHttpCodes) protected `array<string, int>` Map of exceptions to http status codes. * [$method](#%24method) protected `string` The method corresponding to the Exception this object is for. * [$request](#%24request) protected `Cake\Http\ServerRequest|null` If set, this will be request used to create the controller that will render the error. * [$template](#%24template) protected `string` Template to render for {@link \Cake\Core\Exception\CakeException} Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Creates the controller to perform rendering on the error response. * ##### [\_\_debugInfo()](#__debugInfo()) public Returns an array that can be used to describe the internal state of this object. * ##### [\_customMethod()](#_customMethod()) protected Render a custom error method/template. * ##### [\_getController()](#_getController()) protected Get the controller instance to handle the exception. Override this method in subclasses to customize the controller used. This method returns the built in `ErrorController` normally, or if an error is repeated a bare controller will be used. * ##### [\_message()](#_message()) protected Get error message. * ##### [\_method()](#_method()) protected Get method name * ##### [\_outputMessage()](#_outputMessage()) protected Generate the response using the controller object. * ##### [\_outputMessageSafe()](#_outputMessageSafe()) protected A safer way to render error messages, replaces all helpers, with basics and doesn't call component methods. * ##### [\_shutdown()](#_shutdown()) protected Run the shutdown events. * ##### [\_template()](#_template()) protected Get template for rendering exception info. * ##### [clearOutput()](#clearOutput()) protected Clear output buffers so error pages display properly. * ##### [getHttpCode()](#getHttpCode()) protected Gets the appropriate http status code for exception. * ##### [render()](#render()) public Renders the response for the exception. * ##### [write()](#write()) public Emit the response content Method Detail ------------- ### \_\_construct() public ``` __construct(Throwable $exception, Cake\Http\ServerRequest|null $request = null) ``` Creates the controller to perform rendering on the error response. #### Parameters `Throwable` $exception Exception. `Cake\Http\ServerRequest|null` $request optional The request if this is set it will be used instead of creating a new one. ### \_\_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>` ### \_customMethod() protected ``` _customMethod(string $method, Throwable $exception): Cake\Http\Response ``` Render a custom error method/template. #### Parameters `string` $method The method name to invoke. `Throwable` $exception The exception to render. #### Returns `Cake\Http\Response` ### \_getController() protected ``` _getController(): Cake\Controller\Controller ``` Get the controller instance to handle the exception. Override this method in subclasses to customize the controller used. This method returns the built in `ErrorController` normally, or if an error is repeated a bare controller will be used. #### Returns `Cake\Controller\Controller` ### \_message() protected ``` _message(Throwable $exception, int $code): string ``` Get error message. #### Parameters `Throwable` $exception Exception. `int` $code Error code. #### Returns `string` ### \_method() protected ``` _method(Throwable $exception): string ``` Get method name #### Parameters `Throwable` $exception Exception instance. #### Returns `string` ### \_outputMessage() protected ``` _outputMessage(string $template): Cake\Http\Response ``` Generate the response using the controller object. #### Parameters `string` $template The template to render. #### Returns `Cake\Http\Response` ### \_outputMessageSafe() protected ``` _outputMessageSafe(string $template): Cake\Http\Response ``` A safer way to render error messages, replaces all helpers, with basics and doesn't call component methods. #### Parameters `string` $template The template to render. #### Returns `Cake\Http\Response` ### \_shutdown() protected ``` _shutdown(): Cake\Http\Response ``` Run the shutdown events. Triggers the afterFilter and afterDispatch events. #### Returns `Cake\Http\Response` ### \_template() protected ``` _template(Throwable $exception, string $method, int $code): string ``` Get template for rendering exception info. #### Parameters `Throwable` $exception Exception instance. `string` $method Method name. `int` $code Error code. #### Returns `string` ### clearOutput() protected ``` clearOutput(): void ``` Clear output buffers so error pages display properly. #### Returns `void` ### getHttpCode() protected ``` getHttpCode(Throwable $exception): int ``` Gets the appropriate http status code for exception. #### Parameters `Throwable` $exception Exception. #### Returns `int` ### render() public ``` render(): Cake\Http\Response ``` Renders the response for the exception. #### Returns `Cake\Http\Response` ### write() public ``` write(Psr\Http\Message\ResponseInterface|string $output): void ``` Emit the response content #### Parameters `Psr\Http\Message\ResponseInterface|string` $output The response to output. #### Returns `void` Property Detail --------------- ### $controller protected Controller instance. #### Type `Cake\Controller\Controller` ### $error protected The exception being handled. #### Type `Throwable` ### $exceptionHttpCodes protected Map of exceptions to http status codes. This can be customized for users that don't want specific exceptions to throw 404 errors or want their application exceptions to be automatically converted. #### Type `array<string, int>` ### $method protected The method corresponding to the Exception this object is for. #### Type `string` ### $request protected If set, this will be request used to create the controller that will render the error. #### Type `Cake\Http\ServerRequest|null` ### $template protected Template to render for {@link \Cake\Core\Exception\CakeException} #### Type `string` cakephp Interface DriverInterface Interface DriverInterface ========================== Interface for database driver. **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). Method Summary -------------- * ##### [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 @method Returns the number of connection retry attempts made. * ##### [getConnection()](#getConnection()) public Returns correct connection resource or object that is internally used. * ##### [getMaxAliasLength()](#getMaxAliasLength()) public @method Returns the maximum alias length allowed. * ##### [inTransaction()](#inTransaction()) public @method Returns whether a transaction is active. * ##### [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 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()) public Get the schema dialect. * ##### [schemaValue()](#schemaValue()) public Escapes values for use in schema definitions. * ##### [setConnection()](#setConnection()) public Set the internal connection object. * ##### [supports()](#supports()) public @method Checks whether a feature is supported by the driver. * ##### [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. * ##### [supportsSavePoints()](#supportsSavePoints()) public deprecated Returns whether this driver supports save points for nested transactions. Method Detail ------------- ### 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 The query to compile. `Cake\Database\ValueBinder` $binder The value binder to use. #### Returns `array` ### connect() public ``` connect(): bool ``` Establishes a connection to the database server. #### Returns `bool` #### Throws `Cake\Database\Exception\MissingConnectionException` If database connection could not be established. ### 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 Whether to enable auto quoting #### 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 @method ``` getConnectRetries(): int ``` Returns the number of connection retry attempts made. #### Returns `int` ### getConnection() public ``` getConnection(): object ``` Returns correct connection resource or object that is internally used. #### Returns `object` ### getMaxAliasLength() public @method ``` getMaxAliasLength(): int|null ``` Returns the maximum alias length allowed. #### Returns `int|null` ### inTransaction() public @method ``` inTransaction(): bool ``` Returns whether a transaction is active. #### 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 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` ### 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 The table name. `array` $columns optional The list of columns for the schema. #### 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 turn into a prepared statement. #### 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): string ``` Returns a value in a safe representation to be used in a query string #### Parameters `mixed` $value The value to quote. `int` $type Must be one of the \PDO::PARAM\_\* constants #### 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 expression to quote. #### 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() 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 The value to escape. #### Returns `string` ### setConnection() public ``` setConnection(object $connection): $this ``` Set the internal connection object. #### Parameters `object` $connection The connection instance. #### Returns `$this` ### supports() public @method ``` supports(string $feature): bool ``` Checks whether a feature is supported by the driver. #### Parameters `string` $feature #### 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. #### Returns `bool` ### supportsSavePoints() public ``` supportsSavePoints(): bool ``` Returns whether this driver supports save points for nested transactions. #### Returns `bool`
programming_docs
cakephp Class Basic Class Basic ============ Basic authentication adapter for Cake\Http\Client Generally not directly constructed, but instead used by {@link \Cake\Http\Client} when $options['auth']['type'] is 'basic' **Namespace:** [Cake\Http\Client\Auth](namespace-cake.http.client.auth) Method Summary -------------- * ##### [\_generateHeader()](#_generateHeader()) protected Generate basic [proxy] authentication header * ##### [authentication()](#authentication()) public Add Authorization header to the request. * ##### [proxyAuthentication()](#proxyAuthentication()) public Proxy Authentication Method Detail ------------- ### \_generateHeader() protected ``` _generateHeader(string $user, string $pass): string ``` Generate basic [proxy] authentication header #### Parameters `string` $user Username. `string` $pass Password. #### Returns `string` ### authentication() public ``` authentication(Cake\Http\Client\Request $request, array $credentials): Cake\Http\Client\Request ``` Add Authorization header to the request. #### Parameters `Cake\Http\Client\Request` $request Request instance. `array` $credentials Credentials. #### Returns `Cake\Http\Client\Request` #### See Also https://www.ietf.org/rfc/rfc2617.txt ### proxyAuthentication() public ``` proxyAuthentication(Cake\Http\Client\Request $request, array $credentials): Cake\Http\Client\Request ``` Proxy Authentication #### Parameters `Cake\Http\Client\Request` $request Request instance. `array` $credentials Credentials. #### Returns `Cake\Http\Client\Request` #### See Also https://www.ietf.org/rfc/rfc2617.txt cakephp Class Arguments Class Arguments ================ Provides an interface for interacting with a command's options and arguments. **Namespace:** [Cake\Console](namespace-cake.console) Property Summary ---------------- * [$argNames](#%24argNames) protected `array<int, string>` Positional argument name map * [$args](#%24args) protected `array<int, string>` Positional arguments. * [$options](#%24options) protected `array<string, string|int|bool|null>` Named options Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [getArgument()](#getArgument()) public Check if a positional argument exists by name * ##### [getArgumentAt()](#getArgumentAt()) public Get positional arguments by index. * ##### [getArguments()](#getArguments()) public Get all positional arguments. * ##### [getOption()](#getOption()) public Get an option's value or null * ##### [getOptions()](#getOptions()) public Get an array of all the options * ##### [hasArgument()](#hasArgument()) public Check if a positional argument exists by name * ##### [hasArgumentAt()](#hasArgumentAt()) public Check if a positional argument exists * ##### [hasOption()](#hasOption()) public Check if an option is defined and not null. Method Detail ------------- ### \_\_construct() public ``` __construct(array<int, string> $args, array<string, string|int|bool|null> $options, array<int, string> $argNames) ``` Constructor #### Parameters `array<int, string>` $args Positional arguments `array<string, string|int|bool|null>` $options Named arguments `array<int, string>` $argNames List of argument names. Order is expected to be the same as $args. ### getArgument() public ``` getArgument(string $name): string|null ``` Check if a positional argument exists by name #### Parameters `string` $name The argument name to check. #### Returns `string|null` ### getArgumentAt() public ``` getArgumentAt(int $index): string|null ``` Get positional arguments by index. #### Parameters `int` $index The argument index to access. #### Returns `string|null` ### getArguments() public ``` getArguments(): array<int, string> ``` Get all positional arguments. #### Returns `array<int, string>` ### getOption() public ``` getOption(string $name): string|int|bool|null ``` Get an option's value or null #### Parameters `string` $name The name of the option to check. #### Returns `string|int|bool|null` ### getOptions() public ``` getOptions(): array<string, string|int|bool|null> ``` Get an array of all the options #### Returns `array<string, string|int|bool|null>` ### hasArgument() public ``` hasArgument(string $name): bool ``` Check if a positional argument exists by name #### Parameters `string` $name The argument name to check. #### Returns `bool` ### hasArgumentAt() public ``` hasArgumentAt(int $index): bool ``` Check if a positional argument exists #### Parameters `int` $index The argument index to check. #### Returns `bool` ### hasOption() public ``` hasOption(string $name): bool ``` Check if an option is defined and not null. #### Parameters `string` $name The name of the option to check. #### Returns `bool` Property Detail --------------- ### $argNames protected Positional argument name map #### Type `array<int, string>` ### $args protected Positional arguments. #### Type `array<int, string>` ### $options protected Named options #### Type `array<string, string|int|bool|null>` cakephp Class ProgressHelper Class ProgressHelper ===================== Create a progress bar using a supplied callback. Usage ----- The ProgressHelper can be accessed from shells using the helper() method ``` $this->helper('Progress')->output(['callback' => function ($progress) { // Do work $progress->increment(); }); ``` **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. * [$\_progress](#%24_progress) protected `float|int` The current progress. * [$\_total](#%24_total) protected `int` The total number of 'items' to progress through. * [$\_width](#%24_width) protected `int` The width of the bar. 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. * ##### [draw()](#draw()) public Render the progress bar based on the current state. * ##### [getConfig()](#getConfig()) public Returns the config. * ##### [getConfigOrFail()](#getConfigOrFail()) public Returns the config for this specific key. * ##### [increment()](#increment()) public Increment the progress bar. * ##### [init()](#init()) public Initialize the progress bar for use. * ##### [output()](#output()) public Output a progress bar. * ##### [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. ### \_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` ### draw() public ``` draw(): $this ``` Render the progress bar based on the current state. #### 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` ### increment() public ``` increment(float|int $num = 1): $this ``` Increment the progress bar. #### Parameters `float|int` $num optional The amount of progress to advance by. #### Returns `$this` ### init() public ``` init(array $args = []): $this ``` Initialize the progress bar for use. * `total` The total number of items in the progress bar. Defaults to 100. * `width` The width of the progress bar. Defaults to 80. #### Parameters `array` $args optional The initialization data. #### Returns `$this` ### output() public ``` output(array $args): void ``` Output a progress bar. Takes a number of options to customize the behavior: * `total` The total number of items in the progress bar. Defaults to 100. * `width` The width of the progress bar. Defaults to 80. * `callback` The callback that will be called in a loop to advance the progress bar. #### Parameters `array` $args The arguments/options to use when outputing the progress bar. #### 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` ### $\_progress protected The current progress. #### Type `float|int` ### $\_total protected The total number of 'items' to progress through. #### Type `int` ### $\_width protected The width of the bar. #### Type `int` cakephp Class ResponseBase Class ResponseBase =================== Base constraint for response constraints **Abstract** **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()) protected Evaluates the constraint for parameter $other. Returns true if the constraint is met, false otherwise. * ##### [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 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 ``` 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() protected ``` matches(mixed $other): bool ``` Evaluates the constraint for parameter $other. Returns true if the constraint is met, false otherwise. This method can be overridden to implement the evaluation algorithm. #### Parameters `mixed` $other value or object to evaluate #### 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 ``` 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 --------------- ### $response protected #### Type `Psr\Http\Message\ResponseInterface`
programming_docs
cakephp Class SpecialNode Class SpecialNode ================== Debug node for special messages like errors or recursion warnings. **Namespace:** [Cake\Error\Debug](namespace-cake.error.debug) Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [getChildren()](#getChildren()) public Get the child nodes of this node. * ##### [getValue()](#getValue()) public Get the message/value Method Detail ------------- ### \_\_construct() public ``` __construct(string $value) ``` Constructor #### Parameters `string` $value The message/value to include in dump results. ### getChildren() public ``` getChildren(): arrayCake\Error\Debug\NodeInterface> ``` Get the child nodes of this node. #### Returns `arrayCake\Error\Debug\NodeInterface>` ### getValue() public ``` getValue(): string ``` Get the message/value #### Returns `string` cakephp Class BaseAuthorize Class BaseAuthorize ==================== Abstract base authorization adapter for AuthComponent. **Abstract** **Namespace:** [Cake\Auth](namespace-cake.auth) **See:** \Cake\Controller\Component\AuthComponent::$authenticate 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 authorize objects. * [$\_registry](#%24_registry) protected `Cake\Controller\ComponentRegistry` ComponentRegistry instance for getting more components. 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. * ##### [authorize()](#authorize()) abstract public Checks user authorization. * ##### [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. * ##### [setConfig()](#setConfig()) public Sets the config. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\Controller\ComponentRegistry $registry, array<string, mixed> $config = []) ``` Constructor #### Parameters `Cake\Controller\ComponentRegistry` $registry The controller for this request. `array<string, mixed>` $config optional An array of config. This class does not use any 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 ### authorize() abstract public ``` authorize(ArrayAccess|array $user, Cake\Http\ServerRequest $request): bool ``` Checks user authorization. #### Parameters `ArrayAccess|array` $user Active user data `Cake\Http\ServerRequest` $request Request instance. #### 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` ### 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 authorize objects. #### Type `array<string, mixed>` ### $\_registry protected ComponentRegistry instance for getting more components. #### Type `Cake\Controller\ComponentRegistry` cakephp Class DateTimeType Class DateTimeType =================== Datetime type converter. Use to convert datetime instances to strings & back. **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` cakephp Class ConsoleOptionParser Class ConsoleOptionParser ========================== Handles parsing the ARGV in the command line and provides support for GetOpt compatible option definition. Provides a builder pattern implementation for creating shell option parsers. ### Options Named arguments come in two forms, long and short. Long arguments are preceded by two - and give a more verbose option name. i.e. `--version`. Short arguments are preceded by one - and are only one character long. They usually match with a long option, and provide a more terse alternative. ### Using Options Options can be defined with both long and short forms. By using `$parser->addOption()` you can define new options. The name of the option is used as its long form, and you can supply an additional short form, with the `short` option. Short options should only be one letter long. Using more than one letter for a short option will raise an exception. Calling options can be done using syntax similar to most \*nix command line tools. Long options cane either include an `=` or leave it out. `cake my_command --connection default --name=something` Short options can be defined singly or in groups. `cake my_command -cn` Short options can be combined into groups as seen above. Each letter in a group will be treated as a separate option. The previous example is equivalent to: `cake my_command -c -n` Short options can also accept values: `cake my_command -c default` ### Positional arguments If no positional arguments are defined, all of them will be parsed. If you define positional arguments any arguments greater than those defined will cause exceptions. Additionally you can declare arguments as optional, by setting the required param to false. ``` $parser->addArgument('model', ['required' => false]); ``` ### Providing Help text By providing help text for your positional arguments and named arguments, the ConsoleOptionParser can generate a help display for you. You can view the help for shells by using the `--help` or `-h` switch. **Namespace:** [Cake\Console](namespace-cake.console) Property Summary ---------------- * [$\_args](#%24_args) protected `arrayCake\Console\ConsoleInputArgument>` Positional argument definitions. * [$\_command](#%24_command) protected `string` Command name. * [$\_description](#%24_description) protected `string` Description text - displays before options when help is generated * [$\_epilog](#%24_epilog) protected `string` Epilog text - displays after options when help is generated * [$\_options](#%24_options) protected `array<string,Cake\Console\ConsoleInputOption>` Option definitions. * [$\_shortOptions](#%24_shortOptions) protected `array<string, string>` Map of short -> long options, generated when using addOption() * [$\_subcommandSort](#%24_subcommandSort) protected `bool` Subcommand sorting option * [$\_subcommands](#%24_subcommands) protected `array<string,Cake\Console\ConsoleInputSubcommand>` Subcommands for this Shell. * [$\_tokens](#%24_tokens) protected `array` Array of args (argv). * [$rootName](#%24rootName) protected `string` Root alias used in help output Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Construct an OptionParser so you can define its behavior * ##### [\_nextToken()](#_nextToken()) protected Find the next token in the argv set. * ##### [\_optionExists()](#_optionExists()) protected Check to see if $name has an option (short/long) defined for it. * ##### [\_parseArg()](#_parseArg()) protected Parse an argument, and ensure that the argument doesn't exceed the number of arguments and that the argument is a valid choice. * ##### [\_parseLongOption()](#_parseLongOption()) protected Parse the value for a long option out of $this->\_tokens. Will handle options with an `=` in them. * ##### [\_parseOption()](#_parseOption()) protected Parse an option by its name index. * ##### [\_parseShortOption()](#_parseShortOption()) protected Parse the value for a short option out of $this->\_tokens If the $option is a combination of multiple shortcuts like -otf they will be shifted onto the token stack and parsed individually. * ##### [addArgument()](#addArgument()) public Add a positional argument to the option parser. * ##### [addArguments()](#addArguments()) public Add multiple arguments at once. Take an array of argument definitions. The keys are used as the argument names, and the values as params for the argument. * ##### [addOption()](#addOption()) public Add an option to the option parser. Options allow you to define optional or required parameters for your console application. Options are defined by the parameters they use. * ##### [addOptions()](#addOptions()) public Add multiple options at once. Takes an array of option definitions. The keys are used as option names, and the values as params for the option. * ##### [addSubcommand()](#addSubcommand()) public Append a subcommand to the subcommand list. Subcommands are usually methods on your Shell, but can also be used to document Tasks. * ##### [addSubcommands()](#addSubcommands()) public Add multiple subcommands at once. * ##### [argumentNames()](#argumentNames()) public Get the list of argument names. * ##### [arguments()](#arguments()) public Gets the arguments defined in the parser. * ##### [buildFromArray()](#buildFromArray()) public static Build a parser from an array. Uses an array like * ##### [create()](#create()) public static Static factory method for creating new OptionParsers so you can chain methods off of them. * ##### [enableSubcommandSort()](#enableSubcommandSort()) public Enables sorting of subcommands * ##### [getCommand()](#getCommand()) public Gets the command name for shell/task. * ##### [getDescription()](#getDescription()) public Gets the description text for shell/task. * ##### [getEpilog()](#getEpilog()) public Gets the epilog. * ##### [help()](#help()) public Gets formatted help for this parser object. * ##### [isSubcommandSortEnabled()](#isSubcommandSortEnabled()) public Checks whether sorting is enabled for subcommands. * ##### [merge()](#merge()) public Get or set the command name for shell/task. * ##### [options()](#options()) public Get the defined options in the parser. * ##### [parse()](#parse()) public Parse the argv array into a set of params and args. If $command is not null and $command is equal to a subcommand that has a parser, that parser will be used to parse the $argv * ##### [removeOption()](#removeOption()) public Remove an option from the option parser. * ##### [removeSubcommand()](#removeSubcommand()) public Remove a subcommand from the option parser. * ##### [setCommand()](#setCommand()) public Sets the command name for shell/task. * ##### [setDescription()](#setDescription()) public Sets the description text for shell/task. * ##### [setEpilog()](#setEpilog()) public Sets an epilog to the parser. The epilog is added to the end of the options and arguments listing when help is generated. * ##### [setRootName()](#setRootName()) public Set the root name used in the HelpFormatter * ##### [subcommands()](#subcommands()) public Get the array of defined subcommands * ##### [toArray()](#toArray()) public Returns an array representation of this parser. Method Detail ------------- ### \_\_construct() public ``` __construct(string $command = '', bool $defaultOptions = true) ``` Construct an OptionParser so you can define its behavior #### Parameters `string` $command optional The command name this parser is for. The command name is used for generating help. `bool` $defaultOptions optional Whether you want the verbose and quiet options set. Setting this to false will prevent the addition of `--verbose` & `--quiet` options. ### \_nextToken() protected ``` _nextToken(): string ``` Find the next token in the argv set. #### Returns `string` ### \_optionExists() protected ``` _optionExists(string $name): bool ``` Check to see if $name has an option (short/long) defined for it. #### Parameters `string` $name The name of the option. #### Returns `bool` ### \_parseArg() protected ``` _parseArg(string $argument, array $args): array<string> ``` Parse an argument, and ensure that the argument doesn't exceed the number of arguments and that the argument is a valid choice. #### Parameters `string` $argument The argument to append `array` $args The array of parsed args to append to. #### Returns `array<string>` #### Throws `Cake\Console\Exception\ConsoleException` ### \_parseLongOption() protected ``` _parseLongOption(string $option, array<string, mixed> $params): array ``` Parse the value for a long option out of $this->\_tokens. Will handle options with an `=` in them. #### Parameters `string` $option The option to parse. `array<string, mixed>` $params The params to append the parsed value into #### Returns `array` ### \_parseOption() protected ``` _parseOption(string $name, array<string, mixed> $params): array<string, mixed> ``` Parse an option by its name index. #### Parameters `string` $name The name to parse. `array<string, mixed>` $params The params to append the parsed value into #### Returns `array<string, mixed>` #### Throws `Cake\Console\Exception\ConsoleException` ### \_parseShortOption() protected ``` _parseShortOption(string $option, array<string, mixed> $params): array<string, mixed> ``` Parse the value for a short option out of $this->\_tokens If the $option is a combination of multiple shortcuts like -otf they will be shifted onto the token stack and parsed individually. #### Parameters `string` $option The option to parse. `array<string, mixed>` $params The params to append the parsed value into #### Returns `array<string, mixed>` #### Throws `Cake\Console\Exception\ConsoleException` When unknown short options are encountered. ### addArgument() public ``` addArgument(Cake\Console\ConsoleInputArgument|string $name, array<string, mixed> $params = []): $this ``` Add a positional argument to the option parser. ### Params * `help` The help text to display for this argument. * `required` Whether this parameter is required. * `index` The index for the arg, if left undefined the argument will be put onto the end of the arguments. If you define the same index twice the first option will be overwritten. * `choices` A list of valid choices for this argument. If left empty all values are valid.. An exception will be raised when parse() encounters an invalid value. #### Parameters `Cake\Console\ConsoleInputArgument|string` $name The name of the argument. Will also accept an instance of ConsoleInputArgument. `array<string, mixed>` $params optional Parameters for the argument, see above. #### Returns `$this` ### addArguments() public ``` addArguments(array $args): $this ``` Add multiple arguments at once. Take an array of argument definitions. The keys are used as the argument names, and the values as params for the argument. #### Parameters `array` $args Array of arguments to add. #### Returns `$this` #### See Also \Cake\Console\ConsoleOptionParser::addArgument() ### addOption() public ``` addOption(Cake\Console\ConsoleInputOption|string $name, array<string, mixed> $options = []): $this ``` Add an option to the option parser. Options allow you to define optional or required parameters for your console application. Options are defined by the parameters they use. ### Options * `short` - The single letter variant for this option, leave undefined for none. * `help` - Help text for this option. Used when generating help for the option. * `default` - The default value for this option. Defaults are added into the parsed params when the attached option is not provided or has no value. Using default and boolean together will not work. are added into the parsed parameters when the option is undefined. Defaults to null. * `boolean` - The option uses no value, it's just a boolean switch. Defaults to false. If an option is defined as boolean, it will always be added to the parsed params. If no present it will be false, if present it will be true. * `multiple` - The option can be provided multiple times. The parsed option will be an array of values when this option is enabled. * `choices` A list of valid choices for this option. If left empty all values are valid.. An exception will be raised when parse() encounters an invalid value. #### Parameters `Cake\Console\ConsoleInputOption|string` $name The long name you want to the value to be parsed out as when options are parsed. Will also accept an instance of ConsoleInputOption. `array<string, mixed>` $options optional An array of parameters that define the behavior of the option #### Returns `$this` ### addOptions() public ``` addOptions(array<string, mixed> $options): $this ``` Add multiple options at once. Takes an array of option definitions. The keys are used as option names, and the values as params for the option. #### Parameters `array<string, mixed>` $options Array of options to add. #### Returns `$this` #### See Also \Cake\Console\ConsoleOptionParser::addOption() ### addSubcommand() public ``` addSubcommand(Cake\Console\ConsoleInputSubcommand|string $name, array<string, mixed> $options = []): $this ``` Append a subcommand to the subcommand list. Subcommands are usually methods on your Shell, but can also be used to document Tasks. ### Options * `help` - Help text for the subcommand. * `parser` - A ConsoleOptionParser for the subcommand. This allows you to create method specific option parsers. When help is generated for a subcommand, if a parser is present it will be used. #### Parameters `Cake\Console\ConsoleInputSubcommand|string` $name Name of the subcommand. Will also accept an instance of ConsoleInputSubcommand. `array<string, mixed>` $options optional Array of params, see above. #### Returns `$this` ### addSubcommands() public ``` addSubcommands(array<string, mixed> $commands): $this ``` Add multiple subcommands at once. #### Parameters `array<string, mixed>` $commands Array of subcommands. #### Returns `$this` ### argumentNames() public ``` argumentNames(): array<string> ``` Get the list of argument names. #### Returns `array<string>` ### arguments() public ``` arguments(): arrayCake\Console\ConsoleInputArgument> ``` Gets the arguments defined in the parser. #### Returns `arrayCake\Console\ConsoleInputArgument>` ### buildFromArray() public static ``` buildFromArray(array<string, mixed> $spec, bool $defaultOptions = true): static ``` Build a parser from an array. Uses an array like ``` $spec = [ 'description' => 'text', 'epilog' => 'text', 'arguments' => [ // list of arguments compatible with addArguments. ], 'options' => [ // list of options compatible with addOptions ], 'subcommands' => [ // list of subcommands to add. ] ]; ``` #### Parameters `array<string, mixed>` $spec The spec to build the OptionParser with. `bool` $defaultOptions optional Whether you want the verbose and quiet options set. #### Returns `static` ### create() public static ``` create(string $command, bool $defaultOptions = true): static ``` Static factory method for creating new OptionParsers so you can chain methods off of them. #### Parameters `string` $command The command name this parser is for. The command name is used for generating help. `bool` $defaultOptions optional Whether you want the verbose and quiet options set. #### Returns `static` ### enableSubcommandSort() public ``` enableSubcommandSort(bool $value = true): $this ``` Enables sorting of subcommands #### Parameters `bool` $value optional Whether to sort subcommands #### Returns `$this` ### getCommand() public ``` getCommand(): string ``` Gets the command name for shell/task. #### Returns `string` ### getDescription() public ``` getDescription(): string ``` Gets the description text for shell/task. #### Returns `string` ### getEpilog() public ``` getEpilog(): string ``` Gets the epilog. #### Returns `string` ### help() public ``` help(string|null $subcommand = null, string $format = 'text', int $width = 72): string ``` Gets formatted help for this parser object. Generates help text based on the description, options, arguments, subcommands and epilog in the parser. #### Parameters `string|null` $subcommand optional If present and a valid subcommand that has a linked parser. That subcommands help will be shown instead. `string` $format optional Define the output format, can be text or XML `int` $width optional The width to format user content to. Defaults to 72 #### Returns `string` ### isSubcommandSortEnabled() public ``` isSubcommandSortEnabled(): bool ``` Checks whether sorting is enabled for subcommands. #### Returns `bool` ### merge() public ``` merge(Cake\Console\ConsoleOptionParser|array $spec): $this ``` Get or set the command name for shell/task. #### Parameters `Cake\Console\ConsoleOptionParser|array` $spec ConsoleOptionParser or spec to merge with. #### Returns `$this` ### options() public ``` options(): array<string,Cake\Console\ConsoleInputOption> ``` Get the defined options in the parser. #### Returns `array<string,Cake\Console\ConsoleInputOption>` ### parse() public ``` parse(array $argv, Cake\Console\ConsoleIo|null $io = null): array ``` Parse the argv array into a set of params and args. If $command is not null and $command is equal to a subcommand that has a parser, that parser will be used to parse the $argv #### Parameters `array` $argv Array of args (argv) to parse. `Cake\Console\ConsoleIo|null` $io optional A ConsoleIo instance or null. If null prompt options will error. #### Returns `array` #### Throws `Cake\Console\Exception\ConsoleException` When an invalid parameter is encountered. ### removeOption() public ``` removeOption(string $name): $this ``` Remove an option from the option parser. #### Parameters `string` $name The option name to remove. #### Returns `$this` ### removeSubcommand() public ``` removeSubcommand(string $name): $this ``` Remove a subcommand from the option parser. #### Parameters `string` $name The subcommand name to remove. #### Returns `$this` ### setCommand() public ``` setCommand(string $text): $this ``` Sets the command name for shell/task. #### Parameters `string` $text The text to set. #### Returns `$this` ### setDescription() public ``` setDescription(array<string>|string $text): $this ``` Sets the description text for shell/task. #### Parameters `array<string>|string` $text The text to set. If an array the text will be imploded with "\n". #### Returns `$this` ### setEpilog() public ``` setEpilog(array<string>|string $text): $this ``` Sets an epilog to the parser. The epilog is added to the end of the options and arguments listing when help is generated. #### Parameters `array<string>|string` $text The text to set. If an array the text will be imploded with "\n". #### Returns `$this` ### setRootName() public ``` setRootName(string $name): $this ``` Set the root name used in the HelpFormatter #### Parameters `string` $name The root command name #### Returns `$this` ### subcommands() public ``` subcommands(): array<string,Cake\Console\ConsoleInputSubcommand> ``` Get the array of defined subcommands #### Returns `array<string,Cake\Console\ConsoleInputSubcommand>` ### toArray() public ``` toArray(): array<string, mixed> ``` Returns an array representation of this parser. #### Returns `array<string, mixed>` Property Detail --------------- ### $\_args protected Positional argument definitions. #### Type `arrayCake\Console\ConsoleInputArgument>` ### $\_command protected Command name. #### Type `string` ### $\_description protected Description text - displays before options when help is generated #### Type `string` ### $\_epilog protected Epilog text - displays after options when help is generated #### Type `string` ### $\_options protected Option definitions. #### Type `array<string,Cake\Console\ConsoleInputOption>` ### $\_shortOptions protected Map of short -> long options, generated when using addOption() #### Type `array<string, string>` ### $\_subcommandSort protected Subcommand sorting option #### Type `bool` ### $\_subcommands protected Subcommands for this Shell. #### Type `array<string,Cake\Console\ConsoleInputSubcommand>` ### $\_tokens protected Array of args (argv). #### Type `array` ### $rootName protected Root alias used in help output #### Type `string`
programming_docs
cakephp Class XmlException Class XmlException =================== Exception class for Xml. This exception will be thrown from Xml when it encounters an error. **Namespace:** [Cake\Utility\Exception](namespace-cake.utility.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 ConsoleInput Class ConsoleInput =================== Object wrapper for interacting with stdin **Namespace:** [Cake\Console](namespace-cake.console) 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. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [dataAvailable()](#dataAvailable()) public Check if data is available on stdin * ##### [read()](#read()) public Read a value from the stream Method Detail ------------- ### \_\_construct() public ``` __construct(string $handle = 'php://stdin') ``` Constructor #### Parameters `string` $handle optional The location of the stream to use as input. ### 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|null ``` Read a value from the stream #### Returns `string|null` 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` cakephp Class QueryCompiler Class QueryCompiler ==================== Responsible for compiling a Query object into its SQL representation **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` Indicate whether this query dialect supports ordered unions. * [$\_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 Indicate whether this query dialect supports ordered unions. 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 Namespace TestSuite Namespace TestSuite =================== ### Namespaces * [Cake\TestSuite\Constraint](namespace-cake.testsuite.constraint) * [Cake\TestSuite\Fixture](namespace-cake.testsuite.fixture) * [Cake\TestSuite\Stub](namespace-cake.testsuite.stub) ### Classes * ##### [ConnectionHelper](class-cake.testsuite.connectionhelper) Helper for managing test connections * ##### [ConsoleIntegrationTestCase](class-cake.testsuite.consoleintegrationtestcase) A test case class intended to make integration tests of cake console commands easier. * ##### [IntegrationTestCase](class-cake.testsuite.integrationtestcase) A test case class intended to make integration tests of your controllers easier. * ##### [MiddlewareDispatcher](class-cake.testsuite.middlewaredispatcher) Dispatches a request capturing the response for integration testing purposes into the Cake\Http stack. * ##### [TestCase](class-cake.testsuite.testcase) Cake TestCase class * ##### [TestEmailTransport](class-cake.testsuite.testemailtransport) TestEmailTransport * ##### [TestSession](class-cake.testsuite.testsession) Read only access to the session during testing. * ##### [TestSuite](class-cake.testsuite.testsuite) A class to contain test cases and run them with shared fixtures ### Traits * ##### [EmailTrait](trait-cake.testsuite.emailtrait) Make assertions on emails sent through the Cake\TestSuite\TestEmailTransport * ##### [IntegrationTestTrait](trait-cake.testsuite.integrationtesttrait) A trait intended to make integration tests of your controllers easier. * ##### [StringCompareTrait](trait-cake.testsuite.stringcomparetrait) Compare a string to the contents of a file * ##### [TestListenerTrait](trait-cake.testsuite.testlistenertrait) Implements empty default methods for PHPUnit\Framework\TestListener. cakephp Interface InvalidPropertyInterface Interface InvalidPropertyInterface =================================== Describes the methods that any class representing a data storage should comply with. **Namespace:** [Cake\Datasource](namespace-cake.datasource) Method Summary -------------- * ##### [getInvalid()](#getInvalid()) public Get a list of invalid fields and their data for errors upon validation/patching * ##### [getInvalidField()](#getInvalidField()) public Get a single value of an invalid field. Returns null if not set. * ##### [setInvalid()](#setInvalid()) public Set fields as invalid and not patchable into the entity. * ##### [setInvalidField()](#setInvalidField()) public Sets a field as invalid and not patchable into the entity. Method Detail ------------- ### getInvalid() public ``` getInvalid(): array ``` Get a list of invalid fields and their data for errors upon validation/patching #### Returns `array` ### getInvalidField() public ``` getInvalidField(string $field): mixed|null ``` Get a single value of an invalid field. Returns null if not set. #### Parameters `string` $field The name of the field. #### Returns `mixed|null` ### setInvalid() public ``` setInvalid(array<string, mixed> $fields, bool $overwrite = false): $this ``` Set fields as invalid and not patchable into the entity. This is useful for batch operations when one needs to get the original value for an error message after patching. This value could not be patched into the entity and is simply copied into the \_invalid property for debugging purposes or to be able to log it away. #### Parameters `array<string, mixed>` $fields The values to set. `bool` $overwrite optional Whether to overwrite pre-existing values for $field. #### Returns `$this` ### setInvalidField() public ``` setInvalidField(string $field, mixed $value): $this ``` Sets a field as invalid and not patchable into the entity. #### Parameters `string` $field The value to set. `mixed` $value The invalid value to be set for $field. #### Returns `$this`
programming_docs
cakephp Class ContentsContain Class ContentsContain ====================== ContentsContain **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 MailContainsAttachment Class MailContainsAttachment ============================= MailContainsAttachment **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 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. * ##### [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 ``` 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` ### 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 ServiceConfig Class ServiceConfig ==================== Read-only wrapper for configuration data Intended for use with {@link \Cake\Core\Container} as a typehintable way for services to have application configuration injected as arrays cannot be typehinted. **Namespace:** [Cake\Core](namespace-cake.core) Method Summary -------------- * ##### [get()](#get()) public Read a configuration key * ##### [has()](#has()) public Check if $path exists and has a non-null value. Method Detail ------------- ### get() public ``` get(string $path, mixed $default = null): mixed ``` Read a configuration key #### Parameters `string` $path The path to read. `mixed` $default optional The default value to use if $path does not exist. #### Returns `mixed` ### has() public ``` has(string $path): bool ``` Check if $path exists and has a non-null value. #### Parameters `string` $path The path to check. #### Returns `bool` cakephp Class MissingPluginException Class MissingPluginException ============================= Exception raised when a plugin could not be found **Namespace:** [Cake\Core\Exception](namespace-cake.core.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 PluginLoadedCommand Class PluginLoadedCommand ========================== Displays all currently loaded plugins. **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 Displays all currently loaded plugins. * ##### [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 ``` Displays all currently loaded plugins. #### 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 Renderer Namespace Renderer ================== ### Classes * ##### [ConsoleErrorRenderer](class-cake.error.renderer.consoleerrorrenderer) Plain text error rendering with a stack trace. * ##### [ConsoleExceptionRenderer](class-cake.error.renderer.consoleexceptionrenderer) Plain text exception rendering with a stack trace. * ##### [HtmlErrorRenderer](class-cake.error.renderer.htmlerrorrenderer) Interactive HTML error rendering with a stack trace. * ##### [TextErrorRenderer](class-cake.error.renderer.texterrorrenderer) Plain text error rendering with a stack trace. * ##### [TextExceptionRenderer](class-cake.error.renderer.textexceptionrenderer) Plain text exception rendering with a stack trace. * ##### [WebExceptionRenderer](class-cake.error.renderer.webexceptionrenderer) Web Exception Renderer. cakephp Class View Class 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. CakePHP uses a two-step-view pattern. This means that the template content is rendered first, and then inserted into the selected layout. This also means you can pass data from the template to the layout using `$this->set()` View class supports using plugins as themes. You can set ``` public function beforeRender(\Cake\Event\EventInterface $event) { $this->viewBuilder()->setTheme('SuperHot'); } ``` in your Controller to use plugin `SuperHot` as a theme. Eg. If current action is PostsController::index() then View class will look for template file `plugins/SuperHot/templates/Posts/index.php`. If a theme template is not found for the current action the default app template file is used. **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 custom 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. * [$\_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` The name of the layouts subfolder containing layouts for this View. * [$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` Sub-directory for this template file. This is often used for extension based routing. Eg. With an `xml` extension, $subDir would be `xml/` * [$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 * ##### [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 Interact with the HelperRegistry to load all the helpers. * ##### [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 Renders view for given template file and layout. * ##### [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` ### 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 ``` Interact with the HelperRegistry to load all the helpers. #### 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 ``` Renders view for given template file and layout. 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 Name of template file to use `string|false|null` $layout optional Layout to use. False to disable. #### Returns `string` #### Throws `Cake\Core\Exception\CakeException` If there is an error in the view. ### 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 custom config options. #### 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[]>` ### $\_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 The name of the layouts subfolder containing layouts for this View. #### 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 Sub-directory for this template file. This is often used for extension based routing. Eg. With an `xml` extension, $subDir would be `xml/` #### 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 Trait InstanceConfigTrait Trait InstanceConfigTrait ========================== A trait for reading and writing instance config Implementing objects are expected to declare a `$_defaultConfig` property. **Namespace:** [Cake\Core](namespace-cake.core) 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 Method Summary -------------- * ##### [\_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. * ##### [getConfig()](#getConfig()) public Returns the config. * ##### [getConfigOrFail()](#getConfigOrFail()) public Returns the config for this specific key. * ##### [setConfig()](#setConfig()) public Sets the config. 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 ### 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` ### 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` cakephp Namespace Exception Namespace Exception =================== ### Classes * ##### [MissingBehaviorException](class-cake.orm.exception.missingbehaviorexception) Used when a behavior cannot be found. * ##### [MissingEntityException](class-cake.orm.exception.missingentityexception) Exception raised when an Entity could not be found. * ##### [MissingTableClassException](class-cake.orm.exception.missingtableclassexception) Exception raised when a Table could not be found. * ##### [PersistenceFailedException](class-cake.orm.exception.persistencefailedexception) Used when a strict save or delete fails * ##### [RolledbackTransactionException](class-cake.orm.exception.rolledbacktransactionexception) Used when a transaction was rolled back from a callback event. cakephp Interface ConstraintsInterface Interface ConstraintsInterface =============================== Defines the interface for a fixture that needs to manage constraints. If an implementation of `Cake\Datasource\FixtureInterface` also implements this interface, the FixtureManager will use these methods to manage a fixtures constraints. **Namespace:** [Cake\Database](namespace-cake.database) Method Summary -------------- * ##### [createConstraints()](#createConstraints()) public Build and execute SQL queries necessary to create the constraints for the fixture * ##### [dropConstraints()](#dropConstraints()) public Build and execute SQL queries necessary to drop the constraints for the fixture Method Detail ------------- ### 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 An instance of the database into which the constraints will be created. #### 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 An instance of the database into which the constraints will be dropped. #### Returns `bool` cakephp Namespace Configure Namespace Configure =================== ### Namespaces * [Cake\Core\Configure\Engine](namespace-cake.core.configure.engine) ### Interfaces * ##### [ConfigEngineInterface](interface-cake.core.configure.configengineinterface) An interface for creating objects compatible with Configure::load() ### Traits * ##### [FileConfigTrait](trait-cake.core.configure.fileconfigtrait) Trait providing utility methods for file based config engines. cakephp Interface PluginInterface Interface PluginInterface ========================== Plugin Interface **Namespace:** [Cake\Core](namespace-cake.core) Constants --------- * `array<string>` **VALID\_HOOKS** ``` ['bootstrap', 'console', 'middleware', 'routes', 'services'] ``` List of valid hooks. Method Summary -------------- * ##### [bootstrap()](#bootstrap()) public Load all the application configuration and bootstrap logic. * ##### [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 * ##### [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 @method Register plugin services to the application's container Method Detail ------------- ### 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 The host application #### Returns `void` ### console() public ``` console(Cake\Console\CommandCollection $commands): Cake\Console\CommandCollection ``` Add console commands for the plugin. #### Parameters `Cake\Console\CommandCollection` $commands The command collection to update #### Returns `Cake\Console\CommandCollection` ### disable() public ``` disable(string $hook): $this ``` Disables the named hook #### Parameters `string` $hook The hook to disable #### Returns `$this` ### enable() public ``` enable(string $hook): $this ``` Enables the named hook #### Parameters `string` $hook The hook to disable #### 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` ### isEnabled() public ``` isEnabled(string $hook): bool ``` Check if the named hook is enabled #### Parameters `string` $hook The hook to check #### Returns `bool` ### middleware() public ``` middleware(Cake\Http\MiddlewareQueue $middlewareQueue): Cake\Http\MiddlewareQueue ``` Add middleware for the plugin. #### Parameters `Cake\Http\MiddlewareQueue` $middlewareQueue The middleware queue to update. #### 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 The route builder to update. #### Returns `void` ### services() public @method ``` services(Cake\Core\ContainerInterface $container): void ``` Register plugin services to the application's container #### Parameters `Cake\Core\ContainerInterface` $container #### Returns `void` cakephp Class TreeBehavior Class TreeBehavior =================== Makes the table to which this is attached to behave like a nested set and provides methods for managing and retrieving information out of the derived hierarchical structure. Tables attaching this behavior are required to have a column referencing the parent row, and two other numeric columns (lft and rght) where the implicit order will be cached. For more information on what is a nested set and a how it works refer to <https://www.sitepoint.com/hierarchical-data-database-2/> **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 * [$\_primaryKey](#%24_primaryKey) protected `string` Cached copy of the first column in a table's primary key. * [$\_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. * ##### [\_ensureFields()](#_ensureFields()) protected Ensures that the provided entity contains non-empty values for the left and right fields * ##### [\_getMax()](#_getMax()) protected Returns the maximum index value in the table. * ##### [\_getNode()](#_getNode()) protected Returns a single node from the tree from its primary key * ##### [\_getPrimaryKey()](#_getPrimaryKey()) protected Returns a single string value representing the primary key of the attached table * ##### [\_moveDown()](#_moveDown()) protected Helper function used with the actual code for moveDown * ##### [\_moveUp()](#_moveUp()) protected Helper function used with the actual code for moveUp * ##### [\_recoverTree()](#_recoverTree()) protected Recursive method used to recover a single level of the tree * ##### [\_reflectionCache()](#_reflectionCache()) protected Gets the methods implemented by this behavior * ##### [\_removeFromTree()](#_removeFromTree()) protected Helper function containing the actual code for removeFromTree * ##### [\_resolveMethodAliases()](#_resolveMethodAliases()) protected Removes aliased methods that would otherwise be duplicated by userland configuration. * ##### [\_scope()](#_scope()) protected Alters the passed query so that it only returns scoped records as defined in the tree configuration. * ##### [\_setAsRoot()](#_setAsRoot()) protected Updates the left and right column for the passed entity so it can be set as a new root in the tree. It also modifies the ordering in the rest of the tree so the structure remains valid * ##### [\_setChildrenLevel()](#_setChildrenLevel()) protected Set level for descendants. * ##### [\_setParent()](#_setParent()) protected Sets the correct left and right values for the passed entity so it can be updated to a new parent. It also makes the hole in the tree so the node move can be done without corrupting the structure. * ##### [\_sync()](#_sync()) protected Auxiliary function used to automatically alter the value of both the left and right columns by a certain amount that match the passed conditions * ##### [\_unmarkInternalTree()](#_unmarkInternalTree()) protected Helper method used to invert the sign of the left and right columns that are less than 0. They were set to negative values before so their absolute value wouldn't change while performing other tree transformations. * ##### [afterSave()](#afterSave()) public After save listener. * ##### [beforeDelete()](#beforeDelete()) public Also deletes the nodes in the subtree of the entity to be delete * ##### [beforeSave()](#beforeSave()) public Before save listener. Transparently manages setting the lft and rght fields if the parent field is included in the parameters to be saved. * ##### [childCount()](#childCount()) public Get the number of children nodes. * ##### [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. * ##### [findChildren()](#findChildren()) public Get the children nodes of the current model * ##### [findPath()](#findPath()) public Custom finder method which can be used to return the list of nodes from the root to a specific node in the tree. This custom finder requires that the key 'for' is passed in the options containing the id of the node to get its path for. * ##### [findTreeList()](#findTreeList()) public Gets a representation of the elements in the tree as a flat list where the keys are the primary key for the table and the values are the display field for the table. Values are prefixed to visually indicate relative depth in the tree. * ##### [formatTreeList()](#formatTreeList()) public Formats query as a flat list where the keys are the primary key for the table and the values are the display field for the table. Values are prefixed to visually indicate relative depth in the tree. * ##### [getConfig()](#getConfig()) public Returns the config. * ##### [getConfigOrFail()](#getConfigOrFail()) public Returns the config for this specific key. * ##### [getLevel()](#getLevel()) public Returns the depth level of a node in the tree. * ##### [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. * ##### [moveDown()](#moveDown()) public Reorders the node without changing the parent. * ##### [moveUp()](#moveUp()) public Reorders the node without changing its parent. * ##### [recover()](#recover()) public Recovers the lft and right column values out of the hierarchy defined by the parent column. * ##### [removeFromTree()](#removeFromTree()) public Removes the current node from the tree, by positioning it as a new root and re-parents all children up one level. * ##### [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 ### \_ensureFields() protected ``` _ensureFields(Cake\Datasource\EntityInterface $entity): void ``` Ensures that the provided entity contains non-empty values for the left and right fields #### Parameters `Cake\Datasource\EntityInterface` $entity The entity to ensure fields for #### Returns `void` ### \_getMax() protected ``` _getMax(): int ``` Returns the maximum index value in the table. #### Returns `int` ### \_getNode() protected ``` _getNode(mixed $id): Cake\Datasource\EntityInterface ``` Returns a single node from the tree from its primary key #### Parameters `mixed` $id Record id. #### Returns `Cake\Datasource\EntityInterface` #### Throws `Cake\Datasource\Exception\RecordNotFoundException` When node was not found ### \_getPrimaryKey() protected ``` _getPrimaryKey(): string ``` Returns a single string value representing the primary key of the attached table #### Returns `string` ### \_moveDown() protected ``` _moveDown(Cake\Datasource\EntityInterface $node, int|true $number): Cake\Datasource\EntityInterface ``` Helper function used with the actual code for moveDown #### Parameters `Cake\Datasource\EntityInterface` $node The node to move `int|true` $number How many places to move the node, or true to move to last position #### Returns `Cake\Datasource\EntityInterface` #### Throws `Cake\Datasource\Exception\RecordNotFoundException` When node was not found ### \_moveUp() protected ``` _moveUp(Cake\Datasource\EntityInterface $node, int|true $number): Cake\Datasource\EntityInterface ``` Helper function used with the actual code for moveUp #### Parameters `Cake\Datasource\EntityInterface` $node The node to move `int|true` $number How many places to move the node, or true to move to first position #### Returns `Cake\Datasource\EntityInterface` #### Throws `Cake\Datasource\Exception\RecordNotFoundException` When node was not found ### \_recoverTree() protected ``` _recoverTree(int $lftRght = 1, mixed $parentId = null, int $level = 0): int ``` Recursive method used to recover a single level of the tree #### Parameters `int` $lftRght optional The starting lft/rght value `mixed` $parentId optional the parent id of the level to be recovered `int` $level optional Node level #### Returns `int` ### \_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` ### \_removeFromTree() protected ``` _removeFromTree(Cake\Datasource\EntityInterface $node): Cake\Datasource\EntityInterface|false ``` Helper function containing the actual code for removeFromTree #### Parameters `Cake\Datasource\EntityInterface` $node The node to remove from the tree #### Returns `Cake\Datasource\EntityInterface|false` ### \_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` ### \_scope() protected ``` _scope(Cake\ORM\Query $query): Cake\ORM\Query ``` Alters the passed query so that it only returns scoped records as defined in the tree configuration. #### Parameters `Cake\ORM\Query` $query the Query to modify #### Returns `Cake\ORM\Query` ### \_setAsRoot() protected ``` _setAsRoot(Cake\Datasource\EntityInterface $entity): void ``` Updates the left and right column for the passed entity so it can be set as a new root in the tree. It also modifies the ordering in the rest of the tree so the structure remains valid #### Parameters `Cake\Datasource\EntityInterface` $entity The entity to set as a new root #### Returns `void` ### \_setChildrenLevel() protected ``` _setChildrenLevel(Cake\Datasource\EntityInterface $entity): void ``` Set level for descendants. #### Parameters `Cake\Datasource\EntityInterface` $entity The entity whose descendants need to be updated. #### Returns `void` ### \_setParent() protected ``` _setParent(Cake\Datasource\EntityInterface $entity, mixed $parent): void ``` Sets the correct left and right values for the passed entity so it can be updated to a new parent. It also makes the hole in the tree so the node move can be done without corrupting the structure. #### Parameters `Cake\Datasource\EntityInterface` $entity The entity to re-parent `mixed` $parent the id of the parent to set #### Returns `void` #### Throws `RuntimeException` if the parent to set to the entity is not valid ### \_sync() protected ``` _sync(int $shift, string $dir, string $conditions, bool $mark = false): void ``` Auxiliary function used to automatically alter the value of both the left and right columns by a certain amount that match the passed conditions #### Parameters `int` $shift the value to use for operating the left and right columns `string` $dir The operator to use for shifting the value (+/-) `string` $conditions a SQL snipped to be used for comparing left or right against it. `bool` $mark optional whether to mark the updated values so that they can not be modified by future calls to this function. #### Returns `void` ### \_unmarkInternalTree() protected ``` _unmarkInternalTree(): void ``` Helper method used to invert the sign of the left and right columns that are less than 0. They were set to negative values before so their absolute value wouldn't change while performing other tree transformations. #### Returns `void` ### afterSave() public ``` afterSave(Cake\Event\EventInterface $event, Cake\Datasource\EntityInterface $entity): void ``` After save listener. Manages updating level of descendants of currently saved entity. #### Parameters `Cake\Event\EventInterface` $event The afterSave event that was fired `Cake\Datasource\EntityInterface` $entity the entity that is going to be saved #### Returns `void` ### beforeDelete() public ``` beforeDelete(Cake\Event\EventInterface $event, Cake\Datasource\EntityInterface $entity): void ``` Also deletes the nodes in the subtree of the entity to be delete #### Parameters `Cake\Event\EventInterface` $event The beforeDelete event that was fired `Cake\Datasource\EntityInterface` $entity The entity that is going to be saved #### Returns `void` ### beforeSave() public ``` beforeSave(Cake\Event\EventInterface $event, Cake\Datasource\EntityInterface $entity): void ``` Before save listener. Transparently manages setting the lft and rght fields if the parent field is included in the parameters to be 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` #### Throws `RuntimeException` if the parent to set for the node is invalid ### childCount() public ``` childCount(Cake\Datasource\EntityInterface $node, bool $direct = false): int ``` Get the number of children nodes. #### Parameters `Cake\Datasource\EntityInterface` $node The entity to count children for `bool` $direct optional whether to count all nodes in the subtree or just direct children #### Returns `int` ### 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` ### findChildren() public ``` findChildren(Cake\ORM\Query $query, array<string, mixed> $options): Cake\ORM\Query ``` Get the children nodes of the current model Available options are: * for: The id of the record to read. * direct: Boolean, whether to return only the direct (true), or all (false) children, defaults to false (all children). If the direct option is set to true, only the direct children are returned (based upon the parent\_id field) #### Parameters `Cake\ORM\Query` $query Query. `array<string, mixed>` $options Array of options as described above #### Returns `Cake\ORM\Query` #### Throws `InvalidArgumentException` When the 'for' key is not passed in $options ### findPath() public ``` findPath(Cake\ORM\Query $query, array<string, mixed> $options): Cake\ORM\Query ``` Custom finder method which can be used to return the list of nodes from the root to a specific node in the tree. This custom finder requires that the key 'for' is passed in the options containing the id of the node to get its path for. #### Parameters `Cake\ORM\Query` $query The constructed query to modify `array<string, mixed>` $options the list of options for the query #### Returns `Cake\ORM\Query` #### Throws `InvalidArgumentException` If the 'for' key is missing in options ### findTreeList() public ``` findTreeList(Cake\ORM\Query $query, array<string, mixed> $options): Cake\ORM\Query ``` Gets a representation of the elements in the tree as a flat list where the keys are the primary key for the table and the values are the display field for the table. Values are prefixed to visually indicate relative depth in the tree. ### Options * keyPath: A dot separated path to fetch the field to use for the array key, or a closure to return the key out of the provided row. * valuePath: A dot separated path to fetch the field to use for the array value, or a closure to return the value out of the provided row. * spacer: A string to be used as prefix for denoting the depth in the tree for each item #### Parameters `Cake\ORM\Query` $query Query. `array<string, mixed>` $options Array of options as described above. #### Returns `Cake\ORM\Query` ### formatTreeList() public ``` formatTreeList(Cake\ORM\Query $query, array<string, mixed> $options = []): Cake\ORM\Query ``` Formats query as a flat list where the keys are the primary key for the table and the values are the display field for the table. Values are prefixed to visually indicate relative depth in the tree. ### Options * keyPath: A dot separated path to the field that will be the result array key, or a closure to return the key from the provided row. * valuePath: A dot separated path to the field that is the array's value, or a closure to return the value from the provided row. * spacer: A string to be used as prefix for denoting the depth in the tree for each item. #### Parameters `Cake\ORM\Query` $query The query object to format. `array<string, mixed>` $options optional Array of options as described above. #### 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` ### getLevel() public ``` getLevel(Cake\Datasource\EntityInterface|string|int $entity): int|false ``` Returns the depth level of a node in the tree. #### Parameters `Cake\Datasource\EntityInterface|string|int` $entity The entity or primary key get the level of. #### Returns `int|false` ### 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 #### Returns `void` ### moveDown() public ``` moveDown(Cake\Datasource\EntityInterface $node, int|true $number = 1): Cake\Datasource\EntityInterface|false ``` Reorders the node without changing the parent. If the node is the last child, or is a top level node with no subsequent node this method will return the same node without any changes #### Parameters `Cake\Datasource\EntityInterface` $node The node to move `int|true` $number optional How many places to move the node or true to move to last position #### Returns `Cake\Datasource\EntityInterface|false` #### Throws `Cake\Datasource\Exception\RecordNotFoundException` When node was not found ### moveUp() public ``` moveUp(Cake\Datasource\EntityInterface $node, int|true $number = 1): Cake\Datasource\EntityInterface|false ``` Reorders the node without changing its parent. If the node is the first child, or is a top level node with no previous node this method will return the same node without any changes #### Parameters `Cake\Datasource\EntityInterface` $node The node to move `int|true` $number optional How many places to move the node, or true to move to first position #### Returns `Cake\Datasource\EntityInterface|false` #### Throws `Cake\Datasource\Exception\RecordNotFoundException` When node was not found ### recover() public ``` recover(): void ``` Recovers the lft and right column values out of the hierarchy defined by the parent column. #### Returns `void` ### removeFromTree() public ``` removeFromTree(Cake\Datasource\EntityInterface $node): Cake\Datasource\EntityInterface|false ``` Removes the current node from the tree, by positioning it as a new root and re-parents all children up one level. Note that the node will not be deleted just moved away from its current position without moving its children with it. #### Parameters `Cake\Datasource\EntityInterface` $node The node to remove from the tree #### Returns `Cake\Datasource\EntityInterface|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. ### 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 config These are merged with user-provided configuration when the behavior is used. #### Type `array<string, mixed>` ### $\_primaryKey protected Cached copy of the first column in a table's primary key. #### Type `string` ### $\_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`
programming_docs
cakephp Interface CookieInterface Interface CookieInterface ========================== Cookie Interface **Namespace:** [Cake\Http\Cookie](namespace-cake.http.cookie) Constants --------- * `string` **EXPIRES\_FORMAT** ``` 'D, d-M-Y H:i:s T' ``` Expires attribute format. * `string` **SAMESITE\_LAX** ``` 'Lax' ``` SameSite attribute value: Lax * `string` **SAMESITE\_NONE** ``` 'None' ``` SameSite attribute value: None * `string` **SAMESITE\_STRICT** ``` 'Strict' ``` SameSite attribute value: Strict * `array<string>` **SAMESITE\_VALUES** ``` [self::SAMESITE_LAX, self::SAMESITE_STRICT, self::SAMESITE_NONE] ``` Valid values for "SameSite" attribute. Method Summary -------------- * ##### [getDomain()](#getDomain()) public Get the domain attribute. * ##### [getExpiresTimestamp()](#getExpiresTimestamp()) public Get the timestamp from the expiration time * ##### [getExpiry()](#getExpiry()) public Get the current expiry time * ##### [getFormattedExpires()](#getFormattedExpires()) public Builds the expiration value part of the header string * ##### [getId()](#getId()) public Get the id for a cookie * ##### [getName()](#getName()) public Gets the cookie name * ##### [getOptions()](#getOptions()) public Get cookie options * ##### [getPath()](#getPath()) public Get the path attribute. * ##### [getSameSite()](#getSameSite()) public Get the SameSite attribute. * ##### [getScalarValue()](#getScalarValue()) public Gets the cookie value as scalar. * ##### [getValue()](#getValue()) public Gets the cookie value * ##### [isExpired()](#isExpired()) public Check if a cookie is expired when compared to $time * ##### [isHttpOnly()](#isHttpOnly()) public Check if the cookie is HTTP only * ##### [isSecure()](#isSecure()) public Check if the cookie is secure * ##### [toArray()](#toArray()) public Get cookie data as array. * ##### [toHeaderValue()](#toHeaderValue()) public Returns the cookie as header value * ##### [withDomain()](#withDomain()) public Create a cookie with an updated domain * ##### [withExpired()](#withExpired()) public Create a new cookie that will expire/delete the cookie from the browser. * ##### [withExpiry()](#withExpiry()) public Create a cookie with an updated expiration date * ##### [withHttpOnly()](#withHttpOnly()) public Create a cookie with HTTP Only updated * ##### [withName()](#withName()) public Sets the cookie name * ##### [withNeverExpire()](#withNeverExpire()) public Create a new cookie that will virtually never expire. * ##### [withPath()](#withPath()) public Create a new cookie with an updated path * ##### [withSameSite()](#withSameSite()) public Create a cookie with an updated SameSite option. * ##### [withSecure()](#withSecure()) public Create a cookie with Secure updated * ##### [withValue()](#withValue()) public Create a cookie with an updated value. Method Detail ------------- ### getDomain() public ``` getDomain(): string ``` Get the domain attribute. #### Returns `string` ### getExpiresTimestamp() public ``` getExpiresTimestamp(): int|null ``` Get the timestamp from the expiration time #### Returns `int|null` ### getExpiry() public ``` getExpiry(): DateTimeDateTimeImmutable|null ``` Get the current expiry time #### Returns `DateTimeDateTimeImmutable|null` ### getFormattedExpires() public ``` getFormattedExpires(): string ``` Builds the expiration value part of the header string #### Returns `string` ### getId() public ``` getId(): string ``` Get the id for a cookie Cookies are unique across name, domain, path tuples. #### Returns `string` ### getName() public ``` getName(): string ``` Gets the cookie name #### Returns `string` ### getOptions() public ``` getOptions(): array<string, mixed> ``` Get cookie options #### Returns `array<string, mixed>` ### getPath() public ``` getPath(): string ``` Get the path attribute. #### Returns `string` ### getSameSite() public ``` getSameSite(): string|null ``` Get the SameSite attribute. #### Returns `string|null` ### getScalarValue() public ``` getScalarValue(): mixed ``` Gets the cookie value as scalar. This will collapse any complex data in the cookie with json\_encode() #### Returns `mixed` ### getValue() public ``` getValue(): array|string ``` Gets the cookie value #### Returns `array|string` ### isExpired() public ``` isExpired(DateTimeDateTimeImmutable $time = null): bool ``` Check if a cookie is expired when compared to $time Cookies without an expiration date always return false. #### Parameters `DateTimeDateTimeImmutable` $time optional The time to test against. Defaults to 'now' in UTC. #### Returns `bool` ### isHttpOnly() public ``` isHttpOnly(): bool ``` Check if the cookie is HTTP only #### Returns `bool` ### isSecure() public ``` isSecure(): bool ``` Check if the cookie is secure #### Returns `bool` ### toArray() public ``` toArray(): array<string, mixed> ``` Get cookie data as array. #### Returns `array<string, mixed>` ### toHeaderValue() public ``` toHeaderValue(): string ``` Returns the cookie as header value #### Returns `string` ### withDomain() public ``` withDomain(string $domain): static ``` Create a cookie with an updated domain #### Parameters `string` $domain Domain to set #### Returns `static` ### withExpired() public ``` withExpired(): static ``` Create a new cookie that will expire/delete the cookie from the browser. This is done by setting the expiration time to 1 year ago #### Returns `static` ### withExpiry() public ``` withExpiry(DateTimeDateTimeImmutable $dateTime): static ``` Create a cookie with an updated expiration date #### Parameters `DateTimeDateTimeImmutable` $dateTime Date time object #### Returns `static` ### withHttpOnly() public ``` withHttpOnly(bool $httpOnly): static ``` Create a cookie with HTTP Only updated #### Parameters `bool` $httpOnly HTTP Only #### Returns `static` ### withName() public ``` withName(string $name): static ``` Sets the cookie name #### Parameters `string` $name Name of the cookie #### Returns `static` ### withNeverExpire() public ``` withNeverExpire(): static ``` Create a new cookie that will virtually never expire. #### Returns `static` ### withPath() public ``` withPath(string $path): static ``` Create a new cookie with an updated path #### Parameters `string` $path Sets the path #### Returns `static` ### withSameSite() public ``` withSameSite(string|null $sameSite): static ``` Create a cookie with an updated SameSite option. #### Parameters `string|null` $sameSite Value for to set for Samesite option. One of CookieInterface::SAMESITE\_\* constants. #### Returns `static` ### withSecure() public ``` withSecure(bool $secure): static ``` Create a cookie with Secure updated #### Parameters `bool` $secure Secure attribute value #### Returns `static` ### withValue() public ``` withValue(array|string $value): static ``` Create a cookie with an updated value. #### Parameters `array|string` $value Value of the cookie to set #### Returns `static` cakephp Namespace Constraint Namespace Constraint ==================== ### Classes * ##### [ContentsBase](class-cake.console.testsuite.constraint.contentsbase) Base constraint for content constraints * ##### [ContentsContain](class-cake.console.testsuite.constraint.contentscontain) ContentsContain * ##### [ContentsContainRow](class-cake.console.testsuite.constraint.contentscontainrow) ContentsContainRow * ##### [ContentsEmpty](class-cake.console.testsuite.constraint.contentsempty) ContentsEmpty * ##### [ContentsNotContain](class-cake.console.testsuite.constraint.contentsnotcontain) ContentsNotContain * ##### [ContentsRegExp](class-cake.console.testsuite.constraint.contentsregexp) ContentsRegExp * ##### [ExitCode](class-cake.console.testsuite.constraint.exitcode) ExitCode constraint cakephp Class ConsoleOutput Class ConsoleOutput ==================== Object wrapper for outputting information from a shell application. Can be connected to any stream resource that can be used with fopen() Can generate colorized output on consoles that support it. There are a few built in styles * `error` Error messages. * `warning` Warning messages. * `info` Informational messages. * `comment` Additional text. * `question` Magenta text used for user prompts By defining styles with addStyle() you can create custom console styles. ### Using styles in output You can format console output using tags with the name of the style to apply. From inside a shell object ``` $this->out('<warning>Overwrite:</warning> foo.php was overwritten.'); ``` This would create orange 'Overwrite:' text, while the rest of the text would remain the normal color. See ConsoleOutput::styles() to learn more about defining your own styles. Nested styles are not supported at this time. **Namespace:** [Cake\Console](namespace-cake.console) Constants --------- * `int` **COLOR** ``` 2 ``` Color output - Convert known tags in to ANSI color escape codes. * `string` **LF** ``` PHP_EOL ``` Constant for a newline. * `int` **PLAIN** ``` 1 ``` Plain output - tags will be stripped. * `int` **RAW** ``` 0 ``` Raw output constant - no modification of output text. Property Summary ---------------- * [$\_backgroundColors](#%24_backgroundColors) protected static `array<string, int>` background colors used in colored output. * [$\_foregroundColors](#%24_foregroundColors) protected static `array<string, int>` text colors used in colored output. * [$\_options](#%24_options) protected static `array<string, int>` Formatting options for colored output. * [$\_output](#%24_output) protected `resource` File handle for output. * [$\_outputAs](#%24_outputAs) protected `int` The current output type. * [$\_styles](#%24_styles) protected static `array<string, array>` Styles that are available as tags in console output. You can modify these styles with ConsoleOutput::styles() Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Construct the output object. * ##### [\_\_destruct()](#__destruct()) public Clean up and close handles * ##### [\_replaceTags()](#_replaceTags()) protected Replace tags with color codes. * ##### [\_write()](#_write()) protected Writes a message to the output stream. * ##### [getOutputAs()](#getOutputAs()) public Get the output type on how formatting tags are treated. * ##### [getStyle()](#getStyle()) public Gets the current styles offered * ##### [setOutputAs()](#setOutputAs()) public Set the output type on how formatting tags are treated. * ##### [setStyle()](#setStyle()) public Sets style. * ##### [styleText()](#styleText()) public Apply styling to text. * ##### [styles()](#styles()) public Gets all the style definitions. * ##### [write()](#write()) public Outputs a single or multiple messages to stdout or stderr. If no parameters are passed, outputs just a newline. Method Detail ------------- ### \_\_construct() public ``` __construct(string $stream = 'php://stdout') ``` Construct the output object. Checks for a pretty console environment. Ansicon and ConEmu allows pretty consoles on Windows, and is supported. #### Parameters `string` $stream optional The identifier of the stream to write output to. ### \_\_destruct() public ``` __destruct() ``` Clean up and close handles ### \_replaceTags() protected ``` _replaceTags(array<string, string> $matches): string ``` Replace tags with color codes. #### Parameters `array<string, string>` $matches An array of matches to replace. #### Returns `string` ### \_write() protected ``` _write(string $message): int ``` Writes a message to the output stream. #### Parameters `string` $message Message to write. #### Returns `int` ### getOutputAs() public ``` getOutputAs(): int ``` Get the output type on how formatting tags are treated. #### Returns `int` ### getStyle() public ``` getStyle(string $style): array ``` Gets the current styles offered #### Parameters `string` $style The style to get. #### Returns `array` ### setOutputAs() public ``` setOutputAs(int $type): void ``` Set the output type on how formatting tags are treated. #### Parameters `int` $type The output type to use. Should be one of the class constants. #### Returns `void` #### Throws `InvalidArgumentException` in case of a not supported output type. ### setStyle() public ``` setStyle(string $style, array $definition): void ``` Sets style. ### Creates or modifies an existing style. ``` $output->setStyle('annoy', ['text' => 'purple', 'background' => 'yellow', 'blink' => true]); ``` ### Remove a style ``` $this->output->setStyle('annoy', []); ``` #### Parameters `string` $style The style to set. `array` $definition The array definition of the style to change or create.. #### Returns `void` ### styleText() public ``` styleText(string $text): string ``` Apply styling to text. #### Parameters `string` $text Text with styling tags. #### Returns `string` ### styles() public ``` styles(): array<string, mixed> ``` Gets all the style definitions. #### Returns `array<string, mixed>` ### write() public ``` write(array<string>|string $message, int $newlines = 1): int ``` Outputs a single or multiple messages to stdout or 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` Property Detail --------------- ### $\_backgroundColors protected static background colors used in colored output. #### Type `array<string, int>` ### $\_foregroundColors protected static text colors used in colored output. #### Type `array<string, int>` ### $\_options protected static Formatting options for colored output. #### Type `array<string, int>` ### $\_output protected File handle for output. #### Type `resource` ### $\_outputAs protected The current output type. #### Type `int` ### $\_styles protected static Styles that are available as tags in console output. You can modify these styles with ConsoleOutput::styles() #### Type `array<string, array>` cakephp Class DateTimeWidget Class DateTimeWidget ===================== Input widget class for generating a date time input widget. This class is usually used internally by `Cake\View\Helper\FormHelper`, it but can be used to generate standalone date time inputs. **Namespace:** [Cake\View\Widget](namespace-cake.view.widget) Property Summary ---------------- * [$\_templates](#%24_templates) protected `Cake\View\StringTemplate` Template instance. * [$defaultStep](#%24defaultStep) protected `array<string, mixed>` Step size for various input types. * [$defaults](#%24defaults) protected `array<string, mixed>` Data defaults. * [$formatMap](#%24formatMap) protected `array<string>` Formats for various input types. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [formatDateTime()](#formatDateTime()) protected Formats the passed date/time value into required string format. * ##### [mergeDefaults()](#mergeDefaults()) protected Merge default values with supplied data. * ##### [render()](#render()) public Render a date / time 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. ### formatDateTime() protected ``` formatDateTime(DateTime|string|int|null $value, array<string, mixed> $options): string ``` Formats the passed date/time value into required string format. #### Parameters `DateTime|string|int|null` $value Value to deconstruct. `array<string, mixed>` $options Options for conversion. #### Returns `string` #### Throws `InvalidArgumentException` If invalid input type is passed. ### 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 date / time form widget. Data supports the following keys: * `name` The name attribute. * `val` The value attribute. * `escape` Set to false to disable escaping on all attributes. * `type` A valid HTML date/time input type. Defaults to "datetime-local". * `timezone` The timezone the input value should be converted to. * `step` The "step" attribute. Defaults to `1` for "time" and "datetime-local" type inputs. You can set it to `null` or `false` to prevent explicit step attribute being added in HTML. * `format` A `date()` function compatible datetime format string. By default, the widget will use a suitable format based on the input type and database type for the context. If an explicit format is provided, then no default value will be set for the `step` attribute, and it needs to be explicitly set if required. All other keys will be converted into HTML attributes. #### 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 Template instance. #### Type `Cake\View\StringTemplate` ### $defaultStep protected Step size for various input types. If not set, defaults to browser default. #### Type `array<string, mixed>` ### $defaults protected Data defaults. #### Type `array<string, mixed>` ### $formatMap protected Formats for various input types. #### Type `array<string>`
programming_docs
cakephp Class CookieNotSet Class CookieNotSet =================== CookieNotSet **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 QueryExpression Class 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. **Namespace:** [Cake\Database\Expression](namespace-cake.database.expression) Property Summary ---------------- * [$\_conditions](#%24_conditions) protected `array` A list of strings or other expression objects that represent the "branches" of the expression tree. For example one key of the array might look like "sum > :value" * [$\_conjunction](#%24_conjunction) protected `string` String to be used for joining each of the internal expressions this object internally stores for example "AND", "OR", etc. * [$\_typeMap](#%24_typeMap) protected `Cake\Database\TypeMap|null` Method Summary -------------- * ##### [\_\_clone()](#__clone()) public Clone this object and its subtree of expressions. * ##### [\_\_construct()](#__construct()) public Constructor. A new expression object can be created without any params and be built dynamically. Otherwise, it is possible to pass an array of conditions containing either a tree-like array structure to be parsed and/or other expression objects. Optionally, you can set the conjunction keyword to be used for joining each part of this level of the expression tree. * ##### [\_addConditions()](#_addConditions()) protected Auxiliary function used for decomposing a nested array of conditions and build a tree structure inside this object to represent the full SQL expression. String conditions are stored directly in the conditions, while any other representation is wrapped around an adequate instance or of this class. * ##### [\_calculateType()](#_calculateType()) protected Returns the type name for the passed field if it was stored in the typeMap * ##### [\_parseCondition()](#_parseCondition()) protected Parses a string conditions by trying to extract the operator inside it if any and finally returning either an adequate QueryExpression object or a plain string representation of the condition. This function is responsible for generating the placeholders and replacing the values by them, while storing the value elsewhere for future binding. * ##### [add()](#add()) public Adds one or more conditions to this expression object. Conditions can be expressed in a one dimensional array, that will cause all conditions to be added directly at this level of the tree or they can be nested arbitrarily making it create more expression objects that will be nested inside and configured to use the specified conjunction. * ##### [addCase()](#addCase()) public deprecated Adds a new case expression to the expression object * ##### [and()](#and()) public Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "AND" * ##### [and\_()](#and_()) public deprecated Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "AND" * ##### [between()](#between()) public Adds a new condition to the expression object in the form "field BETWEEN from AND to". * ##### [case()](#case()) public Returns a new case expression object. * ##### [count()](#count()) public Returns the number of internal conditions that are stored in this expression. Useful to determine if this expression object is void or it will generate a non-empty string when compiled * ##### [eq()](#eq()) public Adds a new condition to the expression object in the form "field = value". * ##### [equalFields()](#equalFields()) public Builds equal condition or assignment with identifier wrapping. * ##### [exists()](#exists()) public Adds a new condition to the expression object in the form "EXISTS (...)". * ##### [getConjunction()](#getConjunction()) public Gets the currently configured conjunction for the conditions at this level of the expression tree. * ##### [getDefaultTypes()](#getDefaultTypes()) public Gets default types of current type map. * ##### [getTypeMap()](#getTypeMap()) public Returns the existing type map. * ##### [gt()](#gt()) public Adds a new condition to the expression object in the form "field > value". * ##### [gte()](#gte()) public Adds a new condition to the expression object in the form "field >= value". * ##### [hasNestedExpression()](#hasNestedExpression()) public Returns true if this expression contains any other nested ExpressionInterface objects * ##### [in()](#in()) public Adds a new condition to the expression object in the form "field IN (value1, value2)". * ##### [isCallable()](#isCallable()) public deprecated Check whether a callable is acceptable. * ##### [isNotNull()](#isNotNull()) public Adds a new condition to the expression object in the form "field IS NOT NULL". * ##### [isNull()](#isNull()) public Adds a new condition to the expression object in the form "field IS NULL". * ##### [iterateParts()](#iterateParts()) public Executes a callable function for each of the parts that form this expression. * ##### [like()](#like()) public Adds a new condition to the expression object in the form "field LIKE value". * ##### [lt()](#lt()) public Adds a new condition to the expression object in the form "field < value". * ##### [lte()](#lte()) public Adds a new condition to the expression object in the form "field <= value". * ##### [not()](#not()) public Adds a new set of conditions to this level of the tree and negates the final result by prepending a NOT, it will look like "NOT ( (condition1) AND (conditions2) )" conjunction depends on the one currently configured for this object. * ##### [notEq()](#notEq()) public Adds a new condition to the expression object in the form "field != value". * ##### [notExists()](#notExists()) public Adds a new condition to the expression object in the form "NOT EXISTS (...)". * ##### [notIn()](#notIn()) public Adds a new condition to the expression object in the form "field NOT IN (value1, value2)". * ##### [notInOrNull()](#notInOrNull()) public Adds a new condition to the expression object in the form "(field NOT IN (value1, value2) OR field IS NULL". * ##### [notLike()](#notLike()) public Adds a new condition to the expression object in the form "field NOT LIKE value". * ##### [or()](#or()) public Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "OR" * ##### [or\_()](#or_()) public deprecated Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "OR" * ##### [setConjunction()](#setConjunction()) public Changes the conjunction for the conditions at this level of the expression tree. * ##### [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. * ##### [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(Cake\Database\ExpressionInterface|array|string $conditions = [], Cake\Database\TypeMap|array $types = [], string $conjunction = 'AND') ``` Constructor. A new expression object can be created without any params and be built dynamically. Otherwise, it is possible to pass an array of conditions containing either a tree-like array structure to be parsed and/or other expression objects. Optionally, you can set the conjunction keyword to be used for joining each part of this level of the expression tree. #### Parameters `Cake\Database\ExpressionInterface|array|string` $conditions optional Tree like array structure containing all the conditions to be added or nested inside this expression object. `Cake\Database\TypeMap|array` $types optional Associative array of types to be associated with the values passed in $conditions. `string` $conjunction optional the glue that will join all the string conditions at this level of the expression tree. For example "AND", "OR", "XOR"... #### See Also \Cake\Database\Expression\QueryExpression::add() for more details on $conditions and $types ### \_addConditions() protected ``` _addConditions(array $conditions, array<int|string, string> $types): void ``` Auxiliary function used for decomposing a nested array of conditions and build a tree structure inside this object to represent the full SQL expression. String conditions are stored directly in the conditions, while any other representation is wrapped around an adequate instance or of this class. #### Parameters `array` $conditions list of conditions to be stored in this object `array<int|string, string>` $types list of types associated on fields referenced in $conditions #### Returns `void` ### \_calculateType() protected ``` _calculateType(Cake\Database\ExpressionInterface|string $field): string|null ``` Returns the type name for the passed field if it was stored in the typeMap #### Parameters `Cake\Database\ExpressionInterface|string` $field The field name to get a type for. #### Returns `string|null` ### \_parseCondition() protected ``` _parseCondition(string $field, mixed $value): Cake\Database\ExpressionInterface ``` Parses a string conditions by trying to extract the operator inside it if any and finally returning either an adequate QueryExpression object or a plain string representation of the condition. This function is responsible for generating the placeholders and replacing the values by them, while storing the value elsewhere for future binding. #### Parameters `string` $field The value from which the actual field and operator will be extracted. `mixed` $value The value to be bound to a placeholder for the field #### Returns `Cake\Database\ExpressionInterface` #### Throws `InvalidArgumentException` If operator is invalid or missing on NULL usage. ### add() public ``` add(Cake\Database\ExpressionInterface|array|string $conditions, array<int|string, string> $types = []): $this ``` Adds one or more conditions to this expression object. Conditions can be expressed in a one dimensional array, that will cause all conditions to be added directly at this level of the tree or they can be nested arbitrarily making it create more expression objects that will be nested inside and configured to use the specified conjunction. If the type passed for any of the fields is expressed "type[]" (note braces) then it will cause the placeholder to be re-written dynamically so if the value is an array, it will create as many placeholders as values are in it. #### Parameters `Cake\Database\ExpressionInterface|array|string` $conditions single or multiple conditions to be added. When using an array and the key is 'OR' or 'AND' a new expression object will be created with that conjunction and internal array value passed as conditions. `array<int|string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `$this` #### See Also \Cake\Database\Query::where() for examples on conditions ### addCase() public ``` addCase(Cake\Database\ExpressionInterface|array $conditions, Cake\Database\ExpressionInterface|array $values = [], array<string> $types = []): $this ``` Adds a new case expression to the expression object #### Parameters `Cake\Database\ExpressionInterface|array` $conditions 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 #### Returns `$this` ### and() public ``` and(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "AND" #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be joined with AND `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `Cake\Database\Expression\QueryExpression` ### and\_() public ``` and_(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "AND" #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be joined with AND `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `Cake\Database\Expression\QueryExpression` ### between() public ``` between(Cake\Database\ExpressionInterface|string $field, mixed $from, mixed $to, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field BETWEEN from AND to". #### 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 type name for $value as configured using the Type map. #### Returns `$this` ### case() public ``` case(Cake\Database\ExpressionInterface|object|scalar|null $value = null, string|null $type = null): Cake\Database\Expression\CaseStatementExpression ``` Returns a new case expression object. 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. #### Returns `Cake\Database\Expression\CaseStatementExpression` ### count() public ``` count(): int ``` Returns the number of internal conditions that are stored in this expression. Useful to determine if this expression object is void or it will generate a non-empty string when compiled #### Returns `int` ### eq() public ``` eq(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field = value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. If it is suffixed with "[]" and the value is an array then multiple placeholders will be created, one per each value in the array. #### Returns `$this` ### equalFields() public ``` equalFields(string $leftField, string $rightField): $this ``` Builds equal condition or assignment with identifier wrapping. #### Parameters `string` $leftField Left join condition field name. `string` $rightField Right join condition field name. #### Returns `$this` ### exists() public ``` exists(Cake\Database\ExpressionInterface $expression): $this ``` Adds a new condition to the expression object in the form "EXISTS (...)". #### Parameters `Cake\Database\ExpressionInterface` $expression the inner query #### Returns `$this` ### getConjunction() public ``` getConjunction(): string ``` Gets the currently configured conjunction for the conditions at this level of the expression tree. #### Returns `string` ### 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` ### gt() public ``` gt(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field > value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### gte() public ``` gte(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field >= value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### hasNestedExpression() public ``` hasNestedExpression(): bool ``` Returns true if this expression contains any other nested ExpressionInterface objects #### Returns `bool` ### in() public ``` in(Cake\Database\ExpressionInterface|string $field, Cake\Database\ExpressionInterface|array|string $values, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field IN (value1, value2)". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `Cake\Database\ExpressionInterface|array|string` $values the value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### isCallable() public ``` isCallable(Cake\Database\ExpressionInterface|callable|array|string $callable): bool ``` Check whether a callable is acceptable. We don't accept ['class', 'method'] style callbacks, as they often contain user input and arrays of strings are easy to sneak in. #### Parameters `Cake\Database\ExpressionInterface|callable|array|string` $callable The callable to check. #### Returns `bool` ### isNotNull() public ``` isNotNull(Cake\Database\ExpressionInterface|string $field): $this ``` Adds a new condition to the expression object in the form "field IS NOT NULL". #### Parameters `Cake\Database\ExpressionInterface|string` $field database field to be tested for not null #### Returns `$this` ### isNull() public ``` isNull(Cake\Database\ExpressionInterface|string $field): $this ``` Adds a new condition to the expression object in the form "field IS NULL". #### Parameters `Cake\Database\ExpressionInterface|string` $field database field to be tested for null #### Returns `$this` ### iterateParts() public ``` iterateParts(callable $callback): $this ``` Executes a callable function for each of the parts that form this expression. The callable function is required to return a value with which the currently visited part will be replaced. If the callable function returns null then the part will be discarded completely from this expression. The callback function will receive each of the conditions as first param and the key as second param. It is possible to declare the second parameter as passed by reference, this will enable you to change the key under which the modified part is stored. #### Parameters `callable` $callback The callable to apply to each part. #### Returns `$this` ### like() public ``` like(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field LIKE value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### lt() public ``` lt(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field < value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### lte() public ``` lte(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field <= value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### not() public ``` not(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): $this ``` Adds a new set of conditions to this level of the tree and negates the final result by prepending a NOT, it will look like "NOT ( (condition1) AND (conditions2) )" conjunction depends on the one currently configured for this object. #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be added and negated `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `$this` ### notEq() public ``` notEq(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field != value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. If it is suffixed with "[]" and the value is an array then multiple placeholders will be created, one per each value in the array. #### Returns `$this` ### notExists() public ``` notExists(Cake\Database\ExpressionInterface $expression): $this ``` Adds a new condition to the expression object in the form "NOT EXISTS (...)". #### Parameters `Cake\Database\ExpressionInterface` $expression the inner query #### Returns `$this` ### notIn() public ``` notIn(Cake\Database\ExpressionInterface|string $field, Cake\Database\ExpressionInterface|array|string $values, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field NOT IN (value1, value2)". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `Cake\Database\ExpressionInterface|array|string` $values the value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### notInOrNull() public ``` notInOrNull(Cake\Database\ExpressionInterface|string $field, Cake\Database\ExpressionInterface|array|string $values, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "(field NOT IN (value1, value2) OR field IS NULL". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `Cake\Database\ExpressionInterface|array|string` $values the value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### notLike() public ``` notLike(Cake\Database\ExpressionInterface|string $field, mixed $value, string|null $type = null): $this ``` Adds a new condition to the expression object in the form "field NOT LIKE value". #### Parameters `Cake\Database\ExpressionInterface|string` $field Database field to be compared against value `mixed` $value The value to be bound to $field for comparison `string|null` $type optional the type name for $value as configured using the Type map. #### Returns `$this` ### or() public ``` or(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "OR" #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be joined with OR `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `Cake\Database\Expression\QueryExpression` ### or\_() public ``` or_(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object containing all the conditions passed and set up the conjunction to be "OR" #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions to be joined with OR `array<string, string>` $types optional Associative array of fields pointing to the type of the values that are being passed. Used for correctly binding values to statements. #### Returns `Cake\Database\Expression\QueryExpression` ### setConjunction() public ``` setConjunction(string $conjunction): $this ``` Changes the conjunction for the conditions at this level of the expression tree. #### Parameters `string` $conjunction Value to be used for joining conditions #### 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() ### 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` ### 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 "branches" of the expression tree. For example one key of the array might look like "sum > :value" #### Type `array` ### $\_conjunction protected String to be used for joining each of the internal expressions this object internally stores for example "AND", "OR", etc. #### Type `string` ### $\_typeMap protected #### Type `Cake\Database\TypeMap|null`
programming_docs
cakephp Namespace Core Namespace Core ============== ### Namespaces * [Cake\Core\Configure](namespace-cake.core.configure) * [Cake\Core\Exception](namespace-cake.core.exception) * [Cake\Core\Retry](namespace-cake.core.retry) * [Cake\Core\TestSuite](namespace-cake.core.testsuite) ### Interfaces * ##### [ConsoleApplicationInterface](interface-cake.core.consoleapplicationinterface) An interface defining the methods that the console runner depend on. * ##### [ContainerApplicationInterface](interface-cake.core.containerapplicationinterface) Interface for applications that configure and use a dependency injection container. * ##### [ContainerInterface](interface-cake.core.containerinterface) Interface for the Dependency Injection Container in CakePHP applications * ##### [HttpApplicationInterface](interface-cake.core.httpapplicationinterface) An interface defining the methods that the http server depend on. * ##### [PluginApplicationInterface](interface-cake.core.pluginapplicationinterface) Interface for Applications that leverage plugins & events. * ##### [PluginInterface](interface-cake.core.plugininterface) Plugin Interface ### Classes * ##### [App](class-cake.core.app) App is responsible for resource location, and path management. * ##### [BasePlugin](class-cake.core.baseplugin) Base Plugin Class * ##### [ClassLoader](class-cake.core.classloader) ClassLoader * ##### [Configure](class-cake.core.configure) Configuration class. Used for managing runtime configuration information. * ##### [Container](class-cake.core.container) Dependency Injection container * ##### [ObjectRegistry](class-cake.core.objectregistry) Acts as a registry/factory for objects. * ##### [Plugin](class-cake.core.plugin) Plugin is used to load and locate plugins. * ##### [PluginCollection](class-cake.core.plugincollection) Plugin Collection * ##### [ServiceConfig](class-cake.core.serviceconfig) Read-only wrapper for configuration data * ##### [ServiceProvider](class-cake.core.serviceprovider) Container ServiceProvider ### Traits * ##### [ConventionsTrait](trait-cake.core.conventionstrait) Provides methods that allow other classes access to conventions based inflections. * ##### [InstanceConfigTrait](trait-cake.core.instanceconfigtrait) A trait for reading and writing instance config * ##### [StaticConfigTrait](trait-cake.core.staticconfigtrait) A trait that provides a set of static methods to manage configuration for classes that provide an adapter facade or need to have sets of configuration data registered and manipulated. cakephp Class WebExceptionRenderer Class WebExceptionRenderer =========================== Web Exception Renderer. Captures and handles all unhandled exceptions. Displays helpful framework errors when debug is true. When debug is false, WebExceptionRenderer will render 404 or 500 errors. If an uncaught exception is thrown and it is a type that WebExceptionHandler does not know about it will be treated as a 500 error. ### Implementing application specific exception rendering You can implement application specific exception handling by creating a subclass of WebExceptionRenderer and configure it to be the `exceptionRenderer` in config/error.php #### Using a subclass of WebExceptionRenderer Using a subclass of WebExceptionRenderer gives you full control over how Exceptions are rendered, you can configure your class in your config/app.php. **Namespace:** [Cake\Error\Renderer](namespace-cake.error.renderer) Property Summary ---------------- * [$controller](#%24controller) protected `Cake\Controller\Controller` Controller instance. * [$error](#%24error) protected `Throwable` The exception being handled. * [$exceptionHttpCodes](#%24exceptionHttpCodes) protected `array<string, int>` Map of exceptions to http status codes. * [$method](#%24method) protected `string` The method corresponding to the Exception this object is for. * [$request](#%24request) protected `Cake\Http\ServerRequest|null` If set, this will be request used to create the controller that will render the error. * [$template](#%24template) protected `string` Template to render for {@link \Cake\Core\Exception\CakeException} Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Creates the controller to perform rendering on the error response. * ##### [\_\_debugInfo()](#__debugInfo()) public Returns an array that can be used to describe the internal state of this object. * ##### [\_customMethod()](#_customMethod()) protected Render a custom error method/template. * ##### [\_getController()](#_getController()) protected Get the controller instance to handle the exception. Override this method in subclasses to customize the controller used. This method returns the built in `ErrorController` normally, or if an error is repeated a bare controller will be used. * ##### [\_message()](#_message()) protected Get error message. * ##### [\_method()](#_method()) protected Get method name * ##### [\_outputMessage()](#_outputMessage()) protected Generate the response using the controller object. * ##### [\_outputMessageSafe()](#_outputMessageSafe()) protected A safer way to render error messages, replaces all helpers, with basics and doesn't call component methods. * ##### [\_shutdown()](#_shutdown()) protected Run the shutdown events. * ##### [\_template()](#_template()) protected Get template for rendering exception info. * ##### [clearOutput()](#clearOutput()) protected Clear output buffers so error pages display properly. * ##### [getHttpCode()](#getHttpCode()) protected Gets the appropriate http status code for exception. * ##### [render()](#render()) public Renders the response for the exception. * ##### [write()](#write()) public Emit the response content Method Detail ------------- ### \_\_construct() public ``` __construct(Throwable $exception, Cake\Http\ServerRequest|null $request = null) ``` Creates the controller to perform rendering on the error response. #### Parameters `Throwable` $exception Exception. `Cake\Http\ServerRequest|null` $request optional The request if this is set it will be used instead of creating a new one. ### \_\_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>` ### \_customMethod() protected ``` _customMethod(string $method, Throwable $exception): Cake\Http\Response ``` Render a custom error method/template. #### Parameters `string` $method The method name to invoke. `Throwable` $exception The exception to render. #### Returns `Cake\Http\Response` ### \_getController() protected ``` _getController(): Cake\Controller\Controller ``` Get the controller instance to handle the exception. Override this method in subclasses to customize the controller used. This method returns the built in `ErrorController` normally, or if an error is repeated a bare controller will be used. #### Returns `Cake\Controller\Controller` ### \_message() protected ``` _message(Throwable $exception, int $code): string ``` Get error message. #### Parameters `Throwable` $exception Exception. `int` $code Error code. #### Returns `string` ### \_method() protected ``` _method(Throwable $exception): string ``` Get method name #### Parameters `Throwable` $exception Exception instance. #### Returns `string` ### \_outputMessage() protected ``` _outputMessage(string $template): Cake\Http\Response ``` Generate the response using the controller object. #### Parameters `string` $template The template to render. #### Returns `Cake\Http\Response` ### \_outputMessageSafe() protected ``` _outputMessageSafe(string $template): Cake\Http\Response ``` A safer way to render error messages, replaces all helpers, with basics and doesn't call component methods. #### Parameters `string` $template The template to render. #### Returns `Cake\Http\Response` ### \_shutdown() protected ``` _shutdown(): Cake\Http\Response ``` Run the shutdown events. Triggers the afterFilter and afterDispatch events. #### Returns `Cake\Http\Response` ### \_template() protected ``` _template(Throwable $exception, string $method, int $code): string ``` Get template for rendering exception info. #### Parameters `Throwable` $exception Exception instance. `string` $method Method name. `int` $code Error code. #### Returns `string` ### clearOutput() protected ``` clearOutput(): void ``` Clear output buffers so error pages display properly. #### Returns `void` ### getHttpCode() protected ``` getHttpCode(Throwable $exception): int ``` Gets the appropriate http status code for exception. #### Parameters `Throwable` $exception Exception. #### Returns `int` ### render() public ``` render(): Cake\Http\Response ``` Renders the response for the exception. #### Returns `Cake\Http\Response` ### write() public ``` write(Psr\Http\Message\ResponseInterface|string $output): void ``` Emit the response content #### Parameters `Psr\Http\Message\ResponseInterface|string` $output The response to output. #### Returns `void` Property Detail --------------- ### $controller protected Controller instance. #### Type `Cake\Controller\Controller` ### $error protected The exception being handled. #### Type `Throwable` ### $exceptionHttpCodes protected Map of exceptions to http status codes. This can be customized for users that don't want specific exceptions to throw 404 errors or want their application exceptions to be automatically converted. #### Type `array<string, int>` ### $method protected The method corresponding to the Exception this object is for. #### Type `string` ### $request protected If set, this will be request used to create the controller that will render the error. #### Type `Cake\Http\ServerRequest|null` ### $template protected Template to render for {@link \Cake\Core\Exception\CakeException} #### Type `string` cakephp Class AssetMiddleware Class AssetMiddleware ====================== Handles serving plugin assets in development mode. This should not be used in production environments as it has sub-optimal performance when compared to serving files with a real webserver. **Namespace:** [Cake\Routing\Middleware](namespace-cake.routing.middleware) Property Summary ---------------- * [$cacheTime](#%24cacheTime) protected `string` The amount of time to cache the asset. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [\_getAssetFile()](#_getAssetFile()) protected Builds asset file path based off url * ##### [deliverAsset()](#deliverAsset()) protected Sends an asset file to the client * ##### [isNotModified()](#isNotModified()) protected Check the not modified header. * ##### [process()](#process()) public Serve assets if the path matches one. Method Detail ------------- ### \_\_construct() public ``` __construct(array<string, mixed> $options = []) ``` Constructor. #### Parameters `array<string, mixed>` $options optional The options to use ### \_getAssetFile() protected ``` _getAssetFile(string $url): string|null ``` Builds asset file path based off url #### Parameters `string` $url Asset URL #### Returns `string|null` ### deliverAsset() protected ``` deliverAsset(Psr\Http\Message\ServerRequestInterface $request, SplFileInfo $file): Cake\Http\Response ``` Sends an asset file to the client #### Parameters `Psr\Http\Message\ServerRequestInterface` $request The request object to use. `SplFileInfo` $file The file wrapper for the file. #### Returns `Cake\Http\Response` ### isNotModified() protected ``` isNotModified(Psr\Http\Message\ServerRequestInterface $request, SplFileInfo $file): bool ``` Check the not modified header. #### Parameters `Psr\Http\Message\ServerRequestInterface` $request The request to check. `SplFileInfo` $file The file object to compare. #### Returns `bool` ### process() public ``` process(ServerRequestInterface $request, RequestHandlerInterface $handler): Psr\Http\Message\ResponseInterface ``` Serve assets if the path matches one. 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 --------------- ### $cacheTime protected The amount of time to cache the asset. #### Type `string` cakephp Namespace Task Namespace Task ============== ### Classes * ##### [CommandTask](class-cake.shell.task.commandtask) Base class for Shell Command reflection. cakephp Class SimplePaginator Class SimplePaginator ====================== Simplified paginator which avoids potentially expensives queries to get the total count of records. When using a simple paginator you will not be able to generate page numbers. Instead use only the prev/next pagination controls, and handle 404 errors when pagination goes past the available result set. **Namespace:** [Cake\Datasource\Paging](namespace-cake.datasource.paging) 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 pagination settings. * [$\_pagingParams](#%24_pagingParams) protected `array<string, array>` Paging params after pagination operation is done. Method Summary -------------- * ##### [\_configDelete()](#_configDelete()) protected Deletes a single config key. * ##### [\_configRead()](#_configRead()) protected Reads a config key. * ##### [\_configWrite()](#_configWrite()) protected Writes a config key. * ##### [\_extractFinder()](#_extractFinder()) protected Extracts the finder name and options out of the provided pagination options. * ##### [\_prefix()](#_prefix()) protected Prefixes the field with the table alias if possible. * ##### [\_removeAliases()](#_removeAliases()) protected Remove alias if needed. * ##### [addPageCountParams()](#addPageCountParams()) protected Add "page" and "pageCount" params. * ##### [addPrevNextParams()](#addPrevNextParams()) protected Add "prevPage" and "nextPage" params. * ##### [addSortingParams()](#addSortingParams()) protected Add sorting / ordering params. * ##### [addStartEndParams()](#addStartEndParams()) protected Add "start" and "end" params. * ##### [buildParams()](#buildParams()) protected Build pagination params. * ##### [checkLimit()](#checkLimit()) public Check the limit parameter and ensure it's within the maxLimit bounds. * ##### [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. * ##### [extractData()](#extractData()) protected Extract pagination data needed * ##### [getAllowedParameters()](#getAllowedParameters()) protected Shim method for reading the deprecated whitelist or allowedParameters options * ##### [getConfig()](#getConfig()) public Returns the config. * ##### [getConfigOrFail()](#getConfigOrFail()) public Returns the config for this specific key. * ##### [getCount()](#getCount()) protected Simple pagination does not perform any count query, so this method returns `null`. * ##### [getDefaults()](#getDefaults()) public Get the settings for a $model. If there are no settings for a specific repository, the general settings will be used. * ##### [getPagingParams()](#getPagingParams()) public Get paging params after pagination operation. * ##### [getQuery()](#getQuery()) protected Get query for fetching paginated results. * ##### [getSortableFields()](#getSortableFields()) protected Shim method for reading the deprecated sortWhitelist or sortableFields options. * ##### [mergeOptions()](#mergeOptions()) public Merges the various options that Paginator uses. Pulls settings together from the following places: * ##### [paginate()](#paginate()) public Handles automatic pagination of model records. * ##### [setConfig()](#setConfig()) public Sets the config. * ##### [validateSort()](#validateSort()) public Validate that the desired sorting can be performed on the $object. 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 ### \_extractFinder() protected ``` _extractFinder(array<string, mixed> $options): array ``` Extracts the finder name and options out of the provided pagination options. #### Parameters `array<string, mixed>` $options the pagination options. #### Returns `array` ### \_prefix() protected ``` _prefix(Cake\Datasource\RepositoryInterface $object, array $order, bool $allowed = false): array ``` Prefixes the field with the table alias if possible. #### Parameters `Cake\Datasource\RepositoryInterface` $object Repository object. `array` $order Order array. `bool` $allowed optional Whether the field was allowed. #### Returns `array` ### \_removeAliases() protected ``` _removeAliases(array<string, mixed> $fields, string $model): array<string, mixed> ``` Remove alias if needed. #### Parameters `array<string, mixed>` $fields Current fields `string` $model Current model alias #### Returns `array<string, mixed>` ### addPageCountParams() protected ``` addPageCountParams(array<string, mixed> $params, array $data): array<string, mixed> ``` Add "page" and "pageCount" params. #### Parameters `array<string, mixed>` $params Paging params. `array` $data Paginator data. #### Returns `array<string, mixed>` ### addPrevNextParams() protected ``` addPrevNextParams(array<string, mixed> $params, array $data): array<string, mixed> ``` Add "prevPage" and "nextPage" params. #### Parameters `array<string, mixed>` $params Paginator params. `array` $data Paging data. #### Returns `array<string, mixed>` ### addSortingParams() protected ``` addSortingParams(array<string, mixed> $params, array $data): array<string, mixed> ``` Add sorting / ordering params. #### Parameters `array<string, mixed>` $params Paginator params. `array` $data Paging data. #### Returns `array<string, mixed>` ### addStartEndParams() protected ``` addStartEndParams(array<string, mixed> $params, array $data): array<string, mixed> ``` Add "start" and "end" params. #### Parameters `array<string, mixed>` $params Paging params. `array` $data Paginator data. #### Returns `array<string, mixed>` ### buildParams() protected ``` buildParams(array<string, mixed> $data): array<string, mixed> ``` Build pagination params. #### Parameters `array<string, mixed>` $data Paginator data containing keys 'options', 'count', 'defaults', 'finder', 'numResults'. #### Returns `array<string, mixed>` ### checkLimit() public ``` checkLimit(array<string, mixed> $options): array<string, mixed> ``` Check the limit parameter and ensure it's within the maxLimit bounds. #### Parameters `array<string, mixed>` $options An array of options with a limit key to be checked. #### 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` ### extractData() protected ``` extractData(Cake\Datasource\RepositoryInterface $object, array<string, mixed> $params, array<string, mixed> $settings): array ``` Extract pagination data needed #### Parameters `Cake\Datasource\RepositoryInterface` $object The repository object. `array<string, mixed>` $params Request params `array<string, mixed>` $settings The settings/configuration used for pagination. #### Returns `array` ### getAllowedParameters() protected ``` getAllowedParameters(): array<string> ``` Shim method for reading the deprecated whitelist or allowedParameters options #### Returns `array<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` ### getCount() protected ``` getCount(Cake\Datasource\QueryInterface $query, array $data): int|null ``` Simple pagination does not perform any count query, so this method returns `null`. #### Parameters `Cake\Datasource\QueryInterface` $query Query instance. `array` $data Pagination data. #### Returns `int|null` ### getDefaults() public ``` getDefaults(string $alias, array<string, mixed> $settings): array<string, mixed> ``` Get the settings for a $model. If there are no settings for a specific repository, the general settings will be used. #### Parameters `string` $alias Model name to get settings for. `array<string, mixed>` $settings The settings which is used for combining. #### Returns `array<string, mixed>` ### getPagingParams() public ``` getPagingParams(): array<string, array> ``` Get paging params after pagination operation. #### Returns `array<string, array>` ### getQuery() protected ``` getQuery(Cake\Datasource\RepositoryInterface $object, Cake\Datasource\QueryInterface|null $query, array<string, mixed> $data): Cake\Datasource\QueryInterface ``` Get query for fetching paginated results. #### Parameters `Cake\Datasource\RepositoryInterface` $object Repository instance. `Cake\Datasource\QueryInterface|null` $query Query Instance. `array<string, mixed>` $data Pagination data. #### Returns `Cake\Datasource\QueryInterface` ### getSortableFields() protected ``` getSortableFields(array<string, mixed> $config): array<string>|null ``` Shim method for reading the deprecated sortWhitelist or sortableFields options. #### Parameters `array<string, mixed>` $config The configuration data to coalesce and emit warnings on. #### Returns `array<string>|null` ### mergeOptions() public ``` mergeOptions(array<string, mixed> $params, array $settings): array<string, mixed> ``` Merges the various options that Paginator 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 `array<string, mixed>` $params Request params. `array` $settings The settings to merge with the request data. #### Returns `array<string, mixed>` ### paginate() public ``` paginate(Cake\Datasource\RepositoryInterfaceCake\Datasource\QueryInterface $object, array $params = [], array $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 repository. You can configure repository specific settings by keying the settings with the repository 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` repositories. ### Controlling sort fields By default CakePHP will automatically allow sorting on any column on the repository 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 all the columns you wish to allow sorting on. You can define the allowed sort fields in the `$settings` parameter: ``` $settings = [ 'Articles' => [ 'finder' => 'custom', 'sortableFields' => ['title', 'author_id', 'comment_count'], ] ]; ``` Passing an empty array as sortableFields 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 The repository or query to paginate. `array` $params optional Request params `array` $settings optional The settings/configuration used for pagination. #### Returns `Cake\Datasource\ResultSetInterface` #### Throws `Cake\Datasource\Paging\Exception\PageOutOfBoundsException` ### 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. ### validateSort() public ``` validateSort(Cake\Datasource\RepositoryInterface $object, array<string, mixed> $options): array<string, mixed> ``` Validate that the desired sorting can be performed on the $object. Only fields or virtualFields can be sorted on. The direction param will also be sanitized. Lastly sort + direction keys will be converted into the model friendly order key. You can use the allowedParameters option to control which columns/fields are available for sorting via URL parameters. This helps prevent users from ordering large result sets on un-indexed values. If you need to sort on associated columns or synthetic properties you will need to use the `sortableFields` option. Any columns listed in the allowed sort fields will be implicitly trusted. You can use this to sort on synthetic columns, or columns added in custom find operations that may not exist in the schema. The default order options provided to paginate() will be merged with the user's requested sorting field/direction. #### Parameters `Cake\Datasource\RepositoryInterface` $object Repository object. `array<string, mixed>` $options The pagination options being used for this request. #### Returns `array<string, mixed>` 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 pagination settings. When calling paginate() these settings will be merged with the configuration you provide. * `maxLimit` - The maximum limit users can choose to view. Defaults to 100 * `limit` - The initial number of items per page. Defaults to 20. * `page` - The starting page, defaults to 1. * `allowedParameters` - A list of parameters users are allowed to set using request parameters. Modifying this list will allow users to have more influence over pagination, be careful with what you permit. #### Type `array<string, mixed>` ### $\_pagingParams protected Paging params after pagination operation is done. #### Type `array<string, array>`
programming_docs
cakephp Class ResultSet Class 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. **Namespace:** [Cake\ORM](namespace-cake.orm) Property Summary ---------------- * [$\_autoFields](#%24_autoFields) protected `bool|null` Tracks value of $\_autoFields property of $query passed to constructor. * [$\_containMap](#%24_containMap) protected `array` List of associations that should be eager loaded. * [$\_count](#%24_count) protected `int` Holds the count of records in this result set * [$\_current](#%24_current) protected `object|array` Last record fetched from the statement * [$\_defaultAlias](#%24_defaultAlias) protected `string` The default table alias * [$\_defaultTable](#%24_defaultTable) protected `Cake\ORM\Table` Default table instance * [$\_driver](#%24_driver) protected `Cake\Database\DriverInterface` The Database driver object. * [$\_entityClass](#%24_entityClass) protected `string` The fully namespaced name of the class to use for hydrating results * [$\_hydrate](#%24_hydrate) protected `bool` Whether to hydrate results into objects or not * [$\_index](#%24_index) protected `int` Points to the next record number that should be fetched * [$\_map](#%24_map) protected `array<string, mixed>` Map of fields that are fetched from the statement with their type and the table they belong to * [$\_matchingMap](#%24_matchingMap) protected `array<string, mixed>` List of associations that should be placed under the `_matchingData` result key. * [$\_matchingMapColumns](#%24_matchingMapColumns) protected `array<string, mixed>` List of matching associations and the column keys to expect from each of them. * [$\_results](#%24_results) protected `SplFixedArray|array` Results that have been fetched or hydrated into the results. * [$\_statement](#%24_statement) protected `Cake\Database\StatementInterface` Database statement holding the results * [$\_useBuffering](#%24_useBuffering) protected `bool` Whether to buffer results fetched from the statement 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 Serializes a resultset. * ##### [\_\_unserialize()](#__unserialize()) public Unserializes a resultset. * ##### [\_calculateAssociationMap()](#_calculateAssociationMap()) protected Calculates the list of associations that should get eager loaded when fetching each record * ##### [\_calculateColumnMap()](#_calculateColumnMap()) protected Creates a map of row keys out of the query select clause that can be used to hydrate nested result sets more quickly. * ##### [\_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 `{*}` * ##### [\_fetchResult()](#_fetchResult()) protected Helper function to fetch the next result from the statement or seeded results. * ##### [\_groupResult()](#_groupResult()) protected Correctly nests results keys including those coming from associations * ##### [\_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 Gives the number of rows in the result set. * ##### [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 result 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 Get the first record from a result set. * ##### [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 key of the current record 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 record * ##### [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 a ResultSet. * ##### [sample()](#sample()) public Returns a new collection with maximum $size random elements from this collection * ##### [serialize()](#serialize()) public Serializes a resultset. * ##### [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 a resultset. * ##### [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 Whether there are more results to be fetched from the iterator * ##### [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(Cake\ORM\Query $query, Cake\Database\StatementInterface $statement) ``` Constructor #### Parameters `Cake\ORM\Query` $query Query from where results come `Cake\Database\StatementInterface` $statement The statement to fetch from ### \_\_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 ``` Serializes a resultset. #### Returns `array` ### \_\_unserialize() public ``` __unserialize(array $data): void ``` Unserializes a resultset. #### Parameters `array` $data Data array. #### Returns `void` ### \_calculateAssociationMap() protected ``` _calculateAssociationMap(Cake\ORM\Query $query): void ``` Calculates the list of associations that should get eager loaded when fetching each record #### Parameters `Cake\ORM\Query` $query The query from where to derive the associations #### Returns `void` ### \_calculateColumnMap() protected ``` _calculateColumnMap(Cake\ORM\Query $query): void ``` Creates a map of row keys out of the query select clause that can be used to hydrate nested result sets more quickly. #### Parameters `Cake\ORM\Query` $query The query from where to derive the column map #### 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` ### \_fetchResult() protected ``` _fetchResult(): mixed ``` Helper function to fetch the next result from the statement or seeded results. #### Returns `mixed` ### \_groupResult() protected ``` _groupResult(array $row): Cake\Datasource\EntityInterface|array ``` Correctly nests results keys including those coming from associations #### Parameters `array` $row Array containing columns and values or false if there is no results #### Returns `Cake\Datasource\EntityInterface|array` ### \_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 ``` Gives the number of rows in the result set. Part of the Countable interface. #### 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(): object|array ``` Returns the current record in the result iterator Part of Iterator interface. #### Returns `object|array` ### 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(): object|array|null ``` Get the first record from a result set. This method will also close the underlying statement cursor. #### Returns `object|array|null` ### 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(): int ``` Returns the key of the current record in the iterator Part of Iterator interface. #### Returns `int` ### 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 record Part of Iterator interface. #### 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 a ResultSet. Part of Iterator interface. #### Returns `void` #### Throws `Cake\Database\Exception\DatabaseException` ### 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 ``` Serializes a resultset. Part of Serializable interface. #### 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 $serialized): void ``` Unserializes a resultset. Part of Serializable interface. #### Parameters `string` $serialized Serialized object #### 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 ``` Whether there are more results to be fetched from the iterator Part of Iterator interface. #### 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 --------------- ### $\_autoFields protected Tracks value of $\_autoFields property of $query passed to constructor. #### Type `bool|null` ### $\_containMap protected List of associations that should be eager loaded. #### Type `array` ### $\_count protected Holds the count of records in this result set #### Type `int` ### $\_current protected Last record fetched from the statement #### Type `object|array` ### $\_defaultAlias protected The default table alias #### Type `string` ### $\_defaultTable protected Default table instance #### Type `Cake\ORM\Table` ### $\_driver protected The Database driver object. Cached in a property to avoid multiple calls to the same function. #### Type `Cake\Database\DriverInterface` ### $\_entityClass protected The fully namespaced name of the class to use for hydrating results #### Type `string` ### $\_hydrate protected Whether to hydrate results into objects or not #### Type `bool` ### $\_index protected Points to the next record number that should be fetched #### Type `int` ### $\_map protected Map of fields that are fetched from the statement with their type and the table they belong to #### Type `array<string, mixed>` ### $\_matchingMap protected List of associations that should be placed under the `_matchingData` result key. #### Type `array<string, mixed>` ### $\_matchingMapColumns protected List of matching associations and the column keys to expect from each of them. #### Type `array<string, mixed>` ### $\_results protected Results that have been fetched or hydrated into the results. #### Type `SplFixedArray|array` ### $\_statement protected Database statement holding the results #### Type `Cake\Database\StatementInterface` ### $\_useBuffering protected Whether to buffer results fetched from the statement #### Type `bool`
programming_docs
cakephp Class CommandRetry Class CommandRetry =================== Allows any action to be retried in case of an exception. This class can be parametrized with a strategy, which will be followed to determine whether the action should be retried. **Namespace:** [Cake\Core\Retry](namespace-cake.core.retry) Property Summary ---------------- * [$maxRetries](#%24maxRetries) protected `int` * [$numRetries](#%24numRetries) protected `int` * [$strategy](#%24strategy) protected `Cake\Core\Retry\RetryStrategyInterface` The strategy to follow should the executed action fail. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Creates the CommandRetry object with the given strategy and retry count * ##### [getRetries()](#getRetries()) public Returns the last number of retry attemps. * ##### [run()](#run()) public The number of retries to perform in case of failure Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\Core\Retry\RetryStrategyInterface $strategy, int $maxRetries = 1) ``` Creates the CommandRetry object with the given strategy and retry count #### Parameters `Cake\Core\Retry\RetryStrategyInterface` $strategy The strategy to follow should the action fail `int` $maxRetries optional The maximum number of retry attempts allowed ### getRetries() public ``` getRetries(): int ``` Returns the last number of retry attemps. #### Returns `int` ### run() public ``` run(callable $action): mixed ``` The number of retries to perform in case of failure #### Parameters `callable` $action The callable action to execute with a retry strategy #### Returns `mixed` #### Throws `Exception` Property Detail --------------- ### $maxRetries protected #### Type `int` ### $numRetries protected #### Type `int` ### $strategy protected The strategy to follow should the executed action fail. #### Type `Cake\Core\Retry\RetryStrategyInterface` cakephp Namespace Constraint Namespace Constraint ==================== ### Namespaces * [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) ### Classes * ##### [EventFired](class-cake.testsuite.constraint.eventfired) EventFired constraint * ##### [EventFiredWith](class-cake.testsuite.constraint.eventfiredwith) EventFiredWith constraint cakephp Class FlashComponent Class 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. **Namespace:** [Cake\Controller\Component](namespace-cake.controller.component) 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 configuration * [$\_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 Magic method for verbose flash methods based on element names. * ##### [\_\_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. * ##### [configShallow()](#configShallow()) public Proxy method to FlashMessage instance. * ##### [error()](#error()) public @method Set a message using "error" element * ##### [flash()](#flash()) protected Get flash message utility instance. * ##### [getConfig()](#getConfig()) public Proxy method to FlashMessage instance. * ##### [getConfigOrFail()](#getConfigOrFail()) public Proxy method to FlashMessage instance. * ##### [getController()](#getController()) public Get the controller this component is bound to. * ##### [implementedEvents()](#implementedEvents()) public Get the Controller callbacks this Component is interested in. * ##### [info()](#info()) public @method Set a message using "info" element * ##### [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. * ##### [set()](#set()) public Used to set a session variable that can be used to output messages in the view. If you make consecutive calls to this method, the messages will stack (if they are set with the same flash key) * ##### [setConfig()](#setConfig()) public Proxy method to FlashMessage instance. * ##### [success()](#success()) public @method Set a message using "success" element * ##### [warning()](#warning()) public @method Set a message using "warning" element Method Detail ------------- ### \_\_call() public ``` __call(string $name, array $args): void ``` Magic method for verbose flash methods based on element names. For example: $this->Flash->success('My message') would use the `success.php` element under `templates/element/flash/` for rendering the flash message. If you make consecutive calls to this method, the messages will stack (if they are set with the same flash key) Note that the parameter `element` will be always overridden. In order to call a specific element from a plugin, you should set the `plugin` option in $args. For example: `$this->Flash->warning('My message', ['plugin' => 'PluginName'])` would use the `warning.php` element under `plugins/PluginName/templates/element/flash/` for rendering the flash message. #### Parameters `string` $name Element name to use. `array` $args Parameters to pass when calling `FlashComponent::set()`. #### Returns `void` #### Throws `Cake\Http\Exception\InternalErrorException` If missing the flash message. ### \_\_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): 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 ### configShallow() public ``` configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this ``` Proxy method to FlashMessage instance. 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` ### error() public @method ``` error(string $message, array $options = []): void ``` Set a message using "error" element #### Parameters `string` $message `array` $options optional #### Returns `void` ### flash() protected ``` flash(): Cake\Http\FlashMessage ``` Get flash message utility instance. #### Returns `Cake\Http\FlashMessage` ### getConfig() public ``` getConfig(string|null $key = null, mixed $default = null): mixed ``` Proxy method to FlashMessage instance. ### 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 ``` Proxy method to FlashMessage instance. 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` ### implementedEvents() public ``` implementedEvents(): array<string, mixed> ``` Get the Controller callbacks this Component is interested in. 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>` ### info() public @method ``` info(string $message, array $options = []): void ``` Set a message using "info" element #### Parameters `string` $message `array` $options optional #### Returns `void` ### 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` ### set() public ``` set(Throwable|string $message, array<string, mixed> $options = []): void ``` Used to set a session variable that can be used to output messages in the view. If you make consecutive calls to this method, the messages will stack (if they are set with the same flash key) In your controller: $this->Flash->set('This has been saved'); ### Options: * `key` The key to set under the session's Flash key * `element` The element used to render the flash message. Default to 'default'. * `params` An array of variables to make available when using an 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 `Throwable|string` $message Message to be flashed. If an instance of \Throwable the throwable message will be used and code will be set in params. `array<string, mixed>` $options optional An array of options #### Returns `void` ### setConfig() public ``` setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this ``` Proxy method to FlashMessage instance. ### 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. ### success() public @method ``` success(string $message, array $options = []): void ``` Set a message using "success" element #### Parameters `string` $message `array` $options optional #### Returns `void` ### warning() public @method ``` warning(string $message, array $options = []): void ``` Set a message using "warning" element #### Parameters `string` $message `array` $options optional #### Returns `void` 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 configuration These are merged with user-provided config when the component is used. #### Type `array<string, mixed>` ### $\_registry protected Component registry class used to lazy load components. #### Type `Cake\Controller\ComponentRegistry` ### $components protected Other Components this component uses. #### Type `array` cakephp Class SocketException Class SocketException ====================== Exception class for Socket. This exception will be thrown from Socket, Email, HttpSocket SmtpTransport, MailTransport and HttpResponse when it encounters an error. **Namespace:** [Cake\Network\Exception](namespace-cake.network.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 NestedTransactionRollbackException Class NestedTransactionRollbackException ========================================= Class NestedTransactionRollbackException **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(string|null $message = null, int|null $code = 500, 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 a default meesage will be used. `int|null` $code optional Status code, defaults to 500. `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 Session Class 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. Sessions can be created from the defaults using `Session::create()` or you can get an instance of a new session by just instantiating this class and passing the complete options you want to use. When specific options are omitted, this class will take its defaults from the configuration values from the `session.*` directives in php.ini. This class will also alter such directives when configuration values are provided. **Namespace:** [Cake\Http](namespace-cake.http) Property Summary ---------------- * [$\_engine](#%24_engine) protected `SessionHandlerInterface` The Session handler instance used as an engine for persisting the session data. * [$\_isCLI](#%24_isCLI) protected `bool` Whether this session is running under a CLI environment * [$\_lifetime](#%24_lifetime) protected `int` The time in seconds the session will be valid for * [$\_started](#%24_started) protected `bool` Indicates whether the sessions has already started Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [\_defaultConfig()](#_defaultConfig()) protected static Get one of the prebaked default session configurations. * ##### [\_hasSession()](#_hasSession()) protected Returns whether a session exists * ##### [\_overwrite()](#_overwrite()) protected Used to write new data to \_SESSION, since PHP doesn't like us setting the \_SESSION var itself. * ##### [\_timedOut()](#_timedOut()) protected Returns true if the session is no longer valid because the last time it was accessed was after the configured timeout. * ##### [check()](#check()) public Returns true if given variable name is set in session. * ##### [clear()](#clear()) public Clears the session. * ##### [close()](#close()) public Write data and close the session * ##### [consume()](#consume()) public Reads and deletes a variable from session. * ##### [create()](#create()) public static Returns a new instance of a session after building a configuration bundle for it. This function allows an options array which will be used for configuring the session and the handler to be used. The most important key in the configuration array is `defaults`, which indicates the set of configurations to inherit from, the possible defaults are: * ##### [delete()](#delete()) public Removes a variable from session. * ##### [destroy()](#destroy()) public Helper method to destroy invalid sessions. * ##### [engine()](#engine()) public Sets the session handler instance to use for this session. If a string is passed for the first argument, it will be treated as the class name and the second argument will be passed as the first argument in the constructor. * ##### [id()](#id()) public Returns the session id. Calling this method will not auto start the session. You might have to manually assert a started session. * ##### [options()](#options()) public Calls ini\_set for each of the keys in `$options` and set them to the respective value in the passed array. * ##### [read()](#read()) public Returns given session variable, or all of them, if no parameters given. * ##### [readOrFail()](#readOrFail()) public Returns given session variable, or throws Exception if not found. * ##### [renew()](#renew()) public Restarts this session. * ##### [setEngine()](#setEngine()) protected Set the engine property and update the session handler in PHP. * ##### [start()](#start()) public Starts the Session. * ##### [started()](#started()) public Determine if Session has already been started. * ##### [write()](#write()) public Writes value to given session variable name. Method Detail ------------- ### \_\_construct() public ``` __construct(array<string, mixed> $config = []) ``` Constructor. ### Configuration: * timeout: The time in minutes the session should be valid for. * cookiePath: The url path for which session cookie is set. Maps to the `session.cookie_path` php.ini config. Defaults to base path of app. * ini: A list of php.ini directives to change before the session start. * handler: An array containing at least the `engine` key. To be used as the session engine for persisting data. The rest of the keys in the array will be passed as the configuration array for the engine. You can set the `engine` key to an already instantiated session handler object. #### Parameters `array<string, mixed>` $config optional The Configuration to apply to this session object ### \_defaultConfig() protected static ``` _defaultConfig(string $name): array|false ``` Get one of the prebaked default session configurations. #### Parameters `string` $name Config name. #### Returns `array|false` ### \_hasSession() protected ``` _hasSession(): bool ``` Returns whether a session exists #### Returns `bool` ### \_overwrite() protected ``` _overwrite(array $old, array $new): void ``` Used to write new data to \_SESSION, since PHP doesn't like us setting the \_SESSION var itself. #### Parameters `array` $old Set of old variables => values `array` $new New set of variable => value #### Returns `void` ### \_timedOut() protected ``` _timedOut(): bool ``` Returns true if the session is no longer valid because the last time it was accessed was after the configured timeout. #### Returns `bool` ### 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` ### clear() public ``` clear(bool $renew = false): void ``` Clears the session. Optionally it also clears the session id and renews the session. #### Parameters `bool` $renew optional If session should be renewed, as well. Defaults to false. #### Returns `void` ### close() public ``` close(): true ``` Write data and close the session #### Returns `true` ### consume() public ``` consume(string $name): mixed|null ``` Reads and deletes a variable from session. #### Parameters `string` $name The key to read and remove (or a path as sent to Hash.extract). #### Returns `mixed|null` ### create() public static ``` create(array $sessionConfig = []): static ``` Returns a new instance of a session after building a configuration bundle for it. This function allows an options array which will be used for configuring the session and the handler to be used. The most important key in the configuration array is `defaults`, which indicates the set of configurations to inherit from, the possible defaults are: * php: just use session as configured in php.ini * cache: Use the CakePHP caching system as an storage for the session, you will need to pass the `config` key with the name of an already configured Cache engine. * database: Use the CakePHP ORM to persist and manage sessions. By default this requires a table in your database named `sessions` or a `model` key in the configuration to indicate which Table object to use. * cake: Use files for storing the sessions, but let CakePHP manage them and decide where to store them. The full list of options follows: * defaults: either 'php', 'database', 'cache' or 'cake' as explained above. * handler: An array containing the handler configuration * ini: A list of php.ini directives to set before the session starts. * timeout: The time in minutes the session should stay active #### Parameters `array` $sessionConfig optional Session config. #### Returns `static` #### See Also \Cake\Http\Session::\_\_construct() ### delete() public ``` delete(string $name): void ``` Removes a variable from session. #### Parameters `string` $name Session variable to remove #### Returns `void` ### destroy() public ``` destroy(): void ``` Helper method to destroy invalid sessions. #### Returns `void` ### engine() public ``` engine(SessionHandlerInterface|string|null $class = null, array<string, mixed> $options = []): SessionHandlerInterface|null ``` Sets the session handler instance to use for this session. If a string is passed for the first argument, it will be treated as the class name and the second argument will be passed as the first argument in the constructor. If an instance of a SessionHandlerInterface is provided as the first argument, the handler will be set to it. If no arguments are passed it will return the currently configured handler instance or null if none exists. #### Parameters `SessionHandlerInterface|string|null` $class optional The session handler to use `array<string, mixed>` $options optional the options to pass to the SessionHandler constructor #### Returns `SessionHandlerInterface|null` #### Throws `InvalidArgumentException` ### id() public ``` id(string|null $id = null): string ``` Returns the session id. Calling this method will not auto start the session. You might have to manually assert a started session. Passing an id into it, you can also replace the session id if the session has not already been started. Note that depending on the session handler, not all characters are allowed within the session id. For example, the file session handler only allows characters in the range a-z A-Z 0-9 , (comma) and - (minus). #### Parameters `string|null` $id optional Id to replace the current session id #### Returns `string` ### options() public ``` options(array<string, mixed> $options): void ``` Calls ini\_set for each of the keys in `$options` and set them to the respective value in the passed array. ### Example: ``` $session->options(['session.use_cookies' => 1]); ``` #### Parameters `array<string, mixed>` $options Ini options to set. #### Returns `void` #### Throws `RuntimeException` if any directive could not be set ### read() public ``` read(string|null $name = null, mixed $default = null): mixed|null ``` 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) `mixed` $default optional The return value when the path does not exist #### Returns `mixed|null` ### readOrFail() public ``` readOrFail(string $name): mixed|null ``` Returns given session variable, or throws Exception if not found. #### Parameters `string` $name The name of the session variable (or a path as sent to Hash.extract) #### Returns `mixed|null` #### Throws `RuntimeException` ### renew() public ``` renew(): void ``` Restarts this session. #### Returns `void` ### setEngine() protected ``` setEngine(SessionHandlerInterface $handler): SessionHandlerInterface ``` Set the engine property and update the session handler in PHP. #### Parameters `SessionHandlerInterface` $handler The handler to set #### Returns `SessionHandlerInterface` ### start() public ``` start(): bool ``` Starts the Session. #### Returns `bool` #### Throws `RuntimeException` if the session was already started ### started() public ``` started(): bool ``` Determine if Session has already been started. #### Returns `bool` ### write() public ``` write(array|string $name, mixed $value = null): void ``` Writes value to given session variable name. #### Parameters `array|string` $name Name of variable `mixed` $value optional Value to write #### Returns `void` Property Detail --------------- ### $\_engine protected The Session handler instance used as an engine for persisting the session data. #### Type `SessionHandlerInterface` ### $\_isCLI protected Whether this session is running under a CLI environment #### Type `bool` ### $\_lifetime protected The time in seconds the session will be valid for #### Type `int` ### $\_started protected Indicates whether the sessions has already started #### Type `bool` cakephp Class ServerRequestFactory Class ServerRequestFactory =========================== Factory for making ServerRequest instances. This subclass adds in CakePHP specific behavior to populate the basePath and webroot attributes. Furthermore the Uri's path is corrected to only contain the 'virtual' path for the request. **Abstract** **Namespace:** [Cake\Http](namespace-cake.http) Method Summary -------------- * ##### [createServerRequest()](#createServerRequest()) public Create a new server request. * ##### [createUri()](#createUri()) public static Create a new Uri instance from the provided server data. * ##### [fromGlobals()](#fromGlobals()) public static Create a request from the supplied superglobal values. * ##### [getBase()](#getBase()) protected static Calculate the base directory and webroot directory. * ##### [marshalBodyAndRequestMethod()](#marshalBodyAndRequestMethod()) protected static Sets the REQUEST\_METHOD environment variable based on the simulated \_method HTTP override value. The 'ORIGINAL\_REQUEST\_METHOD' is also preserved, if you want the read the non-simulated HTTP method the client used. * ##### [marshalFiles()](#marshalFiles()) protected static Process uploaded files and move things onto the parsed body. * ##### [marshalUriFromSapi()](#marshalUriFromSapi()) protected static Build a UriInterface object. * ##### [updatePath()](#updatePath()) protected static Updates the request URI to remove the base directory. Method Detail ------------- ### createServerRequest() public ``` createServerRequest(string $method, UriInterface|string $uri, array $serverParams = []): Psr\Http\Message\ServerRequestInterface ``` Create a new server request. Note that server-params are taken precisely as given - no parsing/processing of the given values is performed, and, in particular, no attempt is made to determine the HTTP method or URI, which must be provided explicitly. #### Parameters `string` $method The HTTP method associated with the request. `UriInterface|string` $uri The URI associated with the request. If the value is a string, the factory MUST create a UriInterface instance based on it. `array` $serverParams optional Array of SAPI parameters with which to seed the generated request instance. #### Returns `Psr\Http\Message\ServerRequestInterface` ### createUri() public static ``` createUri(array $server = []): Psr\Http\Message\UriInterface ``` Create a new Uri instance from the provided server data. #### Parameters `array` $server optional Array of server data to build the Uri from. $\_SERVER will be added into the $server parameter. #### Returns `Psr\Http\Message\UriInterface` ### fromGlobals() public static ``` fromGlobals(array|null $server = null, array|null $query = null, array|null $parsedBody = null, array|null $cookies = null, array|null $files = null): Cake\Http\ServerRequest ``` Create a request from the supplied superglobal values. If any argument is not supplied, the corresponding superglobal value will be used. The ServerRequest created is then passed to the fromServer() method in order to marshal the request URI and headers. #### Parameters `array|null` $server optional $\_SERVER superglobal `array|null` $query optional $\_GET superglobal `array|null` $parsedBody optional $\_POST superglobal `array|null` $cookies optional $\_COOKIE superglobal `array|null` $files optional $\_FILES superglobal #### Returns `Cake\Http\ServerRequest` #### Throws `InvalidArgumentException` for invalid file values #### See Also fromServer() ### getBase() protected static ``` getBase(Psr\Http\Message\UriInterface $uri, array $server): array ``` Calculate the base directory and webroot directory. #### Parameters `Psr\Http\Message\UriInterface` $uri The Uri instance. `array` $server The SERVER data to use. #### Returns `array` ### marshalBodyAndRequestMethod() protected static ``` marshalBodyAndRequestMethod(array $parsedBody, Cake\Http\ServerRequest $request): Cake\Http\ServerRequest ``` Sets the REQUEST\_METHOD environment variable based on the simulated \_method HTTP override value. The 'ORIGINAL\_REQUEST\_METHOD' is also preserved, if you want the read the non-simulated HTTP method the client used. Request body of content type "application/x-www-form-urlencoded" is parsed into array for PUT/PATCH/DELETE requests. #### Parameters `array` $parsedBody Parsed body. `Cake\Http\ServerRequest` $request Request instance. #### Returns `Cake\Http\ServerRequest` ### marshalFiles() protected static ``` marshalFiles(array $files, Cake\Http\ServerRequest $request): Cake\Http\ServerRequest ``` Process uploaded files and move things onto the parsed body. #### Parameters `array` $files Files array for normalization and merging in parsed body. `Cake\Http\ServerRequest` $request Request instance. #### Returns `Cake\Http\ServerRequest` ### marshalUriFromSapi() protected static ``` marshalUriFromSapi(array $server, array $headers): Cake\Http\Uri ``` Build a UriInterface object. Add in some CakePHP specific logic/properties that help preserve backwards compatibility. #### Parameters `array` $server The server parameters. `array` $headers The normalized headers #### Returns `Cake\Http\Uri` ### updatePath() protected static ``` updatePath(string $base, Psr\Http\Message\UriInterface $uri): Psr\Http\Message\UriInterface ``` Updates the request URI to remove the base directory. #### Parameters `string` $base The base path to remove. `Psr\Http\Message\UriInterface` $uri The uri to update. #### Returns `Psr\Http\Message\UriInterface` cakephp Trait ExpressionTypeCasterTrait Trait ExpressionTypeCasterTrait ================================ Offers a method to convert values to ExpressionInterface objects if the type they should be converted to implements ExpressionTypeInterface **Namespace:** [Cake\Database\Type](namespace-cake.database.type) Method Summary -------------- * ##### [\_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. Method Detail ------------- ### \_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`
programming_docs
cakephp Class LegacyCommandRunner Class LegacyCommandRunner ========================== Class that dispatches to the legacy ShellDispatcher using the same signature as the newer CommandRunner **Namespace:** [Cake\Console\TestSuite](namespace-cake.console.testsuite) Method Summary -------------- * ##### [run()](#run()) public Mimics functionality of Cake\Console\CommandRunner Method Detail ------------- ### run() public ``` run(array $argv, Cake\Console\ConsoleIo|null $io = null): int ``` Mimics functionality of Cake\Console\CommandRunner #### Parameters `array` $argv Argument array `Cake\Console\ConsoleIo|null` $io optional A ConsoleIo instance. #### Returns `int` cakephp Class Message Class Message ============== Email message class. This class is used for sending Internet Message Format based on the standard outlined in <https://www.rfc-editor.org/rfc/rfc2822.txt> **Namespace:** [Cake\Mailer](namespace-cake.mailer) Constants --------- * `string` **EMAIL\_PATTERN** ``` '/^((?:[\\p{L}0-9.!#$%&\'*+\\/=?^_`{|}~-]+)*@[\\p{L}0-9-._]+)$/ui' ``` Holds the regex pattern for email validation * `int` **LINE\_LENGTH\_MUST** ``` 998 ``` Line length - no must more - RFC 2822 - 2.1.1 * `int` **LINE\_LENGTH\_SHOULD** ``` 78 ``` Line length - no should more - RFC 2822 - 2.1.1 * `string` **MESSAGE\_BOTH** ``` 'both' ``` Type of message - BOTH * `string` **MESSAGE\_HTML** ``` 'html' ``` Type of message - HTML * `string` **MESSAGE\_TEXT** ``` 'text' ``` Type of message - TEXT Property Summary ---------------- * [$appCharset](#%24appCharset) protected `string|null` The application wide charset, used to encode headers and body * [$attachments](#%24attachments) protected `array<string, array>` List of files that should be attached to the email. * [$bcc](#%24bcc) protected `array` Blind Carbon Copy * [$boundary](#%24boundary) protected `string|null` If set, boundary to use for multipart mime messages * [$cc](#%24cc) protected `array` Carbon Copy * [$charset](#%24charset) protected `string` Charset the email body is sent in * [$charset8bit](#%24charset8bit) protected `array<string>` 8Bit character sets * [$contentTypeCharset](#%24contentTypeCharset) protected `array<string, string>` Define Content-Type charset name * [$domain](#%24domain) protected `string` Domain for messageId generation. Needs to be manually set for CLI mailing as env('HTTP\_HOST') is empty * [$emailFormat](#%24emailFormat) protected `string` What format should the email be sent in * [$emailFormatAvailable](#%24emailFormatAvailable) protected `array<string>` Available formats to be sent. * [$emailPattern](#%24emailPattern) protected `string|null` Regex for email validation * [$from](#%24from) protected `array` The mail which the email is sent from * [$headerCharset](#%24headerCharset) protected `string|null` Charset the email header is sent in If null, the $charset property will be used as default * [$headers](#%24headers) protected `array` Associative array of a user defined headers Keys will be prefixed 'X-' as per RFC2822 Section 4.7.5 * [$htmlMessage](#%24htmlMessage) protected `string` Html message * [$message](#%24message) protected `array` Final message to send * [$messageId](#%24messageId) protected `string|bool` Message ID * [$priority](#%24priority) protected `int|null` Contains the optional priority of the email. * [$readReceipt](#%24readReceipt) protected `array` The read receipt email * [$replyTo](#%24replyTo) protected `array` List of email(s) that the recipient will reply to * [$returnPath](#%24returnPath) protected `array` The mail that will be used in case of any errors like + Remote mailserver down + Remote user has exceeded his quota + Unknown user * [$sender](#%24sender) protected `array` The sender email * [$subject](#%24subject) protected `string` The subject of the email * [$textMessage](#%24textMessage) protected `string` Text message * [$to](#%24to) protected `array` Recipient of the email * [$transferEncoding](#%24transferEncoding) protected `string|null` The email transfer encoding used. If null, the $charset property is used for determined the transfer encoding. * [$transferEncodingAvailable](#%24transferEncodingAvailable) protected `array<string>` Available encoding to be set for transfer. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [\_\_serialize()](#__serialize()) public Magic method used for serializing the Message object. * ##### [\_\_unserialize()](#__unserialize()) public Magic method used to rebuild the Message object. * ##### [addAttachments()](#addAttachments()) public Add attachments * ##### [addBcc()](#addBcc()) public Add "bcc" address. * ##### [addCc()](#addCc()) public Add "cc" address. * ##### [addEmail()](#addEmail()) protected Add email * ##### [addHeaders()](#addHeaders()) public Add header for the message * ##### [addReplyTo()](#addReplyTo()) public Add "Reply-To" address. * ##### [addTo()](#addTo()) public Add "To" address. * ##### [attachFiles()](#attachFiles()) protected Attach non-embedded files by adding file contents inside boundaries. * ##### [attachInlineFiles()](#attachInlineFiles()) protected Attach inline/embedded files to the message. * ##### [createBoundary()](#createBoundary()) protected Create unique boundary identifier * ##### [createFromArray()](#createFromArray()) public Configures an email instance object from serialized config. * ##### [decodeForHeader()](#decodeForHeader()) protected Decode the specified string * ##### [encodeForHeader()](#encodeForHeader()) protected Encode the specified string using the current charset * ##### [encodeString()](#encodeString()) protected Translates a string for one charset to another if the App.encoding value differs and the mb\_convert\_encoding function exists * ##### [formatAddress()](#formatAddress()) protected Format addresses * ##### [generateMessage()](#generateMessage()) protected Generate full message. * ##### [getAttachments()](#getAttachments()) public Gets attachments to the email message. * ##### [getBcc()](#getBcc()) public Gets "bcc" address. * ##### [getBody()](#getBody()) public Get generated message body as array. * ##### [getBodyHtml()](#getBodyHtml()) public Get HTML body of message. * ##### [getBodyString()](#getBodyString()) public Get generated body as string. * ##### [getBodyText()](#getBodyText()) public Get text body of message. * ##### [getBodyTypes()](#getBodyTypes()) public Gets the body types that are in this email message * ##### [getCc()](#getCc()) public Gets "cc" address. * ##### [getCharset()](#getCharset()) public Charset getter. * ##### [getContentTransferEncoding()](#getContentTransferEncoding()) public Return the Content-Transfer Encoding value based on the set transferEncoding or set charset. * ##### [getContentTypeCharset()](#getContentTypeCharset()) public Return charset value for Content-Type. * ##### [getDomain()](#getDomain()) public Gets domain. * ##### [getEmailFormat()](#getEmailFormat()) public Gets email format. * ##### [getEmailPattern()](#getEmailPattern()) public EmailPattern setter/getter * ##### [getFrom()](#getFrom()) public Gets "from" address. * ##### [getHeaderCharset()](#getHeaderCharset()) public HeaderCharset getter. * ##### [getHeaders()](#getHeaders()) public Get list of headers * ##### [getHeadersString()](#getHeadersString()) public Get headers as string. * ##### [getMessageId()](#getMessageId()) public Gets message ID. * ##### [getOriginalSubject()](#getOriginalSubject()) public Get original subject without encoding * ##### [getPriority()](#getPriority()) public Gets priority. * ##### [getReadReceipt()](#getReadReceipt()) public Gets Read Receipt (Disposition-Notification-To header). * ##### [getReplyTo()](#getReplyTo()) public Gets "Reply-To" address. * ##### [getReturnPath()](#getReturnPath()) public Gets return path. * ##### [getSender()](#getSender()) public Gets the "sender" address. See RFC link below for full explanation. * ##### [getSubject()](#getSubject()) public Gets subject. * ##### [getTo()](#getTo()) public Gets "to" address * ##### [getTransferEncoding()](#getTransferEncoding()) public TransferEncoding getter. * ##### [jsonSerialize()](#jsonSerialize()) public Serializes the email object to a value that can be natively serialized and re-used to clone this email instance. * ##### [readFile()](#readFile()) protected Read the file contents and return a base64 version of the file contents. * ##### [reset()](#reset()) public Reset all the internal variables to be able to send out a new email. * ##### [serialize()](#serialize()) public Serializes the Email object. * ##### [setAttachments()](#setAttachments()) public Add attachments to the email message * ##### [setBcc()](#setBcc()) public Sets "bcc" address. * ##### [setBody()](#setBody()) public Set message body. * ##### [setBodyHtml()](#setBodyHtml()) public Set HTML body for message. * ##### [setBodyText()](#setBodyText()) public Set text body for message. * ##### [setCc()](#setCc()) public Sets "cc" address. * ##### [setCharset()](#setCharset()) public Charset setter. * ##### [setConfig()](#setConfig()) public Sets the configuration for this instance. * ##### [setDomain()](#setDomain()) public Sets domain. * ##### [setEmail()](#setEmail()) protected Set email * ##### [setEmailFormat()](#setEmailFormat()) public Sets email format. * ##### [setEmailPattern()](#setEmailPattern()) public EmailPattern setter/getter * ##### [setEmailSingle()](#setEmailSingle()) protected Set only 1 email * ##### [setFrom()](#setFrom()) public Sets "from" address. * ##### [setHeaderCharset()](#setHeaderCharset()) public HeaderCharset setter. * ##### [setHeaders()](#setHeaders()) public Sets headers for the message * ##### [setMessageId()](#setMessageId()) public Sets message ID. * ##### [setPriority()](#setPriority()) public Sets priority. * ##### [setReadReceipt()](#setReadReceipt()) public Sets Read Receipt (Disposition-Notification-To header). * ##### [setReplyTo()](#setReplyTo()) public Sets "Reply-To" address. * ##### [setReturnPath()](#setReturnPath()) public Sets return path. * ##### [setSender()](#setSender()) public Sets the "sender" address. See RFC link below for full explanation. * ##### [setSubject()](#setSubject()) public Sets subject. * ##### [setTo()](#setTo()) public Sets "to" address. * ##### [setTransferEncoding()](#setTransferEncoding()) public TransferEncoding setter. * ##### [unserialize()](#unserialize()) public Unserializes the Message object. * ##### [validateEmail()](#validateEmail()) protected Validate email address * ##### [wrap()](#wrap()) protected Wrap the message to follow the RFC 2822 - 2.1.1 Method Detail ------------- ### \_\_construct() public ``` __construct(array<string, mixed>|null $config = null) ``` Constructor #### Parameters `array<string, mixed>|null` $config optional Array of configs, or string to load configs from app.php ### \_\_serialize() public ``` __serialize(): array ``` Magic method used for serializing the Message object. #### Returns `array` ### \_\_unserialize() public ``` __unserialize(array $data): void ``` Magic method used to rebuild the Message object. #### Parameters `array` $data Data array. #### Returns `void` ### addAttachments() public ``` addAttachments(array $attachments): $this ``` Add attachments #### Parameters `array` $attachments Array of filenames. #### Returns `$this` #### Throws `InvalidArgumentException` #### See Also \Cake\Mailer\Email::setAttachments() ### addBcc() public ``` addBcc(array|string $email, string|null $name = null): $this ``` Add "bcc" address. #### Parameters `array|string` $email String with email, Array with email as key, name as value or email as value (without name) `string|null` $name optional Name #### Returns `$this` ### addCc() public ``` addCc(array|string $email, string|null $name = null): $this ``` Add "cc" address. #### Parameters `array|string` $email String with email, Array with email as key, name as value or email as value (without name) `string|null` $name optional Name #### Returns `$this` ### addEmail() protected ``` addEmail(string $varName, array|string $email, string|null $name): $this ``` Add email #### Parameters `string` $varName Property name `array|string` $email String with email, Array with email as key, name as value or email as value (without name) `string|null` $name Name #### Returns `$this` #### Throws `InvalidArgumentException` ### addHeaders() public ``` addHeaders(array $headers): $this ``` Add header for the message #### Parameters `array` $headers Headers to set. #### Returns `$this` ### addReplyTo() public ``` addReplyTo(array|string $email, string|null $name = null): $this ``` Add "Reply-To" address. #### Parameters `array|string` $email String with email, Array with email as key, name as value or email as value (without name) `string|null` $name optional Name #### Returns `$this` ### addTo() public ``` addTo(array|string $email, string|null $name = null): $this ``` Add "To" address. #### Parameters `array|string` $email String with email, Array with email as key, name as value or email as value (without name) `string|null` $name optional Name #### Returns `$this` ### attachFiles() protected ``` attachFiles(string|null $boundary = null): array<string> ``` Attach non-embedded files by adding file contents inside boundaries. #### Parameters `string|null` $boundary optional Boundary to use. If null, will default to $this->boundary #### Returns `array<string>` ### attachInlineFiles() protected ``` attachInlineFiles(string|null $boundary = null): array<string> ``` Attach inline/embedded files to the message. #### Parameters `string|null` $boundary optional Boundary to use. If null, will default to $this->boundary #### Returns `array<string>` ### createBoundary() protected ``` createBoundary(): void ``` Create unique boundary identifier #### Returns `void` ### createFromArray() public ``` createFromArray(array<string, mixed> $config): $this ``` Configures an email instance object from serialized config. #### Parameters `array<string, mixed>` $config Email configuration array. #### Returns `$this` ### decodeForHeader() protected ``` decodeForHeader(string $text): string ``` Decode the specified string #### Parameters `string` $text String to decode #### Returns `string` ### encodeForHeader() protected ``` encodeForHeader(string $text): string ``` Encode the specified string using the current charset #### Parameters `string` $text String to encode #### Returns `string` ### encodeString() protected ``` encodeString(string $text, string $charset): string ``` Translates a string for one charset to another if the App.encoding value differs and the mb\_convert\_encoding function exists #### Parameters `string` $text The text to be converted `string` $charset the target encoding #### Returns `string` ### formatAddress() protected ``` formatAddress(array $address): array ``` Format addresses If the address contains non alphanumeric/whitespace characters, it will be quoted as characters like `:` and `,` are known to cause issues in address header fields. #### Parameters `array` $address Addresses to format. #### Returns `array` ### generateMessage() protected ``` generateMessage(): array<string> ``` Generate full message. #### Returns `array<string>` ### getAttachments() public ``` getAttachments(): array<string, array> ``` Gets attachments to the email message. #### Returns `array<string, array>` ### getBcc() public ``` getBcc(): array ``` Gets "bcc" address. #### Returns `array` ### getBody() public ``` getBody(): array ``` Get generated message body as array. #### Returns `array` ### getBodyHtml() public ``` getBodyHtml(): string ``` Get HTML body of message. #### Returns `string` ### getBodyString() public ``` getBodyString(string $eol = "\r\n"): string ``` Get generated body as string. #### Parameters `string` $eol optional End of line string for imploding. #### Returns `string` #### See Also Message::getBody() ### getBodyText() public ``` getBodyText(): string ``` Get text body of message. #### Returns `string` ### getBodyTypes() public ``` getBodyTypes(): array ``` Gets the body types that are in this email message #### Returns `array` ### getCc() public ``` getCc(): array ``` Gets "cc" address. #### Returns `array` ### getCharset() public ``` getCharset(): string ``` Charset getter. #### Returns `string` ### getContentTransferEncoding() public ``` getContentTransferEncoding(): string ``` Return the Content-Transfer Encoding value based on the set transferEncoding or set charset. #### Returns `string` ### getContentTypeCharset() public ``` getContentTypeCharset(): string ``` Return charset value for Content-Type. Checks fallback/compatibility types which include workarounds for legacy japanese character sets. #### Returns `string` ### getDomain() public ``` getDomain(): string ``` Gets domain. #### Returns `string` ### getEmailFormat() public ``` getEmailFormat(): string ``` Gets email format. #### Returns `string` ### getEmailPattern() public ``` getEmailPattern(): string|null ``` EmailPattern setter/getter #### Returns `string|null` ### getFrom() public ``` getFrom(): array ``` Gets "from" address. #### Returns `array` ### getHeaderCharset() public ``` getHeaderCharset(): string ``` HeaderCharset getter. #### Returns `string` ### getHeaders() public ``` getHeaders(array<string> $include = []): array<string> ``` Get list of headers ### Includes: * `from` * `replyTo` * `readReceipt` * `returnPath` * `to` * `cc` * `bcc` * `subject` #### Parameters `array<string>` $include optional List of headers. #### Returns `array<string>` ### getHeadersString() public ``` getHeadersString(array<string> $include = [], string $eol = "\r\n", Closure|null $callback = null): string ``` Get headers as string. #### Parameters `array<string>` $include optional List of headers. `string` $eol optional End of line string for concatenating headers. `Closure|null` $callback optional Callback to run each header value through before stringifying. #### Returns `string` #### See Also Message::getHeaders() ### getMessageId() public ``` getMessageId(): string|bool ``` Gets message ID. #### Returns `string|bool` ### getOriginalSubject() public ``` getOriginalSubject(): string ``` Get original subject without encoding #### Returns `string` ### getPriority() public ``` getPriority(): int|null ``` Gets priority. #### Returns `int|null` ### getReadReceipt() public ``` getReadReceipt(): array ``` Gets Read Receipt (Disposition-Notification-To header). #### Returns `array` ### getReplyTo() public ``` getReplyTo(): array ``` Gets "Reply-To" address. #### Returns `array` ### getReturnPath() public ``` getReturnPath(): array ``` Gets return path. #### Returns `array` ### getSender() public ``` getSender(): array ``` Gets the "sender" address. See RFC link below for full explanation. #### Returns `array` #### Links https://tools.ietf.org/html/rfc2822.html#section-3.6.2 ### getSubject() public ``` getSubject(): string ``` Gets subject. #### Returns `string` ### getTo() public ``` getTo(): array ``` Gets "to" address #### Returns `array` ### getTransferEncoding() public ``` getTransferEncoding(): string|null ``` TransferEncoding getter. #### Returns `string|null` ### jsonSerialize() public ``` jsonSerialize(): array ``` Serializes the email object to a value that can be natively serialized and re-used to clone this email instance. #### Returns `array` #### Throws `Exception` When a view var object can not be properly serialized. ### readFile() protected ``` readFile(Psr\Http\Message\UploadedFileInterface|string $file): string ``` Read the file contents and return a base64 version of the file contents. #### Parameters `Psr\Http\Message\UploadedFileInterface|string` $file The absolute path to the file to read or UploadedFileInterface instance. #### Returns `string` ### reset() public ``` reset(): $this ``` Reset all the internal variables to be able to send out a new email. #### Returns `$this` ### serialize() public ``` serialize(): string ``` Serializes the Email object. #### Returns `string` ### setAttachments() public ``` setAttachments(array $attachments): $this ``` Add attachments to the email message Attachments can be defined in a few forms depending on how much control you need: Attach a single file: ``` $this->setAttachments('path/to/file'); ``` Attach a file with a different filename: ``` $this->setAttachments(['custom_name.txt' => 'path/to/file.txt']); ``` Attach a file and specify additional properties: ``` $this->setAttachments(['custom_name.png' => [ 'file' => 'path/to/file', 'mimetype' => 'image/png', 'contentId' => 'abc123', 'contentDisposition' => false ] ]); ``` Attach a file from string and specify additional properties: ``` $this->setAttachments(['custom_name.png' => [ 'data' => file_get_contents('path/to/file'), 'mimetype' => 'image/png' ] ]); ``` The `contentId` key allows you to specify an inline attachment. In your email text, you can use `<img src="cid:abc123"/>` to display the image inline. The `contentDisposition` key allows you to disable the `Content-Disposition` header, this can improve attachment compatibility with outlook email clients. #### Parameters `array` $attachments Array of filenames. #### Returns `$this` #### Throws `InvalidArgumentException` ### setBcc() public ``` setBcc(array|string $email, string|null $name = null): $this ``` Sets "bcc" address. #### Parameters `array|string` $email String with email, Array with email as key, name as value or email as value (without name) `string|null` $name optional Name #### Returns `$this` ### setBody() public ``` setBody(array<string, string> $content): $this ``` Set message body. #### Parameters `array<string, string>` $content Content array with keys "text" and/or "html" with content string of respective type. #### Returns `$this` ### setBodyHtml() public ``` setBodyHtml(string $content): $this ``` Set HTML body for message. #### Parameters `string` $content Content string #### Returns `$this` ### setBodyText() public ``` setBodyText(string $content): $this ``` Set text body for message. #### Parameters `string` $content Content string #### Returns `$this` ### setCc() public ``` setCc(array|string $email, string|null $name = null): $this ``` Sets "cc" address. #### Parameters `array|string` $email String with email, Array with email as key, name as value or email as value (without name) `string|null` $name optional Name #### Returns `$this` ### setCharset() public ``` setCharset(string $charset): $this ``` Charset setter. #### Parameters `string` $charset Character set. #### Returns `$this` ### setConfig() public ``` setConfig(array<string, mixed> $config): $this ``` Sets the configuration for this instance. #### Parameters `array<string, mixed>` $config Config array. #### Returns `$this` ### setDomain() public ``` setDomain(string $domain): $this ``` Sets domain. Domain as top level (the part after @). #### Parameters `string` $domain Manually set the domain for CLI mailing. #### Returns `$this` ### setEmail() protected ``` setEmail(string $varName, array|string $email, string|null $name): $this ``` Set email #### Parameters `string` $varName Property name `array|string` $email String with email, Array with email as key, name as value or email as value (without name) `string|null` $name Name #### Returns `$this` #### Throws `InvalidArgumentException` ### setEmailFormat() public ``` setEmailFormat(string $format): $this ``` Sets email format. #### Parameters `string` $format Formatting string. #### Returns `$this` #### Throws `InvalidArgumentException` ### setEmailPattern() public ``` setEmailPattern(string|null $regex): $this ``` EmailPattern setter/getter #### Parameters `string|null` $regex The pattern to use for email address validation, null to unset the pattern and make use of filter\_var() instead. #### Returns `$this` ### setEmailSingle() protected ``` setEmailSingle(string $varName, array|string $email, string|null $name, string $throwMessage): $this ``` Set only 1 email #### Parameters `string` $varName Property name `array|string` $email String with email, Array with email as key, name as value or email as value (without name) `string|null` $name Name `string` $throwMessage Exception message #### Returns `$this` #### Throws `InvalidArgumentException` ### setFrom() public ``` setFrom(array|string $email, string|null $name = null): $this ``` Sets "from" address. #### Parameters `array|string` $email String with email, Array with email as key, name as value or email as value (without name) `string|null` $name optional Name #### Returns `$this` #### Throws `InvalidArgumentException` ### setHeaderCharset() public ``` setHeaderCharset(string|null $charset): $this ``` HeaderCharset setter. #### Parameters `string|null` $charset Character set. #### Returns `$this` ### setHeaders() public ``` setHeaders(array $headers): $this ``` Sets headers for the message #### Parameters `array` $headers Associative array containing headers to be set. #### Returns `$this` ### setMessageId() public ``` setMessageId(string|bool $message): $this ``` Sets message ID. #### Parameters `string|bool` $message True to generate a new Message-ID, False to ignore (not send in email), String to set as Message-ID. #### Returns `$this` #### Throws `InvalidArgumentException` ### setPriority() public ``` setPriority(int|null $priority): $this ``` Sets priority. #### Parameters `int|null` $priority 1 (highest) to 5 (lowest) #### Returns `$this` ### setReadReceipt() public ``` setReadReceipt(array|string $email, string|null $name = null): $this ``` Sets Read Receipt (Disposition-Notification-To header). #### Parameters `array|string` $email String with email, Array with email as key, name as value or email as value (without name) `string|null` $name optional Name #### Returns `$this` #### Throws `InvalidArgumentException` ### setReplyTo() public ``` setReplyTo(array|string $email, string|null $name = null): $this ``` Sets "Reply-To" address. #### Parameters `array|string` $email String with email, Array with email as key, name as value or email as value (without name) `string|null` $name optional Name #### Returns `$this` #### Throws `InvalidArgumentException` ### setReturnPath() public ``` setReturnPath(array|string $email, string|null $name = null): $this ``` Sets return path. #### Parameters `array|string` $email String with email, Array with email as key, name as value or email as value (without name) `string|null` $name optional Name #### Returns `$this` #### Throws `InvalidArgumentException` ### setSender() public ``` setSender(array|string $email, string|null $name = null): $this ``` Sets the "sender" address. See RFC link below for full explanation. #### Parameters `array|string` $email String with email, Array with email as key, name as value or email as value (without name) `string|null` $name optional Name #### Returns `$this` #### Throws `InvalidArgumentException` #### Links https://tools.ietf.org/html/rfc2822.html#section-3.6.2 ### setSubject() public ``` setSubject(string $subject): $this ``` Sets subject. #### Parameters `string` $subject Subject string. #### Returns `$this` ### setTo() public ``` setTo(array|string $email, string|null $name = null): $this ``` Sets "to" address. #### Parameters `array|string` $email String with email, Array with email as key, name as value or email as value (without name) `string|null` $name optional Name #### Returns `$this` ### setTransferEncoding() public ``` setTransferEncoding(string|null $encoding): $this ``` TransferEncoding setter. #### Parameters `string|null` $encoding Encoding set. #### Returns `$this` #### Throws `InvalidArgumentException` ### unserialize() public ``` unserialize(string $data): void ``` Unserializes the Message object. #### Parameters `string` $data Serialized string. #### Returns `void` ### validateEmail() protected ``` validateEmail(string $email, string $context): void ``` Validate email address #### Parameters `string` $email Email address to validate `string` $context Which property was set #### Returns `void` #### Throws `InvalidArgumentException` If email address does not validate ### wrap() protected ``` wrap(string|null $message = null, int $wrapLength = self::LINE_LENGTH_MUST): array<string> ``` Wrap the message to follow the RFC 2822 - 2.1.1 #### Parameters `string|null` $message optional Message to wrap `int` $wrapLength optional The line length #### Returns `array<string>` Property Detail --------------- ### $appCharset protected The application wide charset, used to encode headers and body #### Type `string|null` ### $attachments protected List of files that should be attached to the email. Only absolute paths #### Type `array<string, array>` ### $bcc protected Blind Carbon Copy List of email's that should receive a copy of the email. The Recipient WILL NOT be able to see this list #### Type `array` ### $boundary protected If set, boundary to use for multipart mime messages #### Type `string|null` ### $cc protected Carbon Copy List of email's that should receive a copy of the email. The Recipient WILL be able to see this list #### Type `array` ### $charset protected Charset the email body is sent in #### Type `string` ### $charset8bit protected 8Bit character sets #### Type `array<string>` ### $contentTypeCharset protected Define Content-Type charset name #### Type `array<string, string>` ### $domain protected Domain for messageId generation. Needs to be manually set for CLI mailing as env('HTTP\_HOST') is empty #### Type `string` ### $emailFormat protected What format should the email be sent in #### Type `string` ### $emailFormatAvailable protected Available formats to be sent. #### Type `array<string>` ### $emailPattern protected Regex for email validation If null, filter\_var() will be used. Use the emailPattern() method to set a custom pattern.' #### Type `string|null` ### $from protected The mail which the email is sent from #### Type `array` ### $headerCharset protected Charset the email header is sent in If null, the $charset property will be used as default #### Type `string|null` ### $headers protected Associative array of a user defined headers Keys will be prefixed 'X-' as per RFC2822 Section 4.7.5 #### Type `array` ### $htmlMessage protected Html message #### Type `string` ### $message protected Final message to send #### Type `array` ### $messageId protected Message ID #### Type `string|bool` ### $priority protected Contains the optional priority of the email. #### Type `int|null` ### $readReceipt protected The read receipt email #### Type `array` ### $replyTo protected List of email(s) that the recipient will reply to #### Type `array` ### $returnPath protected The mail that will be used in case of any errors like * Remote mailserver down * Remote user has exceeded his quota * Unknown user #### Type `array` ### $sender protected The sender email #### Type `array` ### $subject protected The subject of the email #### Type `string` ### $textMessage protected Text message #### Type `string` ### $to protected Recipient of the email #### Type `array` ### $transferEncoding protected The email transfer encoding used. If null, the $charset property is used for determined the transfer encoding. #### Type `string|null` ### $transferEncodingAvailable protected Available encoding to be set for transfer. #### Type `array<string>`
programming_docs
cakephp Class MoFileParser Class MoFileParser =================== Parses file in MO format **Namespace:** [Cake\I18n\Parser](namespace-cake.i18n.parser) Constants --------- * `int` **MO\_BIG\_ENDIAN\_MAGIC** ``` 0xde120495 ``` Magic used for validating the format of a MO file as well as detecting if the machine used to create that file was big endian. * `int` **MO\_HEADER\_SIZE** ``` 28 ``` The size of the header of a MO file in bytes. * `int` **MO\_LITTLE\_ENDIAN\_MAGIC** ``` 0x950412de ``` Magic used for validating the format of a MO file as well as detecting if the machine used to create that file was little endian. Method Summary -------------- * ##### [\_readLong()](#_readLong()) protected Reads an unsigned long from stream respecting endianess. * ##### [parse()](#parse()) public Parses machine object (MO) format, independent of the machine's endian it was created on. Both 32bit and 64bit systems are supported. Method Detail ------------- ### \_readLong() protected ``` _readLong(resource $stream, bool $isBigEndian): int ``` Reads an unsigned long from stream respecting endianess. #### Parameters `resource` $stream The File being read. `bool` $isBigEndian Whether the current platform is Big Endian #### Returns `int` ### parse() public ``` parse(string $file): array ``` Parses machine object (MO) format, independent of the machine's endian it was created on. Both 32bit and 64bit systems are supported. #### Parameters `string` $file The file to be parsed. #### Returns `array` #### Throws `RuntimeException` If stream content has an invalid format. cakephp Class QueryLogger Class 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 **Namespace:** [Cake\Database\Log](namespace-cake.database.log) 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 Constructor. * ##### [\_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 = []) ``` Constructor. #### 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 = []): void ``` Logs with an arbitrary level. #### Parameters `mixed` $level `string` $message `mixed[]` $context optional #### Returns `void` ### 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` cakephp Class PluginShortRoute Class PluginShortRoute ======================= Plugin short route, that copies the plugin param to the controller parameters It is used for supporting /{plugin} routes. **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 Reverses route plugin shortcut URLs. If the plugin and controller are not the same the match is an auto fail. * ##### [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 a plugin key is found, it will be copied to the controller parameter. * ##### [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 ``` Reverses route plugin shortcut URLs. If the plugin and controller are not the same the match is an auto fail. 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 a plugin key is found, it will be copied to the controller parameter. 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 #### 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`
programming_docs
cakephp Class AssociationCollection Class AssociationCollection ============================ A container/collection for association classes. Contains methods for managing associations, and ordering operations around saving and deleting. **Namespace:** [Cake\ORM](namespace-cake.orm) Property Summary ---------------- * [$\_items](#%24_items) protected `arrayCake\ORM\Association>` Stored associations * [$\_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. * ##### [\_normalizeAssociations()](#_normalizeAssociations()) protected Returns an array out of the original passed associations list where dot notation is transformed into nested arrays so that they can be parsed by other routines * ##### [\_save()](#_save()) protected Helper method for saving an association's data. * ##### [\_saveAssociations()](#_saveAssociations()) protected Helper method for saving an association's data. * ##### [add()](#add()) public Add an association to the collection * ##### [cascadeDelete()](#cascadeDelete()) public Cascade a delete across the various associations. Cascade first across associations for which cascadeCallbacks is true. * ##### [fetchTable()](#fetchTable()) public Convenience method to get a table instance. * ##### [get()](#get()) public Fetch an attached association by name. * ##### [getByProperty()](#getByProperty()) public Fetch an association by property name. * ##### [getByType()](#getByType()) public Get an array of associations matching a specific type. * ##### [getIterator()](#getIterator()) public Allow looping through the associations * ##### [getTableLocator()](#getTableLocator()) public Gets the table locator. * ##### [has()](#has()) public Check for an attached association by name. * ##### [keys()](#keys()) public Get the names of all the associations in the collection. * ##### [load()](#load()) public Creates and adds the Association object to this collection. * ##### [normalizeKeys()](#normalizeKeys()) public Returns an associative array of association names out a mixed array. If true is passed, then it returns all association names in this collection. * ##### [remove()](#remove()) public Drop/remove an association. * ##### [removeAll()](#removeAll()) public Remove all registered associations. * ##### [saveChildren()](#saveChildren()) public Save all the associations that are children of the given entity. * ##### [saveParents()](#saveParents()) public Save all the associations that are parents of the given entity. * ##### [setTableLocator()](#setTableLocator()) public Sets the table locator. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\ORM\Locator\LocatorInterface|null $tableLocator = null) ``` Constructor. Sets the default table locator for associations. If no locator is provided, the global one will be used. #### Parameters `Cake\ORM\Locator\LocatorInterface|null` $tableLocator optional Table locator instance. ### \_normalizeAssociations() protected ``` _normalizeAssociations(array|string $associations): array ``` Returns an array out of the original passed associations list where dot notation is transformed into nested arrays so that they can be parsed by other routines #### Parameters `array|string` $associations The array of included associations. #### Returns `array` ### \_save() protected ``` _save(Cake\ORM\Association $association, Cake\Datasource\EntityInterface $entity, array<string, mixed> $nested, array<string, mixed> $options): bool ``` Helper method for saving an association's data. #### Parameters `Cake\ORM\Association` $association The association object to save with. `Cake\Datasource\EntityInterface` $entity The entity to save `array<string, mixed>` $nested Options for deeper associations `array<string, mixed>` $options Original options #### Returns `bool` ### \_saveAssociations() protected ``` _saveAssociations(Cake\ORM\Table $table, Cake\Datasource\EntityInterface $entity, array $associations, array<string, mixed> $options, bool $owningSide): bool ``` Helper method for saving an association's data. #### Parameters `Cake\ORM\Table` $table The table the save is currently operating on `Cake\Datasource\EntityInterface` $entity The entity to save `array` $associations Array of associations to save. `array<string, mixed>` $options Original options `bool` $owningSide Compared with association classes' isOwningSide method. #### Returns `bool` #### Throws `InvalidArgumentException` When an unknown alias is used. ### add() public ``` add(string $alias, Cake\ORM\Association $association): Cake\ORM\Association ``` Add an association to the collection If the alias added contains a `.` the part preceding the `.` will be dropped. This makes using plugins simpler as the Plugin.Class syntax is frequently used. #### Parameters `string` $alias The association alias `Cake\ORM\Association` $association The association to add. #### Returns `Cake\ORM\Association` ### cascadeDelete() public ``` cascadeDelete(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options): bool ``` Cascade a delete across the various associations. Cascade first across associations for which cascadeCallbacks is true. #### Parameters `Cake\Datasource\EntityInterface` $entity The entity to delete associations for. `array<string, mixed>` $options The options used in the delete operation. #### 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() ### get() public ``` get(string $alias): Cake\ORM\Association|null ``` Fetch an attached association by name. #### Parameters `string` $alias The association alias to get. #### Returns `Cake\ORM\Association|null` ### getByProperty() public ``` getByProperty(string $prop): Cake\ORM\Association|null ``` Fetch an association by property name. #### Parameters `string` $prop The property to find an association by. #### Returns `Cake\ORM\Association|null` ### getByType() public ``` getByType(array<string>|string $class): arrayCake\ORM\Association> ``` Get an array of associations matching a specific type. #### Parameters `array<string>|string` $class The type of associations you want. For example 'BelongsTo' or array like ['BelongsTo', 'HasOne'] #### Returns `arrayCake\ORM\Association>` ### getIterator() public ``` getIterator(): Traversable<string,Cake\ORM\Association> ``` Allow looping through the associations #### Returns `Traversable<string,Cake\ORM\Association>` ### getTableLocator() public ``` getTableLocator(): Cake\ORM\Locator\LocatorInterface ``` Gets the table locator. #### Returns `Cake\ORM\Locator\LocatorInterface` ### has() public ``` has(string $alias): bool ``` Check for an attached association by name. #### Parameters `string` $alias The association alias to get. #### Returns `bool` ### keys() public ``` keys(): array<string> ``` Get the names of all the associations in the collection. #### Returns `array<string>` ### load() public ``` load(string $className, string $associated, array<string, mixed> $options = []): Cake\ORM\Association ``` Creates and adds the Association object to this collection. #### Parameters `string` $className The name of association class. `string` $associated The alias for the target table. `array<string, mixed>` $options optional List of options to configure the association definition. #### Returns `Cake\ORM\Association` #### Throws `InvalidArgumentException` ### normalizeKeys() public ``` normalizeKeys(array|bool $keys): array ``` Returns an associative array of association names out a mixed array. If true is passed, then it returns all association names in this collection. #### Parameters `array|bool` $keys the list of association names to normalize #### Returns `array` ### remove() public ``` remove(string $alias): void ``` Drop/remove an association. Once removed the association will no longer be reachable #### Parameters `string` $alias The alias name. #### Returns `void` ### removeAll() public ``` removeAll(): void ``` Remove all registered associations. Once removed associations will no longer be reachable #### Returns `void` ### saveChildren() public ``` saveChildren(Cake\ORM\Table $table, Cake\Datasource\EntityInterface $entity, array $associations, array<string, mixed> $options): bool ``` Save all the associations that are children of the given entity. Child associations include any association where the given table is not the owning side. #### Parameters `Cake\ORM\Table` $table The table entity is for. `Cake\Datasource\EntityInterface` $entity The entity to save associated data for. `array` $associations The list of associations to save children from. associations not in this list will not be saved. `array<string, mixed>` $options The options for the save operation. #### Returns `bool` ### saveParents() public ``` saveParents(Cake\ORM\Table $table, Cake\Datasource\EntityInterface $entity, array $associations, array<string, mixed> $options = []): bool ``` Save all the associations that are parents of the given entity. Parent associations include any association where the given table is the owning side. #### Parameters `Cake\ORM\Table` $table The table entity is for. `Cake\Datasource\EntityInterface` $entity The entity to save associated data for. `array` $associations The list of associations to save parents from. associations not in this list will not be saved. `array<string, mixed>` $options optional The options for the save operation. #### Returns `bool` ### 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 --------------- ### $\_items protected Stored associations #### Type `arrayCake\ORM\Association>` ### $\_tableLocator protected Table locator instance #### Type `Cake\ORM\Locator\LocatorInterface|null` ### $defaultTable protected This object's default table alias. #### Type `string|null` cakephp Class CheckHttpCacheComponent Class CheckHttpCacheComponent ============================== Use HTTP caching headers to see if rendering can be skipped. Checks if the response can be considered different according to the request headers, and caching headers in the response. If the response was not modified, then the controller and view render process is skipped. And the client will get a response with an empty body and a "304 Not Modified" header. To use this component your controller actions must set either the `Last-Modified` or `Etag` header. Without one of these headers being set this component will have no effect. **Namespace:** [Cake\Controller\Component](namespace-cake.controller.component) 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 * [$\_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 -------------- * ##### [\_\_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. * ##### [beforeRender()](#beforeRender()) public Before Render hook * ##### [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. * ##### [getController()](#getController()) public Get the controller this component is bound to. * ##### [implementedEvents()](#implementedEvents()) public Get the Controller callbacks this Component is interested in. * ##### [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. * ##### [setConfig()](#setConfig()) public Sets the config. 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): 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 ### beforeRender() public ``` beforeRender(Cake\Event\EventInterface $event): void ``` Before Render hook #### Parameters `Cake\Event\EventInterface` $event The Controller.beforeRender event. #### 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` ### getController() public ``` getController(): Cake\Controller\Controller ``` Get the controller this component is bound to. #### Returns `Cake\Controller\Controller` ### implementedEvents() public ``` implementedEvents(): array<string, mixed> ``` Get the Controller callbacks this Component is interested in. 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` ### 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 --------------- ### $\_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>` ### $\_registry protected Component registry class used to lazy load components. #### Type `Cake\Controller\ComponentRegistry` ### $components protected Other Components this component uses. #### Type `array`
programming_docs
cakephp Namespace Engine Namespace Engine ================ ### Classes * ##### [ApcuEngine](class-cake.cache.engine.apcuengine) APCu storage engine for cache * ##### [ArrayEngine](class-cake.cache.engine.arrayengine) Array storage engine for cache. * ##### [FileEngine](class-cake.cache.engine.fileengine) File Storage engine for cache. Filestorage is the slowest cache storage to read and write. However, it is good for servers that don't have other storage engine available, or have content which is not performance sensitive. * ##### [MemcachedEngine](class-cake.cache.engine.memcachedengine) Memcached storage engine for cache. Memcached has some limitations in the amount of control you have over expire times far in the future. See MemcachedEngine::write() for more information. * ##### [NullEngine](class-cake.cache.engine.nullengine) Null cache engine, all operations appear to work, but do nothing. * ##### [RedisEngine](class-cake.cache.engine.redisengine) Redis storage engine for cache. * ##### [WincacheEngine](class-cake.cache.engine.wincacheengine) Wincache storage engine for cache cakephp Class Security Class Security =============== Security Library contains utility methods related to security **Namespace:** [Cake\Utility](namespace-cake.utility) Property Summary ---------------- * [$\_instance](#%24_instance) protected static `object|null` The crypto implementation to use. * [$\_salt](#%24_salt) protected static `string|null` The HMAC salt to use for encryption and decryption routines * [$hashType](#%24hashType) public static `string` Default hash method. If `$type` param for `Security::hash()` is not specified this value is used. Defaults to 'sha1'. Method Summary -------------- * ##### [\_checkKey()](#_checkKey()) protected static Check the encryption key for proper length. * ##### [constantEquals()](#constantEquals()) public static A timing attack resistant comparison that prefers native PHP implementations. * ##### [decrypt()](#decrypt()) public static Decrypt a value using AES-256. * ##### [encrypt()](#encrypt()) public static Encrypt a value using AES-256. * ##### [engine()](#engine()) public static Get the crypto implementation based on the loaded extensions. * ##### [getSalt()](#getSalt()) public static Gets the HMAC salt to be used for encryption/decryption routines. * ##### [hash()](#hash()) public static Create a hash from string using given method. * ##### [insecureRandomBytes()](#insecureRandomBytes()) public static Like randomBytes() above, but not cryptographically secure. * ##### [randomBytes()](#randomBytes()) public static Get random bytes from a secure source. * ##### [randomString()](#randomString()) public static Creates a secure random string. * ##### [setHash()](#setHash()) public static Sets the default hash method for the Security object. This affects all objects using Security::hash(). * ##### [setSalt()](#setSalt()) public static Sets the HMAC salt to be used for encryption/decryption routines. Method Detail ------------- ### \_checkKey() protected static ``` _checkKey(string $key, string $method): void ``` Check the encryption key for proper length. #### Parameters `string` $key Key to check. `string` $method The method the key is being checked for. #### Returns `void` #### Throws `InvalidArgumentException` When key length is not 256 bit/32 bytes ### constantEquals() public static ``` constantEquals(mixed $original, mixed $compare): bool ``` A timing attack resistant comparison that prefers native PHP implementations. #### Parameters `mixed` $original The original value. `mixed` $compare The comparison value. #### Returns `bool` ### decrypt() public static ``` decrypt(string $cipher, string $key, string|null $hmacSalt = null): string|null ``` 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. `string|null` $hmacSalt optional The salt to use for the HMAC process. Leave null to use value of Security::getSalt(). #### Returns `string|null` #### Throws `InvalidArgumentException` On invalid data or key. ### encrypt() public static ``` encrypt(string $plain, string $key, string|null $hmacSalt = null): 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. `string|null` $hmacSalt optional The salt to use for the HMAC process. Leave null to use value of Security::getSalt(). #### Returns `string` #### Throws `InvalidArgumentException` On invalid data or key. ### engine() public static ``` engine(Cake\Utility\Crypto\OpenSsl|null $instance = null): Cake\Utility\Crypto\OpenSsl ``` Get the crypto implementation based on the loaded extensions. You can use this method to forcibly decide between openssl/custom implementations. #### Parameters `Cake\Utility\Crypto\OpenSsl|null` $instance optional The crypto instance to use. #### Returns `Cake\Utility\Crypto\OpenSsl` #### Throws `InvalidArgumentException` When no compatible crypto extension is available. ### getSalt() public static ``` getSalt(): string ``` Gets the HMAC salt to be used for encryption/decryption routines. #### Returns `string` ### hash() public static ``` hash(string $string, string|null $algorithm = null, mixed $salt = false): string ``` Create a hash from string using given method. #### Parameters `string` $string String to hash `string|null` $algorithm optional Hashing algo to use (i.e. sha1, sha256 etc.). Can be any valid algo included in list returned by hash\_algos(). If no value is passed the type specified by `Security::$hashType` is used. `mixed` $salt optional If true, automatically prepends the value returned by Security::getSalt() to $string. #### Returns `string` #### Throws `RuntimeException` #### Links https://book.cakephp.org/4/en/core-libraries/security.html#hashing-data ### insecureRandomBytes() public static ``` insecureRandomBytes(int $length): string ``` Like randomBytes() above, but not cryptographically secure. #### Parameters `int` $length The number of bytes you want. #### Returns `string` #### See Also \Cake\Utility\Security::randomBytes() ### randomBytes() public static ``` randomBytes(int $length): string ``` Get random bytes from a secure source. This method will fall back to an insecure source an trigger a warning if it cannot find a secure source of random data. #### Parameters `int` $length The number of bytes you want. #### Returns `string` ### randomString() public static ``` randomString(int $length = 64): string ``` Creates a secure random string. #### Parameters `int` $length optional String length. Default 64. #### Returns `string` ### setHash() public static ``` setHash(string $hash): void ``` Sets the default hash method for the Security object. This affects all objects using Security::hash(). #### Parameters `string` $hash Method to use (sha1/sha256/md5 etc.) #### Returns `void` #### See Also \Cake\Utility\Security::hash() ### setSalt() public static ``` setSalt(string $salt): void ``` Sets the HMAC salt to be used for encryption/decryption routines. #### Parameters `string` $salt The salt to use for encryption routines. #### Returns `void` Property Detail --------------- ### $\_instance protected static The crypto implementation to use. #### Type `object|null` ### $\_salt protected static The HMAC salt to use for encryption and decryption routines #### Type `string|null` ### $hashType public static Default hash method. If `$type` param for `Security::hash()` is not specified this value is used. Defaults to 'sha1'. #### Type `string` cakephp Class DependentDeleteHelper Class DependentDeleteHelper ============================ Helper class for cascading deletes in associations. **Namespace:** [Cake\ORM\Association](namespace-cake.orm.association) Method Summary -------------- * ##### [cascadeDelete()](#cascadeDelete()) public Cascade a delete to remove dependent records. Method Detail ------------- ### cascadeDelete() public ``` cascadeDelete(Cake\ORM\Association $association, Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): bool ``` Cascade a delete to remove dependent records. This method does nothing if the association is not dependent. #### Parameters `Cake\ORM\Association` $association The association callbacks are being cascaded on. `Cake\Datasource\EntityInterface` $entity The entity that started the cascaded delete. `array<string, mixed>` $options optional The options for the original delete. #### Returns `bool` cakephp Class Mailer Class Mailer ============= Mailer base class. Mailer classes let you encapsulate related Email logic into a reusable and testable class. Defining Messages ----------------- Mailers make it easy for you to define methods that handle email formatting logic. For example: ``` class UserMailer extends Mailer { public function resetPassword($user) { $this ->setSubject('Reset Password') ->setTo($user->email) ->set(['token' => $user->token]); } } ``` Is a trivial example but shows how a mailer could be declared. Sending Messages ---------------- After you have defined some messages you will want to send them: ``` $mailer = new UserMailer(); $mailer->send('resetPassword', $user); ``` Event Listener -------------- Mailers can also subscribe to application event allowing you to decouple email delivery from your application code. By re-declaring the `implementedEvents()` method you can define event handlers that can convert events into email. For example, if your application had a user registration event: ``` public function implementedEvents(): array { return [ 'Model.afterSave' => 'onRegistration', ]; } public function onRegistration(EventInterface $event, EntityInterface $entity, ArrayObject $options) { if ($entity->isNew()) { $this->send('welcome', [$entity]); } } ``` The onRegistration method converts the application event into a mailer method. Our mailer could either be registered in the application bootstrap, or in the Table class' initialize() hook. **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>` Mailer driver class map. * [$\_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 * [$clonedInstances](#%24clonedInstances) protected `array<string, mixed>` Hold message, renderer and transport instance for restoring after running a mailer action. * [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias. * [$logConfig](#%24logConfig) protected `array|null` * [$message](#%24message) protected `Cake\Mailer\Message` Message instance. * [$messageClass](#%24messageClass) protected `string` Message class name. * [$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 static `string` Mailer's name. * [$renderer](#%24renderer) protected `Cake\Mailer\Renderer|null` Email Renderer * [$transport](#%24transport) protected `Cake\Mailer\AbstractTransport|null` The transport instance to use for sending mail. Method Summary -------------- * ##### [\_\_call()](#__call()) public Magic method to forward method class to Message instance. * ##### [\_\_construct()](#__construct()) public Constructor * ##### [\_setModelClass()](#_setModelClass()) protected Set the modelClass property based on conventions. * ##### [addAttachments()](#addAttachments()) public @method Add attachments. {@see \Cake\Mailer\Message::addAttachments()} * ##### [addBcc()](#addBcc()) public @method Add "bcc" address. {@see \Cake\Mailer\Message::addBcc()} * ##### [addCc()](#addCc()) public @method Add "cc" address. {@see \Cake\Mailer\Message::addCc()} * ##### [addHeaders()](#addHeaders()) public @method Add header for the message. {@see \Cake\Mailer\Message::addHeaders()} * ##### [addReplyTo()](#addReplyTo()) public @method Add "Reply-To" address. {@see \Cake\Mailer\Message::addReplyTo()} * ##### [addTo()](#addTo()) public @method Add "To" address. {@see \Cake\Mailer\Message::addTo()} * ##### [configured()](#configured()) public static Returns an array containing the named configurations * ##### [deliver()](#deliver()) public Render content and send email using configured transport. * ##### [drop()](#drop()) public static Drops a constructed adapter. * ##### [fetchTable()](#fetchTable()) public Convenience method to get a table instance. * ##### [flatten()](#flatten()) protected Converts given value to string * ##### [getAttachments()](#getAttachments()) public @method Gets attachments to the email message. {@see \Cake\Mailer\Message::getAttachments()} * ##### [getBcc()](#getBcc()) public @method Gets "bcc" address. {@see \Cake\Mailer\Message::getBcc()} * ##### [getBody()](#getBody()) public @method Get generated message body as array. {@see \Cake\Mailer\Message::getBody()} * ##### [getCc()](#getCc()) public @method Gets "cc" address. {@see \Cake\Mailer\Message::getCc()} * ##### [getCharset()](#getCharset()) public @method Charset getter. {@see \Cake\Mailer\Message::getCharset()} * ##### [getConfig()](#getConfig()) public static Reads existing configuration. * ##### [getConfigOrFail()](#getConfigOrFail()) public static Reads existing configuration for a specific key. * ##### [getDomain()](#getDomain()) public @method Gets domain. {@see \Cake\Mailer\Message::getDomain()} * ##### [getDsnClassMap()](#getDsnClassMap()) public static Returns the DSN class map for this class. * ##### [getEmailFormat()](#getEmailFormat()) public @method Gets email format. {@see \Cake\Mailer\Message::getEmailFormat()} * ##### [getFrom()](#getFrom()) public @method Gets "from" address. {@see \Cake\Mailer\Message::getFrom()} * ##### [getHeaderCharset()](#getHeaderCharset()) public @method HeaderCharset getter. {@see \Cake\Mailer\Message::getHeaderCharset()} * ##### [getHeaders()](#getHeaders()) public @method Get list of headers. {@see \Cake\Mailer\Message::getHeaders()} * ##### [getMessage()](#getMessage()) public Get message instance. * ##### [getMessageId()](#getMessageId()) public @method Gets message ID. {@see \Cake\Mailer\Message::getMessageId()} * ##### [getModelType()](#getModelType()) public Get the model type to be used by this class * ##### [getReadReceipt()](#getReadReceipt()) public @method Gets Read Receipt (Disposition-Notification-To header). {@see \Cake\Mailer\Message::getReadReceipt()} * ##### [getRenderer()](#getRenderer()) public Get email renderer. * ##### [getReplyTo()](#getReplyTo()) public @method Gets "Reply-To" address. {@see \Cake\Mailer\Message::getReplyTo()} * ##### [getReturnPath()](#getReturnPath()) public @method Gets return path. {@see \Cake\Mailer\Message::getReturnPath()} * ##### [getSender()](#getSender()) public @method Gets "sender" address. {@see \Cake\Mailer\Message::getSender()} * ##### [getSubject()](#getSubject()) public @method Gets subject. {@see \Cake\Mailer\Message::getSubject()} * ##### [getTableLocator()](#getTableLocator()) public Gets the table locator. * ##### [getTo()](#getTo()) public @method Gets "to" address. {@see \Cake\Mailer\Message::getTo()} * ##### [getTransport()](#getTransport()) public Gets the transport. * ##### [implementedEvents()](#implementedEvents()) public Implemented events. * ##### [loadModel()](#loadModel()) public deprecated Loads and constructs repository objects required by this object * ##### [logDelivery()](#logDelivery()) protected Log the email message delivery. * ##### [modelFactory()](#modelFactory()) public Override a existing callable to generate repositories of a given type. * ##### [parseDsn()](#parseDsn()) public static Parses a DSN into a valid connection configuration * ##### [render()](#render()) public Render content and set message body. * ##### [reset()](#reset()) public Reset all the internal variables to be able to send out a new email. * ##### [restore()](#restore()) protected Restore message, renderer, transport instances to state before an action was run. * ##### [send()](#send()) public Sends email. * ##### [set()](#set()) public deprecated Sets email view vars. * ##### [setAttachments()](#setAttachments()) public @method Add attachments to the email message. {@see \Cake\Mailer\Message::setAttachments()} * ##### [setBcc()](#setBcc()) public @method Sets "bcc" address. {@see \Cake\Mailer\Message::setBcc()} * ##### [setCc()](#setCc()) public @method Sets "cc" address. {@see \Cake\Mailer\Message::setCc()} * ##### [setCharset()](#setCharset()) public @method Charset setter. {@see \Cake\Mailer\Message::setCharset()} * ##### [setConfig()](#setConfig()) public static This method can be used to define configuration adapters for an application. * ##### [setDomain()](#setDomain()) public @method Sets domain. {@see \Cake\Mailer\Message::setDomain()} * ##### [setDsnClassMap()](#setDsnClassMap()) public static Updates the DSN class map for this class. * ##### [setEmailFormat()](#setEmailFormat()) public @method Sets email format. {@see \Cake\Mailer\Message::getHeaders()} * ##### [setFrom()](#setFrom()) public @method Sets "from" address. {@see \Cake\Mailer\Message::setFrom()} * ##### [setHeaderCharset()](#setHeaderCharset()) public @method HeaderCharset setter. {@see \Cake\Mailer\Message::setHeaderCharset()} * ##### [setHeaders()](#setHeaders()) public @method Sets headers for the message. {@see \Cake\Mailer\Message::setHeaders()} * ##### [setLogConfig()](#setLogConfig()) protected Set logging config. * ##### [setMessage()](#setMessage()) public Set message instance. * ##### [setMessageId()](#setMessageId()) public @method Sets message ID. {@see \Cake\Mailer\Message::setMessageId()} * ##### [setModelType()](#setModelType()) public Set the model type to be used by this class * ##### [setProfile()](#setProfile()) public Sets the configuration profile to use for this instance. * ##### [setReadReceipt()](#setReadReceipt()) public @method Sets Read Receipt (Disposition-Notification-To header). {@see \Cake\Mailer\Message::setReadReceipt()} * ##### [setRenderer()](#setRenderer()) public Set email renderer. * ##### [setReplyTo()](#setReplyTo()) public @method Sets "Reply-To" address. {@see \Cake\Mailer\Message::setReplyTo()} * ##### [setReturnPath()](#setReturnPath()) public @method Sets return path. {@see \Cake\Mailer\Message::setReturnPath()} * ##### [setSender()](#setSender()) public @method Sets "sender" address. {@see \Cake\Mailer\Message::setSender()} * ##### [setSubject()](#setSubject()) public @method Sets subject. {@see \Cake\Mailer\Message::setSubject()} * ##### [setTableLocator()](#setTableLocator()) public Sets the table locator. * ##### [setTo()](#setTo()) public @method Sets "to" address. {@see \Cake\Mailer\Message::setTo()} * ##### [setTransport()](#setTransport()) public Sets the transport. * ##### [setViewVars()](#setViewVars()) public Sets email view vars. * ##### [viewBuilder()](#viewBuilder()) public Get the view builder. Method Detail ------------- ### \_\_call() public ``` __call(string $method, array $args): $this|mixed ``` Magic method to forward method class to Message instance. #### Parameters `string` $method Method name. `array` $args Method arguments #### Returns `$this|mixed` ### \_\_construct() public ``` __construct(array<string, mixed>|string|null $config = null) ``` Constructor #### Parameters `array<string, mixed>|string|null` $config optional Array of configs, or string to load configs from app.php ### \_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` ### addAttachments() public @method ``` addAttachments(mixed $attachments): $this ``` Add attachments. {@see \Cake\Mailer\Message::addAttachments()} #### Parameters $attachments #### Returns `$this` ### addBcc() public @method ``` addBcc(mixed $email, mixed $name = null): $this ``` Add "bcc" address. {@see \Cake\Mailer\Message::addBcc()} #### Parameters $email $name optional #### Returns `$this` ### addCc() public @method ``` addCc(mixed $email, mixed $name = null): $this ``` Add "cc" address. {@see \Cake\Mailer\Message::addCc()} #### Parameters $email $name optional #### Returns `$this` ### addHeaders() public @method ``` addHeaders(array $headers): $this ``` Add header for the message. {@see \Cake\Mailer\Message::addHeaders()} #### Parameters `array` $headers #### Returns `$this` ### addReplyTo() public @method ``` addReplyTo(mixed $email, mixed $name = null): $this ``` Add "Reply-To" address. {@see \Cake\Mailer\Message::addReplyTo()} #### Parameters $email $name optional #### Returns `$this` ### addTo() public @method ``` addTo(mixed $email, mixed $name = null): $this ``` Add "To" address. {@see \Cake\Mailer\Message::addTo()} #### Parameters $email $name optional #### Returns `$this` ### configured() public static ``` configured(): array<string> ``` Returns an array containing the named configurations #### Returns `array<string>` ### deliver() public ``` deliver(string $content = ''): array ``` Render content and send email using configured transport. #### Parameters `string` $content optional Content. #### Returns `array` ### 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` ### 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() ### flatten() protected ``` flatten(array<string>|string $value): string ``` Converts given value to string #### Parameters `array<string>|string` $value The value to convert #### Returns `string` ### getAttachments() public @method ``` getAttachments(): array ``` Gets attachments to the email message. {@see \Cake\Mailer\Message::getAttachments()} #### Returns `array` ### getBcc() public @method ``` getBcc(): array ``` Gets "bcc" address. {@see \Cake\Mailer\Message::getBcc()} #### Returns `array` ### getBody() public @method ``` getBody(?string $type = null): array|string ``` Get generated message body as array. {@see \Cake\Mailer\Message::getBody()} #### Parameters `?string` $type optional #### Returns `array|string` ### getCc() public @method ``` getCc(): array ``` Gets "cc" address. {@see \Cake\Mailer\Message::getCc()} #### Returns `array` ### getCharset() public @method ``` getCharset(): string ``` Charset getter. {@see \Cake\Mailer\Message::getCharset()} #### Returns `string` ### 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. ### getDomain() public @method ``` getDomain(): string ``` Gets domain. {@see \Cake\Mailer\Message::getDomain()} #### Returns `string` ### getDsnClassMap() public static ``` getDsnClassMap(): array<string, string> ``` Returns the DSN class map for this class. #### Returns `array<string, string>` ### getEmailFormat() public @method ``` getEmailFormat(): string ``` Gets email format. {@see \Cake\Mailer\Message::getEmailFormat()} #### Returns `string` ### getFrom() public @method ``` getFrom(): array ``` Gets "from" address. {@see \Cake\Mailer\Message::getFrom()} #### Returns `array` ### getHeaderCharset() public @method ``` getHeaderCharset(): string ``` HeaderCharset getter. {@see \Cake\Mailer\Message::getHeaderCharset()} #### Returns `string` ### getHeaders() public @method ``` getHeaders(array $include = []): $this ``` Get list of headers. {@see \Cake\Mailer\Message::getHeaders()} #### Parameters `array` $include optional #### Returns `$this` ### getMessage() public ``` getMessage(): Cake\Mailer\Message ``` Get message instance. #### Returns `Cake\Mailer\Message` ### getMessageId() public @method ``` getMessageId(): string|bool ``` Gets message ID. {@see \Cake\Mailer\Message::getMessageId()} #### Returns `string|bool` ### getModelType() public ``` getModelType(): string ``` Get the model type to be used by this class #### Returns `string` ### getReadReceipt() public @method ``` getReadReceipt(): array ``` Gets Read Receipt (Disposition-Notification-To header). {@see \Cake\Mailer\Message::getReadReceipt()} #### Returns `array` ### getRenderer() public ``` getRenderer(): Cake\Mailer\Renderer ``` Get email renderer. #### Returns `Cake\Mailer\Renderer` ### getReplyTo() public @method ``` getReplyTo(): array ``` Gets "Reply-To" address. {@see \Cake\Mailer\Message::getReplyTo()} #### Returns `array` ### getReturnPath() public @method ``` getReturnPath(): array ``` Gets return path. {@see \Cake\Mailer\Message::getReturnPath()} #### Returns `array` ### getSender() public @method ``` getSender(): array ``` Gets "sender" address. {@see \Cake\Mailer\Message::getSender()} #### Returns `array` ### getSubject() public @method ``` getSubject(): string ``` Gets subject. {@see \Cake\Mailer\Message::getSubject()} #### Returns `string` ### getTableLocator() public ``` getTableLocator(): Cake\ORM\Locator\LocatorInterface ``` Gets the table locator. #### Returns `Cake\ORM\Locator\LocatorInterface` ### getTo() public @method ``` getTo(): array ``` Gets "to" address. {@see \Cake\Mailer\Message::getTo()} #### Returns `array` ### getTransport() public ``` getTransport(): Cake\Mailer\AbstractTransport ``` Gets the transport. #### Returns `Cake\Mailer\AbstractTransport` ### implementedEvents() public ``` implementedEvents(): array<string, mixed> ``` Implemented events. ### Example: ``` public function implementedEvents() { return [ 'Order.complete' => 'sendEmail', 'Article.afterBuy' => 'decrementInventory', 'User.onRegister' => ['callable' => 'logRegistration', 'priority' => 20, 'passParams' => true] ]; } ``` #### Returns `array<string, mixed>` ### 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. ### logDelivery() protected ``` logDelivery(array $contents): void ``` Log the email message delivery. #### Parameters `array` $contents The content with 'headers' and 'message' keys. #### Returns `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` ### 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 ### render() public ``` render(string $content = ''): $this ``` Render content and set message body. #### Parameters `string` $content optional Content. #### Returns `$this` ### reset() public ``` reset(): $this ``` Reset all the internal variables to be able to send out a new email. #### Returns `$this` ### restore() protected ``` restore(): $this ``` Restore message, renderer, transport instances to state before an action was run. #### Returns `$this` ### send() public ``` send(string|null $action = null, array $args = [], array $headers = []): array ``` Sends email. #### Parameters `string|null` $action optional The name of the mailer action to trigger. If no action is specified then all other method arguments will be ignored. `array` $args optional Arguments to pass to the triggered mailer action. `array` $headers optional Headers to set. #### Returns `array` #### Throws `Cake\Mailer\Exception\MissingActionException` `BadMethodCallException` ### set() public ``` set(array|string $key, mixed $value = null): $this ``` Sets email view vars. #### Parameters `array|string` $key Variable name or hash of view variables. `mixed` $value optional View variable value. #### Returns `$this` ### setAttachments() public @method ``` setAttachments(mixed $attachments): $this ``` Add attachments to the email message. {@see \Cake\Mailer\Message::setAttachments()} #### Parameters $attachments #### Returns `$this` ### setBcc() public @method ``` setBcc(mixed $email, mixed $name = null): $this ``` Sets "bcc" address. {@see \Cake\Mailer\Message::setBcc()} #### Parameters $email $name optional #### Returns `$this` ### setCc() public @method ``` setCc(mixed $email, mixed $name = null): $this ``` Sets "cc" address. {@see \Cake\Mailer\Message::setCc()} #### Parameters $email $name optional #### Returns `$this` ### setCharset() public @method ``` setCharset(mixed $charset): $this ``` Charset setter. {@see \Cake\Mailer\Message::setCharset()} #### Parameters $charset #### Returns `$this` ### 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. ### setDomain() public @method ``` setDomain(mixed $domain): $this ``` Sets domain. {@see \Cake\Mailer\Message::setDomain()} #### Parameters $domain #### Returns `$this` ### 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` ### setEmailFormat() public @method ``` setEmailFormat(mixed $format): $this ``` Sets email format. {@see \Cake\Mailer\Message::getHeaders()} #### Parameters $format #### Returns `$this` ### setFrom() public @method ``` setFrom(mixed $email, mixed $name = null): $this ``` Sets "from" address. {@see \Cake\Mailer\Message::setFrom()} #### Parameters $email $name optional #### Returns `$this` ### setHeaderCharset() public @method ``` setHeaderCharset(mixed $charset): $this ``` HeaderCharset setter. {@see \Cake\Mailer\Message::setHeaderCharset()} #### Parameters $charset #### Returns `$this` ### setHeaders() public @method ``` setHeaders(array $headers): $this ``` Sets headers for the message. {@see \Cake\Mailer\Message::setHeaders()} #### Parameters `array` $headers #### Returns `$this` ### setLogConfig() protected ``` setLogConfig(array<string, mixed>|string|true $log): void ``` Set logging config. #### Parameters `array<string, mixed>|string|true` $log Log config. #### Returns `void` ### setMessage() public ``` setMessage(Cake\Mailer\Message $message): $this ``` Set message instance. #### Parameters `Cake\Mailer\Message` $message Message instance. #### Returns `$this` ### setMessageId() public @method ``` setMessageId(mixed $message): $this ``` Sets message ID. {@see \Cake\Mailer\Message::setMessageId()} #### Parameters $message #### Returns `$this` ### setModelType() public ``` setModelType(string $modelType): $this ``` Set the model type to be used by this class #### Parameters `string` $modelType The model type #### Returns `$this` ### setProfile() public ``` setProfile(array<string, mixed>|string $config): $this ``` Sets the configuration profile to use for this instance. #### Parameters `array<string, mixed>|string` $config String with configuration name, or an array with config. #### Returns `$this` ### setReadReceipt() public @method ``` setReadReceipt(mixed $email, mixed $name = null): $this ``` Sets Read Receipt (Disposition-Notification-To header). {@see \Cake\Mailer\Message::setReadReceipt()} #### Parameters $email $name optional #### Returns `$this` ### setRenderer() public ``` setRenderer(Cake\Mailer\Renderer $renderer): $this ``` Set email renderer. #### Parameters `Cake\Mailer\Renderer` $renderer Render instance. #### Returns `$this` ### setReplyTo() public @method ``` setReplyTo(mixed $email, mixed $name = null): $this ``` Sets "Reply-To" address. {@see \Cake\Mailer\Message::setReplyTo()} #### Parameters $email $name optional #### Returns `$this` ### setReturnPath() public @method ``` setReturnPath(mixed $email, mixed $name = null): $this ``` Sets return path. {@see \Cake\Mailer\Message::setReturnPath()} #### Parameters $email $name optional #### Returns `$this` ### setSender() public @method ``` setSender(mixed $email, mixed $name = null): $this ``` Sets "sender" address. {@see \Cake\Mailer\Message::setSender()} #### Parameters $email $name optional #### Returns `$this` ### setSubject() public @method ``` setSubject(mixed $subject): $this ``` Sets subject. {@see \Cake\Mailer\Message::setSubject()} #### Parameters $subject #### 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` ### setTo() public @method ``` setTo(mixed $email, mixed $name = null): $this ``` Sets "to" address. {@see \Cake\Mailer\Message::setTo()} #### Parameters $email $name optional #### Returns `$this` ### setTransport() public ``` setTransport(Cake\Mailer\AbstractTransport|string $name): $this ``` Sets the transport. When setting the transport you can either use the name of a configured transport or supply a constructed transport. #### Parameters `Cake\Mailer\AbstractTransport|string` $name Either the name of a configured transport, or a transport instance. #### Returns `$this` #### Throws `LogicException` When the chosen transport lacks a send method. `InvalidArgumentException` When $name is neither a string nor an object. ### setViewVars() public ``` setViewVars(array|string $key, mixed $value = null): $this ``` Sets email view vars. #### Parameters `array|string` $key Variable name or hash of view variables. `mixed` $value optional View variable value. #### Returns `$this` ### viewBuilder() public ``` viewBuilder(): Cake\View\ViewBuilder ``` Get the view builder. #### Returns `Cake\View\ViewBuilder` Property Detail --------------- ### $\_config protected static Configuration sets. #### Type `array<string, mixed>` ### $\_dsnClassMap protected static Mailer driver class map. #### Type `array<string, string>` ### $\_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` ### $clonedInstances protected Hold message, renderer and transport instance for restoring after running a mailer action. #### Type `array<string, mixed>` ### $defaultTable protected This object's default table alias. #### Type `string|null` ### $logConfig protected #### Type `array|null` ### $message protected Message instance. #### Type `Cake\Mailer\Message` ### $messageClass protected Message class name. #### Type `string` ### $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 static Mailer's name. #### Type `string` ### $renderer protected Email Renderer #### Type `Cake\Mailer\Renderer|null` ### $transport protected The transport instance to use for sending mail. #### Type `Cake\Mailer\AbstractTransport|null`
programming_docs
cakephp Class SchemaCache Class SchemaCache ================== Schema Cache. This tool is intended to be used by deployment scripts so that you can prevent thundering herd effects on the metadata cache when new versions of your application are deployed, or when migrations requiring updated metadata are required. **Namespace:** [Cake\Database](namespace-cake.database) **Link:** https://en.wikipedia.org/wiki/Thundering\_herd\_problem About the thundering herd problem Property Summary ---------------- * [$\_schema](#%24_schema) protected `Cake\Database\Schema\CachedCollection` Schema Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [build()](#build()) public Build metadata. * ##### [clear()](#clear()) public Clear metadata. * ##### [getSchema()](#getSchema()) public Helper method to get the schema collection. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\Database\Connection $connection) ``` Constructor #### Parameters `Cake\Database\Connection` $connection Connection name to get the schema for or a connection instance ### build() public ``` build(string|null $name = null): array<string> ``` Build metadata. #### Parameters `string|null` $name optional The name of the table to build cache data for. #### Returns `array<string>` ### clear() public ``` clear(string|null $name = null): array<string> ``` Clear metadata. #### Parameters `string|null` $name optional The name of the table to clear cache data for. #### Returns `array<string>` ### getSchema() public ``` getSchema(Cake\Database\Connection $connection): Cake\Database\Schema\CachedCollection ``` Helper method to get the schema collection. #### Parameters `Cake\Database\Connection` $connection Connection object #### Returns `Cake\Database\Schema\CachedCollection` #### Throws `RuntimeException` If given connection object is not compatible with schema caching Property Detail --------------- ### $\_schema protected Schema #### Type `Cake\Database\Schema\CachedCollection` cakephp Class ObjectRegistry Class ObjectRegistry ===================== Acts as a registry/factory for objects. Provides registry & factory functionality for object types. Used as a super class for various composition based re-use features in CakePHP. Each subclass needs to implement the various abstract methods to complete the template method load(). The ObjectRegistry is EventManager aware, but each extending class will need to use \Cake\Event\EventDispatcherTrait to attach and detach on set and bind **Abstract** **Namespace:** [Cake\Core](namespace-cake.core) **See:** \Cake\Controller\ComponentRegistry **See:** \Cake\View\HelperRegistry **See:** \Cake\Console\TaskRegistry 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()) abstract protected Create an instance of a given classname. * ##### [\_resolveClassName()](#_resolveClassName()) abstract protected Should resolve the classname for a given object type. * ##### [\_throwMissingClassError()](#_throwMissingClassError()) abstract protected Throw an exception when the requested object name 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 ------------- ### \_\_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() abstract protected ``` _create(object|string $class, string $alias, array<string, mixed> $config): object ``` Create an instance of a given classname. This method should construct and do any other initialization logic required. #### Parameters `object|string` $class The class to build. `string` $alias The alias of the object. `array<string, mixed>` $config The Configuration settings for construction #### Returns `object` ### \_resolveClassName() abstract protected ``` _resolveClassName(string $class): string|null ``` Should resolve the classname for a given object type. #### Parameters `string` $class The class to resolve. #### Returns `string|null` ### \_throwMissingClassError() abstract protected ``` _throwMissingClassError(string $class, string|null $plugin): void ``` Throw an exception when the requested object name is missing. #### Parameters `string` $class The class that is missing. `string|null` $plugin The plugin $class is missing from. #### Returns `void` #### Throws `Exception` ### 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 --------------- ### $\_loaded protected Map of loaded objects. #### Type `array<object>` cakephp Class StringTemplate Class StringTemplate ===================== Provides an interface for registering and inserting content into simple logic-less string templates. Used by several helpers to provide simple flexible templates for generating HTML and other content. **Namespace:** [Cake\View](namespace-cake.view) Property Summary ---------------- * [$\_compactAttributes](#%24_compactAttributes) protected `array<string, bool>` List of attributes that can be made compact. * [$\_compiled](#%24_compiled) protected `array<string, array>` Contains the list of compiled templates * [$\_config](#%24_config) protected `array<string, mixed>` Runtime config * [$\_configInitialized](#%24_configInitialized) protected `bool` Whether the config property has already been configured with defaults * [$\_configStack](#%24_configStack) protected `array` A stack of template sets that have been stashed temporarily. * [$\_defaultConfig](#%24_defaultConfig) protected `array<string, mixed>` The default templates this instance holds. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [\_compileTemplates()](#_compileTemplates()) protected Compile templates into a more efficient printf() compatible format. * ##### [\_configDelete()](#_configDelete()) protected Deletes a single config key. * ##### [\_configRead()](#_configRead()) protected Reads a config key. * ##### [\_configWrite()](#_configWrite()) protected Writes a config key. * ##### [\_formatAttribute()](#_formatAttribute()) protected Formats an individual attribute, and returns the string value of the composed attribute. Works with minimized attributes that have the same value as their name such as 'disabled' and 'checked' * ##### [add()](#add()) public Registers a list of templates by name * ##### [addClass()](#addClass()) public Adds a class and returns a unique list either in array or space separated * ##### [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 Format a template string with $data * ##### [formatAttributes()](#formatAttributes()) public Returns a space-delimited string with items of the $options array. If a key of $options array happens to be one of those listed in `StringTemplate::$_compactAttributes` and its value is one of: * ##### [getConfig()](#getConfig()) public Returns the config. * ##### [getConfigOrFail()](#getConfigOrFail()) public Returns the config for this specific key. * ##### [load()](#load()) public Load a config file containing templates. * ##### [pop()](#pop()) public Restore the most recently pushed set of templates. * ##### [push()](#push()) public Push the current templates into the template stack. * ##### [remove()](#remove()) public Remove the named template. * ##### [setConfig()](#setConfig()) public Sets the config. Method Detail ------------- ### \_\_construct() public ``` __construct(array<string, mixed> $config = []) ``` Constructor. #### Parameters `array<string, mixed>` $config optional A set of templates to add. ### \_compileTemplates() protected ``` _compileTemplates(array<string> $templates = []): void ``` Compile templates into a more efficient printf() compatible format. #### Parameters `array<string>` $templates optional The template names to compile. If empty all templates will be compiled. #### 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 ### \_formatAttribute() protected ``` _formatAttribute(string $key, array<string>|string $value, bool $escape = true): string ``` Formats an individual attribute, and returns the string value of the composed attribute. Works with minimized attributes that have the same value as their name such as 'disabled' and 'checked' #### Parameters `string` $key The name of the attribute to create `array<string>|string` $value The value of the attribute to create. `bool` $escape optional Define if the value must be escaped #### Returns `string` ### add() public ``` add(array<string> $templates): $this ``` Registers a list of templates by name ### Example: ``` $templater->add([ 'link' => '<a href="{{url}}">{{title}}</a>' 'button' => '<button>{{text}}</button>' ]); ``` #### Parameters `array<string>` $templates An associative list of named templates. #### Returns `$this` ### addClass() public ``` addClass(array|string $input, array<string>|string $newClass, string $useIndex = 'class'): array<string>|string ``` Adds a class and returns a unique list either in array or space separated #### Parameters `array|string` $input The array or string to add the class to `array<string>|string` $newClass the new class or classes to add `string` $useIndex optional if you are inputting an array with an element other than default of 'class'. #### Returns `array<string>|string` ### 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(string $name, array<string, mixed> $data): string ``` Format a template string with $data #### Parameters `string` $name The template name. `array<string, mixed>` $data The data to insert. #### Returns `string` #### Throws `RuntimeException` If template not found. ### formatAttributes() public ``` formatAttributes(array<string, mixed>|null $options, array<string>|null $exclude = null): string ``` Returns a space-delimited string with items of the $options array. If a key of $options array happens to be one of those listed in `StringTemplate::$_compactAttributes` and its value is one of: * '1' (string) * 1 (integer) * true (boolean) * 'true' (string) Then the value will be reset to be identical with key's name. If the value is not one of these 4, the parameter is not output. 'escape' is a special option in that it controls the conversion of attributes to their HTML-entity encoded equivalents. Set to false to disable HTML-encoding. If value for any option key is set to `null` or `false`, that option will be excluded from output. This method uses the 'attribute' and 'compactAttribute' templates. Each of these templates uses the `name` and `value` variables. You can modify these templates to change how attributes are formatted. #### Parameters `array<string, mixed>|null` $options Array of options. `array<string>|null` $exclude optional Array of options to be excluded, the options here will not be part of the return. #### 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` ### load() public ``` load(string $file): void ``` Load a config file containing templates. Template files should define a `$config` variable containing all the templates to load. Loaded templates will be merged with existing templates. #### Parameters `string` $file The file to load #### Returns `void` ### pop() public ``` pop(): void ``` Restore the most recently pushed set of templates. #### Returns `void` ### push() public ``` push(): void ``` Push the current templates into the template stack. #### Returns `void` ### remove() public ``` remove(string $name): void ``` Remove the named template. #### Parameters `string` $name The template to remove. #### 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 --------------- ### $\_compactAttributes protected List of attributes that can be made compact. #### Type `array<string, bool>` ### $\_compiled protected Contains the list of compiled templates #### 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` ### $\_configStack protected A stack of template sets that have been stashed temporarily. #### Type `array` ### $\_defaultConfig protected The default templates this instance holds. #### Type `array<string, mixed>`
programming_docs
cakephp Class CookieEncryptedEquals Class CookieEncryptedEquals ============================ CookieEncryptedEquals **Namespace:** [Cake\TestSuite\Constraint\Response](namespace-cake.testsuite.constraint.response) Property Summary ---------------- * [$\_validCiphers](#%24_validCiphers) protected `array<string>` Valid cipher names for encrypted cookies. * [$cookieName](#%24cookieName) protected `string` * [$key](#%24key) protected `string` * [$mode](#%24mode) protected `string` * [$response](#%24response) protected `Cake\Http\Response` Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [\_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 * ##### [\_implode()](#_implode()) protected Implode method to keep keys are multidimensional arrays * ##### [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, string $mode, string $key) ``` Constructor. #### Parameters `Cake\Http\Response|null` $response A response instance. `string` $cookieName Cookie name `string` $mode Mode `string` $key Key ### \_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 #### 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` ### 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 --------------- ### $\_validCiphers protected Valid cipher names for encrypted cookies. #### Type `array<string>` ### $cookieName protected #### Type `string` ### $key protected #### Type `string` ### $mode protected #### Type `string` ### $response protected #### Type `Cake\Http\Response` cakephp Trait SqlDialectTrait Trait SqlDialectTrait ====================== Sql dialect trait **Namespace:** [Cake\Database\Driver](namespace-cake.database.driver) Method Summary -------------- * ##### [\_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 * ##### [\_updateQueryTranslator()](#_updateQueryTranslator()) protected Apply translation steps to update queries. * ##### [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. * ##### [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 * ##### [savePointSQL()](#savePointSQL()) public Returns a SQL snippet for creating a new transaction savepoint Method Detail ------------- ### \_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` ### \_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` ### 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` ### 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` ### 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` cakephp Class SortIterator Class 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. ### Example: ``` $items = [$user1, $user2, $user3]; $sorted = new SortIterator($items, function ($user) { return $user->age; }); // output all user name order by their age in descending order foreach ($sorted as $user) { echo $user->name; } ``` This iterator does not preserve the keys passed in the original elements. **Namespace:** [Cake\Collection\Iterator](namespace-cake.collection.iterator) Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Wraps this iterator around the passed items so when iterated they are returned in order. * ##### [\_\_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(iterable $items, callable|string $callback, int $dir = \SORT_DESC, int $type = \SORT_NUMERIC) ``` Wraps this iterator around the passed items so when iterated they are returned in order. The callback will receive as first argument each of the elements in $items, the value returned in 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. #### Parameters `iterable` $items The values to sort `callable|string` $callback A function used to return the actual value to be compared. It can also be a string representing the path to use to fetch a column or property in each element `int` $dir optional either SORT\_DESC or SORT\_ASC `int` $type optional the type of comparison to perform, either SORT\_STRING SORT\_NUMERIC or SORT\_NATURAL ### \_\_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`
programming_docs
cakephp Class MemoryStorage Class MemoryStorage ==================== Memory based non-persistent storage for authenticated user record. **Namespace:** [Cake\Auth\Storage](namespace-cake.auth.storage) Property Summary ---------------- * [$\_redirectUrl](#%24_redirectUrl) protected `array|string|null` Redirect URL. * [$\_user](#%24_user) protected `ArrayAccess|array|null` User record. 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 #### Returns `array|string|null` ### write() public ``` write(mixed $user): void ``` Write user record. #### Parameters `mixed` $user #### Returns `void` Property Detail --------------- ### $\_redirectUrl protected Redirect URL. #### Type `array|string|null` ### $\_user protected User record. #### Type `ArrayAccess|array|null` cakephp Class CounterCacheBehavior Class CounterCacheBehavior =========================== CounterCache behavior Enables models to cache the amount of connections in a given relation. Examples with Post model belonging to User model Regular counter cache ``` [ 'Users' => [ 'post_count' ] ] ``` Counter cache with scope ``` [ 'Users' => [ 'posts_published' => [ 'conditions' => [ 'published' => true ] ] ] ] ``` Counter cache using custom find ``` [ 'Users' => [ 'posts_published' => [ 'finder' => 'published' // Will be using findPublished() ] ] ] ``` Counter cache using lambda function returning the count This is equivalent to example #2 ``` [ 'Users' => [ 'posts_published' => function (EventInterface $event, EntityInterface $entity, Table $table) { $query = $table->find('all')->where([ 'published' => true, 'user_id' => $entity->get('user_id') ]); return $query->count(); } ] ] ``` When using a lambda function you can return `false` to disable updating the counter value for the current operation. Ignore updating the field if it is dirty ``` [ 'Users' => [ 'posts_published' => [ 'ignoreDirty' => true ] ] ] ``` You can disable counter updates entirely by sending the `ignoreCounterCache` option to your save operation: ``` $this->Articles->save($article, ['ignoreCounterCache' => true]); ``` **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 configuration * [$\_ignoreDirty](#%24_ignoreDirty) protected `array<string, array<string, bool>>` Store the fields which should be ignored * [$\_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. * ##### [\_getCount()](#_getCount()) protected Fetches and returns the count for a single field in an association * ##### [\_processAssociation()](#_processAssociation()) protected Updates counter cache for a single association * ##### [\_processAssociations()](#_processAssociations()) protected Iterate all associations and update counter caches. * ##### [\_reflectionCache()](#_reflectionCache()) protected Gets the methods implemented by this behavior * ##### [\_resolveMethodAliases()](#_resolveMethodAliases()) protected Removes aliased methods that would otherwise be duplicated by userland configuration. * ##### [\_shouldUpdateCount()](#_shouldUpdateCount()) protected Checks if the count should be updated given a set of conditions. * ##### [afterDelete()](#afterDelete()) public afterDelete callback. * ##### [afterSave()](#afterSave()) public afterSave callback. * ##### [beforeSave()](#beforeSave()) public beforeSave callback. * ##### [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 ### \_getCount() protected ``` _getCount(array<string, mixed> $config, array $conditions): int ``` Fetches and returns the count for a single field in an association #### Parameters `array<string, mixed>` $config The counter cache configuration for a single field `array` $conditions Additional conditions given to the query #### Returns `int` ### \_processAssociation() protected ``` _processAssociation(Cake\Event\EventInterface $event, Cake\Datasource\EntityInterface $entity, Cake\ORM\Association $assoc, array $settings): void ``` Updates counter cache for a single association #### Parameters `Cake\Event\EventInterface` $event Event instance. `Cake\Datasource\EntityInterface` $entity Entity `Cake\ORM\Association` $assoc The association object `array` $settings The settings for counter cache for this association #### Returns `void` #### Throws `RuntimeException` If invalid callable is passed. ### \_processAssociations() protected ``` _processAssociations(Cake\Event\EventInterface $event, Cake\Datasource\EntityInterface $entity): void ``` Iterate all associations and update counter caches. #### Parameters `Cake\Event\EventInterface` $event Event instance. `Cake\Datasource\EntityInterface` $entity Entity. #### Returns `void` ### \_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` ### \_shouldUpdateCount() protected ``` _shouldUpdateCount(array $conditions): bool ``` Checks if the count should be updated given a set of conditions. #### Parameters `array` $conditions Conditions to update count. #### Returns `bool` ### afterDelete() public ``` afterDelete(Cake\Event\EventInterface $event, Cake\Datasource\EntityInterface $entity, ArrayObject $options): void ``` afterDelete callback. Makes sure to update counter cache when a record is deleted. #### Parameters `Cake\Event\EventInterface` $event The afterDelete event that was fired. `Cake\Datasource\EntityInterface` $entity The entity that was deleted. `ArrayObject` $options The options for the query #### Returns `void` ### afterSave() public ``` afterSave(Cake\Event\EventInterface $event, Cake\Datasource\EntityInterface $entity, ArrayObject $options): void ``` afterSave callback. Makes sure to update counter cache when a new record is created or updated. #### Parameters `Cake\Event\EventInterface` $event The afterSave event that was fired. `Cake\Datasource\EntityInterface` $entity The entity that was saved. `ArrayObject` $options The options for the query #### Returns `void` ### beforeSave() public ``` beforeSave(Cake\Event\EventInterface $event, Cake\Datasource\EntityInterface $entity, ArrayObject $options): void ``` beforeSave callback. Check if a field, which should be ignored, is dirty #### 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 for the query #### 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` ### 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>` ### $\_ignoreDirty protected Store the fields which should be ignored #### Type `array<string, array<string, bool>>` ### $\_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 Class Mock Class Mock =========== Implements sending requests to an array of stubbed responses This adapter is not intended for production use. Instead it is the backend used by `Client::addMockResponse()` **Namespace:** [Cake\Http\Client\Adapter](namespace-cake.http.client.adapter) Property Summary ---------------- * [$responses](#%24responses) protected `array` List of mocked responses. Method Summary -------------- * ##### [addResponse()](#addResponse()) public Add a mocked response. * ##### [send()](#send()) public Find a response if one exists. * ##### [urlMatches()](#urlMatches()) protected Check if the request URI matches the mock URI. Method Detail ------------- ### addResponse() public ``` addResponse(Psr\Http\Message\RequestInterface $request, Cake\Http\Client\Response $response, array<string, mixed> $options): void ``` Add a mocked response. ### Options * `match` An additional closure to match requests with. #### Parameters `Psr\Http\Message\RequestInterface` $request A partial request to use for matching. `Cake\Http\Client\Response` $response The response that matches the request. `array<string, mixed>` $options See above. #### Returns `void` ### send() public ``` send(Psr\Http\Message\RequestInterface $request, array<string, mixed> $options): Cake\Http\Client\Response[] ``` Find a response if one exists. #### Parameters `Psr\Http\Message\RequestInterface` $request The request to match `array<string, mixed>` $options Unused. #### Returns `Cake\Http\Client\Response[]` ### urlMatches() protected ``` urlMatches(string $requestUri, Psr\Http\Message\RequestInterface $mock): bool ``` Check if the request URI matches the mock URI. #### Parameters `string` $requestUri The request being sent. `Psr\Http\Message\RequestInterface` $mock The request being mocked. #### Returns `bool` Property Detail --------------- ### $responses protected List of mocked responses. #### Type `array` cakephp Class Postgres Class Postgres =============== Class Postgres **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** ``` 63 ``` * `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 Postgres driver * [$\_config](#%24_config) protected `array<string, mixed>` Configuration data. * [$\_connection](#%24_connection) protected `PDO` Instance of PDO. * [$\_endQuote](#%24_endQuote) protected `string` String used to end a database identifier quoting to make it safe * [$\_schemaDialect](#%24_schemaDialect) protected `Cake\Database\Schema\PostgresSchemaDialect|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 * [$\_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 * ##### [\_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. * ##### [\_transformIdentifierExpression()](#_transformIdentifierExpression()) protected Changes identifer expression into postgresql format. * ##### [\_transformStringExpression()](#_transformStringExpression()) protected Changes string expression into postgresql format. * ##### [\_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. * ##### [setEncoding()](#setEncoding()) public Sets connection encoding * ##### [setSchema()](#setSchema()) public Sets connection default schema, if any relation defined in a query is not fully qualified postgres will fallback to looking the relation into defined default schema * ##### [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. * ##### [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 #### 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 #### 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 postgres SQL. #### Returns `void` ### \_transformIdentifierExpression() protected ``` _transformIdentifierExpression(Cake\Database\Expression\IdentifierExpression $expression): void ``` Changes identifer expression into postgresql format. #### Parameters `Cake\Database\Expression\IdentifierExpression` $expression The expression to tranform. #### Returns `void` ### \_transformStringExpression() protected ``` _transformStringExpression(Cake\Database\Expression\StringExpression $expression): void ``` Changes string expression into postgresql format. #### Parameters `Cake\Database\Expression\StringExpression` $expression The string expression to tranform. #### 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\PostgresCompiler ``` Returns an instance of a QueryCompiler. #### Returns `Cake\Database\PostgresCompiler` ### 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() 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` ### setEncoding() public ``` setEncoding(string $encoding): void ``` Sets connection encoding #### Parameters `string` $encoding The encoding to use. #### Returns `void` ### setSchema() public ``` setSchema(string $schema): void ``` Sets connection default schema, if any relation defined in a query is not fully qualified postgres will fallback to looking the relation into defined default schema #### Parameters `string` $schema The schema names to set `search_path` to. #### Returns `void` ### 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` ### 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 Postgres driver #### Type `array<string, mixed>` ### $\_config protected Configuration data. #### Type `array<string, mixed>` ### $\_connection protected Instance of PDO. #### Type `PDO` ### $\_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\PostgresSchemaDialect|null` ### $\_startQuote protected String used to start a database identifier quoting to make it safe #### Type `string` ### $\_version protected The server version #### Type `string|null` ### $connectRetries protected The last number of connection retry attempts. #### Type `int`
programming_docs
cakephp Class ContentType Class ContentType ================== ContentType **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 Request Class Request ============== Implements methods for HTTP requests. Used by Cake\Http\Client to contain request information for making requests. **Namespace:** [Cake\Http\Client](namespace-cake.http.client) Constants --------- * `string` **METHOD\_DELETE** ``` 'DELETE' ``` HTTP DELETE method * `string` **METHOD\_GET** ``` 'GET' ``` HTTP GET method * `string` **METHOD\_HEAD** ``` 'HEAD' ``` HTTP HEAD method * `string` **METHOD\_OPTIONS** ``` 'OPTIONS' ``` HTTP OPTIONS method * `string` **METHOD\_PATCH** ``` 'PATCH' ``` HTTP PATCH method * `string` **METHOD\_POST** ``` 'POST' ``` HTTP POST method * `string` **METHOD\_PUT** ``` 'PUT' ``` HTTP PUT method * `string` **METHOD\_TRACE** ``` 'TRACE' ``` HTTP TRACE method * `int` **STATUS\_ACCEPTED** ``` 202 ``` HTTP 202 code * `int` **STATUS\_CREATED** ``` 201 ``` HTTP 201 code * `int` **STATUS\_FOUND** ``` 302 ``` HTTP 302 code * `int` **STATUS\_MOVED\_PERMANENTLY** ``` 301 ``` HTTP 301 code * `int` **STATUS\_NON\_AUTHORITATIVE\_INFORMATION** ``` 203 ``` HTTP 203 code * `int` **STATUS\_NO\_CONTENT** ``` 204 ``` HTTP 204 code * `int` **STATUS\_OK** ``` 200 ``` HTTP 200 code * `int` **STATUS\_PERMANENT\_REDIRECT** ``` 308 ``` HTTP 308 code * `int` **STATUS\_SEE\_OTHER** ``` 303 ``` HTTP 303 code * `int` **STATUS\_TEMPORARY\_REDIRECT** ``` 307 ``` HTTP 307 code Property Summary ---------------- * [$\_cookies](#%24_cookies) protected `array` The array of cookies in the response. * [$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 * ##### [addHeaders()](#addHeaders()) protected Add an array of headers to the request. * ##### [cookies()](#cookies()) public Get all cookies * ##### [getBody()](#getBody()) public Gets the body of the message. * ##### [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. * ##### [getMethod()](#getMethod()) public Retrieves the HTTP method of the request. * ##### [getProtocolVersion()](#getProtocolVersion()) public Retrieves the HTTP protocol version as a string. * ##### [getRequestTarget()](#getRequestTarget()) public Retrieves the message's request target. * ##### [getUri()](#getUri()) public Retrieves the URI instance. * ##### [hasHeader()](#hasHeader()) public Checks if a header exists by the given case-insensitive name. * ##### [setContent()](#setContent()) protected Set the body/payload for the message. * ##### [withAddedHeader()](#withAddedHeader()) public Return an instance with the specified header appended with the given value. * ##### [withBody()](#withBody()) public Return an instance with the specified message body. * ##### [withHeader()](#withHeader()) public Return an instance with the provided header, replacing any existing values of any headers with the same case-insensitive name. * ##### [withMethod()](#withMethod()) public Return an instance with the provided HTTP method. * ##### [withProtocolVersion()](#withProtocolVersion()) public Return an instance with the specified HTTP protocol version. * ##### [withRequestTarget()](#withRequestTarget()) public Create a new instance with a specific request-target. * ##### [withUri()](#withUri()) public Returns an instance with the provided URI. * ##### [withoutHeader()](#withoutHeader()) public Return an instance without the specified header. Method Detail ------------- ### \_\_construct() public ``` __construct(string $url = '', string $method = self::METHOD_GET, array $headers = [], array|string|null $data = null) ``` Constructor Provides backwards compatible defaults for some properties. #### Parameters `string` $url optional The request URL `string` $method optional The HTTP method to use. `array` $headers optional The HTTP headers to set. `array|string|null` $data optional The request body to use. ### addHeaders() protected ``` addHeaders(array<string, string> $headers): void ``` Add an array of headers to the request. #### Parameters `array<string, string>` $headers The headers to add. #### Returns `void` ### cookies() public ``` cookies(): array ``` Get all cookies #### Returns `array` ### getBody() public ``` getBody(): StreamInterface ``` Gets the body of the message. #### Returns `StreamInterface` ### 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` ### getMethod() public ``` getMethod(): string ``` Retrieves the HTTP method of the request. #### Returns `string` ### 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` ### getRequestTarget() public ``` getRequestTarget(): string ``` Retrieves the message's request target. Retrieves the message's request-target either as it will appear (for clients), as it appeared at request (for servers), or as it was specified for the instance (see withRequestTarget()). In most cases, this will be the origin-form of the composed URI, unless a value was provided to the concrete implementation (see withRequestTarget() below). If no URI is available, and no request-target has been specifically provided, this method MUST return the string "/". #### Returns `string` ### getUri() public ``` getUri(): UriInterface ``` Retrieves the URI instance. This method MUST return a UriInterface instance. #### Returns `UriInterface` #### Links http://tools.ietf.org/html/rfc3986#section-4.3 ### 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` ### setContent() protected ``` setContent(array|string $content): $this ``` Set the body/payload for the message. Array data will be serialized with {@link \Cake\Http\FormData}, and the content-type will be set. #### Parameters `array|string` $content The body for the request. #### Returns `$this` ### 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. ### 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. ### 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. ### withMethod() public ``` withMethod(string $method): static ``` Return an instance with the provided HTTP method. While HTTP method names are typically all uppercase characters, HTTP method names are case-sensitive and thus implementations SHOULD NOT modify the given string. 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 changed request method. #### Parameters `string` $method Case-insensitive method. #### Returns `static` #### Throws `Exception\InvalidArgumentException` For invalid HTTP methods. ### 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` ### withRequestTarget() public ``` withRequestTarget(mixed $requestTarget): static ``` Create a new instance with a specific request-target. If the request needs a non-origin-form request-target — e.g., for specifying an absolute-form, authority-form, or asterisk-form — this method may be used to create an instance with the specified request-target, verbatim. 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 changed request target. #### Parameters `mixed` $requestTarget #### Returns `static` #### Throws `Exception\InvalidArgumentException` If the request target is invalid. #### Links http://tools.ietf.org/html/rfc7230#section-2.7 (for the various request-target forms allowed in request messages) ### withUri() public ``` withUri(UriInterface $uri, bool $preserveHost = false): static ``` Returns an instance with the provided URI. This method will update the Host header of the returned request by default if the URI contains a host component. If the URI does not contain a host component, any pre-existing Host header will be carried over to the returned request. You can opt-in to preserving the original state of the Host header by setting `$preserveHost` to `true`. When `$preserveHost` is set to `true`, the returned request will not update the Host header of the returned message -- even if the message contains no Host header. This means that a call to `getHeader('Host')` on the original request MUST equal the return value of a call to `getHeader('Host')` on the returned request. 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 UriInterface instance. #### Parameters `UriInterface` $uri New request URI to use. `bool` $preserveHost optional Preserve the original state of the Host header. #### Returns `static` #### Links http://tools.ietf.org/html/rfc3986#section-4.3 ### 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 --------------- ### $\_cookies protected The array of cookies in the response. #### Type `array` ### $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 StopException Class StopException ==================== Exception class for halting errors in console tasks **Namespace:** [Cake\Console\Exception](namespace-cake.console.exception) **See:** \Cake\Console\Shell::\_stop() **See:** \Cake\Console\Shell::error() **See:** \Cake\Command\BaseCommand::abort() 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 ErrorController Class ErrorController ====================== Error Handling Controller Controller used by ErrorHandler to render error views. **Namespace:** [Cake\Controller](namespace-cake.controller) Property Summary ---------------- * [$Auth](#%24Auth) public @property `Cake\Controller\Component\AuthComponent` * [$Flash](#%24Flash) public @property `Cake\Controller\Component\FlashComponent` * [$FormProtection](#%24FormProtection) public @property `Cake\Controller\Component\FormProtectionComponent` * [$Paginator](#%24Paginator) public @property `Cake\Controller\Component\PaginatorComponent` * [$RequestHandler](#%24RequestHandler) public @property `Cake\Controller\Component\RequestHandlerComponent` * [$Security](#%24Security) public @property `Cake\Controller\Component\SecurityComponent` * [$\_components](#%24_components) protected `Cake\Controller\ComponentRegistry|null` Instance of ComponentRegistry used to create Components * [$\_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. * [$\_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 * [$\_viewBuilder](#%24_viewBuilder) protected `Cake\View\ViewBuilder|null` The view builder instance being used. * [$autoRender](#%24autoRender) protected `bool` Set to true to automatically render the view after action logic. * [$defaultTable](#%24defaultTable) protected `string|null` This object's default table alias. * [$middlewares](#%24middlewares) protected `array` Middlewares list. * [$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 controller. Controller names are plural, named after the model they manipulate. * [$paginate](#%24paginate) public `array` Settings for pagination. * [$plugin](#%24plugin) protected `string|null` Automatically set to the name of a 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` An instance of a Response object that contains information about the impending response Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [\_\_get()](#__get()) public Magic accessor for model autoloading. * ##### [\_\_set()](#__set()) public Magic setter for removed properties. * ##### [\_setModelClass()](#_setModelClass()) protected Set the modelClass property based on conventions. * ##### [\_templatePath()](#_templatePath()) protected Get the templatePath based on controller name and request prefix. * ##### [afterFilter()](#afterFilter()) public Called after the controller action is run and rendered. * ##### [beforeFilter()](#beforeFilter()) public Called before the controller action. You can use this method to configure and customize components or perform logic that needs to happen before each controller action. * ##### [beforeRedirect()](#beforeRedirect()) public The beforeRedirect method is invoked when the controller's redirect method is called but before any further action. * ##### [beforeRender()](#beforeRender()) public beforeRender callback. * ##### [chooseViewClass()](#chooseViewClass()) protected Use the view classes defined on this controller to view selection based on content-type negotiation. * ##### [components()](#components()) public Get the component registry for this controller. * ##### [createView()](#createView()) public Constructs the view class instance based on the current configuration. * ##### [disableAutoRender()](#disableAutoRender()) public Disable automatic action rendering. * ##### [dispatchEvent()](#dispatchEvent()) public Wrapper for creating and dispatching events. * ##### [enableAutoRender()](#enableAutoRender()) public Enable automatic action rendering. * ##### [fetchTable()](#fetchTable()) public Convenience method to get a table instance. * ##### [getAction()](#getAction()) public Get the closure for action to be invoked by ControllerFactory. * ##### [getEventManager()](#getEventManager()) public Returns the Cake\Event\EventManager manager instance for this object. * ##### [getMiddleware()](#getMiddleware()) public Get middleware to be applied for this controller. * ##### [getModelType()](#getModelType()) public Get the model type to be used by this class * ##### [getName()](#getName()) public Returns the controller name. * ##### [getPlugin()](#getPlugin()) public Returns the plugin name. * ##### [getRequest()](#getRequest()) public Gets the request instance. * ##### [getResponse()](#getResponse()) public Gets the response instance. * ##### [getTableLocator()](#getTableLocator()) public Gets the table locator. * ##### [implementedEvents()](#implementedEvents()) public Returns a list of all events that will fire in the controller during its lifecycle. You can override this function to add your own listener callbacks * ##### [initialize()](#initialize()) public Initialization hook method. * ##### [invokeAction()](#invokeAction()) public Dispatches the controller action. * ##### [isAction()](#isAction()) public Method to check that an action is accessible from a URL. * ##### [isAutoRenderEnabled()](#isAutoRenderEnabled()) public Returns true if an action should be rendered automatically. * ##### [loadComponent()](#loadComponent()) public Add a component to the controller's registry. * ##### [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. * ##### [middleware()](#middleware()) public Register middleware for the controller. * ##### [modelFactory()](#modelFactory()) public Override a existing callable to generate repositories of a given type. * ##### [paginate()](#paginate()) public Handles pagination of records in Table objects. * ##### [redirect()](#redirect()) public Redirects to given $url, after turning off $this->autoRender. * ##### [referer()](#referer()) public Returns the referring URL for this request. * ##### [render()](#render()) public Instantiates the correct view class, hands it its data, and uses it to render the view output. * ##### [set()](#set()) public Saves a variable or an associative array of variables for use inside a template. * ##### [setAction()](#setAction()) public deprecated Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect() * ##### [setEventManager()](#setEventManager()) public Returns the Cake\Event\EventManagerInterface instance for this object. * ##### [setModelType()](#setModelType()) public Set the model type to be used by this class * ##### [setName()](#setName()) public Sets the controller name. * ##### [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. Controller acts as a proxy for certain View variables which must also be updated here. The properties that get set are: * ##### [setResponse()](#setResponse()) public Sets the response instance. * ##### [setTableLocator()](#setTableLocator()) public Sets the table locator. * ##### [shutdownProcess()](#shutdownProcess()) public Perform the various shutdown processes for this controller. Fire the Components and Controller callbacks in the correct order. * ##### [startupProcess()](#startupProcess()) public Perform the startup process for this controller. Fire the Components and Controller callbacks in the correct order. * ##### [viewBuilder()](#viewBuilder()) public Get the view builder being used. * ##### [viewClasses()](#viewClasses()) public Get the View classes this controller can perform content negotiation with. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\Http\ServerRequest|null $request = null, Cake\Http\Response|null $response = null, string|null $name = null, Cake\Event\EventManagerInterface|null $eventManager = null, Cake\Controller\ComponentRegistry|null $components = null) ``` Constructor. Sets a number of properties based on conventions if they are empty. To override the conventions CakePHP uses you can define properties in your class declaration. #### Parameters `Cake\Http\ServerRequest|null` $request optional Request object for this controller. Can be null for testing, but expect that features that use the request parameters will not work. `Cake\Http\Response|null` $response optional Response object for this controller. `string|null` $name optional Override the name useful in testing when using mocks. `Cake\Event\EventManagerInterface|null` $eventManager optional The event manager. Defaults to a new instance. `Cake\Controller\ComponentRegistry|null` $components optional The component registry. Defaults to a new instance. ### \_\_get() public ``` __get(string $name): Cake\Datasource\RepositoryInterface|null ``` Magic accessor for model autoloading. #### Parameters `string` $name Property name #### Returns `Cake\Datasource\RepositoryInterface|null` ### \_\_set() public ``` __set(string $name, mixed $value): void ``` Magic setter for removed properties. #### Parameters `string` $name Property name. `mixed` $value Value to set. #### 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` ### \_templatePath() protected ``` _templatePath(): string ``` Get the templatePath based on controller name and request prefix. #### Returns `string` ### afterFilter() public ``` afterFilter(Cake\Event\EventInterface $event): Cake\Http\Response|null|void ``` Called after the controller action is run and rendered. #### Parameters `Cake\Event\EventInterface` $event An Event instance #### Returns `Cake\Http\Response|null|void` #### Links https://book.cakephp.org/4/en/controllers.html#request-life-cycle-callbacks ### beforeFilter() public ``` beforeFilter(Cake\Event\EventInterface $event): Cake\Http\Response|null|void ``` Called before the controller action. You can use this method to configure and customize components or perform logic that needs to happen before each controller action. #### Parameters `Cake\Event\EventInterface` $event An Event instance #### Returns `Cake\Http\Response|null|void` #### Links https://book.cakephp.org/4/en/controllers.html#request-life-cycle-callbacks ### beforeRedirect() public ``` beforeRedirect(Cake\Event\EventInterface $event, array|string $url, Cake\Http\Response $response): Cake\Http\Response|null|void ``` The beforeRedirect method is invoked when the controller's redirect method is called but before any further action. If the event is stopped the controller will not continue on to redirect the request. The $url and $status variables have same meaning as for the controller's method. You can set the event result to response instance or modify the redirect location using controller's response instance. #### Parameters `Cake\Event\EventInterface` $event An Event instance `array|string` $url A string or array-based URL pointing to another location within the app, or an absolute URL `Cake\Http\Response` $response The response object. #### Returns `Cake\Http\Response|null|void` #### Links https://book.cakephp.org/4/en/controllers.html#request-life-cycle-callbacks ### beforeRender() public ``` beforeRender(Cake\Event\EventInterface $event): Cake\Http\Response|null|void ``` beforeRender callback. #### Parameters `Cake\Event\EventInterface` $event Event. #### Returns `Cake\Http\Response|null|void` ### chooseViewClass() protected ``` chooseViewClass(): string|null ``` Use the view classes defined on this controller to view selection based on content-type negotiation. #### Returns `string|null` ### components() public ``` components(Cake\Controller\ComponentRegistry|null $components = null): Cake\Controller\ComponentRegistry ``` Get the component registry for this controller. If called with the first parameter, it will be set as the controller $this->\_components property #### Parameters `Cake\Controller\ComponentRegistry|null` $components optional Component registry. #### Returns `Cake\Controller\ComponentRegistry` ### createView() public ``` createView(string|null $viewClass = null): Cake\View\View ``` Constructs the view class instance based on the current configuration. #### Parameters `string|null` $viewClass optional Optional namespaced class name of the View class to instantiate. #### Returns `Cake\View\View` #### Throws `Cake\View\Exception\MissingViewException` If view class was not found. ### disableAutoRender() public ``` disableAutoRender(): $this ``` Disable automatic action rendering. #### 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` ### enableAutoRender() public ``` enableAutoRender(): $this ``` Enable automatic action rendering. #### 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() ### getAction() public ``` getAction(): Closure ``` Get the closure for action to be invoked by ControllerFactory. #### Returns `Closure` #### Throws `Cake\Controller\Exception\MissingActionException` ### 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` ### getMiddleware() public ``` getMiddleware(): array ``` Get middleware to be applied for this controller. #### Returns `array` ### getModelType() public ``` getModelType(): string ``` Get the model type to be used by this class #### Returns `string` ### getName() public ``` getName(): string ``` Returns the 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` ### getTableLocator() public ``` getTableLocator(): Cake\ORM\Locator\LocatorInterface ``` Gets the table locator. #### Returns `Cake\ORM\Locator\LocatorInterface` ### implementedEvents() public ``` implementedEvents(): array<string, mixed> ``` Returns a list of all events that will fire in the controller during its lifecycle. You can override this function to add your own listener callbacks ### Example: ``` public function implementedEvents() { return [ 'Order.complete' => 'sendEmail', 'Article.afterBuy' => 'decrementInventory', 'User.onRegister' => ['callable' => 'logRegistration', 'priority' => 20, 'passParams' => true] ]; } ``` #### Returns `array<string, mixed>` ### initialize() public ``` initialize(): void ``` Initialization hook method. Implement this method to avoid having to overwrite the constructor and call parent. #### Returns `void` ### invokeAction() public ``` invokeAction(Closure $action, array $args): void ``` Dispatches the controller action. #### Parameters `Closure` $action The action closure. `array` $args The arguments to be passed when invoking action. #### Returns `void` #### Throws `UnexpectedValueException` If return value of action is not `null` or `ResponseInterface` instance. ### isAction() public ``` isAction(string $action): bool ``` Method to check that an action is accessible from a URL. Override this method to change which controller methods can be reached. The default implementation disallows access to all methods defined on Cake\Controller\Controller, and allows all public methods on all subclasses of this class. #### Parameters `string` $action The action to check. #### Returns `bool` #### Throws `ReflectionException` ### isAutoRenderEnabled() public ``` isAutoRenderEnabled(): bool ``` Returns true if an action should be rendered automatically. #### Returns `bool` ### loadComponent() public ``` loadComponent(string $name, array<string, mixed> $config = []): Cake\Controller\Component ``` Add a component to the controller's registry. This method will also set the component to a property. For example: ``` $this->loadComponent('Authentication.Authentication'); ``` Will result in a `Authentication` property being set. #### Parameters `string` $name The name of the component to load. `array<string, mixed>` $config optional The config for the component. #### Returns `Cake\Controller\Component` #### Throws `Exception` ### 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` ### middleware() public ``` middleware(Psr\Http\Server\MiddlewareInterfaceClosure|string $middleware, array<string, mixed> $options = []): void ``` Register middleware for the controller. #### Parameters `Psr\Http\Server\MiddlewareInterfaceClosure|string` $middleware Middleware. `array<string, mixed>` $options optional Valid options: * `only`: (array|string) Only run the middleware for specified actions. * `except`: (array|string) Run the middleware for all actions except the specified ones. #### Returns `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` ### paginate() public ``` paginate(Cake\ORM\TableCake\ORM\Query|string|null $object = null, array<string, mixed> $settings = []): Cake\ORM\ResultSetCake\Datasource\ResultSetInterface ``` Handles pagination of records in Table objects. Will load the referenced Table object, and have the paginator paginate the query using the request date and settings defined in `$this->paginate`. This method will also make the PaginatorHelper available in the view. #### Parameters `Cake\ORM\TableCake\ORM\Query|string|null` $object optional Table to paginate (e.g: Table instance, 'TableName' or a Query object) `array<string, mixed>` $settings optional The settings/configuration used for pagination. #### Returns `Cake\ORM\ResultSetCake\Datasource\ResultSetInterface` #### Throws `RuntimeException` When no compatible table object can be found. #### Links https://book.cakephp.org/4/en/controllers.html#paginating-a-model ### redirect() public ``` redirect(Psr\Http\Message\UriInterface|array|string $url, int $status = 302): Cake\Http\Response|null ``` Redirects to given $url, after turning off $this->autoRender. #### Parameters `Psr\Http\Message\UriInterface|array|string` $url A string, array-based URL or UriInterface instance. `int` $status optional HTTP status code. Defaults to `302`. #### Returns `Cake\Http\Response|null` #### Links https://book.cakephp.org/4/en/controllers.html#Controller::redirect ### referer() public ``` referer(array|string|null $default = '/', bool $local = true): string ``` Returns the referring URL for this request. #### Parameters `array|string|null` $default optional Default URL to use if HTTP\_REFERER cannot be read from headers `bool` $local optional If false, do not restrict referring URLs to local server. Careful with trusting external sources. #### Returns `string` ### render() public ``` render(string|null $template = null, string|null $layout = null): Cake\Http\Response ``` Instantiates the correct view class, hands it its data, and uses it to render the view output. #### Parameters `string|null` $template optional Template to use for rendering `string|null` $layout optional Layout to use #### Returns `Cake\Http\Response` #### Links https://book.cakephp.org/4/en/controllers.html#rendering-a-view ### 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` ### setAction() public ``` setAction(string $action, mixed ...$args): mixed ``` Internally redirects one action to another. Does not perform another HTTP request unlike Controller::redirect() Examples: ``` setAction('another_action'); setAction('action_with_parameters', $parameter1); ``` #### Parameters `string` $action The new action to be 'redirected' to. Any other parameters passed to this method will be passed as parameters to the new action. `mixed` ...$args Arguments passed to the action #### Returns `mixed` ### 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` ### 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 ``` Sets the controller name. #### Parameters `string` $name Controller name. #### 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. Controller acts as a proxy for certain View variables which must also be updated here. The properties that get set are: * $this->request - To the $request parameter #### 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` ### setTableLocator() public ``` setTableLocator(Cake\ORM\Locator\LocatorInterface $tableLocator): $this ``` Sets the table locator. #### Parameters `Cake\ORM\Locator\LocatorInterface` $tableLocator LocatorInterface instance. #### Returns `$this` ### shutdownProcess() public ``` shutdownProcess(): Psr\Http\Message\ResponseInterface|null ``` Perform the various shutdown processes for this controller. Fire the Components and Controller callbacks in the correct order. * triggers the component `shutdown` callback. * calls the Controller's `afterFilter` method. #### Returns `Psr\Http\Message\ResponseInterface|null` ### startupProcess() public ``` startupProcess(): Psr\Http\Message\ResponseInterface|null ``` Perform the startup process for this controller. Fire the Components and Controller callbacks in the correct order. * Initializes components, which fires their `initialize` callback * Calls the controller `beforeFilter`. * triggers Component `startup` methods. #### Returns `Psr\Http\Message\ResponseInterface|null` ### viewBuilder() public ``` viewBuilder(): Cake\View\ViewBuilder ``` Get the view builder being used. #### Returns `Cake\View\ViewBuilder` ### viewClasses() public ``` viewClasses(): array<string> ``` Get the View classes this controller can perform content negotiation with. Each view class must implement the `getContentType()` hook method to participate in negotiation. #### Returns `array<string>` #### See Also Cake\Http\ContentTypeNegotiation Property Detail --------------- ### $Auth public @property #### Type `Cake\Controller\Component\AuthComponent` ### $Flash public @property #### Type `Cake\Controller\Component\FlashComponent` ### $FormProtection public @property #### Type `Cake\Controller\Component\FormProtectionComponent` ### $Paginator public @property #### Type `Cake\Controller\Component\PaginatorComponent` ### $RequestHandler public @property #### Type `Cake\Controller\Component\RequestHandlerComponent` ### $Security public @property #### Type `Cake\Controller\Component\SecurityComponent` ### $\_components protected Instance of ComponentRegistry used to create Components #### Type `Cake\Controller\ComponentRegistry|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` ### $\_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` ### $\_viewBuilder protected The view builder instance being used. #### Type `Cake\View\ViewBuilder|null` ### $autoRender protected Set to true to automatically render the view after action logic. #### Type `bool` ### $defaultTable protected This object's default table alias. #### Type `string|null` ### $middlewares protected Middlewares list. #### Type `array` ### $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 controller. Controller names are plural, named after the model they manipulate. Set automatically using conventions in Controller::\_\_construct(). #### Type `string` ### $paginate public Settings for pagination. Used to pre-configure pagination preferences for the various tables your controller will be paginating. #### Type `array` ### $plugin protected Automatically set to the name of a 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 An instance of a Response object that contains information about the impending response #### Type `Cake\Http\Response`
programming_docs
cakephp Class PluralRules Class PluralRules ================== Utility class used to determine the plural number to be used for a variable base on the locale. **Namespace:** [Cake\I18n](namespace-cake.i18n) Property Summary ---------------- * [$\_rulesMap](#%24_rulesMap) protected static `array<string, int>` A map of locale => plurals group used to determine which plural rules apply to the language Method Summary -------------- * ##### [calculate()](#calculate()) public static Returns the plural form number for the passed locale corresponding to the countable provided in $n. Method Detail ------------- ### calculate() public static ``` calculate(string $locale, int $n): int ``` Returns the plural form number for the passed locale corresponding to the countable provided in $n. #### Parameters `string` $locale The locale to get the rule calculated for. `int` $n The number to apply the rules to. #### Returns `int` #### Links http://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html https://developer.mozilla.org/en-US/docs/Mozilla/Localization/Localization\_and\_Plurals#List\_of\_Plural\_Rules Property Detail --------------- ### $\_rulesMap protected static A map of locale => plurals group used to determine which plural rules apply to the language #### Type `array<string, int>` cakephp Class UnfoldIterator Class 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. **Namespace:** [Cake\Collection\Iterator](namespace-cake.collection.iterator) **See:** \Cake\Collection\Collection::unfold() Property Summary ---------------- * [$\_innerIterator](#%24_innerIterator) protected `Traversable` A reference to the internal iterator this object is wrapping. * [$\_unfolder](#%24_unfolder) protected `callable` A function that is passed each element in this iterator and must return an array or Traversable object. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Creates the iterator that will generate child iterators from each of the elements it was constructed with. * ##### [getChildren()](#getChildren()) public Returns an iterator containing the items generated by transforming the current value with the callable function. * ##### [hasChildren()](#hasChildren()) public Returns true as each of the elements in the array represent a list of items Method Detail ------------- ### \_\_construct() public ``` __construct(Traversable $items, callable $unfolder) ``` Creates the iterator that will generate child iterators from each of the elements it was constructed with. #### Parameters `Traversable` $items The list of values to iterate `callable` $unfolder A callable function that will receive the current item and key. It must return an array or Traversable object out of which the nested iterators will be yielded. ### getChildren() public ``` getChildren(): RecursiveIterator ``` Returns an iterator containing the items generated by transforming the current value with the callable function. #### Returns `RecursiveIterator` ### hasChildren() public ``` hasChildren(): bool ``` Returns true as each of the elements in the array represent a list of items #### Returns `bool` Property Detail --------------- ### $\_innerIterator protected A reference to the internal iterator this object is wrapping. #### Type `Traversable` ### $\_unfolder protected A function that is passed each element in this iterator and must return an array or Traversable object. #### Type `callable` cakephp Namespace Decorator Namespace Decorator =================== ### Classes * ##### [AbstractDecorator](class-cake.event.decorator.abstractdecorator) Common base class for event decorator subclasses. * ##### [ConditionDecorator](class-cake.event.decorator.conditiondecorator) Event Condition Decorator * ##### [SubjectFilterDecorator](class-cake.event.decorator.subjectfilterdecorator) Event Subject Filter Decorator cakephp Class Curl Class Curl =========== Implements sending Cake\Http\Client\Request via ext/curl. In addition to the standard options documented in {@link \Cake\Http\Client}, this adapter supports all available curl options. Additional curl options can be set via the `curl` option key when making requests or configuring a client. **Namespace:** [Cake\Http\Client\Adapter](namespace-cake.http.client.adapter) Method Summary -------------- * ##### [buildOptions()](#buildOptions()) public Convert client options into curl options. * ##### [createResponse()](#createResponse()) protected Convert the raw curl response into an Http\Client\Response * ##### [exec()](#exec()) protected Execute the curl handle. * ##### [getProtocolVersion()](#getProtocolVersion()) protected Convert HTTP version number into curl value. * ##### [send()](#send()) public Send a request and get a response back. Method Detail ------------- ### buildOptions() public ``` buildOptions(Psr\Http\Message\RequestInterface $request, array<string, mixed> $options): array ``` Convert client options into curl options. #### Parameters `Psr\Http\Message\RequestInterface` $request The request. `array<string, mixed>` $options The client options #### Returns `array` ### createResponse() protected ``` createResponse(resourceCurlHandle $handle, string $responseData): arrayCake\Http\Client\Response> ``` Convert the raw curl response into an Http\Client\Response #### Parameters `resourceCurlHandle` $handle Curl handle `string` $responseData string The response data from curl\_exec #### Returns `arrayCake\Http\Client\Response>` ### exec() protected ``` exec(resourceCurlHandle $ch): string|bool ``` Execute the curl handle. #### Parameters `resourceCurlHandle` $ch Curl Resource handle #### Returns `string|bool` ### getProtocolVersion() protected ``` getProtocolVersion(Psr\Http\Message\RequestInterface $request): int ``` Convert HTTP version number into curl value. #### Parameters `Psr\Http\Message\RequestInterface` $request The request to get a protocol version for. #### Returns `int` ### send() public ``` send(Psr\Http\Message\RequestInterface $request, array<string, mixed> $options): arrayCake\Http\Client\Response> ``` Send a request and get a response back. #### Parameters `Psr\Http\Message\RequestInterface` $request `array<string, mixed>` $options #### Returns `arrayCake\Http\Client\Response>` cakephp Class NetworkException Class NetworkException ======================= Thrown when the request cannot be completed because of network issues. There is no response object as this exception is thrown when no response has been received. Example: the target host name can not be resolved or the connection failed. **Namespace:** [Cake\Http\Client\Exception](namespace-cake.http.client.exception) Property Summary ---------------- * [$request](#%24request) protected `Psr\Http\Message\RequestInterface` Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [getRequest()](#getRequest()) public Returns the request. Method Detail ------------- ### \_\_construct() public ``` __construct(string $message, Psr\Http\Message\RequestInterface $request, Throwable|null $previous = null) ``` Constructor. #### Parameters `string` $message Exeception message. `Psr\Http\Message\RequestInterface` $request Request instance. `Throwable|null` $previous optional Previous Exception ### getRequest() public ``` getRequest(): Psr\Http\Message\RequestInterface ``` Returns the request. The request object MAY be a different object from the one passed to ClientInterface::sendRequest() #### Returns `Psr\Http\Message\RequestInterface` Property Detail --------------- ### $request protected #### Type `Psr\Http\Message\RequestInterface` cakephp Class BreadcrumbsHelper Class BreadcrumbsHelper ======================== BreadcrumbsHelper to register and display a breadcrumb trail for your views **Namespace:** [Cake\View\Helper](namespace-cake.view.helper) 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 the helper. * [$\_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. * [$crumbs](#%24crumbs) protected `array` The crumb list. * [$helpers](#%24helpers) protected `array` Other helpers used by BreadcrumbsHelper. 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. * ##### [add()](#add()) public Add a crumb to the end of the trail. * ##### [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. * ##### [findCrumb()](#findCrumb()) protected Search a crumb in the current stack which title matches the one provided as argument. If found, the index of the matching crumb will be returned. * ##### [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. * ##### [getCrumbs()](#getCrumbs()) public Returns the crumb list. * ##### [getTemplates()](#getTemplates()) public Gets templates to use or a specific template. * ##### [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. * ##### [insertAfter()](#insertAfter()) public Insert a crumb after the first matching crumb with the specified title. * ##### [insertAt()](#insertAt()) public Insert a crumb at a specific index. * ##### [insertBefore()](#insertBefore()) public Insert a crumb before the first matching crumb with the specified title. * ##### [prepend()](#prepend()) public Prepend a crumb to the start of the queue. * ##### [render()](#render()) public Renders the breadcrumbs trail. * ##### [reset()](#reset()) public Removes all existing crumbs. * ##### [setConfig()](#setConfig()) public Sets the config. * ##### [setTemplates()](#setTemplates()) public Sets templates to use. * ##### [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` ### add() public ``` add(array|string $title, array|string|null $url = null, array<string, mixed> $options = []): $this ``` Add a crumb to the end of the trail. #### Parameters `array|string` $title If provided as a string, it represents the title of the crumb. Alternatively, if you want to add multiple crumbs at once, you can provide an array, with each values being a single crumb. Arrays are expected to be of this form: `array|string|null` $url optional URL of the crumb. Either a string, an array of route params to pass to Url::build() or null / empty if the crumb does not have a link. `array<string, mixed>` $options optional Array of options. These options will be used as attributes HTML attribute the crumb will be rendered in (a - tag by default). It accepts two special keys: #### Returns `$this` ### 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` ### findCrumb() protected ``` findCrumb(string $title): int|null ``` Search a crumb in the current stack which title matches the one provided as argument. If found, the index of the matching crumb will be returned. #### Parameters `string` $title Title to find. #### Returns `int|null` ### 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` ### getCrumbs() public ``` getCrumbs(): array ``` Returns the crumb list. #### Returns `array` ### 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` ### 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` ### insertAfter() public ``` insertAfter(string $matchingTitle, string $title, array|string|null $url = null, array<string, mixed> $options = []): $this ``` Insert a crumb after the first matching crumb with the specified title. Finds the index of the first crumb that matches the provided class, and inserts the supplied callable before it. #### Parameters `string` $matchingTitle The title of the crumb you want to insert this one after. `string` $title Title of the crumb. `array|string|null` $url optional URL of the crumb. Either a string, an array of route params to pass to Url::build() or null / empty if the crumb does not have a link. `array<string, mixed>` $options optional Array of options. These options will be used as attributes HTML attribute the crumb will be rendered in (a - tag by default). It accepts two special keys: #### Returns `$this` #### Throws `LogicException` In case the matching crumb can not be found. ### insertAt() public ``` insertAt(int $index, string $title, array|string|null $url = null, array<string, mixed> $options = []): $this ``` Insert a crumb at a specific index. If the index already exists, the new crumb will be inserted, before the existing element, shifting the existing element one index greater than before. If the index is out of bounds, an exception will be thrown. #### Parameters `int` $index The index to insert at. `string` $title Title of the crumb. `array|string|null` $url optional URL of the crumb. Either a string, an array of route params to pass to Url::build() or null / empty if the crumb does not have a link. `array<string, mixed>` $options optional Array of options. These options will be used as attributes HTML attribute the crumb will be rendered in (a - tag by default). It accepts two special keys: #### Returns `$this` #### Throws `LogicException` In case the index is out of bound ### insertBefore() public ``` insertBefore(string $matchingTitle, string $title, array|string|null $url = null, array<string, mixed> $options = []): $this ``` Insert a crumb before the first matching crumb with the specified title. Finds the index of the first crumb that matches the provided class, and inserts the supplied callable before it. #### Parameters `string` $matchingTitle The title of the crumb you want to insert this one before. `string` $title Title of the crumb. `array|string|null` $url optional URL of the crumb. Either a string, an array of route params to pass to Url::build() or null / empty if the crumb does not have a link. `array<string, mixed>` $options optional Array of options. These options will be used as attributes HTML attribute the crumb will be rendered in (a - tag by default). It accepts two special keys: #### Returns `$this` #### Throws `LogicException` In case the matching crumb can not be found ### prepend() public ``` prepend(array|string $title, array|string|null $url = null, array<string, mixed> $options = []): $this ``` Prepend a crumb to the start of the queue. #### Parameters `array|string` $title If provided as a string, it represents the title of the crumb. Alternatively, if you want to add multiple crumbs at once, you can provide an array, with each values being a single crumb. Arrays are expected to be of this form: `array|string|null` $url optional URL of the crumb. Either a string, an array of route params to pass to Url::build() or null / empty if the crumb does not have a link. `array<string, mixed>` $options optional Array of options. These options will be used as attributes HTML attribute the crumb will be rendered in (a - tag by default). It accepts two special keys: #### Returns `$this` ### render() public ``` render(array<string, mixed> $attributes = [], array<string, mixed> $separator = []): string ``` Renders the breadcrumbs trail. #### Parameters `array<string, mixed>` $attributes optional Array of attributes applied to the `wrapper` template. Accepts the `templateVars` key to allow the insertion of custom template variable in the template. `array<string, mixed>` $separator optional Array of attributes for the `separator` template. Possible properties are : #### Returns `string` ### reset() public ``` reset(): $this ``` Removes all existing crumbs. #### Returns `$this` ### 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` 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 the helper. #### 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` ### $crumbs protected The crumb list. #### Type `array` ### $helpers protected Other helpers used by BreadcrumbsHelper. #### Type `array`
programming_docs
cakephp Class CorsBuilder Class CorsBuilder ================== A builder object that assists in defining Cross Origin Request related headers. Each of the methods in this object provide a fluent interface. Once you've set all the headers you want to use, the `build()` method can be used to return a modified Response. It is most convenient to get this object via `Request::cors()`. **Namespace:** [Cake\Http](namespace-cake.http) **See:** \Cake\Http\Response::cors() Property Summary ---------------- * [$\_headers](#%24_headers) protected `array<string, mixed>` The headers that have been queued so far. * [$\_isSsl](#%24_isSsl) protected `bool` Whether the request was over SSL. * [$\_origin](#%24_origin) protected `string` The request's Origin header value * [$\_response](#%24_response) protected `Psr\Http\Message\MessageInterface` The response object this builder is attached to. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [\_normalizeDomains()](#_normalizeDomains()) protected Normalize the origin to regular expressions and put in an array format * ##### [allowCredentials()](#allowCredentials()) public Enable cookies to be sent in CORS requests. * ##### [allowHeaders()](#allowHeaders()) public Allowed headers that can be sent in CORS requests. * ##### [allowMethods()](#allowMethods()) public Set the list of allowed HTTP Methods. * ##### [allowOrigin()](#allowOrigin()) public Set the list of allowed domains. * ##### [build()](#build()) public Apply the queued headers to the response. * ##### [exposeHeaders()](#exposeHeaders()) public Define the headers a client library/browser can expose to scripting * ##### [maxAge()](#maxAge()) public Define the max-age preflight OPTIONS requests are valid for. Method Detail ------------- ### \_\_construct() public ``` __construct(Psr\Http\Message\MessageInterface $response, string $origin, bool $isSsl = false) ``` Constructor. #### Parameters `Psr\Http\Message\MessageInterface` $response The response object to add headers onto. `string` $origin The request's Origin header. `bool` $isSsl optional Whether the request was over SSL. ### \_normalizeDomains() protected ``` _normalizeDomains(array<string> $domains): array ``` Normalize the origin to regular expressions and put in an array format #### Parameters `array<string>` $domains Domain names to normalize. #### Returns `array` ### allowCredentials() public ``` allowCredentials(): $this ``` Enable cookies to be sent in CORS requests. #### Returns `$this` ### allowHeaders() public ``` allowHeaders(array<string> $headers): $this ``` Allowed headers that can be sent in CORS requests. #### Parameters `array<string>` $headers The list of headers to accept in CORS requests. #### Returns `$this` ### allowMethods() public ``` allowMethods(array<string> $methods): $this ``` Set the list of allowed HTTP Methods. #### Parameters `array<string>` $methods The allowed HTTP methods #### Returns `$this` ### allowOrigin() public ``` allowOrigin(array<string>|string $domains): $this ``` Set the list of allowed domains. Accepts a string or an array of domains that have CORS enabled. You can use `*.example.com` wildcards to accept subdomains, or `*` to allow all domains #### Parameters `array<string>|string` $domains The allowed domains #### Returns `$this` ### build() public ``` build(): Psr\Http\Message\MessageInterface ``` Apply the queued headers to the response. If the builder has no Origin, or if there are no allowed domains, or if the allowed domains do not match the Origin header no headers will be applied. #### Returns `Psr\Http\Message\MessageInterface` ### exposeHeaders() public ``` exposeHeaders(array<string> $headers): $this ``` Define the headers a client library/browser can expose to scripting #### Parameters `array<string>` $headers The list of headers to expose CORS responses #### Returns `$this` ### maxAge() public ``` maxAge(string|int $age): $this ``` Define the max-age preflight OPTIONS requests are valid for. #### Parameters `string|int` $age The max-age for OPTIONS requests in seconds #### Returns `$this` Property Detail --------------- ### $\_headers protected The headers that have been queued so far. #### Type `array<string, mixed>` ### $\_isSsl protected Whether the request was over SSL. #### Type `bool` ### $\_origin protected The request's Origin header value #### Type `string` ### $\_response protected The response object this builder is attached to. #### Type `Psr\Http\Message\MessageInterface` cakephp Class DoublePassDecoratorMiddleware Class DoublePassDecoratorMiddleware ==================================== Decorate double-pass middleware as PSR-15 middleware. The callable can be a closure with the following signature: ``` function ( ServerRequestInterface $request, ResponseInterface $response, callable $next ): ResponseInterface ``` or a class with `__invoke()` method with same signature as above. Neither the arguments nor the return value need be typehinted. **Namespace:** [Cake\Http\Middleware](namespace-cake.http.middleware) **Deprecated:** 4.3.0 "Double pass" middleware are deprecated. Use a `Closure` or a class which implements `Psr\Http\Server\MiddlewareInterface` instead. Property Summary ---------------- * [$callable](#%24callable) protected `callable` A closure or invokable object. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [getCallable()](#getCallable()) public * ##### [process()](#process()) public Run the internal double pass callable to process an incoming server request. Method Detail ------------- ### \_\_construct() public ``` __construct(callable $callable) ``` Constructor #### Parameters `callable` $callable A closure. ### getCallable() public ``` getCallable(): callable ``` #### Returns `callable` ### process() public ``` process(ServerRequestInterface $request, RequestHandlerInterface $handler): Psr\Http\Message\ResponseInterface ``` Run the internal double pass 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 or invokable object. #### Type `callable` cakephp Class SchemacacheClearCommand Class SchemacacheClearCommand ============================== Provides CLI tool for clearing schema cache. **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 RouteBuilder Class RouteBuilder =================== Provides features for building routes inside scopes. Gives an easy to use way to build routes and append them into a route collection. **Namespace:** [Cake\Routing](namespace-cake.routing) Constants --------- * `string` **ID** ``` '[0-9]+' ``` Regular expression for auto increment IDs * `string` **UUID** ``` '[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}' ``` Regular expression for UUIDs Property Summary ---------------- * [$\_collection](#%24_collection) protected `Cake\Routing\RouteCollection` The route collection routes should be added to. * [$\_extensions](#%24_extensions) protected `array<string>` The extensions that should be set into the routes connected. * [$\_namePrefix](#%24_namePrefix) protected `string` Name prefix for connected routes. * [$\_params](#%24_params) protected `array` The scope parameters if there are any. * [$\_path](#%24_path) protected `string` The path prefix scope that this collection uses. * [$\_resourceMap](#%24_resourceMap) protected static `array<string, array>` Default HTTP request method => controller action map. * [$\_routeClass](#%24_routeClass) protected `string` Default route class to use if none is provided in connect() options. * [$middleware](#%24middleware) protected `array<string>` The list of middleware that routes in this builder get added during construction. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [\_makeRoute()](#_makeRoute()) protected Create a route object, or return the provided object. * ##### [\_methodRoute()](#_methodRoute()) protected Helper to create routes that only respond to a single HTTP method. * ##### [addExtensions()](#addExtensions()) public Add additional extensions to what is already in current scope * ##### [applyMiddleware()](#applyMiddleware()) public Apply a middleware to the current route scope. * ##### [connect()](#connect()) public Connects a new Route. * ##### [delete()](#delete()) public Create a route that only responds to DELETE requests. * ##### [fallbacks()](#fallbacks()) public Connect the `/{controller}` and `/{controller}/{action}/*` fallback routes. * ##### [get()](#get()) public Create a route that only responds to GET requests. * ##### [getExtensions()](#getExtensions()) public Get the extensions in this route builder's scope. * ##### [getMiddleware()](#getMiddleware()) public Get the middleware that this builder will apply to routes. * ##### [getRouteClass()](#getRouteClass()) public Get default route class. * ##### [head()](#head()) public Create a route that only responds to HEAD requests. * ##### [loadPlugin()](#loadPlugin()) public Load routes from a plugin. * ##### [middlewareGroup()](#middlewareGroup()) public Apply a set of middleware to a group * ##### [nameExists()](#nameExists()) public Checks if there is already a route with a given name. * ##### [namePrefix()](#namePrefix()) public Get/set the name prefix for this scope. * ##### [options()](#options()) public Create a route that only responds to OPTIONS requests. * ##### [params()](#params()) public Get the parameter names/values for this scope. * ##### [parseDefaults()](#parseDefaults()) protected Parse the defaults if they're a string * ##### [patch()](#patch()) public Create a route that only responds to PATCH requests. * ##### [path()](#path()) public Get the path this scope is for. * ##### [plugin()](#plugin()) public Add plugin routes. * ##### [post()](#post()) public Create a route that only responds to POST requests. * ##### [prefix()](#prefix()) public Add prefixed routes. * ##### [put()](#put()) public Create a route that only responds to PUT requests. * ##### [redirect()](#redirect()) public Connects a new redirection Route in the router. * ##### [registerMiddleware()](#registerMiddleware()) public Register a middleware with the RouteCollection. * ##### [resources()](#resources()) public Generate REST resource routes for the given controller(s). * ##### [scope()](#scope()) public Create a new routing scope. * ##### [setExtensions()](#setExtensions()) public Set the extensions in this route builder's scope. * ##### [setRouteClass()](#setRouteClass()) public Set default route class. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\Routing\RouteCollection $collection, string $path, array $params = [], array<string, mixed> $options = []) ``` Constructor ### Options * `routeClass` - The default route class to use when adding routes. * `extensions` - The extensions to connect when adding routes. * `namePrefix` - The prefix to prepend to all route names. * `middleware` - The names of the middleware routes should have applied. #### Parameters `Cake\Routing\RouteCollection` $collection The route collection to append routes into. `string` $path The path prefix the scope is for. `array` $params optional The scope's routing parameters. `array<string, mixed>` $options optional Options list. ### \_makeRoute() protected ``` _makeRoute(Cake\Routing\Route\Route|string $route, array $defaults, array<string, mixed> $options): Cake\Routing\Route\Route ``` Create a route object, or return the provided object. #### Parameters `Cake\Routing\Route\Route|string` $route The route template or route object. `array` $defaults Default parameters. `array<string, mixed>` $options Additional options parameters. #### Returns `Cake\Routing\Route\Route` #### Throws `InvalidArgumentException` when route class or route object is invalid. `BadMethodCallException` when the route to make conflicts with the current scope ### \_methodRoute() protected ``` _methodRoute(string $method, string $template, array|string $target, string|null $name): Cake\Routing\Route\Route ``` Helper to create routes that only respond to a single HTTP method. #### Parameters `string` $method The HTTP method name to match. `string` $template The URL template to use. `array|string` $target An array describing the target route parameters. These parameters should indicate the plugin, prefix, controller, and action that this route points to. `string|null` $name The name of the route. #### Returns `Cake\Routing\Route\Route` ### addExtensions() public ``` addExtensions(array<string>|string $extensions): $this ``` Add additional extensions to what is already in current scope #### Parameters `array<string>|string` $extensions One or more extensions to add #### Returns `$this` ### applyMiddleware() public ``` applyMiddleware(string ...$names): $this ``` Apply a middleware to the current route scope. Requires middleware to be registered via `registerMiddleware()` #### Parameters `string` ...$names The names of the middleware to apply to the current scope. #### Returns `$this` #### Throws `RuntimeException` #### See Also \Cake\Routing\RouteCollection::addMiddlewareToScope() ### connect() public ``` connect(Cake\Routing\Route\Route|string $route, array|string $defaults = [], array<string, mixed> $options = []): Cake\Routing\Route\Route ``` Connects a new Route. Routes are a way of connecting request URLs to objects in your application. At their core routes are a set or regular expressions that are used to match requests to destinations. Examples: ``` $routes->connect('/{controller}/{action}/*'); ``` The first parameter will be used as a controller name while the second is used as the action name. The '/\*' syntax makes this route greedy in that it will match requests like `/posts/index` as well as requests like `/posts/edit/1/foo/bar`. ``` $routes->connect('/home-page', ['controller' => 'Pages', 'action' => 'display', 'home']); ``` The above shows the use of route parameter defaults. And providing routing parameters for a static route. ``` $routes->connect( '/{lang}/{controller}/{action}/{id}', [], ['id' => '[0-9]+', 'lang' => '[a-z]{3}'] ); ``` Shows connecting a route with custom route parameters as well as providing patterns for those parameters. Patterns for routing parameters do not need capturing groups, as one will be added for each route params. $options offers several 'special' keys that have special meaning in the $options array. * `routeClass` is used to extend and change how individual routes parse requests and handle reverse routing, via a custom routing class. Ex. `'routeClass' => 'SlugRoute'` * `pass` is used to define which of the routed parameters should be shifted into the pass array. Adding a parameter to pass will remove it from the regular route array. Ex. `'pass' => ['slug']`. * `persist` is used 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 parameter to `false`. Ex. `'persist' => ['lang']` * `multibytePattern` Set to true to enable multibyte pattern support in route parameter patterns. * `_name` is used to define a specific name for routes. This can be used to optimize reverse routing lookups. If undefined a name will be generated for each connected route. * `_ext` is an array of filename extensions that will be parsed out of the url if present. See {@link \Cake\Routing\RouteCollection::setExtensions()}. * `_method` Only match requests with specific HTTP verbs. * `_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. Example of using the `_method` condition: ``` $routes->connect('/tasks', ['controller' => 'Tasks', 'action' => 'index', '_method' => 'GET']); ``` The above route will only be matched for GET requests. POST requests will fail to match this route. #### Parameters `Cake\Routing\Route\Route|string` $route A string describing the template of the route `array|string` $defaults optional An array describing the default route parameters. These parameters will be used by default and can supply routing parameters that are not dynamic. See above. `array<string, mixed>` $options optional An array matching the named elements in the route to regular expressions which that element should match. Also contains additional parameters such as which routed parameters should be shifted into the passed arguments, supplying patterns for routing parameters and supplying the name of a custom routing class. #### Returns `Cake\Routing\Route\Route` #### Throws `InvalidArgumentException` `BadMethodCallException` ### delete() public ``` delete(string $template, array|string $target, string|null $name = null): Cake\Routing\Route\Route ``` Create a route that only responds to DELETE requests. #### Parameters `string` $template The URL template to use. `array|string` $target An array describing the target route parameters. These parameters should indicate the plugin, prefix, controller, and action that this route points to. `string|null` $name optional The name of the route. #### Returns `Cake\Routing\Route\Route` ### fallbacks() public ``` fallbacks(string|null $routeClass = null): $this ``` Connect the `/{controller}` and `/{controller}/{action}/*` fallback routes. This is a shortcut method for connecting fallback routes in a given scope. #### Parameters `string|null` $routeClass optional the route class to use, uses the default routeClass if not specified #### Returns `$this` ### get() public ``` get(string $template, array|string $target, string|null $name = null): Cake\Routing\Route\Route ``` Create a route that only responds to GET requests. #### Parameters `string` $template The URL template to use. `array|string` $target An array describing the target route parameters. These parameters should indicate the plugin, prefix, controller, and action that this route points to. `string|null` $name optional The name of the route. #### Returns `Cake\Routing\Route\Route` ### getExtensions() public ``` getExtensions(): array<string> ``` Get the extensions in this route builder's scope. #### Returns `array<string>` ### getMiddleware() public ``` getMiddleware(): array ``` Get the middleware that this builder will apply to routes. #### Returns `array` ### getRouteClass() public ``` getRouteClass(): string ``` Get default route class. #### Returns `string` ### head() public ``` head(string $template, array|string $target, string|null $name = null): Cake\Routing\Route\Route ``` Create a route that only responds to HEAD requests. #### Parameters `string` $template The URL template to use. `array|string` $target An array describing the target route parameters. These parameters should indicate the plugin, prefix, controller, and action that this route points to. `string|null` $name optional The name of the route. #### Returns `Cake\Routing\Route\Route` ### loadPlugin() public ``` loadPlugin(string $name): $this ``` Load routes from a plugin. The routes file will have a local variable named `$routes` made available which contains the current RouteBuilder instance. #### Parameters `string` $name The plugin name #### Returns `$this` #### Throws `Cake\Core\Exception\MissingPluginException` When the plugin has not been loaded. `InvalidArgumentException` When the plugin does not have a routes file. ### middlewareGroup() public ``` middlewareGroup(string $name, array<string> $middlewareNames): $this ``` Apply a set of middleware to a group #### Parameters `string` $name Name of the middleware group `array<string>` $middlewareNames Names of the middleware #### Returns `$this` ### nameExists() public ``` nameExists(string $name): bool ``` Checks if there is already a route with a given name. #### Parameters `string` $name Name. #### Returns `bool` ### namePrefix() public ``` namePrefix(string|null $value = null): string ``` Get/set the name prefix for this scope. Modifying the name prefix will only change the prefix used for routes connected after the prefix is changed. #### Parameters `string|null` $value optional Either the value to set or null. #### Returns `string` ### options() public ``` options(string $template, array|string $target, string|null $name = null): Cake\Routing\Route\Route ``` Create a route that only responds to OPTIONS requests. #### Parameters `string` $template The URL template to use. `array|string` $target An array describing the target route parameters. These parameters should indicate the plugin, prefix, controller, and action that this route points to. `string|null` $name optional The name of the route. #### Returns `Cake\Routing\Route\Route` ### params() public ``` params(): array ``` Get the parameter names/values for this scope. #### Returns `array` ### parseDefaults() protected ``` parseDefaults(array|string $defaults): array ``` Parse the defaults if they're a string #### Parameters `array|string` $defaults Defaults array from the connect() method. #### Returns `array` ### patch() public ``` patch(string $template, array|string $target, string|null $name = null): Cake\Routing\Route\Route ``` Create a route that only responds to PATCH requests. #### Parameters `string` $template The URL template to use. `array|string` $target An array describing the target route parameters. These parameters should indicate the plugin, prefix, controller, and action that this route points to. `string|null` $name optional The name of the route. #### Returns `Cake\Routing\Route\Route` ### path() public ``` path(): string ``` Get the path this scope is for. #### Returns `string` ### plugin() public ``` plugin(string $name, callable|array $options = [], callable|null $callback = null): $this ``` Add plugin routes. This method creates a new scoped route collection that includes relevant plugin information. The plugin name will be inflected to the underscore version to create the routing path. If you want a custom path name, use the `path` option. Routes connected in the scoped collection will have the correct path segment prepended, and have a matching plugin routing key set. ### Options * `path` The path prefix to use. Defaults to `Inflector::dasherize($name)`. * `_namePrefix` Set a prefix used for named routes. The prefix is prepended to the name of any route created in a scope callback. #### Parameters `string` $name The plugin name to build routes for `callable|array` $options optional Either the options to use, or a callback to build routes. `callable|null` $callback optional The callback to invoke that builds the plugin routes Only required when $options is defined. #### Returns `$this` ### post() public ``` post(string $template, array|string $target, string|null $name = null): Cake\Routing\Route\Route ``` Create a route that only responds to POST requests. #### Parameters `string` $template The URL template to use. `array|string` $target An array describing the target route parameters. These parameters should indicate the plugin, prefix, controller, and action that this route points to. `string|null` $name optional The name of the route. #### Returns `Cake\Routing\Route\Route` ### prefix() public ``` prefix(string $name, callable|array $params = [], callable|null $callback = null): $this ``` Add prefixed routes. This method creates a scoped route collection that includes relevant prefix information. The $name parameter is used to generate the routing parameter name. For example a path of `admin` would result in `'prefix' => 'admin'` being applied to all connected routes. You can re-open a prefix as many times as necessary, as well as nest prefixes. Nested prefixes will result in prefix values like `admin/api` which translates to the `Controller\Admin\Api\` namespace. If you need to have prefix with dots, eg: '/api/v1.0', use 'path' key for $params argument: ``` $route->prefix('Api', function($route) { $route->prefix('V10', ['path' => '/v1.0'], function($route) { // Translates to `Controller\Api\V10\` namespace }); }); ``` #### Parameters `string` $name The prefix name to use. `callable|array` $params optional An array of routing defaults to add to each connected route. If you have no parameters, this argument can be a callable. `callable|null` $callback optional The callback to invoke that builds the prefixed routes. #### Returns `$this` #### Throws `InvalidArgumentException` If a valid callback is not passed ### put() public ``` put(string $template, array|string $target, string|null $name = null): Cake\Routing\Route\Route ``` Create a route that only responds to PUT requests. #### Parameters `string` $template The URL template to use. `array|string` $target An array describing the target route parameters. These parameters should indicate the plugin, prefix, controller, and action that this route points to. `string|null` $name optional The name of the route. #### Returns `Cake\Routing\Route\Route` ### redirect() public ``` redirect(string $route, array|string $url, array<string, mixed> $options = []): Cake\Routing\Route\RouteCake\Routing\Route\RedirectRoute ``` Connects a new redirection Route in the router. Redirection routes are different from normal routes as they perform an actual header redirection if a match is found. The redirection can occur within your application or redirect to an outside location. Examples: ``` $routes->redirect('/home/*', ['controller' => 'Posts', 'action' => 'view']); ``` Redirects /home/\* to /posts/view and passes the parameters to /posts/view. Using an array as the redirect destination allows you to use other routes to define where a URL string should be redirected to. ``` $routes->redirect('/posts/*', 'http://google.com', ['status' => 302]); ``` Redirects /posts/\* to [http://google.com](https://google.com) with a HTTP status of 302 ### Options: * `status` Sets the HTTP status (default 301) * `persist` Passes the params to the redirected route, if it can. This is useful with greedy routes, routes that end in `*` are greedy. As you can remap URLs and not lose any passed args. #### Parameters `string` $route A string describing the template of the route `array|string` $url A URL to redirect to. Can be a string or a Cake array-based URL `array<string, mixed>` $options optional An array matching the named elements in the route to regular expressions which that element should match. Also contains additional parameters such as which routed parameters should be shifted into the passed arguments. As well as supplying patterns for routing parameters. #### Returns `Cake\Routing\Route\RouteCake\Routing\Route\RedirectRoute` ### registerMiddleware() public ``` registerMiddleware(string $name, Psr\Http\Server\MiddlewareInterfaceClosure|string $middleware): $this ``` Register a middleware with the RouteCollection. Once middleware has been registered, it can be applied to the current routing scope or any child scopes that share the same RouteCollection. #### Parameters `string` $name The name of the middleware. Used when applying middleware to a scope. `Psr\Http\Server\MiddlewareInterfaceClosure|string` $middleware The middleware to register. #### Returns `$this` #### See Also \Cake\Routing\RouteCollection ### resources() public ``` resources(string $name, callable|array $options = [], callable|null $callback = null): $this ``` Generate REST resource routes for the given controller(s). A quick way to generate a default routes to a set of REST resources (controller(s)). ### Usage Connect resource routes for an app controller: ``` $routes->resources('Posts'); ``` Connect resource routes for the Comments controller in the Comments plugin: ``` Router::plugin('Comments', function ($routes) { $routes->resources('Comments'); }); ``` Plugins will create lowercase dasherized resource routes. e.g `/comments/comments` Connect resource routes for the Articles controller in the Admin prefix: ``` Router::prefix('Admin', function ($routes) { $routes->resources('Articles'); }); ``` Prefixes will create lowercase dasherized resource routes. e.g `/admin/posts` You can create nested resources by passing a callback in: ``` $routes->resources('Articles', function ($routes) { $routes->resources('Comments'); }); ``` The above would generate both resource routes for `/articles`, and `/articles/{article_id}/comments`. You can use the `map` option to connect additional resource methods: ``` $routes->resources('Articles', [ 'map' => ['deleteAll' => ['action' => 'deleteAll', 'method' => 'DELETE']] ]); ``` In addition to the default routes, this would also connect a route for `/articles/delete_all`. By default, the path segment will match the key name. You can use the 'path' key inside the resource definition to customize the path name. You can use the `inflect` option to change how path segments are generated: ``` $routes->resources('PaymentTypes', ['inflect' => 'underscore']); ``` Will generate routes like `/payment-types` instead of `/payment_types` ### Options: * 'id' - The regular expression fragment to use when matching IDs. By default, matches integer values and UUIDs. * 'inflect' - Choose the inflection method used on the resource name. Defaults to 'dasherize'. * 'only' - Only connect the specific list of actions. * 'actions' - Override the method names used for connecting actions. * 'map' - Additional resource routes that should be connected. If you define 'only' and 'map', make sure that your mapped methods are also in the 'only' list. * 'prefix' - Define a routing prefix for the resource controller. If the current scope defines a prefix, this prefix will be appended to it. * 'connectOptions' - Custom options for connecting the routes. * 'path' - Change the path so it doesn't match the resource name. E.g ArticlesController is available at `/posts` #### Parameters `string` $name A controller name to connect resource routes for. `callable|array` $options optional Options to use when generating REST routes, or a callback. `callable|null` $callback optional An optional callback to be executed in a nested scope. Nested scopes inherit the existing path and 'id' parameter. #### Returns `$this` ### scope() public ``` scope(string $path, callable|array $params, callable|null $callback = null): $this ``` Create a new routing scope. Scopes created with this method will inherit the properties of the scope they are added to. This means that both the current path and parameters will be appended to the supplied parameters. ### Special Keys in $params * `_namePrefix` Set a prefix used for named routes. The prefix is prepended to the name of any route created in a scope callback. #### Parameters `string` $path The path to create a scope for. `callable|array` $params Either the parameters to add to routes, or a callback. `callable|null` $callback optional The callback to invoke that builds the plugin routes. Only required when $params is defined. #### Returns `$this` #### Throws `InvalidArgumentException` when there is no callable parameter. ### setExtensions() public ``` setExtensions(array<string>|string $extensions): $this ``` Set the extensions in this route builder's scope. Future routes connected in through this builder will have the connected extensions applied. However, setting extensions does not modify existing routes. #### Parameters `array<string>|string` $extensions The extensions to set. #### Returns `$this` ### setRouteClass() public ``` setRouteClass(string $routeClass): $this ``` Set default route class. #### Parameters `string` $routeClass Class name. #### Returns `$this` Property Detail --------------- ### $\_collection protected The route collection routes should be added to. #### Type `Cake\Routing\RouteCollection` ### $\_extensions protected The extensions that should be set into the routes connected. #### Type `array<string>` ### $\_namePrefix protected Name prefix for connected routes. #### Type `string` ### $\_params protected The scope parameters if there are any. #### Type `array` ### $\_path protected The path prefix scope that this collection uses. #### Type `string` ### $\_resourceMap protected static Default HTTP request method => controller action map. #### Type `array<string, array>` ### $\_routeClass protected Default route class to use if none is provided in connect() options. #### Type `string` ### $middleware protected The list of middleware that routes in this builder get added during construction. #### Type `array<string>`
programming_docs
cakephp Class CompletionCommand Class CompletionCommand ======================== Provide command completion shells such as bash. **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 * [$commands](#%24commands) protected `Cake\Console\CommandCollection` * [$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 Main function Prints out the list of commands. * ##### [executeCommand()](#executeCommand()) public Execute another command with the provided set of arguments. * ##### [fetchTable()](#fetchTable()) public Convenience method to get a table instance. * ##### [getCommands()](#getCommands()) protected Get the list of defined commands. * ##### [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. * ##### [getOptions()](#getOptions()) protected Get the options for a command or subcommand * ##### [getRootName()](#getRootName()) public Get the root command name. * ##### [getSubcommands()](#getSubcommands()) protected Get the list of defined sub-commands. * ##### [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. * ##### [setCommandCollection()](#setCommandCollection()) public Set the command collection used to get completion data on. * ##### [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. * ##### [shellSubcommands()](#shellSubcommands()) protected Reflect the subcommands names out of a shell. 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 build #### 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 ``` Main function Prints out the list of commands. #### Parameters `Cake\Console\Arguments` $args The command arguments. `Cake\Console\ConsoleIo` $io The console io #### Returns `int` ### 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() ### getCommands() protected ``` getCommands(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): int ``` Get the list of defined commands. #### Parameters `Cake\Console\Arguments` $args The command arguments. `Cake\Console\ConsoleIo` $io The console io #### Returns `int` ### 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 ### getOptions() protected ``` getOptions(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): int ``` Get the options for a command or subcommand #### Parameters `Cake\Console\Arguments` $args The command arguments. `Cake\Console\ConsoleIo` $io The console io #### Returns `int` ### getRootName() public ``` getRootName(): string ``` Get the root command name. #### Returns `string` ### getSubcommands() protected ``` getSubcommands(Cake\Console\Arguments $args, Cake\Console\ConsoleIo $io): int ``` Get the list of defined sub-commands. #### Parameters `Cake\Console\Arguments` $args The command arguments. `Cake\Console\ConsoleIo` $io The console io #### Returns `int` ### 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` ### setCommandCollection() public ``` setCommandCollection(Cake\Console\CommandCollection $commands): void ``` Set the command collection used to get completion data on. #### Parameters `Cake\Console\CommandCollection` $commands The command collection #### 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` ### 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` ### shellSubcommands() protected ``` shellSubcommands(Cake\Console\Shell $shell): array<string> ``` Reflect the subcommands names out of a shell. #### Parameters `Cake\Console\Shell` $shell The shell to get commands for #### Returns `array<string>` 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` ### $commands protected #### Type `Cake\Console\CommandCollection` ### $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 Interface WidgetInterface Interface WidgetInterface ========================== Interface for input widgets. **Namespace:** [Cake\View\Widget](namespace-cake.view.widget) Method Summary -------------- * ##### [render()](#render()) public Converts the $data into one or many HTML elements. * ##### [secureFields()](#secureFields()) public Returns a list of fields that need to be secured for this widget. Method Detail ------------- ### render() public ``` render(array<string, mixed> $data, Cake\View\Form\ContextInterface $context): string ``` Converts the $data into one or many HTML elements. #### Parameters `array<string, mixed>` $data The data to render. `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 The data to render. #### Returns `array<string>` cakephp Interface AdapterInterface Interface AdapterInterface =========================== Http client adapter interface. **Namespace:** [Cake\Http\Client](namespace-cake.http.client) Method Summary -------------- * ##### [send()](#send()) public Send a request and get a response back. Method Detail ------------- ### send() public ``` send(Psr\Http\Message\RequestInterface $request, array<string, mixed> $options): arrayCake\Http\Client\Response> ``` Send a request and get a response back. #### Parameters `Psr\Http\Message\RequestInterface` $request The request object to send. `array<string, mixed>` $options Array of options for the stream. #### Returns `arrayCake\Http\Client\Response>` cakephp Class CakeException Class CakeException ==================== Base class that all CakePHP Exceptions extend. **Namespace:** [Cake\Core\Exception](namespace-cake.core.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 TruncateStrategy Class TruncateStrategy ======================= Fixture strategy that truncates all fixture ables at the end of test. **Namespace:** [Cake\TestSuite\Fixture](namespace-cake.testsuite.fixture) Property Summary ---------------- * [$fixtures](#%24fixtures) protected `arrayCake\Datasource\FixtureInterface>` * [$helper](#%24helper) protected `Cake\TestSuite\Fixture\FixtureHelper` Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Initialize strategy. * ##### [setupTest()](#setupTest()) public Called before each test run in each TestCase. * ##### [teardownTest()](#teardownTest()) public Called after each test run in each TestCase. Method Detail ------------- ### \_\_construct() public ``` __construct() ``` Initialize strategy. ### setupTest() public ``` setupTest(array<string> $fixtureNames): void ``` Called before each test run in each TestCase. #### Parameters `array<string>` $fixtureNames #### Returns `void` ### teardownTest() public ``` teardownTest(): void ``` Called after each test run in each TestCase. #### Returns `void` Property Detail --------------- ### $fixtures protected #### Type `arrayCake\Datasource\FixtureInterface>` ### $helper protected #### Type `Cake\TestSuite\Fixture\FixtureHelper`
programming_docs
cakephp Trait MailerAwareTrait Trait MailerAwareTrait ======================= Provides functionality for loading mailer classes onto properties of the host object. Example users of this trait are Cake\Controller\Controller and Cake\Console\Command. **Namespace:** [Cake\Mailer](namespace-cake.mailer) Method Summary -------------- * ##### [getMailer()](#getMailer()) protected Returns a mailer instance. Method Detail ------------- ### getMailer() protected ``` getMailer(string $name, array<string, mixed>|string|null $config = null): Cake\Mailer\Mailer ``` Returns a mailer instance. #### Parameters `string` $name Mailer's name. `array<string, mixed>|string|null` $config optional Array of configs, or profile name string. #### Returns `Cake\Mailer\Mailer` #### Throws `Cake\Mailer\Exception\MissingMailerException` if undefined mailer class. cakephp Class HasOne Class 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. An example of a HasOne association would be User has one Profile. **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 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 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): 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() 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 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 MysqlStatement Class MysqlStatement ===================== Statement class meant to be used by a MySQL PDO 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 ---------------- * [$\_bufferResults](#%24_bufferResults) protected `bool` Whether to buffer results in php * [$\_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. * ##### [bufferResults()](#bufferResults()) public Whether to buffer results in php * ##### [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. You can pass PDO compatible constants for binding values with a type or optionally any type name registered in the Type class. Any value will be converted to the valid type representation if needed. It is not allowed to combine positional and named variables in the same statement ### Examples: ``` $statement->bindValue(1, 'a title'); $statement->bindValue(2, 5, PDO::INT); $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` ### bufferResults() public ``` bufferResults(bool $buffer): $this ``` Whether to buffer results in php #### Parameters `bool` $buffer Toggle buffering #### Returns `$this` ### 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 #### 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 --------------- ### $\_bufferResults protected Whether to buffer results in php #### Type `bool` ### $\_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 LabelWidget Class LabelWidget ================== Form 'widget' for creating labels. 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 ConnectionManager Class ConnectionManager ======================== Manages and loads instances of Connection Provides an interface to loading and creating connection objects. Acts as a registry for the connections defined in an application. Provides an interface for loading and enumerating connections defined in config/app.php **Namespace:** [Cake\Datasource](namespace-cake.datasource) Property Summary ---------------- * [$\_aliasMap](#%24_aliasMap) protected static `array<string>` A map of connection aliases. * [$\_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 driver class names * [$\_registry](#%24_registry) protected static `Cake\Datasource\ConnectionRegistry` The ConnectionRegistry used by the manager. Method Summary -------------- * ##### [alias()](#alias()) public static Set one or more connection aliases. * ##### [configured()](#configured()) public static Returns an array containing the named configurations * ##### [drop()](#drop()) public static Drops a constructed adapter. * ##### [dropAlias()](#dropAlias()) public static Drop an alias. * ##### [get()](#get()) public static Get a connection. * ##### [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. * ##### [parseDsn()](#parseDsn()) public static Parses a DSN into a valid connection configuration * ##### [setConfig()](#setConfig()) public static Configure a new connection object. * ##### [setDsnClassMap()](#setDsnClassMap()) public static Updates the DSN class map for this class. Method Detail ------------- ### alias() public static ``` alias(string $source, string $alias): void ``` Set one or more connection aliases. Connection aliases allow you to rename active connections without overwriting the aliased connection. This is most useful in the test-suite for replacing connections with their test variant. Defined aliases will take precedence over normal connection names. For example, if you alias 'default' to 'test', fetching 'default' will always return the 'test' connection as long as the alias is defined. You can remove aliases with ConnectionManager::dropAlias(). ### Usage ``` // Make 'things' resolve to 'test_things' connection ConnectionManager::alias('test_things', 'things'); ``` #### Parameters `string` $source The existing connection to alias. `string` $alias The alias name that resolves to `$source`. #### Returns `void` ### 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` ### dropAlias() public static ``` dropAlias(string $alias): void ``` Drop an alias. Removes an alias from ConnectionManager. Fetching the aliased connection may fail if there is no other connection with that name. #### Parameters `string` $alias The connection alias to drop #### Returns `void` ### get() public static ``` get(string $name, bool $useAliases = true): Cake\Datasource\ConnectionInterface ``` Get a connection. If the connection has not been constructed an instance will be added to the registry. This method will use any aliases that have been defined. If you want the original unaliased connections pass `false` as second parameter. #### Parameters `string` $name The connection name. `bool` $useAliases optional Set to false to not use aliased connections. #### Returns `Cake\Datasource\ConnectionInterface` #### Throws `Cake\Datasource\Exception\MissingDatasourceConfigException` When config data is missing. ### 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>` ### parseDsn() public static ``` parseDsn(string $config): 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\Database\Driver\Mysql://localhost:3306/database?className=Cake\Database\Connection'; $config = ConnectionManager::parseDsn($dsn); $dsn = 'Cake\Database\Connection://localhost:3306/database?driver=Cake\Database\Driver\Mysql'; $config = ConnectionManager::parseDsn($dsn); ``` For all classes, the value of `scheme` is set as the value of both the `className` and `driver` unless they have been otherwise specified. Note that query-string arguments are also parsed and set as values in the returned configuration. #### Parameters `string` $config The DSN string to convert to a configuration array #### Returns `array<string, mixed>` ### setConfig() public static ``` setConfig(array<string, mixed>|string $key, object|array<string, mixed>|null $config = null): void ``` Configure a new connection object. The connection will not be constructed until it is first used. #### Parameters `array<string, mixed>|string` $key The name of the connection config, or an array of multiple configs. `object|array<string, mixed>|null` $config optional An array of name => config data for adapter. #### Returns `void` #### Throws `Cake\Core\Exception\CakeException` When trying to modify an existing config. #### See Also \Cake\Core\StaticConfigTrait::config() ### 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` Property Detail --------------- ### $\_aliasMap protected static A map of connection aliases. #### Type `array<string>` ### $\_config protected static Configuration sets. #### Type `array<string, mixed>` ### $\_dsnClassMap protected static An array mapping url schemes to fully qualified driver class names #### Type `array<string, string>` ### $\_registry protected static The ConnectionRegistry used by the manager. #### Type `Cake\Datasource\ConnectionRegistry`
programming_docs
cakephp Class Query Class 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. **Namespace:** [Cake\ORM](namespace-cake.orm) **See:** \Cake\Collection\CollectionInterface For a full description of the collection methods supported by this class Constants --------- * `int` **APPEND** ``` 0 ``` Indicates that the operation should append to the list * `string` **JOIN\_TYPE\_INNER** ``` 'INNER' ``` * `string` **JOIN\_TYPE\_LEFT** ``` 'LEFT' ``` * `string` **JOIN\_TYPE\_RIGHT** ``` 'RIGHT' ``` * `bool` **OVERWRITE** ``` true ``` Indicates that the operation should overwrite the list * `int` **PREPEND** ``` 1 ``` Indicates that the operation should prepend to the list Property Summary ---------------- * [$\_autoFields](#%24_autoFields) protected `bool|null` Tracks whether the original query should include fields from the top level table. * [$\_beforeFindFired](#%24_beforeFindFired) protected `bool` True if the beforeFind event has already been triggered for this query * [$\_cache](#%24_cache) protected `Cake\Datasource\QueryCacher|null` A query cacher instance if this query has caching enabled. * [$\_connection](#%24_connection) protected `Cake\Database\Connection` Connection instance to be used to execute this query. * [$\_counter](#%24_counter) protected `callable|null` A callable function that can be used to calculate the total amount of records this query will match when not using `limit` * [$\_deleteParts](#%24_deleteParts) protected deprecated `array<string>` The list of query clauses to traverse for generating a DELETE statement * [$\_dirty](#%24_dirty) protected `bool` Indicates whether internal state of this query was changed, this is used to discard internal cached objects such as the transformed query or the reference to the executed statement. * [$\_eagerLoaded](#%24_eagerLoaded) protected `bool` Whether the query is standalone or the product of an eager load operation. * [$\_eagerLoader](#%24_eagerLoader) protected `Cake\ORM\EagerLoader|null` Instance of a class responsible for storing association containments and for eager loading them when this query is executed * [$\_formatters](#%24_formatters) protected `array<callable>` List of formatter classes or callbacks that will post-process the results when fetched * [$\_functionsBuilder](#%24_functionsBuilder) protected `Cake\Database\FunctionsBuilder|null` Instance of functions builder object used for generating arbitrary SQL functions. * [$\_hasFields](#%24_hasFields) protected `bool|null` Whether the user select any fields before being executed, this is used to determined if any fields should be automatically be selected. * [$\_hydrate](#%24_hydrate) protected `bool` Whether to hydrate results into entity objects * [$\_insertParts](#%24_insertParts) protected deprecated `array<string>` The list of query clauses to traverse for generating an INSERT statement * [$\_iterator](#%24_iterator) protected `Cake\Database\StatementInterface|null` Statement object resulting from executing this query. * [$\_mapReduce](#%24_mapReduce) protected `array` List of map-reduce routines that should be applied over the query result * [$\_options](#%24_options) protected `array` Holds any custom options passed using applyOptions that could not be processed by any method in this class. * [$\_parts](#%24_parts) protected `array<string, mixed>` List of SQL parts that will be used to build this query. * [$\_repository](#%24_repository) public @property `Cake\ORM\Table` Instance of a table object this query is bound to. * [$\_resultDecorators](#%24_resultDecorators) protected `array<callable>` A list of callback functions to be called to alter each row from resulting statement upon retrieval. Each one of the callback function will receive the row array as first argument. * [$\_results](#%24_results) protected `iterable|null` A ResultSet. * [$\_resultsCount](#%24_resultsCount) protected `int|null` The COUNT(\*) for the query. * [$\_selectParts](#%24_selectParts) protected deprecated `array<string>` The list of query clauses to traverse for generating a SELECT statement * [$\_selectTypeMap](#%24_selectTypeMap) protected `Cake\Database\TypeMap|null` The Type map for fields in the select clause * [$\_type](#%24_type) protected `string` Type of this query (select, insert, update, delete). * [$\_typeMap](#%24_typeMap) protected `Cake\Database\TypeMap|null` * [$\_updateParts](#%24_updateParts) protected deprecated `array<string>` The list of query clauses to traverse for generating an UPDATE statement * [$\_useBufferedResults](#%24_useBufferedResults) protected `bool` Boolean for tracking whether buffered results are enabled. * [$\_valueBinder](#%24_valueBinder) protected `Cake\Database\ValueBinder|null` The object responsible for generating query placeholders and temporarily store values associated to each of those. * [$aliasingEnabled](#%24aliasingEnabled) protected `bool` Whether aliases are generated for fields. * [$typeCastEnabled](#%24typeCastEnabled) protected `bool` Tracking flag to disable casting Method Summary -------------- * ##### [\_\_call()](#__call()) public Enables calling methods from the result set as if they were from this class * ##### [\_\_clone()](#__clone()) public Handles clearing iterator and cloning all expressions and value binders. * ##### [\_\_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 Returns string representation of this query (complete SQL statement). * ##### [\_addAssociationsToTypeMap()](#_addAssociationsToTypeMap()) protected Used to recursively add contained association column types to the query. * ##### [\_addDefaultFields()](#_addDefaultFields()) protected Inspects if there are any set fields for selecting, otherwise adds all the fields for the default table. * ##### [\_addDefaultSelectTypes()](#_addDefaultSelectTypes()) protected Sets the default types for converting the fields in the select clause * ##### [\_conjugate()](#_conjugate()) protected Helper function used to build conditions by composing QueryExpression objects. * ##### [\_decorateResults()](#_decorateResults()) protected Decorates the results iterator with MapReduce routines and formatters * ##### [\_decorateStatement()](#_decorateStatement()) protected Auxiliary function used to wrap the original statement from the driver with any registered callbacks. * ##### [\_decoratorClass()](#_decoratorClass()) protected Returns the name of the class to be used for decorating results * ##### [\_dirty()](#_dirty()) protected Marks a query as dirty, removing any preprocessed information from in memory caching such as previous results * ##### [\_execute()](#_execute()) protected Executes this query and returns a ResultSet object containing the results. This will also setup the correct statement class in order to eager load deep associations. * ##### [\_expressionsVisitor()](#_expressionsVisitor()) protected Query parts traversal method used by traverseExpressions() * ##### [\_makeJoin()](#_makeJoin()) protected Returns an array that can be passed to the join method describing a single join clause * ##### [\_performCount()](#_performCount()) protected Performs and returns the COUNT(\*) for the query. * ##### [\_transformQuery()](#_transformQuery()) protected Applies some defaults to the query object before it is executed. * ##### [addDefaultTypes()](#addDefaultTypes()) public Hints this object to associate the correct types when casting conditions for the database. This is done by extracting the field types from the schema associated to the passed table object. This prevents the user from repeating themselves when specifying conditions. * ##### [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. * ##### [andHaving()](#andHaving()) public Connects any previously defined set of conditions to the provided list using the AND operator in the HAVING clause. This method operates in exactly the same way as the method `andWhere()` does. Please refer to its documentation for an insight on how to using each parameter. * ##### [andWhere()](#andWhere()) public @method Connects any previously defined set of conditions to the provided list using the AND operator. {@see \Cake\Database\Query::andWhere()} * ##### [append()](#append()) public @method Appends more rows to the result of the query. * ##### [applyOptions()](#applyOptions()) public Populates or adds parts to current query clauses using an array. This is handy for passing all query clauses at once. * ##### [bind()](#bind()) public Associates a query placeholder to a value and a type. * ##### [cache()](#cache()) public Enable result caching for this query. * ##### [chunk()](#chunk()) public @method Groups the results in arrays of $size rows each. * ##### [clause()](#clause()) public Returns any data that was stored in the specified clause. This is useful for modifying any internal part of the query and it is used by the SQL dialects to transform the query accordingly before it is executed. The valid clauses that can be retrieved are: delete, update, set, insert, values, select, distinct, from, join, set, where, group, having, order, limit, offset and union. * ##### [cleanCopy()](#cleanCopy()) public Creates a copy of this current query, triggers beforeFind and resets some state. * ##### [clearContain()](#clearContain()) public Clears the contained associations from the current query. * ##### [clearResult()](#clearResult()) public Clears the internal result cache and the internal count value from the current query object. * ##### [combine()](#combine()) public @method Returns the values of the column $v index by column $k, and grouped by $g. * ##### [contain()](#contain()) public Sets the list of associations that should be eagerly loaded along with this query. The list of associated tables passed must have been previously set as associations using the Table API. * ##### [count()](#count()) public Returns the total amount of results for the query. * ##### [countBy()](#countBy()) public @method Returns the number of unique values for a column * ##### [counter()](#counter()) public Registers a callable function that will be executed when the `count` method in this query is called. The return value for the function will be set as the return value of the `count` method. * ##### [decorateResults()](#decorateResults()) public Registers a callback to be executed for each result that is fetched from the result set, the callback function will receive as first parameter an array with the raw data from the database for every row that is fetched and must return the row with any possible modifications. * ##### [delete()](#delete()) public Create a delete query. * ##### [disableAutoFields()](#disableAutoFields()) public Disables automatically appending fields. * ##### [disableBufferedResults()](#disableBufferedResults()) public Disables buffered results. * ##### [disableHydration()](#disableHydration()) public Disable hydrating entities. * ##### [disableResultsCasting()](#disableResultsCasting()) public Disables result casting. * ##### [distinct()](#distinct()) public Adds a `DISTINCT` clause to the query to remove duplicates from the result set. This clause can only be used for select statements. * ##### [each()](#each()) public @method Passes each of the query results to the callable * ##### [eagerLoaded()](#eagerLoaded()) public Sets the query instance to be an eager loaded query. If no argument is passed, the current configured query `_eagerLoaded` value is returned. * ##### [enableAutoFields()](#enableAutoFields()) public Sets whether the ORM should automatically append fields. * ##### [enableBufferedResults()](#enableBufferedResults()) public Enables/Disables buffered results. * ##### [enableHydration()](#enableHydration()) public Toggle hydrating entities. * ##### [enableResultsCasting()](#enableResultsCasting()) public Enables result casting. * ##### [epilog()](#epilog()) public A string or expression that will be appended to the generated query * ##### [every()](#every()) public @method Returns true if all the results pass the callable test * ##### [execute()](#execute()) public Compiles the SQL representation of this query and executes it using the configured connection object. Returns the resulting statement object. * ##### [expr()](#expr()) public Returns a new QueryExpression object. This is a handy function when building complex queries using a fluent interface. You can also override this function in subclasses to use a more specialized QueryExpression class if required. * ##### [extract()](#extract()) public @method Extracts a single column from each row * ##### [filter()](#filter()) public @method Keeps the results using passing the callable test * ##### [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 Get the first result from the executing query or raise an exception. * ##### [formatResults()](#formatResults()) public Registers a new formatter callback function that is to be executed when trying to fetch the results from the database. * ##### [from()](#from()) public Adds a single or multiple tables to be used in the FROM clause for this query. Tables can be passed as an array of strings, array of expression objects, a single expression or a single string. * ##### [func()](#func()) public Returns an instance of a functions builder object that can be used for generating arbitrary SQL functions. * ##### [getConnection()](#getConnection()) public Gets the connection instance to be used for executing and transforming this query. * ##### [getContain()](#getContain()) public * ##### [getDefaultTypes()](#getDefaultTypes()) public Gets default types of current type map. * ##### [getEagerLoader()](#getEagerLoader()) public Returns the currently configured instance. * ##### [getIterator()](#getIterator()) public Executes this query and returns a results iterator. This function is required for implementing the IteratorAggregate interface and allows the query to be iterated without having to call execute() manually, thus making it look like a result set instead of the query itself. * ##### [getMapReducers()](#getMapReducers()) public Returns the list of previously registered map reduce routines. * ##### [getOptions()](#getOptions()) public Returns an array with the custom options that were applied to this query and that were not already processed by another method in this class. * ##### [getRepository()](#getRepository()) public @method Returns the default table object that will be used by this query, that is, the table that will appear in the from clause. * ##### [getResultFormatters()](#getResultFormatters()) public Returns the list of previously registered format routines. * ##### [getSelectTypeMap()](#getSelectTypeMap()) public Gets the TypeMap class where the types for each of the fields in the select clause are stored. * ##### [getTypeMap()](#getTypeMap()) public Returns the existing type map. * ##### [getValueBinder()](#getValueBinder()) public Returns the currently used ValueBinder instance. * ##### [group()](#group()) public Adds a single or multiple fields to be used in the GROUP BY clause for this query. Fields can be passed as an array of strings, array of expression objects, a single expression or a single string. * ##### [groupBy()](#groupBy()) public @method In-memory group all results by the value of a column. * ##### [having()](#having()) public Adds a condition or set of conditions to be used in the `HAVING` clause for this query. This method operates in exactly the same way as the method `where()` does. Please refer to its documentation for an insight on how to using each parameter. * ##### [identifier()](#identifier()) public Creates an expression that refers to an identifier. Identifiers are used to refer to field names and allow the SQL compiler to apply quotes or escape the identifier. * ##### [indexBy()](#indexBy()) public @method Returns the results indexed by the value of a column. * ##### [innerJoin()](#innerJoin()) public Adds a single `INNER JOIN` clause to the query. * ##### [innerJoinWith()](#innerJoinWith()) public Creates an INNER JOIN with the passed association table while preserving the foreign key matching and the custom conditions that were originally set for it. * ##### [insert()](#insert()) public Create an insert query. * ##### [into()](#into()) public Set the table name for insert queries. * ##### [isAutoFieldsEnabled()](#isAutoFieldsEnabled()) public Gets whether the ORM should automatically append fields. * ##### [isBufferedResultsEnabled()](#isBufferedResultsEnabled()) public Returns whether buffered results are enabled/disabled. * ##### [isEagerLoaded()](#isEagerLoaded()) public Returns the current configured query `_eagerLoaded` value * ##### [isEmpty()](#isEmpty()) public @method Returns true if this query found no results. * ##### [isHydrationEnabled()](#isHydrationEnabled()) public Returns the current hydration mode. * ##### [isResultsCastingEnabled()](#isResultsCastingEnabled()) public Returns whether result casting is enabled/disabled. * ##### [join()](#join()) public Adds a single or multiple tables to be used as JOIN clauses to this query. Tables can be passed as an array of strings, an array describing the join parts, an array with multiple join descriptions, or a single string. * ##### [jsonSerialize()](#jsonSerialize()) public Executes the query and converts the result set into JSON. * ##### [last()](#last()) public @method Return the last row of the query result * ##### [leftJoin()](#leftJoin()) public Adds a single `LEFT JOIN` clause to the query. * ##### [leftJoinWith()](#leftJoinWith()) public Creates a LEFT JOIN with the passed association table while preserving the foreign key matching and the custom conditions that were originally set for it. * ##### [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. * ##### [map()](#map()) public @method Modifies each of the results using the callable * ##### [mapReduce()](#mapReduce()) public Register a new MapReduce routine to be executed on top of the database results Both the mapper and caller callable should be invokable objects. * ##### [matching()](#matching()) public Adds filtering conditions to this query to only bring rows that have a relation to another from an associated table, based on conditions in the associated table. * ##### [max()](#max()) public @method Returns the maximum value for a single column in all the results. * ##### [min()](#min()) public @method Returns the minimum value for a single column in all the results. * ##### [modifier()](#modifier()) public Adds a single or multiple `SELECT` modifiers to be used in the `SELECT`. * ##### [nest()](#nest()) public @method Creates a tree structure by nesting the values of column $p into that with the same value for $k using $n as the nesting key. * ##### [newExpr()](#newExpr()) public Returns a new QueryExpression object. This is a handy function when building complex queries using a fluent interface. You can also override this function in subclasses to use a more specialized QueryExpression class if required. * ##### [notMatching()](#notMatching()) public Adds filtering conditions to this query to only bring rows that have no match to another from an associated table, based on conditions in the associated table. * ##### [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. * ##### [orderAsc()](#orderAsc()) public Add an ORDER BY clause with an ASC direction. * ##### [orderDesc()](#orderDesc()) public Add an ORDER BY clause with a DESC direction. * ##### [page()](#page()) public Set the page of results you want. * ##### [reduce()](#reduce()) public @method Folds all the results into a single value using the callable. * ##### [reject()](#reject()) public @method Removes the results passing the callable test * ##### [removeJoin()](#removeJoin()) public Remove a join if it has been defined. * ##### [repository()](#repository()) public Set the default Table object that will be used by this query and form the `FROM` clause. * ##### [rightJoin()](#rightJoin()) public Adds a single `RIGHT JOIN` clause to the query. * ##### [rowCountAndClose()](#rowCountAndClose()) public Executes the SQL of this query and immediately closes the statement before returning the row count of records changed. * ##### [sample()](#sample()) public @method In-memory shuffle the results and return a subset of them. * ##### [select()](#select()) public Adds new fields to be returned by a `SELECT` statement when this query is executed. Fields can be passed as an array of strings, array of expression objects, a single expression or a single string. * ##### [selectAllExcept()](#selectAllExcept()) public All the fields associated with the passed table except the excluded fields will be added to the select clause of the query. Passed excluded fields should not be aliased. After the first call to this method, a second call cannot be used to remove fields that have already been added to the query by the first. If you need to change the list after the first call, pass overwrite boolean true which will reset the select clause removing all previous additions. * ##### [set()](#set()) public Set one or many fields to update. * ##### [setConnection()](#setConnection()) public Sets the connection instance to be used for executing and transforming this query. * ##### [setDefaultTypes()](#setDefaultTypes()) public Overwrite the default type mappings for fields in the implementing object. * ##### [setEagerLoader()](#setEagerLoader()) public Sets the instance of the eager loader class to use for loading associations and storing containments. * ##### [setResult()](#setResult()) public Set the result set for a query. * ##### [setSelectTypeMap()](#setSelectTypeMap()) public Sets the TypeMap class where the types for each of the fields in the select clause are stored. * ##### [setTypeMap()](#setTypeMap()) public Creates a new TypeMap if $typeMap is an array, otherwise exchanges it for the given one. * ##### [setValueBinder()](#setValueBinder()) public Overwrite the current value binder * ##### [shuffle()](#shuffle()) public @method In-memory randomize the order the results are returned * ##### [skip()](#skip()) public @method Skips some rows from the start of the query result. * ##### [some()](#some()) public @method Returns true if at least one of the results pass the callable test * ##### [sortBy()](#sortBy()) public @method Sorts the query with the callback * ##### [sql()](#sql()) public Returns the SQL representation of this object. * ##### [stopWhen()](#stopWhen()) public @method Returns each row until the callable returns true. * ##### [subquery()](#subquery()) public static Returns a new Query that has automatic field aliasing disabled. * ##### [sumOf()](#sumOf()) public @method Returns the sum of all values for a single column * ##### [take()](#take()) public @method In-memory limit and offset for the query results. * ##### [toArray()](#toArray()) public @method Returns a key-value array with the results of this query. * ##### [toList()](#toList()) public @method Returns a numerically indexed array with the results of this query. * ##### [traverse()](#traverse()) public Will iterate over every specified part. Traversing functions can aggregate results using variables in the closure or instance variables. This function is commonly used as a way for traversing all query parts that are going to be used for constructing a query. * ##### [traverseExpressions()](#traverseExpressions()) public This function works similar to the traverse() function, with the difference that it does a full depth traversal of the entire expression tree. This will execute the provided callback function for each ExpressionInterface object that is stored inside this query at any nesting depth in any part of the query. * ##### [traverseParts()](#traverseParts()) public Will iterate over the provided parts. * ##### [triggerBeforeFind()](#triggerBeforeFind()) public Trigger the beforeFind event on the query's repository object. * ##### [type()](#type()) public Returns the type of this query (select, insert, update, delete) * ##### [union()](#union()) public Adds a complete query to be used in conjunction with an UNION operator with this query. This is used to combine the result set of this query with the one that will be returned by the passed query. You can add as many queries as you required by calling multiple times this method with different queries. * ##### [unionAll()](#unionAll()) public Adds a complete query to be used in conjunction with the UNION ALL operator with this query. This is used to combine the result set of this query with the one that will be returned by the passed query. You can add as many queries as you required by calling multiple times this method with different queries. * ##### [update()](#update()) public Create an update query. * ##### [values()](#values()) public Set the values for an insert 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. * ##### [whereInList()](#whereInList()) public Adds an IN condition or set of conditions to be used in the WHERE clause for this query. * ##### [whereNotInList()](#whereNotInList()) public Adds a NOT IN condition or set of conditions to be used in the WHERE clause for this query. * ##### [whereNotInListOrNull()](#whereNotInListOrNull()) public Adds a NOT IN condition or set of conditions to be used in the WHERE clause for this query. This also allows the field to be null with a IS NULL condition since the null value would cause the NOT IN condition to always fail. * ##### [whereNotNull()](#whereNotNull()) public Convenience method that adds a NOT NULL condition to the query * ##### [whereNull()](#whereNull()) public Convenience method that adds a IS NULL condition to the query * ##### [window()](#window()) public Adds a named window expression. * ##### [with()](#with()) public Adds a new common table expression (CTE) to the query. * ##### [zip()](#zip()) public @method Returns the first result of both the query and $c in an array, then the second results and so on. * ##### [zipWith()](#zipWith()) public @method Returns each of the results out of calling $c with the first rows of the query and each of the items, then the second rows and so on. Method Detail ------------- ### \_\_call() public ``` __call(string $method, array $arguments): mixed ``` Enables calling methods from the result set as if they were from this class #### Parameters `string` $method the method to call `array` $arguments list of arguments for the method to call #### Returns `mixed` #### Throws `BadMethodCallException` if the method is called for a non-select query ### \_\_clone() public ``` __clone(): void ``` Handles clearing iterator and cloning all expressions and value binders. Handles cloning eager loaders. #### Returns `void` ### \_\_construct() public ``` __construct(Cake\Database\Connection $connection, Cake\ORM\Table $table) ``` Constructor #### Parameters `Cake\Database\Connection` $connection The connection object `Cake\ORM\Table` $table The table this query is starting on ### \_\_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 ``` Returns string representation of this query (complete SQL statement). #### Returns `string` ### \_addAssociationsToTypeMap() protected ``` _addAssociationsToTypeMap(Cake\ORM\Table $table, Cake\Database\TypeMap $typeMap, array<string, array> $associations): void ``` Used to recursively add contained association column types to the query. #### Parameters `Cake\ORM\Table` $table The table instance to pluck associations from. `Cake\Database\TypeMap` $typeMap The typemap to check for columns in. This typemap is indirectly mutated via {@link \Cake\ORM\Query::addDefaultTypes()} `array<string, array>` $associations The nested tree of associations to walk. #### Returns `void` ### \_addDefaultFields() protected ``` _addDefaultFields(): void ``` Inspects if there are any set fields for selecting, otherwise adds all the fields for the default table. #### Returns `void` ### \_addDefaultSelectTypes() protected ``` _addDefaultSelectTypes(): void ``` Sets the default types for converting the fields in the select clause #### Returns `void` ### \_conjugate() protected ``` _conjugate(string $part, Cake\Database\ExpressionInterfaceClosure|array|string|null $append, string $conjunction, array<string, string> $types): void ``` Helper function used to build conditions by composing QueryExpression objects. #### Parameters `string` $part Name of the query part to append the new part to `Cake\Database\ExpressionInterfaceClosure|array|string|null` $append Expression or builder function to append. to append. `string` $conjunction type of conjunction to be used to operate part `array<string, string>` $types Associative array of type names used to bind values to query #### Returns `void` ### \_decorateResults() protected ``` _decorateResults(Traversable $result): Cake\Datasource\ResultSetInterface ``` Decorates the results iterator with MapReduce routines and formatters #### Parameters `Traversable` $result Original results #### Returns `Cake\Datasource\ResultSetInterface` ### \_decorateStatement() protected ``` _decorateStatement(Cake\Database\StatementInterface $statement): Cake\Database\Statement\CallbackStatementCake\Database\StatementInterface ``` Auxiliary function used to wrap the original statement from the driver with any registered callbacks. #### Parameters `Cake\Database\StatementInterface` $statement to be decorated #### Returns `Cake\Database\Statement\CallbackStatementCake\Database\StatementInterface` ### \_decoratorClass() protected ``` _decoratorClass(): string ``` Returns the name of the class to be used for decorating results #### Returns `string` ### \_dirty() protected ``` _dirty(): void ``` Marks a query as dirty, removing any preprocessed information from in memory caching such as previous results #### Returns `void` ### \_execute() protected ``` _execute(): Cake\Datasource\ResultSetInterface ``` Executes this query and returns a ResultSet object containing the results. This will also setup the correct statement class in order to eager load deep associations. #### Returns `Cake\Datasource\ResultSetInterface` ### \_expressionsVisitor() protected ``` _expressionsVisitor(Cake\Database\ExpressionInterface|arrayCake\Database\ExpressionInterface> $expression, Closure $callback): void ``` Query parts traversal method used by traverseExpressions() #### Parameters `Cake\Database\ExpressionInterface|arrayCake\Database\ExpressionInterface>` $expression Query expression or array of expressions. `Closure` $callback The callback to be executed for each ExpressionInterface found inside this query. #### Returns `void` ### \_makeJoin() protected ``` _makeJoin(array<string, mixed>|string $table, Cake\Database\ExpressionInterface|array|string $conditions, string $type): array ``` Returns an array that can be passed to the join method describing a single join clause #### Parameters `array<string, mixed>|string` $table The table to join with `Cake\Database\ExpressionInterface|array|string` $conditions The conditions to use for joining. `string` $type the join type to use #### Returns `array` ### \_performCount() protected ``` _performCount(): int ``` Performs and returns the COUNT(\*) for the query. #### Returns `int` ### \_transformQuery() protected ``` _transformQuery(): void ``` Applies some defaults to the query object before it is executed. Specifically add the FROM clause, adds default table fields if none are specified and applies the joins required to eager load associations defined using `contain` It also sets the default types for the columns in the select clause #### Returns `void` #### See Also \Cake\Database\Query::execute() ### addDefaultTypes() public ``` addDefaultTypes(Cake\ORM\Table $table): $this ``` Hints this object to associate the correct types when casting conditions for the database. This is done by extracting the field types from the schema associated to the passed table object. This prevents the user from repeating themselves when specifying conditions. This method returns the same query object for chaining. #### Parameters `Cake\ORM\Table` $table The table to pull types from #### Returns `$this` ### 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` #### Throws `RuntimeException` if this method is called on a non-select Query. ### andHaving() public ``` andHaving(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array<string, string> $types = []): $this ``` Connects any previously defined set of conditions to the provided list using the AND operator in the HAVING clause. This method operates in exactly the same way as the method `andWhere()` does. Please refer to its documentation for an insight on how to using each parameter. Having fields are not suitable for use with user supplied data as they are not sanitized by the query builder. #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions The AND conditions for HAVING. `array<string, string>` $types optional Associative array of type names used to bind values to query #### Returns `$this` #### See Also \Cake\Database\Query::andWhere() ### andWhere() public @method ``` andWhere(Cake\Database\ExpressionInterfaceClosure|array|string $conditions, array $types = []): $this ``` Connects any previously defined set of conditions to the provided list using the AND operator. {@see \Cake\Database\Query::andWhere()} It is important to notice that when calling this function, any previous set of conditions defined for this query will be treated as a single argument for the AND operator. This function will not only operate the most recently defined condition, but all the conditions as a whole. When using an array for defining conditions, creating constraints form each array entry will use the same logic as with the `where()` function. This means that each array entry will be joined to the other using the AND operator, unless you nest the conditions in the array using other operator. ### Examples: ``` $query->where(['title' => 'Hello World')->andWhere(['author_id' => 1]); ``` Will produce: `WHERE title = 'Hello World' AND author_id = 1` ``` $query ->where(['OR' => ['published' => false, 'published is NULL']]) ->andWhere(['author_id' => 1, 'comments_count >' => 10]) ``` Produces: `WHERE (published = 0 OR published IS NULL) AND author_id = 1 AND comments_count > 10` ``` $query ->where(['title' => 'Foo']) ->andWhere(function ($exp, $query) { return $exp ->or(['author_id' => 1]) ->add(['author_id' => 2]); }); ``` Generates the following conditions: `WHERE (title = 'Foo') AND (author_id = 1 OR author_id = 2)` #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string` $conditions `array` $types optional #### Returns `$this` ### append() public @method ``` append(arrayTraversable $items): Cake\Collection\CollectionInterface ``` Appends more rows to the result of the query. #### Parameters `arrayTraversable` $items #### Returns `Cake\Collection\CollectionInterface` ### 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 method accepts the following query clause related options: * 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 All other options will not affect the query, but will be stored as custom options that can be read via `getOptions()`. Furthermore they are automatically passed to `Model.beforeFind`. ### 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) ``` Custom options can be read via `getOptions()`: ``` $query->applyOptions([ 'fields' => ['id', 'name'], 'custom' => 'value', ]); ``` Here `$options` will hold `['custom' => 'value']` (the `fields` option will be applied to the query instead of being stored, as it's a query clause related option): ``` $options = $query->getOptions(); ``` #### Parameters `array<string, mixed>` $options The options to be applied #### Returns `$this` #### See Also getOptions() ### bind() public ``` bind(string|int $param, mixed $value, string|int|null $type = null): $this ``` Associates a query placeholder to a value and a type. ``` $query->bind(':id', 1, 'integer'); ``` #### 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 `$this` ### cache() public ``` cache(Closure|string|false $key, Psr\SimpleCache\CacheInterface|string $config = 'default'): $this ``` Enable result caching for this query. If a query has caching enabled, it will do the following when executed: * Check the cache for $key. If there are results no SQL will be executed. Instead the cached results will be returned. * When the cached data is stale/missing the result set will be cached as the query is executed. ### Usage ``` // Simple string key + config $query->cache('my_key', 'db_results'); // Function to generate key. $query->cache(function ($q) { $key = serialize($q->clause('select')); $key .= serialize($q->clause('where')); return md5($key); }); // Using a pre-built cache engine. $query->cache('my_key', $engine); // Disable caching $query->cache(false); ``` #### Parameters `Closure|string|false` $key Either the cache key or a function to generate the cache key. When using a function, this query instance will be supplied as an argument. `Psr\SimpleCache\CacheInterface|string` $config optional Either the name of the cache config to use, or a cache config instance. #### Returns `$this` #### Throws `RuntimeException` When you attempt to cache a non-select query. ### chunk() public @method ``` chunk(int $size): Cake\Collection\CollectionInterface ``` Groups the results in arrays of $size rows each. #### Parameters `int` $size #### Returns `Cake\Collection\CollectionInterface` ### clause() public ``` clause(string $name): mixed ``` Returns any data that was stored in the specified clause. This is useful for modifying any internal part of the query and it is used by the SQL dialects to transform the query accordingly before it is executed. The valid clauses that can be retrieved are: delete, update, set, insert, values, select, distinct, from, join, set, where, group, having, order, limit, offset and union. The return value for each of those parts may vary. Some clauses use QueryExpression to internally store their state, some use arrays and others may use booleans or integers. This is summary of the return types for each clause. * update: string The name of the table to update * set: QueryExpression * insert: array, will return an array containing the table + columns. * values: ValuesExpression * select: array, will return empty array when no fields are set * distinct: boolean * from: array of tables * join: array * set: array * where: QueryExpression, returns null when not set * group: array * having: QueryExpression, returns null when not set * order: OrderByExpression, returns null when not set * limit: integer or QueryExpression, null when not set * offset: integer or QueryExpression, null when not set * union: array #### Parameters `string` $name name of the clause to be returned #### Returns `mixed` #### Throws `InvalidArgumentException` When the named clause does not exist. ### cleanCopy() public ``` cleanCopy(): static ``` Creates a copy of this current query, triggers beforeFind and resets some state. The following state will be cleared: * autoFields * limit * offset * map/reduce functions * result formatters * order * containments This method creates query clones that are useful when working with subqueries. #### Returns `static` ### clearContain() public ``` clearContain(): $this ``` Clears the contained associations from the current query. #### Returns `$this` ### clearResult() public ``` clearResult(): $this ``` Clears the internal result cache and the internal count value from the current query object. #### Returns `$this` ### combine() public @method ``` combine(mixed $k, mixed $v, mixed $g = null): Cake\Collection\CollectionInterface ``` Returns the values of the column $v index by column $k, and grouped by $g. #### Parameters $k $v $g optional #### Returns `Cake\Collection\CollectionInterface` ### contain() public ``` contain(array|string $associations, callable|bool $override = false): $this ``` Sets the list of associations that should be eagerly loaded along with this query. The list of associated tables passed must have been previously set as associations using the Table API. ### Example: ``` // Bring articles' author information $query->contain('Author'); // Also bring the category and tags associated to each article $query->contain(['Category', 'Tag']); ``` Associations can be arbitrarily nested using dot notation or nested arrays, this allows this object to calculate joins or any additional queries that must be executed to bring the required associated data. ### Example: ``` // Eager load the product info, and for each product load other 2 associations $query->contain(['Product' => ['Manufacturer', 'Distributor']); // Which is equivalent to calling $query->contain(['Products.Manufactures', 'Products.Distributors']); // For an author query, load his region, state and country $query->contain('Regions.States.Countries'); ``` It is possible to control the conditions and fields selected for each of the contained associations: ### Example: ``` $query->contain(['Tags' => function ($q) { return $q->where(['Tags.is_popular' => true]); }]); $query->contain(['Products.Manufactures' => function ($q) { return $q->select(['name'])->where(['Manufactures.active' => true]); }]); ``` Each association might define special options when eager loaded, the allowed options that can be set per association are: * `foreignKey`: Used to set a different field to match both tables, if set to false no join conditions will be generated automatically. `false` can only be used on joinable associations and cannot be used with hasMany or belongsToMany associations. * `fields`: An array with the fields that should be fetched from the association. * `finder`: The finder to use when loading associated records. Either the name of the finder as a string, or an array to define options to pass to the finder. * `queryBuilder`: Equivalent to passing a callable instead of an options array. ### Example: ``` // Set options for the hasMany articles that will be eagerly loaded for an author $query->contain([ 'Articles' => [ 'fields' => ['title', 'author_id'] ] ]); ``` Finders can be configured to use options. ``` // Retrieve translations for the articles, but only those for the `en` and `es` locales $query->contain([ 'Articles' => [ 'finder' => [ 'translations' => [ 'locales' => ['en', 'es'] ] ] ] ]); ``` When containing associations, it is important to include foreign key columns. Failing to do so will trigger exceptions. ``` // Use a query builder to add conditions to the containment $query->contain('Authors', function ($q) { return $q->where(...); // add conditions }); // Use special join conditions for multiple containments in the same method call $query->contain([ 'Authors' => [ 'foreignKey' => false, 'queryBuilder' => function ($q) { return $q->where(...); // Add full filtering conditions } ], 'Tags' => function ($q) { return $q->where(...); // add conditions } ]); ``` If called with an empty first argument and `$override` is set to true, the previous list will be emptied. #### Parameters `array|string` $associations List of table aliases to be queried. `callable|bool` $override optional The query builder for the association, or if associations is an array, a bool on whether to override previous list with the one passed defaults to merging previous list with the new one. #### Returns `$this` ### count() public ``` count(): int ``` Returns the total amount of results for the query. Returns the COUNT(\*) for the query. If the query has not been modified, and the count has already been performed the cached value is returned #### Returns `int` ### countBy() public @method ``` countBy(callable|string $field): Cake\Collection\CollectionInterface ``` Returns the number of unique values for a column #### Parameters `callable|string` $field #### Returns `Cake\Collection\CollectionInterface` ### counter() public ``` counter(callable|null $counter): $this ``` Registers a callable function that will be executed when the `count` method in this query is called. The return value for the function will be set as the return value of the `count` method. This is particularly useful when you need to optimize a query for returning the count, for example removing unnecessary joins, removing group by or just return an estimated number of rows. The callback will receive as first argument a clone of this query and not this query itself. If the first param is a null value, the built-in counter function will be called instead #### Parameters `callable|null` $counter The counter value #### Returns `$this` ### decorateResults() public ``` decorateResults(callable|null $callback, bool $overwrite = false): $this ``` Registers a callback to be executed for each result that is fetched from the result set, the callback function will receive as first parameter an array with the raw data from the database for every row that is fetched and must return the row with any possible modifications. Callbacks will be executed lazily, if only 3 rows are fetched for database it will called 3 times, event though there might be more rows to be fetched in the cursor. Callbacks are stacked in the order they are registered, if you wish to reset the stack the call this function with the second parameter set to true. If you wish to remove all decorators from the stack, set the first parameter to null and the second to true. ### Example ``` $query->decorateResults(function ($row) { $row['order_total'] = $row['subtotal'] + ($row['subtotal'] * $row['tax']); return $row; }); ``` #### Parameters `callable|null` $callback The callback to invoke when results are fetched. `bool` $overwrite optional Whether this should append or replace all existing decorators. #### Returns `$this` ### delete() public ``` delete(string|null $table = null): $this ``` Create a delete query. This changes the query type to be 'delete'. Can be combined with the where() method to create delete queries. #### Parameters `string|null` $table optional Unused parameter. #### Returns `$this` ### disableAutoFields() public ``` disableAutoFields(): $this ``` Disables automatically appending fields. #### Returns `$this` ### disableBufferedResults() public ``` disableBufferedResults(): $this ``` Disables buffered results. Disabling buffering will consume less memory as fetched results are not remembered for future iterations. #### Returns `$this` ### disableHydration() public ``` disableHydration(): $this ``` Disable hydrating entities. Disabling hydration will cause array results to be returned for the query instead of entities. #### Returns `$this` ### disableResultsCasting() public ``` disableResultsCasting(): $this ``` Disables result casting. When disabled, the fields will be returned as received from the database driver (which in most environments means they are being returned as strings), which can improve performance with larger datasets. #### Returns `$this` ### distinct() public ``` distinct(Cake\Database\ExpressionInterface|array|string|bool $on = [], bool $overwrite = false): $this ``` Adds a `DISTINCT` clause to the query to remove duplicates from the result set. This clause can only be used for select statements. If you wish to filter duplicates based of those rows sharing a particular field or set of fields, you may pass an array of fields to filter on. Beware that this option might not be fully supported in all database systems. ### Examples: ``` // Filters products with the same name and city $query->select(['name', 'city'])->from('products')->distinct(); // Filters products in the same city $query->distinct(['city']); $query->distinct('city'); // Filter products with the same name $query->distinct(['name'], true); $query->distinct('name', true); ``` #### Parameters `Cake\Database\ExpressionInterface|array|string|bool` $on optional Enable/disable distinct class or list of fields to be filtered on `bool` $overwrite optional whether to reset fields with passed list or not #### Returns `$this` ### each() public @method ``` each(callable $c): Cake\Collection\CollectionInterface ``` Passes each of the query results to the callable #### Parameters `callable` $c #### Returns `Cake\Collection\CollectionInterface` ### eagerLoaded() public ``` eagerLoaded(bool $value): $this ``` Sets the query instance to be an eager loaded query. If no argument is passed, the current configured query `_eagerLoaded` value is returned. #### Parameters `bool` $value Whether to eager load. #### Returns `$this` ### enableAutoFields() public ``` enableAutoFields(bool $value = true): $this ``` Sets whether the ORM should automatically append fields. By default calling select() will disable auto-fields. You can re-enable auto-fields with this method. #### Parameters `bool` $value optional Set true to enable, false to disable. #### Returns `$this` ### enableBufferedResults() public ``` enableBufferedResults(bool $enable = true): $this ``` Enables/Disables buffered results. When enabled the results returned by this Query will be buffered. This enables you to iterate a result set multiple times, or both cache and iterate it. When disabled it will consume less memory as fetched results are not remembered for future iterations. #### Parameters `bool` $enable optional Whether to enable buffering #### Returns `$this` ### enableHydration() public ``` enableHydration(bool $enable = true): $this ``` Toggle hydrating entities. If set to false array results will be returned for the query. #### Parameters `bool` $enable optional Use a boolean to set the hydration mode. #### Returns `$this` ### enableResultsCasting() public ``` enableResultsCasting(): $this ``` Enables result casting. When enabled, the fields in the results returned by this Query will be cast to their corresponding PHP data type. #### Returns `$this` ### epilog() public ``` epilog(Cake\Database\ExpressionInterface|string|null $expression = null): $this ``` A string or expression that will be appended to the generated query ### Examples: ``` $query->select('id')->where(['author_id' => 1])->epilog('FOR UPDATE'); $query ->insert('articles', ['title']) ->values(['author_id' => 1]) ->epilog('RETURNING id'); ``` Epliog content is raw SQL and not suitable for use with user supplied data. #### Parameters `Cake\Database\ExpressionInterface|string|null` $expression optional The expression to be appended #### Returns `$this` ### every() public @method ``` every(callable $c): bool ``` Returns true if all the results pass the callable test #### Parameters `callable` $c #### Returns `bool` ### execute() public ``` execute(): Cake\Database\StatementInterface ``` Compiles the SQL representation of this query and executes it using the configured connection object. Returns the resulting statement object. Executing a query internally executes several steps, the first one is letting the connection transform this object to fit its particular dialect, this might result in generating a different Query object that will be the one to actually be executed. Immediately after, literal values are passed to the connection so they are bound to the query in a safe way. Finally, the resulting statement is decorated with custom objects to execute callbacks for each row retrieved if necessary. Resulting statement is traversable, so it can be used in any loop as you would with an array. This method can be overridden in query subclasses to decorate behavior around query execution. #### Returns `Cake\Database\StatementInterface` ### expr() public ``` expr(Cake\Database\ExpressionInterface|array|string|null $rawExpression = null): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object. This is a handy function when building complex queries using a fluent interface. You can also override this function in subclasses to use a more specialized QueryExpression class if required. You can optionally pass a single raw SQL string or an array or expressions in any format accepted by \Cake\Database\Expression\QueryExpression: ``` $expression = $query->expr(); // Returns an empty expression object $expression = $query->expr('Table.column = Table2.column'); // Return a raw SQL expression ``` #### Parameters `Cake\Database\ExpressionInterface|array|string|null` $rawExpression optional A string, array or anything you want wrapped in an expression object #### Returns `Cake\Database\Expression\QueryExpression` ### extract() public @method ``` extract(mixed $field): Cake\Collection\CollectionInterface ``` Extracts a single column from each row #### Parameters $field #### Returns `Cake\Collection\CollectionInterface` ### filter() public @method ``` filter(callable $c = null): Cake\Collection\CollectionInterface ``` Keeps the results using passing the callable test #### Parameters `callable` $c optional #### Returns `Cake\Collection\CollectionInterface` ### 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 ``` firstOrFail(): Cake\Datasource\EntityInterface|array ``` Get the first result from the executing query or raise an exception. #### Returns `Cake\Datasource\EntityInterface|array` #### Throws `Cake\Datasource\Exception\RecordNotFoundException` When there is no first record. ### formatResults() public ``` formatResults(callable|null $formatter = null, int|bool $mode = self::APPEND): $this ``` Registers a new formatter callback function that is to be executed when trying to fetch the results from the database. If the second argument is set to true, it will erase previous formatters and replace them with the passed first argument. Callbacks are required to return an iterator object, which will be used as the return value for this query's result. Formatter functions are applied after all the `MapReduce` routines for this query have been executed. Formatting callbacks will receive two arguments, the first one being an object implementing `\Cake\Collection\CollectionInterface`, that can be traversed and modified at will. The second one being the query instance on which the formatter callback is being applied. Usually the query instance received by the formatter callback is the same query instance on which the callback was attached to, except for in a joined association, in that case the callback will be invoked on the association source side query, and it will receive that query instance instead of the one on which the callback was originally attached to - see the examples below! ### Examples: Return all results from the table indexed by id: ``` $query->select(['id', 'name'])->formatResults(function ($results) { return $results->indexBy('id'); }); ``` Add a new column to the ResultSet: ``` $query->select(['name', 'birth_date'])->formatResults(function ($results) { return $results->map(function ($row) { $row['age'] = $row['birth_date']->diff(new DateTime)->y; return $row; }); }); ``` Add a new column to the results with respect to the query's hydration configuration: ``` $query->formatResults(function ($results, $query) { return $results->map(function ($row) use ($query) { $data = [ 'bar' => 'baz', ]; if ($query->isHydrationEnabled()) { $row['foo'] = new Foo($data) } else { $row['foo'] = $data; } return $row; }); }); ``` Retaining access to the association target query instance of joined associations, by inheriting the contain callback's query argument: ``` // Assuming a `Articles belongsTo Authors` association that uses the join strategy $articlesQuery->contain('Authors', function ($authorsQuery) { return $authorsQuery->formatResults(function ($results, $query) use ($authorsQuery) { // Here `$authorsQuery` will always be the instance // where the callback was attached to. // The instance passed to the callback in the second // argument (`$query`), will be the one where the // callback is actually being applied to, in this // example that would be `$articlesQuery`. // ... return $results; }); }); ``` #### Parameters `callable|null` $formatter optional The formatting callable. `int|bool` $mode optional Whether to overwrite, append or prepend the formatter. #### Returns `$this` #### Throws `InvalidArgumentException` ### from() public ``` from(array|string $tables = [], bool $overwrite = false): $this ``` Adds a single or multiple tables to be used in the FROM clause for this query. Tables 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 to alias tables using the value as the real field to be aliased. It is possible to alias strings, ExpressionInterface objects or even other Query objects. By default this function will append any passed argument to the list of tables to be selected from, unless the second argument is set to true. This method can be used for select, update and delete statements. ### Examples: ``` $query->from(['p' => 'posts']); // Produces FROM posts p $query->from('authors'); // Appends authors: FROM posts p, authors $query->from(['products'], true); // Resets the list: FROM products $query->from(['sub' => $countQuery]); // FROM (SELECT ...) sub ``` #### Parameters `array|string` $tables optional tables to be added to the list. This argument, can be passed as an array of strings, array of expression objects, or a single string. See the examples above for the valid call types. `bool` $overwrite optional whether to reset tables with passed list or not #### Returns `$this` ### func() public ``` func(): Cake\Database\FunctionsBuilder ``` Returns an instance of a functions builder object that can be used for generating arbitrary SQL functions. ### Example: ``` $query->func()->count('*'); $query->func()->dateDiff(['2012-01-05', '2012-01-02']) ``` #### Returns `Cake\Database\FunctionsBuilder` ### getConnection() public ``` getConnection(): Cake\Database\Connection ``` Gets the connection instance to be used for executing and transforming this query. #### Returns `Cake\Database\Connection` ### getContain() public ``` getContain(): array ``` #### Returns `array` ### getDefaultTypes() public ``` getDefaultTypes(): array<int|string, string> ``` Gets default types of current type map. #### Returns `array<int|string, string>` ### getEagerLoader() public ``` getEagerLoader(): Cake\ORM\EagerLoader ``` Returns the currently configured instance. #### Returns `Cake\ORM\EagerLoader` ### getIterator() public ``` getIterator(): Cake\Datasource\ResultSetInterface ``` Executes this query and returns a results iterator. This function is required for implementing the IteratorAggregate interface and allows the query to be iterated without having to call execute() manually, thus making it look like a result set instead of the query itself. #### Returns `Cake\Datasource\ResultSetInterface` ### getMapReducers() public ``` getMapReducers(): array ``` Returns the list of previously registered map reduce routines. #### Returns `array` ### getOptions() public ``` getOptions(): array ``` Returns an array with the custom options that were applied to this query and that were not already processed by another method in this class. ### Example: ``` $query->applyOptions(['doABarrelRoll' => true, 'fields' => ['id', 'name']); $query->getOptions(); // Returns ['doABarrelRoll' => true] ``` #### Returns `array` #### See Also \Cake\Datasource\QueryInterface::applyOptions() to read about the options that will be processed by this class and not returned by this function applyOptions() ### getRepository() public @method ``` getRepository(): Cake\ORM\Table ``` Returns the default table object that will be used by this query, that is, the table that will appear in the from clause. #### Returns `Cake\ORM\Table` ### getResultFormatters() public ``` getResultFormatters(): array<callable> ``` Returns the list of previously registered format routines. #### Returns `array<callable>` ### getSelectTypeMap() public ``` getSelectTypeMap(): Cake\Database\TypeMap ``` Gets the TypeMap class where the types for each of the fields in the select clause are stored. #### Returns `Cake\Database\TypeMap` ### getTypeMap() public ``` getTypeMap(): Cake\Database\TypeMap ``` Returns the existing type map. #### Returns `Cake\Database\TypeMap` ### getValueBinder() public ``` getValueBinder(): Cake\Database\ValueBinder ``` Returns the currently used ValueBinder instance. A ValueBinder is responsible for generating query placeholders and temporarily associate values to those placeholders so that they can be passed correctly to the statement object. #### Returns `Cake\Database\ValueBinder` ### group() public ``` group(Cake\Database\ExpressionInterface|array|string $fields, bool $overwrite = false): $this ``` Adds a single or multiple fields to be used in the GROUP BY clause for this query. Fields can be passed as an array of strings, array of expression objects, a single expression or a single string. By default this function will append any passed argument to the list of fields to be grouped, unless the second argument is set to true. ### Examples: ``` // Produces GROUP BY id, title $query->group(['id', 'title']); // Produces GROUP BY title $query->group('title'); ``` Group fields are not suitable for use with user supplied data as they are not sanitized by the query builder. #### Parameters `Cake\Database\ExpressionInterface|array|string` $fields fields to be added to the list `bool` $overwrite optional whether to reset fields with passed list or not #### Returns `$this` ### groupBy() public @method ``` groupBy(callable|string $field): Cake\Collection\CollectionInterface ``` In-memory group all results by the value of a column. #### Parameters `callable|string` $field #### Returns `Cake\Collection\CollectionInterface` ### having() public ``` having(Cake\Database\ExpressionInterfaceClosure|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 `HAVING` clause for this query. This method operates in exactly the same way as the method `where()` does. Please refer to its documentation for an insight on how to using each parameter. Having fields are not suitable for use with user supplied data as they are not sanitized by the query builder. #### Parameters `Cake\Database\ExpressionInterfaceClosure|array|string|null` $conditions optional The having conditions. `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` #### See Also \Cake\Database\Query::where() ### identifier() public ``` identifier(string $identifier): Cake\Database\ExpressionInterface ``` Creates an expression that refers to an identifier. Identifiers are used to refer to field names and allow the SQL compiler to apply quotes or escape the identifier. The value is used as is, and you might be required to use aliases or include the table reference in the identifier. Do not use this method to inject SQL methods or logical statements. ### Example ``` $query->newExpr()->lte('count', $query->identifier('total')); ``` #### Parameters `string` $identifier The identifier for an expression #### Returns `Cake\Database\ExpressionInterface` ### indexBy() public @method ``` indexBy(callable|string $callback): Cake\Collection\CollectionInterface ``` Returns the results indexed by the value of a column. #### Parameters `callable|string` $callback #### Returns `Cake\Collection\CollectionInterface` ### innerJoin() public ``` innerJoin(array<string, mixed>|string $table, Cake\Database\ExpressionInterface|array|string $conditions = [], array<string, string> $types = []): $this ``` Adds a single `INNER JOIN` clause to the query. This is a shorthand method for building joins via `join()`. The arguments of this method are identical to the `leftJoin()` shorthand, please refer to that method's description for further details. #### Parameters `array<string, mixed>|string` $table The table to join with `Cake\Database\ExpressionInterface|array|string` $conditions optional The conditions to use for joining. `array<string, string>` $types optional a list of types associated to the conditions used for converting values to the corresponding database representation. #### Returns `$this` ### innerJoinWith() public ``` innerJoinWith(string $assoc, callable|null $builder = null): $this ``` Creates an INNER JOIN with the passed association table while preserving the foreign key matching and the custom conditions that were originally set for it. This function will add entries in the `contain` graph. ### Example: ``` // Bring only articles that were tagged with 'cake' $query->innerJoinWith('Tags', function ($q) { return $q->where(['name' => 'cake']); }); ``` This will create the following SQL: ``` SELECT Articles.* FROM articles Articles INNER JOIN tags Tags ON Tags.name = 'cake' INNER JOIN articles_tags ArticlesTags ON ArticlesTags.tag_id = Tags.id AND ArticlesTags.articles_id = Articles.id ``` This function works the same as `matching()` with the difference that it will select no fields from the association. #### Parameters `string` $assoc The association to join with `callable|null` $builder optional a function that will receive a pre-made query object that can be used to add custom conditions or selecting some fields #### Returns `$this` #### See Also \Cake\ORM\Query::matching() ### insert() public ``` insert(array $columns, array<int|string, string> $types = []): $this ``` Create an insert query. This changes the query type to be 'insert'. Note calling this method will reset any data previously set with Query::values() Can be combined with the where() method to create delete queries. #### Parameters `array` $columns The columns to insert into. `array<int|string, string>` $types optional A map between columns & their datatypes. #### Returns `$this` ### into() public ``` into(string $table): $this ``` Set the table name for insert queries. #### Parameters `string` $table The table name to insert into. #### Returns `$this` ### isAutoFieldsEnabled() public ``` isAutoFieldsEnabled(): bool|null ``` Gets whether the ORM should automatically append fields. By default calling select() will disable auto-fields. You can re-enable auto-fields with enableAutoFields(). #### Returns `bool|null` ### isBufferedResultsEnabled() public ``` isBufferedResultsEnabled(): bool ``` Returns whether buffered results are enabled/disabled. When enabled the results returned by this Query will be buffered. This enables you to iterate a result set multiple times, or both cache and iterate it. When disabled it will consume less memory as fetched results are not remembered for future iterations. #### Returns `bool` ### isEagerLoaded() public ``` isEagerLoaded(): bool ``` Returns the current configured query `_eagerLoaded` value #### Returns `bool` ### isEmpty() public @method ``` isEmpty(): bool ``` Returns true if this query found no results. #### Returns `bool` ### isHydrationEnabled() public ``` isHydrationEnabled(): bool ``` Returns the current hydration mode. #### Returns `bool` ### isResultsCastingEnabled() public ``` isResultsCastingEnabled(): bool ``` Returns whether result casting is enabled/disabled. When enabled, the fields in the results returned by this Query will be casted to their corresponding PHP data type. When disabled, the fields will be returned as received from the database driver (which in most environments means they are being returned as strings), which can improve performance with larger datasets. #### Returns `bool` ### join() public ``` join(array<string, mixed>|string $tables, array<string, string> $types = [], bool $overwrite = false): $this ``` Adds a single or multiple tables to be used as JOIN clauses to this query. Tables can be passed as an array of strings, an array describing the join parts, an array with multiple join descriptions, or a single string. By default this function will append any passed argument to the list of tables to be joined, unless the third argument is set to true. When no join type is specified an `INNER JOIN` is used by default: `$query->join(['authors'])` will produce `INNER JOIN authors ON 1 = 1` It is also possible to alias joins using the array key: `$query->join(['a' => 'authors'])` will produce `INNER JOIN authors a ON 1 = 1` A join can be fully described and aliased using the array notation: ``` $query->join([ 'a' => [ 'table' => 'authors', 'type' => 'LEFT', 'conditions' => 'a.id = b.author_id' ] ]); // Produces LEFT JOIN authors a ON a.id = b.author_id ``` You can even specify multiple joins in an array, including the full description: ``` $query->join([ 'a' => [ 'table' => 'authors', 'type' => 'LEFT', 'conditions' => 'a.id = b.author_id' ], 'p' => [ 'table' => 'publishers', 'type' => 'INNER', 'conditions' => 'p.id = b.publisher_id AND p.name = "Cake Software Foundation"' ] ]); // LEFT JOIN authors a ON a.id = b.author_id // INNER JOIN publishers p ON p.id = b.publisher_id AND p.name = "Cake Software Foundation" ``` ### Using conditions and types Conditions can be expressed, as in the examples above, using a string for comparing columns, or string with already quoted literal values. Additionally it is possible to use conditions expressed in arrays or expression objects. When using arrays for expressing conditions, it is often desirable to convert the literal values to the correct database representation. This is achieved using the second parameter of this function. ``` $query->join(['a' => [ 'table' => 'articles', 'conditions' => [ 'a.posted >=' => new DateTime('-3 days'), 'a.published' => true, 'a.author_id = authors.id' ] ]], ['a.posted' => 'datetime', 'a.published' => 'boolean']) ``` ### Overwriting joins When creating aliased joins using the array notation, you can override previous join definitions by using the same alias in consequent calls to this function or you can replace all previously defined joins with another list if the third parameter for this function is set to true. ``` $query->join(['alias' => 'table']); // joins table with as alias $query->join(['alias' => 'another_table']); // joins another_table with as alias $query->join(['something' => 'different_table'], [], true); // resets joins list ``` #### Parameters `array<string, mixed>|string` $tables list of tables to be joined in the query `array<string, string>` $types optional Associative array of type names used to bind values to query `bool` $overwrite optional whether to reset joins with passed list or not #### Returns `$this` #### See Also \Cake\Database\TypeFactory ### jsonSerialize() public ``` jsonSerialize(): Cake\Datasource\ResultSetInterface ``` Executes the query and converts the result set into JSON. Part of JsonSerializable interface. #### Returns `Cake\Datasource\ResultSetInterface` ### last() public @method ``` last(): mixed ``` Return the last row of the query result #### Returns `mixed` ### leftJoin() public ``` leftJoin(array<string, mixed>|string $table, Cake\Database\ExpressionInterface|array|string $conditions = [], array $types = []): $this ``` Adds a single `LEFT JOIN` clause to the query. This is a shorthand method for building joins via `join()`. The table name can be passed as a string, or as an array in case it needs to be aliased: ``` // LEFT JOIN authors ON authors.id = posts.author_id $query->leftJoin('authors', 'authors.id = posts.author_id'); // LEFT JOIN authors a ON a.id = posts.author_id $query->leftJoin(['a' => 'authors'], 'a.id = posts.author_id'); ``` Conditions can be passed as strings, arrays, or expression objects. When using arrays it is possible to combine them with the `$types` parameter in order to define how to convert the values: ``` $query->leftJoin(['a' => 'articles'], [ 'a.posted >=' => new DateTime('-3 days'), 'a.published' => true, 'a.author_id = authors.id' ], ['a.posted' => 'datetime', 'a.published' => 'boolean']); ``` See `join()` for further details on conditions and types. #### Parameters `array<string, mixed>|string` $table The table to join with `Cake\Database\ExpressionInterface|array|string` $conditions optional The conditions to use for joining. `array` $types optional a list of types associated to the conditions used for converting values to the corresponding database representation. #### Returns `$this` ### leftJoinWith() public ``` leftJoinWith(string $assoc, callable|null $builder = null): $this ``` Creates a LEFT JOIN with the passed association table while preserving the foreign key matching and the custom conditions that were originally set for it. This function will add entries in the `contain` graph. ### Example: ``` // Get the count of articles per user $usersQuery ->select(['total_articles' => $query->func()->count('Articles.id')]) ->leftJoinWith('Articles') ->group(['Users.id']) ->enableAutoFields(); ``` You can also customize the conditions passed to the LEFT JOIN: ``` // Get the count of articles per user with at least 5 votes $usersQuery ->select(['total_articles' => $query->func()->count('Articles.id')]) ->leftJoinWith('Articles', function ($q) { return $q->where(['Articles.votes >=' => 5]); }) ->group(['Users.id']) ->enableAutoFields(); ``` This will create the following SQL: ``` SELECT COUNT(Articles.id) AS total_articles, Users.* FROM users Users LEFT JOIN articles Articles ON Articles.user_id = Users.id AND Articles.votes >= 5 GROUP BY USers.id ``` It is possible to left join deep associations by using dot notation ### Example: ``` // Total comments in articles by 'markstory' $query ->select(['total_comments' => $query->func()->count('Comments.id')]) ->leftJoinWith('Comments.Users', function ($q) { return $q->where(['username' => 'markstory']); }) ->group(['Users.id']); ``` Please note that the query passed to the closure will only accept calling `select`, `where`, `andWhere` and `orWhere` on it. If you wish to add more complex clauses you can do it directly in the main query. #### Parameters `string` $assoc The association to join with `callable|null` $builder optional a function that will receive a pre-made query object that can be used to add custom conditions or selecting some fields #### Returns `$this` ### 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` ### map() public @method ``` map(callable $c): Cake\Collection\CollectionInterface ``` Modifies each of the results using the callable #### Parameters `callable` $c #### Returns `Cake\Collection\CollectionInterface` ### mapReduce() public ``` mapReduce(callable|null $mapper = null, callable|null $reducer = null, bool $overwrite = false): $this ``` Register a new MapReduce routine to be executed on top of the database results Both the mapper and caller callable should be invokable objects. The MapReduce routing will only be run when the query is executed and the first result is attempted to be fetched. If the third argument is set to true, it will erase previous map reducers and replace it with the arguments passed. #### Parameters `callable|null` $mapper optional The mapper callable. `callable|null` $reducer optional The reducing function. `bool` $overwrite optional Set to true to overwrite existing map + reduce functions. #### Returns `$this` #### See Also \Cake\Collection\Iterator\MapReduce for details on how to use emit data to the map reducer. ### matching() public ``` matching(string $assoc, callable|null $builder = null): $this ``` Adds filtering conditions to this query to only bring rows that have a relation to another from an associated table, based on conditions in the associated table. This function will add entries in the `contain` graph. ### Example: ``` // Bring only articles that were tagged with 'cake' $query->matching('Tags', function ($q) { return $q->where(['name' => 'cake']); }); ``` It is possible to filter by deep associations by using dot notation: ### Example: ``` // Bring only articles that were commented by 'markstory' $query->matching('Comments.Users', function ($q) { return $q->where(['username' => 'markstory']); }); ``` As this function will create `INNER JOIN`, you might want to consider calling `distinct` on this query as you might get duplicate rows if your conditions don't filter them already. This might be the case, for example, of the same user commenting more than once in the same article. ### Example: ``` // Bring unique articles that were commented by 'markstory' $query->distinct(['Articles.id']) ->matching('Comments.Users', function ($q) { return $q->where(['username' => 'markstory']); }); ``` Please note that the query passed to the closure will only accept calling `select`, `where`, `andWhere` and `orWhere` on it. If you wish to add more complex clauses you can do it directly in the main query. #### Parameters `string` $assoc The association to filter by `callable|null` $builder optional a function that will receive a pre-made query object that can be used to add custom conditions or selecting some fields #### Returns `$this` ### max() public @method ``` max(mixed $field): mixed ``` Returns the maximum value for a single column in all the results. #### Parameters $field #### Returns `mixed` ### min() public @method ``` min(mixed $field): mixed ``` Returns the minimum value for a single column in all the results. #### Parameters $field #### Returns `mixed` ### modifier() public ``` modifier(Cake\Database\ExpressionInterface|array|string $modifiers, bool $overwrite = false): $this ``` Adds a single or multiple `SELECT` modifiers to be used in the `SELECT`. By default this function will append any passed argument to the list of modifiers to be applied, unless the second argument is set to true. ### Example: ``` // Ignore cache query in MySQL $query->select(['name', 'city'])->from('products')->modifier('SQL_NO_CACHE'); // It will produce the SQL: SELECT SQL_NO_CACHE name, city FROM products // Or with multiple modifiers $query->select(['name', 'city'])->from('products')->modifier(['HIGH_PRIORITY', 'SQL_NO_CACHE']); // It will produce the SQL: SELECT HIGH_PRIORITY SQL_NO_CACHE name, city FROM products ``` #### Parameters `Cake\Database\ExpressionInterface|array|string` $modifiers modifiers to be applied to the query `bool` $overwrite optional whether to reset order with field list or not #### Returns `$this` ### nest() public @method ``` nest(mixed $k, mixed $p, mixed $n = 'children'): Cake\Collection\CollectionInterface ``` Creates a tree structure by nesting the values of column $p into that with the same value for $k using $n as the nesting key. #### Parameters $k $p $n optional #### Returns `Cake\Collection\CollectionInterface` ### newExpr() public ``` newExpr(Cake\Database\ExpressionInterface|array|string|null $rawExpression = null): Cake\Database\Expression\QueryExpression ``` Returns a new QueryExpression object. This is a handy function when building complex queries using a fluent interface. You can also override this function in subclasses to use a more specialized QueryExpression class if required. You can optionally pass a single raw SQL string or an array or expressions in any format accepted by \Cake\Database\Expression\QueryExpression: ``` $expression = $query->expr(); // Returns an empty expression object $expression = $query->expr('Table.column = Table2.column'); // Return a raw SQL expression ``` #### Parameters `Cake\Database\ExpressionInterface|array|string|null` $rawExpression optional A string, array or anything you want wrapped in an expression object #### Returns `Cake\Database\Expression\QueryExpression` ### notMatching() public ``` notMatching(string $assoc, callable|null $builder = null): $this ``` Adds filtering conditions to this query to only bring rows that have no match to another from an associated table, based on conditions in the associated table. This function will add entries in the `contain` graph. ### Example: ``` // Bring only articles that were not tagged with 'cake' $query->notMatching('Tags', function ($q) { return $q->where(['name' => 'cake']); }); ``` It is possible to filter by deep associations by using dot notation: ### Example: ``` // Bring only articles that weren't commented by 'markstory' $query->notMatching('Comments.Users', function ($q) { return $q->where(['username' => 'markstory']); }); ``` As this function will create a `LEFT JOIN`, you might want to consider calling `distinct` on this query as you might get duplicate rows if your conditions don't filter them already. This might be the case, for example, of the same article having multiple comments. ### Example: ``` // Bring unique articles that were commented by 'markstory' $query->distinct(['Articles.id']) ->notMatching('Comments.Users', function ($q) { return $q->where(['username' => 'markstory']); }); ``` Please note that the query passed to the closure will only accept calling `select`, `where`, `andWhere` and `orWhere` on it. If you wish to add more complex clauses you can do it directly in the main query. #### Parameters `string` $assoc The association to filter by `callable|null` $builder optional a function that will receive a pre-made query object that can be used to add custom conditions or selecting some fields #### 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` ### orderAsc() public ``` orderAsc(Cake\Database\ExpressionInterfaceClosure|string $field, bool $overwrite = false): $this ``` Add an ORDER BY clause with an ASC direction. This method allows you to set complex expressions as order conditions unlike order() Order fields are not suitable for use with user supplied data as they are not sanitized by the query builder. #### Parameters `Cake\Database\ExpressionInterfaceClosure|string` $field The field to order on. `bool` $overwrite optional Whether to reset the order clauses. #### Returns `$this` ### orderDesc() public ``` orderDesc(Cake\Database\ExpressionInterfaceClosure|string $field, bool $overwrite = false): $this ``` Add an ORDER BY clause with a DESC direction. This method allows you to set complex expressions as order conditions unlike order() Order fields are not suitable for use with user supplied data as they are not sanitized by the query builder. #### Parameters `Cake\Database\ExpressionInterfaceClosure|string` $field The field to order on. `bool` $overwrite optional Whether to reset the order clauses. #### 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. ### reduce() public @method ``` reduce(callable $c, mixed $zero = null): mixed ``` Folds all the results into a single value using the callable. #### Parameters `callable` $c $zero optional #### Returns `mixed` ### reject() public @method ``` reject(callable $c): Cake\Collection\CollectionInterface ``` Removes the results passing the callable test #### Parameters `callable` $c #### Returns `Cake\Collection\CollectionInterface` ### removeJoin() public ``` removeJoin(string $name): $this ``` Remove a join if it has been defined. Useful when you are redefining joins or want to re-order the join clauses. #### Parameters `string` $name The alias/name of the join to remove. #### Returns `$this` ### 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 table object to use #### Returns `$this` ### rightJoin() public ``` rightJoin(array<string, mixed>|string $table, Cake\Database\ExpressionInterface|array|string $conditions = [], array $types = []): $this ``` Adds a single `RIGHT JOIN` clause to the query. This is a shorthand method for building joins via `join()`. The arguments of this method are identical to the `leftJoin()` shorthand, please refer to that methods description for further details. #### Parameters `array<string, mixed>|string` $table The table to join with `Cake\Database\ExpressionInterface|array|string` $conditions optional The conditions to use for joining. `array` $types optional a list of types associated to the conditions used for converting values to the corresponding database representation. #### Returns `$this` ### rowCountAndClose() public ``` rowCountAndClose(): int ``` Executes the SQL of this query and immediately closes the statement before returning the row count of records changed. This method can be used with UPDATE and DELETE queries, but is not recommended for SELECT queries and is not used to count records. Example ------- ``` $rowCount = $query->update('articles') ->set(['published'=>true]) ->where(['published'=>false]) ->rowCountAndClose(); ``` The above example will change the published column to true for all false records, and return the number of records that were updated. #### Returns `int` ### sample() public @method ``` sample(int $size = 10): Cake\Collection\CollectionInterface ``` In-memory shuffle the results and return a subset of them. #### Parameters `int` $size optional #### Returns `Cake\Collection\CollectionInterface` ### select() public ``` select(Cake\Database\ExpressionInterface|callable|array|string $fields = [], bool $overwrite = false): $this ``` Adds new fields to be returned by a `SELECT` statement when this query is executed. 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 to alias fields using the value as the real field to be aliased. It is possible to alias strings, Expression objects or even other Query objects. If a callable function is passed, the returning array of the function will be used as the list of fields. 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->select(['id', 'title']); // Produces SELECT id, title $query->select(['author' => 'author_id']); // Appends author: SELECT id, title, author_id as author $query->select('id', true); // Resets the list: SELECT id $query->select(['total' => $countQuery]); // SELECT id, (SELECT ...) AS total $query->select(function ($query) { return ['article_id', 'total' => $query->count('*')]; }) ``` By default no fields are selected, if you have an instance of `Cake\ORM\Query` and try to append fields you should also call `Cake\ORM\Query::enableAutoFields()` to select the default fields from the table. If you pass an instance of a `Cake\ORM\Table` or `Cake\ORM\Association` class, all the fields in the schema of the table or the association will be added to the select clause. #### Parameters `Cake\Database\ExpressionInterface|callable|array|string` $fields optional Fields to be added to the list. `bool` $overwrite optional whether to reset fields with passed list or not #### Returns `$this` ### selectAllExcept() public ``` selectAllExcept(Cake\ORM\TableCake\ORM\Association $table, array<string> $excludedFields, bool $overwrite = false): $this ``` All the fields associated with the passed table except the excluded fields will be added to the select clause of the query. Passed excluded fields should not be aliased. After the first call to this method, a second call cannot be used to remove fields that have already been added to the query by the first. If you need to change the list after the first call, pass overwrite boolean true which will reset the select clause removing all previous additions. #### Parameters `Cake\ORM\TableCake\ORM\Association` $table The table to use to get an array of columns `array<string>` $excludedFields The un-aliased column names you do not want selected from $table `bool` $overwrite optional Whether to reset/remove previous selected fields #### Returns `$this` #### Throws `InvalidArgumentException` If Association|Table is not passed in first argument ### set() public ``` set(Cake\Database\Expression\QueryExpressionClosure|array|string $key, mixed $value = null, array<string, string>|string $types = []): $this ``` Set one or many fields to update. ### Examples Passing a string: ``` $query->update('articles')->set('title', 'The Title'); ``` Passing an array: ``` $query->update('articles')->set(['title' => 'The Title'], ['title' => 'string']); ``` Passing a callable: ``` $query->update('articles')->set(function ($exp) { return $exp->eq('title', 'The title', 'string'); }); ``` #### Parameters `Cake\Database\Expression\QueryExpressionClosure|array|string` $key The column name or array of keys * values to set. This can also be a QueryExpression containing a SQL fragment. It can also be a Closure, that is required to return an expression object. `mixed` $value optional The value to update $key to. Can be null if $key is an array or QueryExpression. When $key is an array, this parameter will be used as $types instead. `array<string, string>|string` $types optional The column types to treat data as. #### Returns `$this` ### setConnection() public ``` setConnection(Cake\Database\Connection $connection): $this ``` Sets the connection instance to be used for executing and transforming this query. #### Parameters `Cake\Database\Connection` $connection Connection instance #### 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() ### setEagerLoader() public ``` setEagerLoader(Cake\ORM\EagerLoader $instance): $this ``` Sets the instance of the eager loader class to use for loading associations and storing containments. #### Parameters `Cake\ORM\EagerLoader` $instance The eager loader to use. #### Returns `$this` ### setResult() public ``` setResult(iterable $results): $this ``` Set the result set for a query. Setting the resultset of a query will make execute() a no-op. Instead of executing the SQL query and fetching results, the ResultSet provided to this method will be returned. This method is most useful when combined with results stored in a persistent cache. #### Parameters `iterable` $results The results this query should return. #### Returns `$this` ### setSelectTypeMap() public ``` setSelectTypeMap(Cake\Database\TypeMap $typeMap): $this ``` Sets the TypeMap class where the types for each of the fields in the select clause are stored. #### Parameters `Cake\Database\TypeMap` $typeMap The map object 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` ### setValueBinder() public ``` setValueBinder(Cake\Database\ValueBinder|null $binder): $this ``` Overwrite the current value binder A ValueBinder is responsible for generating query placeholders and temporarily associate values to those placeholders so that they can be passed correctly to the statement object. #### Parameters `Cake\Database\ValueBinder|null` $binder The binder or null to disable binding. #### Returns `$this` ### shuffle() public @method ``` shuffle(): Cake\Collection\CollectionInterface ``` In-memory randomize the order the results are returned #### Returns `Cake\Collection\CollectionInterface` ### skip() public @method ``` skip(int $howMany): Cake\Collection\CollectionInterface ``` Skips some rows from the start of the query result. #### Parameters `int` $howMany #### Returns `Cake\Collection\CollectionInterface` ### some() public @method ``` some(callable $c): bool ``` Returns true if at least one of the results pass the callable test #### Parameters `callable` $c #### Returns `bool` ### sortBy() public @method ``` sortBy(mixed $callback, int $dir): Cake\Collection\CollectionInterface ``` Sorts the query with the callback #### Parameters $callback `int` $dir #### Returns `Cake\Collection\CollectionInterface` ### sql() public ``` sql(Cake\Database\ValueBinder|null $binder = null): string ``` Returns the SQL representation of this object. This function will compile this query to make it compatible with the SQL dialect that is used by the connection, This process might add, remove or alter any query part or internal expression to make it executable in the target platform. The resulting query may have placeholders that will be replaced with the actual values when the query is executed, hence it is most suitable to use with prepared statements. #### Parameters `Cake\Database\ValueBinder|null` $binder optional #### Returns `string` ### stopWhen() public @method ``` stopWhen(callable $c): Cake\Collection\CollectionInterface ``` Returns each row until the callable returns true. #### Parameters `callable` $c #### Returns `Cake\Collection\CollectionInterface` ### subquery() public static ``` subquery(Cake\ORM\Table $table): static ``` Returns a new Query that has automatic field aliasing disabled. #### Parameters `Cake\ORM\Table` $table The table this query is starting on #### Returns `static` ### sumOf() public @method ``` sumOf(callable|string $field): float ``` Returns the sum of all values for a single column #### Parameters `callable|string` $field #### Returns `float` ### take() public @method ``` take(int $size = 1, int $from = 0): Cake\Collection\CollectionInterface ``` In-memory limit and offset for the query results. #### Parameters `int` $size optional `int` $from optional #### Returns `Cake\Collection\CollectionInterface` ### toArray() public @method ``` toArray(): array ``` Returns a key-value array with the results of this query. #### Returns `array` ### toList() public @method ``` toList(): array ``` Returns a numerically indexed array with the results of this query. #### Returns `array` ### traverse() public ``` traverse(callable $callback): $this ``` Will iterate over every specified part. Traversing functions can aggregate results using variables in the closure or instance variables. This function is commonly used as a way for traversing all query parts that are going to be used for constructing a query. The callback will receive 2 parameters, the first one is the value of the query part that is being iterated and the second the name of such part. ### Example ``` $query->select(['title'])->from('articles')->traverse(function ($value, $clause) { if ($clause === 'select') { var_dump($value); } }); ``` #### Parameters `callable` $callback A function or callable to be executed for each part #### Returns `$this` ### traverseExpressions() public ``` traverseExpressions(callable $callback): $this ``` This function works similar to the traverse() function, with the difference that it does a full depth traversal of the entire expression tree. This will execute the provided callback function for each ExpressionInterface object that is stored inside this query at any nesting depth in any part of the query. Callback will receive as first parameter the currently visited expression. #### Parameters `callable` $callback the function to be executed for each ExpressionInterface found inside this query. #### Returns `$this` ### traverseParts() public ``` traverseParts(callable $visitor, array<string> $parts): $this ``` Will iterate over the provided parts. Traversing functions can aggregate results using variables in the closure or instance variables. This method can be used to traverse a subset of query parts in order to render a SQL query. The callback will receive 2 parameters, the first one is the value of the query part that is being iterated and the second the name of such part. ### Example ``` $query->select(['title'])->from('articles')->traverse(function ($value, $clause) { if ($clause === 'select') { var_dump($value); } }, ['select', 'from']); ``` #### Parameters `callable` $visitor A function or callable to be executed for each part `array<string>` $parts The list of query parts to traverse #### Returns `$this` ### triggerBeforeFind() public ``` triggerBeforeFind(): void ``` Trigger the beforeFind event on the query's repository object. Will not trigger more than once, and only for select queries. #### Returns `void` ### type() public ``` type(): string ``` Returns the type of this query (select, insert, update, delete) #### Returns `string` ### union() public ``` union(Cake\Database\Query|string $query, bool $overwrite = false): $this ``` Adds a complete query to be used in conjunction with an UNION operator with this query. This is used to combine the result set of this query with the one that will be returned by the passed query. You can add as many queries as you required by calling multiple times this method with different queries. By default, the UNION operator will remove duplicate rows, if you wish to include every row for all queries, use unionAll(). ### Examples ``` $union = (new Query($conn))->select(['id', 'title'])->from(['a' => 'articles']); $query->select(['id', 'name'])->from(['d' => 'things'])->union($union); ``` Will produce: `SELECT id, name FROM things d UNION SELECT id, title FROM articles a` #### Parameters `Cake\Database\Query|string` $query full SQL query to be used in UNION operator `bool` $overwrite optional whether to reset the list of queries to be operated or not #### Returns `$this` ### unionAll() public ``` unionAll(Cake\Database\Query|string $query, bool $overwrite = false): $this ``` Adds a complete query to be used in conjunction with the UNION ALL operator with this query. This is used to combine the result set of this query with the one that will be returned by the passed query. You can add as many queries as you required by calling multiple times this method with different queries. Unlike UNION, UNION ALL will not remove duplicate rows. ``` $union = (new Query($conn))->select(['id', 'title'])->from(['a' => 'articles']); $query->select(['id', 'name'])->from(['d' => 'things'])->unionAll($union); ``` Will produce: `SELECT id, name FROM things d UNION ALL SELECT id, title FROM articles a` #### Parameters `Cake\Database\Query|string` $query full SQL query to be used in UNION operator `bool` $overwrite optional whether to reset the list of queries to be operated or not #### Returns `$this` ### update() public ``` update(Cake\Database\ExpressionInterface|string $table = null): $this ``` Create an update query. This changes the query type to be 'update'. Can be combined with set() and where() methods to create update queries. #### Parameters `Cake\Database\ExpressionInterface|string` $table optional Unused parameter. #### Returns `$this` ### values() public ``` values(Cake\Database\Expression\ValuesExpressionCake\Database\Query|array $data): $this ``` Set the values for an insert query. Multi inserts can be performed by calling values() more than one time, or by providing an array of value sets. Additionally $data can be a Query instance to insert data from another SELECT statement. #### Parameters `Cake\Database\Expression\ValuesExpressionCake\Database\Query|array` $data The data to insert. #### Returns `$this` #### Throws `Cake\Database\Exception\DatabaseException` if you try to set values before declaring columns. Or if you try to set values on non-insert queries. ### where() public ``` where(Cake\Database\ExpressionInterfaceClosure|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 `Cake\Database\ExpressionInterfaceClosure|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` ### whereInList() public ``` whereInList(string $field, array $values, array<string, mixed> $options = []): $this ``` Adds an IN condition or set of conditions to be used in the WHERE clause for this query. This method does allow empty inputs in contrast to where() if you set 'allowEmpty' to true. Be careful about using it without proper sanity checks. Options: * `types` - Associative array of type names used to bind values to query * `allowEmpty` - Allow empty array. #### Parameters `string` $field Field `array` $values Array of values `array<string, mixed>` $options optional Options #### Returns `$this` ### whereNotInList() public ``` whereNotInList(string $field, array $values, array<string, mixed> $options = []): $this ``` Adds a NOT IN condition or set of conditions to be used in the WHERE clause for this query. This method does allow empty inputs in contrast to where() if you set 'allowEmpty' to true. Be careful about using it without proper sanity checks. #### Parameters `string` $field Field `array` $values Array of values `array<string, mixed>` $options optional Options #### Returns `$this` ### whereNotInListOrNull() public ``` whereNotInListOrNull(string $field, array $values, array<string, mixed> $options = []): $this ``` Adds a NOT IN condition or set of conditions to be used in the WHERE clause for this query. This also allows the field to be null with a IS NULL condition since the null value would cause the NOT IN condition to always fail. This method does allow empty inputs in contrast to where() if you set 'allowEmpty' to true. Be careful about using it without proper sanity checks. #### Parameters `string` $field Field `array` $values Array of values `array<string, mixed>` $options optional Options #### Returns `$this` ### whereNotNull() public ``` whereNotNull(Cake\Database\ExpressionInterface|array|string $fields): $this ``` Convenience method that adds a NOT NULL condition to the query #### Parameters `Cake\Database\ExpressionInterface|array|string` $fields A single field or expressions or a list of them that should be not null. #### Returns `$this` ### whereNull() public ``` whereNull(Cake\Database\ExpressionInterface|array|string $fields): $this ``` Convenience method that adds a IS NULL condition to the query #### Parameters `Cake\Database\ExpressionInterface|array|string` $fields A single field or expressions or a list of them that should be null. #### Returns `$this` ### window() public ``` window(string $name, Cake\Database\Expression\WindowExpressionClosure $window, bool $overwrite = false): $this ``` Adds a named window expression. You are responsible for adding windows in the order your database requires. #### Parameters `string` $name Window name `Cake\Database\Expression\WindowExpressionClosure` $window Window expression `bool` $overwrite optional Clear all previous query window expressions #### Returns `$this` ### with() public ``` with(Cake\Database\Expression\CommonTableExpressionClosure $cte, bool $overwrite = false): $this ``` Adds a new common table expression (CTE) to the query. ### Examples: Common table expressions can either be passed as preconstructed expression objects: ``` $cte = new \Cake\Database\Expression\CommonTableExpression( 'cte', $connection ->newQuery() ->select('*') ->from('articles') ); $query->with($cte); ``` or returned from a closure, which will receive a new common table expression object as the first argument, and a new blank query object as the second argument: ``` $query->with(function ( \Cake\Database\Expression\CommonTableExpression $cte, \Cake\Database\Query $query ) { $cteQuery = $query ->select('*') ->from('articles'); return $cte ->name('cte') ->query($cteQuery); }); ``` #### Parameters `Cake\Database\Expression\CommonTableExpressionClosure` $cte The CTE to add. `bool` $overwrite optional Whether to reset the list of CTEs. #### Returns `$this` ### zip() public @method ``` zip(arrayTraversable $c): Cake\Collection\CollectionInterface ``` Returns the first result of both the query and $c in an array, then the second results and so on. #### Parameters `arrayTraversable` $c #### Returns `Cake\Collection\CollectionInterface` ### zipWith() public @method ``` zipWith(mixed $collections, callable $callable): Cake\Collection\CollectionInterface ``` Returns each of the results out of calling $c with the first rows of the query and each of the items, then the second rows and so on. #### Parameters $collections `callable` $callable #### Returns `Cake\Collection\CollectionInterface` Property Detail --------------- ### $\_autoFields protected Tracks whether the original query should include fields from the top level table. #### Type `bool|null` ### $\_beforeFindFired protected True if the beforeFind event has already been triggered for this query #### Type `bool` ### $\_cache protected A query cacher instance if this query has caching enabled. #### Type `Cake\Datasource\QueryCacher|null` ### $\_connection protected Connection instance to be used to execute this query. #### Type `Cake\Database\Connection` ### $\_counter protected A callable function that can be used to calculate the total amount of records this query will match when not using `limit` #### Type `callable|null` ### $\_deleteParts protected deprecated The list of query clauses to traverse for generating a DELETE statement #### Type `array<string>` ### $\_dirty protected Indicates whether internal state of this query was changed, this is used to discard internal cached objects such as the transformed query or the reference to the executed statement. #### Type `bool` ### $\_eagerLoaded protected Whether the query is standalone or the product of an eager load operation. #### Type `bool` ### $\_eagerLoader protected Instance of a class responsible for storing association containments and for eager loading them when this query is executed #### Type `Cake\ORM\EagerLoader|null` ### $\_formatters protected List of formatter classes or callbacks that will post-process the results when fetched #### Type `array<callable>` ### $\_functionsBuilder protected Instance of functions builder object used for generating arbitrary SQL functions. #### Type `Cake\Database\FunctionsBuilder|null` ### $\_hasFields protected Whether the user select any fields before being executed, this is used to determined if any fields should be automatically be selected. #### Type `bool|null` ### $\_hydrate protected Whether to hydrate results into entity objects #### Type `bool` ### $\_insertParts protected deprecated The list of query clauses to traverse for generating an INSERT statement #### Type `array<string>` ### $\_iterator protected Statement object resulting from executing this query. #### Type `Cake\Database\StatementInterface|null` ### $\_mapReduce protected List of map-reduce routines that should be applied over the query result #### Type `array` ### $\_options protected Holds any custom options passed using applyOptions that could not be processed by any method in this class. #### Type `array` ### $\_parts protected List of SQL parts that will be used to build this query. #### Type `array<string, mixed>` ### $\_repository public @property Instance of a table object this query is bound to. #### Type `Cake\ORM\Table` ### $\_resultDecorators protected A list of callback functions to be called to alter each row from resulting statement upon retrieval. Each one of the callback function will receive the row array as first argument. #### Type `array<callable>` ### $\_results protected A ResultSet. When set, query execution will be bypassed. #### Type `iterable|null` ### $\_resultsCount protected The COUNT(\*) for the query. When set, count query execution will be bypassed. #### Type `int|null` ### $\_selectParts protected deprecated The list of query clauses to traverse for generating a SELECT statement #### Type `array<string>` ### $\_selectTypeMap protected The Type map for fields in the select clause #### Type `Cake\Database\TypeMap|null` ### $\_type protected Type of this query (select, insert, update, delete). #### Type `string` ### $\_typeMap protected #### Type `Cake\Database\TypeMap|null` ### $\_updateParts protected deprecated The list of query clauses to traverse for generating an UPDATE statement #### Type `array<string>` ### $\_useBufferedResults protected Boolean for tracking whether buffered results are enabled. #### Type `bool` ### $\_valueBinder protected The object responsible for generating query placeholders and temporarily store values associated to each of those. #### Type `Cake\Database\ValueBinder|null` ### $aliasingEnabled protected Whether aliases are generated for fields. #### Type `bool` ### $typeCastEnabled protected Tracking flag to disable casting #### Type `bool`
programming_docs
cakephp Class PluginAssetsRemoveCommand Class PluginAssetsRemoveCommand ================================ Command for removing plugin assets from 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 Remove plugin assets from app's webroot. #### 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 FileEngine Class FileEngine ================= File Storage engine for cache. Filestorage is the slowest cache storage to read and write. However, it is good for servers that don't have other storage engine available, or have content which is not performance sensitive. You can configure a FileEngine cache, using Cache::config() **Namespace:** [Cake\Cache\Engine](namespace-cake.cache.engine) Constants --------- * `string` **CHECK\_KEY** ``` 'key' ``` * `string` **CHECK\_VALUE** ``` 'value' ``` Property Summary ---------------- * [$\_File](#%24_File) protected `SplFileObject|null` Instance of SplFileObject class * [$\_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 config used unless overridden by runtime configuration * [$\_groupPrefix](#%24_groupPrefix) protected `string` Contains the compiled string with all group prefixes to be prepended to every key in this cache engine * [$\_init](#%24_init) protected `bool` True unless FileEngine::\_\_active(); fails Method Summary -------------- * ##### [\_active()](#_active()) protected Determine if cache directory is writable * ##### [\_clearDirectory()](#_clearDirectory()) protected Used to clear a directory of matching files. * ##### [\_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. * ##### [\_setKey()](#_setKey()) protected Sets the current cache key this class is managing, and creates a writable SplFileObject for the cache file the key is referring to. * ##### [add()](#add()) public Add a key to the cache if it does not already exist. * ##### [clear()](#clear()) public Delete all values from the cache * ##### [clearGroup()](#clearGroup()) public Recursively deletes all files under any directory named as $group * ##### [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 Not implemented * ##### [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 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()) public Not implemented * ##### [init()](#init()) public Initialize File 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 ------------- ### \_active() protected ``` _active(): bool ``` Determine if cache directory is writable #### Returns `bool` ### \_clearDirectory() protected ``` _clearDirectory(string $path): void ``` Used to clear a directory of matching files. #### Parameters `string` $path The path to search. #### 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 ### \_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 #### Returns `string` ### \_setKey() protected ``` _setKey(string $key, bool $createKey = false): bool ``` Sets the current cache key this class is managing, and creates a writable SplFileObject for the cache file the key is referring to. #### Parameters `string` $key The key `bool` $createKey optional Whether the key should be created if it doesn't exists, or not #### Returns `bool` ### 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 values from the cache #### Returns `bool` ### clearGroup() public ``` clearGroup(string $group): bool ``` Recursively deletes all files under any directory named as $group 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 ``` Not implemented #### Parameters `string` $key The key to decrement `int` $offset optional The number to offset #### Returns `int|false` #### Throws `LogicException` ### 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> ``` 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() public ``` increment(string $key, int $offset = 1): int|false ``` Not implemented #### Parameters `string` $key The key to increment `int` $offset optional The number to offset #### Returns `int|false` #### Throws `LogicException` ### init() public ``` init(array<string, mixed> $config = []): bool ``` Initialize File 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` ### 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 --------------- ### $\_File protected Instance of SplFileObject class #### Type `SplFileObject|null` ### $\_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 config used unless overridden by runtime configuration * `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. * `lock` Used by FileCache. Should files be locked before writing to them? * `mask` The mask used for created files * `path` Path to where cachefiles should be saved. Defaults to system's temp dir. * `prefix` Prepended to all entries. Good for when you need to share a keyspace with either another cache config or another application. cache::gc from ever being called automatically. * `serialize` Should cache objects be serialized first. #### 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` ### $\_init protected True unless FileEngine::\_\_active(); fails #### Type `bool`
programming_docs
cakephp Class ContentsRegExp Class ContentsRegExp ===================== ContentsRegExp **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 #### 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 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 HeaderNotContains Class HeaderNotContains ======================== Constraint for ensuring a header does not contain a value. **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` cakephp Namespace Exception Namespace Exception =================== ### Classes * ##### [ConsoleException](class-cake.console.exception.consoleexception) Exception class for Console libraries. This exception will be thrown from Console library classes when they encounter an error. * ##### [MissingHelperException](class-cake.console.exception.missinghelperexception) Used when a Helper cannot be found. * ##### [MissingOptionException](class-cake.console.exception.missingoptionexception) Exception raised with suggestions * ##### [MissingShellException](class-cake.console.exception.missingshellexception) Used when a shell cannot be found. * ##### [MissingShellMethodException](class-cake.console.exception.missingshellmethodexception) Used when a shell method cannot be found. * ##### [MissingTaskException](class-cake.console.exception.missingtaskexception) Used when a Task cannot be found. * ##### [StopException](class-cake.console.exception.stopexception) Exception class for halting errors in console tasks cakephp Class FunctionsBuilder Class FunctionsBuilder ======================= Contains methods related to generating FunctionExpression objects with most commonly used SQL functions. This acts as a factory for FunctionExpression objects. **Namespace:** [Cake\Database](namespace-cake.database) Method Summary -------------- * ##### [\_\_call()](#__call()) public Magic method dispatcher to create custom SQL function calls * ##### [aggregate()](#aggregate()) public Helper method to create arbitrary SQL aggregate function calls. * ##### [avg()](#avg()) public Returns a AggregateExpression representing a call to SQL AVG function. * ##### [cast()](#cast()) public Returns a FunctionExpression representing a SQL CAST. * ##### [coalesce()](#coalesce()) public Returns a FunctionExpression representing a call to SQL COALESCE function. * ##### [concat()](#concat()) public Returns a FunctionExpression representing a string concatenation * ##### [count()](#count()) public Returns a AggregateExpression representing a call to SQL COUNT function. * ##### [dateAdd()](#dateAdd()) public Add the time unit to the date expression * ##### [dateDiff()](#dateDiff()) public Returns a FunctionExpression representing the difference in days between two dates. * ##### [datePart()](#datePart()) public Returns the specified date part from the SQL expression. * ##### [dayOfWeek()](#dayOfWeek()) public Returns a FunctionExpression representing a call to SQL WEEKDAY function. 1 - Sunday, 2 - Monday, 3 - Tuesday... * ##### [extract()](#extract()) public Returns the specified date part from the SQL expression. * ##### [lag()](#lag()) public Returns an AggregateExpression representing call to SQL LAG(). * ##### [lead()](#lead()) public Returns an AggregateExpression representing call to SQL LEAD(). * ##### [max()](#max()) public Returns a AggregateExpression representing a call to SQL MAX function. * ##### [min()](#min()) public Returns a AggregateExpression representing a call to SQL MIN function. * ##### [now()](#now()) public Returns a FunctionExpression representing a call that will return the current date and time. By default it returns both date and time, but you can also make it generate only the date or only the time. * ##### [rand()](#rand()) public Returns a FunctionExpression representing a call to SQL RAND function. * ##### [rowNumber()](#rowNumber()) public Returns an AggregateExpression representing call to SQL ROW\_NUMBER(). * ##### [sum()](#sum()) public Returns a AggregateExpression representing a call to SQL SUM function. * ##### [toLiteralParam()](#toLiteralParam()) protected Creates function parameter array from expression or string literal. * ##### [weekday()](#weekday()) public Returns a FunctionExpression representing a call to SQL WEEKDAY function. 1 - Sunday, 2 - Monday, 3 - Tuesday... Method Detail ------------- ### \_\_call() public ``` __call(string $name, array $args): Cake\Database\Expression\FunctionExpression ``` Magic method dispatcher to create custom SQL function calls #### Parameters `string` $name the SQL function name to construct `array` $args list with up to 3 arguments, first one being an array with parameters for the SQL function, the second one a list of types to bind to those params, and the third one the return type of the function #### Returns `Cake\Database\Expression\FunctionExpression` ### aggregate() public ``` aggregate(string $name, array $params = [], array $types = [], string $return = 'float'): Cake\Database\Expression\AggregateExpression ``` Helper method to create arbitrary SQL aggregate function calls. #### Parameters `string` $name The SQL aggregate function name `array` $params optional Array of arguments to be passed to the function. Can be an associative array with the literal value or identifier: `['value' => 'literal']` or `['value' => 'identifier'] `array` $types optional Array of types that match the names used in `$params`: `['name' => 'type']` `string` $return optional Return type of the entire expression. Defaults to float. #### Returns `Cake\Database\Expression\AggregateExpression` ### avg() public ``` avg(Cake\Database\ExpressionInterface|string $expression, array $types = []): Cake\Database\Expression\AggregateExpression ``` Returns a AggregateExpression representing a call to SQL AVG function. #### Parameters `Cake\Database\ExpressionInterface|string` $expression the function argument `array` $types optional list of types to bind to the arguments #### Returns `Cake\Database\Expression\AggregateExpression` ### cast() public ``` cast(Cake\Database\ExpressionInterface|string $field, string $type = ''): Cake\Database\Expression\FunctionExpression ``` Returns a FunctionExpression representing a SQL CAST. The `$type` parameter is a SQL type. The return type for the returned expression is the default type name. Use `setReturnType()` to update it. #### Parameters `Cake\Database\ExpressionInterface|string` $field Field or expression to cast. `string` $type optional The SQL data type #### Returns `Cake\Database\Expression\FunctionExpression` ### coalesce() public ``` coalesce(array $args, array $types = []): Cake\Database\Expression\FunctionExpression ``` Returns a FunctionExpression representing a call to SQL COALESCE function. #### Parameters `array` $args List of expressions to evaluate as function parameters `array` $types optional list of types to bind to the arguments #### Returns `Cake\Database\Expression\FunctionExpression` ### concat() public ``` concat(array $args, array $types = []): Cake\Database\Expression\FunctionExpression ``` Returns a FunctionExpression representing a string concatenation #### Parameters `array` $args List of strings or expressions to concatenate `array` $types optional list of types to bind to the arguments #### Returns `Cake\Database\Expression\FunctionExpression` ### count() public ``` count(Cake\Database\ExpressionInterface|string $expression, array $types = []): Cake\Database\Expression\AggregateExpression ``` Returns a AggregateExpression representing a call to SQL COUNT function. #### Parameters `Cake\Database\ExpressionInterface|string` $expression the function argument `array` $types optional list of types to bind to the arguments #### Returns `Cake\Database\Expression\AggregateExpression` ### dateAdd() public ``` dateAdd(Cake\Database\ExpressionInterface|string $expression, string|int $value, string $unit, array $types = []): Cake\Database\Expression\FunctionExpression ``` Add the time unit to the date expression #### Parameters `Cake\Database\ExpressionInterface|string` $expression Expression to obtain the date part from. `string|int` $value Value to be added. Use negative to subtract. `string` $unit Unit of the value e.g. hour or day. `array` $types optional list of types to bind to the arguments #### Returns `Cake\Database\Expression\FunctionExpression` ### dateDiff() public ``` dateDiff(array $args, array $types = []): Cake\Database\Expression\FunctionExpression ``` Returns a FunctionExpression representing the difference in days between two dates. #### Parameters `array` $args List of expressions to obtain the difference in days. `array` $types optional list of types to bind to the arguments #### Returns `Cake\Database\Expression\FunctionExpression` ### datePart() public ``` datePart(string $part, Cake\Database\ExpressionInterface|string $expression, array $types = []): Cake\Database\Expression\FunctionExpression ``` Returns the specified date part from the SQL expression. #### Parameters `string` $part Part of the date to return. `Cake\Database\ExpressionInterface|string` $expression Expression to obtain the date part from. `array` $types optional list of types to bind to the arguments #### Returns `Cake\Database\Expression\FunctionExpression` ### dayOfWeek() public ``` dayOfWeek(Cake\Database\ExpressionInterface|string $expression, array $types = []): Cake\Database\Expression\FunctionExpression ``` Returns a FunctionExpression representing a call to SQL WEEKDAY function. 1 - Sunday, 2 - Monday, 3 - Tuesday... #### Parameters `Cake\Database\ExpressionInterface|string` $expression the function argument `array` $types optional list of types to bind to the arguments #### Returns `Cake\Database\Expression\FunctionExpression` ### extract() public ``` extract(string $part, Cake\Database\ExpressionInterface|string $expression, array $types = []): Cake\Database\Expression\FunctionExpression ``` Returns the specified date part from the SQL expression. #### Parameters `string` $part Part of the date to return. `Cake\Database\ExpressionInterface|string` $expression Expression to obtain the date part from. `array` $types optional list of types to bind to the arguments #### Returns `Cake\Database\Expression\FunctionExpression` ### lag() public ``` lag(Cake\Database\ExpressionInterface|string $expression, int $offset, mixed $default = null, string $type = null): Cake\Database\Expression\AggregateExpression ``` Returns an AggregateExpression representing call to SQL LAG(). #### Parameters `Cake\Database\ExpressionInterface|string` $expression The value evaluated at offset `int` $offset The row offset `mixed` $default optional The default value if offset doesn't exist `string` $type optional The output type of the lag expression. Defaults to float. #### Returns `Cake\Database\Expression\AggregateExpression` ### lead() public ``` lead(Cake\Database\ExpressionInterface|string $expression, int $offset, mixed $default = null, string $type = null): Cake\Database\Expression\AggregateExpression ``` Returns an AggregateExpression representing call to SQL LEAD(). #### Parameters `Cake\Database\ExpressionInterface|string` $expression The value evaluated at offset `int` $offset The row offset `mixed` $default optional The default value if offset doesn't exist `string` $type optional The output type of the lead expression. Defaults to float. #### Returns `Cake\Database\Expression\AggregateExpression` ### max() public ``` max(Cake\Database\ExpressionInterface|string $expression, array $types = []): Cake\Database\Expression\AggregateExpression ``` Returns a AggregateExpression representing a call to SQL MAX function. #### Parameters `Cake\Database\ExpressionInterface|string` $expression the function argument `array` $types optional list of types to bind to the arguments #### Returns `Cake\Database\Expression\AggregateExpression` ### min() public ``` min(Cake\Database\ExpressionInterface|string $expression, array $types = []): Cake\Database\Expression\AggregateExpression ``` Returns a AggregateExpression representing a call to SQL MIN function. #### Parameters `Cake\Database\ExpressionInterface|string` $expression the function argument `array` $types optional list of types to bind to the arguments #### Returns `Cake\Database\Expression\AggregateExpression` ### now() public ``` now(string $type = 'datetime'): Cake\Database\Expression\FunctionExpression ``` Returns a FunctionExpression representing a call that will return the current date and time. By default it returns both date and time, but you can also make it generate only the date or only the time. #### Parameters `string` $type optional (datetime|date|time) #### Returns `Cake\Database\Expression\FunctionExpression` ### rand() public ``` rand(): Cake\Database\Expression\FunctionExpression ``` Returns a FunctionExpression representing a call to SQL RAND function. #### Returns `Cake\Database\Expression\FunctionExpression` ### rowNumber() public ``` rowNumber(): Cake\Database\Expression\AggregateExpression ``` Returns an AggregateExpression representing call to SQL ROW\_NUMBER(). #### Returns `Cake\Database\Expression\AggregateExpression` ### sum() public ``` sum(Cake\Database\ExpressionInterface|string $expression, array $types = []): Cake\Database\Expression\AggregateExpression ``` Returns a AggregateExpression representing a call to SQL SUM function. #### Parameters `Cake\Database\ExpressionInterface|string` $expression the function argument `array` $types optional list of types to bind to the arguments #### Returns `Cake\Database\Expression\AggregateExpression` ### toLiteralParam() protected ``` toLiteralParam(Cake\Database\ExpressionInterface|string $expression): arrayCake\Database\ExpressionInterface|string> ``` Creates function parameter array from expression or string literal. #### Parameters `Cake\Database\ExpressionInterface|string` $expression function argument #### Returns `arrayCake\Database\ExpressionInterface|string>` ### weekday() public ``` weekday(Cake\Database\ExpressionInterface|string $expression, array $types = []): Cake\Database\Expression\FunctionExpression ``` Returns a FunctionExpression representing a call to SQL WEEKDAY function. 1 - Sunday, 2 - Monday, 3 - Tuesday... #### Parameters `Cake\Database\ExpressionInterface|string` $expression the function argument `array` $types optional list of types to bind to the arguments #### Returns `Cake\Database\Expression\FunctionExpression`
programming_docs
cakephp Namespace Controller Namespace Controller ==================== ### Namespaces * [Cake\Controller\Component](namespace-cake.controller.component) * [Cake\Controller\Exception](namespace-cake.controller.exception) ### Classes * ##### [Component](class-cake.controller.component) Base class for an individual Component. Components provide reusable bits of controller logic that can be composed into a controller. Components also provide request life-cycle callbacks for injecting logic at specific points. * ##### [ComponentRegistry](class-cake.controller.componentregistry) ComponentRegistry is a registry for loaded components * ##### [Controller](class-cake.controller.controller) Application controller class for organization of business logic. Provides basic functionality, such as rendering views inside layouts, automatic model availability, redirection, callbacks, and more. * ##### [ControllerFactory](class-cake.controller.controllerfactory) Factory method for building controllers for request. * ##### [ErrorController](class-cake.controller.errorcontroller) Error Handling Controller cakephp Class Component Class Component ================ Base class for an individual Component. Components provide reusable bits of controller logic that can be composed into a controller. Components also provide request life-cycle callbacks for injecting logic at specific points. ### Initialize hook Like Controller and Table, this class has an initialize() hook that you can use to add custom 'constructor' logic. It is important to remember that each request (and sub-request) will only make one instance of any given component. ### Life cycle callbacks Components can provide several callbacks that are fired at various stages of the request cycle. The available callbacks are: * `beforeFilter(EventInterface $event)` Called before Controller::beforeFilter() method by default. * `startup(EventInterface $event)` Called after Controller::beforeFilter() method, and before the controller action is called. * `beforeRender(EventInterface $event)` Called before Controller::beforeRender(), and before the view class is loaded. * `afterFilter(EventInterface $event)` Called after the action is complete and the view has been rendered but before Controller::afterFilter(). * `beforeRedirect(EventInterface $event $url, Response $response)` Called before a redirect is done. Allows you to change the URL that will be redirected to by returning a Response instance with new URL set using Response::location(). Redirection can be prevented by stopping the event propagation. While the controller is not an explicit argument for the callback methods it is the subject of each event and can be fetched using EventInterface::getSubject(). **Namespace:** [Cake\Controller](namespace-cake.controller) **See:** \Cake\Controller\Controller::$components **Link:** https://book.cakephp.org/4/en/controllers/components.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 * [$\_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 -------------- * ##### [\_\_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. * ##### [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. * ##### [getController()](#getController()) public Get the controller this component is bound to. * ##### [implementedEvents()](#implementedEvents()) public Get the Controller callbacks this Component is interested in. * ##### [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. * ##### [setConfig()](#setConfig()) public Sets the config. 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): 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 ### 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` ### getController() public ``` getController(): Cake\Controller\Controller ``` Get the controller this component is bound to. #### Returns `Cake\Controller\Controller` ### implementedEvents() public ``` implementedEvents(): array<string, mixed> ``` Get the Controller callbacks this Component is interested in. 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` ### 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 --------------- ### $\_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>` ### $\_registry protected Component registry class used to lazy load components. #### Type `Cake\Controller\ComponentRegistry` ### $components protected Other Components this component uses. #### Type `array` cakephp Class MissingTableClassException Class MissingTableClassException ================================= Exception raised when a Table 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 RedirectException Class RedirectException ======================== An exception subclass used by the routing layer to indicate that a route has resolved to a redirect. The URL and status code are provided as constructor arguments. ``` throw new RedirectException('http://example.com/some/path', 301); ``` If you need a more general purpose redirect exception use {@link \Cake\Http\Exception\RedirectException} instead of this class. **Namespace:** [Cake\Routing\Exception](namespace-cake.routing.exception) **Deprecated:** 4.1.0 Use {@link \Cake\Http\Exception\RedirectException} instead. 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 ClassNode Class ClassNode ================ Dump node for objects/class instances. **Namespace:** [Cake\Error\Debug](namespace-cake.error.debug) Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [addProperty()](#addProperty()) public Add a property * ##### [getChildren()](#getChildren()) public Get property nodes * ##### [getId()](#getId()) public Get the reference id * ##### [getValue()](#getValue()) public Get the class name Method Detail ------------- ### \_\_construct() public ``` __construct(string $class, int $id) ``` Constructor #### Parameters `string` $class The class name `int` $id The reference id of this object in the DumpContext ### addProperty() public ``` addProperty(Cake\Error\Debug\PropertyNode $node): void ``` Add a property #### Parameters `Cake\Error\Debug\PropertyNode` $node The property to add. #### Returns `void` ### getChildren() public ``` getChildren(): arrayCake\Error\Debug\PropertyNode> ``` Get property nodes #### Returns `arrayCake\Error\Debug\PropertyNode>` ### getId() public ``` getId(): int ``` Get the reference id #### Returns `int` ### getValue() public ``` getValue(): string ``` Get the class name #### Returns `string` cakephp Class NegotiationRequiredView Class NegotiationRequiredView ============================== A view class that responds to any content-type and can be used to create an empty body 406 status code response. This is most useful when using content-type negotiation via `viewClasses()` in your controller. Add this View at the end of the acceptable View classes to require clients to pick an available content-type and that you have no default type. **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 custom 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. * [$\_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` The name of the layouts subfolder containing layouts for this View. * [$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` Sub-directory for this template file. This is often used for extension based routing. Eg. With an `xml` extension, $subDir would be `xml/` * [$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 * ##### [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 Get the content-type * ##### [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 Interact with the HelperRegistry to load all the helpers. * ##### [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 Renders view with no body and a 406 status code. * ##### [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` ### 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 ``` Get the content-type #### 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 ``` Interact with the HelperRegistry to load all the helpers. #### 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 ``` Renders view with no body and a 406 status code. 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 Name of template file to use `string|false|null` $layout optional Layout to use. False to disable. #### 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 custom config options. #### 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[]>` ### $\_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 The name of the layouts subfolder containing layouts for this View. #### 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 Sub-directory for this template file. This is often used for extension based routing. Eg. With an `xml` extension, $subDir would be `xml/` #### 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 StatusFailure Class StatusFailure ==================== StatusFailure **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` cakephp Class Uri Class 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 This class is an internal implementation workaround that will be removed in 5.x **Namespace:** [Cake\Http](namespace-cake.http) Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor * ##### [\_\_get()](#__get()) public Backwards compatibility shim for previously dynamic properties. * ##### [\_\_toString()](#__toString()) public Return the string representation as a URI reference. * ##### [getAuthority()](#getAuthority()) public Retrieve the authority component of the URI. * ##### [getBase()](#getBase()) public Get the application base path. * ##### [getFragment()](#getFragment()) public Retrieve the fragment component of the URI. * ##### [getHost()](#getHost()) public Retrieve the host component of the URI. * ##### [getPath()](#getPath()) public Retrieve the path component of the URI. * ##### [getPort()](#getPort()) public Retrieve the port component of the URI. * ##### [getQuery()](#getQuery()) public Retrieve the query string of the URI. * ##### [getScheme()](#getScheme()) public Retrieve the scheme component of the URI. * ##### [getUri()](#getUri()) public Get the decorated URI * ##### [getUserInfo()](#getUserInfo()) public Retrieve the user information component of the URI. * ##### [getWebroot()](#getWebroot()) public Get the application webroot path. * ##### [withFragment()](#withFragment()) public Return an instance with the specified URI fragment. * ##### [withHost()](#withHost()) public Return an instance with the specified host. * ##### [withPath()](#withPath()) public Return an instance with the specified path. * ##### [withPort()](#withPort()) public Return an instance with the specified port. * ##### [withQuery()](#withQuery()) public Return an instance with the specified query string. * ##### [withScheme()](#withScheme()) public Return an instance with the specified scheme. * ##### [withUserInfo()](#withUserInfo()) public Return an instance with the specified user information. Method Detail ------------- ### \_\_construct() public ``` __construct(Psr\Http\Message\UriInterface $uri, string $base, string $webroot) ``` Constructor #### Parameters `Psr\Http\Message\UriInterface` $uri Uri instance to decorate `string` $base The base path. `string` $webroot The webroot path. ### \_\_get() public ``` __get(string $name): mixed ``` Backwards compatibility shim for previously dynamic properties. #### Parameters `string` $name The attribute to read. #### Returns `mixed` ### \_\_toString() public ``` __toString(): string ``` Return the string representation as a URI reference. Depending on which components of the URI are present, the resulting string is either a full URI or relative reference according to RFC 3986, Section 4.1. The method concatenates the various components of the URI, using the appropriate delimiters: * If a scheme is present, it MUST be suffixed by ":". * If an authority is present, it MUST be prefixed by "//". * The path can be concatenated without delimiters. But there are two cases where the path has to be adjusted to make the URI reference valid as PHP does not allow to throw an exception in \_\_toString(): + If the path is rootless and an authority is present, the path MUST be prefixed by "/". + If the path is starting with more than one "/" and no authority is present, the starting slashes MUST be reduced to one. * If a query is present, it MUST be prefixed by "?". * If a fragment is present, it MUST be prefixed by "#". #### Returns `string` ### getAuthority() public ``` getAuthority(): string ``` Retrieve the authority component of the URI. If no authority information is present, this method MUST return an empty string. The authority syntax of the URI is: ``` [user-info@]host[:port] ``` If the port component is not set or is the standard port for the current scheme, it SHOULD NOT be included. #### Returns `string` ### getBase() public ``` getBase(): string ``` Get the application base path. #### Returns `string` ### getFragment() public ``` getFragment(): string ``` Retrieve the fragment component of the URI. If no fragment is present, this method MUST return an empty string. The leading "#" character is not part of the fragment and MUST NOT be added. The value returned MUST be percent-encoded, but MUST NOT double-encode any characters. To determine what characters to encode, please refer to RFC 3986, Sections 2 and 3.5. #### Returns `string` ### getHost() public ``` getHost(): string ``` Retrieve the host component of the URI. If no host is present, this method MUST return an empty string. The value returned MUST be normalized to lowercase, per RFC 3986 Section 3.2.2. #### Returns `string` ### getPath() public ``` getPath(): string ``` Retrieve the path component of the URI. The path can either be empty or absolute (starting with a slash) or rootless (not starting with a slash). Implementations MUST support all three syntaxes. Normally, the empty path "" and absolute path "/" are considered equal as defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically do this normalization because in contexts with a trimmed base path, e.g. the front controller, this difference becomes significant. It's the task of the user to handle both "" and "/". The value returned MUST be percent-encoded, but MUST NOT double-encode any characters. To determine what characters to encode, please refer to RFC 3986, Sections 2 and 3.3. As an example, if the value should include a slash ("/") not intended as delimiter between path segments, that value MUST be passed in encoded form (e.g., "%2F") to the instance. #### Returns `string` ### getPort() public ``` getPort(): null|int ``` Retrieve the port component of the URI. If a port is present, and it is non-standard for the current scheme, this method MUST return it as an integer. If the port is the standard port used with the current scheme, this method SHOULD return null. If no port is present, and no scheme is present, this method MUST return a null value. If no port is present, but a scheme is present, this method MAY return the standard port for that scheme, but SHOULD return null. #### Returns `null|int` ### getQuery() public ``` getQuery(): string ``` Retrieve the query string of the URI. If no query string is present, this method MUST return an empty string. The leading "?" character is not part of the query and MUST NOT be added. The value returned MUST be percent-encoded, but MUST NOT double-encode any characters. To determine what characters to encode, please refer to RFC 3986, Sections 2 and 3.4. As an example, if a value in a key/value pair of the query string should include an ampersand ("&") not intended as a delimiter between values, that value MUST be passed in encoded form (e.g., "%26") to the instance. #### Returns `string` ### getScheme() public ``` getScheme(): string ``` Retrieve the scheme component of the URI. If no scheme is present, this method MUST return an empty string. The value returned MUST be normalized to lowercase, per RFC 3986 Section 3.1. The trailing ":" character is not part of the scheme and MUST NOT be added. #### Returns `string` ### getUri() public ``` getUri(): Psr\Http\Message\UriInterface ``` Get the decorated URI #### Returns `Psr\Http\Message\UriInterface` ### getUserInfo() public ``` getUserInfo(): string ``` Retrieve the user information component of the URI. If no user information is present, this method MUST return an empty string. If a user is present in the URI, this will return that value; additionally, if the password is also present, it will be appended to the user value, with a colon (":") separating the values. The trailing "@" character is not part of the user information and MUST NOT be added. #### Returns `string` ### getWebroot() public ``` getWebroot(): string ``` Get the application webroot path. #### Returns `string` ### withFragment() public ``` withFragment(string $fragment): static ``` Return an instance with the specified URI fragment. This method MUST retain the state of the current instance, and return an instance that contains the specified URI fragment. Users can provide both encoded and decoded fragment characters. Implementations ensure the correct encoding as outlined in getFragment(). An empty fragment value is equivalent to removing the fragment. #### Parameters `string` $fragment #### Returns `static` ### withHost() public ``` withHost(string $host): static ``` Return an instance with the specified host. This method MUST retain the state of the current instance, and return an instance that contains the specified host. An empty host value is equivalent to removing the host. #### Parameters `string` $host #### Returns `static` ### withPath() public ``` withPath(string $path): static ``` Return an instance with the specified path. This method MUST retain the state of the current instance, and return an instance that contains the specified path. The path can either be empty or absolute (starting with a slash) or rootless (not starting with a slash). Implementations MUST support all three syntaxes. If the path is intended to be domain-relative rather than path relative then it must begin with a slash ("/"). Paths not starting with a slash ("/") are assumed to be relative to some base path known to the application or consumer. Users can provide both encoded and decoded path characters. Implementations ensure the correct encoding as outlined in getPath(). #### Parameters `string` $path #### Returns `static` ### withPort() public ``` withPort(null|int $port): static ``` Return an instance with the specified port. This method MUST retain the state of the current instance, and return an instance that contains the specified port. Implementations MUST raise an exception for ports outside the established TCP and UDP port ranges. A null value provided for the port is equivalent to removing the port information. #### Parameters `null|int` $port #### Returns `static` ### withQuery() public ``` withQuery(string $query): static ``` Return an instance with the specified query string. This method MUST retain the state of the current instance, and return an instance that contains the specified query string. Users can provide both encoded and decoded query characters. Implementations ensure the correct encoding as outlined in getQuery(). An empty query string value is equivalent to removing the query string. #### Parameters `string` $query #### Returns `static` ### withScheme() public ``` withScheme(string $scheme): static ``` Return an instance with the specified scheme. This method MUST retain the state of the current instance, and return an instance that contains the specified scheme. Implementations MUST support the schemes "http" and "https" case insensitively, and MAY accommodate other schemes if required. An empty scheme is equivalent to removing the scheme. #### Parameters `string` $scheme #### Returns `static` ### withUserInfo() public ``` withUserInfo(string $user, null|string $password = null): static ``` Return an instance with the specified user information. This method MUST retain the state of the current instance, and return an instance that contains the specified user information. Password is optional, but the user information MUST include the user; an empty string for the user is equivalent to removing user information. #### Parameters `string` $user `null|string` $password optional #### Returns `static`
programming_docs
cakephp Namespace Shell Namespace Shell =============== ### Namespaces * [Cake\Shell\Helper](namespace-cake.shell.helper) * [Cake\Shell\Task](namespace-cake.shell.task) cakephp Class LinkConstraint Class LinkConstraint ===================== Checks whether links to a given association exist / do not exist. **Namespace:** [Cake\ORM\Rule](namespace-cake.orm.rule) Constants --------- * `string` **STATUS\_LINKED** ``` 'linked' ``` Status that requires a link to be present. * `string` **STATUS\_NOT\_LINKED** ``` 'notLinked' ``` Status that requires a link to not be present. Property Summary ---------------- * [$\_association](#%24_association) protected `Cake\ORM\Association|string` The association that should be checked. * [$\_requiredLinkState](#%24_requiredLinkState) protected `string` The link status that is required to be present in order for the check to succeed. Method Summary -------------- * ##### [\_\_construct()](#__construct()) public Constructor. * ##### [\_\_invoke()](#__invoke()) public Callable handler. * ##### [\_aliasFields()](#_aliasFields()) protected Alias fields. * ##### [\_buildConditions()](#_buildConditions()) protected Build conditions. * ##### [\_countLinks()](#_countLinks()) protected Count links. Method Detail ------------- ### \_\_construct() public ``` __construct(Cake\ORM\Association|string $association, string $requiredLinkStatus) ``` Constructor. #### Parameters `Cake\ORM\Association|string` $association The alias of the association that should be checked. `string` $requiredLinkStatus The link status that is required to be present in order for the check to succeed. ### \_\_invoke() public ``` __invoke(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options): bool ``` Callable handler. Performs the actual link check. #### Parameters `Cake\Datasource\EntityInterface` $entity The entity involved in the operation. `array<string, mixed>` $options Options passed from the rules checker. #### Returns `bool` ### \_aliasFields() protected ``` _aliasFields(array<string> $fields, Cake\ORM\Table $source): array<string> ``` Alias fields. #### Parameters `array<string>` $fields The fields that should be aliased. `Cake\ORM\Table` $source The object to use for aliasing. #### Returns `array<string>` ### \_buildConditions() protected ``` _buildConditions(array $fields, array $values): array ``` Build conditions. #### Parameters `array` $fields The condition fields. `array` $values The condition values. #### Returns `array` ### \_countLinks() protected ``` _countLinks(Cake\ORM\Association $association, Cake\Datasource\EntityInterface $entity): int ``` Count links. #### Parameters `Cake\ORM\Association` $association The association for which to count links. `Cake\Datasource\EntityInterface` $entity The entity involved in the operation. #### Returns `int` Property Detail --------------- ### $\_association protected The association that should be checked. #### Type `Cake\ORM\Association|string` ### $\_requiredLinkState protected The link status that is required to be present in order for the check to succeed. #### Type `string` love ImageData:getFormat ImageData:getFormat =================== **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This function is not supported in earlier versions. Gets the [pixel format](pixelformat "PixelFormat") of the ImageData. Function -------- ### Synopsis ``` format = ImageData:getFormat( ) ``` ### Arguments None. ### Returns `[PixelFormat](pixelformat "PixelFormat") format` The pixel format the ImageData was created with. See Also -------- * [ImageData](imagedata "ImageData") love Source:getVelocity Source:getVelocity ================== **Available since LÖVE [0.7.0](https://love2d.org/wiki/0.7.0 "0.7.0")** This function is not supported in earlier versions. Gets the velocity of the Source. Function -------- ### Synopsis ``` x, y, z = Source:getVelocity( ) ``` ### Arguments None. ### Returns `[number](number "number") x` The X part of the velocity vector. `[number](number "number") y` The Y part of the velocity vector. `[number](number "number") z` The Z part of the velocity vector. See Also -------- * [Source](source "Source") * [Source:setVelocity](source-setvelocity "Source:setVelocity") love love.audio.setDistanceModel love.audio.setDistanceModel =========================== **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This function is not supported in earlier versions. Sets the distance attenuation model. Function -------- ### Synopsis ``` love.audio.setDistanceModel( model ) ``` ### Arguments `[DistanceModel](distancemodel "DistanceModel") model` The new distance model. ### Returns Nothing. See Also -------- * [love.audio](love.audio "love.audio") love love.joystickaxis love.joystickaxis ================= **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This callback is not supported in earlier versions. Called when a joystick axis moves. Function -------- ### Synopsis ``` love.joystickaxis( joystick, axis, value ) ``` ### Arguments `[Joystick](joystick "Joystick") joystick` The joystick object. `[number](number "number") axis` The axis number. `[number](number "number") value` The new axis value. ### Returns Nothing. See Also -------- * [love](love "love") love Mesh:setDrawMode Mesh:setDrawMode ================ **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Sets the mode used when drawing the Mesh. Function -------- ### Synopsis ``` Mesh:setDrawMode( mode ) ``` ### Arguments `[MeshDrawMode](meshdrawmode "MeshDrawMode") mode` The mode to use when drawing the Mesh. ### Returns Nothing. See Also -------- * [Mesh](mesh "Mesh") * [Mesh:getDrawMode](mesh-getdrawmode "Mesh:getDrawMode") love Source:getRolloff Source:getRolloff ================= **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This function is not supported in earlier versions. Returns the rolloff factor of the source. Function -------- ### Synopsis ``` rolloff = Source:getRolloff( ) ``` ### Arguments None. ### Returns `[number](number "number") rolloff` The rolloff factor. See Also -------- * [Source](source "Source") love ParticleSystem:setEmissionArea ParticleSystem:setEmissionArea ============================== **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** It has been renamed from [ParticleSystem:setAreaSpread](particlesystem-setareaspread "ParticleSystem:setAreaSpread"). Sets area-based spawn parameters for the particles. Newly created particles will spawn in an area around the emitter based on the parameters to this function. Function -------- ### Synopsis ``` ParticleSystem:setEmissionArea( distribution, dx, dy, angle, directionRelativeToCenter ) ``` ### Arguments `[AreaSpreadDistribution](areaspreaddistribution "AreaSpreadDistribution") distribution` The type of distribution for new particles. `[number](number "number") dx` The maximum spawn distance from the emitter along the x-axis for uniform distribution, or the standard deviation along the x-axis for normal distribution. `[number](number "number") dy` The maximum spawn distance from the emitter along the y-axis for uniform distribution, or the standard deviation along the y-axis for normal distribution. `[number](number "number") angle (0)` The angle in radians of the emission area. `[boolean](boolean "boolean") directionRelativeToCenter (false)` True if newly spawned particles will be oriented relative to the center of the emission area, false otherwise. ### Returns Nothing. See Also -------- * [ParticleSystem](particlesystem "ParticleSystem") * [ParticleSystem:getEmissionArea](particlesystem-getemissionarea "ParticleSystem:getEmissionArea") love love.graphics.getLineStipple love.graphics.getLineStipple ============================ **Removed in LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This function is not supported in that and later versions. Gets the current line stipple. Function -------- ### Synopsis ``` pattern, repeat = love.graphics.getLineStipple( ) ``` ### Arguments None. ### Returns `[number](number "number") pattern` The 16-bit stipple pattern. `[number](number "number") repeat` The repeat factor. See Also -------- * [love.graphics](love.graphics "love.graphics") love Video:getWidth Video:getWidth ============== **Available since LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** This function is not supported in earlier versions. Gets the width of the Video in pixels. Function -------- ### Synopsis ``` width = Video:getWidth( ) ``` ### Arguments None. ### Returns `[number](number "number") width` The width of the Video. See Also -------- * [Video](video "Video") * [Video:getHeight](video-getheight "Video:getHeight") * [Video:getDimensions](video-getdimensions "Video:getDimensions") love Framebuffer:setWrap Framebuffer:setWrap =================== **Available since LÖVE [0.7.2](https://love2d.org/wiki/0.7.2 "0.7.2")** This function is not supported in earlier versions. **Removed in LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** It has been renamed to [Canvas:setWrap](canvas-setwrap "Canvas:setWrap"). Sets the wrapping properties of a Framebuffer. This function sets the way the edges of a Framebuffer are treated if it is scaled or rotated. If the WrapMode is set to 'clamp', the edge will not be interpolated. If set to 'repeat', the edge will be interpolated with the pixels on the opposing side of the framebuffer. Function -------- ### Synopsis ``` Framebuffer:setWrap( horiz, vert ) ``` ### Arguments `[WrapMode](wrapmode "WrapMode") horiz` Horizontal wrapping mode of the framebuffer. `[WrapMode](wrapmode "WrapMode") vert` Vertical wrapping mode of the framebuffer. ### Returns Nothing. See Also -------- * [Framebuffer](framebuffer "Framebuffer") * [WrapMode](wrapmode "WrapMode") love Font:setLineHeight Font:setLineHeight ================== Sets the line height. When rendering the font in lines the actual height will be determined by the line height multiplied by the height of the font. The default is `1.0`. Function -------- ### Synopsis ``` Font:setLineHeight( height ) ``` ### Arguments `[number](number "number") height` The new line height. ### Returns Nothing. See Also -------- * [Font](font "Font") * [Font:getLineHeight](font-getlineheight "Font:getLineHeight") love FileMode FileMode ======== The different modes you can open a [File](file "File") in. Constants --------- r Open a file for read. w Open a file for write. a Open a file for append. c Do not open a file (represents a closed file.) See Also -------- * [File](file "File") * [File:open]((file)-open "(File):open") * [love.filesystem](love.filesystem "love.filesystem") * [love.filesystem.newFile](love.filesystem.newfile "love.filesystem.newFile") love Source:setCone Source:setCone ============== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Sets the Source's directional volume cones. Together with [Source:setDirection](source-setdirection "Source:setDirection"), the cone angles allow for the Source's volume to vary depending on its direction. Function -------- ### Synopsis ``` Source:setCone( innerAngle, outerAngle, outerVolume ) ``` ### Arguments `[number](number "number") innerAngle` The inner angle from the Source's direction, in radians. The Source will play at normal volume if the listener is inside the cone defined by this angle. `[number](number "number") outerAngle` The outer angle from the Source's direction, in radians. The Source will play at a volume between the normal and outer volumes, if the listener is in between the cones defined by the inner and outer angles. `[number](number "number") outerVolume (0)` The Source's volume when the listener is outside both the inner and outer cone angles. ### Returns Nothing. See Also -------- * [Source](source "Source") * [Source:getCone](source-getcone "Source:getCone") * [Source:setDirection](source-setdirection "Source:setDirection") love ChainShape:getVertexCount ChainShape:getVertexCount ========================= **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This function is not supported in earlier versions. Returns the number of vertices the shape has. Function -------- ### Synopsis ``` count = ChainShape:getVertexCount( ) ``` ### Arguments None. ### Returns `[number](number "number") count` The number of vertices. See Also -------- * [ChainShape](chainshape "ChainShape") love Font:getFilter Font:getFilter ============== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Gets the filter mode for a font. Function -------- ### Synopsis ``` min, mag, anisotropy = Font:getFilter( ) ``` ### Arguments None. ### Returns `[FilterMode](filtermode "FilterMode") min` Filter mode used when minifying the font. `[FilterMode](filtermode "FilterMode") mag` Filter mode used when magnifying the font. `[number](number "number") anisotropy` Maximum amount of anisotropic filtering used. See Also -------- * [Font](font "Font") * [FilterMode](filtermode "FilterMode") love love.graphics.rotate love.graphics.rotate ==================== Rotates the coordinate system in two dimensions. Calling this function affects all future drawing operations by rotating the coordinate system around the origin by the given amount of radians. This change lasts until love.draw() exits. Function -------- ### Synopsis ``` love.graphics.rotate( angle ) ``` ### Arguments `[number](number "number") angle` The amount to rotate the coordinate system in radians. ### Returns Nothing. Examples -------- ### Rotating a static scene This example shows how to rotate a static scene around a given point. Since the rotation is always around the origin, translating the center of the screen to the origin and back around the rotate operation makes the effective rotation point be the center of the screen. This is demonstrated by drawing a rectangle that shows the rotation and a point that is right in the center and thus does not move when the scene rotates. Note that the drawing commands have coordinates that depend solely on the screen size. ``` local angle = 0   function love.draw() local width = love.graphics.getWidth() local height = love.graphics.getHeight() -- rotate around the center of the screen by angle radians love.graphics.translate(width/2, height/2) love.graphics.rotate(angle) love.graphics.translate(-width/2, -height/2) -- draw a white rectangle slightly off center love.graphics.setColor(0xff, 0xff, 0xff) love.graphics.rectangle('fill', width/2-100, height/2-100, 300, 400) -- draw a five-pixel-wide blue point at the center love.graphics.setPointSize(5) love.graphics.setColor(0, 0, 0xff) love.graphics.points(width/2, height/2) end   function love.update(dt) love.timer.sleep(.01) angle = angle + dt * math.pi/2 angle = angle % (2*math.pi) end ``` ### Rotating the entire screen This example shows how you can rotate the screen 90 degrees, counter clockwise. Especially useful if you just distribute .love files for android, where the game always starts in landscape mode. After this, the width and height of the canvas will be "swapped". Don't forget to always translate the input and do all the screen bounds specific checks accordingly. ``` function love.load() --get the width and height of the CANVAS, not of the DESKTOP width, height = love.graphics.getWidth(), love.graphics.getHeight() end   function love.draw() love.graphics.translate(width/2, height/2) love.graphics.rotate(-math.pi / 2) love.graphics.translate(-height/2, -width/2)   love.graphics.setColor(255, 0, 0) love.graphics.points(0, 0) --It will require zoom to observe the 1 pixel point, but it goes to show that it works. end   -- simple function for translating mouse input, for example local function translate(_x, _y) local y = _x local x = height - _y   return x, y end --[[ --Say you are doing love.graphics.rectangle("fill", 150, 170, 125, 145), in the translated system, like above --You would just need to translate(x, y) the mouse input and then check the x to be within --[150, 275] and y within [170, 315] respectively. No inversion of width and height. --]] ``` See Also -------- * [love.graphics](love.graphics "love.graphics") * [love.graphics.pop](love.graphics.pop "love.graphics.pop") * [love.graphics.push](love.graphics.push "love.graphics.push") * [love.graphics.scale](love.graphics.scale "love.graphics.scale") * [love.graphics.shear](love.graphics.shear "love.graphics.shear") * [love.graphics.translate](love.graphics.translate "love.graphics.translate") * [love.graphics.origin](love.graphics.origin "love.graphics.origin") love love.graphics.getCompressedImageFormats love.graphics.getCompressedImageFormats ======================================= **Available since LÖVE [0.9.2](https://love2d.org/wiki/0.9.2 "0.9.2") and removed in LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** It has been replaced by [love.graphics.getImageFormats](love.graphics.getimageformats "love.graphics.getImageFormats"). Gets the available [compressed image formats](compressedformat "CompressedFormat"), and whether each is supported. Function -------- ### Synopsis ``` formats = love.graphics.getCompressedImageFormats( ) ``` ### Arguments None. ### Returns `[table](table "table") formats` A table containing [CompressedImageFormats](compressedimageformat "CompressedImageFormat") as keys, and a boolean indicating whether the format is supported as values. Not all systems support all formats. Examples -------- ### Display a list of the compressed image formats on the screen ``` formats = love.graphics.getCompressedImageFormats()   function love.draw() local y = 0 for formatname, formatsupported in pairs(formats) do local str = string.format("Supports format '%s': %s", formatname, tostring(formatsupported)) love.graphics.print(str, 10, y) y = y + 20 end end ``` See Also -------- * [love.graphics](love.graphics "love.graphics") * [CompressedImageFormat](compressedimageformat "CompressedImageFormat") * [love.graphics.newImage](love.graphics.newimage "love.graphics.newImage") * [love.image.newCompressedData](love.image.newcompresseddata "love.image.newCompressedData") love love.event.pump love.event.pump =============== **Available since LÖVE [0.6.0](https://love2d.org/wiki/0.6.0 "0.6.0")** This function is not supported in earlier versions. Pump events into the event queue. This is a low-level function, and is usually not called by the user, but by `[love.run](love.run "love.run")`. Note that this does need to be called for any OS to think you're still running, and if you want to handle OS-generated events at all (think callbacks). love.event.pump can only be called from the main thread, but afterwards, the rest of love.event can be used from any other thread. Function -------- ### Synopsis ``` love.event.pump( ) ``` ### Arguments None. ### Returns Nothing. See Also -------- * [love.event.poll](love.event.poll "love.event.poll") * [love.event.wait](love.event.wait "love.event.wait") * [love.event](love.event "love.event")
programming_docs
love RevoluteJoint:setMotorEnabled RevoluteJoint:setMotorEnabled ============================= **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** It has been renamed from [RevoluteJoint:enableMotor](revolutejoint-enablemotor "RevoluteJoint:enableMotor"). Enables/disables the joint motor. Function -------- ### Synopsis ``` RevoluteJoint:setMotorEnabled( enable ) ``` ### Arguments `[boolean](boolean "boolean") enable` True to enable, false to disable. ### Returns Nothing. See Also -------- * [RevoluteJoint](revolutejoint "RevoluteJoint") love ParticleSystem:isStopped ParticleSystem:isStopped ======================== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Checks whether the particle system is stopped. Function -------- ### Synopsis ``` stopped = ParticleSystem:isStopped( ) ``` ### Arguments None. ### Returns `[boolean](boolean "boolean") stopped` True if system is stopped, false otherwise. See Also -------- * [ParticleSystem](particlesystem "ParticleSystem") * [ParticleSystem:isActive](particlesystem-isactive "ParticleSystem:isActive") * [ParticleSystem:isPaused](particlesystem-ispaused "ParticleSystem:isPaused") love RevoluteJoint:getLimits RevoluteJoint:getLimits ======================= Gets the joint limits. Function -------- ### Synopsis ``` lower, upper = RevoluteJoint:getLimits( ) ``` ### Arguments None. ### Returns `[number](number "number") lower` The lower limit, in radians. `[number](number "number") upper` The upper limit, in radians. See Also -------- * [RevoluteJoint](revolutejoint "RevoluteJoint") love Shape:getDensity Shape:getDensity ================ **Removed in LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This function is not supported in that and later versions. Gets the density of the Shape. Function -------- ### Synopsis ``` density = Shape:getDensity( ) ``` ### Arguments None. ### Returns `[number](number "number") density` The density of the Shape. See Also -------- * [Shape](shape "Shape") love Font:getLineHeight Font:getLineHeight ================== Gets the line height. This will be the value previously set by [Font:setLineHeight](font-setlineheight "Font:setLineHeight"), or `1.0` by default. Function -------- ### Synopsis ``` height = Font:getLineHeight( ) ``` ### Arguments None. ### Returns `[number](number "number") height` The current line height. See Also -------- * [Font](font "Font") * [Font:setLineHeight](font-setlineheight "Font:setLineHeight") love love.audio.stop love.audio.stop =============== Stops currently played [sources](source "Source"). Function -------- This function will stop all currently active [sources](source "Source"). ### Synopsis ``` love.audio.stop( ) ``` ### Arguments None. ### Returns Nothing. Function -------- This function will only stop the specified [source](source "Source"). ### Synopsis ``` love.audio.stop( source ) ``` ### Arguments `[Source](source "Source") source` The [source](source "Source") on which to stop the playback. ### Returns Nothing. Function -------- **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This variant is not supported in earlier versions. Simultaneously stops all given [Sources](source "Source"). ### Synopsis ``` love.audio.stop( source1, source2, ... ) ``` ### Arguments `[Source](source "Source") source1` The first Source to stop. `[Source](source "Source") source2` The second Source to stop. `[Source](source "Source") ...` Additional Sources to stop. ### Returns Nothing. Function -------- **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This variant is not supported in earlier versions. Simultaneously stops all given [Sources](source "Source"). ### Synopsis ``` love.audio.stop( sources ) ``` ### Arguments `[table](table "table") sources` A table containing a list of Sources to stop. ### Returns Nothing. See Also -------- * [love.audio](love.audio "love.audio") love love.event.clear love.event.clear ================ **Available since LÖVE [0.7.2](https://love2d.org/wiki/0.7.2 "0.7.2")** This function is not supported in earlier versions. Clears the event queue. Function -------- ### Synopsis ``` love.event.clear() ``` ### Arguments None. ### Returns Nothing. See Also -------- * [love.event](love.event "love.event") love Video:isPlaying Video:isPlaying =============== **Available since LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** This function is not supported in earlier versions. Gets whether the Video is currently playing. Function -------- ### Synopsis ``` playing = Video:isPlaying( ) ``` ### Arguments None. ### Returns `[boolean](boolean "boolean") playing` Whether the video is playing. See Also -------- * [Video](video "Video") * [Video:play](video-play "Video:play") * [Video:pause](video-pause "Video:pause") love love.mousepressed love.mousepressed ================= Callback function triggered when a mouse button is pressed. Function -------- ### Synopsis ``` love.mousepressed( x, y, button, istouch, presses ) ``` ### Arguments `[number](number "number") x` Mouse x position, in pixels. `[number](number "number") y` Mouse y position, in pixels. `[number](number "number") button` The button index that was pressed. 1 is the primary mouse button, 2 is the secondary mouse button and 3 is the middle button. Further buttons are mouse dependent. `[boolean](boolean "boolean") istouch` True if the mouse button press originated from a touchscreen touch-press. `[number](number "number") presses` Available since 11.0 The number of presses in a short time frame and small area, used to simulate double, triple clicks ### Returns Nothing. ### Notes Use [love.wheelmoved](love.wheelmoved "love.wheelmoved") to detect mouse wheel motion. It will not register as a button press in version [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0") and newer. Function -------- **Removed in LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** This variant is not supported in that and later versions. ### Synopsis ``` love.mousepressed( x, y, button ) ``` ### Arguments `[number](number "number") x` Mouse x position. `[number](number "number") y` Mouse y position. `[MouseConstant](mouseconstant "MouseConstant") button` Mouse button pressed. ### Returns Nothing. Examples -------- Position a string ("Text") wherever the user left-clicks. ``` function love.load() printx = 0 printy = 0 end   function love.draw() love.graphics.print("Text", printx, printy) end   function love.mousepressed(x, y, button, istouch) if button == 1 then -- Versions prior to 0.10.0 use the MouseConstant 'l' printx = x printy = y end end ``` See Also -------- * [love](love "love") * [love.mousereleased](love.mousereleased "love.mousereleased") * [love.mouse.isDown](love.mouse.isdown "love.mouse.isDown") love love.system.getOS love.system.getOS ================= **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Gets the current operating system. In general, LÖVE abstracts away the need to know the current operating system, but there are a few cases where it can be useful (especially in combination with [os.execute](https://www.lua.org/manual/5.1/manual.html#pdf-os.execute).) Function -------- ### Synopsis ``` osString = love.system.getOS( ) ``` ### Arguments None. ### Returns `[string](string "string") osString` The current operating system. `"OS X"`, `"Windows"`, `"Linux"`, `"Android"` or `"iOS"`. Notes ----- In LÖVE version [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0"), the **love.\_os** string contains the current operating system. See Also -------- * [love.system](love.system "love.system") love love.joystick.getNumBalls love.joystick.getNumBalls ========================= **Available since LÖVE [0.5.0](https://love2d.org/wiki/0.5.0 "0.5.0") and removed in LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier or later versions. Returns the number of balls on the joystick. Function -------- ### Synopsis ``` balls = love.joystick.getNumBalls( joystick ) ``` ### Arguments `[number](number "number") joystick` The joystick to be checked ### Returns `[number](number "number") balls` The number of balls available See Also -------- * [love.joystick](love.joystick "love.joystick") love WheelJoint:getSpringFrequency WheelJoint:getSpringFrequency ============================= **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This method is not supported in earlier versions. Returns the spring frequency. Function -------- ### Synopsis ``` freq = WheelJoint:getSpringFrequency( ) ``` ### Arguments None. ### Returns `[number](number "number") freq` The frequency in hertz. See Also -------- * [WheelJoint](wheeljoint "WheelJoint") * [WheelJoint:setSpringFrequency](wheeljoint-setspringfrequency "WheelJoint:setSpringFrequency") love PulleyJoint:getLength2 PulleyJoint:getLength2 ====================== **Removed in LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This method is not supported in that and later versions. ".0" can not be assigned to a declared number type with value 0.8. Get the current length of the rope segment attached to the second body. Function -------- ### Synopsis ``` length = PulleyJoint:getLength2( ) ``` ### Arguments None. ### Returns `[number](number "number") length` The length of the rope segment. See Also -------- * [PulleyJoint](pulleyjoint "PulleyJoint") love Body:getMassData Body:getMassData ================ **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This method is not supported in earlier versions. Returns the mass, its center, and the rotational inertia. Function -------- ### Synopsis ``` x, y, mass, inertia = Body:getMassData( ) ``` ### Arguments None. ### Returns `[number](number "number") x` The x position of the center of mass. `[number](number "number") y` The y position of the center of mass. `[number](number "number") mass` The mass of the body. `[number](number "number") inertia` The rotational inertia. See Also -------- * [Body](body "Body") * [Body:setMassData](body-setmassdata "Body:setMassData") love love.joystickpressed love.joystickpressed ==================== Called when a joystick button is pressed. Function -------- **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This variant is not supported in earlier versions. ### Synopsis ``` love.joystickpressed( joystick, button ) ``` ### Arguments `[Joystick](joystick "Joystick") joystick` The joystick object. `[number](number "number") button` The button number. ### Returns Nothing. Examples -------- ### Use joystickpressed to map stimulate the jumping of a player ``` function love.joystickpressed(joystick,button) player:jumping() end   --inside playerClass function player:jumping() if joyStick:isGamepadDown('a') then if self.jump then self.speedY = self.jumpSpeed self.jump = false end end end ``` Function -------- **Removed in LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This variant is not supported in that and later versions. ### Synopsis ``` love.joystickpressed( joystick, button ) ``` ### Arguments `[number](number "number") joystick` The joystick number. `[number](number "number") button` The button number. ### Returns Nothing. See Also -------- * [love](love "love") * [love.joystickreleased](love.joystickreleased "love.joystickreleased") love love.touchreleased love.touchreleased ================== **Available since LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** This function is not supported in earlier versions. Callback function triggered when the touch screen stops being touched. Function -------- ### Synopsis ``` love.touchreleased( id, x, y, dx, dy, pressure ) ``` ### Arguments `[light userdata](light_userdata "light userdata") id` The identifier for the touch press. `[number](number "number") x` The x-axis position of the touch inside the window, in pixels. `[number](number "number") y` The y-axis position of the touch inside the window, in pixels. `[number](number "number") dx` The x-axis movement of the touch inside the window, in pixels. `[number](number "number") dy` The y-axis movement of the touch inside the window, in pixels. `[number](number "number") pressure` The amount of pressure being applied. Most touch screens aren't pressure sensitive, in which case the pressure will be 1. ### Returns Nothing. Notes ----- The identifier is only guaranteed to be unique for the specific touch press until **love.touchreleased** is called with that identifier, at which point it may be reused for new touch presses. The unofficial Android and iOS ports of LÖVE 0.9.2 reported touch positions as normalized values in the range of [0, 1], whereas this API reports positions in pixels. See Also -------- * [love](love "love") * [love.touchpressed](love.touchpressed "love.touchpressed") * [love.touchmoved](love.touchmoved "love.touchmoved") * [love.touch](love.touch "love.touch") love Rasterizer:getAscent Rasterizer:getAscent ==================== **Available since LÖVE [0.7.0](https://love2d.org/wiki/0.7.0 "0.7.0")** This function is not supported in earlier versions. Gets ascent height. Function -------- ### Synopsis ``` height = Rasterizer:getAscent() ``` ### Arguments None. ### Returns `[number](number "number") height` Ascent height. See Also -------- * [Rasterizer](rasterizer "Rasterizer") love Font:hasGlyphs Font:hasGlyphs ============== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Gets whether the Font can render a character or string. Function -------- ### Synopsis ``` hasglyphs = Font:hasGlyphs( text ) ``` ### Arguments `[string](string "string") text` A UTF-8 encoded unicode string. ### Returns `[boolean](boolean "boolean") hasglyph` Whether the font can render all the UTF-8 characters in the string. Function -------- ### Synopsis ``` hasglyphs = Font:hasGlyphs( character1, character2, ... ) ``` ### Arguments `[string](string "string") character1` A unicode character. `[string](string "string") character2` Another unicode character. ### Returns `[boolean](boolean "boolean") hasglyph` Whether the font can render all the glyphs represented by the characters. Function -------- ### Synopsis ``` hasglyphs = Font:hasGlyphs( codepoint1, codepoint2, ... ) ``` ### Arguments `[number](number "number") codepoint1` A unicode codepoint number. `[number](number "number") codepoint2` Another unicode codepoint number. ### Returns `[boolean](boolean "boolean") hasglyph` Whether the font can render all the glyphs represented by the codepoint numbers. See Also -------- * [Font](font "Font") love love.window.showMessageBox love.window.showMessageBox ========================== **Available since LÖVE [0.9.2](https://love2d.org/wiki/0.9.2 "0.9.2")** This function is not supported in earlier versions. Displays a message box dialog above the love window. The message box contains a title, optional text, and buttons. This function will pause all execution of the main thread until the user has clicked a button to exit the message box. Calling the function from a different thread may cause love to crash. Function -------- Displays a simple message box with a single 'OK' button. ### Synopsis ``` success = love.window.showMessageBox( title, message, type, attachtowindow ) ``` ### Arguments `[string](string "string") title` The title of the message box. `[string](string "string") message` The text inside the message box. `[MessageBoxType](messageboxtype "MessageBoxType") type ("info")` The type of the message box. `[boolean](boolean "boolean") attachtowindow (true)` Whether the message box should be attached to the love window or free-floating. ### Returns `[boolean](boolean "boolean") success` Whether the message box was successfully displayed. Function -------- Displays a message box with a customized list of buttons. ### Synopsis ``` pressedbutton = love.window.showMessageBox( title, message, buttonlist, type, attachtowindow ) ``` ### Arguments `[string](string "string") title` The title of the message box. `[string](string "string") message` The text inside the message box. `[table](table "table") buttonlist` A table containing a list of button names to show. The table can also contain the fields `enterbutton` and `escapebutton`, which should be the index of the default button to use when the user presses 'enter' or 'escape', respectively. `[MessageBoxType](messageboxtype "MessageBoxType") type ("info")` The type of the message box. `[boolean](boolean "boolean") attachtowindow (true)` Whether the message box should be attached to the love window or free-floating. ### Returns `[number](number "number") pressedbutton` The index of the button pressed by the user. May be 0 if the message box dialog was closed without pressing a button. Examples -------- ### Display a simple message box if the user's system doesn't support shaders ``` local errortitle = "Shader support is required for the game to run" local errormessage = "This system is below the minimum system requirements for the game.\ If your graphics drivers aren't up-to-date, try updating them and running the game again."   if not love.graphics.isSupported("shader") then love.window.showMessageBox(errortitle, errormessage, "error") end ``` ### Display a message box with customized buttons ``` local title = "This is a title" local message = "This is some text" local buttons = {"OK", "No!", "Help", escapebutton = 2}   local pressedbutton = love.window.showMessageBox(title, message, buttons) if pressedbutton == 1 then -- "OK" was pressed elseif pressedbutton == 2 then -- etc. end ``` See Also -------- * [love.window](love.window "love.window") love love.graphics.newQuad love.graphics.newQuad ===================== Creates a new [Quad](quad "Quad"). The purpose of a Quad is to use a fraction of an image to draw objects, as opposed to drawing entire image. It is most useful for sprite sheets and atlases: in a sprite atlas, multiple sprites reside in same image, quad is used to draw a specific sprite from that image; in animated sprites with all frames residing in the same image, quad is used to draw specific frame from the animation. This function can be slow if it is called repeatedly, such as from [love.update](love.update "love.update") or [love.draw](love.draw "love.draw"). If you need to use a specific resource often, create it once and store it somewhere it can be reused! Function -------- ### Synopsis ``` quad = love.graphics.newQuad( x, y, width, height, sw, sh ) ``` ### Arguments `[number](number "number") x` The top-left position in the [Image](image "Image") along the x-axis. `[number](number "number") y` The top-left position in the [Image](image "Image") along the y-axis. `[number](number "number") width` The width of the Quad in the [Image](image "Image"). (Must be greater than 0.) `[number](number "number") height` The height of the Quad in the [Image](image "Image"). (Must be greater than 0.) `[number](number "number") sw` The reference width, the width of the [Image](image "Image"). (Must be greater than 0.) `[number](number "number") sh` The reference height, the height of the [Image](image "Image"). (Must be greater than 0.) ### Returns `[Quad](quad "Quad") quad` The new Quad. Examples -------- ### Use a Quad to display part of an Image: ``` img = love.graphics.newImage("mushroom-64x64.png")   -- Let's say we want to display only the top-left -- 32x32 quadrant of the Image: top_left = love.graphics.newQuad(0, 0, 32, 32, img:getDimensions())   -- And here is bottom left: bottom_left = love.graphics.newQuad(0, 32, 32, 32, img:getDimensions())   function love.draw() love.graphics.draw(img, top_left, 50, 50) love.graphics.draw(img, bottom_left, 50, 200) -- v0.8: -- love.graphics.drawq(img, top_left, 50, 50) -- love.graphics.drawq(img, bottom_left, 50, 200) end ``` See Also -------- * [love.graphics](love.graphics "love.graphics") * [Quad](quad "Quad")
programming_docs
love VideoStream:rewind VideoStream:rewind ================== **Available since LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** This function is not supported in earlier versions. Rewinds video stream. Synonym to `VideoStream:seek(0)` Function -------- ### Synopsis ``` VideoStream:rewind( ) ``` ### Arguments None. ### Returns None. See Also -------- * [VideoStream](videostream "VideoStream") * [VideoStream:seek](videostream-seek "VideoStream:seek") * [VideoStream:tell](videostream-tell "VideoStream:tell") love BezierCurve:evaluate BezierCurve:evaluate ==================== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Evaluate Bézier curve at parameter t. The parameter must be between 0 and 1 (inclusive). This function can be used to move objects along paths or tween parameters. However it should not be used to render the curve, see [BezierCurve:render](beziercurve-render "BezierCurve:render") for that purpose. Function -------- ### Synopsis ``` x,y = BezierCurve:evaluate(t) ``` ### Arguments `[number](number "number") t` Where to evaluate the curve. ### Returns `[number](number "number") x` x coordinate of the curve at parameter t. `[number](number "number") y` y coordinate of the curve at parameter t. See Also -------- * [BezierCurve](beziercurve "BezierCurve") * [BezierCurve:render](beziercurve-render "BezierCurve:render") * [love.math](love.math "love.math") * [Bezier Curves, how to trace a line? - LÖVE forum](https://love2d.org/forums/viewtopic.php?f=4&t=83825) love DistanceJoint:setFrequency DistanceJoint:setFrequency ========================== Sets the response speed. Function -------- ### Synopsis ``` DistanceJoint:setFrequency( Hz ) ``` ### Arguments `[number](number "number") Hz` The response speed. ### Returns Nothing. See Also -------- * [DistanceJoint](distancejoint "DistanceJoint") love Canvas:getFormat Canvas:getFormat ================ **Available since LÖVE [0.9.1](https://love2d.org/wiki/0.9.1 "0.9.1")** This function is not supported in earlier versions. **Removed in LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** It has been replaced by [Texture:getFormat](texture-getformat "Texture:getFormat"). Gets the texture format of the Canvas. Function -------- ### Synopsis ``` format = Canvas:getFormat( ) ``` ### Arguments None. ### Returns `[CanvasFormat](canvasformat "CanvasFormat") format` The format of the Canvas. See Also -------- * [Canvas](canvas "Canvas") * [love.graphics.newCanvas](love.graphics.newcanvas "love.graphics.newCanvas") love GearJoint GearJoint ========= Keeps bodies together in such a way that they act like gears. Constructors ------------ | | | | | | --- | --- | --- | --- | | [love.physics.newGearJoint](love.physics.newgearjoint "love.physics.newGearJoint") | Create a **GearJoint** connecting two Joints. | | | Functions --------- | | | | | | --- | --- | --- | --- | | [GearJoint:getJoints](gearjoint-getjoints "GearJoint:getJoints") | Get the Joints connected by this GearJoint. | 0.9.2 | | | [GearJoint:getRatio](gearjoint-getratio "GearJoint:getRatio") | Get the ratio of a gear joint. | | | | [GearJoint:setRatio](gearjoint-setratio "GearJoint:setRatio") | Set the ratio of a gear joint. | | | | [Joint:destroy](joint-destroy "Joint:destroy") | Explicitly destroys the Joint. | | | | [Joint:getAnchors](joint-getanchors "Joint:getAnchors") | Get the anchor points of the joint. | | | | [Joint:getBodies](joint-getbodies "Joint:getBodies") | Gets the [bodies](body "Body") that the Joint is attached to. | 0.9.2 | | | [Joint:getCollideConnected](joint-getcollideconnected "Joint:getCollideConnected") | Gets whether the connected Bodies collide. | | | | [Joint:getReactionForce](joint-getreactionforce "Joint:getReactionForce") | Returns the reaction force on the second body. | | | | [Joint:getReactionTorque](joint-getreactiontorque "Joint:getReactionTorque") | Returns the reaction torque on the second body. | | | | [Joint:getType](joint-gettype "Joint:getType") | Gets a string representing the type. | | | | [Joint:getUserData](joint-getuserdata "Joint:getUserData") | Returns the Lua value associated with this Joint. | 0.9.2 | | | [Joint:isDestroyed](joint-isdestroyed "Joint:isDestroyed") | Gets whether the Joint is destroyed. | 0.9.2 | | | [Joint:setCollideConnected](joint-setcollideconnected "Joint:setCollideConnected") | Sets whether the connected Bodies should collide with each other. | | 0.8.0 | | [Joint:setUserData](joint-setuserdata "Joint:setUserData") | Associates a Lua value with the Joint. | 0.9.2 | | Supertypes ---------- * [Joint](joint "Joint") * [Object](object "Object") See Also -------- * [love.physics](love.physics "love.physics") love Joystick:isGamepad Joystick:isGamepad ================== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Gets whether the Joystick is recognized as a gamepad. If this is the case, the Joystick's buttons and axes can be used in a standardized manner across different operating systems and joystick models via [Joystick:getGamepadAxis](joystick-getgamepadaxis "Joystick:getGamepadAxis"), [Joystick:isGamepadDown](joystick-isgamepaddown "Joystick:isGamepadDown"), [love.gamepadpressed](love.gamepadpressed "love.gamepadpressed"), and related functions. LÖVE automatically recognizes most popular controllers with a similar layout to the Xbox 360 controller as gamepads, but you can add more with [love.joystick.setGamepadMapping](love.joystick.setgamepadmapping "love.joystick.setGamepadMapping"). Function -------- ### Synopsis ``` isgamepad = Joystick:isGamepad( ) ``` ### Arguments None. ### Returns `[boolean](boolean "boolean") isgamepad` True if the Joystick is recognized as a gamepad, false otherwise. Notes ----- If the Joystick is recognized as a gamepad, the physical locations for the virtual gamepad axes and buttons correspond as closely as possible to the layout of a standard Xbox 360 controller. See Also -------- * [Joystick](joystick "Joystick") * [Joystick:getGamepadAxis](joystick-getgamepadaxis "Joystick:getGamepadAxis") * [Joystick:isGamepadDown](joystick-isgamepaddown "Joystick:isGamepadDown") * [Joystick:getGamepadMapping](joystick-getgamepadmapping "Joystick:getGamepadMapping") * [love.gamepadaxis](love.gamepadaxis "love.gamepadaxis") * [love.gamepadpressed](love.gamepadpressed "love.gamepadpressed") * [love.gamepadreleased](love.gamepadreleased "love.gamepadreleased") love Shader:sendColor Shader:sendColor ================ **Available since LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** This function is not supported in earlier versions. Sends one or more colors to a special (*extern* / *uniform*) vec3 or vec4 variable inside the shader. The color components must be in the range of [0, 1]. The colors are gamma-corrected if global [gamma-correction](love.graphics.isgammacorrect "love.graphics.isGammaCorrect") is enabled. Extern variables must be marked using the *extern* keyword, e.g. ``` extern vec4 Color; ``` The corresponding sendColor call would be ``` shader:sendColor("Color", {r, g, b, a}) ``` Extern variables can be accessed in both the Vertex and Pixel stages of a shader, as long as the variable is declared in each. In versions prior to [11.0](https://love2d.org/wiki/11.0 "11.0"), color component values were within the range of 0 to 255 instead of 0 to 1. Function -------- ### Synopsis ``` Shader:sendColor( name, color, ... ) ``` ### Arguments `[string](string "string") name` The name of the color extern variable to send to in the shader. `[table](table "table") color` A table with red, green, blue, and optional alpha color components in the range of [0, 1] to send to the extern as a vector. `[table](table "table") ...` Additional colors to send in case the extern is an array. All colors need to be of the same size (e.g. only vec3's). ### Returns Nothing. See Also -------- * [Shader](shader "Shader") * [Shader:send](shader-send "Shader:send") love ParticleSystem:update ParticleSystem:update ===================== Updates the particle system; moving, creating and killing particles. Function -------- ### Synopsis ``` ParticleSystem:update( dt ) ``` ### Arguments `[number](number "number") dt` The time (seconds) since last frame. ### Returns Nothing. See Also -------- * [ParticleSystem](particlesystem "ParticleSystem") love World:getBodyList World:getBodyList ================= | | | --- | | ***Deprecated in LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")*** | | It has been renamed to [World:getBodies](world-getbodies "World:getBodies"). | **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This method is not supported in earlier versions. Returns a table with all bodies. Function -------- ### Synopsis ``` bodies = World:getBodyList( ) ``` ### Arguments None. ### Returns `[table](table "table") bodies` A [sequence](sequence "sequence") with all bodies. See Also -------- * [World](world "World") love love.filesystem.getWorkingDirectory love.filesystem.getWorkingDirectory =================================== **Available since LÖVE [0.5.0](https://love2d.org/wiki/0.5.0 "0.5.0")** This function is not supported in earlier versions. Gets the current working directory. Function -------- ### Synopsis ``` cwd = love.filesystem.getWorkingDirectory( ) ``` ### Arguments None. ### Returns `[string](string "string") cwd` The current working directory. See Also -------- * [love.filesystem](love.filesystem "love.filesystem") love love.window.getIcon love.window.getIcon =================== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Gets the window icon. Function -------- ### Synopsis ``` imagedata = love.window.getIcon( ) ``` ### Arguments None. ### Returns `[ImageData](imagedata "ImageData") imagedata` The window icon imagedata, or nil if no icon has been set with [love.window.setIcon](love.window.seticon "love.window.setIcon"). See Also -------- * [love.window](love.window "love.window") * [love.window.setIcon](love.window.seticon "love.window.setIcon") love Body:getLocalPoint Body:getLocalPoint ================== Transform a point from world coordinates to local coordinates. Function -------- ### Synopsis ``` localX, localY = Body:getLocalPoint( worldX, worldY ) ``` ### Arguments `[number](number "number") worldX` The x position in world coordinates. `[number](number "number") worldY` The y position in world coordinates. ### Returns `[number](number "number") localX` The x position in local coordinates. `[number](number "number") localY` The y position in local coordinates. See Also -------- * [Body](body "Body") love love.math.gammaToLinear love.math.gammaToLinear ======================= **Available since LÖVE [0.9.1](https://love2d.org/wiki/0.9.1 "0.9.1")** This function is not supported in earlier versions. Converts a color from gamma-space (sRGB) to linear-space (RGB). This is useful when doing [gamma-correct rendering](love.graphics.isgammacorrect "love.graphics.isGammaCorrect") and you need to do math in linear RGB in the few cases where LÖVE doesn't handle conversions automatically. Read more about gamma-correct rendering [here](https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch24.html), [here](http://filmicgames.com/archives/299), and [here](http://renderwonk.com/blog/index.php/archive/adventures-with-gamma-correct-rendering/). In versions prior to [11.0](https://love2d.org/wiki/11.0 "11.0"), color component values were within the range of 0 to 255 instead of 0 to 1. Gamma-correct rendering is an advanced topic and it's easy to get color-spaces mixed up. If you're not sure whether you need this, you might want to avoid it. Function -------- ### Synopsis ``` lr, lg, lb = love.math.gammaToLinear( r, g, b ) ``` ### Arguments `[number](number "number") r` The red channel of the sRGB color to convert. `[number](number "number") g` The green channel of the sRGB color to convert. `[number](number "number") b` The blue channel of the sRGB color to convert. ### Returns `[number](number "number") lr` The red channel of the converted color in linear RGB space. `[number](number "number") lg` The green channel of the converted color in linear RGB space. `[number](number "number") lb` The blue channel of the converted color in linear RGB space. ### Notes An alpha value can be passed into the function as a fourth argument, but it will be returned unchanged because alpha is always linear. Function -------- ### Synopsis ``` lr, lg, lb = love.math.gammaToLinear( color ) ``` ### Arguments `[table](table "table") color` An array with the red, green, and blue channels of the sRGB color to convert. ### Returns `[number](number "number") lr` The red channel of the converted color in linear RGB space. `[number](number "number") lg` The green channel of the converted color in linear RGB space. `[number](number "number") lb` The blue channel of the converted color in linear RGB space. Function -------- ### Synopsis ``` lc = love.math.gammaToLinear( c ) ``` ### Arguments `[number](number "number") c` The value of a color channel in sRGB space to convert. ### Returns `[number](number "number") lc` The value of the color channel in linear RGB space. Examples -------- ### Pre-multiply an image's alpha with its RGB values in linear RGB space ``` local function PremultiplyLinearPixel(x, y, r, g, b, a) r = r * a g = g * a b = b * a return r, g, b, a end   local function PremultiplyGammaPixel(x, y, r, g, b, a) r, g, b = love.math.gammaToLinear(r, g, b) r = r * a g = g * a b = b * a r, g, b = love.math.linearToGamma(r, g, b) return r, g, b, a end   -- Loads an image and pre-multiplies its RGB values with its alpha, for use with the ('alpha', 'premultiplied') blend mode. -- The multiplication correctly accounts for the color-space of the image. function NewPremultipliedImage(filepath, flags) local imagedata = love.image.newImageData(filepath)   local mapfunction = (flags and flags.linear) and PremultiplyLinearPixel or PremultiplyGammaPixel imagedata:mapPixel(mapfunction)   return love.graphics.newImage(imagedata, flags) end   image = NewPremultipliedImage("pig.png") ``` See Also -------- * [love.math](love.math "love.math") * [love.math.linearToGamma](love.math.lineartogamma "love.math.linearToGamma") love enet.host:get socket address enet.host:get socket address ============================ Returns a string that describes the socket address of the given [host](enet.host "enet.host"). The string is formatted as “a.b.c.d:port”, where “a.b.c.d” is the IP address of the used socket. Function -------- ### Synopsis ``` host:get_socket_address() ``` ### Arguments None. ### Returns `[string](string "string") address` A string that describes the socket address. See Also -------- * [lua-enet](lua-enet "lua-enet") * [enet.host](enet.host "enet.host") love World:getAllowSleeping World:getAllowSleeping ====================== **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This method is not supported in earlier versions. **Removed in LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** It has been renamed to [World:isSleepingAllowed](world-issleepingallowed "World:isSleepingAllowed"). Returns the sleep behaviour of the world. Function -------- ### Synopsis ``` allowSleep = World:getAllowSleeping( ) ``` ### Arguments None. ### Returns `[boolean](boolean "boolean") allowSleep` True if the bodies are allowed to sleep or false if not. See Also -------- * [World](world "World") * [World:setAllowSleeping](world-setallowsleeping "World:setAllowSleeping") love Texture:getMipmapCount Texture:getMipmapCount ====================== **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This function is not supported in earlier versions. Gets the number of mipmaps contained in the Texture. If the texture was not created with mipmaps, it will return 1. Function -------- ### Synopsis ``` mipmaps = Texture:getMipmapCount( ) ``` ### Arguments None. ### Returns `[number](number "number") mipmaps` The number of mipmaps in the Texture. See Also -------- * [Texture](texture "Texture") * [Texture:setMipmapFilter](texture-setmipmapfilter "Texture:setMipmapFilter") * [love.graphics.newImage](love.graphics.newimage "love.graphics.newImage") * [love.graphics.newCanvas](love.graphics.newcanvas "love.graphics.newCanvas") love love.mousemoved love.mousemoved =============== **Available since LÖVE [0.9.2](https://love2d.org/wiki/0.9.2 "0.9.2")** This function is not supported in earlier versions. Callback function triggered when the mouse is moved. Function -------- ### Synopsis ``` love.mousemoved( x, y, dx, dy, istouch ) ``` ### Arguments `[number](number "number") x` The mouse position on the x-axis. `[number](number "number") y` The mouse position on the y-axis. `[number](number "number") dx` The amount moved along the x-axis since the last time love.mousemoved was called. `[number](number "number") dy` The amount moved along the y-axis since the last time love.mousemoved was called. `[boolean](boolean "boolean") istouch` Available since 0.10.0 True if the mouse button press originated from a touchscreen touch-press. ### Returns Nothing. Notes ----- If [Relative Mode](love.mouse.setrelativemode "love.mouse.setRelativeMode") is enabled for the mouse, the **dx** and **dy** arguments of this callback will update but **x** and **y** are not guaranteed to. See Also -------- * [love](love "love") * [love.mousepressed](love.mousepressed "love.mousepressed") * [love.mousereleased](love.mousereleased "love.mousereleased") * [love.mouse.setPosition](love.mouse.setposition "love.mouse.setPosition") * [love.mouse.getPosition](love.mouse.getposition "love.mouse.getPosition") * [love.mouse.setRelativeMode](love.mouse.setrelativemode "love.mouse.setRelativeMode") * [love.mouse.getRelativeMode](love.mouse.getrelativemode "love.mouse.getRelativeMode") love BezierCurve:rotate BezierCurve:rotate ================== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Rotate the Bézier curve by an angle. Function -------- ### Synopsis ``` BezierCurve:rotate(angle, ox, oy) ``` ### Arguments `[number](number "number") angle` Rotation angle in radians. `[number](number "number") ox (0)` X coordinate of the rotation center. `[number](number "number") oy (0)` Y coordinate of the rotation center. ### Returns Nothing. See Also -------- * [BezierCurve:translate](beziercurve-translate "BezierCurve:translate") * [BezierCurve:scale](beziercurve-scale "BezierCurve:scale") * [BezierCurve](beziercurve "BezierCurve") * [love.math](love.math "love.math") love love.audio.getMaxSourceEffects love.audio.getMaxSourceEffects ============================== **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This function is not supported in earlier versions. Gets the maximum number of active Effects in a single [Source](source "Source") object, that the system can support. Function -------- ### Synopsis ``` maximum = love.audio.getMaxSourceEffects( ) ``` ### Arguments None. ### Returns `[number](number "number") maximum` The maximum number of active Effects per Source. Notes ----- This function return 0 for system that doesn't support audio effects. See Also -------- * [love.audio](love.audio "love.audio") * [love.audio.isEffectsSupported](love.audio.iseffectssupported "love.audio.isEffectsSupported") * [love.audio.setEffect](love.audio.seteffect "love.audio.setEffect")
programming_docs
love SpriteBatch:setDrawRange SpriteBatch:setDrawRange ======================== **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This function is not supported in earlier versions. Restricts the drawn sprites in the SpriteBatch to a subset of the total. Function -------- ### Synopsis ``` SpriteBatch:setDrawRange( start, count ) ``` ### Arguments `[number](number "number") start` The index of the first sprite to draw. Index 1 corresponds to the first sprite added with [SpriteBatch:add](spritebatch-add "SpriteBatch:add"). `[number](number "number") count` The number of sprites to draw. ### Returns Nothing. Function -------- Allows all sprites in the SpriteBatch to be drawn. ### Synopsis ``` SpriteBatch:setDrawRange( ) ``` ### Arguments None. ### Returns Nothing. See Also -------- * [SpriteBatch](spritebatch "SpriteBatch") * [SpriteBatch:getDrawRange](https://love2d.org/w/index.php?title=SpriteBatch:getDrawRange&action=edit&redlink=1 "SpriteBatch:getDrawRange (page does not exist)") * [love.graphics.draw](love.graphics.draw "love.graphics.draw") love DistanceJoint DistanceJoint ============= Keeps two bodies at the same distance. Constructors ------------ | | | | | | --- | --- | --- | --- | | [love.physics.newDistanceJoint](love.physics.newdistancejoint "love.physics.newDistanceJoint") | Creates a **DistanceJoint** between two bodies. | | | Functions --------- | | | | | | --- | --- | --- | --- | | [DistanceJoint:getDamping](distancejoint-getdamping "DistanceJoint:getDamping") | Gets the damping ratio. | | 0.8.0 | | [DistanceJoint:getDampingRatio](distancejoint-getdampingratio "DistanceJoint:getDampingRatio") | Gets the damping ratio. | 0.8.0 | | | [DistanceJoint:getFrequency](distancejoint-getfrequency "DistanceJoint:getFrequency") | Gets the response speed. | | | | [DistanceJoint:getLength](distancejoint-getlength "DistanceJoint:getLength") | Gets the equilibrium distance between the two Bodies. | | | | [DistanceJoint:setDamping](distancejoint-setdamping "DistanceJoint:setDamping") | Sets the damping ratio. | | 0.8.0 | | [DistanceJoint:setDampingRatio](distancejoint-setdampingratio "DistanceJoint:setDampingRatio") | Sets the damping ratio. | 0.8.0 | | | [DistanceJoint:setFrequency](distancejoint-setfrequency "DistanceJoint:setFrequency") | Sets the response speed. | | | | [DistanceJoint:setLength](distancejoint-setlength "DistanceJoint:setLength") | Sets the equilibrium distance between the two Bodies. | | | | [Joint:destroy](joint-destroy "Joint:destroy") | Explicitly destroys the Joint. | | | | [Joint:getAnchors](joint-getanchors "Joint:getAnchors") | Get the anchor points of the joint. | | | | [Joint:getBodies](joint-getbodies "Joint:getBodies") | Gets the [bodies](body "Body") that the Joint is attached to. | 0.9.2 | | | [Joint:getCollideConnected](joint-getcollideconnected "Joint:getCollideConnected") | Gets whether the connected Bodies collide. | | | | [Joint:getReactionForce](joint-getreactionforce "Joint:getReactionForce") | Returns the reaction force on the second body. | | | | [Joint:getReactionTorque](joint-getreactiontorque "Joint:getReactionTorque") | Returns the reaction torque on the second body. | | | | [Joint:getType](joint-gettype "Joint:getType") | Gets a string representing the type. | | | | [Joint:getUserData](joint-getuserdata "Joint:getUserData") | Returns the Lua value associated with this Joint. | 0.9.2 | | | [Joint:isDestroyed](joint-isdestroyed "Joint:isDestroyed") | Gets whether the Joint is destroyed. | 0.9.2 | | | [Joint:setCollideConnected](joint-setcollideconnected "Joint:setCollideConnected") | Sets whether the connected Bodies should collide with each other. | | 0.8.0 | | [Joint:setUserData](joint-setuserdata "Joint:setUserData") | Associates a Lua value with the Joint. | 0.9.2 | | Supertypes ---------- * [Joint](joint "Joint") * [Object](object "Object") See Also -------- * [love.physics](love.physics "love.physics") love World:setMeter World:setMeter ============== **Removed in LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This method is not supported in that and later versions. Set the scale of the world. The world scale is the number of pixels per meter. Try to keep your shape sizes less than 10 times this scale. The default scale for new worlds is 30 pixels per meter. This is important because the physics in Box2D is tuned to work well for objects of size 0.1m up to 10m. All physics coordinates are divided by this number for the physics calculations. Function -------- ### Synopsis ``` World:setMeter( scale ) ``` ### Arguments `[number](number "number") scale` The size of 1 meter in pixels. ### Returns Nothing. See Also -------- * [World](world "World") love love.graphics.isCreated love.graphics.isCreated ======================= **Removed in LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** Moved to the [love.window](love.window "love.window") module as [love.window.isCreated](love.window.iscreated "love.window.isCreated"). Checks if the window has been created. Function -------- ### Synopsis ``` created = love.graphics.isCreated( ) ``` ### Arguments None. ### Returns `[boolean](boolean "boolean") created` True if the window has been created, false otherwise. See Also -------- * [love.graphics](love.graphics "love.graphics") love Thread:getName Thread:getName ============== **Available since LÖVE [0.7.0](https://love2d.org/wiki/0.7.0 "0.7.0") and removed in LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier or later versions. Get the name of a thread. Function -------- ### Synopsis ``` name = Thread:getName( ) ``` ### Arguments None. ### Returns `[string](string "string") name` The name of the thread. See Also -------- * [Thread](thread "Thread") love Decoder:getChannels Decoder:getChannels =================== | | | --- | | ***Deprecated in LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")*** | | This function has been renamed to [Decoder:getChannelCount](decoder-getchannelcount "Decoder:getChannelCount"). | Returns the number of channels in the stream. Function -------- ### Synopsis ``` channels = Decoder:getChannels( ) ``` ### Arguments None. ### Returns `[number](number "number") channels` 1 for mono, 2 for stereo. See Also -------- * [Decoder](decoder "Decoder") love love.graphics.getDefaultImageFilter love.graphics.getDefaultImageFilter =================================== **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0") and removed in LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** It has been renamed to [love.graphics.getDefaultFilter](love.graphics.getdefaultfilter "love.graphics.getDefaultFilter"). Returns the default scaling filters. Function -------- ### Synopsis ``` min, mag = love.graphics.getDefaultImageFilter( ) ``` ### Arguments None. ### Returns `[FilterMode](filtermode "FilterMode") min` Filter mode used when scaling the image down. `[FilterMode](filtermode "FilterMode") mag` Filter mode used when scaling the image up. See Also -------- * [love.graphics](love.graphics "love.graphics") * [love.graphics.setDefaultImageFilter](love.graphics.setdefaultimagefilter "love.graphics.setDefaultImageFilter") love DistanceJoint:getDamping DistanceJoint:getDamping ======================== **Removed in LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** It has been replaced with [DistanceJoint:getDampingRatio](distancejoint-getdampingratio "DistanceJoint:getDampingRatio"). Gets the damping ratio. Function -------- ### Synopsis ``` ratio = DistanceJoint:getDamping( ) ``` ### Arguments None. ### Returns `[number](number "number") ratio` The damping ratio. See Also -------- * [DistanceJoint](distancejoint "DistanceJoint") love Body:setAngularDamping Body:setAngularDamping ====================== Sets the angular damping of a Body See [Body:getAngularDamping](body-getangulardamping "Body:getAngularDamping") for a definition of angular damping. Angular damping can take any value from 0 to infinity. It is recommended to stay between 0 and 0.1, though. Other values will look unrealistic. Function -------- ### Synopsis ``` Body:setAngularDamping( damping ) ``` ### Arguments `[number](number "number") damping` The new angular damping. ### Returns Nothing. See Also -------- * [Body](body "Body") love ParticleSystem:setSpread ParticleSystem:setSpread ======================== Sets the amount of spread for the system. Function -------- ### Synopsis ``` ParticleSystem:setSpread( spread ) ``` ### Arguments `[number](number "number") spread` The amount of spread (radians). ### Returns Nothing. See Also -------- * [ParticleSystem](particlesystem "ParticleSystem") love FrictionJoint:setMaxForce FrictionJoint:setMaxForce ========================= **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This function is not supported in earlier versions. Sets the maximum friction force in Newtons. Function -------- ### Synopsis ``` FrictionJoint:setMaxForce( force ) ``` ### Arguments `[number](number "number") maxForce` Max force in Newtons. ### Returns Nothing. See Also -------- * [FrictionJoint](frictionjoint "FrictionJoint") * [FrictionJoint:getMaxForce](frictionjoint-getmaxforce "FrictionJoint:getMaxForce") love ParticleSystem:stop ParticleSystem:stop =================== Stops the particle emitter, resetting the lifetime counter. Function -------- ### Synopsis ``` ParticleSystem:stop( ) ``` ### Arguments None. ### Returns Nothing. See Also -------- * [ParticleSystem](particlesystem "ParticleSystem") love enet.peer:ping interval enet.peer:ping interval ======================= Specifies the interval in milliseconds that pings are sent to the other end of the connection (defaults to 500). Function -------- ### Synopsis ``` peer:ping_interval(interval) ``` ### Arguments `[number](number "number") interval` Time in milliseconds to wait before automatically calling [peer:ping()](enet.peer-ping "enet.peer:ping"). ### Returns Nothing. See Also -------- * [lua-enet](lua-enet "lua-enet") * [enet.peer](enet.peer "enet.peer") * [enet.peer:ping](enet.peer-ping "enet.peer:ping") love love.audio.play love.audio.play =============== Plays the specified Source. Function -------- ### Synopsis ``` love.audio.play( source ) ``` ### Arguments `[Source](source "Source") source` The Source to play. ### Returns Nothing. Function -------- **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This variant is not supported in earlier versions. Starts playing multiple Sources simultaneously. ### Synopsis ``` love.audio.play( sources ) ``` ### Arguments `[table](table "table") sources` Table containing a list of Sources to play. ### Returns Nothing. Function -------- **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This variant is not supported in earlier versions. Starts playing multiple Sources simultaneously. ### Synopsis ``` love.audio.play( source1, source2, ... ) ``` ### Arguments `[Source](source "Source") source1` The first Source to play. `[Source](source "Source") source2` The second Source to play. `[Source](source "Source") ...` Additional Sources to play. ### Returns Nothing. See Also -------- * [love.audio](love.audio "love.audio") * [Source:play](source-play "Source:play") love SpriteBatch SpriteBatch =========== Using a single image, draw any number of identical copies of the image using a single call to [love.graphics.draw](love.graphics.draw "love.graphics.draw")(). This can be used, for example, to draw repeating copies of a single background image with high performance. A SpriteBatch can be even more useful when the underlying image is a [texture atlas](https://en.wikipedia.org/wiki/Texture_atlas) (a single image file containing many independent images); by adding [Quads](quad "Quad") to the batch, different sub-images from within the atlas can be drawn. Constructors ------------ | | | | | | --- | --- | --- | --- | | [love.graphics.newSpriteBatch](love.graphics.newspritebatch "love.graphics.newSpriteBatch") | Creates a new **SpriteBatch**. | | | Functions --------- | | | | | | --- | --- | --- | --- | | [Object:release](object-release "Object:release") | Immediately destroys the object's Lua reference. | 11.0 | | | [Object:type](object-type "Object:type") | Gets the type of the object as a string. | | | | [Object:typeOf](object-typeof "Object:typeOf") | Checks whether an object is of a certain type. | | | | [SpriteBatch:add](spritebatch-add "SpriteBatch:add") | Adds a sprite to the batch. | | | | [SpriteBatch:addLayer](spritebatch-addlayer "SpriteBatch:addLayer") | Adds a sprite to a batch created with an [Array Texture](texturetype "TextureType"). | 11.0 | | | [SpriteBatch:addq](spritebatch-addq "SpriteBatch:addq") | Adds a Quad to the batch. | | 0.9.0 | | [SpriteBatch:attachAttribute](spritebatch-attachattribute "SpriteBatch:attachAttribute") | Attaches a per-vertex attribute from a [Mesh](mesh "Mesh") onto this SpriteBatch, for use when drawing. | 0.10.0 | | | [SpriteBatch:bind](spritebatch-bind "SpriteBatch:bind") | Binds the SpriteBatch to memory for more efficient updating. | 0.8.0 | 0.10.0 | | [SpriteBatch:clear](spritebatch-clear "SpriteBatch:clear") | Removes all sprites from the buffer. | | | | [SpriteBatch:flush](spritebatch-flush "SpriteBatch:flush") | Immediately sends all new and modified sprite data to the graphics card. | 0.9.2 | | | [SpriteBatch:getBufferSize](spritebatch-getbuffersize "SpriteBatch:getBufferSize") | Gets the maximum number of sprites the SpriteBatch can hold. | 0.9.0 | | | [SpriteBatch:getColor](spritebatch-getcolor "SpriteBatch:getColor") | Gets the color that will be used for the next add and set operations. | 0.9.0 | | | [SpriteBatch:getCount](spritebatch-getcount "SpriteBatch:getCount") | Gets the number of sprites currently in the SpriteBatch. | 0.9.0 | | | [SpriteBatch:getImage](spritebatch-getimage "SpriteBatch:getImage") | Returns the image used by the SpriteBatch. | 0.8.0 | 0.10.0 | | [SpriteBatch:getTexture](spritebatch-gettexture "SpriteBatch:getTexture") | Gets the texture ([Image](image "Image") or [Canvas](canvas "Canvas")) used by the SpriteBatch. | 0.9.1 | | | [SpriteBatch:set](spritebatch-set "SpriteBatch:set") | Changes a sprite in the batch. | 0.8.0 | | | [SpriteBatch:setBufferSize](spritebatch-setbuffersize "SpriteBatch:setBufferSize") | Sets the maximum number of sprites the SpriteBatch can hold. | 0.9.0 | 11.0 | | [SpriteBatch:setColor](spritebatch-setcolor "SpriteBatch:setColor") | Sets the color that will be used for the next add or set operations. | 0.8.0 | | | [SpriteBatch:setDrawRange](spritebatch-setdrawrange "SpriteBatch:setDrawRange") | Restricts the drawn sprites in the SpriteBatch to a subset of the total. | 11.0 | | | [SpriteBatch:setImage](spritebatch-setimage "SpriteBatch:setImage") | Replaces the image used for the sprites. | 0.7.2 | 0.10.0 | | [SpriteBatch:setLayer](spritebatch-setlayer "SpriteBatch:setLayer") | Changes a sprite previously added with [add](spritebatch-add "SpriteBatch:add") or [addLayer](spritebatch-addlayer "SpriteBatch:addLayer"), in a batch created with an [Array Texture](texturetype "TextureType"). | 11.0 | | | [SpriteBatch:setTexture](spritebatch-settexture "SpriteBatch:setTexture") | Sets the texture ([Image](image "Image") or [Canvas](canvas "Canvas")) used for the sprites in the batch. | 0.9.1 | | | [SpriteBatch:setq](spritebatch-setq "SpriteBatch:setq") | Changes a sprite with a quad in the batch. | 0.8.0 | 0.9.0 | | [SpriteBatch:unbind](spritebatch-unbind "SpriteBatch:unbind") | Unbinds the SpriteBatch. | 0.8.0 | 0.10.0 | Enums ----- | | | | | | --- | --- | --- | --- | | [SpriteBatchUsage](spritebatchusage "SpriteBatchUsage") | Usage hints for **SpriteBatches** and [Meshes](mesh "Mesh"). | 0.8.0 | | Supertypes ---------- * [Drawable](drawable "Drawable") * [Object](object "Object") See Also -------- * [love.graphics](love.graphics "love.graphics") love love.window.toggleFullscreen love.window.toggleFullscreen ============================ **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Enters or exits fullscreen. The display to use when entering fullscreen is chosen based on which display the window is currently in, if multiple monitors are connected. Function -------- ### Synopsis ``` success = love.window.setFullscreen( fullscreen ) ``` ### Arguments `[boolean](boolean "boolean") fullscreen` Whether to enter or exit fullscreen mode. ### Returns `[boolean](boolean "boolean") success` True if an attempt to enter fullscreen was successful, false otherwise. Function -------- ### Synopsis ``` success = love.window.setFullscreen( fullscreen, fstype ) ``` ### Arguments `[boolean](boolean "boolean") fullscreen` Whether to enter or exit fullscreen mode. `[FullscreenType](fullscreentype "FullscreenType") fstype` The type of fullscreen mode to use. ### Returns `[boolean](boolean "boolean") success` True if an attempt to enter fullscreen was successful, false otherwise. Notes ----- If fullscreen mode is entered and the window size doesn't match one of the monitor's display modes (in normal fullscreen mode) or the window size doesn't match the desktop size (in 'desktop' fullscreen mode), the window will be resized appropriately. The window will revert back to its original size again when fullscreen mode is exited using this function. Examples -------- Make the window fullscreen in desktop mode. ``` function love.load() love.window.setFullscreen(true, "desktop") end ``` See Also -------- * [love.window](love.window "love.window") * [love.window.getFullscreen](love.window.getfullscreen "love.window.getFullscreen") * [love.window.setMode](love.window.setmode "love.window.setMode") * [love.resize](love.resize "love.resize") love Shape:getRestitution Shape:getRestitution ==================== **Removed in LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This function is not supported in that and later versions. Gets the restitution of this shape. Function -------- ### Synopsis ``` restitution = Shape:getRestitution( ) ``` ### Arguments None. ### Returns `[number](number "number") restitution` The restitution of this Shape. See Also -------- * [Shape](shape "Shape") love ImageData:setPixel ImageData:setPixel ================== Sets the color of a pixel at a specific position in the image. Valid x and y values start at 0 and go up to image width and height minus 1. In versions prior to [11.0](https://love2d.org/wiki/11.0 "11.0"), color component values were within the range of 0 to 255 instead of 0 to 1. Function -------- ### Synopsis ``` ImageData:setPixel( x, y, r, g, b, a ) ``` ### Arguments `[number](number "number") x` The position of the pixel on the x-axis. `[number](number "number") y` The position of the pixel on the y-axis. `[number](number "number") r` The red component (0-1). `[number](number "number") g` The green component (0-1). `[number](number "number") b` The blue component (0-1). `[number](number "number") a` The alpha component (0-1). ### Returns Nothing. Examples -------- Create a 32x1 pixel transparent-to-white gradient [drawable image](image "Image"). ``` data = love.image.newImageData(32,1) for i=0, 31 do -- remember: start at 0 data:setPixel(i, 0, 1, 1, 1, i / 31) end img = love.graphics.newImage(data) ``` See Also -------- * [ImageData](imagedata "ImageData") * [ImageData:getPixel](imagedata-getpixel "ImageData:getPixel")
programming_docs
love Body:getLinearVelocityFromLocalPoint Body:getLinearVelocityFromLocalPoint ==================================== Get the linear velocity of a point on the body. The linear velocity for a point on the body is the velocity of the body center of mass plus the velocity at that point from the body spinning. The point on the body must given in local coordinates. Use [Body:getLinearVelocityFromWorldPoint](body-getlinearvelocityfromworldpoint "Body:getLinearVelocityFromWorldPoint") to specify this with world coordinates. Function -------- ### Synopsis ``` vx, vy = Body:getLinearVelocityFromLocalPoint( x, y ) ``` ### Arguments `[number](number "number") x` The x position to measure velocity. `[number](number "number") y` The y position to measure velocity. ### Returns `[number](number "number") vx` The x component of velocity at point (x,y). `[number](number "number") vy` The y component of velocity at point (x,y). See Also -------- * [Body](body "Body") love PrismaticJoint:setUpperLimit PrismaticJoint:setUpperLimit ============================ Sets the upper limit. Function -------- ### Synopsis ``` PrismaticJoint:setUpperLimit( upper ) ``` ### Arguments `[number](number "number") upper` The upper limit, usually in meters. ### Returns Nothing. See Also -------- * [PrismaticJoint](prismaticjoint "PrismaticJoint") love RecordingDevice:getBitDepth RecordingDevice:getBitDepth =========================== **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This function is not supported in earlier versions. Gets the number of bits per sample in the data currently being recorded. Function -------- ### Synopsis ``` bits = RecordingDevice:getBitDepth( ) ``` ### Arguments None. ### Returns `[number](number "number") bits` The number of bits per sample in the data that's currently being recorded. See Also -------- * [RecordingDevice](recordingdevice "RecordingDevice") * [RecordingDevice:start](recordingdevice-start "RecordingDevice:start") love BezierCurve:getControlPoint BezierCurve:getControlPoint =========================== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Get coordinates of the i-th control point. Indices start with 1. Function -------- ### Synopsis ``` x, y = BezierCurve:getControlPoint(i) ``` ### Arguments `[number](number "number") i` Index of the control point. ### Returns `[number](number "number") x` Position of the control point along the x axis. `[number](number "number") y` Position of the control point along the y axis. See Also -------- * [BezierCurve](beziercurve "BezierCurve") * [BezierCurve:getDegree](beziercurve-getdegree "BezierCurve:getDegree") * [BezierCurve:setControlPoint](beziercurve-setcontrolpoint "BezierCurve:setControlPoint") * [BezierCurve:insertControlPoint](beziercurve-insertcontrolpoint "BezierCurve:insertControlPoint") * [love.math](love.math "love.math") love ParticleSystem:setParticleLife ParticleSystem:setParticleLife ============================== **Removed in LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** It has been renamed to [ParticleSystem:setParticleLifetime](particlesystem-setparticlelifetime "ParticleSystem:setParticleLifetime"). Sets the life of the particles. Function -------- ### Synopsis ``` ParticleSystem:setParticleLife( min, max ) ``` ### Arguments `[number](number "number") min` The minimum life of the particles (seconds). `[number](number "number") max (min)` The maximum life of the particles (seconds). ### Returns Nothing. See Also -------- * [ParticleSystem](particlesystem "ParticleSystem") love Fixture:setFilterData Fixture:setFilterData ===================== **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This method is not supported in earlier versions. Sets the filter data of the fixture. Groups, categories, and mask can be used to define the collision behaviour of the fixture. If two fixtures are in the same group they either always collide if the group is positive, or never collide if it's negative. If the group is zero or they do not match, then the contact filter checks if the fixtures select a category of the other fixture with their masks. The fixtures do not collide if that's not the case. If they do have each other's categories selected, the return value of the custom contact filter will be used. They always collide if none was set. There can be up to 16 categories. Categories and masks are encoded as the bits of a 16-bit integer. When created, prior to calling this function, all fixtures have category set to 1, mask set to 65535 (all categories) and group set to 0. This function allows setting all filter data for a fixture at once. To set only the categories, the mask or the group, you can use [Fixture:setCategory](fixture-setcategory "Fixture:setCategory"), [Fixture:setMask](fixture-setmask "Fixture:setMask") or [Fixture:setGroupIndex](fixture-setgroupindex "Fixture:setGroupIndex") respectively. Function -------- ### Synopsis ``` Fixture:setFilterData( categories, mask, group ) ``` ### Arguments `[number](number "number") categories` The categories as an integer from 0 to 65535. `[number](number "number") mask` The mask as an integer from 0 to 65535. `[number](number "number") group` The group as an integer from -32768 to 32767. ### Returns Nothing. See Also -------- * [Fixture](fixture "Fixture") * [Fixture:getFilterData](fixture-getfilterdata "Fixture:getFilterData") love love.graphics.ellipse love.graphics.ellipse ===================== **Available since LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** This function is not supported in earlier versions. Draws an ellipse. Function -------- ### Synopsis ``` love.graphics.ellipse( mode, x, y, radiusx, radiusy ) ``` ### Arguments `[DrawMode](drawmode "DrawMode") mode` How to draw the ellipse. `[number](number "number") x` The position of the center along x-axis. `[number](number "number") y` The position of the center along y-axis. `[number](number "number") radiusx` The radius of the ellipse along the x-axis (half the ellipse's width). `[number](number "number") radiusy` The radius of the ellipse along the y-axis (half the ellipse's height). ### Returns Nothing. Function -------- ### Synopsis ``` love.graphics.ellipse( mode, x, y, radiusx, radiusy, segments ) ``` ### Arguments `[DrawMode](drawmode "DrawMode") mode` How to draw the ellipse. `[number](number "number") x` The position of the center along x-axis. `[number](number "number") y` The position of the center along y-axis. `[number](number "number") radiusx` The radius of the ellipse along the x-axis (half the ellipse's width). `[number](number "number") radiusy` The radius of the ellipse along the y-axis (half the ellipse's height). `[number](number "number") segments` The number of segments used for drawing the ellipse. ### Returns Nothing. Examples -------- ### The effect of the segment argument ``` function love.draw() love.graphics.setColor(255, 255, 255) love.graphics.ellipse("fill", 300, 300, 75, 50, 100) -- Draw white ellipse with 100 segments. love.graphics.setColor(255, 0, 0) love.graphics.ellipse("fill", 300, 300, 75, 50, 5) -- Draw red ellipse with five segments. end ``` See Also -------- * [love.graphics](love.graphics "love.graphics") love Texture Texture ======= **Available since LÖVE [0.9.1](https://love2d.org/wiki/0.9.1 "0.9.1")** This type is not supported in earlier versions, but the methods were still available on [Canvas](canvas "Canvas") and [Image](image "Image") objects. Superclass for drawable objects which represent a texture. All Textures can be drawn with [Quads](quad "Quad"). This is an abstract type that can't be created directly. Functions --------- | | | | | | --- | --- | --- | --- | | [Texture:getDPIScale](texture-getdpiscale "Texture:getDPIScale") | Gets the DPI scale factor of the Texture. | 11.0 | | | [Texture:getDepth](texture-getdepth "Texture:getDepth") | Gets the depth of a [Volume Texture](texturetype "TextureType"). | 11.0 | | | [Texture:getDepthSampleMode](texture-getdepthsamplemode "Texture:getDepthSampleMode") | Gets the comparison mode used when sampling from a [depth texture](pixelformat "PixelFormat") in a shader. | 11.0 | | | [Texture:getDimensions](texture-getdimensions "Texture:getDimensions") | Gets the width and height of the Texture. | 0.9.0 | | | [Texture:getFilter](texture-getfilter "Texture:getFilter") | Gets the [filter mode](filtermode "FilterMode") of the Texture. | | | | [Texture:getFormat](texture-getformat "Texture:getFormat") | Gets the [pixel format](pixelformat "PixelFormat") of the Texture. | 11.0 | | | [Texture:getHeight](texture-getheight "Texture:getHeight") | Gets the height of the Texture. | | | | [Texture:getLayerCount](texture-getlayercount "Texture:getLayerCount") | Gets the number of layers / slices in an [Array Texture](texturetype "TextureType"). | 11.0 | | | [Texture:getMipmapCount](texture-getmipmapcount "Texture:getMipmapCount") | Gets the number of mipmaps contained in the Texture. | 11.0 | | | [Texture:getMipmapFilter](texture-getmipmapfilter "Texture:getMipmapFilter") | Gets the mipmap filter mode for a Texture. | 0.9.0 | | | [Texture:getPixelDimensions](texture-getpixeldimensions "Texture:getPixelDimensions") | Gets the width and height in pixels of the Texture. | 11.0 | | | [Texture:getPixelHeight](texture-getpixelheight "Texture:getPixelHeight") | Gets the height in pixels of the Texture. | 11.0 | | | [Texture:getPixelWidth](texture-getpixelwidth "Texture:getPixelWidth") | Gets the width in pixels of the Texture. | 11.0 | | | [Texture:getTextureType](texture-gettexturetype "Texture:getTextureType") | Gets the [type](texturetype "TextureType") of the Texture. | 11.0 | | | [Texture:getWidth](texture-getwidth "Texture:getWidth") | Gets the width of the Texture. | | | | [Texture:getWrap](texture-getwrap "Texture:getWrap") | Gets the wrapping properties of a Texture. | | | | [Texture:isReadable](texture-isreadable "Texture:isReadable") | Gets whether the Texture can be drawn sent to a Shader. | 11.0 | | | [Texture:setDepthSampleMode](texture-setdepthsamplemode "Texture:setDepthSampleMode") | Sets the comparison mode used when sampling from a [depth texture](pixelformat "PixelFormat") in a shader. | 11.0 | | | [Texture:setFilter](texture-setfilter "Texture:setFilter") | Sets the [filter mode](filtermode "FilterMode") of the Texture. | | | | [Texture:setMipmapFilter](texture-setmipmapfilter "Texture:setMipmapFilter") | Sets the mipmap filter mode for a Texture. | 0.9.0 | | | [Texture:setWrap](texture-setwrap "Texture:setWrap") | Sets the wrapping properties of a Texture. | | | Supertypes ---------- * [Drawable](drawable "Drawable") * [Object](object "Object") Subtypes -------- | | | | | | --- | --- | --- | --- | | [Canvas](canvas "Canvas") | Off-screen render target. | 0.8.0 | | | [Image](image "Image") | Drawable image type. | | | Enums ----- | | | | | | --- | --- | --- | --- | | [TextureType](texturetype "TextureType") | Types of textures (2D, cubemap, etc.) | 11.0 | | See Also -------- * [love.graphics](love.graphics "love.graphics") * [love.graphics.draw](love.graphics.draw "love.graphics.draw") * [Mesh:setTexture](mesh-settexture "Mesh:setTexture") * [ParticleSystem:setTexture](particlesystem-settexture "ParticleSystem:setTexture") * [SpriteBatch:setTexture](spritebatch-settexture "SpriteBatch:setTexture") * [Shader:send](shader-send "Shader:send") love love.graphics.setIcon love.graphics.setIcon ===================== **Removed in LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** Moved to the [love.window](love.window "love.window") module as [love.window.setIcon](love.window.seticon "love.window.setIcon"). **Available since LÖVE [0.7.0](https://love2d.org/wiki/0.7.0 "0.7.0")** This function is not supported in earlier versions. Set window icon. This feature is not completely supported on Windows (apparently an SDL bug, not a LOVE bug: [[1]](https://bitbucket.org/rude/love/issue/143/windows-no-titlebar-icon)). Function -------- ### Synopsis ``` love.graphics.setIcon( image ) ``` ### Arguments `[Image](image "Image") image` The window icon. ### Returns Nothing. See Also -------- * [love.graphics](love.graphics "love.graphics") love ParticleSystem:setSizes ParticleSystem:setSizes ======================= **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** It has replaced [ParticleSystem:setSize](particlesystem-setsize "ParticleSystem:setSize"). Sets a series of sizes by which to scale a particle sprite. 1.0 is normal size. The particle system will interpolate between each size evenly over the particle's lifetime. At least one size must be specified. A maximum of eight may be used. Function -------- ### Synopsis ``` ParticleSystem:setSizes( size1, size2, ..., size8 ) ``` ### Arguments `[number](number "number") size1` The first size. `[number](number "number") size2` The second size. `[number](number "number") size8` The eighth size. ### Returns Nothing. See Also -------- * [ParticleSystem](particlesystem "ParticleSystem") * [ParticleSystem:setSizeVariation](particlesystem-setsizevariation "ParticleSystem:setSizeVariation") love Joystick:getAxisCount Joystick:getAxisCount ===================== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** It has been moved from [love.joystick.getNumAxes](love.joystick.getnumaxes "love.joystick.getNumAxes"). Gets the number of axes on the joystick. Function -------- ### Synopsis ``` axes = Joystick:getAxisCount( ) ``` ### Arguments None. ### Returns `[number](number "number") axes` The number of axes available. See Also -------- * [Joystick](joystick "Joystick") * [Joystick:getAxis](joystick-getaxis "Joystick:getAxis") * [Joystick:getAxes](joystick-getaxes "Joystick:getAxes") love Joint:getAnchors Joint:getAnchors ================ Get the anchor points of the joint. Function -------- ### Synopsis ``` x1, y1, x2, y2 = Joint:getAnchors( ) ``` ### Arguments None. ### Returns `[number](number "number") x1` The x-component of the anchor on Body 1. `[number](number "number") y1` The y-component of the anchor on Body 1. `[number](number "number") x2` The x-component of the anchor on Body 2. `[number](number "number") y2` The y-component of the anchor on Body 2. See Also -------- * [Joint](joint "Joint") love love.resize love.resize =========== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This callback is not supported in earlier versions. Called when the window is resized, for example if the user resizes the window, or if `love.window.setMode` is called with an unsupported width or height in fullscreen and the window chooses the closest appropriate size. Function -------- ### Synopsis ``` love.resize( w, h ) ``` ### Arguments `[number](number "number") w` The new width. `[number](number "number") h` The new height. ### Returns Nothing. Notes ----- Calls to `love.window.setMode` will **only** trigger this event if the width or height of the window after the call doesn't match the requested width and height. This can happen if a fullscreen mode is requested which doesn't match any supported mode, or if the fullscreen type is ['desktop'](fullscreentype "FullscreenType") and the requested width or height don't match the desktop resolution. Since [11.0](https://love2d.org/wiki/11.0 "11.0"), this function returns width and height in DPI-scaled units rather than pixels. Example ------- ``` function love.resize(w, h) print(("Window resized to width: %d and height: %d."):format(w, h)) end ``` See Also -------- * [love](love "love") * [love.window.setMode](love.window.setmode "love.window.setMode") * [love.window.setFullscreen](love.window.setfullscreen "love.window.setFullscreen") * [love.conf](love.conf "love.conf") love Contact:getFriction Contact:getFriction =================== Get the friction between two shapes that are in contact. Function -------- ### Synopsis ``` friction = Contact:getFriction( ) ``` ### Arguments None. ### Returns `[number](number "number") friction` The friction of the contact. See Also -------- * [Contact](contact "Contact") love WheelJoint:setMotorEnabled WheelJoint:setMotorEnabled ========================== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This method is not supported in earlier versions. Starts and stops the joint motor. Function -------- ### Synopsis ``` WheelJoint:setMotorEnabled( enable ) ``` ### Arguments `[boolean](boolean "boolean") enable` True turns the motor on and false turns it off. ### Returns Nothing. See Also -------- * [WheelJoint](wheeljoint "WheelJoint") love Shape:testSegment Shape:testSegment ================= **Removed in LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This function is not supported in that and later versions. Checks whether a line segment intersects a shape. This function will either return the "time" of impact and the surface normal at the point of collision, or nil if the line does not intersect the shape. The "time" is a value between 0.0 and 1.0 and can be used to calculate where the collision occured. Function -------- ### Synopsis ``` t, xn, yn = Shape:testSegment( x1, y1, x2, y2 ) ``` ### Arguments `[number](number "number") x1` The x-component of the first endpoint. `[number](number "number") y1` The y-component of the first endpoint. `[number](number "number") x2` The x-component of the second endpoint. `[number](number "number") y2` The y-component of the second endpoint. ### Returns `[number](number "number") t` The time of impact, or nil if no impact. `[number](number "number") xn` The x-component of the surface normal. `[number](number "number") yn` The y-component of the surface normal. See Also -------- * [Shape](shape "Shape") love Thread:get Thread:get ========== **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0") and removed in LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** It has been moved to the [Channel](channel "Channel") api. Retrieves the value of a message and removes it from the thread's message box. Function -------- ### Synopsis ``` value = Thread:get( name ) ``` ### Arguments `[string](string "string") name` The name of the message. ### Returns `[Variant](variant "Variant") value` The contents of the message or nil when no message in message box. See Also -------- * [Thread](thread "Thread") * [Thread:set](thread-set "Thread:set") love Mesh:setDrawRange Mesh:setDrawRange ================= **Available since LÖVE [0.9.1](https://love2d.org/wiki/0.9.1 "0.9.1")** This function is not supported in earlier versions. Restricts the drawn vertices of the Mesh to a subset of the total. Function -------- **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This variant is not supported in earlier versions. ### Synopsis ``` Mesh:setDrawRange( start, count ) ``` ### Arguments `[number](number "number") start` The index of the first vertex to use when drawing, or the index of the first value in the vertex map to use if one is set for this Mesh. `[number](number "number") count` The number of vertices to use when drawing, or number of values in the vertex map to use if one is set for this Mesh. ### Returns Nothing. Function -------- Allows all vertices in the Mesh to be drawn. ### Synopsis ``` Mesh:setDrawRange( ) ``` ### Arguments None. ### Returns Nothing. Function -------- **Removed in LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This variant is not supported in that and later versions. ### Synopsis ``` Mesh:setDrawRange( min, max ) ``` ### Arguments `[number](number "number") min` The index of the first vertex to use when drawing, or the index of the first value in the vertex map to use if one is set for this Mesh. `[number](number "number") max` The index of the last vertex to use when drawing, or the index of the last value in the vertex map to use if one is set for this Mesh. ### Returns Nothing. Notes ----- If a [vertex map](mesh-setvertexmap "Mesh:setVertexMap") is used with the Mesh, this method will set a subset of the values in the vertex map array to use, instead of a subset of the total vertices in the Mesh. For example, if `Mesh:setVertexMap(1, 2, 3, 1, 3, 4)` and `Mesh:setDrawRange(4, 2)` are called, vertices 1, 3, and 4 will be drawn. See Also -------- * [Mesh](mesh "Mesh") * [Mesh:getDrawRange](mesh-getdrawrange "Mesh:getDrawRange") * [love.graphics.draw](love.graphics.draw "love.graphics.draw")
programming_docs
love Fixture:getFilterData Fixture:getFilterData ===================== **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This method is not supported in earlier versions. Returns the filter data of the fixture. Categories and masks are encoded as the bits of a 16-bit integer. Function -------- ### Synopsis ``` categories, mask, group = Fixture:getFilterData( ) ``` ### Arguments None. ### Returns `[number](number "number") categories` The categories as an integer from 0 to 65535. `[number](number "number") mask` The mask as an integer from 0 to 65535. `[number](number "number") group` The group as an integer from -32768 to 32767. See Also -------- * [Fixture](fixture "Fixture") * [Fixture:setFilterData](fixture-setfilterdata "Fixture:setFilterData") love Drawable Drawable ======== Superclass for all things that can be drawn on screen. This is an abstract type that can't be created directly. Functions --------- | | | | | | --- | --- | --- | --- | | [Object:release](object-release "Object:release") | Immediately destroys the object's Lua reference. | 11.0 | | | [Object:type](object-type "Object:type") | Gets the type of the object as a string. | | | | [Object:typeOf](object-typeof "Object:typeOf") | Checks whether an object is of a certain type. | | | Supertypes ---------- * [Object](object "Object") Subtypes -------- | | | | | | --- | --- | --- | --- | | [Canvas](canvas "Canvas") | Off-screen render target. | 0.8.0 | | | [Framebuffer](framebuffer "Framebuffer") | Off-screen render target. | 0.7.0 | 0.8.0 | | [Image](image "Image") | Drawable image type. | | | | [Mesh](mesh "Mesh") | A 2D polygon mesh used for drawing arbitrary textured shapes. | 0.9.0 | | | [ParticleSystem](particlesystem "ParticleSystem") | Used to create cool effects, like fire. | | | | [SpriteBatch](spritebatch "SpriteBatch") | Store image positions in a buffer, and draw it in one call. | | | | [Text](text "Text") | Drawable text. | 0.10.0 | | | [Texture](texture "Texture") | Superclass for drawable objects which represent a texture. | 0.9.1 | | | [Video](video "Video") | A drawable video. | 0.10.0 | | See Also -------- * [love.graphics](love.graphics "love.graphics") love Body:setType Body:setType ============ **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This method is not supported in earlier versions. Sets a new body type. Function -------- ### Synopsis ``` Body:setType( type ) ``` ### Arguments `[BodyType](bodytype "BodyType") type` The new type. ### Returns Nothing. See Also -------- * [Body](body "Body") * [Body:getType](body-gettype "Body:getType") love ChainShape:getPreviousVertex ChainShape:getPreviousVertex ============================ **Available since LÖVE [0.10.2](https://love2d.org/wiki/0.10.2 "0.10.2")** This function is not supported in earlier versions. Gets the vertex that establishes a connection to the previous shape. Setting next and previous ChainShape vertices can help prevent unwanted collisions when a flat shape slides along the edge and moves over to the new shape. Function -------- ### Synopsis ``` x, y = ChainShape:getPreviousVertex( ) ``` ### Arguments None. ### Returns `[number](number "number") x (nil)` The x-component of the vertex, or nil if [ChainShape:setPreviousVertex](chainshape-setpreviousvertex "ChainShape:setPreviousVertex") hasn't been called. `[number](number "number") y (nil)` The y-component of the vertex, or nil if [ChainShape:setPreviousVertex](chainshape-setpreviousvertex "ChainShape:setPreviousVertex") hasn't been called. See Also -------- * [ChainShape](chainshape "ChainShape") * [ChainShape:setPreviousVertex](chainshape-setpreviousvertex "ChainShape:setPreviousVertex") * [ChainShape:getNextVertex](chainshape-getnextvertex "ChainShape:getNextVertex") love love.errorhandler love.errorhandler ================= **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** It has been renamed from [love.errhand](love.errhand "love.errhand"). The error handler, used to display error messages. Note that if the error handler itself throws error, LÖVE only prints the error in the console and exit immediately! Function -------- ### Synopsis ``` mainLoop = love.errorhandler( msg ) ``` ### Arguments `[string](string "string") msg` The error message. ### Returns `[function](function "function") mainLoop` Function which handles one frame, including events and rendering, when called. Examples -------- ### The default function used if you don't supply your own. ``` local utf8 = require("utf8")   local function error_printer(msg, layer) print((debug.traceback("Error: " .. tostring(msg), 1+(layer or 1)):gsub("\n[^\n]+$", ""))) end   function love.errorhandler(msg) msg = tostring(msg)   error_printer(msg, 2)   if not love.window or not love.graphics or not love.event then return end   if not love.graphics.isCreated() or not love.window.isOpen() then local success, status = pcall(love.window.setMode, 800, 600) if not success or not status then return end end   -- Reset state. if love.mouse then love.mouse.setVisible(true) love.mouse.setGrabbed(false) love.mouse.setRelativeMode(false) if love.mouse.isCursorSupported() then love.mouse.setCursor() end end if love.joystick then -- Stop all joystick vibrations. for i,v in ipairs(love.joystick.getJoysticks()) do v:setVibration() end end if love.audio then love.audio.stop() end   love.graphics.reset() local font = love.graphics.setNewFont(14)   love.graphics.setColor(1, 1, 1, 1)   local trace = debug.traceback()   love.graphics.origin()   local sanitizedmsg = {} for char in msg:gmatch(utf8.charpattern) do table.insert(sanitizedmsg, char) end sanitizedmsg = table.concat(sanitizedmsg)   local err = {}   table.insert(err, "Error\n") table.insert(err, sanitizedmsg)   if #sanitizedmsg ~= #msg then table.insert(err, "Invalid UTF-8 string in error message.") end   table.insert(err, "\n")   for l in trace:gmatch("(.-)\n") do if not l:match("boot.lua") then l = l:gsub("stack traceback:", "Traceback\n") table.insert(err, l) end end   local p = table.concat(err, "\n")   p = p:gsub("\t", "") p = p:gsub("%[string \"(.-)\"%]", "%1")   local function draw() local pos = 70 love.graphics.clear(89/255, 157/255, 220/255) love.graphics.printf(p, pos, pos, love.graphics.getWidth() - pos) love.graphics.present() end   local fullErrorText = p local function copyToClipboard() if not love.system then return end love.system.setClipboardText(fullErrorText) p = p .. "\nCopied to clipboard!" draw() end   if love.system then p = p .. "\n\nPress Ctrl+C or tap to copy this error" end   return function() love.event.pump()   for e, a, b, c in love.event.poll() do if e == "quit" then return 1 elseif e == "keypressed" and a == "escape" then return 1 elseif e == "keypressed" and a == "c" and love.keyboard.isDown("lctrl", "rctrl") then copyToClipboard() elseif e == "touchpressed" then local name = love.window.getTitle() if #name == 0 or name == "Untitled" then name = "Game" end local buttons = {"OK", "Cancel"} if love.system then buttons[3] = "Copy to clipboard" end local pressed = love.window.showMessageBox("Quit "..name.."?", "", buttons) if pressed == 1 then return 1 elseif pressed == 3 then copyToClipboard() end end end   draw()   if love.timer then love.timer.sleep(0.1) end end   end ``` See Also -------- * [love](love "love") love PulleyJoint:getConstant PulleyJoint:getConstant ======================= Get the total length of the rope. Function -------- ### Synopsis ``` length = PulleyJoint:getConstant( ) ``` ### Arguments None. ### Returns `[number](number "number") length` The length of the rope in the joint. See Also -------- * [PulleyJoint](pulleyjoint "PulleyJoint") love PrismaticJoint:getUpperLimit PrismaticJoint:getUpperLimit ============================ Gets the upper limit. Function -------- ### Synopsis ``` upper = PrismaticJoint:getUpperLimit( ) ``` ### Arguments None. ### Returns `[number](number "number") upper` The upper limit, usually in meters. See Also -------- * [PrismaticJoint](prismaticjoint "PrismaticJoint") love Shape:getFriction Shape:getFriction ================= **Removed in LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This function is not supported in that and later versions. Gets the friction of this shape. Function -------- ### Synopsis ``` friction = Shape:getFriction( ) ``` ### Arguments None. ### Returns `[number](number "number") friction` The friction of this Shape. See Also -------- * [Shape](shape "Shape") love Canvas:getMipmapMode Canvas:getMipmapMode ==================== **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This function is not supported in earlier versions. Gets the [MipmapMode](mipmapmode "MipmapMode") this Canvas was created with. Function -------- ### Synopsis ``` mode = Canvas:getMipmapMode( ) ``` ### Arguments None. ### Returns `[MipmapMode](mipmapmode "MipmapMode") mode` The mipmap mode this Canvas was created with. See Also -------- * [Canvas](canvas "Canvas") * [love.graphics.newCanvas](love.graphics.newcanvas "love.graphics.newCanvas") * [Canvas:generateMipmaps](canvas-generatemipmaps "Canvas:generateMipmaps") love ParticleSystem:setLinearDamping ParticleSystem:setLinearDamping =============================== **Available since LÖVE [0.9.2](https://love2d.org/wiki/0.9.2 "0.9.2")** This function is not supported in earlier versions. Sets the amount of linear damping (constant deceleration) for particles. Function -------- ### Synopsis ``` ParticleSystem:setLinearDamping( min, max ) ``` ### Arguments `[number](number "number") min` The minimum amount of linear damping applied to particles. `[number](number "number") max (min)` The maximum amount of linear damping applied to particles. ### Returns Nothing. See Also -------- * [ParticleSystem](particlesystem "ParticleSystem") * [ParticleSystem:getLinearDamping](particlesystem-getlineardamping "ParticleSystem:getLinearDamping") love love.audio.getActiveSourceCount love.audio.getActiveSourceCount =============================== **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** It has been renamed from [love.audio.getSourceCount](love.audio.getsourcecount "love.audio.getSourceCount"). Gets the current number of simultaneously playing sources. Function -------- ### Synopsis ``` count = love.audio.getActiveSourceCount( ) ``` ### Arguments None. ### Returns `[number](number "number") count` The current number of simultaneously playing sources. See Also -------- * [love.audio](love.audio "love.audio") love love.mouse.getX love.mouse.getX =============== Returns the current x-position of the mouse. Function -------- ### Synopsis ``` x = love.mouse.getX( ) ``` ### Arguments None. ### Returns `[number](number "number") x` The position of the mouse along the x-axis. Examples -------- Draw a vertical [line](love.graphics.line "love.graphics.line") at the mouse's x-position. ``` function love.draw() local x = love.mouse.getX() love.graphics.line(x,0, x,love.graphics.getHeight()) end ``` See Also -------- * [love.mouse](love.mouse "love.mouse") * [love.mouse.getY](love.mouse.gety "love.mouse.getY") * [love.mouse.getPosition](love.mouse.getposition "love.mouse.getPosition") love love.touch.getPosition love.touch.getPosition ====================== **Available since LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** This function is not supported in earlier versions. Gets the current position of the specified touch-press, in pixels. Function -------- ### Synopsis ``` x, y = love.touch.getPosition( id ) ``` ### Arguments `[light userdata](light_userdata "light userdata") id` The identifier of the touch-press. Use [love.touch.getTouches](love.touch.gettouches "love.touch.getTouches"), [love.touchpressed](love.touchpressed "love.touchpressed"), or [love.touchmoved](love.touchmoved "love.touchmoved") to obtain touch id values. ### Returns `[number](number "number") x` The position along the x-axis of the touch-press inside the window, in pixels. `[number](number "number") y` The position along the y-axis of the touch-press inside the window, in pixels. Notes ----- The unofficial Android and iOS ports of LÖVE 0.9.2 reported touch-press positions as normalized values in the range of [0, 1], whereas this API reports positions in pixels. Examples -------- ### Draw a circle at each location in the window where a touch press is active. ``` function love.draw() local touches = love.touch.getTouches()   for i, id in ipairs(touches) do local x, y = love.touch.getPosition(id) love.graphics.circle("fill", x, y, 20) end end ``` See Also -------- * [love.touch](love.touch "love.touch") * [love.touch.getTouches](love.touch.gettouches "love.touch.getTouches") * [love.touchpressed](love.touchpressed "love.touchpressed") * [love.touchreleased](love.touchreleased "love.touchreleased") love love.window.close love.window.close ================= **Available since LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** This function is not supported in earlier versions. Closes the window. It can be reopened with [love.window.setMode](love.window.setmode "love.window.setMode"). [love.graphics](love.graphics "love.graphics") functions and objects will cause a hard crash of LÖVE if used while the window is closed. Function -------- ### Synopsis ``` love.window.close( ) ``` ### Arguments None. ### Returns Nothing. Notes ----- This only close the window and leave LÖVE running in the background. If you want to stop the program, consider [love.event.quit](love.event.quit "love.event.quit"). See Also -------- * [love.window](love.window "love.window") * [love.window.setMode](love.window.setmode "love.window.setMode") * [love.graphics.isActive](love.graphics.isactive "love.graphics.isActive") love Body:getFixtures Body:getFixtures ================ **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** It has been renamed from [Body:getFixtureList](body-getfixturelist "Body:getFixtureList"). Returns a table with all fixtures. Function -------- ### Synopsis ``` fixtures = Body:getFixtures( ) ``` ### Arguments None. ### Returns `[table](table "table") fixtures` A [sequence](sequence "sequence") with all [fixtures](fixture "Fixture"). See Also -------- * [Body](body "Body") * [Fixture](fixture "Fixture") love love.graphics.setFont love.graphics.setFont ===================== Set an already-loaded [Font](font "Font") as the current font or create and load a new one from the file and size. It's recommended that [Font](font "Font") objects are created with [love.graphics.newFont](love.graphics.newfont "love.graphics.newFont") in the loading stage and then passed to this function in the drawing stage. Function -------- ### Synopsis ``` love.graphics.setFont( font ) ``` ### Arguments `[Font](font "Font") font` The Font object to use. ### Returns Nothing. Function -------- **Removed in LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This variant is not supported in that and later versions. ### Synopsis ``` love.graphics.setFont( filename, size ) ``` ### Arguments `[string](string "string") filename` The filepath to the font. `[number](number "number") size (12)` The size of the font. ### Returns Nothing. Function -------- **Removed in LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This variant is not supported in that and later versions. This variant creates a new font using the default font and the size specified, and sets it as the current font. **Do not use this function in [love.update](love.update "love.update") or [love.draw](love.draw "love.draw").** That would create a new font every frame, eating up memory very quickly. ### Synopsis ``` love.graphics.setFont( size ) ``` ### Arguments `[number](number "number") size (12)` The size of the font. ### Returns Nothing. Examples -------- ### Draw some text with default font, 18px ``` function love.graphics.load() love.graphics.setFont(love.graphics.newFont(18)) end   function love.draw() love.graphics.print("Hello", 300, 300) end ``` ### Draw some text with custom font, 18px ``` function love.load() Font = love.graphics.newFont("font.ttf", 18) end   function love.draw() love.graphics.setFont(Font) love.graphics.print("Hello World", 0, 0) end ``` See Also -------- * [love.graphics](love.graphics "love.graphics") * [love.graphics.newFont](love.graphics.newfont "love.graphics.newFont") * [love.graphics.getFont](love.graphics.getfont "love.graphics.getFont") * [love.graphics.setNewFont](love.graphics.setnewfont "love.graphics.setNewFont") love AreaSpreadDistribution AreaSpreadDistribution ====================== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This enum is not supported in earlier versions. Types of particle area spread distribution. Constants --------- uniform Uniform distribution. normal Normal (gaussian) distribution. ellipse Available since 0.10.2 Uniform distribution in an ellipse. borderellipse Available since 11.0 Distribution in an ellipse with particles spawning at the edges of the ellipse. borderrectangle Available since 11.0 Distribution in a rectangle with particles spawning at the edges of the rectangle. none No distribution - area spread is disabled. See Also -------- * [ParticleSystem](particlesystem "ParticleSystem") * [ParticleSystem:setAreaSpread](particlesystem-setareaspread "ParticleSystem:setAreaSpread") * [ParticleSystem:getAreaSpread](particlesystem-getareaspread "ParticleSystem:getAreaSpread") love World:queryBoundingBox World:queryBoundingBox ====================== **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This method is not supported in earlier versions. Calls a function for each fixture inside the specified area by searching for any overlapping bounding box ([Fixture:getBoundingBox](fixture-getboundingbox "Fixture:getBoundingBox")). Function -------- ### Synopsis ``` World:queryBoundingBox( topLeftX, topLeftY, bottomRightX, bottomRightY, callback ) ``` ### Arguments `[number](number "number") topLeftX` The x position of the top-left point. `[number](number "number") topLeftY` The y position of the top-left point. `[number](number "number") bottomRightX` The x position of the bottom-right point. `[number](number "number") bottomRightY` The y position of the bottom-right point. `[function](function "function") callback` This function gets passed one argument, the fixture, and should return a boolean. The search will continue if it is true or stop if it is false. ### Returns Nothing. See Also -------- * [World](world "World") love PulleyJoint:getRatio PulleyJoint:getRatio ==================== Get the pulley ratio. Function -------- ### Synopsis ``` ratio = PulleyJoint:getRatio( ) ``` ### Arguments None. ### Returns `[number](number "number") ratio` The pulley ratio of the joint. See Also -------- * [PulleyJoint](pulleyjoint "PulleyJoint") love Mesh:attachAttribute Mesh:attachAttribute ==================== **Available since LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** This function is not supported in earlier versions. Attaches a vertex attribute from a different Mesh onto this Mesh, for use when drawing. This can be used to share vertex attribute data between several different Meshes. Function -------- ### Synopsis ``` Mesh:attachAttribute( name, mesh ) ``` ### Arguments `[string](string "string") name` The name of the vertex attribute to attach. `[Mesh](mesh "Mesh") mesh` The Mesh to get the vertex attribute from. ### Returns Nothing. Function -------- **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This variant is not supported in earlier versions. ### Synopsis ``` Mesh:attachAttribute( name, mesh, step, attachname ) ``` ### Arguments `[string](string "string") name` The name of the vertex attribute to attach. `[Mesh](mesh "Mesh") mesh` The Mesh to get the vertex attribute from. `[VertexAttributeStep](vertexattributestep "VertexAttributeStep") step ("pervertex")` Whether the attribute will be per-vertex or [per-instance](love.graphics.drawinstanced "love.graphics.drawInstanced") when the mesh is drawn. `[string](string "string") attachname (name)` The name of the attribute to use in shader code. Defaults to the name of the attribute in the given mesh. Can be used to use a different name for this attribute when rendering. ### Returns Nothing. Notes ----- If a Mesh wasn't [created](love.graphics.newmesh "love.graphics.newMesh") with a custom vertex format, it will have 3 vertex attributes named `VertexPosition`, `VertexTexCoord`, and `VertexColor`. Custom named attributes can be accessed in a [vertex shader](shader "Shader") by declaring them as `attribute vec4 MyCustomAttributeName;` at the top-level of the vertex shader code. The name must match what was specified in the Mesh's vertex format and in the `name` argument of **Mesh:attachAttribute**. See Also -------- * [Mesh](mesh "Mesh") * [Mesh:getVertexFormat](mesh-getvertexformat "Mesh:getVertexFormat") * [love.graphics.draw](love.graphics.draw "love.graphics.draw")
programming_docs
love love.graphics.getMeshCullMode love.graphics.getMeshCullMode ============================= **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This function is not supported in earlier versions. Gets whether [back-facing](love.graphics.setfrontfacewinding "love.graphics.setFrontFaceWinding") triangles in a [Mesh](mesh "Mesh") are culled. Mesh face culling is designed for use with low level custom hardware-accelerated 3D rendering via [custom vertex attributes](love.graphics.newmesh "love.graphics.newMesh") on Meshes, custom [vertex shaders](love.graphics.newshader "love.graphics.newShader"), and [depth testing](love.graphics.setdepthmode "love.graphics.setDepthMode") with a [depth buffer](pixelformat "PixelFormat"). Function -------- ### Synopsis ``` mode = love.graphics.getMeshCullMode( mode ) ``` ### Arguments None. ### Returns `[CullMode](cullmode "CullMode") mode` The Mesh face culling mode in use (whether to render everything, cull back-facing triangles, or cull front-facing triangles). See Also -------- * [love.graphics](love.graphics "love.graphics") * [love.graphics.setMeshCullMode](love.graphics.setmeshcullmode "love.graphics.setMeshCullMode") * [love.graphics.setFrontFaceWinding](love.graphics.setfrontfacewinding "love.graphics.setFrontFaceWinding") * [love.graphics.setDepthMode](love.graphics.setdepthmode "love.graphics.setDepthMode") * [Mesh](mesh "Mesh") love MouseJoint:setFrequency MouseJoint:setFrequency ======================= **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This method is not supported in earlier versions. Sets a new frequency. Function -------- ### Synopsis ``` MouseJoint:setFrequency( freq ) ``` ### Arguments `[number](number "number") freq` The new frequency in hertz. ### Returns Nothing. See Also -------- * [MouseJoint](mousejoint "MouseJoint") * [MouseJoint:getFrequency](mousejoint-getfrequency "MouseJoint:getFrequency") love Quad:getViewport Quad:getViewport ================ Gets the current viewport of this Quad. Function -------- ### Synopsis ``` x, y, w, h = Quad:getViewport( ) ``` ### Arguments None. ### Returns `[number](number "number") x` The top-left corner along the x-axis. `[number](number "number") y` The top-left corner along the y-axis. `[number](number "number") w` The width of the viewport. `[number](number "number") h` The height of the viewport. See Also -------- * [Quad](quad "Quad") * [Quad:setViewport](quad-setviewport "Quad:setViewport") love Canvas:clear Canvas:clear ============ **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0") and removed in LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** It has been replaced by [love.graphics.clear](love.graphics.clear "love.graphics.clear"). Clears the contents of a [Canvas](canvas "Canvas") to a specific color. Calling this function directly after the Canvas becomes active (via [love.graphics.setCanvas](love.graphics.setcanvas "love.graphics.setCanvas") or [Canvas:renderTo](canvas-renderto "Canvas:renderTo")) is more efficient than calling it when the Canvas isn't active, especially on mobile devices. [love.graphics.setScissor](love.graphics.setscissor "love.graphics.setScissor") will restrict the area of the Canvas that this function affects. Function -------- Clear the canvas to transparent black: (0, 0, 0, 0). ### Synopsis ``` Canvas:clear( ) ``` ### Arguments None. ### Returns Nothing. Function -------- Clear the canvas to a specific color. ### Synopsis ``` Canvas:clear( red, green, blue, alpha ) ``` ### Arguments `[number](number "number") red` Red component of the clear color (0-255). `[number](number "number") green` Green component of the clear color (0-255). `[number](number "number") blue` Blue component of the clear color (0-255). `[number](number "number") alpha (255)` Alpha component of the clear color (0-255). ### Returns Nothing. Function -------- ### Synopsis ``` Canvas:clear( rgba ) ``` ### Arguments `[table](table "table") rgba` A [sequence](sequence "sequence") with the red, green, blue and alpha values as numbers (alpha may be ommitted). ### Returns Nothing. Examples -------- ### Clear canvas before drawing If the c-key is pressed the canvas will be cleared before drawing a new line on the screen. ``` local canvas = love.graphics.newCanvas() local clear function love.update() -- Use an anonymous function to draw lines on our canvas. canvas:renderTo(function() if clear then canvas:clear() end -- Clear the canvas before drawing lines. love.graphics.setColor(love.math.random(255), 0, 0) love.graphics.line(0, 0, love.math.random(0, love.graphics.getWidth()), love.math.random(0, love.graphics.getHeight())) end) end   function love.draw() love.graphics.setColor(255, 255, 255) love.graphics.draw(canvas) end   function love.keypressed(key) if key == "c" then clear = not clear end end ``` See Also -------- * [Canvas](canvas "Canvas") love love.keyboard.getKeyRepeat love.keyboard.getKeyRepeat ========================== **Removed in LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in that and later versions. Returns the delay and interval of key repeating. Function -------- ### Synopsis ``` delay, interval = love.keyboard.getKeyRepeat( ) ``` ### Arguments None. ### Returns `[number](number "number") delay` The amount of time before repeating the key (in seconds) `[number](number "number") interval` The amount of time between repeats (in seconds) See Also -------- * [love.keyboard](love.keyboard "love.keyboard") love Texture:getTextureType Texture:getTextureType ====================== **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This function is not supported in earlier versions. Gets the [type](texturetype "TextureType") of the Texture. Function -------- ### Synopsis ``` texturetype = Texture:getTextureType( ) ``` ### Arguments None. ### Returns `[TextureType](texturetype "TextureType") texturetype` The type of the Texture. See Also -------- * [Texture](texture "Texture") love love.textedited love.textedited =============== **Available since LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** This function is not supported in earlier versions. Called when the candidate text for an IME (Input Method Editor) has changed. The candidate text is not the final text that the user will eventually choose. Use [love.textinput](love.textinput "love.textinput") for that. Function -------- ### Synopsis ``` love.textedited( text, start, length ) ``` ### Arguments `[string](string "string") text` The UTF-8 encoded unicode candidate text. `[number](number "number") start` The start cursor of the selected candidate text. `[number](number "number") length` The length of the selected candidate text. May be 0. ### Returns Nothing. See Also -------- * [love](love "love") * [love.textinput](love.textinput "love.textinput") * [love.keyboard.setTextInput](love.keyboard.settextinput "love.keyboard.setTextInput") * [love.keyboard.hasTextInput](love.keyboard.hastextinput "love.keyboard.hasTextInput") * [utf8](utf8 "utf8") love Joystick:isVibrationSupported Joystick:isVibrationSupported ============================= **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Gets whether the Joystick supports vibration. Function -------- ### Synopsis ``` supported = Joystick:isVibrationSupported( ) ``` ### Arguments None. ### Returns `[boolean](boolean "boolean") supported` True if rumble / force feedback vibration is supported on this Joystick, false if not. Notes ----- The very first call to this function may take more time than expected because SDL's Haptic / Force Feedback subsystem needs to be initialized. See Also -------- * [Joystick](joystick "Joystick") * [Joystick:setVibration](joystick-setvibration "Joystick:setVibration") * [Joystick:getVibration](joystick-getvibration "Joystick:getVibration") love Mesh:getVertexFormat Mesh:getVertexFormat ==================== **Available since LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** This function is not supported in earlier versions. Gets the vertex format that the Mesh was [created](love.graphics.newmesh "love.graphics.newMesh") with. Function -------- ### Synopsis ``` format = Mesh:getVertexFormat( ) ``` ### Arguments None. ### Returns `[table](table "table") format` The vertex format of the Mesh, which is a table containing tables for each vertex attribute the Mesh was created with, in the form of `{attribute, ...}`. `[table](table "table") attribute` A table containing the attribute's name, it's [data type](attributedatatype "AttributeDataType"), and the number of components in the attribute, in the form of `{name, datatype, components}`. `[table](table "table") ...` Additional vertex attributes in the Mesh. Notes ----- If a Mesh wasn't [created](love.graphics.newmesh "love.graphics.newMesh") with a custom vertex format, it will have the following vertex format: ``` defaultformat = { {"VertexPosition", "float", 2}, -- The x,y position of each vertex. {"VertexTexCoord", "float", 2}, -- The u,v texture coordinates of each vertex. {"VertexColor", "byte", 4} -- The r,g,b,a color of each vertex. } ``` See Also -------- * [Mesh](mesh "Mesh") * [love.graphics.newMesh](love.graphics.newmesh "love.graphics.newMesh") * [AttributeDataType](attributedatatype "AttributeDataType") * [Mesh:setVertex](mesh-setvertex "Mesh:setVertex") * [Mesh:setVertexAttribute](mesh-setvertexattribute "Mesh:setVertexAttribute") * [love.graphics.draw](love.graphics.draw "love.graphics.draw") love love.graphics.newVolumeImage love.graphics.newVolumeImage ============================ **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This function is not supported in earlier versions. Creates a new [volume](texturetype "TextureType") (3D) [Image](image "Image"). This function can be slow if it is called repeatedly, such as from [love.update](love.update "love.update") or [love.draw](love.draw "love.draw"). If you need to use a specific resource often, create it once and store it somewhere it can be reused! Volume images are 3D textures with width, height, and depth. They can't be rendered directly, they can only be used in [Shader](shader "Shader") code (and sent to the shader via [Shader:send](shader-send "Shader:send")). Or, more accurately, the default shaders can't render volume images, and you need to make one yourself to do it. To use a volume image in a Shader, it must be declared as a `VolumeImage` or `sampler3D` type (instead of `Image` or `sampler2D`). The `Texel(VolumeImage image, vec3 texcoords)` shader function must be used to get pixel colors from the volume image. The vec3 argument is a normalized texture coordinate with the z component representing the depth to sample at (ranging from [0, 1]). Volume images are typically used as lookup tables in shaders for color grading, for example, because sampling using a texture coordinate that is partway in between two pixels can interpolate across all 3 dimensions in the volume image, resulting in a smooth gradient even when a small-sized volume image is used as the lookup table. [Array images](love.graphics.newarrayimage "love.graphics.newArrayImage") are a much better choice than volume images for storing multiple different sprites in a single array image for directly drawing them. Function -------- Creates a volume Image given multiple image files with matching dimensions. ### Synopsis ``` image = love.graphics.newVolumeImage( layers, settings ) ``` ### Arguments `[table](table "table") layers` A table containing filepaths to images (or [File](file "File"), [FileData](filedata "FileData"), [ImageData](imagedata "ImageData"), or [CompressedImageData](compressedimagedata "CompressedImageData") objects), in an array. A table of tables can also be given, where each sub-table represents a single mipmap level and contains all layers for that mipmap. `[table](table "table") settings (nil)` Optional table of settings to configure the volume image, containing the following fields: `[boolean](boolean "boolean") mipmaps (false)` True to make the image use mipmaps, false to disable them. Mipmaps will be automatically generated if the image isn't a [compressed texture](pixelformat "PixelFormat") format. `[boolean](boolean "boolean") linear (false)` True to treat the image's pixels as linear instead of sRGB, when [gamma correct rendering](love.graphics.isgammacorrect "love.graphics.isGammaCorrect") is enabled. Most images are authored as sRGB. ### Returns `[Image](image "Image") image` A volume Image object. Notes ----- Volume images are not supported on some older mobile devices. Use [love.graphics.getTextureTypes](love.graphics.gettexturetypes "love.graphics.getTextureTypes") to check at runtime. See Also -------- * [love.graphics](love.graphics "love.graphics") * [Image](image "Image") * [TextureType](texturetype "TextureType") love Text Text ==== **Available since LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** This type is not supported in earlier versions. Drawable text. Text may appear blurry if it's rendered at non-integer pixel locations. Constructors ------------ | | | | | | --- | --- | --- | --- | | [love.graphics.newText](love.graphics.newtext "love.graphics.newText") | Creates a new drawable **Text** object. | 0.10.0 | | Functions --------- | | | | | | --- | --- | --- | --- | | [Object:release](object-release "Object:release") | Immediately destroys the object's Lua reference. | 11.0 | | | [Object:type](object-type "Object:type") | Gets the type of the object as a string. | | | | [Object:typeOf](object-typeof "Object:typeOf") | Checks whether an object is of a certain type. | | | | [Text:add](text-add "Text:add") | Adds additional colored text to the Text object at the specified position. | 0.10.0 | | | [Text:addf](text-addf "Text:addf") | Adds additional formatted / colored text to the Text object at the specified position. | 0.10.0 | | | [Text:clear](text-clear "Text:clear") | Clears the contents of the Text object. | 0.10.0 | | | [Text:getDimensions](text-getdimensions "Text:getDimensions") | Gets the width and height of the text. | 0.10.1 | | | [Text:getFont](text-getfont "Text:getFont") | Gets the [Font](font "Font") used with the **Text** object. | 0.10.0 | | | [Text:getHeight](text-getheight "Text:getHeight") | Gets the height of the text. | 0.10.0 | | | [Text:getWidth](text-getwidth "Text:getWidth") | Gets the width of the text. | 0.10.0 | | | [Text:set](text-set "Text:set") | Replaces the contents of the Text object with a new string. | 0.10.0 | | | [Text:setFont](text-setfont "Text:setFont") | Replaces the [Font](font "Font") used with the text. | 0.10.0 | | | [Text:setf](text-setf "Text:setf") | Replaces the contents of the Text object with a new formatted string. | 0.10.0 | | Supertypes ---------- * [Drawable](drawable "Drawable") * [Object](object "Object") See Also -------- * [love.graphics](love.graphics "love.graphics") * [Font](font "Font") * [love.graphics.draw](love.graphics.draw "love.graphics.draw") love PolygonShape:validate PolygonShape:validate ===================== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Validates whether the PolygonShape is convex. Concave PolygonShapes cannot be used in [love.physics](love.physics "love.physics"). Function -------- ### Synopsis ``` convex = PolygonShape:validate() ``` ### Arguments None. ### Returns `[boolean](boolean "boolean") convex` Whether the PolygonShape is convex. See Also -------- * [PolygonShape](polygonshape "PolygonShape") love World:getJointCount World:getJointCount =================== Returns the number of joints in the world. Function -------- ### Synopsis ``` n = World:getJointCount( ) ``` ### Arguments None. ### Returns `[number](number "number") n` The number of joints in the world. See Also -------- * [World](world "World") love sequence sequence ======== From the Lua 5.2 [reference manual §2.1](https://www.lua.org/manual/5.2/manual.html#2.1): We use the term sequence to denote a [table](table "table") where the set of all positive numeric keys is equal to {1..n} for some integer n, which is called the length of the sequence (see [§3.4.6](https://www.lua.org/manual/5.2/manual.html#3.4.6)). ``` sequence = { 'foo', 'bar', 'baz', 'qux', --[[ ... ]] }   -- or   sequence = { [1] = 'foo', [2] = 'bar', [3] = 'baz', [4] = 'qux', -- [n] = ..., } ``` love SpriteBatch:setLayer SpriteBatch:setLayer ==================== **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This function is not supported in earlier versions. Changes a sprite previously added with [add](spritebatch-add "SpriteBatch:add") or [addLayer](spritebatch-addlayer "SpriteBatch:addLayer"), in a batch created with an [Array Texture](texturetype "TextureType"). Function -------- Changes the sprite in the SpriteBatch. ### Synopsis ``` SpriteBatch:setLayer( spriteindex, layerindex, x, y, r, sx, sy, ox, oy, kx, ky ) ``` ### Arguments `[number](number "number") spriteindex` The index of the existing sprite to replace. `[number](number "number") layerindex` The index of the layer in the Array Texture to use for this sprite. `[number](number "number") x (0)` The position to draw the sprite (x-axis). `[number](number "number") y (0)` The position to draw the sprite (y-axis). `[number](number "number") r (0)` Orientation (radians). `[number](number "number") sx (1)` Scale factor (x-axis). `[number](number "number") sy (sx)` Scale factor (y-axis). `[number](number "number") ox (0)` Origin offset (x-axis). `[number](number "number") oy (0)` Origin offset (y-axis). `[number](number "number") kx (0)` Shearing factor (x-axis). `[number](number "number") ky (0)` Shearing factor (y-axis). ### Returns Nothing. Function -------- Adds a layer of the SpriteBatch's Array Texture using the specified [Quad](quad "Quad"). ### Synopsis ``` SpriteBatch:setLayer( spriteindex, layerindex, quad, x, y, r, sx, sy, ox, oy, kx, ky ) ``` ### Arguments `[number](number "number") spriteindex` The index of the existing sprite to replace. `[number](number "number") layerindex` The index of the layer to use for this sprite. `[Quad](quad "Quad") quad` The subsection of the texture's layer to use when drawing the sprite. `[number](number "number") x (0)` The position to draw the sprite (x-axis). `[number](number "number") y (0)` The position to draw the sprite (y-axis). `[number](number "number") r (0)` Orientation (radians). `[number](number "number") sx (1)` Scale factor (x-axis). `[number](number "number") sy (sx)` Scale factor (y-axis). `[number](number "number") ox (0)` Origin offset (x-axis). `[number](number "number") oy (0)` Origin offset (y-axis). `[number](number "number") kx (0)` Shearing factor (x-axis). `[number](number "number") ky (0)` Shearing factor (y-axis). ### Returns Nothing. ### Notes The specified layer index overrides any layer index set on the Quad via [Quad:setLayer](https://love2d.org/w/index.php?title=Quad:setLayer&action=edit&redlink=1 "Quad:setLayer (page does not exist)"). Function -------- Adds a layer of the SpriteBatch's Array Texture using the specified [Transform](transform "Transform"). ### Synopsis ``` SpriteBatch:setLayer( spriteindex, layerindex, transform ) ``` ### Arguments `[number](number "number") spriteindex` The index of the existing sprite to replace. `[number](number "number") layerindex` The index of the layer to use for the sprite. `[Transform](transform "Transform") transform` A transform object. ### Returns Nothing. Function -------- Adds a layer of the SpriteBatch's Array Texture using the specified [Quad](quad "Quad") and [Transform](transform "Transform"). ### Synopsis ``` SpriteBatch:setLayer( spriteindex, layerindex, quad, transform ) ``` ### Arguments `[number](number "number") spriteindex` The index of the existing sprite to replace. `[number](number "number") layerindex` The index of the layer to use for the sprite. `[Quad](quad "Quad") quad` The subsection of the texture's layer to use when drawing the sprite. `[Transform](transform "Transform") transform` A transform object. ### Returns Nothing. ### Notes The specified layer index overrides any layer index set on the Quad via [Quad:setLayer](https://love2d.org/w/index.php?title=Quad:setLayer&action=edit&redlink=1 "Quad:setLayer (page does not exist)"). See Also -------- * [SpriteBatch](spritebatch "SpriteBatch") * [SpriteBatch:addLayer](spritebatch-addlayer "SpriteBatch:addLayer") * [love.graphics.newArrayImage](love.graphics.newarrayimage "love.graphics.newArrayImage") * [love.graphics.newCanvas](love.graphics.newcanvas "love.graphics.newCanvas") * [love.graphics.newShader](love.graphics.newshader "love.graphics.newShader") * [TextureType](texturetype "TextureType")
programming_docs
love love.graphics.circle love.graphics.circle ==================== Draws a circle. Function -------- ### Synopsis ``` love.graphics.circle( mode, x, y, radius ) ``` ### Arguments `[DrawMode](drawmode "DrawMode") mode` How to draw the circle. `[number](number "number") x` The position of the center along x-axis. `[number](number "number") y` The position of the center along y-axis. `[number](number "number") radius` The radius of the circle. ### Returns Nothing. Function -------- ### Synopsis ``` love.graphics.circle( mode, x, y, radius, segments ) ``` ### Arguments `[DrawMode](drawmode "DrawMode") mode` How to draw the circle. `[number](number "number") x` The position of the center along x-axis. `[number](number "number") y` The position of the center along y-axis. `[number](number "number") radius` The radius of the circle. `[number](number "number") segments` The number of segments used for drawing the circle. Note: The default variable for the segments parameter varies between different versions of LÖVE. ### Returns Nothing. Examples -------- ### The effect of the segment argument ``` function love.draw() love.graphics.setColor(1, 1, 1) love.graphics.circle("fill", 300, 300, 50, 100) -- Draw white circle with 100 segments. love.graphics.setColor(1, 0, 0) love.graphics.circle("fill", 300, 300, 50, 5) -- Draw red circle with five segments. end ``` See Also -------- * [love.graphics](love.graphics "love.graphics") love Body:setLinearDamping Body:setLinearDamping ===================== Sets the linear damping of a Body See [Body:getLinearDamping](body-getlineardamping "Body:getLinearDamping") for a definition of linear damping. Linear damping can take any value from 0 to infinity. It is recommended to stay between 0 and 0.1, though. Other values will make the objects look "floaty"(if gravity is enabled). Function -------- ### Synopsis ``` Body:setLinearDamping( ld ) ``` ### Arguments `[number](number "number") ld` The new linear damping ### Returns Nothing. See Also -------- * [Body](body "Body") love love.mouse.hasCursor love.mouse.hasCursor ==================== **Available since LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** This function is not supported in earlier versions. | | | --- | | ***Deprecated in LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")*** | | This function has been renamed to [love.mouse.isCursorSupported](love.mouse.iscursorsupported "love.mouse.isCursorSupported"). | Gets whether cursor functionality is supported. If it isn't supported, calling [love.mouse.newCursor](love.mouse.newcursor "love.mouse.newCursor") and [love.mouse.getSystemCursor](love.mouse.getsystemcursor "love.mouse.getSystemCursor") will cause an error. Mobile devices do not support cursors. Function -------- ### Synopsis ``` hascursor = love.mouse.hasCursor( ) ``` ### Arguments None. ### Returns `[boolean](boolean "boolean") hascursor` Whether the system has cursor functionality. See Also -------- * [love.mouse](love.mouse "love.mouse") love love.system.hasBackgroundMusic love.system.hasBackgroundMusic ============================== **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This function is not supported in earlier versions. Gets whether another application on the system is playing music in the background. Currently this is implemented on iOS and Android, and will always return false on other operating systems. The `t.audio.mixwithsystem` flag in [love.conf](love.conf "love.conf") can be used to configure whether background audio / music from other apps should play while LÖVE is open. Function -------- ### Synopsis ``` backgroundmusic = love.system.hasBackgroundMusic( ) ``` ### Arguments None. ### Returns `[boolean](boolean "boolean") backgroundmusic` True if the user is playing music in the background via another app, false otherwise. See Also -------- * [love.system](love.system "love.system") love love.physics.newBody love.physics.newBody ==================== Creates a new body. There are three types of bodies. * Static bodies do not move, have a infinite mass, and can be used for level boundaries. * Dynamic bodies are the main actors in the simulation, they collide with everything. * Kinematic bodies do not react to forces and only collide with dynamic bodies. The mass of the body gets calculated when a [Fixture](fixture "Fixture") is attached or removed, but can be changed at any time with [Body:setMass](body-setmass "Body:setMass") or [Body:resetMassData](body-resetmassdata "Body:resetMassData"). Making changes to a [World](world "World") is not allowed inside of the [beginContact](https://love2d.org/w/index.php?title=beginContact&action=edit&redlink=1 "beginContact (page does not exist)"), [endContact](https://love2d.org/w/index.php?title=endContact&action=edit&redlink=1 "endContact (page does not exist)"), [preSolve](https://love2d.org/w/index.php?title=preSolve&action=edit&redlink=1 "preSolve (page does not exist)"), and [postSolve](https://love2d.org/w/index.php?title=postSolve&action=edit&redlink=1 "postSolve (page does not exist)") callback functions, as BOX2D locks the world during these callbacks. Function -------- **Available since LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This variant is not supported in earlier versions. ### Synopsis ``` body = love.physics.newBody( world, x, y, type ) ``` ### Arguments `[World](world "World") world` The world to create the body in. `[number](number "number") x (0)` The x position of the body. `[number](number "number") y (0)` The y position of the body. `[BodyType](bodytype "BodyType") type ("static")` The type of the body. ### Returns `[Body](body "Body") body` A new body. Function -------- **Removed in LÖVE [0.8.0](https://love2d.org/wiki/0.8.0 "0.8.0")** This variant is not supported in that and later versions. ### Synopsis ``` body = love.physics.newBody( world, x, y, m, i ) ``` ### Arguments `[World](world "World") world` The world to create the body in. `[number](number "number") x (0)` The x position of the body. `[number](number "number") y (0)` The y position of the body. `[number](number "number") m (0)` The mass of the body. `[number](number "number") i (0)` The rotational inertia of the body. ### Returns `[Body](body "Body") body` A new body. See Also -------- * [love.physics](love.physics "love.physics") * [Body](body "Body") love love.gamepadpressed love.gamepadpressed =================== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Called when a Joystick's virtual gamepad button is pressed. Function -------- ### Synopsis ``` love.gamepadpressed( joystick, button ) ``` ### Arguments `[Joystick](joystick "Joystick") joystick` The joystick object. `[GamepadButton](gamepadbutton "GamepadButton") button` The virtual gamepad button. ### Returns Nothing. See Also -------- * [love](love "love") * [love.gamepadreleased](love.gamepadreleased "love.gamepadreleased") * [Joystick:isGamepad](joystick-isgamepad "Joystick:isGamepad") love love.threaderror love.threaderror ================ **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This callback is not supported in earlier versions. Callback function triggered when a [Thread](thread "Thread") encounters an error. Function -------- ### Synopsis ``` love.threaderror( thread, errorstr ) ``` ### Arguments `[Thread](thread "Thread") thread` The thread which produced the error. `[string](string "string") errorstr` The error message. ### Returns Nothing. Example ------- ``` function love.load() mythread = love.thread.newThread("thread.lua") mythread:start() end   function love.threaderror(thread, errorstr) print("Thread error!\n"..errorstr) -- thread:getError() will return the same error string now. end ``` See Also -------- * [love](love "love") love love.graphics.getWidth love.graphics.getWidth ====================== **Available since LÖVE [0.2.1](https://love2d.org/wiki/0.2.1 "0.2.1")** This function is not supported in earlier versions. Gets the width in pixels of the window. Function -------- ### Synopsis ``` width = love.graphics.getWidth( ) ``` ### Arguments None. ### Returns `[number](number "number") width` The width of the window. See Also -------- * [love.graphics](love.graphics "love.graphics") * [love.graphics.getHeight](love.graphics.getheight "love.graphics.getHeight") * [love.graphics.getDimensions](love.graphics.getdimensions "love.graphics.getDimensions") love love.graphics.getSystemLimit love.graphics.getSystemLimit ============================ **Available since LÖVE [0.9.1](https://love2d.org/wiki/0.9.1 "0.9.1") and removed in LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** It has been replaced by [love.graphics.getSystemLimits](love.graphics.getsystemlimits "love.graphics.getSystemLimits"). Gets the system-dependent maximum value for a love.graphics feature. Function -------- ### Synopsis ``` limit = love.graphics.getSystemLimit( limittype ) ``` ### Arguments `[GraphicsLimit](graphicslimit "GraphicsLimit") limittype` The graphics feature to get the maximum value of. ### Returns `[number](number "number") limit` The system-dependent max value for the feature. See Also -------- * [love.graphics](love.graphics "love.graphics") love Mesh:isAttributeEnabled Mesh:isAttributeEnabled ======================= **Available since LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** This function is not supported in earlier versions. Gets whether a specific vertex attribute in the Mesh is enabled. Vertex data from disabled attributes is not used when drawing the Mesh. Function -------- ### Synopsis ``` enabled = Mesh:isAttributeEnabled( name ) ``` ### Arguments `[string](string "string") name` The name of the vertex attribute to be checked. ### Returns `[boolean](boolean "boolean") enabled` Whether the vertex attribute is used when drawing this Mesh. Notes ----- If a Mesh wasn't [created](love.graphics.newmesh "love.graphics.newMesh") with a custom vertex format, it will have 3 vertex attributes named `VertexPosition`, `VertexTexCoord`, and `VertexColor`. Otherwise the attribute name must either match one of the vertex attributes specified in the [vertex format](mesh-getvertexformat "Mesh:getVertexFormat") when [creating the Mesh](love.graphics.newmesh "love.graphics.newMesh"), or must match a vertex attribute from another Mesh attached to this Mesh via [Mesh:attachAttribute](mesh-attachattribute "Mesh:attachAttribute"). See Also -------- * [Mesh](mesh "Mesh") * [Mesh:setAttributeEnabled](mesh-setattributeenabled "Mesh:setAttributeEnabled") * [Mesh:getVertexFormat](mesh-getvertexformat "Mesh:getVertexFormat") * [love.graphics.draw](love.graphics.draw "love.graphics.draw") love RevoluteJoint:isMotorEnabled RevoluteJoint:isMotorEnabled ============================ Checks whether the motor is enabled. Function -------- ### Synopsis ``` enabled = RevoluteJoint:isMotorEnabled( ) ``` ### Arguments None. ### Returns `[boolean](boolean "boolean") enabled` True if enabled, false if disabled. See Also -------- * [RevoluteJoint](revolutejoint "RevoluteJoint") love StackType StackType ========= **Available since LÖVE [0.9.2](https://love2d.org/wiki/0.9.2 "0.9.2")** This enum is not supported in earlier versions. Graphics state stack types used with [love.graphics.push](love.graphics.push "love.graphics.push"). Constants --------- transform The transformation stack ([love.graphics.translate](love.graphics.translate "love.graphics.translate"), [love.graphics.rotate](love.graphics.rotate "love.graphics.rotate"), etc.) all All [love.graphics](love.graphics "love.graphics") state, including transform state. Notes ----- Aside from the graphics transform state, the `all` Stack Type constant affects the following: * [background color](love.graphics.setbackgroundcolor "love.graphics.setBackgroundColor") * [blend mode](love.graphics.setblendmode "love.graphics.setBlendMode") * [active canvas](love.graphics.setcanvas "love.graphics.setCanvas") * [current color](love.graphics.setcolor "love.graphics.setColor") * [color mask](love.graphics.setcolormask "love.graphics.setColorMask") * [default filter mode](love.graphics.setdefaultfilter "love.graphics.setDefaultFilter") * [active font](love.graphics.setfont "love.graphics.setFont") * [scissor rectangle](love.graphics.setscissor "love.graphics.setScissor") * [active shader](love.graphics.setshader "love.graphics.setShader") * [wireframe mode](love.graphics.setwireframe "love.graphics.setWireframe") * [stencil test mode](love.graphics.setstenciltest "love.graphics.setStencilTest") * [line join mode](love.graphics.setlinejoin "love.graphics.setLineJoin") * [line style](love.graphics.setlinestyle "love.graphics.setLineStyle") * [line width](love.graphics.setlinewidth "love.graphics.setLineWidth") * [point size](love.graphics.setpointsize "love.graphics.setPointSize") * [point style](love.graphics.setpointstyle "love.graphics.setPointStyle") See Also -------- * [love.graphics](love.graphics "love.graphics") * [love.graphics.push](love.graphics.push "love.graphics.push") * [love.graphics.pop](love.graphics.pop "love.graphics.pop") love Mesh:getVertices Mesh:getVertices ================ **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0") and removed in LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** Use [Mesh:getVertex](mesh-getvertex "Mesh:getVertex") in a loop instead. Gets all the vertices in the Mesh. This method can be slow if the Mesh has a large number of vertices. Keep the original table used to create the Mesh around and update it when necessary instead of using this method frequently, if possible. Function -------- ### Synopsis ``` vertices = Mesh:getVertices( ) ``` ### Arguments None. ### Returns `[table](table "table") vertices` The table filled with vertex information tables for each vertex as follows: `[number](number "number") [1]` The position of the vertex on the x-axis. `[number](number "number") [2]` The position of the vertex on the y-axis. `[number](number "number") [3]` The horizontal component of the texture coordinate. Texture coordinates are normally in the range of [0, 1], but can be greater or less (see [WrapMode](wrapmode "WrapMode").) `[number](number "number") [4]` The vertical component of the texture coordinate. Texture coordinates are normally in the range of [0, 1], but can be greater or less (see [WrapMode](wrapmode "WrapMode").) `[number](number "number") [5] (255)` The red color component. `[number](number "number") [6] (255)` The green color component. `[number](number "number") [7] (255)` The blue color component. `[number](number "number") [8] (255)` The alpha color component. See Also -------- * [Mesh](mesh "Mesh") * [Mesh:setVertices](mesh-setvertices "Mesh:setVertices") * [Mesh:getVertex](mesh-getvertex "Mesh:getVertex") * [Mesh:getVertexCount](mesh-getvertexcount "Mesh:getVertexCount") love Image Image ===== Drawable image type. Constructors ------------ | | | | | | --- | --- | --- | --- | | [love.graphics.newArrayImage](love.graphics.newarrayimage "love.graphics.newArrayImage") | Creates a new [array](texturetype "TextureType") **Image**. | 11.0 | | | [love.graphics.newCubeImage](love.graphics.newcubeimage "love.graphics.newCubeImage") | Creates a new [cubemap](texturetype "TextureType") **Image**. | 11.0 | | | [love.graphics.newImage](love.graphics.newimage "love.graphics.newImage") | Creates a new **Image**. | | | | [love.graphics.newVolumeImage](love.graphics.newvolumeimage "love.graphics.newVolumeImage") | Creates a new [volume](texturetype "TextureType") **Image**. | 11.0 | | Functions --------- These functions have parentheses in odd places. This is because the *Image:* namespace is reserved in Mediawiki. | | | | | | --- | --- | --- | --- | | [(Image):getData]((image)-getdata "(Image):getData") | Gets the original [ImageData](imagedata "ImageData") or [CompressedData](compresseddata "CompressedData") used to create the Image. | 0.9.0 | 11.0 | | [(Image):getFlags]((image)-getflags "(Image):getFlags") | Gets the flags used when the image was created. | 0.10.0 | | | [(Image):isCompressed]((image)-iscompressed "(Image):isCompressed") | Gets whether the Image was created from [CompressedData](compresseddata "CompressedData"). | 0.9.0 | | | [(Image):refresh]((image)-refresh "(Image):refresh") | Reloads the Image's contents from the ImageData or CompressedData used to create the image. | 0.9.0 | 11.0 | | [(Image):replacePixels]((image)-replacepixels "(Image):replacePixels") | Replace the contents of an Image. | 11.0 | | | [Object:release](object-release "Object:release") | Immediately destroys the object's Lua reference. | 11.0 | | | [Object:type](object-type "Object:type") | Gets the type of the object as a string. | | | | [Object:typeOf](object-typeof "Object:typeOf") | Checks whether an object is of a certain type. | | | | [Texture:getDPIScale](texture-getdpiscale "Texture:getDPIScale") | Gets the DPI scale factor of the Texture. | 11.0 | | | [Texture:getDepth](texture-getdepth "Texture:getDepth") | Gets the depth of a [Volume Texture](texturetype "TextureType"). | 11.0 | | | [Texture:getDepthSampleMode](texture-getdepthsamplemode "Texture:getDepthSampleMode") | Gets the comparison mode used when sampling from a [depth texture](pixelformat "PixelFormat") in a shader. | 11.0 | | | [Texture:getDimensions](texture-getdimensions "Texture:getDimensions") | Gets the width and height of the Texture. | 0.9.0 | | | [Texture:getFilter](texture-getfilter "Texture:getFilter") | Gets the [filter mode](filtermode "FilterMode") of the Texture. | | | | [Texture:getFormat](texture-getformat "Texture:getFormat") | Gets the [pixel format](pixelformat "PixelFormat") of the Texture. | 11.0 | | | [Texture:getHeight](texture-getheight "Texture:getHeight") | Gets the height of the Texture. | | | | [Texture:getLayerCount](texture-getlayercount "Texture:getLayerCount") | Gets the number of layers / slices in an [Array Texture](texturetype "TextureType"). | 11.0 | | | [Texture:getMipmapCount](texture-getmipmapcount "Texture:getMipmapCount") | Gets the number of mipmaps contained in the Texture. | 11.0 | | | [Texture:getMipmapFilter](texture-getmipmapfilter "Texture:getMipmapFilter") | Gets the mipmap filter mode for a Texture. | 0.9.0 | | | [Texture:getPixelDimensions](texture-getpixeldimensions "Texture:getPixelDimensions") | Gets the width and height in pixels of the Texture. | 11.0 | | | [Texture:getPixelHeight](texture-getpixelheight "Texture:getPixelHeight") | Gets the height in pixels of the Texture. | 11.0 | | | [Texture:getPixelWidth](texture-getpixelwidth "Texture:getPixelWidth") | Gets the width in pixels of the Texture. | 11.0 | | | [Texture:getTextureType](texture-gettexturetype "Texture:getTextureType") | Gets the [type](texturetype "TextureType") of the Texture. | 11.0 | | | [Texture:getWidth](texture-getwidth "Texture:getWidth") | Gets the width of the Texture. | | | | [Texture:getWrap](texture-getwrap "Texture:getWrap") | Gets the wrapping properties of a Texture. | | | | [Texture:isReadable](texture-isreadable "Texture:isReadable") | Gets whether the Texture can be drawn sent to a Shader. | 11.0 | | | [Texture:setDepthSampleMode](texture-setdepthsamplemode "Texture:setDepthSampleMode") | Sets the comparison mode used when sampling from a [depth texture](pixelformat "PixelFormat") in a shader. | 11.0 | | | [Texture:setFilter](texture-setfilter "Texture:setFilter") | Sets the [filter mode](filtermode "FilterMode") of the Texture. | | | | [Texture:setMipmapFilter](texture-setmipmapfilter "Texture:setMipmapFilter") | Sets the mipmap filter mode for a Texture. | 0.9.0 | | | [Texture:setWrap](texture-setwrap "Texture:setWrap") | Sets the wrapping properties of a Texture. | | | Supertypes ---------- * [Texture](texture "Texture") * [Drawable](drawable "Drawable") * [Object](object "Object") See Also -------- * [ImageData](imagedata "ImageData") * [love.graphics](love.graphics "love.graphics") * [Image Formats](image_formats "Image Formats")
programming_docs
love ParticleSystem:getEmissionRate ParticleSystem:getEmissionRate ============================== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Gets the amount of particles emitted per second. Function -------- ### Synopsis ``` rate = ParticleSystem:getEmissionRate( ) ``` ### Arguments Nothing. ### Returns `[number](number "number") rate` The amount of particles per second. See Also -------- * [ParticleSystem](particlesystem "ParticleSystem") * [ParticleSystem:setEmissionRate](particlesystem-setemissionrate "ParticleSystem:setEmissionRate") love (File):write (File):write ============ Write data to a file. Function -------- ### Synopsis ``` success, err = File:write( data, size ) ``` ### Arguments `[string](string "string") data` The string data to write. `[number](number "number") size (all)` How many bytes to write. ### Returns `[boolean](boolean "boolean") success` Whether the operation was successful. `[string](string "string") err` The error string if an error occurred. Function -------- ### Synopsis ``` success, err = File:write( data, size ) ``` ### Arguments `[Data](data "Data") data` The Data object to write. `[number](number "number") size (all)` How many bytes to write. ### Returns `[boolean](boolean "boolean") success` Whether the operation was successful. `[string](string "string") errorstr` The error string if an error occurred. Notes ----- **Writing to multiple lines**: In Windows, some text editors (e.g. Notepad before Windows 10 1809) only treat CRLF ("\r\n") as a new line. ``` --example f = love.filesystem.newFile("note.txt") f:open("w") for i = 1, 10 do f:write("This is line "..i.."!\r\n") end f:close() ``` See Also -------- * [File](file "File") * [File:flush]((file)-flush "(File):flush") * [File:setBuffer]((file)-setbuffer "(File):setBuffer") love MipmapMode MipmapMode ========== **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This enum is not supported in earlier versions. Controls whether a [Canvas](canvas "Canvas") has mipmaps, and its behaviour when it does. Constants --------- none The Canvas has no mipmaps. manual The Canvas has mipmaps. [love.graphics.setCanvas](love.graphics.setcanvas "love.graphics.setCanvas") can be used to render to a specific mipmap level, or [Canvas:generateMipmaps](canvas-generatemipmaps "Canvas:generateMipmaps") can (re-)compute all mipmap levels based on the base level. auto The Canvas has mipmaps, and all mipmap levels will automatically be recomputed when switching away from the Canvas with [love.graphics.setCanvas](love.graphics.setcanvas "love.graphics.setCanvas"). See Also -------- * [love.graphics](love.graphics "love.graphics") * [love.graphics.newCanvas](love.graphics.newcanvas "love.graphics.newCanvas") * [Canvas](canvas "Canvas") love Texture:getLayerCount Texture:getLayerCount ===================== **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This function is not supported in earlier versions. Gets the number of layers / slices in an [Array Texture](texturetype "TextureType"). Returns 1 for 2D, Cubemap, and Volume textures. Function -------- ### Synopsis ``` layers = Texture:getLayerCount( ) ``` ### Arguments None. ### Returns `[number](number "number") layers` The number of layers in the Array Texture. See Also -------- * [Texture](texture "Texture") * [love.graphics.newArrayImage](love.graphics.newarrayimage "love.graphics.newArrayImage") * [love.graphics.newCanvas](love.graphics.newcanvas "love.graphics.newCanvas") love PolygonShape PolygonShape ============ A PolygonShape is a convex polygon with up to 8 vertices. Constructors ------------ | | | | | | --- | --- | --- | --- | | [love.physics.newPolygonShape](love.physics.newpolygonshape "love.physics.newPolygonShape") | Creates a new **PolygonShape**. | | | | [love.physics.newRectangleShape](love.physics.newrectangleshape "love.physics.newRectangleShape") | Shorthand for creating rectangular **PolygonShapes**. | | | Functions --------- | | | | | | --- | --- | --- | --- | | [Object:release](object-release "Object:release") | Immediately destroys the object's Lua reference. | 11.0 | | | [Object:type](object-type "Object:type") | Gets the type of the object as a string. | | | | [Object:typeOf](object-typeof "Object:typeOf") | Checks whether an object is of a certain type. | | | | [PolygonShape:getPoints](polygonshape-getpoints "PolygonShape:getPoints") | Get the local coordinates of the polygon's vertices. | | | | [PolygonShape:validate](polygonshape-validate "PolygonShape:validate") | Validates whether the PolygonShape is convex. | 0.9.0 | | | [Shape:computeAABB](shape-computeaabb "Shape:computeAABB") | Returns the points of the bounding box for the transformed shape. | 0.8.0 | | | [Shape:computeMass](shape-computemass "Shape:computeMass") | Computes the mass properties for the shape. | 0.8.0 | | | [Shape:destroy](shape-destroy "Shape:destroy") | Explicitly destroys the Shape. | | 0.8.0 | | [Shape:getBody](shape-getbody "Shape:getBody") | Get the body the shape is attached to. | 0.7.0 | 0.8.0 | | [Shape:getBoundingBox](shape-getboundingbox "Shape:getBoundingBox") | Gets the bounding box of the shape. | | 0.8.0 | | [Shape:getCategory](shape-getcategory "Shape:getCategory") | Gets the categories this shape is a member of. | | 0.8.0 | | [Shape:getCategoryBits](shape-getcategorybits "Shape:getCategoryBits") | Gets the categories as a 16-bit integer. | | 0.8.0 | | [Shape:getChildCount](shape-getchildcount "Shape:getChildCount") | Returns the number of children the shape has. | 0.8.0 | | | [Shape:getData](shape-getdata "Shape:getData") | Get the data set with setData. | | 0.8.0 | | [Shape:getDensity](shape-getdensity "Shape:getDensity") | Gets the density of the Shape. | | 0.8.0 | | [Shape:getFilterData](shape-getfilterdata "Shape:getFilterData") | Gets the filter data of the Shape. | | 0.8.0 | | [Shape:getFriction](shape-getfriction "Shape:getFriction") | Gets the friction of this shape. | | 0.8.0 | | [Shape:getMask](shape-getmask "Shape:getMask") | Gets which categories this shape should **NOT** collide with. | | 0.8.0 | | [Shape:getRadius](shape-getradius "Shape:getRadius") | Gets the radius of the shape. | | | | [Shape:getRestitution](shape-getrestitution "Shape:getRestitution") | Gets the restitution of this shape. | | 0.8.0 | | [Shape:getType](shape-gettype "Shape:getType") | Gets a string representing the Shape. | | | | [Shape:isSensor](shape-issensor "Shape:isSensor") | Checks whether a Shape is a sensor or not. | | 0.8.0 | | [Shape:rayCast](shape-raycast "Shape:rayCast") | Casts a ray against the shape. | 0.8.0 | | | [Shape:setCategory](shape-setcategory "Shape:setCategory") | Sets the categories this shape is a member of. | | 0.8.0 | | [Shape:setData](shape-setdata "Shape:setData") | Set data to be passed to the collision callback. | | 0.8.0 | | [Shape:setDensity](shape-setdensity "Shape:setDensity") | Sets the density of a Shape. | | 0.8.0 | | [Shape:setFilterData](shape-setfilterdata "Shape:setFilterData") | Sets the filter data for a Shape. | | 0.8.0 | | [Shape:setFriction](shape-setfriction "Shape:setFriction") | Sets the friction of the shape. | | 0.8.0 | | [Shape:setMask](shape-setmask "Shape:setMask") | Sets which categories this shape should **NOT** collide with. | | 0.8.0 | | [Shape:setRestitution](shape-setrestitution "Shape:setRestitution") | Sets the restitution of the shape. | | 0.8.0 | | [Shape:setSensor](shape-setsensor "Shape:setSensor") | Sets whether this shape should act as a sensor. | | 0.8.0 | | [Shape:testPoint](shape-testpoint "Shape:testPoint") | Checks whether a point lies inside the shape. | | | | [Shape:testSegment](shape-testsegment "Shape:testSegment") | Checks whether a line segment intersects a shape. | | 0.8.0 | Supertypes ---------- * [Shape](shape "Shape") * [Object](object "Object") See Also -------- * [love.physics](love.physics "love.physics") love Transform:inverse Transform:inverse ================= **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This function is not supported in earlier versions. Creates a new Transform containing the inverse of this Transform. Function -------- ### Synopsis ``` inverse = Transform:inverse( ) ``` ### Arguments None. ### Returns `[Transform](transform "Transform") inverse` A new Transform object representing the inverse of this Transform's matrix. See Also -------- * [Transform](transform "Transform") love love.graphics.getColor love.graphics.getColor ====================== Gets the current color. In versions prior to [11.0](https://love2d.org/wiki/11.0 "11.0"), color component values were within the range of 0 to 255 instead of 0 to 1. Function -------- ### Synopsis ``` r, g, b, a = love.graphics.getColor( ) ``` ### Arguments None. ### Returns `[number](number "number") r` The red component (0-1). `[number](number "number") g` The green component (0-1). `[number](number "number") b` The blue component (0-1). `[number](number "number") a` The alpha component (0-1). See Also -------- * [love.graphics](love.graphics "love.graphics") love Joystick:getHatCount Joystick:getHatCount ==================== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** It has been moved from [love.joystick.getNumHats](love.joystick.getnumhats "love.joystick.getNumHats"). Gets the number of hats on the joystick. Function -------- ### Synopsis ``` hats = Joystick:getHatCount( ) ``` ### Arguments None. ### Returns `[number](number "number") hats` How many hats the joystick has. See Also -------- * [Joystick](joystick "Joystick") * [Joystick:getHat](joystick-gethat "Joystick:getHat") love Mesh:getImage Mesh:getImage ============= **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. **Removed in LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** Use [Mesh:getTexture](mesh-gettexture "Mesh:getTexture") instead. Gets the [Image](image "Image") used when drawing the Mesh. Function -------- ### Synopsis ``` image = Mesh:getImage( ) ``` ### Arguments None. ### Returns `[Image](image "Image") image (nil)` The Image used to texture the Mesh when drawing. May be nil if no Image is being used with the Mesh. See Also -------- * [Mesh](mesh "Mesh") * [Mesh:setImage](mesh-setimage "Mesh:setImage") love Font:getAscent Font:getAscent ============== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Gets the ascent of the Font. The ascent spans the distance between the baseline and the top of the glyph that reaches farthest from the baseline. Function -------- ### Synopsis ``` ascent = Font:getAscent( ) ``` ### Arguments None. ### Returns `[number](number "number") ascent` The ascent of the Font in pixels. See Also -------- * [Font](font "Font") * [Font:getDescent](font-getdescent "Font:getDescent") * [Font:getBaseline](font-getbaseline "Font:getBaseline") love Mesh:hasVertexColors Mesh:hasVertexColors ==================== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0") and removed in LÖVE [0.10.0](https://love2d.org/wiki/0.10.0 "0.10.0")** It has been replaced by [Mesh:isAttributeEnabled](mesh-isattributeenabled "Mesh:isAttributeEnabled")("VertexColor"). Gets whether per-vertex colors are used instead of the constant color when drawing the Mesh (constant color being [love.graphics.setColor](love.graphics.setcolor "love.graphics.setColor").) Per-vertex colors are enabled by default for a Mesh if at least one vertex color was not the default (255, 255, 255, 255) when the Mesh was [created](love.graphics.newmesh "love.graphics.newMesh"). Function -------- ### Synopsis ``` vertexcolors = Mesh:hasVertexColors( ) ``` ### Arguments None. ### Returns `[boolean](boolean "boolean") vertexcolors` True if per-vertex coloring is used, otherwise [love.graphics.setColor](love.graphics.setcolor "love.graphics.setColor") is used when drawing the Mesh. See Also -------- * [Mesh](mesh "Mesh") * [Mesh:setVertexColors](mesh-setvertexcolors "Mesh:setVertexColors") * [love.graphics.newMesh](love.graphics.newmesh "love.graphics.newMesh") love love.mouse.setY love.mouse.setY =============== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Sets the current Y position of the mouse. Non-integer values are floored. Function -------- ### Synopsis ``` love.mouse.setY( y ) ``` ### Arguments `[number](number "number") y` The new position of the mouse along the y-axis. ### Returns Nothing. See Also -------- * [love.mouse](love.mouse "love.mouse") * [love.mouse.setPosition](love.mouse.setposition "love.mouse.setPosition") * [love.mouse.setX](love.mouse.setx "love.mouse.setX") * [love.mouse.getY](love.mouse.gety "love.mouse.getY") love love.graphics.getFrontFaceWinding love.graphics.getFrontFaceWinding ================================= **Available since LÖVE [11.0](https://love2d.org/wiki/11.0 "11.0")** This function is not supported in earlier versions. Gets whether triangles with clockwise- or counterclockwise-ordered vertices are considered front-facing. This is designed for use in combination with [Mesh face culling](love.graphics.setmeshcullmode "love.graphics.setMeshCullMode"). Other love.graphics shapes, lines, and sprites are not guaranteed to have a specific winding order to their internal vertices. Function -------- ### Synopsis ``` winding = love.graphics.getFrontFaceWinding( ) ``` ### Arguments None. ### Returns `[VertexWinding](vertexwinding "VertexWinding") winding` The winding mode being used. The default winding is counterclockwise ("ccw"). See Also -------- * [love.graphics](love.graphics "love.graphics") * [love.graphics.setFrontFaceWinding](love.graphics.setfrontfacewinding "love.graphics.setFrontFaceWinding") * [love.graphics.setMeshCullMode](love.graphics.setmeshcullmode "love.graphics.setMeshCullMode") * [Mesh](mesh "Mesh") love PrismaticJoint:setLimits PrismaticJoint:setLimits ======================== Sets the limits. Function -------- ### Synopsis ``` PrismaticJoint:setLimits( lower, upper ) ``` ### Arguments `[number](number "number") lower` The lower limit, usually in meters. `[number](number "number") upper` The upper limit, usually in meters. ### Returns Nothing. See Also -------- * [PrismaticJoint](prismaticjoint "PrismaticJoint") love love.window.getFullscreenModes love.window.getFullscreenModes ============================== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** Moved from [love.graphics.getModes](love.graphics.getmodes "love.graphics.getModes"). Gets a list of supported fullscreen modes. Function -------- ### Synopsis ``` modes = love.window.getFullscreenModes( display ) ``` ### Arguments `[number](number "number") display (1)` The index of the display, if multiple monitors are available. ### Returns `[table](table "table") modes` A table of width/height pairs. (Note that this may not be in order.) Examples -------- ### Format of the returned table ``` modes = love.window.getFullscreenModes()   -- modes = { -- { width = 320, height = 240 }, -- { width = 640, height = 480 }, -- { width = 800, height = 600 }, -- { width = 1024, height = 768 }, -- ... -- } ``` ### Sort table to ensure it is in order ``` modes = love.window.getFullscreenModes() table.sort(modes, function(a, b) return a.width*a.height < b.width*b.height end) -- sort from smallest to largest ``` See Also -------- * [love.window](love.window "love.window") * [love.window.setMode](love.window.setmode "love.window.setMode") love Rasterizer:hasGlyphs Rasterizer:hasGlyphs ==================== **Available since LÖVE [0.7.0](https://love2d.org/wiki/0.7.0 "0.7.0")** This function is not supported in earlier versions. Checks if font contains specified glyphs. Function -------- ### Synopsis ``` hasGlyphs = Rasterizer:hasGlyphs( glyph1, glyph2, ... ) ``` ### Arguments `[string or number](https://love2d.org/w/index.php?title=string_or_number&action=edit&redlink=1 "string or number (page does not exist)") glyph1` Glyph `[string or number](https://love2d.org/w/index.php?title=string_or_number&action=edit&redlink=1 "string or number (page does not exist)") glyph2` Glyph `[string or number](https://love2d.org/w/index.php?title=string_or_number&action=edit&redlink=1 "string or number (page does not exist)") ...` Additional glyphs ### Returns `[boolean](boolean "boolean") hasGlyphs` Whatever font contains specified glyphs. See Also -------- * [Rasterizer](rasterizer "Rasterizer") love ParticleSystem:setSpinVariation ParticleSystem:setSpinVariation =============================== Sets the amount of spin variation (0 meaning no variation and 1 meaning full variation between start and end). Function -------- ### Synopsis ``` ParticleSystem:setSpinVariation( variation ) ``` ### Arguments `[number](number "number") variation` The amount of variation (0 meaning no variation and 1 meaning full variation between start and end). ### Returns Nothing. See Also -------- * [ParticleSystem](particlesystem "ParticleSystem") love Joystick:getGamepadMapping Joystick:getGamepadMapping ========================== **Available since LÖVE [0.9.0](https://love2d.org/wiki/0.9.0 "0.9.0")** This function is not supported in earlier versions. Gets the button, axis or hat that a virtual gamepad input is bound to. Function -------- ### Synopsis ``` inputtype, inputindex, hatdirection = Joystick:getGamepadMapping( axis ) ``` ### Arguments `[GamepadAxis](gamepadaxis "GamepadAxis") axis` The virtual gamepad axis to get the binding for. ### Returns `[JoystickInputType](joystickinputtype "JoystickInputType") inputtype` The type of input the virtual gamepad axis is bound to. `[number](number "number") inputindex` The index of the Joystick's button, axis or hat that the virtual gamepad axis is bound to. `[JoystickHat](joystickhat "JoystickHat") hatdirection (nil)` The direction of the hat, if the virtual gamepad axis is bound to a hat. nil otherwise. ### Notes Returns nil if the Joystick isn't recognized as a gamepad or the virtual gamepad axis is not bound to a Joystick input. Function -------- ### Synopsis ``` inputtype, inputindex, hatdirection = Joystick:getGamepadMapping( button ) ``` ### Arguments `[GamepadButton](gamepadbutton "GamepadButton") button` The virtual gamepad button to get the binding for. ### Returns `[JoystickInputType](joystickinputtype "JoystickInputType") inputtype` The type of input the virtual gamepad button is bound to. `[number](number "number") inputindex` The index of the Joystick's button, axis or hat that the virtual gamepad button is bound to. `[JoystickHat](joystickhat "JoystickHat") hatdirection (nil)` The direction of the hat, if the virtual gamepad button is bound to a hat. nil otherwise. ### Notes Returns nil if the Joystick isn't recognized as a gamepad or the virtual gamepad button is not bound to a Joystick input. Notes ----- The physical locations for the virtual gamepad axes and buttons correspond as closely as possible to the layout of a standard Xbox 360 controller. See Also -------- * [Joystick](joystick "Joystick") * [Joystick:isGamepad](joystick-isgamepad "Joystick:isGamepad") * [Joystick:isGamepadDown](joystick-isgamepaddown "Joystick:isGamepadDown") * [Joystick:getGamepadAxis](joystick-getgamepadaxis "Joystick:getGamepadAxis") * [love.joystick.setGamepadMapping](love.joystick.setgamepadmapping "love.joystick.setGamepadMapping")
programming_docs