Odyssey
2017112700_adminAlwaysLower.php
1 <?php
2 /* Notes:
3  * 1. Anything complicated needs to be done with SQL.
4  * 2. Always have a check to know if the migration needs to occur (up or down).
5  * 3. Use up() and down(), not change(), because of the SQL
6  */
7 use Phinx\Migration\AbstractMigration;
8 
9 class AdminAlwaysLower extends AbstractMigration
10 {
11  /* This is the process for moving forward. We are re-creating the table so if there is
12  * existing data will need to create a temporary table, copy the data, drop the old table,
13  * rename the temporary table.
14  */
15  public function up()
16  {
17  // List of columns in tables to update. Just going to update them to their lowercase equivalent.
18  $columnsToCheck= array(
19  array("table" => "cuauditadmin", "column" => "user_name"),
20  array("table" => "cuadmeco", "column" => "admin"),
21  array("table" => "cuadminallow", "column" => "user_name"),
22  array("table" => "cuadminexclude", "column" => "user_name"),
23  array("table" => "cuadminusers", "column" => "user_name")
24  );
25 
26  $sql= array();
27  foreach($columnsToCheck as $colArray)
28  {
29  $column= $colArray["column"];
30  $table= $colArray["table"];
31  $sql[]= "(select coalesce(bool_or($column != lower($column)), false) from $table) as $table";
32  // Bool_or to be true if the query needs to be run.
33  }
34 
35  $sql= "select " . implode(",", $sql);
36  $row= $this->fetchRow($sql);
37 
38  // Check if there aren't changes and if so, print out no changes.
39  $changes= false;
40  foreach($columnsToCheck as $colArray)
41  {
42  if ($row[$colArray["table"]])
43  {
44  $changes= true;
45  break;
46  }
47  }
48 
49  if (!$changes)
50  print "All username values are already lowercase. Nothing is done.\n";
51  else
52  {
53  foreach($columnsToCheck as $colArray)
54  {
55  $column= $colArray["column"];
56  $table= $colArray["table"];
57  if ($row[$table])
58  {
59  print "Changing usernames in table $table...\n";
60  $sql= "update $table set $column = lower($column) where $column != lower($column)";
61  $this->query($sql);
62  }
63  }
64  }
65 
66  }
67 
68  /* To execute this you need to run the following command:
69  * php vendor/bin/phinx rollback (using correct path to phinx)
70  * Or, to roll back to a specific time:
71  * php vendor/bin/phinx rollback -t 20151123211207
72  */
73  public function down()
74  {
75  print "Not implementing the 'down'";
76  }
77 }