Completed
Push — master ( a2fc1a...c1afcc )
by Sébastien
02:25
created

MysqliMetadataReader::readColumnsMetadata()   F

Complexity

Conditions 17
Paths 1539

Size

Total Lines 95
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 55
CRAP Score 17.2753

Importance

Changes 0
Metric Value
dl 0
loc 95
ccs 55
cts 61
cp 0.9016
rs 2
c 0
b 0
f 0
cc 17
eloc 52
nc 1539
nop 1
crap 17.2753

How to fix   Long Method    Complexity   

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
namespace Soluble\Metadata\Reader;
4
5
use Soluble\Metadata\ColumnsMetadata;
6
use Soluble\Metadata\Exception;
7
use Soluble\Metadata\Reader\Mapping\MysqliMapping;
8
use Soluble\Datatype\Column;
9
10
11
class MysqliMetadataReader extends AbstractMetadataReader
12
{
13
14
    /**
15
     * @var \Mysqli
16
     */
17
    protected $mysqli;
18
19
    /**
20
     *
21
     * @var boolean
22
     */
23
    protected $cache_active = true;
24
25
    /**
26
     *
27
     * @var Array
28
     */
29
    protected static $metadata_cache = [];
30
31
    /**
32
     *
33
     * @param \Mysqli $mysqli
34
     */
35 13
    public function __construct(\Mysqli $mysqli)
36
    {
37 13
        $this->mysqli = $mysqli;
38 13
    }
39
40
    /**
41
     *
42
     * {@inheritdoc}
43
     */
44 7
    protected function readColumnsMetadata($sql)
45
    {
46 7
        $metadata = new ColumnsMetadata();
47 7
        $fields = $this->readFields($sql);
48 5
        $type_map = MysqliMapping::getDatatypeMapping();
49
50 5
        foreach ($fields as $idx => $field) {
51 5
            $name = $field->orgname == '' ? $field->name : $field->orgname;
52 5
            $tableName = $field->orgtable;
53 5
            $schemaName = $field->db;
54
55 5
            $datatype = $field->type;
56
57
58 5
            if (!$type_map->offsetExists($datatype)) {
59
                $msg = "Cannot get type for field '$name'. Mapping for native type [$datatype] cannot be resolved into a valid type";
60
                throw new Exception\UnsupportedTypeException($msg);
61
            }
62
63
64 5
            $datatype = $type_map->offsetGet($datatype);
65
66 5
            $column = Column\Type::createColumnDefinition($datatype['type'], $name, $tableName, $schemaName);
67
68 5
            $column->setAlias($field->name);
69 5
            $column->setTableAlias($field->table);
70 5
            $column->setCatalog($field->catalog);
71 5
            $column->setOrdinalPosition($idx + 1);
72 5
            $column->setDataType($datatype['type']);
73 5
            $column->setIsNullable(!($field->flags & MYSQLI_NOT_NULL_FLAG) > 0 && ($field->orgtable != ''));
74 5
            $column->setIsPrimary(($field->flags & MYSQLI_PRI_KEY_FLAG) > 0);
75
76 5
            $column->setColumnDefault($field->def);
77
78 5
            if (($field->flags & MYSQLI_SET_FLAG) > 0) {
79 1
                $column->setNativeDataType('SET');
80 5
            } elseif (($field->flags & MYSQLI_ENUM_FLAG) > 0) {
81 2
                $column->setNativeDataType('ENUM');
82 2
            } else {
83 5
                $column->setNativeDataType($datatype['native']);
84
            }
85
86 5
            if ($field->table == '') {
87 1
                $column->setIsGroup(($field->flags & MYSQLI_GROUP_FLAG) > 0);
88 1
            }
89
90 5
            if ($column instanceof Column\Definition\NumericColumnInterface) {
91 5
                $column->setNumericUnsigned(($field->flags & MYSQLI_UNSIGNED_FLAG) > 0);
92 5
            }
93
94 5
            if ($column instanceof Column\Definition\IntegerColumn) {
95 5
                $column->setIsAutoIncrement(($field->flags & MYSQLI_AUTO_INCREMENT_FLAG) > 0);
96 5
            }
97
98 5
            if ($column instanceof Column\Definition\DecimalColumn) {
99
                // salary DECIMAL(5,2)
100
                // In this example, 5 is the precision and 2 is the scale.
101
                // Standard SQL requires that DECIMAL(5,2) be able to store any value
102
                // with five digits and two decimals, so values that can be stored in
103
                // the salary column range from -999.99 to 999.99.
104
105 2
                $column->setNumericScale($field->length - $field->decimals + 1);
106 2
                $column->setNumericPrecision($field->decimals);
107 2
            }
108
109 5
            if ($column instanceof Column\Definition\StringColumn) {
110 4
                $column->setCharacterMaximumLength($field->length);
111 4
            }
112
113 5
            if ($column instanceof Column\Definition\BlobColumn) {
114 1
                $column->setCharacterOctetLength($field->length);
115 1
            }
116
117 5
            $alias = $column->getAlias();
118
119 5
            if ($metadata->offsetExists($alias)) {
120 1
                $prev_column = $metadata->offsetGet($alias);
121 1
                $prev_def = $prev_column->toArray();
122 1
                $curr_def = $column->toArray();
123 1
                if ($prev_def['dataType'] != $curr_def['dataType'] || $prev_def['nativeDataType'] != $curr_def['nativeDataType']) {
124 1
                    throw new Exception\AmbiguousColumnException("Cannot get column metadata, non unique column found '$alias' in query with different definitions.");
125
                }
126
127
                // If the the previous definition, was a prev_def
128
                if ($prev_def['isPrimary']) {
129
                    $column = $prev_column;
130
                }
131
            }
132
133
134 5
            $metadata->offsetSet($alias, $column);
135 5
        }
136
137 4
        return $metadata;
138
    }
139
140
    /**
141
     *
142
     * @param string $sql
143
     * @throws Exception\ConnectionException
144
     * @return array
145
     */
146 7
    protected function readFields($sql)
147
    {
148 7
        if (trim($sql) == '') {
149 1
            throw new Exception\EmptyQueryException(__METHOD__ . ": Error cannot handle empty queries");
150
        }
151
152 6
        $sql = $this->getEmptyQuery($sql);
153 6
        $stmt = $this->mysqli->prepare($sql);
154
155 6
        if (!$stmt) {
156 1
            $message = $this->mysqli->error;
157 1
            throw new Exception\InvalidQueryException(__METHOD__ . ": Error sql is not correct : $message");
158
        }
159 5
        $stmt->execute();
160
161 5
        $result = $stmt->result_metadata();
162 5
        $metaFields = $result->fetch_fields();
163 5
        $result->close();
164 5
        $stmt->close();
165 5
        return $metaFields;
166
    }
167
}
168