1 | <?php |
||
2 | /** |
||
3 | * Created for IG Monitoring. |
||
4 | * User: jakim <[email protected]> |
||
5 | * Date: 19.06.2018 |
||
6 | */ |
||
7 | |||
8 | namespace app\components\stats; |
||
9 | |||
10 | |||
11 | use app\models\Account; |
||
12 | use app\models\AccountStats; |
||
13 | use Carbon\Carbon; |
||
14 | use yii\base\Component; |
||
15 | use yii\db\Expression; |
||
16 | use yii\helpers\ArrayHelper; |
||
17 | |||
18 | class AccountDaily extends Component |
||
19 | { |
||
20 | /** |
||
21 | * @var \app\models\Account |
||
22 | */ |
||
23 | public $model; |
||
24 | |||
25 | private $statsAttributes = [ |
||
26 | 'media', |
||
27 | 'followed_by', |
||
28 | 'follows', |
||
29 | 'er', |
||
30 | 'avg_likes', |
||
31 | 'avg_comments', |
||
32 | ]; |
||
33 | |||
34 | protected $cache = []; |
||
35 | |||
36 | public function __construct(Account $model, array $config = []) |
||
37 | { |
||
38 | $this->model = $model; |
||
39 | $this->cache = []; |
||
40 | parent::__construct($config); |
||
41 | } |
||
42 | |||
43 | public function get() |
||
44 | { |
||
45 | return $this->cache; |
||
46 | } |
||
47 | |||
48 | /** |
||
49 | * The difference between the data from subsequent days from a given date range. |
||
50 | * |
||
51 | * @param $olderDate |
||
52 | * @param null $newerDate |
||
0 ignored issues
–
show
Documentation
Bug
introduced
by
Loading history...
|
|||
53 | * @return \app\components\stats\AccountDaily |
||
54 | */ |
||
55 | public function initData($olderDate, $newerDate = null) |
||
56 | { |
||
57 | $olderDate = (new Carbon($olderDate))->startOfDay()->toDateTimeString(); |
||
58 | $newerDate = (new Carbon($newerDate))->endOfDay()->toDateTimeString(); |
||
59 | |||
60 | if (empty($this->cache)) { |
||
61 | //group by DATE Y-m-d |
||
62 | $ids = AccountStats::find() |
||
63 | ->select(new Expression('MAX(id) as id')) |
||
64 | ->andWhere(['account_id' => $this->model->id]) |
||
65 | ->andWhere(['>=', 'created_at', $olderDate]) |
||
66 | ->andWhere(['<=', 'created_at', $newerDate]) |
||
67 | ->groupBy(new Expression('DATE(created_at)')) |
||
68 | ->column(); |
||
69 | |||
70 | $stats = AccountStats::find() |
||
71 | ->select([ |
||
72 | 'account_stats.*', |
||
73 | new Expression('DATE(created_at) as created_at'), |
||
74 | ]) |
||
75 | ->andWhere(['account_id' => $this->model->id]) |
||
76 | ->andWhere(['id' => $ids]) |
||
77 | ->orderBy('id ASC') |
||
78 | ->asArray() |
||
79 | ->all(); |
||
80 | |||
81 | foreach ($stats as $stat) { |
||
82 | foreach ($this->statsAttributes as $statsAttribute) { |
||
83 | $value = ArrayHelper::getValue($stat, $statsAttribute, 0); |
||
84 | $this->cache[$stat['created_at']][$statsAttribute] = $value; |
||
85 | } |
||
86 | } |
||
87 | } |
||
88 | |||
89 | return $this; |
||
90 | } |
||
91 | } |