Completed
Branch master (acab90)
by Nil
03:50
created

EloquentPageRepository::findAll()   B

Complexity

Conditions 6
Paths 17

Size

Total Lines 39
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 39
rs 8.439
cc 6
eloc 25
nc 17
nop 1
1
<?php
2
3
namespace NilPortugues\Foundation\Infrastructure\Model\Repository\Eloquent;
4
5
use NilPortugues\Foundation\Domain\Model\Repository\Contracts\Page;
6
use NilPortugues\Foundation\Domain\Model\Repository\Contracts\Pageable;
7
use NilPortugues\Foundation\Domain\Model\Repository\Contracts\PageRepository;
8
use NilPortugues\Foundation\Domain\Model\Repository\Page as ResultPage;
9
10
class EloquentPageRepository extends BaseEloquentRepository implements PageRepository
11
{
12
    /**
13
     * Returns a Page of entities meeting the paging restriction provided in the Pageable object.
14
     *
15
     * @param Pageable $pageable
16
     *
17
     * @return Page
18
     */
19
    public function findAll(Pageable $pageable = null)
20
    {
21
        $model = self::$instance;
22
        $query = $model->query();
23
24
        if ($pageable) {
25
            $fields = $pageable->fields();
26
            $columns = (!$fields->isNull()) ? $fields->get() : ['*'];
27
28
            if (count($distinctFields = $pageable->distinctFields()->get()) > 0) {
29
                $query->getQuery()->distinct();
30
                $columns = $distinctFields;
31
            }
32
33
            $filter = $pageable->filters();
34
            if (!$filter->isNull()) {
35
                EloquentFilter::filter($query, $filter);
36
            }
37
38
            $sort = $pageable->sortings();
39
            if (!$sort->isNull()) {
40
                EloquentSorter::sort($query, $sort);
41
            }
42
43
            return new ResultPage(
44
                $query->paginate($pageable->pageSize(), $columns, 'page', $pageable->pageNumber())->items(),
45
                $query->paginate()->total(),
46
                $pageable->pageNumber(),
47
                ceil($query->paginate()->total() / $pageable->pageSize())
48
            );
49
        }
50
51
        return new ResultPage(
52
            $query->paginate($query->paginate()->total(), ['*'], 'page', 1)->items(),
53
            $query->paginate()->total(),
54
            1,
55
            1
56
        );
57
    }
58
}
59