Completed
Push — master ( 91b102...f00e62 )
by Daniel
06:22
created

getMySQLlistDatabases()   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 1
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
        MySQLiByDanielGPqueries;
41
42
    /**
43
     * Ensures table has special quoes and DOT as final char
44
     * (if not empty, of course)
45
     *
46
     * @param string $referenceTable
47
     * @return string
48
     */
49
    private function correctTableWithQuotesAsFieldPrefix($referenceTable)
50
    {
51
        if ($referenceTable != '') {
52
            return '`' . str_replace('`', '', $referenceTable) . '`.';
53
        }
54
        return '';
55
    }
56
57
    /**
58
     * Prepares the output of text fields defined w. FKs
59
     *
60
     * @param array $foreignKeysArray
61
     * @param array $value
62
     * @param array $iar
63
     * @return string
64
     */
65
    protected function getFieldOutputTextFK($foreignKeysArray, $value, $iar)
66
    {
67
        $query   = $this->sQueryGenericSelectKeyValue([
68
            '`' . $value['COLUMN_NAME'] . '`',
69
            $foreignKeysArray[$value['COLUMN_NAME']][2],
70
            $foreignKeysArray[$value['COLUMN_NAME']][0]
71
        ]);
72
        $inAdtnl = ['size' => 1];
73
        if ($value['IS_NULLABLE'] == 'YES') {
74
            $inAdtnl = array_merge($inAdtnl, ['include_null']);
75
        }
76
        if ($iar !== []) {
77
            $inAdtnl = array_merge($inAdtnl, $iar);
78
        }
79
        $slct = [
80
            'Options' => $this->setMySQLquery2Server($query, 'array_key_value')['result'],
81
            'Value'   => $this->getFieldValue($value),
82
        ];
83
        return $this->setArrayToSelect($slct['Options'], $slct['Value'], $value['COLUMN_NAME'], $inAdtnl);
84
    }
85
86
    /**
87
     * Prepares the output of text fields w/o FKs
88
     *
89
     * @param array $value
90
     * @param array $iar
91
     * @return string
92
     */
93
    protected function getFieldOutputTextNonFK($value, $iar)
94
    {
95
        $fldNos  = $this->setFieldNumbers($value);
96
        $inAdtnl = [
97
            'type'      => ($value['COLUMN_NAME'] == 'password' ? 'password' : 'text'),
98
            'name'      => $value['COLUMN_NAME'],
99
            'id'        => $value['COLUMN_NAME'],
100
            'size'      => min(30, $fldNos['M']),
101
            'maxlength' => min(255, $fldNos['M']),
102
            'value'     => $this->getFieldValue($value),
103
        ];
104
        if ($iar !== []) {
105
            $inAdtnl = array_merge($inAdtnl, $iar);
106
        }
107
        return $this->setStringIntoShortTag('input', $inAdtnl);
108
    }
109
110
    /**
111
     * Return the list of Tables from the MySQL server
112
     *
113
     * @return string
114
     */
115
    protected function getMySQLStatistics($filterArray = null)
116
    {
117
        return $this->getMySQLlistMultiple('Statistics', 'full_array_key_numbered', $filterArray);
118
    }
119
120
    /**
121
     * returns a list of MySQL databases
122
     *
123
     * @return array
124
     */
125
    protected function getMySQLactiveDatabases()
126
    {
127
        return $this->getMySQLlistDatabases(true);
128
    }
129
130
    /**
131
     * returns a list of active MySQL engines
132
     *
133
     * @return array
134
     */
135
    protected function getMySQLactiveEngines()
136
    {
137
        return $this->getMySQLlistEngines(true);
138
    }
139
140
    /**
141
     * returns the list of all MySQL global variables
142
     *
143
     * @return array
144
     */
145
    protected function getMySQLglobalVariables()
146
    {
147
        return $this->getMySQLlistMultiple('VariablesGlobal', 'array_key_value');
148
    }
149
150
    /**
151
     * returns a list of MySQL indexes (w. choice of to choose any combination of db/table/column)
152
     *
153
     * @return array
154
     */
155
    protected function getMySQLlistColumns($filterArray = null)
156
    {
157
        return $this->getMySQLlistMultiple('Columns', 'full_array_key_numbered', $filterArray);
158
    }
159
160
    /**
161
     * returns a list of MySQL databases (w. choice of exclude/include the system ones)
162
     *
163
     * @return array
164
     */
165
    protected function getMySQLlistDatabases($excludeSystemDbs = true)
166
    {
167
        return $this->getMySQLlistMultiple('Databases', 'array_first_key_rest_values', $excludeSystemDbs);
168
    }
169
170
    /**
171
     * returns a list of MySQL engines (w. choice of return only the active ones)
172
     *
173
     * @return array
174
     */
175
    protected function getMySQLlistEngines($onlyActiveOnes = true)
176
    {
177
        return $this->getMySQLlistMultiple('Engines', 'array_first_key_rest_values', $onlyActiveOnes);
178
    }
179
180
    /**
181
     * returns a list of MySQL indexes (w. choice of to choose any combination of db/table/column)
182
     *
183
     * @return array
184
     */
185
    protected function getMySQLlistIndexes($filterArray = null)
186
    {
187
        return $this->getMySQLlistMultiple('Indexes', 'full_array_key_numbered', $filterArray);
188
    }
189
190
    /**
191
     * Return various informations (from predefined list) from the MySQL server
192
     *
193
     * @return int|array
194
     */
195
    private function getMySQLlistMultiple($returnChoice, $returnType, $additionalFeatures = null)
196
    {
197
        if (is_null($this->mySQLconnection)) {
198
            if ($returnType == 'value') {
199
                return null;
200
            }
201
            return [];
202
        }
203
        return $this->getMySQLlistMultipleFinal($returnChoice, $returnType, $additionalFeatures);
204
    }
205
206
    /**
207
     * Return various informations (from predefined list) from the MySQL server
208
     *
209
     * @param string $rChoice
210
     * @param string $returnType
211
     * @param array $additionalFeatures
212
     * @return array
213
     */
214
    private function getMySQLlistMultipleFinal($rChoice, $returnType, $additionalFeatures = null)
215
    {
216
        $qByChoice = [
217
            'Columns'         => ['sQueryMySqlColumns', $additionalFeatures],
218
            'Databases'       => ['sQueryMySqlActiveDatabases', $additionalFeatures],
219
            'Engines'         => ['sQueryMySqlActiveEngines', $additionalFeatures],
220
            'Indexes'         => ['sQueryMySqlIndexes', $additionalFeatures],
221
            'ServerTime'      => ['sQueryMySqlServerTime'],
222
            'Statistics'      => ['sQueryMySqlStatistics', $additionalFeatures],
223
            'Tables'          => ['sQueryMySqlTables', $additionalFeatures],
224
            'VariablesGlobal' => ['sQueryMySqlGlobalVariables'],
225
        ];
226
        if (array_key_exists($rChoice, $qByChoice)) {
227
            return $this->setMySQLquery2Server($this->transformStrIntoFn($qByChoice, $rChoice), $returnType)['result'];
228
        }
229
        return [];
230
    }
231
232
    /**
233
     * Return the list of Tables from the MySQL server
234
     *
235
     * @return string
236
     */
237
    protected function getMySQLlistTables($filterArray = null)
238
    {
239
        return $this->getMySQLlistMultiple('Tables', 'full_array_key_numbered', $filterArray);
240
    }
241
242
    /**
243
     * Return the time from the MySQL server
244
     *
245
     * @return string
246
     */
247
    protected function getMySQLserverTime()
248
    {
249
        return $this->getMySQLlistMultiple('ServerTime', 'value');
250
    }
251
252
    /**
253
     * Reads data from table into REQUEST super global
254
     *
255
     * @param string $tableName
256
     * @param array $filtersArray
257
     */
258
    protected function getRowDataFromTable($tableName, $filtersArray)
259
    {
260
        $query   = $this->sQueryRowsFromTable([$tableName, $this->setArrayToFilterValues($filtersArray)]);
261
        $rawData = $this->setMySQLquery2Server($query, 'array_pairs_key_value')['result'];
262
        if (!is_null($rawData)) {
263
            $this->initializeSprGlbAndSession();
264
            foreach ($rawData as $key => $value) {
265
                $vToSet = str_replace(['\\\\"', '\\"', "\\\\'", "\\'"], ['"', '"', "'", "'"], $value);
266
                $this->tCmnRequest->request->set($key, $vToSet);
267
            }
268
        }
269
    }
270
271
    /**
272
     * Builds an filter string from pair of key and value, where value is array
273
     *
274
     * @param string $key
275
     * @param array $value
276
     * @param string $referenceTable
277
     * @return string
278
     */
279
    private function setArrayLineArrayToFilter($key, $value, $referenceTable)
280
    {
281
        $filters2 = implode(', ', array_diff($value, ['']));
282
        if ($filters2 != '') {
283
            return '(' . $referenceTable . '`' . $key . '` IN ("'
284
                    . str_replace(',', '","', str_replace(["'", '"'], '', $filters2)) . '"))';
285
        }
286
        return '';
287
    }
288
289
    /**
290
     * Builds an filter string from pair of key and value, none array
291
     *
292
     * @param string $key
293
     * @param int|float|string $value
294
     * @return string
295
     */
296
    private function setArrayLineToFilter($key, $value)
297
    {
298
        $fTemp = '=';
299
        if ((substr($value, 0, 1) == '%') && (substr($value, -1) == '%')) {
300
            $fTemp = 'LIKE';
301
        }
302
        return '(`' . $key . '` ' . $fTemp . '"' . $value . '")';
303
    }
304
305
    /**
306
     * Transforms an array into usable filters
307
     *
308
     * @param array $entryArray
309
     * @param string $referenceTable
310
     * @return array
311
     */
312
    private function setArrayToFilterValues($entryArray, $referenceTable = '')
313
    {
314
        $filters  = [];
315
        $refTable = $this->correctTableWithQuotesAsFieldPrefix($referenceTable);
316
        foreach ($entryArray as $key => $value) {
317
            if (is_array($value)) {
318
                $filters[] = $this->setArrayLineArrayToFilter($key, $value, $refTable);
319
            } elseif (!in_array($value, ['', '%%'])) {
320
                $filters[] = $this->setArrayLineToFilter($key, $value);
321
            }
322
        }
323
        return implode(' AND ', array_diff($filters, ['']));
324
    }
325
326
    private function transformStrIntoFn($queryByChoice, $rChoice)
327
    {
328
        $query = null;
329
        switch (count($queryByChoice[$rChoice])) {
330 View Code Duplication
            case 1:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
331
                $query = call_user_func([$this, $queryByChoice[$rChoice][0]]);
332
                break;
333 View Code Duplication
            case 2:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
334
                $query = call_user_func([$this, $queryByChoice[$rChoice][0]], $queryByChoice[$rChoice][1]);
335
                break;
336
        }
337
        return $query;
338
    }
339
}
340