Passed
Push — trunk ( ff423b...970276 )
by Christian
13:19 queued 19s
created

SqlHelper::object()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 13
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Shopware\Core\Framework\DataAbstractionLayer\Dbal;
4
5
use Shopware\Core\Framework\Log\Package;
6
7
/**
8
 * @description This class is used to build a select part of a SQL.
9
 *
10
 * @final
11
 */
12
#[Package('core')]
13
class SqlHelper
14
{
15
    /**
16
     * @description This function is used to build the json_object of the select part of a query.
17
     *
18
     * @param array<string, string> $fields The key is the alias of the column, the value is the column itself
19
     *
20
     * @example
21
     *
22
     * $fields = [ 'id' => 'product.id', 'name' => 'product.name' ];
23
     * $select = EntityDefinitionQueryHelper::object($fields, 'product');
24
     * // $select = "JSON_OBJECT('id', product.id, 'name', product.name) as product";
25
     */
26
    public static function object(array $fields, string $alias): string
27
    {
28
        $columnSelectSql = '';
29
30
        foreach ($fields as $columnAlias => $column) {
31
            $columnSelectSql .= sprintf('\'%s\', %s,', $columnAlias, $column);
32
        }
33
34
        $columnSelectSql = rtrim($columnSelectSql, ',');
35
36
        $sql = 'JSON_OBJECT(%s) as %s';
37
38
        return sprintf($sql, $columnSelectSql, $alias);
39
    }
40
41
    /**
42
     * @description This function is used to build the json_array of the select part of a query.
43
     *
44
     * @param array<int|string, string> $fields The key is the alias of the column, the value is the column itself
45
     *
46
     * @example
47
     *
48
     * $fields = [ 'id' => 'tags.id', 'name' => 'tags.name' ];
49
     * $select = EntityDefinitionQueryHelper::object($fields, 'tags');
50
     * // $select = "CONCAT('[', GROUP_CONCAT(DISTINCT JSON_OBJECT('id', tags.id, 'name', tags.name)), ']') as tags";
51
     */
52
    public static function objectArray(array $fields, string $alias): string
53
    {
54
        $columnSelectSql = '';
55
56
        foreach ($fields as $columnAlias => $column) {
57
            $columnSelectSql .= sprintf('\'%s\', %s,', $columnAlias, $column);
58
        }
59
60
        $columnSelectSql = rtrim($columnSelectSql, ',');
61
62
        $sql = <<<EOF
63
CONCAT(
64
    '[',
65
         GROUP_CONCAT(DISTINCT
66
             JSON_OBJECT(
67
                %s
68
             )
69
         ),
70
    ']'
71
) as %s
72
EOF;
73
74
        return sprintf($sql, $columnSelectSql, $alias);
75
    }
76
}
77