Passed
Push — master ( 6894ed...3cfcb2 )
by Daniel
02:29
created

MySQLiByDanielGPstructures   A

Complexity

Total Complexity 37

Size/Duplication

Total Lines 289
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 289
rs 9.44
c 0
b 0
f 0
wmc 37

19 Methods

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