UnicodeComparator::getLocale()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 1 Features 1
Metric Value
c 1
b 1
f 1
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace PHPExtra\Sorter\Comparator;
4
5
/**
6
 * Case-sensitive multibyte string comparison
7
 * This comparator uses Collator object from INTL with Collator::NUMERIC_COLLATION flag set to TRUE.
8
 *
9
 * @see Collator::NUMERIC_COLLATION
10
 * @author Jacek Kobus <[email protected]>
11
 */
12
class UnicodeComparator implements ComparatorInterface
13
{
14
    /**
15
     * @var \Collator
16
     */
17
    private $collator;
18
19
    /**
20
     * @param string $locale
21
     */
22 38
    function __construct($locale = null)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
23
    {
24 38
        if(!$locale){
0 ignored issues
show
Bug Best Practice introduced by
The expression $locale of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
25 13
            $locale = \Locale::getDefault();
26 13
        }
27 38
        $this->collator = new \Collator($locale);
28 38
        $this->collator->setAttribute(\Collator::NUMERIC_COLLATION, \Collator::ON);
29 38
    }
30
31
    /**
32
     * Get locale used by collator
33
     *
34
     * @return string
35
     */
36 2
    public function getLocale()
37
    {
38 2
        return $this->collator->getLocale(\Locale::VALID_LOCALE);
39
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44 28
    public function compare($a, $b)
45
    {
46
        //@todo result can be false in case of an error - lets pretend that those strings are equal for now
47 28
        $result = $this->collator->compare($a, $b);
48 28
        return $result !== false ? $result : 0;
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54 9
    public function supports($value)
55
    {
56 9
        return $value === null || is_string($value) || is_int($value) || is_float($value);
57
    }
58
}