Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save marcus-at-localhost/5c10fe03cd74329120cdbc51de8139b4 to your computer and use it in GitHub Desktop.
Save marcus-at-localhost/5c10fe03cd74329120cdbc51de8139b4 to your computer and use it in GitHub Desktop.
How to create a nested data-transfer-object (DTO) array with different types.md

#dto #data-transfer-object #php

Based on https://github.com/spatie/data-transfer-object/tree/v2

$object = [
    'parameters' => [
        [
            'name' => 'foo',
            'type' => 'text',
            'value' => 'bar'
        ],
        [
            'name' => 'baz',
            'type' => 'select',
            'values' => ['foo', 'bar']
        ]
    ]
];

The function array_map will iterate over every parameters, and for each one it will call Parameters::createFromArray($param), which will return an instance of Parameters based on the type it finds in the $param array.

namespace Formio\Dto;

use Spatie\DataTransferObject\FlexibleDataTransferObject;

class Content extends FlexibleDataTransferObject
{
    public Parameters $parameters;

    public function __construct(array $parameters)
    {
        parent::__construct($parameters);

        $this->parameters = array_map(function($param) {
            return \Formio\Dto\Parameters::createFromArray($param);
        }, $this->parameters);
    }
}
// file Parameters.php
namespace Formio\Dto;

use Spatie\DataTransferObject\FlexibleDataTransferObject;

abstract class Parameters extends FlexibleDataTransferObject
{
    public string $name;
    public string $type;

    public static function createFromArray(array $parameters)
    {
        switch($parameters['type']) {
            case 'select':
                return new ParametersSelect($parameters);
            default:
                return new ParametersText($parameters);
        }
    }
}

class ParametersSelect extends Parameters
{
    public array $values;
}

class ParametersText extends Parameters
{
    public string $value;
}
$dto = \Formio\Dto\Content($object)

Source https://stackoverflow.com/questions/76789091

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment