Completed
Push — master ( 037c01...3910ea )
by Oscar
01:42
created

SelectAggregate   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 7
dl 0
loc 62
rs 10
c 0
b 0
f 0

2 Methods

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