Passed
Pull Request — master (#303)
by
unknown
05:45 queued 01:27
created

ColumnSchema::getSequenceName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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.
78
     */
79 91
    public function dbTypecast(mixed $value): mixed
80
    {
81 91
        if ($this->dimension > 0) {
82 4
            if ($value === null || $value instanceof ExpressionInterface) {
83 2
                return $value;
84
            }
85
86 3
            if ($this->getType() === Schema::TYPE_COMPOSITE) {
87 1
                $value = $this->dbTypecastArray($value, $this->dimension);
88
            }
89
90 3
            return new ArrayExpression($value, $this->getDbType(), $this->dimension);
91
        }
92
93 90
        return $this->dbTypecastValue($value);
94
    }
95
96
    /**
97
     * Recursively converts array values for use in a db query.
98
     *
99
     * @param mixed $value The array or iterable object.
100
     * @param int $dimension The array dimension. Should be more than 0.
101
     *
102
     * @return array Converted values.
103
     */
104 1
    private function dbTypecastArray(mixed $value, int $dimension): array
105
    {
106 1
        $items = [];
107
108 1
        if (!is_iterable($value)) {
109 1
            return $items;
110
        }
111
112
        /** @psalm-var mixed $val */
113 1
        foreach ($value as $val) {
114 1
            if ($dimension > 1) {
115 1
                $items[] = $this->dbTypecastArray($val, $dimension - 1);
116
            } else {
117
                /** @psalm-suppress MixedAssignment */
118 1
                $items[] = $this->dbTypecastValue($val);
119
            }
120
        }
121
122 1
        return $items;
123
    }
124
125
    /**
126
     * Converts the input value for use in a db query.
127
     */
128 90
    private function dbTypecastValue(mixed $value): mixed
129
    {
130 90
        if ($value === null || $value instanceof ExpressionInterface) {
131 30
            return $value;
132
        }
133
134 85
        return match ($this->getType()) {
135 85
            SchemaInterface::TYPE_JSON => new JsonExpression($value, $this->getDbType()),
136
137 85
            SchemaInterface::TYPE_BINARY => is_string($value)
138 3
                ? new Param($value, PDO::PARAM_LOB) // explicitly setup PDO param type for binary column
139 3
                : $this->typecast($value),
140
141 85
            Schema::TYPE_BIT => is_int($value)
142 1
                ? str_pad(decbin($value), (int) $this->getSize(), '0', STR_PAD_LEFT)
143 2
                : (string) $value,
144
145 85
            Schema::TYPE_COMPOSITE => new CompositeExpression($value, $this->getDbType(), $this->columns),
146
147 85
            default => $this->typecast($value),
148 85
        };
149
    }
150
151
    /**
152
     * Converts the input value according to {@see phpType} after retrieval from the database.
153
     *
154
     * If the value is null or an {@see Expression}, it won't be converted.
155
     *
156
     * @param mixed $value The input value
157
     *
158
     * @throws JsonException
159
     *
160
     * @return mixed The converted value
161
     */
162 98
    public function phpTypecast(mixed $value): mixed
163
    {
164 98
        if ($this->dimension > 0) {
165 12
            if (is_string($value)) {
166 12
                $value = $this->getArrayParser()->parse($value);
167
            }
168
169 12
            if (!is_array($value)) {
170 1
                return null;
171
            }
172
173 12
            array_walk_recursive($value, function (mixed &$val) {
174
                /** @psalm-var mixed $val */
175 12
                $val = $this->phpTypecastValue($val);
176 12
            });
177
178 12
            return $value;
179
        }
180
181 92
        return $this->phpTypecastValue($value);
182
    }
183
184
    /**
185
     * Casts $value after retrieving from the DBMS to PHP representation.
186
     *
187
     * @throws JsonException
188
     */
189 98
    private function phpTypecastValue(mixed $value): mixed
190
    {
191 98
        if ($value === null) {
192 11
            return null;
193
        }
194
195 98
        return match ($this->getType()) {
196 98
            Schema::TYPE_BIT => is_string($value) ? bindec($value) : $value,
197
198 98
            SchemaInterface::TYPE_BOOLEAN => $value && $value !== 'f',
199
200 98
            SchemaInterface::TYPE_JSON
201 98
                => json_decode((string) $value, true, 512, JSON_THROW_ON_ERROR),
202
203 98
            Schema::TYPE_COMPOSITE => $this->phpTypecastComposite($value),
204
205 98
            default => parent::phpTypecast($value),
206 98
        };
207
    }
208
209
    /**
210
     * Converts the input value according to the composite type after retrieval from the database.
211
     */
212 5
    private function phpTypecastComposite(mixed $value): array|null
213
    {
214 5
        if (is_string($value)) {
215 5
            $value = $this->getCompositeParser()->parse($value);
216
        }
217
218 5
        if (!is_iterable($value)) {
219 1
            return null;
220
        }
221
222 5
        $fields = [];
223 5
        $columns = (array) $this->columns;
224 5
        $columnNames = array_keys($columns);
225
226
        /**
227
         * @psalm-var int|string $columnName
228
         * @psalm-var mixed $item
229
         */
230 5
        foreach ($value as $columnName => $item) {
231 5
            $columnName = $columnNames[$columnName] ?? $columnName;
232
233 5
            if (isset($columns[$columnName])) {
234
                /** @psalm-var mixed $item */
235 5
                $item = $columns[$columnName]->phpTypecast($item);
236
            }
237
238
            /** @psalm-suppress MixedAssignment */
239 5
            $fields[$columnName] = $item;
240
        }
241
242 5
        return $fields;
243
    }
244
245
    /**
246
     * Creates instance of ArrayParser.
247
     */
248 12
    private function getArrayParser(): ArrayParser
249
    {
250 12
        return new ArrayParser();
251
    }
252
253
    /**
254
     * @return int Get the dimension of the array.
255
     *
256
     * Defaults to 0, means this column isn't an array.
257
     */
258 6
    public function getDimension(): int
259
    {
260 6
        return $this->dimension;
261
    }
262
263
    /**
264
     * @return string|null name of an associated sequence if column is auto incremental.
265
     */
266 99
    public function getSequenceName(): string|null
267
    {
268 99
        return $this->sequenceName;
269
    }
270
271
    /**
272
     * Set dimension of an array.
273
     *
274
     * Defaults to 0, means this column isn't an array.
275
     */
276 161
    public function dimension(int $dimension): void
277
    {
278 161
        $this->dimension = $dimension;
279
    }
280
281
    /**
282
     * Set the name of an associated sequence if a column is auto incremental.
283
     */
284 84
    public function sequenceName(string|null $sequenceName): void
285
    {
286 84
        $this->sequenceName = $sequenceName;
287
    }
288
289
    /**
290
     * Set columns of the composite type.
291
     *
292
     * @param ColumnSchemaInterface[]|null $columns The metadata of the composite type columns.
293
     * @psalm-param array<string, ColumnSchemaInterface>|null $columns
294
     */
295 5
    public function columns(array|null $columns): void
296
    {
297 5
        $this->columns = $columns;
298
    }
299
300
    /**
301
     * Get the metadata of the composite type columns.
302
     *
303
     * @return ColumnSchemaInterface[]|null
304
     */
305 5
    public function getColumns(): array|null
306
    {
307 5
        return $this->columns;
308
    }
309
310
    /**
311
     * Creates instance of `CompositeParser`.
312
     */
313 5
    private function getCompositeParser(): CompositeParser
314
    {
315 5
        return new CompositeParser();
316
    }
317
}
318