Completed
Pull Request — master (#1393)
by
unknown
03:29
created

PdoAdapter::getRenameColumnInstructions()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
c 0
b 0
f 0
ccs 0
cts 0
cp 0
nc 1
1
<?php
2
/**
3
 * Phinx
4
 *
5
 * (The MIT license)
6
 * Copyright (c) 2015 Rob Morgan
7
 *
8
 * Permission is hereby granted, free of charge, to any person obtaining a copy
9
 * of this software and associated * documentation files (the "Software"), to
10
 * deal in the Software without restriction, including without limitation the
11
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
12
 * sell copies of the Software, and to permit persons to whom the Software is
13
 * furnished to do so, subject to the following conditions:
14
 *
15
 * The above copyright notice and this permission notice shall be included in
16
 * all copies or substantial portions of the Software.
17
 *
18
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24
 * IN THE SOFTWARE.
25
 *
26
 * @package    Phinx
27
 * @subpackage Phinx\Db\Adapter
28
 */
29
namespace Phinx\Db\Adapter;
30
31
use BadMethodCallException;
32
use Phinx\Db\Action\AddColumn;
33
use Phinx\Db\Action\AddForeignKey;
34
use Phinx\Db\Action\AddIndex;
35
use Phinx\Db\Action\ChangeColumn;
36
use Phinx\Db\Action\ChangeTable;
37
use Phinx\Db\Action\DropForeignKey;
38
use Phinx\Db\Action\DropIndex;
39
use Phinx\Db\Action\DropTable;
40
use Phinx\Db\Action\RemoveColumn;
41
use Phinx\Db\Action\RenameColumn;
42
use Phinx\Db\Action\RenameTable;
43
use Phinx\Db\Table\Column;
44
use Phinx\Db\Table\ForeignKey;
45
use Phinx\Db\Table\Index;
46
use Phinx\Db\Table\Table;
47
use Phinx\Db\Util\AlterInstructions;
48
use Phinx\Migration\MigrationInterface;
49
use Symfony\Component\Console\Output\OutputInterface;
50
51 287
/**
52
 * Phinx PDO Adapter.
53 287
 *
54
 * @author Rob Morgan <[email protected]>
55 287
 */
56 3
abstract class PdoAdapter extends AbstractAdapter implements DirectActionInterface
57 3
{
58
    /**
59 287
     * @var \PDO|null
60
     */
61
    protected $connection;
62
63
    /**
64
     * Writes a message to stdout if vebose output is on
65
     *
66
     * @param string $message The message to show
67
     * @return void
68 193
     */
69
    protected function verboseLog($message)
70 193
    {
71
        if (!$this->isDryRunEnabled() &&
72
             $this->getOutput()->getVerbosity() < OutputInterface::VERBOSITY_VERY_VERBOSE) {
73 193
            return;
74 191
        }
75 191
76 74
        $this->getOutput()->writeln($message);
77 74
    }
78
79
    /**
80
     * {@inheritdoc}
81
     */
82
    public function setOptions(array $options)
83
    {
84
        parent::setOptions($options);
85
86 74
        if (isset($options['connection'])) {
87
            $this->setConnection($options['connection']);
88
        }
89
90
        return $this;
91
    }
92
93 193
    /**
94
     * Sets the database connection.
95
     *
96
     * @param \PDO $connection Connection
97
     * @return \Phinx\Db\Adapter\AdapterInterface
98
     */
99
    public function setConnection(\PDO $connection)
100
    {
101 191
        $this->connection = $connection;
102
103 191
        // Create the schema table if it doesn't already exist
104 189
        if (!$this->hasSchemaTable()) {
105 189
            $this->createSchemaTable();
106 191
        } else {
107
            $table = new \Phinx\Db\Table($this->getSchemaTableName(), [], $this);
108
            if (!$table->hasColumn('migration_name')) {
109
                $table
110
                    ->addColumn(
111
                        'migration_name',
112 1
                        'string',
113
                        ['limit' => 100, 'after' => 'version', 'default' => null, 'null' => true]
114 1
                    )
115
                    ->save();
116
            }
117
            if (!$table->hasColumn('breakpoint')) {
118
                $table
119
                    ->addColumn('breakpoint', 'boolean', ['default' => false])
120
                    ->save();
121
            }
122
        }
123
124
        return $this;
125
    }
126 218
127
    /**
128 218
     * Gets the database connection
129 3
     *
130 3
     * @return \PDO
131
     */
132
    public function getConnection()
133 217
    {
134
        if ($this->connection === null) {
135
            $this->connect();
136
        }
137
138
        return $this->connection;
139
    }
140
141
    /**
142 220
     * {@inheritdoc}
143
     */
144 220
    public function connect()
145
    {
146
    }
147
148
    /**
149
     * {@inheritdoc}
150 151
     */
151
    public function disconnect()
152 151
    {
153 151
    }
154
155
    /**
156
     * {@inheritdoc}
157
     */
158
    public function execute($sql)
159 213
    {
160
        $this->verboseLog($sql);
161 213
162 213
        if ($this->isDryRunEnabled()) {
163 213
            return 0;
164 208
        }
165 208
166 213
        return $this->getConnection()->exec($sql);
167
    }
168
169
    /**
170
     * Returns the Cake\Database connection object using the same underlying
171
     * PDO object as this connection.
172 1
     *
173
     * @return \Cake\Database\Connection
174 1
     */
175 1
    abstract public function getDecoratedConnection();
176 1
177 1
    /**
178
     * {@inheritdoc}
179 1
     */
180 1
    public function getQueryBuilder()
181 1
    {
182
        return $this->getDecoratedConnection()->newQuery();
183 1
    }
184 1
185 1
    /**
186
     * Executes a query and returns PDOStatement.
187
     *
188
     * @param string $sql SQL
189
     * @return \PDOStatement
190 11
     */
191
    public function query($sql)
192 11
    {
193 11
        return $this->getConnection()->query($sql);
194 11
    }
195 11
196
    /**
197 11
     * {@inheritdoc}
198 11
     */
199 11
    public function fetchRow($sql)
200
    {
201 11
        $result = $this->query($sql);
202 11
203 11
        return $result->fetch();
204 11
    }
205 11
206 11
    /**
207
     * {@inheritdoc}
208 11
     */
209 11
    public function fetchAll($sql)
210
    {
211 11
        $rows = [];
212 11
        $result = $this->query($sql);
213 11
        while ($row = $result->fetch()) {
214
            $rows[] = $row;
215 11
        }
216 11
217 11
        return $rows;
218
    }
219
220
    /**
221
     * {@inheritdoc}
222 5
     */
223
    public function insert(Table $table, $row)
224 5
    {
225
        $sql = sprintf(
226 5
            'INSERT INTO %s ',
227
            $this->quoteTableName($table->getName())
228
        );
229
        $columns = array_keys($row);
230
        $sql .= '(' . implode(', ', array_map([$this, 'quoteColumnName'], $columns)) . ')';
231
232 8
        foreach ($row as $column => $value) {
233
            if (is_bool($value)) {
234 8
                $row[$column] = $this->castToBool($value);
235
            }
236 8
        }
237 8
238 6
        if ($this->isDryRunEnabled()) {
239 6
            $sql .= ' VALUES (' . implode(', ', array_map([$this, 'quoteValue'], $row)) . ');';
240 2
            $this->output->writeln($sql);
241 1
        } else {
242 1
            $sql .= ' VALUES (' . implode(', ', array_fill(0, count($columns), '?')) . ')';
243 1
            $stmt = $this->getConnection()->prepare($sql);
244 1
            $stmt->execute(array_values($row));
245 8
        }
246
    }
247 7
248 7
    /**
249 7
     * Quotes a database value.
250 7
     *
251
     * @param mixed $value  The value to quote
252 7
     * @return mixed
253
     */
254
    private function quoteValue($value)
255
    {
256
        if (is_numeric($value)) {
257
            return $value;
258 5
        }
259
260 5
        if ($value === null) {
261
            return 'null';
262 5
        }
263 5
264 5
        return $this->getConnection()->quote($value);
265 5
    }
266 5
267 5
    /**
268 5
     * {@inheritdoc}
269 5
     */
270 5
    public function bulkinsert(Table $table, $rows)
271 5
    {
272 5
        $sql = sprintf(
273 5
            'INSERT INTO %s ',
274 5
            $this->quoteTableName($table->getName())
275 5
        );
276
        $current = current($rows);
277 5
        $keys = array_keys($current);
278 5
        $sql .= '(' . implode(', ', array_map([$this, 'quoteColumnName'], $keys)) . ') VALUES ';
279
280 3
        if ($this->isDryRunEnabled()) {
281 3
            $values = array_map(function ($row) {
282 3
                return '(' . implode(', ', array_map([$this, 'quoteValue'], $row)) . ')';
283 3
            }, $rows);
284 3
            $sql .= implode(', ', $values) . ';';
285 3
            $this->output->writeln($sql);
286
        } else {
287 3
            $count_keys = count($keys);
288
            $query = '(' . implode(', ', array_fill(0, $count_keys, '?')) . ')';
289
            $count_vars = count($rows);
290 5
            $queries = array_fill(0, $count_vars, $query);
291
            $sql .= implode(',', $queries);
292
            $stmt = $this->getConnection()->prepare($sql);
293
            $vals = [];
294
295
            foreach ($rows as $row) {
296 1
                foreach ($row as $v) {
297
                    if (is_bool($v)) {
298 1
                        $vals[] = $this->castToBool($v);
299 1
                    } else {
300 1
                        $vals[] = $v;
301 1
                    }
302 1
                }
303 1
            }
304 1
305 1
            $stmt->execute($vals);
306 1
        }
307 1
    }
308 1
309 1
    /**
310
     * {@inheritdoc}
311 1
     */
312
    public function getVersions()
313
    {
314
        $rows = $this->getVersionLog();
315
316
        return array_keys($rows);
317 1
    }
318
319 1
    /**
320 1
     * {@inheritdoc}
321 1
     */
322 1
    public function getVersionLog()
323 1
    {
324 1
        $result = [];
325 1
326 1
        switch ($this->options['version_order']) {
327 1
            case \Phinx\Config\Config::VERSION_ORDER_CREATION_TIME:
328
                $orderBy = 'version ASC';
329
                break;
330
            case \Phinx\Config\Config::VERSION_ORDER_EXECUTION_TIME:
331
                $orderBy = 'start_time ASC, version ASC';
332
                break;
333
            default:
334
                throw new \RuntimeException('Invalid version_order configuration option');
335
        }
336
337
        $rows = $this->fetchAll(sprintf('SELECT * FROM %s ORDER BY %s', $this->getSchemaTableName(), $orderBy));
338
        foreach ($rows as $version) {
339
            $result[$version['version']] = $version;
340
        }
341
342
        return $result;
343
    }
344
345
    /**
346
     * {@inheritdoc}
347
     */
348
    public function migrated(MigrationInterface $migration, $direction, $startTime, $endTime)
349 208
    {
350
        if (strcasecmp($direction, MigrationInterface::UP) === 0) {
351
            // up
352 208
            $sql = sprintf(
353 208
                "INSERT INTO %s (%s, %s, %s, %s, %s) VALUES ('%s', '%s', '%s', '%s', %s);",
354 208
                $this->quoteTableName($this->getSchemaTableName()),
355 208
                $this->quoteColumnName('version'),
356 208
                $this->quoteColumnName('migration_name'),
357 208
                $this->quoteColumnName('start_time'),
358 208
                $this->quoteColumnName('end_time'),
359 208
                $this->quoteColumnName('breakpoint'),
360 208
                $migration->getVersion(),
361 208
                substr($migration->getName(), 0, 100),
362 208
                $startTime,
363 208
                $endTime,
364 208
                $this->castToBool(false)
365 208
            );
366 208
367 208
            $this->execute($sql);
368
        } else {
369 208
            // down
370 208
            $sql = sprintf(
371 208
                "DELETE FROM %s WHERE %s = '%s'",
372 208
                $this->quoteTableName($this->getSchemaTableName()),
373 208
                $this->quoteColumnName('version'),
374
                $migration->getVersion()
375
            );
376
377
            $this->execute($sql);
378
        }
379 121
380
        return $this;
381 121
    }
382
383
    /**
384
     * {@inheritdoc}
385
     */
386
    public function toggleBreakpoint(MigrationInterface $migration)
387
    {
388
        $this->query(
389
            sprintf(
390
                'UPDATE %1$s SET %2$s = CASE %2$s WHEN %3$s THEN %4$s ELSE %3$s END, %7$s = %7$s WHERE %5$s = \'%6$s\';',
391
                $this->getSchemaTableName(),
392
                $this->quoteColumnName('breakpoint'),
393
                $this->castToBool(true),
394
                $this->castToBool(false),
395
                $this->quoteColumnName('version'),
396
                $migration->getVersion(),
397
                $this->quoteColumnName('start_time')
398
            )
399
        );
400
401
        return $this;
402
    }
403
404
    /**
405
     * {@inheritdoc}
406
     */
407
    public function resetAllBreakpoints()
408
    {
409
        return $this->execute(
410
            sprintf(
411
                'UPDATE %1$s SET %2$s = %3$s, %4$s = %4$s WHERE %2$s <> %3$s;',
412
                $this->getSchemaTableName(),
413
                $this->quoteColumnName('breakpoint'),
414
                $this->castToBool(false),
415
                $this->quoteColumnName('start_time')
416
            )
417
        );
418
    }
419
420
    /**
421
     * {@inheritdoc}
422
     */
423
    public function createSchema($schemaName = 'public')
424
    {
425
        throw new BadMethodCallException('Creating a schema is not supported');
426
    }
427
428
    /**
429
     * {@inheritdoc}
430
     */
431
    public function dropSchema($name)
432
    {
433
        throw new BadMethodCallException('Dropping a schema is not supported');
434
    }
435
436
    /**
437
     * {@inheritdoc}
438
     */
439
    public function getColumnTypes()
440
    {
441
        return [
442
            'string',
443
            'char',
444
            'text',
445
            'integer',
446
            'biginteger',
447
            'bit',
448
            'float',
449
            'decimal',
450
            'datetime',
451
            'timestamp',
452
            'time',
453
            'date',
454
            'blob',
455
            'binary',
456
            'varbinary',
457
            'boolean',
458
            'uuid',
459
            // Geospatial data types
460
            'geometry',
461
            'point',
462
            'linestring',
463
            'polygon',
464
        ];
465
    }
466
467
    /**
468
     * {@inheritdoc}
469
     */
470
    public function castToBool($value)
471
    {
472
        return (bool)$value ? 1 : 0;
473
    }
474
475
    /**
476
     * Retrieve a database connection attribute
477
     * @see http://php.net/manual/en/pdo.getattribute.php
478
     *
479
     * @param int $attribute One of the PDO::ATTR_* constants
480
     * @return mixed
481
     */
482
    public function getAttribute($attribute)
483
    {
484
        return $this->connection->getAttribute($attribute);
485
    }
486
487
    /**
488
     * Get the defintion for a `DEFAULT` statement.
489
     *
490
     * @param  mixed $default Default value
491
     * @param string $columnType column type added
492
     * @return string
493
     */
494 View Code Duplication
    protected function getDefaultValueDefinition($default, $columnType = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
495
    {
496
        if (is_string($default) && 'CURRENT_TIMESTAMP' !== $default) {
497
            $default = $this->getConnection()->quote($default);
498
        } elseif (is_bool($default)) {
499
            $default = $this->castToBool($default);
500
        } elseif ($columnType === static::PHINX_TYPE_BOOLEAN) {
501
            $default = $this->castToBool((bool)$default);
502
        }
503
504
        return isset($default) ? " DEFAULT $default" : '';
505
    }
506
507
    /**
508
     * Executes all the ALTER TABLE instructions passed for the given table
509
     *
510
     * @param string $tableName The table name to use in the ALTER statement
511
     * @param AlterInstructions $instructions The object containing the alter sequence
512
     * @return void
513
     */
514
    protected function executeAlterSteps($tableName, AlterInstructions $instructions)
515
    {
516
        $alter = sprintf('ALTER TABLE %s %%s', $this->quoteTableName($tableName));
517
        $instructions->execute($alter, [$this, 'execute']);
518
    }
519
520
    /**
521
     * {@inheritdoc}
522
     */
523
    public function addColumn(Table $table, Column $column)
524
    {
525
        $instructions = $this->getAddColumnInstructions($table, $column);
526
        $this->executeAlterSteps($table->getName(), $instructions);
527
    }
528
529
    /**
530
     * Returns the instrutions to add the specified column to a database table.
531
     *
532
     * @param \Phinx\Db\Table\Table $table Table
533
     * @param \Phinx\Db\Table\Column $column Column
534
     * @return AlterInstructions
535
     */
536
    abstract protected function getAddColumnInstructions(Table $table, Column $column);
537
538
    /**
539
     * {@inheritdoc}
540
     */
541
    public function renameColumn($tableName, $columnName, $newColumnName)
542
    {
543
        $instructions = $this->getRenameColumnInstructions($tableName, $columnName, $newColumnName);
544
        $this->executeAlterSteps($tableName, $instructions);
545
    }
546
547
    /**
548
     * Returns the instructions to rename the specified column.
549
     *
550
     * @param string $tableName Table Name
551
     * @param string $columnName Column Name
552
     * @param string $newColumnName New Column Name
553
     * @return AlterInstructions:w
0 ignored issues
show
Documentation introduced by
The doc-type AlterInstructions:w could not be parsed: Unknown type name "AlterInstructions:w" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
554
     *
555
     */
556
    abstract protected function getRenameColumnInstructions($tableName, $columnName, $newColumnName);
557
558
    /**
559
     * {@inheritdoc}
560
     */
561
    public function changeColumn($tableName, $columnName, Column $newColumn)
562
    {
563
        $instructions = $this->getChangeColumnInstructions($tableName, $columnName, $newColumn);
564
        $this->executeAlterSteps($tableName, $instructions);
565
    }
566
567
    /**
568
     * Returns the instructions to change a table column type.
569
     *
570
     * @param string $tableName  Table Name
571
     * @param string $columnName Column Name
572
     * @param \Phinx\Db\Table\Column $newColumn  New Column
573
     * @return AlterInstructions
574
     */
575
    abstract protected function getChangeColumnInstructions($tableName, $columnName, Column $newColumn);
576
577
    /**
578
     * {@inheritdoc}
579
     */
580
    public function dropColumn($tableName, $columnName)
581
    {
582
        $instructions = $this->getDropColumnInstructions($tableName, $columnName);
583
        $this->executeAlterSteps($tableName, $instructions);
584
    }
585
586
    /**
587
     * Returns the instructions to drop the specified column.
588
     *
589
     * @param string $tableName Table Name
590
     * @param string $columnName Column Name
591
     * @return AlterInstructions
592
     */
593
    abstract protected function getDropColumnInstructions($tableName, $columnName);
594
595
    /**
596
     * {@inheritdoc}
597
     */
598
    public function addIndex(Table $table, Index $index)
599
    {
600
        $instructions = $this->getAddIndexInstructions($table, $index);
601
        $this->executeAlterSteps($table->getName(), $instructions);
602
    }
603
604
    /**
605
     * Returns the instructions to add the specified index to a database table.
606
     *
607
     * @param \Phinx\Db\Table\Table $table Table
608
     * @param \Phinx\Db\Table\Index $index Index
609
     * @return AlterInstructions
610
     */
611
    abstract protected function getAddIndexInstructions(Table $table, Index $index);
612
613
    /**
614
     * {@inheritdoc}
615
     */
616
    public function dropIndex($tableName, $columns)
617
    {
618
        $instructions = $this->getDropIndexByColumnsInstructions($tableName, $columns);
619
        $this->executeAlterSteps($tableName, $instructions);
620
    }
621
622
    /**
623
     * Returns the instructions to drop the specified index from a database table.
624
     *
625
     * @param string $tableName The name of of the table where the index is
626
     * @param mixed $columns Column(s)
627
     * @return AlterInstructions
628
     */
629
    abstract protected function getDropIndexByColumnsInstructions($tableName, $columns);
630
631
    /**
632
     * {@inheritdoc}
633
     */
634
    public function dropIndexByName($tableName, $indexName)
635
    {
636
        $instructions = $this->getDropIndexByNameInstructions($tableName, $indexName);
637
        $this->executeAlterSteps($tableName, $instructions);
638
    }
639
640
    /**
641
     * Returns the instructions to drop the index specified by name from a database table.
642
     *
643
     * @param string $tableName The table name whe the index is
644
     * @param string $indexName The name of the index
645
     * @return AlterInstructions
646
     */
647
    abstract protected function getDropIndexByNameInstructions($tableName, $indexName);
648
649
    /**
650
     * {@inheritdoc}
651
     */
652
    public function addForeignKey(Table $table, ForeignKey $foreignKey)
653
    {
654
        $instructions = $this->getAddForeignKeyInstructions($table, $foreignKey);
655
        $this->executeAlterSteps($table->getName(), $instructions);
656
    }
657
658
    /**
659
     * Returns the instructions to adds the specified foreign key to a database table.
660
     *
661
     * @param \Phinx\Db\Table\Table $table The table to add the constraint to
662
     * @param \Phinx\Db\Table\ForeignKey $foreignKey The foreign key to add
663
     * @return AlterInstructions
664
     */
665
    abstract protected function getAddForeignKeyInstructions(Table $table, ForeignKey $foreignKey);
666
667
    /**
668
     * {@inheritdoc}
669
     */
670
    public function dropForeignKey($tableName, $columns, $constraint = null)
671
    {
672
        if ($constraint) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $constraint of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
673
            $instructions = $this->getDropForeignKeyInstructions($tableName, $constraint);
674
        } else {
675
            $instructions = $this->getDropForeignKeyByColumnsInstructions($tableName, $columns);
676
        }
677
678
        $this->executeAlterSteps($tableName, $instructions);
679
    }
680
681
    /**
682
     * Returns the instructions to drop the specified foreign key from a database table.
683
     *
684
     * @param string   $tableName The table where the foreign key constraint is
685
     * @param string   $constraint Constraint name
686
     * @return AlterInstructions
687
     */
688
    abstract protected function getDropForeignKeyInstructions($tableName, $constraint);
689
690
    /**
691
     * Returns the instructions to drop the specified foreign key from a database table.
692
     *
693
     * @param string $tableName The table where the foreign key constraint is
694
     * @param array $columns The list of column names
695
     * @return AlterInstructions
696
     */
697
    abstract protected function getDropForeignKeyByColumnsInstructions($tableName, $columns);
698
699
    /**
700
     * {@inheritdoc}
701
     */
702
    public function dropTable($tableName)
703
    {
704
        $instructions = $this->getDropTableInstructions($tableName);
705
        $this->executeAlterSteps($tableName, $instructions);
706
    }
707
708
    /**
709
     * Returns the instructions to drop the specified database table.
710
     *
711
     * @param string $tableName Table Name
712
     * @return AlterInstructions
713
     */
714
    abstract protected function getDropTableInstructions($tableName);
715
716
    /**
717
     * {@inheritdoc}
718
     */
719
    public function renameTable($tableName, $newTableName)
720
    {
721
        $instructions = $this->getRenameTableInstructions($tableName, $newTableName);
722
        $this->executeAlterSteps($tableName, $instructions);
723
    }
724
725
    /**
726
     * Returns the instructions to rename the specified database table.
727
     *
728
     * @param string $tableName Table Name
729
     * @param string $newTableName New Name
730
     * @return AlterInstructions
731
     */
732
    abstract protected function getRenameTableInstructions($tableName, $newTableName);
733
734
    /**
735
     * {@inheritdoc}
736
     */
737
    public function changeTable(Table $table, array $newOptions)
738
    {
739
        $instructions = $this->getChangeTableInstructions($table, $newOptions);
740
        $this->executeAlterSteps($table->getName(), $instructions);
741
    }
742
743
    /**
744
     * Returns the instructions to change the options for the specified database table.
745
     *
746
     * @param Table $table Table
747
     * @param array $newOptions New Options
748
     * @return AlterInstructions
749
     */
750
    abstract protected function getChangeTableInstructions(Table $table, array $newOptions);
751
752
    /**
753
     * {@inheritdoc}
754
     */
755
    public function executeActions(Table $table, array $actions)
756
    {
757
        $instructions = new AlterInstructions();
758
759
        foreach ($actions as $action) {
760
            switch (true) {
761
                case ($action instanceof AddColumn):
762
                    $instructions->merge($this->getAddColumnInstructions($table, $action->getColumn()));
763
                    break;
764
765
                case ($action instanceof AddIndex):
766
                    $instructions->merge($this->getAddIndexInstructions($table, $action->getIndex()));
767
                    break;
768
769
                case ($action instanceof AddForeignKey):
770
                    $instructions->merge($this->getAddForeignKeyInstructions($table, $action->getForeignKey()));
771
                    break;
772
773
                case ($action instanceof ChangeColumn):
774
                    $instructions->merge($this->getChangeColumnInstructions(
775
                        $table->getName(),
776
                        $action->getColumnName(),
777
                        $action->getColumn()
778
                    ));
779
                    break;
780
781
                case ($action instanceof DropForeignKey && !$action->getForeignKey()->getConstraint()):
782
                    $instructions->merge($this->getDropForeignKeyByColumnsInstructions(
783
                        $table->getName(),
784
                        $action->getForeignKey()->getColumns()
785
                    ));
786
                    break;
787
788
                case ($action instanceof DropForeignKey && $action->getForeignKey()->getConstraint()):
789
                    $instructions->merge($this->getDropForeignKeyInstructions(
790
                        $table->getName(),
791
                        $action->getForeignKey()->getConstraint()
0 ignored issues
show
Bug introduced by
It seems like $action->getForeignKey()->getConstraint() targeting Phinx\Db\Table\ForeignKey::getConstraint() can also be of type boolean; however, Phinx\Db\Adapter\PdoAdap...oreignKeyInstructions() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
792
                    ));
793
                    break;
794
795
                case ($action instanceof DropIndex && $action->getIndex()->getName() !== null):
796
                    $instructions->merge($this->getDropIndexByNameInstructions(
797
                        $table->getName(),
798
                        $action->getIndex()->getName()
799
                    ));
800
                    break;
801
802
                case ($action instanceof DropIndex && $action->getIndex()->getName() == null):
803
                    $instructions->merge($this->getDropIndexByColumnsInstructions(
804
                        $table->getName(),
805
                        $action->getIndex()->getColumns()
806
                    ));
807
                    break;
808
809
                case ($action instanceof DropTable):
810
                    $instructions->merge($this->getDropTableInstructions(
811
                        $table->getName()
812
                    ));
813
                    break;
814
815
                case ($action instanceof RemoveColumn):
816
                    $instructions->merge($this->getDropColumnInstructions(
817
                        $table->getName(),
818
                        $action->getColumn()->getName()
819
                    ));
820
                    break;
821
822
                case ($action instanceof RenameColumn):
823
                    $instructions->merge($this->getRenameColumnInstructions(
824
                        $table->getName(),
825
                        $action->getColumn()->getName(),
826
                        $action->getNewName()
827
                    ));
828
                    break;
829
830
                case ($action instanceof RenameTable):
831
                    $instructions->merge($this->getRenameTableInstructions(
832
                        $table->getName(),
833
                        $action->getNewName()
834
                    ));
835
                    break;
836
837
                case ($action instanceof ChangeTable):
838
                    $instructions->merge($this->getChangeTableInstructions(
839
                        $table,
840
                        $action->getNewOptions()
841
                    ));
842
                    break;
843
844
                default:
845
                    throw new \InvalidArgumentException(
846
                        sprintf("Don't know how to execute action: '%s'", get_class($action))
847
                    );
848
            }
849
        }
850
851
        $this->executeAlterSteps($table->getName(), $instructions);
852
    }
853
}
854