Commit 3b313c7e authored by Bertrand Gauthier's avatar Bertrand Gauthier
Browse files

GetIdStrategy : Stratégie pour extraire le·s id·s du·des objet·s transmis par...

GetIdStrategy : Stratégie pour extraire le·s id·s du·des objet·s transmis par un hydrateur ; utilisable dans un hydrateur héritant de DoctrineObject, associée à un élément de formulaire mappé à une relation to-one ou to-many d'une entité Doctrine.
parent 12a19575
Loading
Loading
Loading
Loading
+56 −0
Original line number Diff line number Diff line
<?php

namespace UnicaenApp\Hydrator\Strategy;

use DomainException;
use Laminas\Hydrator\Strategy\StrategyInterface;

/**
 * Stratégie pour extraire le·s id·s du·des objet·s transmis par un hydrateur.
 *
 * À utiliser :
 *   - dans un hydrateur héritant de {@see \Doctrine\Laminas\Hydrator\DoctrineObject},
 *   - associée à un élément de formulaire mappé à une relation to-one ou to-many d'une entité Doctrine (ex: <select>).
 */
class GetIdStrategy implements StrategyInterface
{
    /**
     * Transforme l'instance e·s objet·s
     */
    public function extract($value, ?object $object = null): array|int|string|null
    {
        if ($value === null) {
            return null;
        }

        if (is_object($value)) {
            return $this->extractFromObjectValue($value, $object);
        } elseif (is_iterable($value)) {
            // mode 'multiple'
            $values = [];
            foreach (iterator_to_array($value) as $v) {
                $values[] = $this->extractFromObjectValue($v, $object);
            }
            return $values;
        }

        throw new DomainException(
            "Valeur inattendue reçue : " . (is_object($value) ? get_class($value) : gettype($value))
        );
    }

    protected function extractFromObjectValue(object $value, ?object $object = null)
    {
        return $value->getId();
    }

    /**
     * On présuppose que la valeur reçue est un ou plusieurs id·s (comme fourni·s par un <select> par ex) donc
     * on se contente de la retourner telle quelle, charge à l'hydrateur héritant de
     * {@see \Doctrine\Laminas\Hydrator\DoctrineObject} de fetcher le·s objet·s correspondant·s.
     */
    public function hydrate($value, ?array $data): array|int|string|null
    {
        return $value;
    }
}
 No newline at end of file