ColumnSchema::dbTypecast()   A
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 6
c 0
b 0
f 0
nc 5
nop 1
dl 0
loc 12
ccs 7
cts 7
cp 1
crap 6
rs 9.2222
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Mssql;
6
7
use Yiisoft\Db\Command\ParamInterface;
8
use Yiisoft\Db\Expression\Expression;
9
use Yiisoft\Db\Schema\AbstractColumnSchema;
10
use Yiisoft\Db\Schema\SchemaInterface;
11
12
use function bin2hex;
13
use function is_string;
14
15
/**
16
 * Represents the metadata of a column in a database table for MSSQL Server.
17
 *
18
 * It provides information about the column's name, type, size, precision, and other details.
19
 *
20
 * Is used to store and retrieve metadata about a column in a database table. It's typically used in conjunction with
21
 * the {@see TableSchema}, which represents the metadata of a database table as a whole.
22
 *
23
 * The following code shows how to use:
24
 *
25
 * ```php
26
 * use Yiisoft\Db\Mssql\ColumnSchema;
27
 *
28
 * $column = new ColumnSchema();
29
 * $column->name('id');
30
 * $column->allowNull(false);
31
 * $column->dbType('int');
32
 * $column->phpType('integer');
33
 * $column->type('integer');
34
 * $column->defaultValue(0);
35
 * $column->autoIncrement(true);
36
 * $column->primaryKey(true);
37
 * ```
38
 */
39
final class ColumnSchema extends AbstractColumnSchema
40
{
41 156
    public function dbTypecast(mixed $value): mixed
42
    {
43 156
        if ($this->getType() === SchemaInterface::TYPE_BINARY && $this->getDbType() === 'varbinary') {
44 7
            if ($value instanceof ParamInterface && is_string($value->getValue())) {
45 1
                $value = (string) $value->getValue();
46
            }
47 7
            if (is_string($value)) {
48 7
                return new Expression('CONVERT(VARBINARY(MAX), ' . ('0x' . bin2hex($value)) . ')');
49
            }
50
        }
51
52 156
        return parent::dbTypecast($value);
53
    }
54
}
55