Completed
Push — master ( 33c4fa...8fada7 )
by Daniel
02:22
created

getMySQLactiveEngines()   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
        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
     * Returns given value for a field from REQUEST global variable
59
     *
60
     * @param array $details
61
     * @return string
62
     */
63
    protected function getFieldValue($details)
64
    {
65
        $this->initializeSprGlbAndSession();
66
        $rqCN = $this->tCmnRequest->request->get($details['COLUMN_NAME']);
67
        if (!is_null($rqCN)) {
68
            if (($details['IS_NULLABLE'] == 'YES') && ($rqCN == '')) {
69
                return 'NULL';
70
            }
71
            return $rqCN;
72
        }
73
        return $this->getFieldValueWithoutUserInput($details);
74
    }
75
76
    /**
77
     * Handles field value ignoring any input from the user
78
     *
79
     * @param array $details
80
     * @return string
81
     */
82
    private function getFieldValueWithoutUserInput($details)
83
    {
84
        if ($details['COLUMN_DEFAULT'] === null) {
85
            if ($details['IS_NULLABLE'] == 'YES') {
86
                return 'NULL';
87
            }
88
            return '';
89
        }
90
        return $details['COLUMN_DEFAULT'];
91
    }
92
93
    /**
94
     * Return the list of Tables from the MySQL server
95
     *
96
     * @return string
97
     */
98
    protected function getMySQLStatistics($filterArray = null)
99
    {
100
        return $this->getMySQLlistMultiple('Statistics', 'full_array_key_numbered', $filterArray);
101
    }
102
103
    /**
104
     * returns a list of MySQL databases
105
     *
106
     * @return array
107
     */
108
    protected function getMySQLactiveDatabases()
109
    {
110
        return $this->getMySQLlistDatabases(true);
111
    }
112
113
    /**
114
     * returns a list of active MySQL engines
115
     *
116
     * @return array
117
     */
118
    protected function getMySQLactiveEngines()
119
    {
120
        return $this->getMySQLlistEngines(true);
121
    }
122
123
    /**
124
     * returns the list of all MySQL global variables
125
     *
126
     * @return array
127
     */
128
    protected function getMySQLglobalVariables()
129
    {
130
        return $this->getMySQLlistMultiple('VariablesGlobal', 'array_key_value');
131
    }
132
133
    /**
134
     * returns a list of MySQL indexes (w. choice of to choose any combination of db/table/column)
135
     *
136
     * @return array
137
     */
138
    protected function getMySQLlistColumns($filterArray = null)
139
    {
140
        return $this->getMySQLlistMultiple('Columns', 'full_array_key_numbered', $filterArray);
141
    }
142
143
    /**
144
     * returns a list of MySQL databases (w. choice of exclude/include the system ones)
145
     *
146
     * @return array
147
     */
148
    protected function getMySQLlistDatabases($excludeSystemDbs = true)
149
    {
150
        return $this->getMySQLlistMultiple('Databases', 'array_first_key_rest_values', $excludeSystemDbs);
151
    }
152
153
    /**
154
     * returns a list of MySQL engines (w. choice of return only the active ones)
155
     *
156
     * @return array
157
     */
158
    protected function getMySQLlistEngines($onlyActiveOnes = true)
159
    {
160
        return $this->getMySQLlistMultiple('Engines', 'array_first_key_rest_values', $onlyActiveOnes);
161
    }
162
163
    /**
164
     * returns a list of MySQL indexes (w. choice of to choose any combination of db/table/column)
165
     *
166
     * @return array
167
     */
168
    protected function getMySQLlistIndexes($filterArray = null)
169
    {
170
        return $this->getMySQLlistMultiple('Indexes', 'full_array_key_numbered', $filterArray);
171
    }
172
173
    /**
174
     * Return various informations (from predefined list) from the MySQL server
175
     *
176
     * @return int|array
177
     */
178
    private function getMySQLlistMultiple($returnChoice, $returnType, $additionalFeatures = null)
179
    {
180
        if (is_null($this->mySQLconnection)) {
181
            if ($returnType == 'value') {
182
                return null;
183
            }
184
            return [];
185
        }
186
        return $this->getMySQLlistMultipleFinal($returnChoice, $returnType, $additionalFeatures);
187
    }
188
189
    /**
190
     * Return various informations (from predefined list) from the MySQL server
191
     *
192
     * @return array
193
     */
194
    private function getMySQLlistMultipleFinal($returnChoice, $returnType, $additionalFeatures = null)
195
    {
196
        $queryByChoice = [
197
            'Columns'         => $this->sQueryMySqlColumns($additionalFeatures),
198
            'Databases'       => $this->sQueryMySqlActiveDatabases($additionalFeatures),
199
            'Engines'         => $this->sQueryMySqlActiveEngines($additionalFeatures),
200
            'Indexes'         => $this->sQueryMySqlIndexes($additionalFeatures),
201
            'ServerTime'      => $this->sQueryMySqlServerTime(),
202
            'Statistics'      => $this->sQueryMySqlStatistics($additionalFeatures),
203
            'Tables'          => $this->sQueryMySqlTables($additionalFeatures),
204
            'VariablesGlobal' => $this->sQueryMySqlGlobalVariables(),
205
        ];
206
        if (array_key_exists($returnChoice, $queryByChoice)) {
207
            return $this->setMySQLquery2Server($queryByChoice[$returnChoice], $returnType)['result'];
208
        }
209
        return [];
210
    }
211
212
    /**
213
     * Return the list of Tables from the MySQL server
214
     *
215
     * @return string
216
     */
217
    protected function getMySQLlistTables($filterArray = null)
218
    {
219
        return $this->getMySQLlistMultiple('Tables', 'full_array_key_numbered', $filterArray);
220
    }
221
222
    /**
223
     * Return the time from the MySQL server
224
     *
225
     * @return string
226
     */
227
    protected function getMySQLserverTime()
228
    {
229
        return $this->getMySQLlistMultiple('ServerTime', 'value');
230
    }
231
232
    /**
233
     * Reads data from table into REQUEST super global
234
     *
235
     * @param string $tableName
236
     * @param array $filtersArray
237
     */
238
    protected function getRowDataFromTable($tableName, $filtersArray)
239
    {
240
        $query   = $this->sQueryRowsFromTable([$tableName, $this->setArrayToFilterValues($filtersArray)]);
241
        $rawData = $this->setMySQLquery2Server($query, 'array_pairs_key_value')['result'];
242
        if (!is_null($rawData)) {
243
            $this->initializeSprGlbAndSession();
244
            foreach ($rawData as $key => $value) {
245
                $vToSet = str_replace(['\\\\"', '\\"', "\\\\'", "\\'"], ['"', '"', "'", "'"], $value);
246
                $this->tCmnRequest->request->set($key, $vToSet);
247
            }
248
        }
249
    }
250
251
    /**
252
     * Builds an filter string from pair of key and value, where value is array
253
     *
254
     * @param string $key
255
     * @param array $value
256
     * @param string $referenceTable
257
     * @return string
258
     */
259
    private function setArrayLineArrayToFilter($key, $value, $referenceTable)
260
    {
261
        $filters2 = implode(', ', array_diff($value, ['']));
262
        if ($filters2 != '') {
263
            return '(' . $referenceTable . '`' . $key . '` IN ("'
264
                    . str_replace(',', '","', str_replace(["'", '"'], '', $filters2)) . '"))';
265
        }
266
        return '';
267
    }
268
269
    /**
270
     * Builds an filter string from pair of key and value, none array
271
     *
272
     * @param string $key
273
     * @param int|float|string $value
274
     * @return string
275
     */
276
    private function setArrayLineToFilter($key, $value)
277
    {
278
        $fTemp = '=';
279
        if ((substr($value, 0, 1) == '%') && (substr($value, -1) == '%')) {
280
            $fTemp = 'LIKE';
281
        }
282
        return '(`' . $key . '` ' . $fTemp . '"' . $value . '")';
283
    }
284
285
    /**
286
     * Transforms an array into usable filters
287
     *
288
     * @param array $entryArray
289
     * @param string $referenceTable
290
     * @return array
291
     */
292
    private function setArrayToFilterValues($entryArray, $referenceTable = '')
293
    {
294
        $filters  = [];
295
        $refTable = $this->correctTableWithQuotesAsFieldPrefix($referenceTable);
296
        foreach ($entryArray as $key => $value) {
297
            if (is_array($value)) {
298
                $filters[] = $this->setArrayLineArrayToFilter($key, $value, $refTable);
299
            } elseif (!in_array($value, ['', '%%'])) {
300
                $filters[] = $this->setArrayLineToFilter($key, $value);
301
            }
302
        }
303
        return implode(' AND ', array_diff($filters, ['']));
304
    }
305
}
306