Completed
Push — master ( 0d5d72...dfde49 )
by Nate
06:40 queued 04:53
created

ActiveDataProvider::prepareTotalCount()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 5
c 1
b 0
f 0
ccs 0
cts 5
cp 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
crap 2
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipboxfactory/craft-ember/blob/master/LICENSE
6
 * @link       https://github.com/flipboxfactory/craft-ember
7
 */
8
9
namespace flipbox\ember\data;
10
11
use yii\base\InvalidConfigException;
12
use yii\db\Query;
13
use yii\db\QueryInterface;
14
15
/**
16
 * @author Flipbox Factory <[email protected]>
17
 * @since 1.0.2
18
 *
19
 * Ref: https://github.com/craftcms/cms/issues/2857
20
 */
21
class ActiveDataProvider extends \yii\data\ActiveDataProvider
22
{
23
    /**
24
     * {@inheritdoc}
25
     */
26
    protected function prepareModels()
27
    {
28
        $query = $this->getQueryClone();
29
        if (($pagination = $this->getPagination()) !== false) {
30
            $pagination->totalCount = $this->getTotalCount();
31
            if ($pagination->totalCount === 0) {
32
                return [];
33
            }
34
            $query->limit($pagination->getLimit())->offset($pagination->getOffset());
35
        }
36
        if (($sort = $this->getSort()) !== false) {
37
            $query->addOrderBy($sort->getOrders());
38
        }
39
40
        return $query->all($this->db);
41
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    protected function prepareTotalCount()
47
    {
48
        $query = $this->getQueryClone();
49
        return (int)$query->limit(-1)->offset(-1)->orderBy([])->count('*', $this->db);
50
    }
51
52
    /**
53
     * @return QueryInterface
54
     * @throws InvalidConfigException
55
     */
56
    private function getQueryClone(): QueryInterface
57
    {
58
        if (!$this->query instanceof QueryInterface) {
59
            throw new InvalidConfigException('The "query" property must be an instance of a class that implements 
60
            the QueryInterface e.g. yii\db\Query or its subclasses.');
61
        }
62
63
        $query = clone $this->query;
64
65
        if ($this->query instanceof Query) {
66
            /** @var Query $query */
67
            foreach ($this->query->getBehaviors() as $name => $behavior) {
68
                $query->attachBehavior($name, clone $behavior);
69
            }
70
        }
71
72
        return $query;
73
    }
74
}
75