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

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 $keys;
  19.     public function __construct(array $keys)
  20.     {
  21.         $this->keys $keys;
  22.     }
  23.     /**
  24.      * Duplicates the given value through the array.
  25.      *
  26.      * @param mixed $value The value
  27.      *
  28.      * @return array
  29.      */
  30.     public function transform($value)
  31.     {
  32.         $result = [];
  33.         foreach ($this->keys as $key) {
  34.             $result[$key] = $value;
  35.         }
  36.         return $result;
  37.     }
  38.     /**
  39.      * Extracts the duplicated value from an array.
  40.      *
  41.      * @return mixed
  42.      *
  43.      * @throws TransformationFailedException if the given value is not an array or
  44.      *                                       if the given array cannot be transformed
  45.      */
  46.     public function reverseTransform($array)
  47.     {
  48.         if (!\is_array($array)) {
  49.             throw new TransformationFailedException('Expected an array.');
  50.         }
  51.         $result current($array);
  52.         $emptyKeys = [];
  53.         foreach ($this->keys as $key) {
  54.             if (isset($array[$key]) && '' !== $array[$key] && false !== $array[$key] && [] !== $array[$key]) {
  55.                 if ($array[$key] !== $result) {
  56.                     throw new TransformationFailedException('All values in the array should be the same.');
  57.                 }
  58.             } else {
  59.                 $emptyKeys[] = $key;
  60.             }
  61.         }
  62.         if (\count($emptyKeys) > 0) {
  63.             if (\count($emptyKeys) == \count($this->keys)) {
  64.                 // All keys empty
  65.                 return null;
  66.             }
  67.             throw new TransformationFailedException(sprintf('The keys "%s" should not be empty.'implode('", "'$emptyKeys)));
  68.         }
  69.         return $result;
  70.     }
  71. }