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 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 7
c 0
b 0
f 0
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 0
crap 1
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace Puzzle\QueryBuilder\Queries\Snippets;
6
7
use Puzzle\QueryBuilder\Snippet;
8
9
class Count implements Snippet, Selectable
10
{
11
    private
12
        $columnName,
1 ignored issue
show
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
Coding Style introduced by
The visibility should be declared for property $columnName.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
13
        $alias;
14
15
    /**
16
     * @param Snippet|string $columnName
17
     */
18 11
    public function __construct($columnName, ?string $alias = null)
19
    {
20 11
        if((! $columnName instanceof Snippet) && empty($columnName))
21
        {
22 2
            throw new \InvalidArgumentException('Empty column name.');
23
        }
24
25 9
        $this->columnName = $columnName;
26 9
        $this->alias = $alias;
27 9
    }
28
29 9
    public function toString(): string
30
    {
31 9
        return implode(' ', array_filter(array(
32 9
            $this->buildCountSnippet(),
33 9
            $this->buildAliasSnippet()
34
        )));
35
    }
36
37 9
    private function buildCountSnippet(): string
38
    {
39 9
        $columnName = $this->columnName;
40
41 9
        if($columnName instanceof Snippet)
42
        {
43 5
            $columnName = $columnName->toString();
44
        }
45
46 9
        return sprintf('COUNT(%s)', $columnName);
47
    }
48
49 9
    private function buildAliasSnippet(): string
50
    {
51 9
        $alias = $this->alias;
52
53 9
        if(! empty($alias))
54
        {
55 6
            return sprintf('AS %s', $alias);
56
        }
57
58 3
        return '';
59
    }
60
}
61