1 | <?php |
||
2 | |||
3 | namespace DB; |
||
4 | |||
5 | use PDO as GlobalPDO; |
||
6 | |||
7 | class schema |
||
8 | { |
||
9 | /** |
||
10 | * Get ENUM or SET values. |
||
11 | * |
||
12 | * @return array |
||
13 | */ |
||
14 | public static function get_enumset_values(\DB\pdo $pdo, string $table, string $field) |
||
15 | { |
||
16 | $type = $pdo->query("SHOW COLUMNS FROM {$table} WHERE Field = '{$field}'")->row_array()['Type']; |
||
17 | $result = []; |
||
18 | if (preg_match("/^enum\(\'(.*)\'\)$/", $type, $matches)) { |
||
19 | $enum = explode("','", $matches[1]); |
||
20 | |||
21 | $result = $enum; |
||
22 | } elseif (preg_match("/^set\(\'(.*)\'\)$/", $type, $matches)) { |
||
23 | $set = explode("','", $matches[1]); |
||
24 | |||
25 | $result = $set; |
||
26 | } |
||
27 | |||
28 | return array_values(array_unique($result)); |
||
29 | } |
||
30 | |||
31 | /** |
||
32 | * Modify ENUM or SET values. |
||
33 | * @see https://stackoverflow.com/questions/1501958/how-do-i-add-more-members-to-my-enum-type-column-in-mysql |
||
34 | * @return array |
||
35 | */ |
||
36 | public static function modify_enumset_values(\DB\pdo $pdo, string $table, string $field, array $newData) |
||
37 | { |
||
38 | for ($i = 0; $i < count($newData); $i++) { |
||
0 ignored issues
–
show
|
|||
39 | $newData[$i] = "'$newData[$i]'"; |
||
40 | } |
||
41 | $data = implode(', ', array_values(array_unique($newData))); |
||
42 | $sql = "ALTER TABLE `$table` MODIFY COLUMN `$field` SET($data) NOT NULL"; |
||
43 | return $pdo->query($sql)->exec(); |
||
44 | } |
||
45 | |||
46 | /** |
||
47 | * Replaces any parameter placeholders in a query with the value of that |
||
48 | * parameter. Useful for debugging. Assumes anonymous parameters from |
||
49 | * $params are are in the same order as specified in $query |
||
50 | * |
||
51 | * @param string $query The sql query with parameter placeholders |
||
52 | * @param array $params The array of substitution parameters |
||
53 | * @return string The interpolated query |
||
54 | */ |
||
55 | public static function interpolateQuery($query, $params) |
||
56 | { |
||
57 | $keys = array(); |
||
58 | |||
59 | # build a regular expression for each parameter |
||
60 | foreach ($params as $key => $value) { |
||
61 | if (is_string($key)) { |
||
62 | $keys[] = '/:' . $key . '/'; |
||
63 | } else { |
||
64 | $keys[] = '/[?]/'; |
||
65 | } |
||
66 | } |
||
67 | |||
68 | $query = preg_replace($keys, $params, $query, 1, $count); |
||
69 | |||
70 | #trigger_error('replaced '.$count.' keys'); |
||
71 | |||
72 | return $query; |
||
73 | } |
||
74 | } |
||
75 |
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: