Passed
Pull Request — dev (#77)
by Def
38:49 queued 06:58
created

CommandPDO::insertEx()   B

Complexity

Conditions 7
Paths 18

Size

Total Lines 53
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 7.0199

Importance

Changes 0
Metric Value
cc 7
eloc 29
nc 18
nop 2
dl 0
loc 53
ccs 25
cts 27
cp 0.9259
crap 7.0199
rs 8.5226
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Db\Oracle;
6
7
use PDO;
8
use PDOException;
9
use Yiisoft\Db\Command\ParamInterface;
10
use Yiisoft\Db\Driver\PDO\CommandPDO as AbstractCommandPDO;
11
use Yiisoft\Db\Exception\ConvertException;
12
use Yiisoft\Db\QueryBuilder\QueryBuilder;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Yiisoft\Db\Oracle\QueryBuilder. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
13
use Yiisoft\Db\QueryBuilder\QueryBuilderInterface;
14
use Yiisoft\Db\Schema\Schema;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Yiisoft\Db\Oracle\Schema. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
15
use Yiisoft\Db\Schema\SchemaInterface;
16
17
use function array_keys;
18
use function count;
19
use function implode;
20
use function strlen;
21
22
/**
23
 * Command represents an Oracle SQL statement to be executed against a database.
24
 */
25
final class CommandPDO extends AbstractCommandPDO
26
{
27 183
    public function queryBuilder(): QueryBuilderInterface
28
    {
29 183
        return $this->db->getQueryBuilder();
30
    }
31
32
    public function schema(): SchemaInterface
33
    {
34
        return $this->db->getSchema();
35
    }
36
37 1
    public function insertEx(string $table, array $columns): bool|array
38
    {
39 1
        $params = [];
40 1
        $sql = $this->queryBuilder()->insertEx($table, $columns, $params);
41
42 1
        $tableSchema = $this->db->getSchema()->getTableSchema($table);
43
44 1
        $returnColumns = $tableSchema?->getPrimaryKey() ?? [];
45 1
        $columnSchemas = $tableSchema?->getColumns() ?? [];
46
47 1
        $returnParams = [];
48 1
        $returning = [];
49 1
        foreach ($returnColumns as $name) {
50 1
            $phName = QueryBuilder::PARAM_PREFIX . (count($params) + count($returnParams));
51
52 1
            $returnParams[$phName] = [
53
                'column' => $name,
54
                'value' => '',
55
            ];
56
57 1
            if (!isset($columnSchemas[$name]) || $columnSchemas[$name]->getPhpType() !== Schema::PHP_TYPE_INTEGER) {
58
                $returnParams[$phName]['dataType'] = PDO::PARAM_STR;
59
            } else {
60 1
                $returnParams[$phName]['dataType'] = PDO::PARAM_INT;
61
            }
62
63 1
            $returnParams[$phName]['size'] = $columnSchemas[$name]->getSize() ?? -1;
64
65 1
            $returning[] = $this->db->getQuoter()->quoteColumnName($name);
66
        }
67
68 1
        $sql .= ' RETURNING ' . implode(', ', $returning) . ' INTO ' . implode(', ', array_keys($returnParams));
69
70 1
        $this->setSql($sql)->bindValues($params);
71 1
        $this->prepare(false);
72
73
        /** @psalm-var array<string, array{column: string, value: mixed, dataType: int, size: int}> $returnParams */
74 1
        foreach ($returnParams as $name => &$value) {
75 1
            $this->bindParam($name, $value['value'], $value['dataType'], $value['size']);
76
        }
77
78 1
        if (!$this->execute()) {
79
            return false;
80
        }
81
82 1
        $result = [];
83
84 1
        foreach ($returnParams as $value) {
85
            /** @var mixed */
86 1
            $result[$value['column']] = $value['value'];
87
        }
88
89 1
        return $result;
90
    }
91
92 173
    protected function bindPendingParams(): void
93
    {
94 173
        $paramsPassedByReference = [];
95
96
        /** @psalm-var ParamInterface[] */
97 173
        $params = $this->params;
98
99 173
        foreach ($params as $name => $value) {
100 150
            if (PDO::PARAM_STR === $value->getType()) {
101
                /** @var mixed */
102 144
                $paramsPassedByReference[$name] = $value->getValue();
103 144
                $this->pdoStatement?->bindParam(
104
                    $name,
105 144
                    $paramsPassedByReference[$name],
106 144
                    $value->getType(),
107 144
                    strlen((string) $value->getValue())
108
                );
109
            } else {
110 24
                $this->pdoStatement?->bindValue($name, $value->getValue(), $value->getType());
111
            }
112
        }
113
    }
114
115 172
    protected function internalExecute(?string $rawSql): void
116
    {
117 172
        $attempt = 0;
118
119 172
        while (true) {
120
            try {
121
                if (
122 172
                    ++$attempt === 1
123 172
                    && $this->isolationLevel !== null
124 172
                    && $this->db->getTransaction() === null
125
                ) {
126
                    $this->db->transaction(fn (string $rawSql) => $this->internalExecute($rawSql), $this->isolationLevel);
127
                } else {
128 172
                    $this->pdoStatement?->execute();
129
                }
130 172
                break;
131 6
            } catch (PDOException $e) {
132 6
                $rawSql = $rawSql ?: $this->getRawSql();
133 6
                $e = (new ConvertException($e, $rawSql))->run();
134
135 6
                if ($this->retryHandler === null || !($this->retryHandler)($e, $attempt)) {
136 6
                    throw $e;
137
                }
138
            }
139
        }
140
    }
141
}
142