AccountDiff   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 33
c 1
b 0
f 0
dl 0
loc 53
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A prepareData() 0 21 3
A init() 0 6 1
A findDataModel() 0 18 1
1
<?php
2
/**
3
 * Created for IG Monitoring.
4
 * User: jakim <[email protected]>
5
 * Date: 2019-01-25
6
 */
7
8
namespace app\components\stats\diffs;
9
10
11
use app\components\stats\base\BaseDiff;
12
use app\components\traits\SetAccountTrait;
13
use app\models\AccountStats;
14
use yii\db\Expression;
15
use yii\helpers\ArrayHelper;
16
17
/**
18
 * Class AccountDiff
19
 *
20
 * @package app\components\stats\datasets
21
 */
22
class AccountDiff extends BaseDiff
23
{
24
    use SetAccountTrait;
25
26
    public function init()
27
    {
28
        parent::init();
29
        $this->throwExceptionIfFromToAreNotSet();
30
        $this->throwExceptionIfStatsAttributesIsNotSet();
31
        $this->throwExceptionIfAccountIsNotSet();
32
    }
33
34
    protected function prepareData(): array
35
    {
36
        $data = [];
37
38
        $dbTo = $this->to->copy()->endOfDay()->toDateTimeString();
39
        $dbFrom = $this->from->copy()->endOfDay()->toDateTimeString();
40
41
        $toModel = $this->findDataModel($dbTo);
42
43
        if (strtotime($toModel['created_at']) > strtotime($dbFrom)) {
44
            $fromModel = $this->findDataModel($dbFrom, $toModel['id']);
45
        } else {
46
            $fromModel = $toModel;
47
        }
48
49
        foreach ($this->statsAttributes as $statsAttribute) {
50
            $value = ArrayHelper::getValue($toModel, $statsAttribute, 0) - ArrayHelper::getValue($fromModel, $statsAttribute, 0);
51
            $data[$statsAttribute] = $value;
52
        }
53
54
        return $data;
55
    }
56
57
    protected function findDataModel(string $date, $ignoredStatsId = null)
58
    {
59
        $columns = array_map(function ($attr) {
60
            return "account_stats.{$attr}";
61
        }, $this->statsAttributes);
62
        $columns[] = 'id';
63
        $columns[] = new Expression('DATE(created_at) as created_at');
64
65
        return AccountStats::find()
66
            ->cache()
67
            ->select($columns)
68
            ->andWhere(['account_id' => $this->account->id])
69
            ->andWhere(['<=', 'created_at', $date])
70
            ->andFilterWhere(['not', ['id' => $ignoredStatsId]])
71
            ->orderBy('id DESC')
72
            ->limit(1)
73
            ->asArray()
74
            ->one();
75
    }
76
}