Passed
Push — master ( 0ce2d3...012822 )
by Alexander
01:00
created

QueryHelper::caseWhen()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 16
ccs 8
cts 8
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 4
nop 3
crap 3
1
<?php
2
3
namespace Horat1us\Yii\Helpers;
4
5
use yii\db\Expression;
6
7
/**
8
 * Class QueryHelper
9
 * @package Horat1us\Yii\Helpers
10
 */
11
class QueryHelper
12
{
13
    /**
14
     * @param string $sqlMethod
15
     * @param mixed[] $params
16
     * @return Expression
17
     */
18
    public static function sqlCall(string $sqlMethod, ...$params): Expression
19
    {
20 3
        $expressions = implode(', ', array_map(function ($expression) {
21 3
            return "({$expression})";
22 3
        }, (array)$params));
23
24 3
        $command = "{$sqlMethod}({$expressions})";
25
26 3
        return new Expression($command);
27
    }
28
29
    /**
30
     * Only for PostgreSQL
31
     *
32
     * @param array ...$params
33
     * @return Expression
34
     */
35 1
    public static function coalesce(...$params): Expression
36
    {
37 1
        return static::sqlCall('COALESCE', ...$params);
38
    }
39
40
    /**
41
     * @param array $cases
42
     * @param string|null $value
43
     * @param string|null $else
44
     * @return string
45
     */
46 3
    public static function caseWhen(array $cases, string $value = '', string $else = null): string
47
    {
48 3
        $command = "CASE {$value}";
49
50 3
        foreach ($cases as $condition => $statement) {
51 3
            $command .= " WHEN {$condition} THEN {$statement}";
52
        }
53
54 3
        if ($else) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $else of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
55 1
            $command .= " ELSE {$else}";
56
        }
57
58 3
        $command .= " END";
59
60 3
        return new Expression($command);
61
    }
62
}