Completed
Push — master ( d5ed8a...45b64e )
by Oscar
01:36
created

SelectAggregate::run()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
declare(strict_types = 1);
3
4
namespace SimpleCrud\Query;
5
6
use InvalidArgumentException;
7
use PDO;
8
use SimpleCrud\Table;
9
10
final class SelectAggregate implements QueryInterface
11
{
12
    use Traits\Common;
13
    use Traits\HasRelatedWith;
14
    use Traits\HasPagination;
15
    use Traits\HasJoinRelation;
16
17
    private $field;
18
    private const AGGREGATION_FUNCTIONS = [
19
        'AVG',
20
        'COUNT',
21
        'MAX',
22
        'MIN',
23
        'SUM',
24
    ];
25
    private $allowedMethods = [
26
        'from',
27
        'join',
28
        'catJoin',
29
        'groupBy',
30
        'having',
31
        'orHaving',
32
        'orderBy',
33
        'catHaving',
34
        'where',
35
        'orWhere',
36
        'catWhere',
37
        'limit',
38
        'offset',
39
        'distinct',
40
        'forUpdate',
41
        'setFlag',
42
    ];
43
44
    public function __construct(Table $table, string $function, string $field = 'id')
45
    {
46
        $this->table = $table;
47
        $this->field = $field;
48
49
        $function = strtoupper($function);
50
51
        if (!in_array($function, self::AGGREGATION_FUNCTIONS)) {
52
            throw InvalidArgumentException(
53
                sprintf('Invalid aggregation function. Must be one of the followings: %s', implode(', ', self::AGGREGATION_FUNCTIONS))
54
            );
55
        }
56
57
        $this->query = $table->getDatabase()
58
            ->select()
59
            ->from((string) $table)
60
            ->columns(sprintf('%s(%s)', $function, $field));
61
    }
62
63
    public function run()
64
    {
65
        $statement = $this->__invoke();
66
        $statement->setFetchMode(PDO::FETCH_NUM);
67
68
        $field = $this->table->{$this->field};
69
70
        return $field->format($statement->fetchColumn());
71
    }
72
}
73