Completed
Pull Request — master (#1687)
by
unknown
01:32
created

Table::addForeignKeyWithName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14

Duplication

Lines 14
Ratio 100 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 14
loc 14
ccs 4
cts 4
cp 1
rs 9.7998
c 0
b 0
f 0
cc 1
nc 1
nop 5
crap 1
1
<?php
2
3
/**
4
 * MIT License
5
 * For full license information, please view the LICENSE file that was distributed with this source code.
6
 */
7
8
namespace Phinx\Db;
9
10
use InvalidArgumentException;
11
use Phinx\Db\Action\AddColumn;
12
use Phinx\Db\Action\AddForeignKey;
13
use Phinx\Db\Action\AddIndex;
14
use Phinx\Db\Action\ChangeColumn;
15
use Phinx\Db\Action\ChangeComment;
16
use Phinx\Db\Action\ChangePrimaryKey;
17
use Phinx\Db\Action\CreateTable;
18
use Phinx\Db\Action\DropForeignKey;
19
use Phinx\Db\Action\DropIndex;
20
use Phinx\Db\Action\DropTable;
21
use Phinx\Db\Action\RemoveColumn;
22
use Phinx\Db\Action\RenameColumn;
23
use Phinx\Db\Action\RenameTable;
24
use Phinx\Db\Adapter\AdapterInterface;
25
use Phinx\Db\Plan\Intent;
26
use Phinx\Db\Plan\Plan;
27
use Phinx\Db\Table\Column;
28
use Phinx\Db\Table\Table as TableValue;
29
use RuntimeException;
30
31
/**
32
 * This object is based loosely on: http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html.
33
 */
34
class Table
35
{
36
    /**
37
     * @var \Phinx\Db\Table\Table
38
     */
39
    protected $table;
40
41
    /**
42
     * @var \Phinx\Db\Adapter\AdapterInterface
43
     */
44
    protected $adapter;
45
46
    /**
47
     * @var \Phinx\Db\Plan\Intent
48
     */
49
    protected $actions;
50
51
    /**
52
     * @var array
53
     */
54
    protected $data = [];
55
56
    /**
57
     * @param string $name Table Name
58
     * @param array $options Options
59
     * @param \Phinx\Db\Adapter\AdapterInterface|null $adapter Database Adapter
60
     */
61
    public function __construct($name, $options = [], AdapterInterface $adapter = null)
62
    {
63
        $this->table = new TableValue($name, $options);
64
        $this->actions = new Intent();
65
66
        if ($adapter !== null) {
67
            $this->setAdapter($adapter);
68
        }
69
    }
70
71
    /**
72
     * Gets the table name.
73
     *
74
     * @return string|null
75
     */
76
    public function getName()
77
    {
78
        return $this->table->getName();
79
    }
80
81
    /**
82
     * Gets the table options.
83
     *
84 239
     * @return array
85
     */
86 239
    public function getOptions()
87 239
    {
88
        return $this->table->getOptions();
89 239
    }
90 231
91 231
    /**
92 239
     * Gets the table name and options as an object
93
     *
94
     * @return \Phinx\Db\Table\Table
95
     */
96
    public function getTable()
97
    {
98
        return $this->table;
99
    }
100 239
101
    /**
102 239
     * Sets the database adapter.
103 239
     *
104
     * @param \Phinx\Db\Adapter\AdapterInterface $adapter Database Adapter
105
     *
106
     * @return $this
107
     */
108
    public function setAdapter(AdapterInterface $adapter)
109
    {
110
        $this->adapter = $adapter;
111 215
112
        return $this;
113 215
    }
114
115
    /**
116
     * Gets the database adapter.
117
     *
118
     * @throws \RuntimeException
119
     *
120
     * @return \Phinx\Db\Adapter\AdapterInterface|null
121
     */
122 239
    public function getAdapter()
123
    {
124 239
        if (!$this->adapter) {
125 239
            throw new RuntimeException('There is no database adapter set yet, cannot proceed');
126
        }
127
128
        return $this->adapter;
129
    }
130
131
    /**
132
     * Does the table have pending actions?
133 189
     *
134
     * @return bool
135 189
     */
136
    public function hasPendingActions()
137
    {
138
        return count($this->actions->getActions()) > 0 || count($this->data) > 0;
139
    }
140
141
    /**
142
     * Does the table exist?
143
     *
144 231
     * @return bool
145
     */
146 231
    public function exists()
147 231
    {
148
        return $this->getAdapter()->hasTable($this->getName());
149
    }
150
151
    /**
152
     * Drops the database table.
153
     *
154
     * @return $this
155 225
     */
156
    public function drop()
157 225
    {
158
        $this->actions->addAction(new DropTable($this->table));
159
160
        return $this;
161
    }
162
163
    /**
164
     * Renames the database table.
165 195
     *
166
     * @param string $newTableName New Table Name
167 195
     *
168
     * @return $this
169
     */
170
    public function rename($newTableName)
171
    {
172
        $this->actions->addAction(new RenameTable($this->table, $newTableName));
173
174
        return $this;
175 1
    }
176
177 1
    /**
178 1
     * Changes the primary key of the database table.
179
     *
180
     * @param string|array|null $columns Column name(s) to belong to the primary key, or null to drop the key
181
     *
182
     * @return $this
183
     */
184
    public function changePrimaryKey($columns)
185
    {
186 3
        $this->actions->addAction(new ChangePrimaryKey($this->table, $columns));
187
188 3
        return $this;
189 3
    }
190 3
191
    /**
192
     * Changes the comment of the database table.
193
     *
194
     * @param string|null $comment New comment string, or null to drop the comment
195
     *
196
     * @return $this
197
     */
198
    public function changeComment($comment)
199
    {
200
        $this->actions->addAction(new ChangeComment($this->table, $comment));
201
202
        return $this;
203
    }
204
205
    /**
206
     * Gets an array of the table columns.
207
     *
208
     * @return \Phinx\Db\Table\Column[]
209
     */
210
    public function getColumns()
211 10
    {
212
        return $this->getAdapter()->getColumns($this->getName());
213 10
    }
214
215
    /**
216
     * Gets a table column if it exists.
217
     *
218
     * @param string $name Column name
219
     *
220
     * @return \Phinx\Db\Table\Column|null
221
     */
222 196
    public function getColumn($name)
223
    {
224 196
        $columns = array_filter(
225 196
            $this->getColumns(),
226
            function ($column) use ($name) {
227
                return $column->getName() === $name;
228
            }
229
        );
230
231
        return array_pop($columns);
232
    }
233 204
234
    /**
235 204
     * Sets an array of data to be inserted.
236
     *
237
     * @param array $data Data
238
     *
239
     * @return $this
240
     */
241
    public function setData($data)
242
    {
243
        $this->data = $data;
244 196
245
        return $this;
246 196
    }
247 196
248
    /**
249
     * Gets the data waiting to be inserted.
250
     *
251
     * @return array
252
     */
253
    public function getData()
254
    {
255 191
        return $this->data;
256
    }
257 191
258
    /**
259
     * Resets all of the pending data to be inserted
260
     *
261
     * @return void
262
     */
263
    public function resetData()
264
    {
265
        $this->setData([]);
266 196
    }
267
268 196
    /**
269 196
     * Resets all of the pending table changes.
270
     *
271
     * @return void
272
     */
273
    public function reset()
274
    {
275
        $this->actions = new Intent();
276
        $this->resetData();
277 192
    }
278
279 192
    /**
280
     * Add a table column.
281
     *
282
     * Type can be: string, text, integer, float, decimal, datetime, timestamp,
283
     * time, date, binary, boolean.
284
     *
285
     * Valid options can be: limit, default, null, precision or scale.
286
     *
287
     * @param string|\Phinx\Db\Table\Column $columnName Column Name
288 196
     * @param string|\Phinx\Util\Literal|null $type Column Type
289
     * @param array $options Column Options
290 196
     *
291 196
     * @throws \InvalidArgumentException
292
     *
293
     * @return $this
294
     */
295
    public function addColumn($columnName, $type = null, $options = [])
296
    {
297
        if ($columnName instanceof Column) {
298
            $action = new AddColumn($this->table, $columnName);
299 197
        } else {
300
            if ( 'sqlite' == $this->getAdapter()->getAdapterType() ||
301 197
                 'sqlite' == (getenv('PHINX_TESTING_ADAPTER')) ) {
302
                array_key_exists('null', $options) ?: $options['null'] = true;
303
            }
304
            $action = AddColumn::build($this->table, $columnName, $type, $options);
305
        }
306
307
        // Delegate to Adapters to check column type
308
        if (!$this->getAdapter()->isValidColumnType($action->getColumn())) {
309 196
            throw new InvalidArgumentException(sprintf(
310
                'An invalid column type "%s" was specified for column "%s".',
311 196
                $type,
312 196
                $action->getColumn()->getName()
313 196
            ));
314 196
        }
315 196
316
        $this->actions->addAction($action);
317
318
        return $this;
319
    }
320
321
    /**
322
     * Remove a table column.
323
     *
324
     * @param string $columnName Column Name
325
     *
326
     * @return $this
327
     */
328
    public function removeColumn($columnName)
329
    {
330
        $action = RemoveColumn::build($this->table, $columnName);
331
        $this->actions->addAction($action);
332 210
333
        return $this;
334
    }
335 210
336 1
    /**
337
     * Rename a table column.
338
     *
339
     * @param string $oldName Old Column Name
340 209
     * @param string $newName New Column Name
341 207
     *
342 207
     * @return $this
343 207
     */
344 207
    public function renameColumn($oldName, $newName)
345 207
    {
346 2
        $action = RenameColumn::build($this->table, $oldName, $newName);
347
        $this->actions->addAction($action);
348
349
        return $this;
350 209
    }
351 1
352 1
    /**
353 1
     * Change a table column type.
354 1
     *
355 1
     * @param string $columnName Column Name
356
     * @param string|\Phinx\Db\Table\Column|\Phinx\Util\Literal $newColumnType New Column Type
357
     * @param array $options Options
358 208
     *
359 208
     * @return $this
360
     */
361
    public function changeColumn($columnName, $newColumnType, array $options = [])
362
    {
363
        if ($newColumnType instanceof Column) {
364
            $action = new ChangeColumn($this->table, $columnName, $newColumnType);
365
        } else {
366
            $action = ChangeColumn::build($this->table, $columnName, $newColumnType, $options);
367
        }
368 1
        $this->actions->addAction($action);
369
370 1
        return $this;
371 1
    }
372
373
    /**
374
     * Checks to see if a column exists.
375
     *
376
     * @param string $columnName Column Name
377
     *
378
     * @return bool
379
     */
380
    public function hasColumn($columnName)
381 4
    {
382
        return $this->getAdapter()->hasColumn($this->getName(), $columnName);
383 4
    }
384 4
385
    /**
386
     * Add an index to a database table.
387
     *
388
     * In $options you can specific unique = true/false or name (index name).
389
     *
390
     * @param string|array|\Phinx\Db\Table\Index $columns Table Column(s)
391
     * @param array $options Index Options
392
     *
393
     * @return $this
394
     */
395 17
    public function addIndex($columns, array $options = [])
396
    {
397
        $action = AddIndex::build($this->table, $columns, $options);
398 17
        $this->actions->addAction($action);
399 4
400 4
        return $this;
401 4
    }
402 4
403 13
    /**
404
     * Removes the given index from a table.
405
     *
406
     * @param string|array $columns Columns
407 17
     *
408 15
     * @return $this
409 15
     */
410
    public function removeIndex($columns)
411 17
    {
412 17
        $action = DropIndex::build($this->table, is_string($columns) ? [$columns] : $columns);
413
        $this->actions->addAction($action);
414
415
        return $this;
416
    }
417
418
    /**
419
     * Removes the given index identified by its name from a table.
420
     *
421 89
     * @param string $name Index name
422
     *
423 89
     * @return $this
424
     */
425
    public function removeIndexByName($name)
426
    {
427
        $action = DropIndex::buildFromName($this->table, $name);
428
        $this->actions->addAction($action);
429
430
        return $this;
431
    }
432
433
    /**
434
     * Checks to see if an index exists.
435 29
     *
436
     * @param string|array $columns Columns
437
     *
438 29
     * @return bool
439 28
     */
440 28
    public function hasIndex($columns)
441 22
    {
442 22
        return $this->getAdapter()->hasIndex($this->getName(), $columns);
0 ignored issues
show
Bug introduced by
It seems like $columns defined by parameter $columns on line 440 can also be of type array; however, Phinx\Db\Adapter\AdapterInterface::hasIndex() 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...
443 28
    }
444 28
445 28
    /**
446 1
     * Checks to see if an index specified by name exists.
447
     *
448
     * @param string $indexName
449 29
     *
450 29
     * @return bool
451
     */
452
    public function hasIndexByName($indexName)
453
    {
454
        return $this->getAdapter()->hasIndexByName($this->getName(), $indexName);
455
    }
456
457
    /**
458
     * Add a foreign key to a database table.
459 1
     *
460
     * In $options you can specify on_delete|on_delete = cascade|no_action ..,
461 1
     * on_update, constraint = constraint name.
462 1
     *
463
     * @param string|array $columns Columns
464
     * @param string|\Phinx\Db\Table $referencedTable Referenced Table
465
     * @param string|array $referencedColumns Referenced Columns
466
     * @param array $options Options
467
     *
468
     * @return $this
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
     *
490
     * @return $this
491
     */
492 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...
493
    {
494
        $action = AddForeignKey::build(
495
            $this->table,
496
            $columns,
0 ignored issues
show
Bug introduced by
It seems like $columns defined by parameter $columns on line 492 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...
497
            $referencedTable,
0 ignored issues
show
Bug introduced by
It seems like $referencedTable defined by parameter $referencedTable on line 492 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...
498
            $referencedColumns,
499
            $options,
500
            $name
501 8
        );
502
        $this->actions->addAction($action);
503 8
504 4
        return $this;
505 4
    }
506 8
507 8
    /**
508
     * Removes the given foreign key from the table.
509
     *
510 8
     * @param string|array $columns Column(s)
511
     * @param string|null $constraint Constraint names
512 8
     *
513 8
     * @return $this
514 8
     */
515 8
    public function dropForeignKey($columns, $constraint = null)
516
    {
517 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 515 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...
518
        $this->actions->addAction($action);
519
520
        return $this;
521
    }
522
523
    /**
524
     * Checks to see if a foreign key exists.
525
     *
526
     * @param string|array $columns Column(s)
527 1
     * @param string|null $constraint Constraint names
528
     *
529 1
     * @return bool
530 1
     */
531 1
    public function hasForeignKey($columns, $constraint = null)
532 1
    {
533
        return $this->getAdapter()->hasForeignKey($this->getName(), $columns, $constraint);
0 ignored issues
show
Bug introduced by
It seems like $columns defined by parameter $columns on line 531 can also be of type array; however, Phinx\Db\Adapter\AdapterInterface::hasForeignKey() 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...
534
    }
535 1
536
    /**
537
     * Add timestamp columns created_at and updated_at to the table.
538 1
     *
539
     * @param string|null $createdAt Alternate name for the created_at column
540
     * @param string|null $updatedAt Alternate name for the updated_at column
541
     * @param bool $withTimezone Whether to set the timezone option on the added columns
542
     *
543
     * @return $this
544
     */
545
    public function addTimestamps($createdAt = 'created_at', $updatedAt = 'updated_at', $withTimezone = false)
546
    {
547
        $createdAt = $createdAt === null ? 'created_at' : $createdAt;
548 1
        $updatedAt = $updatedAt === null ? 'updated_at' : $updatedAt;
549
550 1
        $this->addColumn($createdAt, 'timestamp', [
551
                   'default' => 'CURRENT_TIMESTAMP',
552
                   'update' => '',
553
                   'timezone' => $withTimezone,
554
             ])
555
             ->addColumn($updatedAt, 'timestamp', [
556
                 'null' => true,
557
                 'default' => null,
558
                 'timezone' => $withTimezone,
559
             ]);
560
561 15
        return $this;
562
    }
563 15
564 15
    /**
565 15
     * Alias that always sets $withTimezone to true
566 15
     *
567
     * @see addTimestamps
568 15
     *
569 15
     * @param string|null $createdAt Alternate name for the created_at column
570 15
     * @param string|null $updatedAt Alternate name for the updated_at column
571
     *
572 15
     * @return $this
573
     */
574 15
    public function addTimestampsWithTimezone($createdAt = null, $updatedAt = null)
575
    {
576
        $this->addTimestamps($createdAt, $updatedAt, true);
577
578
        return $this;
579
    }
580
581
    /**
582
     * Insert data into the table.
583
     *
584
     * @param array $data array of data in the form:
585
     *              array(
586
     *                  array("col1" => "value1", "col2" => "anotherValue1"),
587
     *                  array("col2" => "value2", "col2" => "anotherValue2"),
588
     *              )
589 17
     *              or array("col1" => "value1", "col2" => "anotherValue1")
590
     *
591
     * @return $this
592 17
     */
593 11
    public function insert($data)
594 11
    {
595 11
        // handle array of array situations
596 11
        $keys = array_keys($data);
597
        $firstKey = array_shift($keys);
598 8
        if ($firstKey !== null && is_array($data[$firstKey])) {
599 8
            foreach ($data as $row) {
600
                $this->data[] = $row;
601
            }
602
603
            return $this;
604
        }
605
606
        if (count($data) > 0) {
607 196
            $this->data[] = $data;
608
        }
609 196
610 196
        return $this;
611 196
    }
612 196
613
    /**
614
     * Creates a table from the object instance.
615
     *
616
     * @return void
617
     */
618
    public function create()
619
    {
620 46
        $this->executeActions(false);
621
        $this->saveData();
622 46
        $this->reset(); // reset pending changes
623
    }
624
625
    /**
626
     * Updates a table from the object instance.
627 46
     *
628 38
     * @return void
629 46
     */
630
    public function update()
631 46
    {
632 6
        $this->executeActions(true);
633 46
        $this->saveData();
634
        $this->reset(); // reset pending changes
635 46
    }
636 3
637 46
    /**
638
     * Commit the pending data waiting for insertion.
639 46
     *
640 46
     * @return void
641 46
     */
642
    public function saveData()
643
    {
644
        $rows = $this->getData();
645
        if (empty($rows)) {
646
            return;
647
        }
648 196
649
        $bulk = true;
650 196
        $row = current($rows);
651 196
        $c = array_keys($row);
652 192
        foreach ($this->getData() as $row) {
653
            $k = array_keys($row);
654
            if ($k != $c) {
655 12
                $bulk = false;
656 12
                break;
657 12
            }
658 12
        }
659 12
660 12
        if ($bulk) {
661 1
            $this->getAdapter()->bulkinsert($this->table, $this->getData());
662 1
        } else {
663
            foreach ($this->getData() as $row) {
664 12
                $this->getAdapter()->insert($this->table, $row);
665
            }
666 12
        }
667 11
668 11
        $this->resetData();
669 1
    }
670 1
671 1
    /**
672
     * Immediately truncates the table. This operation cannot be undone
673 12
     *
674
     * @return void
675
     */
676
    public function truncate()
677
    {
678
        $this->getAdapter()->truncateTable($this->getName());
679
    }
680 2
681
    /**
682 2
     * Commits the table changes.
683 2
     *
684
     * If the table doesn't exist it is created otherwise it is updated.
685
     *
686
     * @return void
687
     */
688
    public function save()
689
    {
690
        if ($this->exists()) {
691
            $this->update(); // update the table
692 195
        } else {
693
            $this->create(); // create the table
694 195
        }
695 45
    }
696 45
697 195
    /**
698
     * Executes all the pending actions for this table
699
     *
700 195
     * @param bool $exists Whether or not the table existed prior to executing this method
701 195
     *
702
     * @return void
703
     */
704
    protected function executeActions($exists)
705
    {
706
        // Renaming a table is tricky, specially when running a reversible migration
707
        // down. We will just assume the table already exists if the user commands a
708
        // table rename.
709
        $renamed = collection($this->actions->getActions())
710
            ->filter(function ($action) {
711
                return $action instanceof RenameTable;
712
            })
713
            ->first();
714
715
        if ($renamed) {
716
            $exists = true;
717
        }
718
719
        // If the table does not exist, the last command in the chain needs to be
720
        // a CreateTable action.
721
        if (!$exists) {
722
            $this->actions->addAction(new CreateTable($this->table));
723
        }
724
725
        $plan = new Plan($this->actions);
726
        $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...
727
    }
728
}
729