Encoding
Hydration provides facilities for preparing Hydratable structures for storage as configuration
files, analogous to json_encode()
. The class needs to support the JsonSerializable interface and
call Hydratable::encode().
public function jsonSerialize()
{
return self::$hydrator->encode($this);
}
Encoding provides for the formatting and ordering of properties, and the suppression of properties
with default values. This is achieved by adding encoding rules to Properties via the encodeWith()
method. encodeWith()
accepts a string, EncoderRule
or an array of rules. If a single string is
passed, then it can be a compound rule of the form "rule1|rule2|rule3...".
Encoding rules are a command verb with any arguments separated by colons. Possible command verbs are
array
, drop
, order
, scalar
, and transform
.
Array
The array
rule will cast the encoded value to an array.
Drop
A drop
rule will omit a property when a matching condition is found. The conditions are:
- blank
The property will be dropped if it is an empty string.
- empty[:method]
The property will be dropped if the empty method returns true. The default
empty method is isEmpty()
. This can be overridden by supplying an alternate method name.
- false
The property is dropped if it evaluates to false.
- null
The property is dropped if it is null.
- true
The property is dropped if it evaluates to true.
- zero
The property is dropped if it is equal to zero.
Order
The order rule requires a number (e.g. "order:20"). Hydration will sort the generated properties with the lowest order first. The number can be integer or floating point.
Scalar
The scalar rule will convert a single valued array into a stand-alone value. Note that the result
might not be an actual scalar if the array element is not a scalar. This rule will convert
[[1, 2, 3]]
to [1, 2, 3]
.
Transform
Transform rules take a method name or a Callable as the argument (e.g. "transform:compress"). This function will be called with the property value, the source object, and the current Property as arguments. It is expected that the value is passed by reference.
Encoding transforms allow the application to convert objects into forms that are easier for users to manipulate.