Completed
Push — master ( 192638...f858f1 )
by Ivannis Suárez
05:02
created

Comparator::compare()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
rs 8.8571
cc 5
eloc 6
nc 6
nop 2
1
<?php
2
3
/**
4
 * This file is part of the Cubiche package.
5
 *
6
 * Copyright (c) Cubiche
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
namespace Cubiche\Core\Comparable;
12
13
use Cubiche\Core\Delegate\AbstractCallable;
14
use Cubiche\Core\Visitor\VisiteeTrait;
15
16
/**
17
 * Comparator class.
18
 *
19
 * @author Karel Osorio Ramírez <[email protected]>
20
 * @author Ivannis Suárez Jerez <[email protected]>
21
 */
22
class Comparator extends AbstractCallable implements ComparatorInterface
23
{
24
    use VisiteeTrait;
25
26
    /**
27
     * @param callable $comparator
28
     *
29
     * @return \Cubiche\Core\Comparable\ComparatorInterface
30
     */
31
    public static function from(callable $comparator)
32
    {
33
        if ($comparator instanceof ComparatorInterface) {
34
            return $comparator;
35
        }
36
37
        return new Custom($comparator);
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public function compare($a, $b)
44
    {
45
        if ($a instanceof ComparableInterface) {
46
            return $a->compareTo($b);
47
        }
48
49
        if ($b instanceof ComparableInterface) {
50
            return -1 * $b->compareTo($a);
51
        }
52
53
        return $a < $b ? -1 : ($a == $b ? 0 : 1);
54
    }
55
56
    /**
57
     * {@inheritdoc}
58
     */
59
    public function reverse()
60
    {
61
        return new ReverseComparator($this);
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function otherwise(callable $comparator)
68
    {
69
        return new MultiComparator($this, $comparator);
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    protected function innerCallable()
76
    {
77
        return array($this, 'compare');
78
    }
79
}
80