Passed
Pull Request — master (#303)
by
unknown
03:40
created

ColumnSchema::phpTypecastComposite()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 31
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 13
nc 8
nop 1
dl 0
loc 31
ccs 14
cts 14
cp 1
crap 5
rs 9.5222
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Pgsql;
6
7
use JsonException;
8
use PDO;
9
use Yiisoft\Db\Command\Param;
10
use Yiisoft\Db\Expression\ArrayExpression;
11
use Yiisoft\Db\Expression\ExpressionInterface;
12
use Yiisoft\Db\Expression\JsonExpression;
13
use Yiisoft\Db\Pgsql\Composite\CompositeExpression;
14
use Yiisoft\Db\Pgsql\Composite\CompositeParser;
15
use Yiisoft\Db\Schema\AbstractColumnSchema;
16
use Yiisoft\Db\Schema\ColumnSchemaInterface;
17
use Yiisoft\Db\Schema\SchemaInterface;
18
19
use function array_walk_recursive;
20
use function bindec;
21
use function decbin;
22
use function is_array;
23
use function is_int;
24
use function is_string;
25
use function json_decode;
26
use function str_pad;
27
28
/**
29
 * Represents the metadata of a column in a database table for PostgreSQL Server.
30
 *
31
 * It provides information about the column's name, type, size, precision, and other details.
32
 *
33
 * It's used to store and retrieve metadata about a column in a database table and is typically used in conjunction with
34
 * the {@see TableSchema}, which represents the metadata of a database table as a whole.
35
 *
36
 * The following code shows how to use:
37
 *
38
 * ```php
39
 * use Yiisoft\Db\Pgsql\ColumnSchema;
40
 *
41
 * $column = new ColumnSchema();
42
 * $column->name('id');
43
 * $column->allowNull(false);
44
 * $column->dbType('integer');
45
 * $column->phpType('integer');
46
 * $column->type('integer');
47
 * $column->defaultValue(0);
48
 * $column->autoIncrement(true);
49
 * $column->primaryKey(true);
50
 * ```
51
 */
52
final class ColumnSchema extends AbstractColumnSchema
53
{
54
    /**
55
     * @var int The dimension of array. Defaults to 0, means this column isn't an array.
56
     */
57
    private int $dimension = 0;
58
59
    /**
60
     * @var string|null Name of an associated sequence if column is auto incremental.
61
     */
62
    private string|null $sequenceName = null;
63
64
    /**
65
     * @var ColumnSchemaInterface[]|null Columns metadata of the composite type.
66
     * @psalm-var array<string, ColumnSchemaInterface>|null
67
     */
68
    private array|null $columns = null;
69
70
    /**
71
     * Converts the input value according to {@see type} and {@see dbType} for use in a db query.
72
     *
73
     * If the value is null or an {@see Expression}, it won't be converted.
74
     *
75
     * @param mixed $value input value
76
     *
77
     * @return mixed Converted value. This may also be an array containing the value as the first element and the PDO
78
     * type as the second element.
79
     */
80 90
    public function dbTypecast(mixed $value): mixed
81
    {
82 90
        if ($this->dimension > 0) {
83 4
            if ($value === null || $value instanceof ExpressionInterface) {
84 2
                return $value;
85
            }
86
87 3
            if ($this->getType() === Schema::TYPE_COMPOSITE) {
88 1
                $value = $this->dbTypecastArray($value, $this->dimension);
89
            }
90
91 3
            return new ArrayExpression($value, $this->getDbType(), $this->dimension);
92
        }
93
94 89
        return $this->dbTypecastValue($value);
95
    }
96
97
    /**
98
     * @param int $dimension Should be more than 0
99
     */
100 1
    private function dbTypecastArray(mixed $value, int $dimension): array
101
    {
102 1
        $items = [];
103
104 1
        if (!is_iterable($value)) {
105 1
            return $items;
106
        }
107
108
        /** @psalm-var mixed $val */
109 1
        foreach ($value as $val) {
110 1
            if ($dimension > 1) {
111 1
                $items[] = $this->dbTypecastArray($val, $dimension - 1);
112
            } else {
113
                /** @psalm-suppress MixedAssignment */
114 1
                $items[] = $this->dbTypecastValue($val);
115
            }
116
        }
117
118 1
        return $items;
119
    }
120
121 89
    private function dbTypecastValue(mixed $value): mixed
122
    {
123 89
        if ($value === null || $value instanceof ExpressionInterface) {
124 30
            return $value;
125
        }
126
127 84
        return match ($this->getType()) {
128 84
            SchemaInterface::TYPE_JSON => new JsonExpression($value, $this->getDbType()),
129
130 84
            SchemaInterface::TYPE_BINARY => is_string($value)
131 3
                ? new Param($value, PDO::PARAM_LOB) // explicitly setup PDO param type for binary column
132 3
                : $this->typecast($value),
133
134 84
            Schema::TYPE_BIT => is_int($value)
135 1
                ? str_pad(decbin($value), (int) $this->getSize(), '0', STR_PAD_LEFT)
136 1
                : $this->typecast($value),
137
138 84
            Schema::TYPE_COMPOSITE => new CompositeExpression($value, $this->getDbType(), $this->columns),
139
140 84
            default => $this->typecast($value),
141 84
        };
142
    }
143
144
    /**
145
     * Converts the input value according to {@see phpType} after retrieval from the database.
146
     *
147
     * If the value is null or an {@see Expression}, it won't be converted.
148
     *
149
     * @param mixed $value The input value
150
     *
151
     * @throws JsonException
152
     *
153
     * @return mixed The converted value
154
     */
155 97
    public function phpTypecast(mixed $value): mixed
156
    {
157 97
        if ($this->dimension > 0) {
158 12
            if (is_string($value)) {
159 12
                $value = $this->getArrayParser()->parse($value);
160
            }
161
162 12
            if (is_array($value)) {
163 12
                array_walk_recursive($value, function (string|null &$val) {
164
                    /** @psalm-var mixed $val */
165 12
                    $val = $this->phpTypecastValue($val);
166 12
                });
167
            } else {
168 1
                return null;
169
            }
170
171 12
            return $value;
172
        }
173
174 91
        return $this->phpTypecastValue($value);
175
    }
176
177
    /**
178
     * Casts $value after retrieving from the DBMS to PHP representation.
179
     *
180
     * @throws JsonException
181
     */
182 97
    protected function phpTypecastValue(mixed $value): mixed
183
    {
184 97
        if ($value === null) {
185 11
            return null;
186
        }
187
188 97
        return match ($this->getType()) {
189 97
            Schema::TYPE_BIT => is_string($value) ? bindec($value) : $value,
190
191 97
            SchemaInterface::TYPE_BOOLEAN => $value && $value !== 'f',
192
193 97
            SchemaInterface::TYPE_JSON
194 97
                => json_decode((string) $value, true, 512, JSON_THROW_ON_ERROR),
195
196 97
            Schema::TYPE_COMPOSITE => $this->phpTypecastComposite($value),
197
198 97
            default => parent::phpTypecast($value),
199 97
        };
200
    }
201
202 5
    private function phpTypecastComposite(mixed $value): array|null
203
    {
204 5
        if (is_string($value)) {
205 5
            $value = $this->getCompositeParser()->parse($value);
206
        }
207
208 5
        if (!is_iterable($value)) {
209 1
            return null;
210
        }
211
212 5
        $fields = [];
213 5
        $columns = (array) $this->columns;
214 5
        $columnNames = array_keys($columns);
215
216
        /**
217
         * @psalm-var int|string $columnName
218
         * @psalm-var mixed $item
219
         */
220 5
        foreach ($value as $columnName => $item) {
221 5
            $columnName = $columnNames[$columnName] ?? $columnName;
222
223 5
            if (isset($columns[$columnName])) {
224
                /** @psalm-var mixed $item */
225 5
                $item = $columns[$columnName]->phpTypecast($item);
226
            }
227
228
            /** @psalm-suppress MixedAssignment */
229 5
            $fields[$columnName] = $item;
230
        }
231
232 5
        return $fields;
233
    }
234
235
    /**
236
     * Creates instance of ArrayParser.
237
     */
238 12
    protected function getArrayParser(): ArrayParser
239
    {
240 12
        return new ArrayParser();
241
    }
242
243
    /**
244
     * @return int Get the dimension of the array.
245
     *
246
     * Defaults to 0, means this column isn't an array.
247
     */
248 6
    public function getDimension(): int
249
    {
250 6
        return $this->dimension;
251
    }
252
253
    /**
254
     * @return string|null name of an associated sequence if column is auto incremental.
255
     */
256 99
    public function getSequenceName(): string|null
257
    {
258 99
        return $this->sequenceName;
259
    }
260
261
    /**
262
     * Set dimension of an array.
263
     *
264
     * Defaults to 0, means this column isn't an array.
265
     */
266 160
    public function dimension(int $dimension): void
267
    {
268 160
        $this->dimension = $dimension;
269
    }
270
271
    /**
272
     * Set the name of an associated sequence if a column is auto incremental.
273
     */
274 84
    public function sequenceName(string|null $sequenceName): void
275
    {
276 84
        $this->sequenceName = $sequenceName;
277
    }
278
279
    /**
280
     * @param ColumnSchemaInterface[]|null $columns The columns metadata of the composite type.
281
     * @psalm-param array<string, ColumnSchemaInterface>|null $columns
282
     */
283 5
    public function columns(array|null $columns): void
284
    {
285 5
        $this->columns = $columns;
286
    }
287
288
    /**
289
     * @return ColumnSchemaInterface[]|null Columns metadata of the composite type.
290
     */
291 5
    public function getColumns(): array|null
292
    {
293 5
        return $this->columns;
294
    }
295
296
    /**
297
     * Creates instance of CompositeParser.
298
     */
299 5
    private function getCompositeParser(): CompositeParser
300
    {
301 5
        return new CompositeParser();
302
    }
303
}
304