| 1: | <?php |
| 2: | namespace TIC\FormBundle\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: | |
| 13: | private $values = array( |
| 14: | 'null' => '', |
| 15: | 'false' => '0', |
| 16: | 'true' => '1', |
| 17: | ); |
| 18: | |
| 19: | private $nullable; |
| 20: | |
| 21: | public function __construct($notnull = null) |
| 22: | { |
| 23: | $this->nullable = empty($notnull); |
| 24: | } |
| 25: | |
| 26: | |
| 27: | |
| 28: | |
| 29: | |
| 30: | |
| 31: | |
| 32: | public function transform($value) |
| 33: | { |
| 34: | if ($this->nullable && $value === null) return $this->values['null']; |
| 35: | return empty($value) ? $this->values['false'] : $this->values['true']; |
| 36: | } |
| 37: | |
| 38: | |
| 39: | |
| 40: | |
| 41: | |
| 42: | |
| 43: | |
| 44: | public function reverseTransform($value) |
| 45: | { |
| 46: | if ($value === null || $value === $this->values['null']) |
| 47: | return $this->nullable ? null : false; |
| 48: | |
| 49: | if ($value === $this->values['false']) return false; |
| 50: | if ($value === $this->values['true']) return true; |
| 51: | |
| 52: | return empty($value) ? false : true; |
| 53: | } |
| 54: | |
| 55: | |
| 56: | } |
| 57: | |