ComplexSorter::withDirection()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 6
nc 2
nop 1
1
<?php
2
/**
3
 * Spiral Framework.
4
 *
5
 * @license   MIT
6
 * @author    Anton Titov (Wolfy-J)
7
 */
8
9
namespace Spiral\Listing\Sorters;
10
11
use Spiral\Listing\DirectionalSorterInterface;
12
use Spiral\Listing\Exceptions\SorterException;
13
use Spiral\Listing\SorterInterface;
14
15
class ComplexSorter implements DirectionalSorterInterface
16
{
17
    /**
18
     * @var int
19
     */
20
    private $direction = self::ASC;
21
22
    /**
23
     * @var SorterInterface
24
     */
25
    private $ascSorter = null;
26
27
    /**
28
     * @var SorterInterface
29
     */
30
    private $descSorter = null;
31
32
    /**
33
     * @param SorterInterface $ascSorter
34
     * @param SorterInterface $descSorter
35
     */
36
    public function __construct(SorterInterface $ascSorter, SorterInterface $descSorter)
37
    {
38
        $this->ascSorter = $ascSorter;
39
        $this->descSorter = $descSorter;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function apply($selector)
46
    {
47
        if ($this->direction == self::ASC) {
48
            return $this->ascSorter->apply($selector);
49
        }
50
51
        return $this->descSorter->apply($selector);
52
    }
53
54
    /**
55
     * Get sorter direction if any
56
     *
57
     * @return int
58
     */
59
    public function getDirection()
60
    {
61
        return $this->direction;
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function withDirection($direction)
68
    {
69
        if (!in_array($direction, [self::ASC, self::DESC])) {
70
            throw new SorterException("Invalid sorting direction '{$direction}'");
71
        }
72
73
        $sorter = clone $this;
74
        $sorter->direction = $direction;
75
76
        return $sorter;
77
    }
78
}