vendor/symfony/form/Extension/Core/DataTransformer/BooleanToStringTransformer.php line 80

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\InvalidArgumentException;
  13. use Symfony\Component\Form\Exception\TransformationFailedException;
  14. /**
  15.  * Transforms between a Boolean and a string.
  16.  *
  17.  * @author Bernhard Schussek <bschussek@gmail.com>
  18.  * @author Florian Eckerstorfer <florian@eckerstorfer.org>
  19.  */
  20. class BooleanToStringTransformer implements DataTransformerInterface
  21. {
  22.     private $trueValue;
  23.     private $falseValues;
  24.     /**
  25.      * @param string $trueValue The value emitted upon transform if the input is true
  26.      */
  27.     public function __construct(string $trueValue, array $falseValues = [null])
  28.     {
  29.         $this->trueValue $trueValue;
  30.         $this->falseValues $falseValues;
  31.         if (\in_array($this->trueValue$this->falseValuestrue)) {
  32.             throw new InvalidArgumentException('The specified "true" value is contained in the false-values');
  33.         }
  34.     }
  35.     /**
  36.      * Transforms a Boolean into a string.
  37.      *
  38.      * @param bool $value Boolean value
  39.      *
  40.      * @return string|null String value
  41.      *
  42.      * @throws TransformationFailedException if the given value is not a Boolean
  43.      */
  44.     public function transform($value)
  45.     {
  46.         if (null === $value) {
  47.             return null;
  48.         }
  49.         if (!\is_bool($value)) {
  50.             throw new TransformationFailedException('Expected a Boolean.');
  51.         }
  52.         return $value $this->trueValue null;
  53.     }
  54.     /**
  55.      * Transforms a string into a Boolean.
  56.      *
  57.      * @param string $value String value
  58.      *
  59.      * @return bool Boolean value
  60.      *
  61.      * @throws TransformationFailedException if the given value is not a string
  62.      */
  63.     public function reverseTransform($value)
  64.     {
  65.         if (\in_array($value$this->falseValuestrue)) {
  66.             return false;
  67.         }
  68.         if (!\is_string($value)) {
  69.             throw new TransformationFailedException('Expected a string.');
  70.         }
  71.         return true;
  72.     }
  73. }