Hydration lets your application simplify configuration files to make them easier to use. When a simplified form is passed to the class hydration function, it can test for this condition and synthesize an object that contains the additional information.

Example: Assume an application has a list of inputs. Inputs can have several types, but the majority of them will have the type "text", so we'd like to make that easier for the user by allowing them to omit the type and just supply the name of the input.

Instead of

{
  "inputs": [
    {
      "name": "field1",
      "type": "text"
    },
    {
      "name": "field2",
      "type": "button"
    },
    {
      "name": "field3",
      "type": "text"
    }
  ]
}

It would be nice if the user could just write

{
  "inputs": [
    "field1",
    {
      "name": "field2",
      "type": "button"
    },
    "field3"
  ]
}

This is easy to implement:

class Input implements Hydration
{
    protected string $name = '';
    private static Hydrator $hydrator;
    protected string $type = '';    

    public function hydrate($json, $options = []): bool
    {
        if (!isset(self::$hydrator)) {
            self::$hydrator = Hydrator::make(self::class);
        }
        // Make sure we've decoded the input text
        $json = self::$hydrator->decode($json, $options);

        if (is_string($json)) {
            // Turn the string into a text object
            $expand = new stdClass();
            $expand->name = $config;
            $expand->type = 'text';
            return self::$hydrator->hydrate($this, $expand, $options);
        }
        return self::$hydrator->hydrate($this, $json, $options);
    }


}

It might be even nicer if the user could simplify further:

{
  "inputs": ["field1", "field2/button", "field3"]
}

Which is also reasonably easy:

class Input implements Hydration
{
    protected string $name = '';
    private static Hydrator $hydrator;
    protected string $type = '';    

    public function hydrate($json, $options = []): bool
    {
        if (!isset(self::$hydrator)) {
            self::$hydrator = Hydrator::make(self::class);
        }
        // Make sure we've decoded the input text
        $json = self::$hydrator->decode($json, $options);

        if (is_string($json)) {
            // Turn the string into a text object, extracting a type.
            $parts = explode('/', $json);
            $expand = new stdClass();
            $expand->name = $parts[0];
            $expand->type = $parts[1] ??'text';
            return self::$hydrator->hydrate($this, $expand, $options);
        }
        return self::$hydrator->hydrate($this, $json, $options);
    }


}

Encoding

Hydration also allows the application to simplify encoded data via transform rules. See the
encoding documentation for more information.