Completed
Pull Request — master (#1687)
by
unknown
03:39 queued 01:25
created

Table::removeIndexByName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
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 (
301 197
                'sqlite' == $this->getAdapter()->getAdapterType() ||
302
                'sqlite' == (getenv('PHINX_TESTING_ADAPTER'))
303
            ) {
304
                array_key_exists('null', $options) ?: $options['null'] = true;
305
            }
306
            $action = AddColumn::build($this->table, $columnName, $type, $options);
307
        }
308
309 196
        // Delegate to Adapters to check column type
310
        if (!$this->getAdapter()->isValidColumnType($action->getColumn())) {
311 196
            throw new InvalidArgumentException(sprintf(
312 196
                'An invalid column type "%s" was specified for column "%s".',
313 196
                $type,
314 196
                $action->getColumn()->getName()
315 196
            ));
316
        }
317
318
        $this->actions->addAction($action);
319
320
        return $this;
321
    }
322
323
    /**
324
     * Remove a table column.
325
     *
326
     * @param string $columnName Column Name
327
     *
328
     * @return $this
329
     */
330
    public function removeColumn($columnName)
331
    {
332 210
        $action = RemoveColumn::build($this->table, $columnName);
333
        $this->actions->addAction($action);
334
335 210
        return $this;
336 1
    }
337
338
    /**
339
     * Rename a table column.
340 209
     *
341 207
     * @param string $oldName Old Column Name
342 207
     * @param string $newName New Column Name
343 207
     *
344 207
     * @return $this
345 207
     */
346 2
    public function renameColumn($oldName, $newName)
347
    {
348
        $action = RenameColumn::build($this->table, $oldName, $newName);
349
        $this->actions->addAction($action);
350 209
351 1
        return $this;
352 1
    }
353 1
354 1
    /**
355 1
     * Change a table column type.
356
     *
357
     * @param string $columnName Column Name
358 208
     * @param string|\Phinx\Db\Table\Column|\Phinx\Util\Literal $newColumnType New Column Type
359 208
     * @param array $options Options
360
     *
361
     * @return $this
362
     */
363
    public function changeColumn($columnName, $newColumnType, array $options = [])
364
    {
365
        if ($newColumnType instanceof Column) {
366
            $action = new ChangeColumn($this->table, $columnName, $newColumnType);
367
        } else {
368 1
            $action = ChangeColumn::build($this->table, $columnName, $newColumnType, $options);
369
        }
370 1
        $this->actions->addAction($action);
371 1
372
        return $this;
373
    }
374
375
    /**
376
     * Checks to see if a column exists.
377
     *
378
     * @param string $columnName Column Name
379
     *
380
     * @return bool
381 4
     */
382
    public function hasColumn($columnName)
383 4
    {
384 4
        return $this->getAdapter()->hasColumn($this->getName(), $columnName);
385
    }
386
387
    /**
388
     * Add an index to a database table.
389
     *
390
     * In $options you can specific unique = true/false or name (index name).
391
     *
392
     * @param string|array|\Phinx\Db\Table\Index $columns Table Column(s)
393
     * @param array $options Index Options
394
     *
395 17
     * @return $this
396
     */
397
    public function addIndex($columns, array $options = [])
398 17
    {
399 4
        $action = AddIndex::build($this->table, $columns, $options);
400 4
        $this->actions->addAction($action);
401 4
402 4
        return $this;
403 13
    }
404
405
    /**
406
     * Removes the given index from a table.
407 17
     *
408 15
     * @param string|array $columns Columns
409 15
     *
410
     * @return $this
411 17
     */
412 17
    public function removeIndex($columns)
413
    {
414
        $action = DropIndex::build($this->table, is_string($columns) ? [$columns] : $columns);
415
        $this->actions->addAction($action);
416
417
        return $this;
418
    }
419
420
    /**
421 89
     * Removes the given index identified by its name from a table.
422
     *
423 89
     * @param string $name Index name
424
     *
425
     * @return $this
426
     */
427
    public function removeIndexByName($name)
428
    {
429
        $action = DropIndex::buildFromName($this->table, $name);
430
        $this->actions->addAction($action);
431
432
        return $this;
433
    }
434
435 29
    /**
436
     * Checks to see if an index exists.
437
     *
438 29
     * @param string|array $columns Columns
439 28
     *
440 28
     * @return bool
441 22
     */
442 22
    public function hasIndex($columns)
443 28
    {
444 28
        return $this->getAdapter()->hasIndex($this->getName(), $columns);
0 ignored issues
show
Bug introduced by
It seems like $columns defined by parameter $columns on line 442 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...
445 28
    }
446 1
447
    /**
448
     * Checks to see if an index specified by name exists.
449 29
     *
450 29
     * @param string $indexName
451
     *
452
     * @return bool
453
     */
454
    public function hasIndexByName($indexName)
455
    {
456
        return $this->getAdapter()->hasIndexByName($this->getName(), $indexName);
457
    }
458
459 1
    /**
460
     * Add a foreign key to a database table.
461 1
     *
462 1
     * In $options you can specify on_delete|on_delete = cascade|no_action ..,
463
     * on_update, constraint = constraint name.
464
     *
465
     * @param string|array $columns Columns
466
     * @param string|\Phinx\Db\Table $referencedTable Referenced Table
467
     * @param string|array $referencedColumns Referenced Columns
468
     * @param array $options Options
469
     *
470
     * @return $this
471 1
     */
472 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...
473 1
    {
474 1
        $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 472 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 472 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...
475
        $this->actions->addAction($action);
476
477
        return $this;
478
    }
479
480
    /**
481
     * Add a foreign key to a database table with a given name.
482
     *
483
     * In $options you can specify on_delete|on_delete = cascade|no_action ..,
484 12
     * on_update, constraint = constraint name.
485
     *
486 12
     * @param string $name The constraint name
487
     * @param string|array $columns Columns
488
     * @param string|\Phinx\Db\Table $referencedTable Referenced Table
489
     * @param string|array $referencedColumns Referenced Columns
490
     * @param array $options Options
491
     *
492
     * @return $this
493
     */
494 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...
495
    {
496
        $action = AddForeignKey::build(
497
            $this->table,
498
            $columns,
0 ignored issues
show
Bug introduced by
It seems like $columns defined by parameter $columns on line 494 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...
499
            $referencedTable,
0 ignored issues
show
Bug introduced by
It seems like $referencedTable defined by parameter $referencedTable on line 494 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...
500
            $referencedColumns,
501 8
            $options,
502
            $name
503 8
        );
504 4
        $this->actions->addAction($action);
505 4
506 8
        return $this;
507 8
    }
508
509
    /**
510 8
     * Removes the given foreign key from the table.
511
     *
512 8
     * @param string|array $columns Column(s)
513 8
     * @param string|null $constraint Constraint names
514 8
     *
515 8
     * @return $this
516
     */
517 8
    public function dropForeignKey($columns, $constraint = null)
518
    {
519
        $action = DropForeignKey::build($this->table, $columns, $constraint);
0 ignored issues
show
Bug introduced by
It seems like $columns defined by parameter $columns on line 517 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...
520
        $this->actions->addAction($action);
521
522
        return $this;
523
    }
524
525
    /**
526
     * Checks to see if a foreign key exists.
527 1
     *
528
     * @param string|array $columns Column(s)
529 1
     * @param string|null $constraint Constraint names
530 1
     *
531 1
     * @return bool
532 1
     */
533
    public function hasForeignKey($columns, $constraint = null)
534
    {
535 1
        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 533 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...
536
    }
537
538 1
    /**
539
     * Add timestamp columns created_at and updated_at to the table.
540
     *
541
     * @param string|null $createdAt Alternate name for the created_at column
542
     * @param string|null $updatedAt Alternate name for the updated_at column
543
     * @param bool $withTimezone Whether to set the timezone option on the added columns
544
     *
545
     * @return $this
546
     */
547
    public function addTimestamps($createdAt = 'created_at', $updatedAt = 'updated_at', $withTimezone = false)
548 1
    {
549
        $createdAt = $createdAt === null ? 'created_at' : $createdAt;
550 1
        $updatedAt = $updatedAt === null ? 'updated_at' : $updatedAt;
551
552
        $this->addColumn($createdAt, 'timestamp', [
553
                   'default' => 'CURRENT_TIMESTAMP',
554
                   'update' => '',
555
                   'timezone' => $withTimezone,
556
             ])
557
             ->addColumn($updatedAt, 'timestamp', [
558
                 'null' => true,
559
                 'default' => null,
560
                 'timezone' => $withTimezone,
561 15
             ]);
562
563 15
        return $this;
564 15
    }
565 15
566 15
    /**
567
     * Alias that always sets $withTimezone to true
568 15
     *
569 15
     * @see addTimestamps
570 15
     *
571
     * @param string|null $createdAt Alternate name for the created_at column
572 15
     * @param string|null $updatedAt Alternate name for the updated_at column
573
     *
574 15
     * @return $this
575
     */
576
    public function addTimestampsWithTimezone($createdAt = null, $updatedAt = null)
577
    {
578
        $this->addTimestamps($createdAt, $updatedAt, true);
579
580
        return $this;
581
    }
582
583
    /**
584
     * Insert data into the table.
585
     *
586
     * @param array $data array of data in the form:
587
     *              array(
588
     *                  array("col1" => "value1", "col2" => "anotherValue1"),
589 17
     *                  array("col2" => "value2", "col2" => "anotherValue2"),
590
     *              )
591
     *              or array("col1" => "value1", "col2" => "anotherValue1")
592 17
     *
593 11
     * @return $this
594 11
     */
595 11
    public function insert($data)
596 11
    {
597
        // handle array of array situations
598 8
        $keys = array_keys($data);
599 8
        $firstKey = array_shift($keys);
600
        if ($firstKey !== null && is_array($data[$firstKey])) {
601
            foreach ($data as $row) {
602
                $this->data[] = $row;
603
            }
604
605
            return $this;
606
        }
607 196
608
        if (count($data) > 0) {
609 196
            $this->data[] = $data;
610 196
        }
611 196
612 196
        return $this;
613
    }
614
615
    /**
616
     * Creates a table from the object instance.
617
     *
618
     * @return void
619
     */
620 46
    public function create()
621
    {
622 46
        $this->executeActions(false);
623
        $this->saveData();
624
        $this->reset(); // reset pending changes
625
    }
626
627 46
    /**
628 38
     * Updates a table from the object instance.
629 46
     *
630
     * @return void
631 46
     */
632 6
    public function update()
633 46
    {
634
        $this->executeActions(true);
635 46
        $this->saveData();
636 3
        $this->reset(); // reset pending changes
637 46
    }
638
639 46
    /**
640 46
     * Commit the pending data waiting for insertion.
641 46
     *
642
     * @return void
643
     */
644
    public function saveData()
645
    {
646
        $rows = $this->getData();
647
        if (empty($rows)) {
648 196
            return;
649
        }
650 196
651 196
        $bulk = true;
652 192
        $row = current($rows);
653
        $c = array_keys($row);
654
        foreach ($this->getData() as $row) {
655 12
            $k = array_keys($row);
656 12
            if ($k != $c) {
657 12
                $bulk = false;
658 12
                break;
659 12
            }
660 12
        }
661 1
662 1
        if ($bulk) {
663
            $this->getAdapter()->bulkinsert($this->table, $this->getData());
664 12
        } else {
665
            foreach ($this->getData() as $row) {
666 12
                $this->getAdapter()->insert($this->table, $row);
667 11
            }
668 11
        }
669 1
670 1
        $this->resetData();
671 1
    }
672
673 12
    /**
674
     * Immediately truncates the table. This operation cannot be undone
675
     *
676
     * @return void
677
     */
678
    public function truncate()
679
    {
680 2
        $this->getAdapter()->truncateTable($this->getName());
681
    }
682 2
683 2
    /**
684
     * Commits the table changes.
685
     *
686
     * If the table doesn't exist it is created otherwise it is updated.
687
     *
688
     * @return void
689
     */
690
    public function save()
691
    {
692 195
        if ($this->exists()) {
693
            $this->update(); // update the table
694 195
        } else {
695 45
            $this->create(); // create the table
696 45
        }
697 195
    }
698
699
    /**
700 195
     * Executes all the pending actions for this table
701 195
     *
702
     * @param bool $exists Whether or not the table existed prior to executing this method
703
     *
704
     * @return void
705
     */
706
    protected function executeActions($exists)
707
    {
708
        // Renaming a table is tricky, specially when running a reversible migration
709
        // down. We will just assume the table already exists if the user commands a
710
        // table rename.
711
        $renamed = collection($this->actions->getActions())
712
            ->filter(function ($action) {
713
                return $action instanceof RenameTable;
714
            })
715
            ->first();
716
717
        if ($renamed) {
718
            $exists = true;
719
        }
720
721
        // If the table does not exist, the last command in the chain needs to be
722
        // a CreateTable action.
723
        if (!$exists) {
724
            $this->actions->addAction(new CreateTable($this->table));
725
        }
726
727
        $plan = new Plan($this->actions);
728
        $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...
729
    }
730
}
731