Aggregate::getValue()   A
last analyzed

Complexity

Conditions 3
Paths 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 5
nc 1
nop 2
dl 0
loc 6
rs 10
c 1
b 0
f 0
ccs 6
cts 6
cp 1
crap 3
1
<?php
2
/**
3
 * @author Todd Burry <[email protected]>
4
 * @copyright 2009-2017 Vanilla Forums Inc.
5
 * @license MIT
6
 */
7
8
namespace Garden\Db;
9
10
/**
11
 * Represents an aggregate function call.
12
 *
13
 * Use an aggregate by passing an instance as a value in the "columns" option on a call to {@link Db::get()}.
14
 */
15
class Aggregate extends Literal {
16
    const AVG = 'avg';
17
    const COUNT = 'count';
18
    const COUNT_DISTINCT = 'count-distinct';
19
    const MAX = 'max';
20
    const MIN = 'min';
21
    const SUM = 'sum';
22
23
    private $func;
24
    private $column;
25
    private $alias;
26
27
    /**
28
     * Construct an {@link Aggregate} object.
29
     *
30
     * @param string $func The name of the aggregate function. Use one of the **Aggregate::*** constants.
31
     * @param string $column The name of the column to aggregate.
32
     * @param string $alias The alias of the aggregate. If left out then the function name will be used as the alias.
33
     */
34 6
    public function __construct($func, $column, $alias = '') {
35 6
        $format = '%1$s(%2$s) as %3$s';
36 6
        if ($func === static::COUNT_DISTINCT) {
37
            $format = '%1$s(distinct %2$s) as %3$s';
38
            $func = static::COUNT;
39
        }
40
41 6
        parent::__construct($format);
42
43 6
        $this->func = $func;
44 6
        $this->column = $column;
45 6
        $this->alias = $alias;
46 6
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51 6
    public function getValue(Db $db, ...$args) {
52 6
        return parent::getValue(
53 6
            $db,
54 6
            $this->func,
55 6
            $this->column === '*' ? '*' : $db->escape($this->column),
56 6
            $db->escape($this->alias ?: $this->func)
57
        );
58
    }
59
}
60