vendor/symfony/form/Extension/Core/DataTransformer/ValueToDuplicatesTransformer.php line 61

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\Form\Extension\Core\DataTransformer;
  11. use Symfony\Component\Form\DataTransformerInterface;
  12. use Symfony\Component\Form\Exception\TransformationFailedException;
  13. /**
  14.  * @author Bernhard Schussek <bschussek@gmail.com>
  15.  */
  16. class ValueToDuplicatesTransformer implements DataTransformerInterface
  17. {
  18.     private array $keys;
  19.     public function __construct(array $keys)
  20.     {
  21.         $this->keys = $keys;
  22.     }
  23.     /**
  24.      * Duplicates the given value through the array.
  25.      */
  26.     public function transform(mixed $value): array
  27.     {
  28.         $result = [];
  29.         foreach ($this->keys as $key) {
  30.             $result[$key] = $value;
  31.         }
  32.         return $result;
  33.     }
  34.     /**
  35.      * Extracts the duplicated value from an array.
  36.      *
  37.      * @throws TransformationFailedException if the given value is not an array or
  38.      *                                       if the given array cannot be transformed
  39.      */
  40.     public function reverseTransform(mixed $array): mixed
  41.     {
  42.         if (!\is_array($array)) {
  43.             throw new TransformationFailedException('Expected an array.');
  44.         }
  45.         $result = current($array);
  46.         $emptyKeys = [];
  47.         foreach ($this->keys as $key) {
  48.             if (isset($array[$key]) && '' !== $array[$key] && false !== $array[$key] && [] !== $array[$key]) {
  49.                 if ($array[$key] !== $result) {
  50.                     throw new TransformationFailedException('All values in the array should be the same.');
  51.                 }
  52.             } else {
  53.                 $emptyKeys[] = $key;
  54.             }
  55.         }
  56.         if (\count($emptyKeys) > 0) {
  57.             if (\count($emptyKeys) == \count($this->keys)) {
  58.                 // All keys empty
  59.                 return null;
  60.             }
  61.             throw new TransformationFailedException(sprintf('The keys "%s" should not be empty.', implode('", "', $emptyKeys)));
  62.         }
  63.         return $result;
  64.     }
  65. }