Completed
Push — master ( 152a5f...57e856 )
by José
11s
created

PdoAdapter::quoteValue()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 1
crap 3
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\DropForeignKey;
37
use Phinx\Db\Action\DropIndex;
38
use Phinx\Db\Action\DropTable;
39
use Phinx\Db\Action\RemoveColumn;
40
use Phinx\Db\Action\RenameColumn;
41
use Phinx\Db\Action\RenameTable;
42
use Phinx\Db\Table\Column;
43
use Phinx\Db\Table\ForeignKey;
44
use Phinx\Db\Table\Index;
45
use Phinx\Db\Table\Table;
46
use Phinx\Db\Util\AlterInstructions;
47
use Phinx\Migration\MigrationInterface;
48
use Symfony\Component\Console\Output\OutputInterface;
49
50
/**
51 287
 * Phinx PDO Adapter.
52
 *
53 287
 * @author Rob Morgan <[email protected]>
54
 */
55 287
abstract class PdoAdapter extends AbstractAdapter implements DirectActionInterface
56 3
{
57 3
    /**
58
     * @var \PDO|null
59 287
     */
60
    protected $connection;
61
62
    /**
63
     * Writes a message to stdout if vebose output is on
64
     *
65
     * @param string $message The message to show
66
     * @return void
67
     */
68 193
    protected function verboseLog($message)
69
    {
70 193
        if (!$this->isDryRunEnabled() &&
71
             $this->getOutput()->getVerbosity() < OutputInterface::VERBOSITY_VERY_VERBOSE) {
72
            return;
73 193
        }
74 191
75 191
        $this->getOutput()->writeln($message);
76 74
    }
77 74
78
    /**
79
     * {@inheritdoc}
80
     */
81
    public function setOptions(array $options)
82
    {
83
        parent::setOptions($options);
84
85
        if (isset($options['connection'])) {
86 74
            $this->setConnection($options['connection']);
87
        }
88
89
        return $this;
90
    }
91
92
    /**
93 193
     * Sets the database connection.
94
     *
95
     * @param \PDO $connection Connection
96
     * @return \Phinx\Db\Adapter\AdapterInterface
97
     */
98
    public function setConnection(\PDO $connection)
99
    {
100
        $this->connection = $connection;
101 191
102
        // Create the schema table if it doesn't already exist
103 191
        if (!$this->hasSchemaTable()) {
104 189
            $this->createSchemaTable();
105 189
        } else {
106 191
            $table = new \Phinx\Db\Table($this->getSchemaTableName(), [], $this);
107
            if (!$table->hasColumn('migration_name')) {
108
                $table
109
                    ->addColumn(
110
                        'migration_name',
111
                        'string',
112 1
                        ['limit' => 100, 'after' => 'version', 'default' => null, 'null' => true]
113
                    )
114 1
                    ->save();
115
            }
116
            if (!$table->hasColumn('breakpoint')) {
117
                $table
118
                    ->addColumn('breakpoint', 'boolean', ['default' => false])
119
                    ->save();
120
            }
121
        }
122
123
        return $this;
124
    }
125
126 218
    /**
127
     * Gets the database connection
128 218
     *
129 3
     * @return \PDO
130 3
     */
131
    public function getConnection()
132
    {
133 217
        if ($this->connection === null) {
134
            $this->connect();
135
        }
136
137
        return $this->connection;
138
    }
139
140
    /**
141
     * {@inheritdoc}
142 220
     */
143
    public function connect()
144 220
    {
145
    }
146
147
    /**
148
     * {@inheritdoc}
149
     */
150 151
    public function disconnect()
151
    {
152 151
    }
153 151
154
    /**
155
     * {@inheritdoc}
156
     */
157
    public function execute($sql)
158
    {
159 213
        $this->verboseLog($sql);
160
161 213
        if ($this->isDryRunEnabled()) {
162 213
            return 0;
163 213
        }
164 208
165 208
        return $this->getConnection()->exec($sql);
166 213
    }
167
168
    /**
169
     * Executes a query and returns PDOStatement.
170
     *
171
     * @param string $sql SQL
172 1
     * @return \PDOStatement
173
     */
174 1
    public function query($sql)
175 1
    {
176 1
        return $this->getConnection()->query($sql);
177 1
    }
178
179 1
    /**
180 1
     * {@inheritdoc}
181 1
     */
182
    public function fetchRow($sql)
183 1
    {
184 1
        $result = $this->query($sql);
185 1
186
        return $result->fetch();
187
    }
188
189
    /**
190 11
     * {@inheritdoc}
191
     */
192 11
    public function fetchAll($sql)
193 11
    {
194 11
        $rows = [];
195 11
        $result = $this->query($sql);
196
        while ($row = $result->fetch()) {
197 11
            $rows[] = $row;
198 11
        }
199 11
200
        return $rows;
201 11
    }
202 11
203 11
    /**
204 11
     * {@inheritdoc}
205 11
     */
206 11
    public function insert(Table $table, $row)
207
    {
208 11
        $sql = sprintf(
209 11
            'INSERT INTO %s ',
210
            $this->quoteTableName($table->getName())
211 11
        );
212 11
        $columns = array_keys($row);
213 11
        $sql .= '(' . implode(', ', array_map([$this, 'quoteColumnName'], $columns)) . ')';
214
215 11
        if ($this->isDryRunEnabled()) {
216 11
            $sql .= ' VALUES (' . implode(', ', array_map([$this, 'quoteValue'], $row)) . ');';
217 11
            $this->output->writeln($sql);
218
        } else {
219
            $sql .= ' VALUES (' . implode(', ', array_fill(0, count($columns), '?')) . ')';
220
            $stmt = $this->getConnection()->prepare($sql);
221
            $stmt->execute(array_values($row));
222 5
        }
223
    }
224 5
225
    /**
226 5
     * Quotes a database value.
227
     *
228
     * @param mixed $value  The value to quote
229
     * @return mixed
230
     */
231
    private function quoteValue($value)
232 8
    {
233
        if (is_numeric($value)) {
234 8
            return $value;
235
        }
236 8
237 8
        if ($value === null) {
238 6
            return 'null';
239 6
        }
240 2
241 1
        return $this->getConnection()->quote($value);
242 1
    }
243 1
244 1
    /**
245 8
     * {@inheritdoc}
246
     */
247 7
    public function bulkinsert(Table $table, $rows)
248 7
    {
249 7
        $sql = sprintf(
250 7
            'INSERT INTO %s ',
251
            $this->quoteTableName($table->getName())
252 7
        );
253
        $current = current($rows);
254
        $keys = array_keys($current);
255
        $sql .= '(' . implode(', ', array_map([$this, 'quoteColumnName'], $keys)) . ') VALUES ';
256
257
        if ($this->isDryRunEnabled()) {
258 5
            $values = array_map(function ($row) {
259
                return '(' . implode(', ', array_map([$this, 'quoteValue'], $row)) . ')';
260 5
            }, $rows);
261
            $sql .= implode(', ', $values) . ';';
262 5
            $this->output->writeln($sql);
263 5
        } else {
264 5
            $count_keys = count($keys);
265 5
            $query = '(' . implode(', ', array_fill(0, $count_keys, '?')) . ')';
266 5
            $count_vars = count($rows);
267 5
            $queries = array_fill(0, $count_vars, $query);
268 5
            $sql .= implode(',', $queries);
269 5
            $stmt = $this->getConnection()->prepare($sql);
270 5
            $vals = [];
271 5
272 5
            foreach ($rows as $row) {
273 5
                foreach ($row as $v) {
274 5
                    $vals[] = $v;
275 5
                }
276
            }
277 5
278 5
            $stmt->execute($vals);
279
        }
280 3
    }
281 3
282 3
    /**
283 3
     * {@inheritdoc}
284 3
     */
285 3
    public function getVersions()
286
    {
287 3
        $rows = $this->getVersionLog();
288
289
        return array_keys($rows);
290 5
    }
291
292
    /**
293
     * {@inheritdoc}
294
     */
295
    public function getVersionLog()
296 1
    {
297
        $result = [];
298 1
299 1
        switch ($this->options['version_order']) {
300 1
            case \Phinx\Config\Config::VERSION_ORDER_CREATION_TIME:
301 1
                $orderBy = 'version ASC';
302 1
                break;
303 1
            case \Phinx\Config\Config::VERSION_ORDER_EXECUTION_TIME:
304 1
                $orderBy = 'start_time ASC, version ASC';
305 1
                break;
306 1
            default:
307 1
                throw new \RuntimeException('Invalid version_order configuration option');
308 1
        }
309 1
310
        $rows = $this->fetchAll(sprintf('SELECT * FROM %s ORDER BY %s', $this->getSchemaTableName(), $orderBy));
311 1
        foreach ($rows as $version) {
312
            $result[$version['version']] = $version;
313
        }
314
315
        return $result;
316
    }
317 1
318
    /**
319 1
     * {@inheritdoc}
320 1
     */
321 1
    public function migrated(MigrationInterface $migration, $direction, $startTime, $endTime)
322 1
    {
323 1
        if (strcasecmp($direction, MigrationInterface::UP) === 0) {
324 1
            // up
325 1
            $sql = sprintf(
326 1
                "INSERT INTO %s (%s, %s, %s, %s, %s) VALUES ('%s', '%s', '%s', '%s', %s);",
327 1
                $this->quoteTableName($this->getSchemaTableName()),
328
                $this->quoteColumnName('version'),
329
                $this->quoteColumnName('migration_name'),
330
                $this->quoteColumnName('start_time'),
331
                $this->quoteColumnName('end_time'),
332
                $this->quoteColumnName('breakpoint'),
333
                $migration->getVersion(),
334
                substr($migration->getName(), 0, 100),
335
                $startTime,
336
                $endTime,
337
                $this->castToBool(false)
338
            );
339
340
            $this->execute($sql);
341
        } else {
342
            // down
343
            $sql = sprintf(
344
                "DELETE FROM %s WHERE %s = '%s'",
345
                $this->quoteTableName($this->getSchemaTableName()),
346
                $this->quoteColumnName('version'),
347
                $migration->getVersion()
348
            );
349 208
350
            $this->execute($sql);
351
        }
352 208
353 208
        return $this;
354 208
    }
355 208
356 208
    /**
357 208
     * @inheritDoc
358 208
     */
359 208
    public function toggleBreakpoint(MigrationInterface $migration)
360 208
    {
361 208
        $this->query(
362 208
            sprintf(
363 208
                '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\';',
364 208
                $this->getSchemaTableName(),
365 208
                $this->quoteColumnName('breakpoint'),
366 208
                $this->castToBool(true),
367 208
                $this->castToBool(false),
368
                $this->quoteColumnName('version'),
369 208
                $migration->getVersion(),
370 208
                $this->quoteColumnName('start_time')
371 208
            )
372 208
        );
373 208
374
        return $this;
375
    }
376
377
    /**
378
     * @inheritDoc
379 121
     */
380
    public function resetAllBreakpoints()
381 121
    {
382
        return $this->execute(
383
            sprintf(
384
                'UPDATE %1$s SET %2$s = %3$s, %4$s = %4$s WHERE %2$s <> %3$s;',
385
                $this->getSchemaTableName(),
386
                $this->quoteColumnName('breakpoint'),
387
                $this->castToBool(false),
388
                $this->quoteColumnName('start_time')
389
            )
390
        );
391
    }
392
393
    /**
394
     * {@inheritdoc}
395
     */
396
    public function createSchema($schemaName = 'public')
397
    {
398
        throw new BadMethodCallException('Creating a schema is not supported');
399
    }
400
401
    /**
402
     * {@inheritdoc}
403
     */
404
    public function dropSchema($name)
405
    {
406
        throw new BadMethodCallException('Dropping a schema is not supported');
407
    }
408
409
    /**
410
     * {@inheritdoc}
411
     */
412
    public function getColumnTypes()
413
    {
414
        return [
415
            'string',
416
            'char',
417
            'text',
418
            'integer',
419
            'biginteger',
420
            'bit',
421
            'float',
422
            'decimal',
423
            'datetime',
424
            'timestamp',
425
            'time',
426
            'date',
427
            'blob',
428
            'binary',
429
            'varbinary',
430
            'boolean',
431
            'uuid',
432
            // Geospatial data types
433
            'geometry',
434
            'point',
435
            'linestring',
436
            'polygon',
437
        ];
438
    }
439
440
    /**
441
     * {@inheritdoc}
442
     */
443
    public function castToBool($value)
444
    {
445
        return (bool)$value ? 1 : 0;
446
    }
447
448
    /**
449
     * Retrieve a database connection attribute
450
     * @see http://php.net/manual/en/pdo.getattribute.php
451
     *
452
     * @param int $attribute One of the PDO::ATTR_* constants
453
     * @return mixed
454
     */
455
    public function getAttribute($attribute)
456
    {
457
        return $this->connection->getAttribute($attribute);
458
    }
459
460
    /**
461
     * Get the defintion for a `DEFAULT` statement.
462
     *
463
     * @param  mixed $default Default value
464
     * @param string $columnType column type added
465
     * @return string
466
     */
467 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...
468
    {
469
        if (is_string($default) && 'CURRENT_TIMESTAMP' !== $default) {
470
            $default = $this->getConnection()->quote($default);
471
        } elseif (is_bool($default)) {
472
            $default = $this->castToBool($default);
473
        } elseif ($columnType === static::PHINX_TYPE_BOOLEAN) {
474
            $default = $this->castToBool((bool)$default);
475
        }
476
477
        return isset($default) ? " DEFAULT $default" : '';
478
    }
479
480
    /**
481
     * Executes all the ALTER TABLE instructions passed for the given table
482
     *
483
     * @param string $tableName The table name to use in the ALTER statement
484
     * @param AlterInstructions $instructions The object containing the alter sequence
485
     * @return void
486
     */
487
    protected function executeAlterSteps($tableName, AlterInstructions $instructions)
488
    {
489
        $alter = sprintf('ALTER TABLE %s %%s', $this->quoteTableName($tableName));
490
        $instructions->execute($alter, [$this, 'execute']);
491
    }
492
493
    /**
494
     * {@inheritdoc}
495
     */
496
    public function addColumn(Table $table, Column $column)
497
    {
498
        $instructions = $this->getAddColumnInstructions($table, $column);
499
        $this->executeAlterSteps($table, $instructions);
0 ignored issues
show
Documentation introduced by
$table is of type object<Phinx\Db\Table\Table>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
500
    }
501
502
    /**
503
     * Returns the instrutions to add the specified column to a database table.
504
     *
505
     * @param \Phinx\Db\Table\Table $table Table
506
     * @param \Phinx\Db\Table\Column $column Column
507
     * @return AlterInstructions
508
     */
509
    abstract protected function getAddColumnInstructions(Table $table, Column $column);
510
511
    /**
512
     * {@inheritdoc}
513
     */
514
    public function renameColumn($tableName, $columnName, $newColumnName)
515
    {
516
        $instructions = $this->getRenameColumnInstructions($tableName, $columnName, $newColumnName);
517
        $this->executeAlterSteps($tableName, $instructions);
518
    }
519
520
    /**
521
     * Returns the instructions to rename the specified column.
522
     *
523
     * @param string $tableName Table Name
524
     * @param string $columnName Column Name
525
     * @param string $newColumnName New Column Name
526
     * @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...
527
     *
528
     */
529
    abstract protected function getRenameColumnInstructions($tableName, $columnName, $newColumnName);
530
531
    /**
532
     * {@inheritdoc}
533
     */
534
    public function changeColumn($tableName, $columnName, Column $newColumn)
535
    {
536
        $instructions = $this->getChangeColumnInstructions($tableName, $columnName, $newColumn);
537
        $this->executeAlterSteps($tableName, $instructions);
538
    }
539
540
    /**
541
     * Returns the instructions to change a table column type.
542
     *
543
     * @param string $tableName  Table Name
544
     * @param string $columnName Column Name
545
     * @param \Phinx\Db\Table\Column $newColumn  New Column
546
     * @return AlterInstructions
547
     */
548
    abstract protected function getChangeColumnInstructions($tableName, $columnName, Column $newColumn);
549
550
    /**
551
     * {@inheritdoc}
552
     */
553
    public function dropColumn($tableName, $columnName)
554
    {
555
        $instructions = $this->getDropColumnInstructions($tableName, $columnName);
556
        $this->executeAlterSteps($tableName, $instructions);
557
    }
558
559
    /**
560
     * Returns the instructions to drop the specified column.
561
     *
562
     * @param string $tableName Table Name
563
     * @param string $columnName Column Name
564
     * @return AlterInstructions
565
     */
566
    abstract protected function getDropColumnInstructions($tableName, $columnName);
567
568
    /**
569
     * {@inheritdoc}
570
     */
571
    public function addIndex(Table $table, Index $index)
572
    {
573
        $instructions = $this->getAddIndexInstructions($table, $index);
574
        $this->executeAlterSteps($table->getName(), $instructions);
575
    }
576
577
    /**
578
     * Returns the instructions to add the specified index to a database table.
579
     *
580
     * @param \Phinx\Db\Table\Table $table Table
581
     * @param \Phinx\Db\Table\Index $index Index
582
     * @return AlterInstructions
583
     */
584
    abstract protected function getAddIndexInstructions(Table $table, Index $index);
585
586
    /**
587
     * {@inheritdoc}
588
     */
589
    public function dropIndex($tableName, $columns)
590
    {
591
        $instructions = $this->getDropIndexByColumnsInstructions($tableName, $columns);
592
        $this->executeAlterSteps($tableName, $instructions);
593
    }
594
595
    /**
596
     * Returns the instructions to drop the specified index from a database table.
597
     *
598
     * @param string $tableName The name of of the table where the index is
599
     * @param mixed $columns Column(s)
600
     * @return AlterInstructions
601
     */
602
    abstract protected function getDropIndexByColumnsInstructions($tableName, $columns);
603
604
    /**
605
     * {@inheritdoc}
606
     */
607
    public function dropIndexByName($tableName, $indexName)
608
    {
609
        $instructions = $this->getDropIndexByNameInstructions($tableName, $indexName);
610
        $this->executeAlterSteps($tableName, $instructions);
611
    }
612
613
    /**
614
     * Returns the instructions to drop the index specified by name from a database table.
615
     *
616
     * @param string $tableName The table name whe the index is
617
     * @param string $indexName The name of the index
618
     * @return AlterInstructions
619
     */
620
    abstract protected function getDropIndexByNameInstructions($tableName, $indexName);
621
622
    /**
623
     * {@inheritdoc}
624
     */
625
    public function addForeignKey(Table $table, ForeignKey $foreignKey)
626
    {
627
        $instructions = $this->getAddForeignKeyInstructions($table, $foreignKey);
628
        $this->executeAlterSteps($table->getName(), $instructions);
629
    }
630
631
    /**
632
     * Returns the instructions to adds the specified foreign key to a database table.
633
     *
634
     * @param \Phinx\Db\Table\Table $table The table to add the constraint to
635
     * @param \Phinx\Db\Table\ForeignKey $foreignKey The foreign key to add
636
     * @return AlterInstructions
637
     */
638
    abstract protected function getAddForeignKeyInstructions(Table $table, ForeignKey $foreignKey);
639
640
    /**
641
     * {@inheritdoc}
642
     */
643
    public function dropForeignKey($tableName, $columns, $constraint = null)
644
    {
645
        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...
646
            $instructions = $this->getDropForeignKeyInstructions($tableName, $constraint);
647
        } else {
648
            $instructions = $this->getDropForeignKeyByColumnsInstructions($tableName, $columns);
649
        }
650
651
        $this->executeAlterSteps($tableName, $instructions);
652
    }
653
654
    /**
655
     * Returns the instructions to drop the specified foreign key from a database table.
656
     *
657
     * @param string   $tableName The table where the foreign key constraint is
658
     * @param string   $constraint Constraint name
659
     * @return AlterInstructions
660
     */
661
    abstract protected function getDropForeignKeyInstructions($tableName, $constraint);
662
663
    /**
664
     * Returns the instructions to drop the specified foreign key from a database table.
665
     *
666
     * @param string $tableName The table where the foreign key constraint is
667
     * @param array $columns The list of column names
668
     * @return AlterInstructions
669
     */
670
    abstract protected function getDropForeignKeyByColumnsInstructions($tableName, $columns);
671
672
    /**
673
     * {@inheritdoc}
674
     */
675
    public function dropTable($tableName)
676
    {
677
        $instructions = $this->getDropTableInstructions($tableName);
678
        $this->executeAlterSteps($tableName, $instructions);
679
    }
680
681
    /**
682
     * Returns the instructions to drop the specified database table.
683
     *
684
     * @param string $tableName Table Name
685
     * @return AlterInstructions
686
     */
687
    abstract protected function getDropTableInstructions($tableName);
688
689
    /**
690
     * {@inheritdoc}
691
     */
692
    public function renameTable($tableName, $newTableName)
693
    {
694
        $instructions = $this->getRenameTableInstructions($tableName, $newTableName);
695
        $this->executeAlterSteps($tableName, $instructions);
696
    }
697
698
    /**
699
     * Returns the instructions to rename the specified database table.
700
     *
701
     * @param string $tableName Table Name
702
     * @param string $newTableName New Name
703
     * @return AlterInstructions
704
     */
705
    abstract protected function getRenameTableInstructions($tableName, $newTableName);
706
707
    /**
708
     * {@inheritdoc}
709
     */
710
    public function executeActions(Table $table, array $actions)
711
    {
712
        $instructions = new AlterInstructions();
713
714
        foreach ($actions as $action) {
715
            switch (true) {
716
                case ($action instanceof AddColumn):
717
                    $instructions->merge($this->getAddColumnInstructions($table, $action->getColumn()));
718
                    break;
719
720
                case ($action instanceof AddIndex):
721
                    $instructions->merge($this->getAddIndexInstructions($table, $action->getIndex()));
722
                    break;
723
724
                case ($action instanceof AddForeignKey):
725
                    $instructions->merge($this->getAddForeignKeyInstructions($table, $action->getForeignKey()));
726
                    break;
727
728
                case ($action instanceof ChangeColumn):
729
                    $instructions->merge($this->getChangeColumnInstructions(
730
                        $table->getName(),
731
                        $action->getColumnName(),
732
                        $action->getColumn()
733
                    ));
734
                    break;
735
736
                case ($action instanceof DropForeignKey && !$action->getForeignKey()->getConstraint()):
737
                    $instructions->merge($this->getDropForeignKeyByColumnsInstructions(
738
                        $table->getName(),
739
                        $action->getForeignKey()->getColumns()
740
                    ));
741
                    break;
742
743
                case ($action instanceof DropForeignKey && $action->getForeignKey()->getConstraint()):
744
                    $instructions->merge($this->getDropForeignKeyInstructions(
745
                        $table->getName(),
746
                        $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...
747
                    ));
748
                    break;
749
750
                case ($action instanceof DropIndex && $action->getIndex()->getName() !== null):
751
                    $instructions->merge($this->getDropIndexByNameInstructions(
752
                        $table->getName(),
753
                        $action->getIndex()->getName()
754
                    ));
755
                    break;
756
757
                case ($action instanceof DropIndex && $action->getIndex()->getName() == null):
758
                    $instructions->merge($this->getDropIndexByColumnsInstructions(
759
                        $table->getName(),
760
                        $action->getIndex()->getColumns()
761
                    ));
762
                    break;
763
764
                case ($action instanceof DropTable):
765
                    $instructions->merge($this->getDropTableInstructions(
766
                        $table->getName()
767
                    ));
768
                    break;
769
770
                case ($action instanceof RemoveColumn):
771
                    $instructions->merge($this->getDropColumnInstructions(
772
                        $table->getName(),
773
                        $action->getColumn()->getName()
774
                    ));
775
                    break;
776
777
                case ($action instanceof RenameColumn):
778
                    $instructions->merge($this->getRenameColumnInstructions(
779
                        $table->getName(),
780
                        $action->getColumn()->getName(),
781
                        $action->getNewName()
782
                    ));
783
                    break;
784
785
                case ($action instanceof RenameTable):
786
                    $instructions->merge($this->getRenameTableInstructions(
787
                        $table->getName(),
788
                        $action->getNewName()
789
                    ));
790
                    break;
791
792
                default:
793
                    throw new \InvalidArgumentException(
794
                        sprintf("Don't know how to execute action: '%s'", get_class($action))
795
                    );
796
            }
797
        }
798
799
        $this->executeAlterSteps($table->getName(), $instructions);
800
    }
801
}
802