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: * Conversion pour valeur booléenne à 3 niveau (vrai/faux/null).
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: * Construct the data transformer with parameters.
22: *
23: * @param bool $notnull Disable the 'null' option ('null' as 'false')
24: */
25: public function __construct(bool $notnull = null)
26: {
27: $this->nullable = empty($notnull);
28: }
29:
30: /**
31: * Transforms from DB value to form value.
32: *
33: * @param mixed $value
34: * @return string Label for true, false or null
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: * Reverse transforms form value to db value.
44: *
45: * @param mixed $value
46: * @return bool|null
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: