ViewSorter   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 2
dl 0
loc 51
ccs 0
cts 26
cp 0
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
B choice() 0 13 6
A compare() 0 8 4
1
<?php
2
/**
3
 * AnimeDb package.
4
 *
5
 * @author    Peter Gribanov <[email protected]>
6
 * @copyright Copyright (c) 2011, Peter Gribanov
7
 * @license   http://opensource.org/licenses/GPL-3.0 GPL v3
8
 */
9
10
namespace AnimeDb\Bundle\CatalogBundle\Form;
11
12
use Symfony\Component\Form\FormView;
13
use Symfony\Component\Form\Extension\Core\View\ChoiceView;
14
15
/**
16
 * Form view sorter.
17
 *
18
 * @author  Peter Gribanov <[email protected]>
19
 */
20
class ViewSorter
21
{
22
    /**
23
     * @var \Collator|null
24
     */
25
    protected $collator = null;
26
27
    /**
28
     * @param string $locale
29
     */
30
    public function __construct($locale)
31
    {
32
        if (extension_loaded('intl')) {
33
            $this->collator = new \Collator($locale);
34
        }
35
    }
36
37
    /**
38
     * Sort choice.
39
     *
40
     * @param FormView $choice
41
     */
42
    public function choice(FormView $choice)
43
    {
44
        $that = $this;
45
        if ($choice->vars['compound']) {
46
            usort($choice->children, function (FormView $a, FormView $b) use ($that) {
47
                return $that->compare($a->vars['label'] ?: $a->vars['value'], $b->vars['label'] ?: $b->vars['value']);
48
            });
49
        } else {
50
            usort($choice->vars['choices'], function (ChoiceView $a, ChoiceView $b) use ($that) {
51
                return $that->compare($a->label ?: $a->value, $b->label ?: $b->value);
52
            });
53
        }
54
    }
55
56
    /**
57
     * @param string $a
58
     * @param string $b
59
     *
60
     * @return int
61
     */
62
    public function compare($a, $b)
63
    {
64
        if ($this->collator instanceof \Collator) {
65
            return $this->collator->compare($a, $b);
66
        } else {
67
            return $a == $b ? 0 : ($a > $b ? 1 : -1);
68
        }
69
    }
70
}
71