EnsureKeysTrait
Provides functionality to guarantee the existence of specific keys or properties within document structures or collections.
This trait processes the configuration provided in ModelParam::ENSURE
to automatically populate missing keys with default values.
Usage example:
class MyModel
{
use EnsureKeysTrait;
public function fetchAndProcess($init)
{
$data = ['id' => 1];
// Ensures 'status' exists, defaults to 'draft'
$this->ensureDocumentKeys($data, $init);
return $data;
}
}
// Usage
$model->fetchAndProcess
([
ModelParam::ENSURE =>
[
ModelParam::KEYS => ['status'],
ModelParam::DEFAULT => 'draft'
]
]);
Tags
Table of Contents
Properties
- $ensure : array<string|int, mixed>|null
- The default configuration used to ensure attributes on the model's documents.
Methods
- initializeEnsure() : static
- Initialize the `ensure` definition of the model.
- ensureDocumentKeys() : void
- Ensures that specific attributes (keys or properties) exist on a document or a collection.
Properties
$ensure
The default configuration used to ensure attributes on the model's documents.
public
array<string|int, mixed>|null
$ensure
= null
Either a flat list of keys, or an associative array with the ModelParam::KEYS,
ModelParam::DEFAULT and ModelParam::ENFORCE entries. null means "no default".
Methods
initializeEnsure()
Initialize the `ensure` definition of the model.
public
initializeEnsure([array<string, mixed> $init = [] ]) : static
Parameters
- $init : array<string, mixed> = []
-
Optional initialization array.
Return values
static —Returns $this to allow method chaining.
ensureDocumentKeys()
Ensures that specific attributes (keys or properties) exist on a document or a collection.
protected
ensureDocumentKeys(mixed &$data[, array<string|int, mixed> $init = [] ]) : void
The configuration is resolved from $init[ModelParam::ENSURE], falling back to the instance
$ensure property. It can be a flat list of keys or a structured array exposing
ModelParam::KEYS, ModelParam::DEFAULT and ModelParam::ENFORCE. The method
auto-detects whether $data is an indexed collection (each element is processed) or a single
document, and mutates it in place. It is a no-op when $data is empty or no configuration applies.
Parameters
- $data : mixed
-
Reference to the document or list of documents. Modified in place.
- $init : array<string|int, mixed> = []
-
Runtime options; a
ModelParam::ENSUREentry overrides the$ensureproperty.