Completed
Push — master ( afca2b...7dac57 )
by Eric
9s
created

BooleanTransformer::transform()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4.0218

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 15
ccs 8
cts 9
cp 0.8889
rs 9.2
cc 4
eloc 8
nc 3
nop 1
crap 4.0218
1
<?php
2
3
/*
4
 * This file is part of the Lug package.
5
 *
6
 * (c) Eric GELOEN <[email protected]>
7
 *
8
 * For the full copyright and license information, please read the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Lug\Bundle\ResourceBundle\Form\DataTransformer;
13
14
use Symfony\Component\Form\DataTransformerInterface;
15
use Symfony\Component\Form\Exception\TransformationFailedException;
16
17
/**
18
 * @author GeLo <[email protected]>
19
 */
20
class BooleanTransformer implements DataTransformerInterface
21
{
22
    /**
23
     * {@inheritdoc}
24
     */
25 26
    public function transform($value)
26
    {
27 26
        if ($value === null) {
28
            return;
29
        }
30
31 26
        if (!is_bool($value)) {
32 4
            throw new TransformationFailedException(sprintf(
33 4
                'The boolean type expects a boolean or null value, got "%s"',
34 4
                is_object($value) ? get_class($value) : gettype($value)
35 4
            ));
36
        }
37
38 22
        return $value;
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44 18
    public function reverseTransform($value)
45
    {
46 18
        if ($value === null || $value === '') {
47 3
            return false;
48
        }
49
50 15
        if (!is_scalar($value)
51 15
            || ($value = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) === null) {
52 4
            throw new TransformationFailedException('The boolean value is not valid.');
53
        }
54
55 11
        return $value;
56
    }
57
}
58