Completed
Push — master ( bd4750...88eef9 )
by Oscar
12s
created

AggregationTrait::__invoke()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 7
Ratio 100 %

Importance

Changes 0
Metric Value
dl 7
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
1
<?php
2
3
namespace SimpleCrud\Queries\Mysql;
4
5
use PDO;
6
7
/**
8
 * Trait with common funcions used in aggregation queries (min,max,avg,count,sum).
9
 *
10
 * @property \SimpleCrud\Table $table
11
 */
12
trait AggregationTrait
13
{
14
    use ExtendedSelectionTrait;
15
    protected $field;
16
17
    /**
18
     * Set the field name to sum over.
19
     *
20
     * @param string $field
21
     *
22
     * @return self
23
     */
24
    public function field($field)
25
    {
26
        $this->field = $field;
27
28
        return $this;
29
    }
30
31
    /**
32
     * Run the query and return the value.
33
     * 
34
     * @return int
35
     */
36
    public function run()
37
    {
38
        $result = $this->__invoke()->fetch();
39
        $field = $this->table->{$this->field};
40
        
41
        return $field->dataFromDatabase($result[0]);
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47 View Code Duplication
    public function __invoke()
48
    {
49
        $statement = $this->table->getDatabase()->execute((string) $this, $this->marks);
50
        $statement->setFetchMode(PDO::FETCH_NUM);
51
52
        return $statement;
53
    }
54
55
    /**
56
     * Build and return the query.
57
     *
58
     * @return string
59
     */
60 View Code Duplication
    public function __toString()
61
    {
62
        $query = "SELECT ".self::AGGREGATION_FUNCTION."(`{$this->field}`) FROM `{$this->table->getName()}`";
63
64
        $query .= $this->fromToString();
65
        $query .= $this->whereToString();
66
        $query .= $this->limitToString();
67
68
        return $query;
69
    }
70
}
71