Completed
Push — master ( 665550...56a36e )
by Daniel
02:22
created

getMySQLactiveDatabases()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/**
4
 *
5
 * The MIT License (MIT)
6
 *
7
 * Copyright (c) 2015 Daniel Popiniuc
8
 *
9
 * Permission is hereby granted, free of charge, to any person obtaining a copy
10
 * of this software and associated documentation files (the "Software"), to deal
11
 * in the Software without restriction, including without limitation the rights
12
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
 * copies of the Software, and to permit persons to whom the Software is
14
 * furnished to do so, subject to the following conditions:
15
 *
16
 * The above copyright notice and this permission notice shall be included in all
17
 * copies or substantial portions of the Software.
18
 *
19
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
 * SOFTWARE.
26
 *
27
 */
28
29
namespace danielgp\common_lib;
30
31
/**
32
 * Usefull functions to get quick MySQL content
33
 *
34
 * @author Daniel Popiniuc
35
 */
36
trait MySQLiByDanielGPstructures
37
{
38
39
    use MySQLiByDanielGP;
40
41
    /**
42
     * Ensures table has special quoes and DOT as final char
43
     * (if not empty, of course)
44
     *
45
     * @param string $referenceTable
46
     * @return string
47
     */
48
    private function correctTableWithQuotesAsFieldPrefix($referenceTable)
49
    {
50
        if ($referenceTable != '') {
51
            return '`' . str_replace('`', '', $referenceTable) . '`.';
52
        }
53
        return '';
54
    }
55
56
    /**
57
     * Return the list of Tables from the MySQL server
58
     *
59
     * @return string
60
     */
61
    protected function getMySQLStatistics($filterArray = null)
62
    {
63
        return $this->getMySQLlistMultiple('Statistics', 'full_array_key_numbered', $filterArray);
64
    }
65
66
    /**
67
     * returns a list of MySQL databases
68
     *
69
     * @return array
70
     */
71
    protected function getMySQLactiveDatabases()
72
    {
73
        return $this->getMySQLlistDatabases(true);
74
    }
75
76
    /**
77
     * returns a list of active MySQL engines
78
     *
79
     * @return array
80
     */
81
    protected function getMySQLactiveEngines()
82
    {
83
        return $this->getMySQLlistEngines(true);
84
    }
85
86
    /**
87
     * returns the list of all MySQL global variables
88
     *
89
     * @return array
90
     */
91
    protected function getMySQLglobalVariables()
92
    {
93
        return $this->getMySQLlistMultiple('VariablesGlobal', 'array_key_value');
94
    }
95
96
    /**
97
     * returns a list of MySQL indexes (w. choice of to choose any combination of db/table/column)
98
     *
99
     * @return array
100
     */
101
    protected function getMySQLlistColumns($filterArray = null)
102
    {
103
        return $this->getMySQLlistMultiple('Columns', 'full_array_key_numbered', $filterArray);
104
    }
105
106
    /**
107
     * returns a list of MySQL databases (w. choice of exclude/include the system ones)
108
     *
109
     * @return array
110
     */
111
    protected function getMySQLlistDatabases($excludeSystemDbs = true)
112
    {
113
        return $this->getMySQLlistMultiple('Databases', 'array_first_key_rest_values', $excludeSystemDbs);
114
    }
115
116
    /**
117
     * returns a list of MySQL engines (w. choice of return only the active ones)
118
     *
119
     * @return array
120
     */
121
    protected function getMySQLlistEngines($onlyActiveOnes = true)
122
    {
123
        return $this->getMySQLlistMultiple('Engines', 'array_first_key_rest_values', $onlyActiveOnes);
124
    }
125
126
    /**
127
     * returns a list of MySQL indexes (w. choice of to choose any combination of db/table/column)
128
     *
129
     * @return array
130
     */
131
    protected function getMySQLlistIndexes($filterArray = null)
132
    {
133
        return $this->getMySQLlistMultiple('Indexes', 'full_array_key_numbered', $filterArray);
134
    }
135
136
    /**
137
     * Return the list of Tables from the MySQL server
138
     *
139
     * @return string
140
     */
141
    protected function getMySQLlistTables($filterArray = null)
142
    {
143
        return $this->getMySQLlistMultiple('Tables', 'full_array_key_numbered', $filterArray);
144
    }
145
146
    /**
147
     * Return the time from the MySQL server
148
     *
149
     * @return string
150
     */
151
    protected function getMySQLserverTime()
152
    {
153
        return $this->getMySQLlistMultiple('ServerTime', 'value');
154
    }
155
156
    /**
157
     * Reads data from table into REQUEST super global
158
     *
159
     * @param string $tableName
160
     * @param array $filtersArray
161
     */
162
    protected function getRowDataFromTable($tableName, $filtersArray)
163
    {
164
        $query   = $this->sQueryRowsFromTable([$tableName, $this->setArrayToFilterValues($filtersArray)]);
165
        $rawData = $this->setMySQLquery2Server($query, 'array_pairs_key_value')['result'];
166
        if (!is_null($rawData)) {
167
            $this->initializeSprGlbAndSession();
168
            foreach ($rawData as $key => $value) {
169
                $vToSet = str_replace(['\\\\"', '\\"', "\\\\'", "\\'"], ['"', '"', "'", "'"], $value);
170
                $this->tCmnRequest->request->set($key, $vToSet);
171
            }
172
        }
173
    }
174
175
    /**
176
     * Builds an filter string from pair of key and value, where value is array
177
     *
178
     * @param string $key
179
     * @param array $value
180
     * @param string $referenceTable
181
     * @return string
182
     */
183
    private function setArrayLineArrayToFilter($key, $value, $referenceTable)
184
    {
185
        $filters2 = implode(', ', array_diff($value, ['']));
186
        if ($filters2 != '') {
187
            return '(' . $referenceTable . '`' . $key . '` IN ("'
188
                    . str_replace(',', '","', str_replace(["'", '"'], '', $filters2)) . '"))';
189
        }
190
        return '';
191
    }
192
193
    /**
194
     * Builds an filter string from pair of key and value, none array
195
     *
196
     * @param string $key
197
     * @param int|float|string $value
198
     * @return string
199
     */
200
    private function setArrayLineToFilter($key, $value)
201
    {
202
        $fTemp = '=';
203
        if ((substr($value, 0, 1) == '%') && (substr($value, -1) == '%')) {
204
            $fTemp = 'LIKE';
205
        }
206
        return '(`' . $key . '` ' . $fTemp . '"' . $value . '")';
207
    }
208
209
    /**
210
     * Transforms an array into usable filters
211
     *
212
     * @param array $entryArray
213
     * @param string $referenceTable
214
     * @return array
215
     */
216
    private function setArrayToFilterValues($entryArray, $referenceTable = '')
217
    {
218
        $filters  = [];
219
        $refTable = $this->correctTableWithQuotesAsFieldPrefix($referenceTable);
220
        foreach ($entryArray as $key => $value) {
221
            if (is_array($value)) {
222
                $filters[] = $this->setArrayLineArrayToFilter($key, $value, $refTable);
223
            } elseif (!in_array($value, ['', '%%'])) {
224
                $filters[] = $this->setArrayLineToFilter($key, $value);
225
            }
226
        }
227
        return implode(' AND ', array_diff($filters, ['']));
228
    }
229
230
    /**
231
     * Returns maximum length for a given MySQL field
232
     *
233
     * @param array $fieldDetails
234
     * @param boolean $outputFormated
235
     * @return array
236
     */
237
    protected function setFieldNumbers($fieldDetails, $outputFormated = false)
238
    {
239
        $sRtrn = $this->setFieldSpecific($fieldDetails);
240
        if ($outputFormated) {
241
            if (is_array($sRtrn)) {
242
                foreach ($sRtrn as $key => $value) {
243
                    $sRtrn[$key] = $this->setNumberFormat($value);
244
                }
245
            }
246
        }
247
        return $sRtrn;
248
    }
249
250
    /**
251
     * Establishes numbers of fields
252
     *
253
     * @param array $fieldDetails
254
     * @return array
255
     */
256
    private function setFieldSpecific($fieldDetails)
257
    {
258
        if (in_array($fieldDetails['DATA_TYPE'], ['char', 'varchar', 'tinytext', 'text', 'mediumtext', 'longtext'])) {
259
            return ['M' => $fieldDetails['CHARACTER_MAXIMUM_LENGTH']];
260
        } elseif (in_array($fieldDetails['DATA_TYPE'], ['decimal', 'numeric'])) {
261
            return ['M' => $fieldDetails['NUMERIC_PRECISION'], 'd' => $fieldDetails['NUMERIC_SCALE']];
262
        } elseif (in_array($fieldDetails['DATA_TYPE'], ['bigint', 'int', 'mediumint', 'smallint', 'tinyint'])) {
263
            return $this->setFldLmtsExact($fieldDetails['DATA_TYPE']);
264
        }
265
        return $this->setFieldSpecificElse($fieldDetails);
266
    }
267
268
    private function setFieldSpecificElse($fieldDetails)
269
    {
270
        $map = ['date' => 10, 'datetime' => 19, 'enum' => 65536, 'set' => 64, 'time' => 8, 'timestamp' => 19];
271
        if (array_key_exists($fieldDetails['DATA_TYPE'], $map)) {
272
            return ['M' => $map[$fieldDetails['DATA_TYPE']]];
273
        }
274
        return ['M' => '???'];
275
    }
276
277
    private function setFldLmtsExact($cTp)
278
    {
279
        $xct     = [
280
            'bigint'    => ['l' => -9223372036854775808, 'L' => 9223372036854775807, 's' => 21, 'sUS' => 20],
281
            'int'       => ['l' => -2147483648, 'L' => 2147483647, 's' => 11, 'sUS' => 10],
282
            'mediumint' => ['l' => -8388608, 'L' => 8388607, 's' => 9, 'sUS' => 8],
283
            'smallint'  => ['l' => -32768, 'L' => 32767, 's' => 6, 'sUS' => 5],
284
            'tinyint'   => ['l' => -128, 'L' => 127, 's' => 4, 'sUS' => 3],
285
        ];
286
        $aReturn = null;
287
        if (array_key_exists($cTp, $xct)) {
288
            $aReturn = ['m' => $xct[$cTp]['l'], 'M' => $xct[$cTp]['L'], 'l' => $xct[$cTp]['s']];
289
            if (strpos($cTp, 'unsigned') !== false) {
290
                $aReturn = ['m' => 0, 'M' => ($xct[$cTp]['L'] - $xct[$cTp]['l']), 'l' => $xct[$cTp]['sUS']];
291
            }
292
        }
293
        return $aReturn;
294
    }
295
}
296