GridSortingTransformer   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 12
lcom 0
cbo 1
dl 0
loc 69
rs 10
c 0
b 0
f 0
ccs 0
cts 48
cp 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
C transform() 0 32 7
B reverseTransform() 0 27 5
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\GridBundle\Form\DataTransformer;
13
14
use Lug\Component\Grid\Sort\SorterInterface;
15
use Symfony\Component\Form\DataTransformerInterface;
16
use Symfony\Component\Form\Exception\TransformationFailedException;
17
18
/**
19
 * @author GeLo <[email protected]>
20
 */
21
class GridSortingTransformer implements DataTransformerInterface
22
{
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public function transform($value)
27
    {
28
        if ($value === null) {
29
            return;
30
        }
31
32
        if (!is_array($value)) {
33
            throw new TransformationFailedException(sprintf(
34
                'The grid sorting value should be an array, got "%s".',
35
                is_object($value) ? get_class($value) : gettype($value)
36
            ));
37
        }
38
39
        $sorting = [];
40
41
        foreach ($value as $key => $order) {
42
            if (!in_array($order, [SorterInterface::ASC, SorterInterface::DESC], true)) {
43
                throw new TransformationFailedException(sprintf(
44
                    'The grid sorting order should be "ASC" or "DESC", got "%s".',
45
                    $order
46
                ));
47
            }
48
49
            if ($order === SorterInterface::DESC) {
50
                $key = '-'.$key;
51
            }
52
53
            $sorting[] = $key;
54
        }
55
56
        return implode(',', $sorting);
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62
    public function reverseTransform($value)
63
    {
64
        $exploded = explode(',', $value);
65
66
        if ($exploded === false) {
67
            throw new TransformationFailedException(sprintf(
68
                'The grid sorting should be comma-separated, got "%s".',
69
                $value
70
            ));
71
        }
72
73
        $sorting = [];
74
75
        foreach (array_map('trim', $exploded) as $order) {
76
            if (empty($order)) {
77
                continue;
78
            }
79
80
            if ($order[0] === '-') {
81
                $sorting[substr($order, 1)] = SorterInterface::DESC;
82
            } else {
83
                $sorting[$order] = SorterInterface::ASC;
84
            }
85
        }
86
87
        return $sorting;
88
    }
89
}
90