AlterTrait uses trait:short, trait:short, trait:short, trait:short, trait:short, trait:short, trait:short, trait:short, trait:short, trait:short, trait:short, trait:short, trait:short, trait:short, trait:short, trait:short
Provides a set of methods to alter properties of arrays or objects based on a configurable set of rules (called "alters").
Supports chaining multiple alterations on a single property:
Example usage:
class MyProcessor
{
use AlterDocumentTrait;
public function __construct()
{
$this->alters =
[
'price' => Alter::FLOAT,
'tags' => [ Alter::ARRAY , Alter::CLEAN ],
'meta' => [ Alter::JSON_PARSE ],
'link' => [ Alter::URL , '/product/' ],
'score' => [ Alter::CALL , fn( $value ) => $value * 10 ],
'total' => [ ALTER::MAP , fn( &$document ) => $document['price'] + ( $document['price'] * ( $document['vat'] ?? 0 ) ) ] ,
'geo' => [ Alter::NORMALIZE , [ Alter::HYDRATE , GeoCoordinates::class ] ],
'name' => [ Alter::TRIM , Alter::UPPERCASE , Alter::NORMALIZE ],
];
}
}
Supported alteration types (see enum Alter):
- Alter::ARRAY → Split string into array and apply sub-alters.
- Alter::CLEAN → Remove empty/null elements from an array.
- Alter::CALL → Call a function on the value.
- Alter::FLOAT → Convert to float (or array of floats).
- Alter::GET → Fetch a document using a model.
- Alter::HYDRATE → Hydrate a value with a specific class.
- Alter::INT → Convert to integer (or array of integers).
- Alter::JSON_PARSE → Parse JSON string.
- Alter::JSON_STRINGIFY → Convert value to JSON string.
- Alter::MAP → Map a property of a document (or all the document structure) - Can transform or update the document.
- Alter::NORMALIZE → Normalize a document property using configurable flags.
- Alter::NOT → Invert boolean values.
- Alter::URL → Generate a URL from a property.
- Alter::VALUE → Override with a fixed value.
Tags
Table of Contents
Properties
- $alterKey : string
- The default alter key reference.
Methods
- alterArrayCleanProperty() : array<string|int, mixed>|float
- Clean an array of null or empty string elements.
- alterArrayElements() : array<string|int, mixed>
- Alters all elements in an array.
- alterArrayProperty() : array<string|int, mixed>
- Transform a string expression separated by semi-colon ';' to creates an array.
- alterCallableProperty() : mixed
- Alters a value by invoking a user-defined callable.
- alterFloatProperty() : float|array<string|int, mixed>
- Casts a value (or every element of an array) to float.
- alterGetDocument() : mixed
- Gets a document with a Documents model.
- alterHydrateProperty() : mixed
- Hydrate a property value into a specific class instance using reflection.
- alterIntProperty() : int|array<string|int, mixed>
- Casts a value (or all elements of an array) to integer.
- alterJsonParseProperty() : string|false|null
- Decodes a JSON string
- alterJsonStringifyProperty() : string|false|null
- Returns the JSON representation of a value
- alterListifyProperty() : string|null
- Transforms a string or array into a normalized list string.
- alterMapProperty() : mixed
- Provides a mechanism to alter a property of a document using a custom "map" callback.
- alterNormalizeProperty() : mixed
- Normalize a document property using configurable flags.
- alterNotProperty() : bool|array<string|int, mixed>
- Invert a boolean value or an array of booleans.
- alterUrlProperty() : string
- Generates a complete URL by combining path segments and document properties.
- alterValue() : mixed
- Replace a value with a new one if different, otherwise keep the original.
- initializeAlterKey() : static
- Initialize the 'alters' property.
- alterProperty() : array<string|int, mixed>|object
- Alters a specific property of the given document using one or more transformation rules.
- applyChainedAlterations() : array<string|int, mixed>|object
- Applies chained alterations to a property.
- applySingleAlteration() : array<string|int, mixed>|object
- Applies a single alteration (original behavior).
- executeAlteration() : mixed
- Executes a specific alteration.
- firstIsAlter() : bool
- Checks if a value is an Alter enum or an array starting with an Alter enum.
- isChainedDefinition() : bool
- Detects if the definition represents chained alterations.
Properties
$alterKey
The default alter key reference.
public
string
$alterKey
= \org\schema\constants\Schema::ID
Tags
Methods
alterArrayCleanProperty()
Clean an array of null or empty string elements.
public
alterArrayCleanProperty(mixed $value[, bool &$modified = false ]) : array<string|int, mixed>|float
Parameters
- $value : mixed
- $modified : bool = false
Return values
array<string|int, mixed>|floatalterArrayElements()
Alters all elements in an array.
public
alterArrayElements(array<string|int, mixed> $array[, array<string|int, mixed> $options = [] ][, Container|null $container = null ]) : array<string|int, mixed>
Parameters
- $array : array<string|int, mixed>
-
The array reference to alter.
- $options : array<string|int, mixed> = []
-
The options representation.
- $container : Container|null = null
-
An optional DI container reference.
Tags
Return values
array<string|int, mixed>alterArrayProperty()
Transform a string expression separated by semi-colon ';' to creates an array.
public
alterArrayProperty(mixed $value[, array<string|int, mixed> $options = [] ][, Container|null $container = null ][, bool &$modified = false ]) : array<string|int, mixed>
You can chain multiple alter definition to transform the content of the array, ex:
Property::CATEGORY => [ Alter::ARRAY , Alter::CLEAN , Alter::JSON_PARSE ] ,
The previous example transform the 'category' string in an Array and after remove all null or empty array elements and JSON parse all elements.
Parameters
- $value : mixed
- $options : array<string|int, mixed> = []
- $container : Container|null = null
-
An optional DI container reference.
- $modified : bool = false
Tags
Return values
array<string|int, mixed>alterCallableProperty()
Alters a value by invoking a user-defined callable.
public
alterCallableProperty(mixed $value[, array<string|int, mixed> $definition = [] ][, bool &$modified = false ]) : mixed
This method allows transforming a property value using any callable (closure, function name, static method, service callback, etc.). It is typically used when an alteration rule is defined as:
[
Alter::CALLABLE,
$callable,
...$additionalParams
]
The first element of $definition must be a callable or a string
resolvable to a callable via resolveCallable().
The callable will be invoked with the following signature:
function (mixed $value, mixed ...$additionalParams): mixed
Any additional elements from $definition will be forwarded as extra arguments.
If the callable returns a different value, $modified will be set to true.
Parameters
- $value : mixed
-
The current value of the property to be altered.
- $definition : array<string|int, mixed> = []
-
The alteration definition:
- index
0: the callable (closure, function name, or resolvable string) - index
1+: optional parameters passed to the callable
- index
- $modified : bool = false
-
Output flag set to
trueif the callable altered the value.
Tags
Return values
mixed —The altered value returned by the callable, or the original value if no callable was provided or callable resolution failed.
alterFloatProperty()
Casts a value (or every element of an array) to float.
public
alterFloatProperty(mixed $value[, bool &$modified = false ]) : float|array<string|int, mixed>
This method ensures that the resulting value is always of type float
(or an array of floats). It also sets $modified to true when any
transformation occurs.
Rules:
- If
$valueis already a float → returned as is, not marked modified. - If
$valueis an array → each element converted viafloatval(). - Otherwise →
$valueis cast to float.
Parameters
- $value : mixed
-
The value to convert. Can be scalar or array.
- $modified : bool = false
-
Output flag set to
trueif a cast was performed.
Tags
Return values
float|array<string|int, mixed> —The float-cast value or an array of float-cast values.
alterGetDocument()
Gets a document with a Documents model.
public
alterGetDocument(mixed $value[, array<string|int, mixed> $definition = [] ][, Container|null $container = null ][, bool &$modified = false ]) : mixed
Parameters
- $value : mixed
- $definition : array<string|int, mixed> = []
- $container : Container|null = null
-
DI container for resolving base URL from service definitions.
- $modified : bool = false
Tags
alterHydrateProperty()
Hydrate a property value into a specific class instance using reflection.
public
alterHydrateProperty(mixed $value[, array<string|int, mixed> $definition = [] ][, bool &$modified = false ]) : mixed
This method transforms a raw value (typically an array) into an object of the specified class. If the input value is an array, it can be normalized and then hydrated using either the Thing constructor or the ReflectionTrait::hydrate() method depending on the class type.
Behavior
- If
$valueis not an array, it is returned as-is. - If
$valueis an empty array, the method returnsnull(by default). - If
$schemarefers to a class extending Thing, the object is created directly via its constructor. - Otherwise, hydration is performed via ReflectionTrait::hydrate().
- The
$modifiedflag is set totrueif the resulting value differs from the input.
Usage Example
Property::GEO => [ Alter::HYDRATE, GeoCoordinates::class ],
Custom Normalization
You can specify a custom normalization flag as a third element in the definition:
[ Alter::HYDRATE, GeoCoordinates::class, true , CleanFlag::ALL ]
By default, the value is normalized using:
normalize() with flags CleanFlag::DEFAULT | CleanFlag::RETURN_NULL.
Parameters
- $value : mixed
-
The original value to hydrate. Can be a scalar, array, or object.
- $definition : array<string|int, mixed> = []
-
The alter definition, expected as:
[ 0 => string|null $schema, // Fully qualified class name to hydrate into 1 => bool $normalize // Whether to normalize the value before hydration (default true) 2 => int $flags // Optional CleanFlag bitmask ] - $modified : bool = false
-
Reference flag set to
trueif the resulting value differs from the original.
Tags
Return values
mixed —The hydrated value, possibly an instance of $schema, or null if empty.
alterIntProperty()
Casts a value (or all elements of an array) to integer.
public
alterIntProperty(mixed $value[, bool &$modified = false ]) : int|array<string|int, mixed>
This alteration is typically used within property transformation
pipelines to ensure that the resulting value is strictly of type int.
Behavior:
- If
$valueis an array, each element is individually cast using intval(). - If
$valueis already an integer, it is returned unchanged and$modifiedremainsfalse. - If
$valueis not an integer, it is cast to integer and$modifiedbecomestrue.
The $modified flag will be set to true whenever at least one casting
occurs (i.e., when the original value or any array element was not already
an integer).
Example:
use oihana\traits\alters\AlterIntPropertyTrait;
class Product {
use AlterIntPropertyTrait;
}
$product = new Product();
$modified = false;
// Casting a single value
$id = $product->alterIntProperty("42", $modified);
// $id === 42
// $modified === true
// Casting an array of values
$values = $product->alterIntProperty(["10", "20", "30"], $modified);
// $values === [10, 20, 30]
// $modified === true
// Already an int
$count = $product->alterIntProperty(5, $modified);
// $count === 5
// $modified === false
Parameters
- $value : mixed
-
The input value, scalar or array.
- $modified : bool = false
-
Reference flag indicating if any cast occurred.
Return values
int|array<string|int, mixed> —The cast integer or array of integers.
alterJsonParseProperty()
Decodes a JSON string
public
alterJsonParseProperty(mixed $value[, array<string|int, mixed> $definition = [] ][, bool &$modified = false ]) : string|false|null
Parameters
- $value : mixed
- $definition : array<string|int, mixed> = []
- $modified : bool = false
Return values
string|false|nullalterJsonStringifyProperty()
Returns the JSON representation of a value
public
alterJsonStringifyProperty(mixed $value[, array<string|int, mixed> $definition = [] ][, bool &$modified = false ]) : string|false|null
Parameters
- $value : mixed
- $definition : array<string|int, mixed> = []
- $modified : bool = false
Return values
string|false|nullalterListifyProperty()
Transforms a string or array into a normalized list string.
public
alterListifyProperty(mixed $value[, array<string|int, mixed> $definition = [] ][, bool &$modified = false ]) : string|null
The transformation can be customized via the $definition array:
$definition[0](string): Input separator for strings (default:;)$definition[1](string): Output separator for joining (default:PHP_EOL)$definition[2](string|null): Default value if result is empty (default:null)
Parameters
- $value : mixed
-
The value to transform (string, array, or null)
- $definition : array<string|int, mixed> = []
-
Optional parameters: [separator, replace, default]
- $modified : bool = false
-
Reference flag indicating if the value was modified
Tags
Return values
string|null —The normalized list string, or default if empty
alterMapProperty()
Provides a mechanism to alter a property of a document using a custom "map" callback.
public
alterMapProperty(array<string|int, mixed>|object &$document, Container|null $container, string $key, mixed $value[, array<string|int, mixed> $params = [] ][, bool &$modified = false ]) : mixed
This allows applying arbitrary transformations to a specific property of an array or object, with access to the full document and optionally a DI container.
The first element of $params must be a callable (or string resolvable to a callable via resolveCallable),
which will be invoked with the following signature:
function map(array|object $document, ?Container $container, string $key, mixed $value, array $params = []): mixed
The callable should return the new value for the property. Any modification will set $modified to true.
Parameters
- $document : array<string|int, mixed>|object
-
The document (array or object) containing the property.
- $container : Container|null
-
Optional DI container, for resolving services if needed.
- $key : string
-
The key or property name being altered.
- $value : mixed
-
The current value of the property.
- $params : array<string|int, mixed> = []
-
Additional parameters, where the first element must be the callable.
- $modified : bool = false
-
Output flag indicating whether the value was modified by the callable.
Tags
Return values
mixed —The altered value for the property.
alterNormalizeProperty()
Normalize a document property using configurable flags.
public
alterNormalizeProperty(mixed $value[, array<string|int, mixed> $definition = [] ][, bool &$modified = false ]) : mixed
The normalization can be customized via the $definition array:
- If empty or no flags provided, uses CleanFlag::DEFAULT | CleanFlag::RETURN_NULL
- If a flags value is provided at index 0, uses that instead
Parameters
- $value : mixed
-
The value to normalize
- $definition : array<string|int, mixed> = []
-
Optional flags array: [CleanFlag value, ...other params]
- $modified : bool = false
-
Reference flag indicating if the value was modified
Tags
Return values
mixed —The normalized value, or null if cleaned away
alterNotProperty()
Invert a boolean value or an array of booleans.
public
alterNotProperty(mixed $value[, bool &$modified = false ]) : bool|array<string|int, mixed>
Parameters
- $value : mixed
-
The value to alter. Can be a boolean, array of booleans, or any other value.
- $modified : bool = false
-
Reference flag set to true if the value is altered.
Tags
Return values
bool|array<string|int, mixed> —Returns the inverted boolean or array of inverted booleans.
alterUrlProperty()
Generates a complete URL by combining path segments and document properties.
public
alterUrlProperty(array<string|int, mixed>|object $document[, array<string|int, mixed> $options = [] ][, Container|null $container = null ][, bool &$modified = false ][, string|null $propertyName = null ][, string $containerKey = 'baseUrl' ]) : string
The method builds a URL in the following order:
- Resolves the base URL from the container (if containerKey is provided and not false)
- Joins the base URL with the provided path segment
- Appends the property value from the document
- Optionally adds a trailing slash
Parameters via $options array:
[0](string) — Path segment to append after base URL (e.g., '/products', '/api/v1/users')[1](string) — Document property name containing the final segment (default: 'id')[2](string|bool) — Container service key for base URL resolution orfalseto skip (default: 'baseUrl')[3](bool) — Add trailing slash to the result (default: false)
Parameters
- $document : array<string|int, mixed>|object
-
The document to read property values from.
- $options : array<string|int, mixed> = []
-
Configuration array: [path, propertyName, containerKey, trailingSlash]
- $container : Container|null = null
-
DI container for resolving base URL from service definitions.
- $modified : bool = false
-
Reference flag set to true if URL alteration occurs.
- $propertyName : string|null = null
-
Default property name to use if not specified in options.
- $containerKey : string = 'baseUrl'
-
Default container key for base URL if not specified in options.
Tags
Return values
string —The generated URL.
alterValue()
Replace a value with a new one if different, otherwise keep the original.
public
alterValue(mixed $value[, array<string|int, mixed> $definition = [] ][, bool &$modified = false ]) : mixed
Parameters
- $value : mixed
-
The original value
- $definition : array<string|int, mixed> = []
-
The definition reference to extract the new value to apply.
- $modified : bool = false
-
Will be set to true if the value was replaced
Return values
mixed —The altered value
initializeAlterKey()
Initialize the 'alters' property.
public
initializeAlterKey([array<string|int, mixed> $init = [] ]) : static
Parameters
- $init : array<string|int, mixed> = []
Return values
staticalterProperty()
Alters a specific property of the given document using one or more transformation rules.
protected
alterProperty(string $key, array<string|int, mixed>|object $document, string|array<string|int, mixed> $definition[, Container|null $container = null ]) : array<string|int, mixed>|object
The transformation is defined by the $definition argument, which can be:
- A string representing a single
Alter::constant (e.g.Alter::FLOAT) - An array with a single alteration and parameters:
[ Alter::URL , '/product/' ] - An array with chained alterations (NEW):
[ Alter::NORMALIZE , [ Alter::HYDRATE , Class::class ] ] - An array with multiple simple alterations (NEW):
[ Alter::TRIM , Alter::UPPERCASE , Alter::NORMALIZE ]
If the alteration modifies the value, the altered value is set back into the document. Otherwise, the original document is returned unmodified.
Supported alter types:
- Alter::ARRAY — Explodes a string into an array (using
;) and applies sub-alters - Alter::CALL — Calls a user-defined callable on the value
- Alter::CLEAN — Removes empty (
"") or null elements from arrays - Alter::FLOAT — Casts the value to float
- Alter::GET — Resolves a document by ID using a model
- Alter::HYDRATE — Hydrate a value with a specific class.
- Alter::INT — Casts the value to integer
- Alter::JSON_PARSE — Parses a JSON string into a PHP value
- Alter::JSON_STRINGIFY — Encodes a value into a JSON string
- Alter::MAP — Normalize a document property using configurable flags
- Alter::NORMALIZE — Normalize a document property using configurable flags
- Alter::NOT — Invert boolean values
- Alter::URL — Generates a URL based on document properties
- Alter::VALUE — Replaces the value with a fixed constant
Parameters
- $key : string
-
The name of the property to alter (e.g. 'price', 'tags')
- $document : array<string|int, mixed>|object
-
The document (array or object) passed by reference
- $definition : string|array<string|int, mixed>
-
The alteration definition: either a string (
Alter::) or an array ([ Alter::X , ...args ]) - $container : Container|null = null
-
An optional DI container reference.
Tags
Return values
array<string|int, mixed>|object —The altered document (same reference type as input)
applyChainedAlterations()
Applies chained alterations to a property.
protected
applyChainedAlterations(string $key, array<string|int, mixed>|object $document, array<string|int, mixed> $definitions[, Container|null $container = null ]) : array<string|int, mixed>|object
Each alteration in the chain is applied sequentially, with the output of one becoming the input of the next.
Parameters
- $key : string
-
The property key
- $document : array<string|int, mixed>|object
-
The document containing the property
- $definitions : array<string|int, mixed>
-
The array of alteration definitions
- $container : Container|null = null
-
An optional DI container reference.
Tags
Return values
array<string|int, mixed>|object —$document The document with the altered property
applySingleAlteration()
Applies a single alteration (original behavior).
protected
applySingleAlteration(string $key, array<string|int, mixed>|object $document, array<string|int, mixed> $definitions[, Container|null $container = null ]) : array<string|int, mixed>|object
Parameters
- $key : string
-
The property key
- $document : array<string|int, mixed>|object
-
The document containing the property
- $definitions : array<string|int, mixed>
-
The alteration definition with parameters
- $container : Container|null = null
-
An optional DI container reference.
Tags
Return values
array<string|int, mixed>|object —The document with the altered property
executeAlteration()
Executes a specific alteration.
protected
executeAlteration(string|Alter $alter, string $key, mixed $value, array<string|int, mixed> $params, array<string|int, mixed>|object &$document[, Container|null $container = null ][, bool &$modified = false ]) : mixed
Parameters
- $alter : string|Alter
-
The alteration type
- $key : string
-
The property key (for context)
- $value : mixed
-
The value to alter
- $params : array<string|int, mixed>
-
The alteration parameters
- $document : array<string|int, mixed>|object
-
The full document (for context)
- $container : Container|null = null
-
An optional DI container reference.
- $modified : bool = false
-
Output parameter indicating if the value was modified
Tags
Return values
mixed —The altered value
firstIsAlter()
Checks if a value is an Alter enum or an array starting with an Alter enum.
protected
firstIsAlter(mixed $first) : bool
Parameters
- $first : mixed
-
The value to check
Return values
bool —True if it's an Alter or array with Alter as first element
isChainedDefinition()
Detects if the definition represents chained alterations.
protected
isChainedDefinition(array<string|int, mixed> $definitions) : bool
Chaining is detected when:
- The first element is an Alter enum
- AND the second element is either:
- Another Alter enum (simple chaining)
- An array whose first element is an Alter enum (chaining with params)
Parameters
- $definitions : array<string|int, mixed>
-
The alteration definitions
Return values
bool —True if chaining is detected, false otherwise