Select   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 76
wmc 14
lcom 1
cbo 0
ccs 40
cts 40
cp 1
rs 10
c 1
b 0
f 1

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A select() 0 6 1
A toString() 0 9 2
A buildColumnsString() 0 16 3
A addColumns() 0 8 1
A validateColumns() 0 10 4
A ensureIsArray() 0 9 2
1
<?php
2
3
namespace Muffin\Queries\Snippets;
4
5
use Muffin\Snippet;
6
7
class Select implements Snippet
8
{
9
    private
10
        $columns;
11
12 33
    public function __construct($columns = array())
13
    {
14 33
        $this->columns = array();
15
16 33
        $this->addColumns($columns);
17 32
    }
18
19 28
    public function select($columns)
0 ignored issues
show
Best Practice introduced by
Using PHP4-style constructors that are named like the class is not recommend; better use the more explicit __construct method.
Loading history...
20
    {
21 28
        $this->addColumns($columns);
22
23 28
        return $this;
24
    }
25
26 31
    public function toString()
27
    {
28 31
        if(empty($this->columns))
29 31
        {
30 2
            throw new \LogicException('No columns defined for SELECT clause');
31
        }
32
33 29
        return sprintf('SELECT %s', $this->buildColumnsString());
34
    }
35
36 29
    private function buildColumnsString()
37
    {
38 29
        $columns = array();
39
40 29
        foreach($this->columns as $column)
41
        {
42 29
            if($column instanceof Selectable)
43 29
            {
44 2
                $column = $column->toString();
45 2
            }
46
47 29
            $columns[] = $column;
48 29
        }
49
50 29
        return implode(', ', array_unique($columns));
51
    }
52
53 33
    private function addColumns($columns)
54
    {
55 33
        $columns = array_filter($this->ensureIsArray($columns));
56
57 33
        $this->validateColumns($columns);
58
59 32
        $this->columns = array_merge($this->columns, $columns);
60 32
    }
61
62 33
    private function validateColumns($columns)
63
    {
64 33
        foreach($columns as $column)
65
        {
66 31
            if(! is_string($column) && (!$column instanceof Selectable))
67 31
            {
68 1
                throw new \InvalidArgumentException('Column name must be a string.');
69
            }
70 33
        }
71 32
    }
72
73 33
    private function ensureIsArray($select)
74
    {
75 33
        if(! is_array($select))
76 33
        {
77 21
            $select = array($select);
78 21
        }
79
80 33
        return $select;
81
    }
82
}
83