Hydration has several facilities for the intelligent creation of arrays.
Cast to Array
Why make your users do this:
{
"something": ["some value"]
}
For a single-valued array when they would like to just do this:
{
"something": "some value"
}
To achieve this, make the property an array by adding a call to `key()' and Hydration will convert the scalar value to an array.
key()
is also useful for creating associative arrays from arrays of objects using a property of
the object as the array key. Simply pass the name of the property to be used as the key.
class Element
{
public string $name;
public string $data;
}
class ElementManager implements Hydratable
{
public array $elements;
public function hydrate($json, $options = []): bool
{
if (!isset(self::$hydrator)) {
self::$hydrator = Hydrator::make()
->addProperty(
Property::make('elements')
->key('name')
->bind(Element::class)
);
}
return self::$hydrator->hydrate($this, $json, $options);
}
}
Given an input like
{
"elements": [
{
"name": "element1",
"data": "somedata"
},
{
"name": "element2",
"data": "moredata"
}
]
}
Hydration will set the $elements
property of the ElementManager to contain two Elements with
keys "element1" and "element2".
By default, Hydration will throw an error if the input data creates a duplicate key. The application
can call the allowDuplicates()
method to override this. The method takes a Boolean argument that
defaults to true. If duplicates are allowed, earlier elements with the same key will be silently
overwritten.
Selectively Casting to array
The json_decode()
function can convert JSON objects into associative arrays by passing the
JSON_OBJECT_AS_ARRAY
flag, but the flag functions globally on the entire decode. Hydration
lets the application perform this conversion selectively, by calling the toArray()
method.
Property::make('someArray')
->toArray();