Completed
Push — master ( 424c6b...82a97c )
by Peter
14:20 queued 06:35
created

ViewSorter::compare()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

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