Completed
Push — feature/pixie-port ( 8213a1...132a2b )
by Vladimir
13:51
created

getMatchActivityWorthQuery()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 11
nc 1
nop 0
1
<?php
2
3
use Pecee\Pixie\QueryBuilder\JoinBuilder;
4
5
abstract class MatchActivityQueryBuilder extends QueryBuilderFlex
6
{
7
    /**
8
     * @throws \Pecee\Pixie\Exception
9
     * @throws Exception
10
     *
11
     * @return static
12
     */
13
    protected function getMatchActivityWorthQuery()
14
    {
15
        $qb = self::createBuilder();
16
17
        // The subquery to calculate each match's worth towards activity if it has occurred less than 45 days ago.
18
        //   - 86400 is in seconds; i.e. 24 hours
19
        //   - 0.0116687059537612 is a magic number
20
        $matchActivityWorthQuery = $qb->table('matches')->alias('m');
21
        $matchActivityWorthQuery
22
            ->select([
23
                'm.id',
24
                $qb->raw('TIMESTAMPDIFF(SECOND, `m`.`timestamp`, NOW()) / 86400 AS days_passed'),
25
                $qb->raw('(0.0116687059537612 * (POW((45 - LEAST((SELECT days_passed), 45)), (1/6)) + ATAN(31 - (SELECT days_passed)) / 2)) AS activity'),
26
            ])
27
            ->where($qb->raw('DATEDIFF(NOW(), `m`.`timestamp`) <= 45'))
28
            ->orderBy('m.timestamp', 'DESC')
29
        ;
30
31
        return $matchActivityWorthQuery;
32
    }
33
34
    /**
35
     * @throws \Pecee\Pixie\Exception
36
     * @throws Exception
37
     */
38
    protected function buildMatchActivity(QueryBuilderFlex $subQuery, JoinBuilder $joinBuilder)
39
    {
40
        $qb = self::createBuilder();
41
        $type = $this->modelType;
42
43
        $this
44
            ->select(
45
                $qb->raw('SUM(m2.activity) AS activity')
46
            )
47
            ->leftJoin(
48
                $qb->subQuery($subQuery, 'm2'),
49
                function (&$table) use ($joinBuilder) {
50
                    $table = $joinBuilder;
51
                }
52
            )
53
            ->groupBy($type::getEagerColumnsList())
54
        ;
55
56
        return $this;
57
    }
58
}
59