Completed
Push — master ( c1b59a...ea89b8 )
by Sébastien
03:58
created

MysqliMetadataReader::getDatatypeMapping()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 54
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 1

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 54
ccs 29
cts 29
cp 1
rs 9.6716
cc 1
eloc 28
nc 1
nop 0
crap 1

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
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
use Soluble\Datatype\Column\Exception\UnsupportedDatatypeException;
10
11
12
class MysqliMetadataReader extends AbstractMetadataReader
13
{
14
15
    /**
16
     * @var \Mysqli
17
     */
18
    protected $mysqli;
19
20
    /**
21
     *
22
     * @var boolean
23
     */
24
    protected $cache_active = true;
25
26
    /**
27
     *
28
     * @var Array
29
     */
30
    protected static $metadata_cache = [];
31
32
    /**
33
     *
34
     * @param \Mysqli $mysqli
35
     */
36 7
    public function __construct(\Mysqli $mysqli)
37
    {
38 7
        $this->mysqli = $mysqli;
39 7
    }
40
41
    /**
42
     *
43
     * {@inheritdoc}
44
     */
45 6
    protected function readColumnsMetadata($sql)
46
    {
47 6
        $metadata = new ColumnsMetadata();
48 6
        $fields = $this->readFields($sql);
49 4
        $type_map = MysqliMapping::getDatatypeMapping();
50
51 4
        foreach ($fields as $idx => $field) {
52 4
            $name = $field->orgname == '' ? $field->name : $field->orgname;
53 4
            $tableName = $field->orgtable;
54 4
            $schemaName = $field->db;
55
56 4
            $datatype = $field->type;
57
58
59 4
            if (!$type_map->offsetExists($datatype)) {
60
                throw new UnsupportedDatatypeException("Datatype '$datatype' not yet supported by " . __CLASS__);
61
            }
62
63
64 4
            $datatype = $type_map->offsetGet($datatype);
65
66 4
            $column = Column\Type::createColumnDefinition($datatype['type'], $name, $tableName, $schemaName);
67
68 4
            $column->setAlias($field->name);
69 4
            $column->setTableAlias($field->table);
70 4
            $column->setCatalog($field->catalog);
71 4
            $column->setOrdinalPosition($idx + 1);
72 4
            $column->setDataType($datatype['type']);
73 4
            $column->setIsNullable(!($field->flags & MYSQLI_NOT_NULL_FLAG) > 0 && ($field->orgtable != ''));
74 4
            $column->setIsPrimary(($field->flags & MYSQLI_PRI_KEY_FLAG) > 0);
75
76 4
            $column->setColumnDefault($field->def);
77
78 4
            if (($field->flags & MYSQLI_SET_FLAG) > 0) {
79 1
                $column->setNativeDataType('SET');
80 4
            } elseif (($field->flags & MYSQLI_ENUM_FLAG) > 0) {
81 2
                $column->setNativeDataType('ENUM');
82 2
            } else {
83 4
                $column->setNativeDataType($datatype['native']);
84
            }
85
86 4
            if ($field->table == '') {
87
                $column->setIsGroup(($field->flags & MYSQLI_GROUP_FLAG) > 0);
88
            }
89
90 4
            if ($column instanceof Column\Definition\NumericColumnInterface) {
91 4
                $column->setNumericUnsigned(($field->flags & MYSQLI_UNSIGNED_FLAG) > 0);
92 4
            }
93
94 4
            if ($column instanceof Column\Definition\IntegerColumn) {
95 4
                $column->setIsAutoIncrement(($field->flags & MYSQLI_AUTO_INCREMENT_FLAG) > 0);
96 4
            }
97
98 4
            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 1
                $column->setNumericScale($field->length - $field->decimals + 1);
106 1
                $column->setNumericPrecision($field->decimals);
107 1
            }
108
109 4
            if ($column instanceof Column\Definition\StringColumn) {
110 3
                $column->setCharacterMaximumLength($field->length);
111 3
            }
112
113 4
            if ($column instanceof Column\Definition\BlobColumn) {
114 1
                $column->setCharacterOctetLength($field->length);
115 1
            }
116
117 4
            $alias = $column->getAlias();
118
119 4
            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 4
            $metadata->offsetSet($alias, $column);
135 4
        }
136
137 3
        return $metadata;
138
    }
139
140
    /**
141
     *
142
     * @param string $sql
143
     * @throws Exception\ConnectionException
144
     * @return array
145
     */
146 6
    protected function readFields($sql)
147
    {
148 6
        if (trim($sql) == '') {
149 1
            throw new Exception\EmptyQueryException(__METHOD__ . ": Error cannot handle empty queries");
150
        }
151
152 5
        $sql = $this->makeQueryEmpty($sql);
153
154 5
        $stmt = $this->mysqli->prepare($sql);
155
156 5
        if (!$stmt) {
157 1
            $message = $this->mysqli->error;
158 1
            throw new Exception\InvalidQueryException(__METHOD__ . ": Error sql is not correct : $message");
159
        }
160 4
        $stmt->execute();
161
162 4
        $result = $stmt->result_metadata();
163 4
        $metaFields = $result->fetch_fields();
164 4
        $result->close();
165 4
        $stmt->close();
166 4
        return $metaFields;
167
    }
168
}
169