| 1: | <?php |
| 2: | namespace TIC\CoreBundle\Form\DataTransformer; |
| 3: | |
| 4: | use Symfony\Component\Form\DataTransformerInterface; |
| 5: | use Symfony\Component\Form\Exception\TransformationFailedException; |
| 6: | |
| 7: | |
| 8: | |
| 9: | |
| 10: | class BooleanOrNullTransformer implements DataTransformerInterface |
| 11: | { |
| 12: | protected $values = array( |
| 13: | 'null' => '', |
| 14: | 'false' => '0', |
| 15: | 'true' => '1', |
| 16: | ); |
| 17: | |
| 18: | private $nullable; |
| 19: | |
| 20: | |
| 21: | |
| 22: | |
| 23: | |
| 24: | |
| 25: | public function __construct(bool $notnull = null) |
| 26: | { |
| 27: | $this->nullable = empty($notnull); |
| 28: | } |
| 29: | |
| 30: | |
| 31: | |
| 32: | |
| 33: | |
| 34: | |
| 35: | |
| 36: | public function transform(mixed $value): string |
| 37: | { |
| 38: | if ($this->nullable && $value === null) return $this->values['null']; |
| 39: | return empty($value) ? $this->values['false'] : $this->values['true']; |
| 40: | } |
| 41: | |
| 42: | |
| 43: | |
| 44: | |
| 45: | |
| 46: | |
| 47: | |
| 48: | public function reverseTransform(mixed $value): ?bool |
| 49: | { |
| 50: | if ($value === null || $value === $this->values['null']) |
| 51: | return $this->nullable ? null : false; |
| 52: | |
| 53: | if ($value === $this->values['false']) return false; |
| 54: | if ($value === $this->values['true']) return true; |
| 55: | |
| 56: | return empty($value) ? false : true; |
| 57: | } |
| 58: | |
| 59: | } |
| 60: | |