Completed
Push — master ( e33650...15989c )
by José
02:42
created

Table::changePrimaryKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
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
28
 */
29
namespace Phinx\Db;
30
31
use Phinx\Db\Action\AddColumn;
32
use Phinx\Db\Action\AddForeignKey;
33
use Phinx\Db\Action\AddIndex;
34
use Phinx\Db\Action\ChangeColumn;
35
use Phinx\Db\Action\ChangeComment;
36
use Phinx\Db\Action\ChangePrimaryKey;
37
use Phinx\Db\Action\CreateTable;
38
use Phinx\Db\Action\DropColumn;
39
use Phinx\Db\Action\DropForeignKey;
40
use Phinx\Db\Action\DropIndex;
41
use Phinx\Db\Action\DropTable;
42
use Phinx\Db\Action\RemoveColumn;
43
use Phinx\Db\Action\RenameColumn;
44
use Phinx\Db\Action\RenameTable;
45
use Phinx\Db\Adapter\AdapterInterface;
46
use Phinx\Db\Plan\Intent;
47
use Phinx\Db\Plan\Plan;
48
use Phinx\Db\Table\Column;
49
use Phinx\Db\Table\Table as TableValue;
50
51
/**
52
 *
53
 * This object is based loosely on: http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html.
54
 */
55
class Table
56
{
57
    /**
58
     * @var \Phinx\Db\Table\Table
59
     */
60
    protected $table;
61
62
    /**
63
     * @var \Phinx\Db\Adapter\AdapterInterface
64
     */
65
    protected $adapter;
66
67
    /**
68
     * @var \Phinx\Db\Plan\Intent
69
     */
70
    protected $actions;
71
72
    /**
73
     * @var array
74
     */
75
    protected $data = [];
76
77
    /**
78
     * Class Constructor.
79
     *
80
     * @param string $name Table Name
81
     * @param array $options Options
82
     * @param \Phinx\Db\Adapter\AdapterInterface $adapter Database Adapter
83
     */
84 239
    public function __construct($name, $options = [], AdapterInterface $adapter = null)
85
    {
86 239
        $this->table = new TableValue($name, $options);
87 239
        $this->actions = new Intent();
88
89 239
        if ($adapter !== null) {
90 231
            $this->setAdapter($adapter);
91 231
        }
92 239
    }
93
94
    /**
95
     * Gets the table name.
96
     *
97
     * @return string|null
98
     */
99
    public function getName()
100 239
    {
101
        return $this->table->getName();
102 239
    }
103 239
104
    /**
105
     * Gets the table options.
106
     *
107
     * @return array
108
     */
109
    public function getOptions()
110
    {
111 215
        return $this->table->getOptions();
112
    }
113 215
114
    /**
115
     * Gets the table name and options as an object
116
     *
117
     * @return \Phinx\Db\Table\Table
118
     */
119
    public function getTable()
120
    {
121
        return $this->table;
122 239
    }
123
124 239
    /**
125 239
     * Sets the database adapter.
126
     *
127
     * @param \Phinx\Db\Adapter\AdapterInterface $adapter Database Adapter
128
     * @return \Phinx\Db\Table
129
     */
130
    public function setAdapter(AdapterInterface $adapter)
131
    {
132
        $this->adapter = $adapter;
133 189
134
        return $this;
135 189
    }
136
137
    /**
138
     * Gets the database adapter.
139
     *
140
     * @return \Phinx\Db\Adapter\AdapterInterface|null
141
     */
142
    public function getAdapter()
143
    {
144 231
        if (!$this->adapter) {
145
            throw new \RuntimeException('There is no database adapter set yet, cannot proceed');
146 231
        }
147 231
148
        return $this->adapter;
149
    }
150
151
    /**
152
     * Does the table have pending actions?
153
     *
154
     * @return bool
155 225
     */
156
    public function hasPendingActions()
157 225
    {
158
        return count($this->actions->getActions()) > 0 || count($this->data) > 0;
159
    }
160
161
    /**
162
     * Does the table exist?
163
     *
164
     * @return bool
165 195
     */
166
    public function exists()
167 195
    {
168
        return $this->getAdapter()->hasTable($this->getName());
169
    }
170
171
    /**
172
     * Drops the database table.
173
     *
174
     * @return \Phinx\Db\Table
175 1
     */
176
    public function drop()
177 1
    {
178 1
        $this->actions->addAction(new DropTable($this->table));
179
180
        return $this;
181
    }
182
183
    /**
184
     * Renames the database table.
185
     *
186 3
     * @param string $newTableName New Table Name
187
     * @return \Phinx\Db\Table
188 3
     */
189 3
    public function rename($newTableName)
190 3
    {
191
        $this->actions->addAction(new RenameTable($this->table, $newTableName));
192
193
        return $this;
194
    }
195
196
    /**
197
     * Changes the primary key of the database table.
198
     *
199
     * @param string|array|null $columns Column name(s) to belong to the primary key, or null to drop the key
200
     * @return $this
201
     */
202
    public function changePrimaryKey($columns)
203
    {
204
        $this->actions->addAction(new ChangePrimaryKey($this->table, $columns));
205
206
        return $this;
207
    }
208
209
    /**
210
     * Changes the comment of the database table.
211 10
     *
212
     * @param string|null $comment New comment string, or null to drop the comment
213 10
     * @return $this
214
     */
215
    public function changeComment($comment)
216
    {
217
        $this->actions->addAction(new ChangeComment($this->table, $comment));
218
219
        return $this;
220
    }
221
222 196
    /**
223
     * Gets an array of the table columns.
224 196
     *
225 196
     * @return \Phinx\Db\Table\Column[]
226
     */
227
    public function getColumns()
228
    {
229
        return $this->getAdapter()->getColumns($this->getName());
230
    }
231
232
    /**
233 204
     * Gets a table column if it exists.
234
     *
235 204
     * @param string $name Column name
236
     * @return \Phinx\Db\Table\Column|null
237
     */
238
    public function getColumn($name)
239
    {
240
        $columns = array_filter(
241
            $this->getColumns(),
242
            function ($column) use ($name) {
243
                return $column->getName() === $name;
244 196
            }
245
        );
246 196
247 196
        return array_pop($columns);
248
    }
249
250
    /**
251
     * Sets an array of data to be inserted.
252
     *
253
     * @param array $data Data
254
     * @return \Phinx\Db\Table
255 191
     */
256
    public function setData($data)
257 191
    {
258
        $this->data = $data;
259
260
        return $this;
261
    }
262
263
    /**
264
     * Gets the data waiting to be inserted.
265
     *
266 196
     * @return array
267
     */
268 196
    public function getData()
269 196
    {
270
        return $this->data;
271
    }
272
273
    /**
274
     * Resets all of the pending data to be inserted
275
     *
276
     * @return void
277 192
     */
278
    public function resetData()
279 192
    {
280
        $this->setData([]);
281
    }
282
283
    /**
284
     * Resets all of the pending table changes.
285
     *
286
     * @return void
287
     */
288 196
    public function reset()
289
    {
290 196
        $this->actions = new Intent();
291 196
        $this->resetData();
292
    }
293
294
    /**
295
     * Add a table column.
296
     *
297
     * Type can be: string, text, integer, float, decimal, datetime, timestamp,
298
     * time, date, binary, boolean.
299 197
     *
300
     * Valid options can be: limit, default, null, precision or scale.
301 197
     *
302
     * @param string|\Phinx\Db\Table\Column $columnName Column Name
303
     * @param string|\Phinx\Util\Literal $type Column Type
304
     * @param array $options Column Options
305
     * @throws \RuntimeException
306
     * @throws \InvalidArgumentException
307
     * @return \Phinx\Db\Table
308
     */
309 196
    public function addColumn($columnName, $type = null, $options = [])
310
    {
311 196 View Code Duplication
        if ($columnName instanceof Column) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
312 196
            $action = new AddColumn($this->table, $columnName);
313 196
        } else {
314 196
            $action = AddColumn::build($this->table, $columnName, $type, $options);
315 196
        }
316
317
        // Delegate to Adapters to check column type
318
        if (!$this->getAdapter()->isValidColumnType($action->getColumn())) {
319
            throw new \InvalidArgumentException(sprintf(
320
                'An invalid column type "%s" was specified for column "%s".',
321
                $type,
322
                $action->getColumn()->getName()
323
            ));
324
        }
325
326
        $this->actions->addAction($action);
327
328
        return $this;
329
    }
330
331
    /**
332 210
     * Remove a table column.
333
     *
334
     * @param string $columnName Column Name
335 210
     * @return \Phinx\Db\Table
336 1
     */
337
    public function removeColumn($columnName)
338
    {
339
        $action = RemoveColumn::build($this->table, $columnName);
340 209
        $this->actions->addAction($action);
341 207
342 207
        return $this;
343 207
    }
344 207
345 207
    /**
346 2
     * Rename a table column.
347
     *
348
     * @param string $oldName Old Column Name
349
     * @param string $newName New Column Name
350 209
     * @return \Phinx\Db\Table
351 1
     */
352 1
    public function renameColumn($oldName, $newName)
353 1
    {
354 1
        $action = RenameColumn::build($this->table, $oldName, $newName);
355 1
        $this->actions->addAction($action);
356
357
        return $this;
358 208
    }
359 208
360
    /**
361
     * Change a table column type.
362
     *
363
     * @param string        $columnName    Column Name
364
     * @param string|\Phinx\Db\Table\Column|\Phinx\Util\Literal $newColumnType New Column Type
365
     * @param array         $options       Options
366
     * @return \Phinx\Db\Table
367
     */
368 1
    public function changeColumn($columnName, $newColumnType, array $options = [])
369
    {
370 1 View Code Duplication
        if ($newColumnType instanceof Column) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
371 1
            $action = new ChangeColumn($this->table, $columnName, $newColumnType);
372
        } else {
373
            $action = ChangeColumn::build($this->table, $columnName, $newColumnType, $options);
374
        }
375
        $this->actions->addAction($action);
376
377
        return $this;
378
    }
379
380
    /**
381 4
     * Checks to see if a column exists.
382
     *
383 4
     * @param string $columnName Column Name
384 4
     * @return bool
385
     */
386
    public function hasColumn($columnName)
387
    {
388
        return $this->getAdapter()->hasColumn($this->getName(), $columnName);
389
    }
390
391
    /**
392
     * Add an index to a database table.
393
     *
394
     * In $options you can specific unique = true/false or name (index name).
395 17
     *
396
     * @param string|array|\Phinx\Db\Table\Index $columns Table Column(s)
397
     * @param array $options Index Options
398 17
     * @return \Phinx\Db\Table
399 4
     */
400 4
    public function addIndex($columns, array $options = [])
401 4
    {
402 4
        $action = AddIndex::build($this->table, $columns, $options);
403 13
        $this->actions->addAction($action);
404
405
        return $this;
406
    }
407 17
408 15
    /**
409 15
     * Removes the given index from a table.
410
     *
411 17
     * @param array $columns Columns
412 17
     * @return \Phinx\Db\Table
413
     */
414
    public function removeIndex(array $columns)
415
    {
416
        $action = DropIndex::build($this->table, $columns);
417
        $this->actions->addAction($action);
418
419
        return $this;
420
    }
421 89
422
    /**
423 89
     * Removes the given index identified by its name from a table.
424
     *
425
     * @param string $name Index name
426
     * @return \Phinx\Db\Table
427
     */
428
    public function removeIndexByName($name)
429
    {
430
        $action = DropIndex::buildFromName($this->table, $name);
431
        $this->actions->addAction($action);
432
433
        return $this;
434
    }
435 29
436
    /**
437
     * Checks to see if an index exists.
438 29
     *
439 28
     * @param string|array $columns Columns
440 28
     * @return bool
441 22
     */
442 22
    public function hasIndex($columns)
443 28
    {
444 28
        return $this->getAdapter()->hasIndex($this->getName(), $columns);
445 28
    }
446 1
447
    /**
448
     * Checks to see if an index specified by name exists.
449 29
     *
450 29
     * @param string $indexName
451
     * @return bool
452
     */
453
    public function hasIndexByName($indexName)
454
    {
455
        return $this->getAdapter()->hasIndexByName($this->getName(), $indexName);
456
    }
457
458
    /**
459 1
     * Add a foreign key to a database table.
460
     *
461 1
     * In $options you can specify on_delete|on_delete = cascade|no_action ..,
462 1
     * on_update, constraint = constraint name.
463
     *
464
     * @param string|array $columns Columns
465
     * @param string|\Phinx\Db\Table $referencedTable   Referenced Table
466
     * @param string|array $referencedColumns Referenced Columns
467
     * @param array $options Options
468
     * @return \Phinx\Db\Table
469
     */
470 View Code Duplication
    public function addForeignKey($columns, $referencedTable, $referencedColumns = ['id'], $options = [])
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...
471 1
    {
472
        $action = AddForeignKey::build($this->table, $columns, $referencedTable, $referencedColumns, $options);
0 ignored issues
show
Bug introduced by
It seems like $columns defined by parameter $columns on line 470 can also be of type array; however, Phinx\Db\Action\AddForeignKey::build() does only seem to accept string|array<integer,string>, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and 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...
Bug introduced by
It seems like $referencedTable defined by parameter $referencedTable on line 470 can also be of type object<Phinx\Db\Table>; however, Phinx\Db\Action\AddForeignKey::build() does only seem to accept object<Phinx\Db\Table\Table>|string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and 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...
473 1
        $this->actions->addAction($action);
474 1
475
        return $this;
476
    }
477
478
    /**
479
     * Add a foreign key to a database table with a given name.
480
     *
481
     * In $options you can specify on_delete|on_delete = cascade|no_action ..,
482
     * on_update, constraint = constraint name.
483
     *
484 12
     * @param string $name The constraint name
485
     * @param string|array $columns Columns
486 12
     * @param string|\Phinx\Db\Table $referencedTable   Referenced Table
487
     * @param string|array $referencedColumns Referenced Columns
488
     * @param array $options Options
489
     * @return \Phinx\Db\Table
490
     */
491 View Code Duplication
    public function addForeignKeyWithName($name, $columns, $referencedTable, $referencedColumns = ['id'], $options = [])
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...
492
    {
493
        $action = AddForeignKey::build(
494
            $this->table,
495
            $columns,
0 ignored issues
show
Bug introduced by
It seems like $columns defined by parameter $columns on line 491 can also be of type array; however, Phinx\Db\Action\AddForeignKey::build() does only seem to accept string|array<integer,string>, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and 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...
496
            $referencedTable,
0 ignored issues
show
Bug introduced by
It seems like $referencedTable defined by parameter $referencedTable on line 491 can also be of type object<Phinx\Db\Table>; however, Phinx\Db\Action\AddForeignKey::build() does only seem to accept object<Phinx\Db\Table\Table>|string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and 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...
497
            $referencedColumns,
498
            $options,
499
            $name
500
        );
501 8
        $this->actions->addAction($action);
502
503 8
        return $this;
504 4
    }
505 4
506 8
    /**
507 8
     * Removes the given foreign key from the table.
508
     *
509
     * @param string|array $columns    Column(s)
510 8
     * @param null|string  $constraint Constraint names
511
     * @return \Phinx\Db\Table
512 8
     */
513 8
    public function dropForeignKey($columns, $constraint = null)
514 8
    {
515 8
        $action = DropForeignKey::build($this->table, $columns, $constraint);
0 ignored issues
show
Bug introduced by
It seems like $columns defined by parameter $columns on line 513 can also be of type array; however, Phinx\Db\Action\DropForeignKey::build() does only seem to accept string|array<integer,string>, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and 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...
516
        $this->actions->addAction($action);
517 8
518
        return $this;
519
    }
520
521
    /**
522
     * Checks to see if a foreign key exists.
523
     *
524
     * @param  string|array $columns    Column(s)
525
     * @param  null|string  $constraint Constraint names
526
     * @return bool
527 1
     */
528
    public function hasForeignKey($columns, $constraint = null)
529 1
    {
530 1
        return $this->getAdapter()->hasForeignKey($this->getName(), $columns, $constraint);
0 ignored issues
show
Documentation introduced by
$columns is of type string|array, but the function expects a array<integer,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...
531 1
    }
532 1
533
    /**
534
     * Add timestamp columns created_at and updated_at to the table.
535 1
     *
536
     * @param string|null $createdAt    Alternate name for the created_at column
537
     * @param string|null $updatedAt    Alternate name for the updated_at column
538 1
     * @param bool        $withTimezone Whether to set the timezone option on the added columns
539
     *
540
     * @return \Phinx\Db\Table
541
     */
542
    public function addTimestamps($createdAt = 'created_at', $updatedAt = 'updated_at', $withTimezone = false)
543
    {
544
        $createdAt = is_null($createdAt) ? 'created_at' : $createdAt;
545
        $updatedAt = is_null($updatedAt) ? 'updated_at' : $updatedAt;
546
547
        $this->addColumn($createdAt, 'timestamp', [
548 1
                   'default' => 'CURRENT_TIMESTAMP',
549
                   'update' => '',
550 1
                   'timezone' => $withTimezone,
551
             ])
552
             ->addColumn($updatedAt, 'timestamp', [
553
                 'null' => true,
554
                 'default' => null,
555
                 'timezone' => $withTimezone,
556
             ]);
557
558
        return $this;
559
    }
560
561 15
    /**
562
     * Alias that always sets $withTimezone to true
563 15
     * @see addTimestamps
564 15
     *
565 15
     * @param string|null $createdAt Alternate name for the created_at column
566 15
     * @param string|null $updatedAt Alternate name for the updated_at column
567
     *
568 15
     * @return \Phinx\Db\Table
569 15
     */
570 15
    public function addTimestampsWithTimezone($createdAt = null, $updatedAt = null)
571
    {
572 15
        $this->addTimestamps($createdAt, $updatedAt, true);
573
574 15
        return $this;
575
    }
576
577
    /**
578
     * Insert data into the table.
579
     *
580
     * @param array $data array of data in the form:
581
     *              array(
582
     *                  array("col1" => "value1", "col2" => "anotherValue1"),
583
     *                  array("col2" => "value2", "col2" => "anotherValue2"),
584
     *              )
585
     *              or array("col1" => "value1", "col2" => "anotherValue1")
586
     *
587
     * @return \Phinx\Db\Table
588
     */
589 17
    public function insert($data)
590
    {
591
        // handle array of array situations
592 17
        if (isset($data[0]) && is_array($data[0])) {
593 11
            foreach ($data as $row) {
594 11
                $this->data[] = $row;
595 11
            }
596 11
597
            return $this;
598 8
        }
599 8
        $this->data[] = $data;
600
601
        return $this;
602
    }
603
604
    /**
605
     * Creates a table from the object instance.
606
     *
607 196
     * @return void
608
     */
609 196
    public function create()
610 196
    {
611 196
        $this->executeActions(false);
612 196
        $this->saveData();
613
        $this->reset(); // reset pending changes
614
    }
615
616
    /**
617
     * Updates a table from the object instance.
618
     *
619
     * @throws \RuntimeException
620 46
     * @return void
621
     */
622 46
    public function update()
623
    {
624
        $this->executeActions(true);
625
        $this->saveData();
626
        $this->reset(); // reset pending changes
627 46
    }
628 38
629 46
    /**
630
     * Commit the pending data waiting for insertion.
631 46
     *
632 6
     * @return void
633 46
     */
634
    public function saveData()
635 46
    {
636 3
        $rows = $this->getData();
637 46
        if (empty($rows)) {
638
            return;
639 46
        }
640 46
641 46
        $bulk = true;
642
        $row = current($rows);
643
        $c = array_keys($row);
644
        foreach ($this->getData() as $row) {
645
            $k = array_keys($row);
646
            if ($k != $c) {
647
                $bulk = false;
648 196
                break;
649
            }
650 196
        }
651 196
652 192
        if ($bulk) {
653
            $this->getAdapter()->bulkinsert($this->table, $this->getData());
654
        } else {
655 12
            foreach ($this->getData() as $row) {
656 12
                $this->getAdapter()->insert($this->table, $row);
657 12
            }
658 12
        }
659 12
660 12
        $this->resetData();
661 1
    }
662 1
663
    /**
664 12
     * Immediately truncates the table. This operation cannot be undone
665
     *
666 12
     * @return void
667 11
     */
668 11
    public function truncate()
669 1
    {
670 1
        $this->getAdapter()->truncateTable($this->getName());
671 1
    }
672
673 12
    /**
674
     * Commits the table changes.
675
     *
676
     * If the table doesn't exist it is created otherwise it is updated.
677
     *
678
     * @return void
679
     */
680 2
    public function save()
681
    {
682 2
        if ($this->exists()) {
683 2
            $this->update(); // update the table
684
        } else {
685
            $this->create(); // create the table
686
        }
687
    }
688
689
    /**
690
     * Executes all the pending actions for this table
691
     *
692 195
     * @param bool $exists Whether or not the table existed prior to executing this method
693
     * @return void
694 195
     */
695 45
    protected function executeActions($exists)
696 45
    {
697 195
        // Renaming a table is tricky, specially when running a reversible migration
698
        // down. We will just assume the table already exists if the user commands a
699
        // table rename.
700 195
        $renamed = collection($this->actions->getActions())
701 195
            ->filter(function ($action) {
702
                return $action instanceof RenameTable;
703
            })
704
            ->first();
705
706
        if ($renamed) {
707
            $exists = true;
708
        }
709
710
        // If the table does not exist, the last command in the chain needs to be
711
        // a CreateTable action.
712
        if (!$exists) {
713
            $this->actions->addAction(new CreateTable($this->table));
714
        }
715
716
        $plan = new Plan($this->actions);
717
        $plan->execute($this->getAdapter());
0 ignored issues
show
Bug introduced by
It seems like $this->getAdapter() can be null; however, execute() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
718
    }
719
}
720