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 array definition to ensure attributes in the documents of the model.
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 of documents.
Properties
$ensure
The default array definition to ensure attributes in the documents of the model.
public
array<string|int, mixed>|null
$ensure
= null
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 of documents.
protected
ensureDocumentKeys(mixed &$data[, array<string|int, mixed> $init = [] ]) : void
It parses the configuration from $init[ModelParam::ENSURE] and applies it to $data. It automatically detects if $data is a collection (indexed array) or a single item.
Parameters
- $data : mixed
-
Reference to the document(s). Modified in place.
- $init : array<string|int, mixed> = []
-
The initialization options containing ModelParam::ENSURE.