Passed
Pull Request — master (#93)
by Alexander
12:07
created

CommentFeedReader::withLimit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 3
c 1
b 0
f 1
dl 0
loc 5
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace App\Blog\Comment;
6
7
use Cycle\ORM\Select;
8
use Yiisoft\Data\Reader\DataReaderInterface;
9
use Yiisoft\Data\Reader\Filter\CompareFilter;
10
use Yiisoft\Data\Reader\Filter\FilterInterface;
11
use Yiisoft\Data\Reader\Filter\FilterProcessorInterface;
12
use Yiisoft\Data\Reader\FilterableDataInterface;
13
use Yiisoft\Data\Reader\Sort;
14
use Yiisoft\Data\Reader\SortableDataInterface;
15
16
final class CommentFeedReader implements FilterableDataInterface, DataReaderInterface, SortableDataInterface
17
{
18
    private Select $query;
19
    private ?int $limit = null;
20
    private ?Sort $sorting = null;
21
    private ?FilterInterface $filter = null;
22
23
    public function __construct(Select $query)
24
    {
25
        $this->query = clone $query;
26
    }
27
28
    public function getSort(): ?Sort
29
    {
30
        return $this->sorting;
31
    }
32
33
    public function withLimit(int $limit): self
34
    {
35
        $clone = clone $this;
36
        $clone->limit = $limit;
37
        return $clone;
38
    }
39
40
    public function withSort(?Sort $sorting): self
41
    {
42
        $clone = clone $this;
43
        $clone->sorting = $sorting;
44
        return $clone;
45
    }
46
47
    public function read(): iterable
48
    {
49
        $query = clone $this->query;
50
        if ($this->sorting !== null) {
51
            $query->orderBy($this->sorting->getOrder());
52
        }
53
        if ($this->limit !== null) {
54
            $query->limit($this->limit);
55
        }
56
57
        if ($this->filter !== null) {
58
            $filterParams = $this->filter->toArray();
59
            $query->where($filterParams[1], $filterParams[0], $filterParams[2]);
60
        }
61
62
        return $query->fetchData();
63
    }
64
65
    public function withFilter(FilterInterface $filter): self
66
    {
67
        if (!$filter instanceof CompareFilter) {
68
            throw new \InvalidArgumentException('Filter should implement CompareFilter');
69
        }
70
71
        $clone = clone $this;
72
        $clone->filter = $filter;
73
        return $clone;
74
    }
75
76
    public function withFilterProcessors(FilterProcessorInterface ...$filterProcessors): void
77
    {
78
        // skip
79
    }
80
}
81