InlineParameterFormatter::formatParameters()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.0119

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 10
cts 11
cp 0.9091
rs 9.6
c 0
b 0
f 0
cc 4
nc 4
nop 2
crap 4.0119
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\Migrations;
6
7
use Doctrine\DBAL\Connection;
8
use Doctrine\DBAL\Types\Type;
9
use function array_map;
10
use function implode;
11
use function is_array;
12
use function is_bool;
13
use function is_int;
14
use function is_string;
15
use function sprintf;
16
17
/**
18
 * The InlineParameterFormatter class is responsible for formatting SQL query parameters to a string
19
 * for display output.
20
 *
21
 * @internal
22
 */
23
final class InlineParameterFormatter implements ParameterFormatter
24
{
25
    /** @var Connection */
26
    private $connection;
27
28 2
    public function __construct(Connection $connection)
29
    {
30 2
        $this->connection = $connection;
31 2
    }
32
33
    /**
34
     * @param mixed[] $params
35
     * @param mixed[] $types
36
     */
37 1
    public function formatParameters(array $params, array $types) : string
38
    {
39 1
        if ($params === []) {
40
            return '';
41
        }
42
43 1
        $formattedParameters = [];
44
45 1
        foreach ($params as $key => $value) {
46 1
            $type = $types[$key] ?? 'string';
47
48 1
            $formattedParameter = '[' . $this->formatParameter($value, $type) . ']';
49
50 1
            $formattedParameters[] = is_string($key)
51 1
                ? sprintf(':%s => %s', $key, $formattedParameter)
52 1
                : $formattedParameter;
53
        }
54
55 1
        return sprintf('with parameters (%s)', implode(', ', $formattedParameters));
56
    }
57
58
    /**
59
     * @param string|int $value
60
     * @param string|int $type
61
     *
62
     * @return string|int
63
     */
64 1
    private function formatParameter($value, $type)
65
    {
66 1
        if (is_string($type) && Type::hasType($type)) {
67 1
            return Type::getType($type)->convertToDatabaseValue(
68 1
                $value,
69 1
                $this->connection->getDatabasePlatform()
70
            );
71
        }
72
73 1
        return $this->parameterToString($value);
74
    }
75
76
    /**
77
     * @param int[]|bool[]|string[]|array|int|string|bool $value
78
     */
79 1
    private function parameterToString($value) : string
80
    {
81 1
        if (is_array($value)) {
82
            return implode(', ', array_map(function ($value) : string {
83 1
                return $this->parameterToString($value);
84 1
            }, $value));
85
        }
86
87 1
        if (is_int($value) || is_string($value)) {
88 1
            return (string) $value;
89
        }
90
91 1
        if (is_bool($value)) {
92 1
            return $value === true ? 'true' : 'false';
93
        }
94
    }
95
}
96