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

AggregationTrait   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 59
Duplicated Lines 28.81 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 1
dl 17
loc 59
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A field() 0 6 1
A run() 0 7 1
A __invoke() 7 7 1
A __toString() 10 10 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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