Passed
Push — master ( c4f127...730a00 )
by Sergei
24:33 queued 20:27
created

ColumnSchema::phpTypecastComposite()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 25
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 12
nc 8
nop 1
dl 0
loc 25
ccs 13
cts 13
cp 1
crap 5
rs 9.5555
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[] Columns metadata of the composite type.
66
     * @psalm-var array<string, ColumnSchemaInterface>
67
     */
68
    private array $columns = [];
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 104
    public function dbTypecast(mixed $value): mixed
80
    {
81 104
        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) {
0 ignored issues
show
Bug introduced by
The type Yiisoft\Db\Pgsql\Schema was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

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