Count::toString()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 7
ccs 5
cts 5
cp 1
rs 9.4286
c 1
b 0
f 1
cc 1
eloc 4
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Muffin\Queries\Snippets;
4
5
use Muffin\Snippet;
6
7
class Count implements Snippet, Selectable
8
{
9
    private
10
        $columnName,
11
        $alias;
12
13 11
    public function __construct($columnName, $alias = null)
14
    {
15 11
        if((! $columnName instanceof Snippet) && empty($columnName))
16 11
        {
17 2
            throw new \InvalidArgumentException('Empty column name.');
18
        }
19
20 9
        $this->columnName = $columnName;
21 9
        $this->alias = $alias;
22 9
    }
23
24 9
    public function toString()
25
    {
26 9
        return implode(' ', array_filter(array(
27 9
            $this->buildCountSnippet(),
28 9
            $this->buildAliasSnippet()
29 9
        )));
30
    }
31
32 9
    private function buildCountSnippet()
33
    {
34 9
        $columnName = $this->columnName;
35
36 9
        if($columnName instanceof Snippet)
37 9
        {
38 5
            $columnName = $columnName->toString();
39 5
        }
40
41 9
        return sprintf('COUNT(%s)', $columnName);
42
    }
43
44 9
    private function buildAliasSnippet()
45
    {
46 9
        $alias = $this->alias;
47
48 9
        if(! empty($alias))
49 9
        {
50 6
            return sprintf('AS %s', $alias);
51
        }
52 3
    }
53
}
54