ViewSorter::choice()   B
last analyzed

Complexity

Conditions 6
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 0
cts 12
cp 0
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 8
nc 2
nop 1
crap 42
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