• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

codeigniter4 / CodeIgniter4 / 20102278103

10 Dec 2025 02:36PM UTC coverage: 84.513%. Remained the same
20102278103

Pull #9830

github

web-flow
Merge e3826f8f4 into 76bea167c
Pull Request #9830: refactor: Types for `BaseModel`, `Model` and dependencies

8 of 8 new or added lines in 1 file covered. (100.0%)

17 existing lines in 2 files now uncovered.

21473 of 25408 relevant lines covered (84.51%)

196.99 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

97.98
/system/Model.php
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of CodeIgniter 4 framework.
7
 *
8
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
9
 *
10
 * For the full copyright and license information, please view
11
 * the LICENSE file that was distributed with this source code.
12
 */
13

14
namespace CodeIgniter;
15

16
use Closure;
17
use CodeIgniter\Database\BaseBuilder;
18
use CodeIgniter\Database\BaseConnection;
19
use CodeIgniter\Database\ConnectionInterface;
20
use CodeIgniter\Database\Exceptions\DatabaseException;
21
use CodeIgniter\Database\Exceptions\DataException;
22
use CodeIgniter\Entity\Entity;
23
use CodeIgniter\Exceptions\BadMethodCallException;
24
use CodeIgniter\Exceptions\ModelException;
25
use CodeIgniter\Validation\ValidationInterface;
26
use Config\Database;
27
use Config\Feature;
28
use stdClass;
29

30
/**
31
 * The Model class extends BaseModel and provides additional
32
 * convenient features that makes working with a SQL database
33
 * table less painful.
34
 *
35
 * It will:
36
 *      - automatically connect to database
37
 *      - allow intermingling calls to the builder
38
 *      - removes the need to use Result object directly in most cases
39
 *
40
 * @property-read BaseConnection $db
41
 *
42
 * @method $this groupBy($by, ?bool $escape = null)
43
 * @method $this groupEnd()
44
 * @method $this groupStart()
45
 * @method $this having($key, $value = null, ?bool $escape = null)
46
 * @method $this havingGroupEnd()
47
 * @method $this havingGroupStart()
48
 * @method $this havingIn(?string $key = null, $values = null, ?bool $escape = null)
49
 * @method $this havingLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
50
 * @method $this havingNotIn(?string $key = null, $values = null, ?bool $escape = null)
51
 * @method $this join(string $table, string $cond, string $type = '', ?bool $escape = null)
52
 * @method $this like($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
53
 * @method $this limit(?int $value = null, ?int $offset = 0)
54
 * @method $this notGroupStart()
55
 * @method $this notHavingGroupStart()
56
 * @method $this notHavingLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
57
 * @method $this notLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
58
 * @method $this offset(int $offset)
59
 * @method $this orderBy(string $orderBy, string $direction = '', ?bool $escape = null)
60
 * @method $this orGroupStart()
61
 * @method $this orHaving($key, $value = null, ?bool $escape = null)
62
 * @method $this orHavingGroupStart()
63
 * @method $this orHavingIn(?string $key = null, $values = null, ?bool $escape = null)
64
 * @method $this orHavingLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
65
 * @method $this orHavingNotIn(?string $key = null, $values = null, ?bool $escape = null)
66
 * @method $this orLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
67
 * @method $this orNotGroupStart()
68
 * @method $this orNotHavingGroupStart()
69
 * @method $this orNotHavingLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
70
 * @method $this orNotLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
71
 * @method $this orWhere($key, $value = null, ?bool $escape = null)
72
 * @method $this orWhereIn(?string $key = null, $values = null, ?bool $escape = null)
73
 * @method $this orWhereNotIn(?string $key = null, $values = null, ?bool $escape = null)
74
 * @method $this select($select = '*', ?bool $escape = null)
75
 * @method $this selectAvg(string $select = '', string $alias = '')
76
 * @method $this selectCount(string $select = '', string $alias = '')
77
 * @method $this selectMax(string $select = '', string $alias = '')
78
 * @method $this selectMin(string $select = '', string $alias = '')
79
 * @method $this selectSum(string $select = '', string $alias = '')
80
 * @method $this when($condition, callable $callback, ?callable $defaultCallback = null)
81
 * @method $this whenNot($condition, callable $callback, ?callable $defaultCallback = null)
82
 * @method $this where($key, $value = null, ?bool $escape = null)
83
 * @method $this whereIn(?string $key = null, $values = null, ?bool $escape = null)
84
 * @method $this whereNotIn(?string $key = null, $values = null, ?bool $escape = null)
85
 *
86
 * @phpstan-import-type row_array from BaseModel
87
 */
88
class Model extends BaseModel
89
{
90
    /**
91
     * Name of database table.
92
     *
93
     * @var string
94
     */
95
    protected $table;
96

97
    /**
98
     * The table's primary key.
99
     *
100
     * @var string
101
     */
102
    protected $primaryKey = 'id';
103

104
    /**
105
     * Whether primary key uses auto increment.
106
     *
107
     * @var bool
108
     */
109
    protected $useAutoIncrement = true;
110

111
    /**
112
     * Query Builder object.
113
     *
114
     * @var BaseBuilder|null
115
     */
116
    protected $builder;
117

118
    /**
119
     * Holds information passed in via 'set'
120
     * so that we can capture it (not the builder)
121
     * and ensure it gets validated first.
122
     *
123
     * @var array{escape: array<int|string, bool|null>, data: row_array}|array{}
124
     */
125
    protected $tempData = [];
126

127
    /**
128
     * Escape array that maps usage of escape
129
     * flag for every parameter.
130
     *
131
     * @var array<int|string, bool|null>
132
     */
133
    protected $escape = [];
134

135
    /**
136
     * Builder method names that should not be used in the Model.
137
     *
138
     * @var list<string>
139
     */
140
    private array $builderMethodsNotAvailable = [
141
        'getCompiledInsert',
142
        'getCompiledSelect',
143
        'getCompiledUpdate',
144
    ];
145

146
    public function __construct(?ConnectionInterface $db = null, ?ValidationInterface $validation = null)
147
    {
148
        /**
149
         * @var BaseConnection|null $db
150
         */
151
        $db ??= Database::connect($this->DBGroup);
315✔
152

153
        $this->db = $db;
315✔
154

155
        parent::__construct($validation);
315✔
156
    }
157

158
    /**
159
     * Specify the table associated with a model.
160
     *
161
     * @return $this
162
     */
163
    public function setTable(string $table)
164
    {
165
        $this->table = $table;
1✔
166

167
        return $this;
1✔
168
    }
169

170
    protected function doFind(bool $singleton, $id = null)
171
    {
172
        $builder = $this->builder();
56✔
173
        $useCast = $this->useCasts();
55✔
174

175
        if ($useCast) {
55✔
176
            $returnType = $this->tempReturnType;
18✔
177
            $this->asArray();
18✔
178
        }
179

180
        if ($this->tempUseSoftDeletes) {
55✔
181
            $builder->where($this->table . '.' . $this->deletedField, null);
31✔
182
        }
183

184
        $row  = null;
55✔
185
        $rows = [];
55✔
186

187
        if (is_array($id)) {
55✔
188
            $rows = $builder->whereIn($this->table . '.' . $this->primaryKey, $id)
3✔
189
                ->get()
3✔
190
                ->getResult($this->tempReturnType);
3✔
191
        } elseif ($singleton) {
52✔
192
            $row = $builder->where($this->table . '.' . $this->primaryKey, $id)
44✔
193
                ->get()
44✔
194
                ->getFirstRow($this->tempReturnType);
44✔
195
        } else {
196
            $rows = $builder->get()->getResult($this->tempReturnType);
9✔
197
        }
198

199
        if ($useCast) {
55✔
200
            $this->tempReturnType = $returnType;
18✔
201

202
            if ($singleton) {
18✔
203
                if ($row === null) {
15✔
204
                    return null;
1✔
205
                }
206

207
                return $this->convertToReturnType($row, $returnType);
14✔
208
            }
209

210
            foreach ($rows as $i => $row) {
3✔
211
                $rows[$i] = $this->convertToReturnType($row, $returnType);
3✔
212
            }
213

214
            return $rows;
3✔
215
        }
216

217
        if ($singleton) {
37✔
218
            return $row;
29✔
219
        }
220

221
        return $rows;
9✔
222
    }
223

224
    protected function doFindColumn(string $columnName)
225
    {
226
        return $this->select($columnName)->asArray()->find();
2✔
227
    }
228

229
    /**
230
     * {@inheritDoc}
231
     *
232
     * Works with the current Query Builder instance.
233
     */
234
    protected function doFindAll(?int $limit = null, int $offset = 0)
235
    {
236
        $limitZeroAsAll = config(Feature::class)->limitZeroAsAll ?? true;
22✔
237
        if ($limitZeroAsAll) {
22✔
238
            $limit ??= 0;
22✔
239
        }
240

241
        $builder = $this->builder();
22✔
242

243
        $useCast = $this->useCasts();
22✔
244
        if ($useCast) {
22✔
245
            $returnType = $this->tempReturnType;
5✔
246
            $this->asArray();
5✔
247
        }
248

249
        if ($this->tempUseSoftDeletes) {
22✔
250
            $builder->where($this->table . '.' . $this->deletedField, null);
10✔
251
        }
252

253
        $results = $builder->limit($limit, $offset)
22✔
254
            ->get()
22✔
255
            ->getResult($this->tempReturnType);
22✔
256

257
        if ($useCast) {
22✔
258
            foreach ($results as $i => $row) {
5✔
259
                $results[$i] = $this->convertToReturnType($row, $returnType);
4✔
260
            }
261

262
            $this->tempReturnType = $returnType;
5✔
263
        }
264

265
        return $results;
22✔
266
    }
267

268
    /**
269
     * {@inheritDoc}
270
     *
271
     * Will take any previous Query Builder calls into account
272
     * when determining the result set.
273
     */
274
    protected function doFirst()
275
    {
276
        $builder = $this->builder();
24✔
277

278
        $useCast = $this->useCasts();
24✔
279
        if ($useCast) {
24✔
280
            $returnType = $this->tempReturnType;
5✔
281
            $this->asArray();
5✔
282
        }
283

284
        if ($this->tempUseSoftDeletes) {
24✔
285
            $builder->where($this->table . '.' . $this->deletedField, null);
19✔
286
        } elseif ($this->useSoftDeletes && ($builder->QBGroupBy === []) && $this->primaryKey !== '') {
13✔
287
            $builder->groupBy($this->table . '.' . $this->primaryKey);
6✔
288
        }
289

290
        // Some databases, like PostgreSQL, need order
291
        // information to consistently return correct results.
292
        if ($builder->QBGroupBy !== [] && ($builder->QBOrderBy === []) && $this->primaryKey !== '') {
24✔
293
            $builder->orderBy($this->table . '.' . $this->primaryKey, 'asc');
9✔
294
        }
295

296
        $row = $builder->limit(1, 0)->get()->getFirstRow($this->tempReturnType);
24✔
297

298
        if ($useCast && $row !== null) {
24✔
299
            $row = $this->convertToReturnType($row, $returnType);
4✔
300

301
            $this->tempReturnType = $returnType;
4✔
302
        }
303

304
        return $row;
24✔
305
    }
306

307
    protected function doInsert(array $row)
308
    {
309
        $escape       = $this->escape;
86✔
310
        $this->escape = [];
86✔
311

312
        // Require non-empty primaryKey when
313
        // not using auto-increment feature
314
        if (! $this->useAutoIncrement && ! isset($row[$this->primaryKey])) {
86✔
315
            throw DataException::forEmptyPrimaryKey('insert');
1✔
316
        }
317

318
        $builder = $this->builder();
85✔
319

320
        // Must use the set() method to ensure to set the correct escape flag
321
        foreach ($row as $key => $val) {
85✔
322
            $builder->set($key, $val, $escape[$key] ?? null);
84✔
323
        }
324

325
        if ($this->allowEmptyInserts && $row === []) {
85✔
326
            $table = $this->db->protectIdentifiers($this->table, true, null, false);
1✔
327
            if ($this->db->getPlatform() === 'MySQLi') {
1✔
328
                $sql = 'INSERT INTO ' . $table . ' VALUES ()';
1✔
329
            } elseif ($this->db->getPlatform() === 'OCI8') {
1✔
330
                $allFields = $this->db->protectIdentifiers(
1✔
331
                    array_map(
1✔
332
                        static fn ($row) => $row->name,
1✔
333
                        $this->db->getFieldData($this->table),
1✔
334
                    ),
1✔
335
                    false,
1✔
336
                    true,
1✔
337
                );
1✔
338

339
                $sql = sprintf(
1✔
340
                    'INSERT INTO %s (%s) VALUES (%s)',
1✔
341
                    $table,
1✔
342
                    implode(',', $allFields),
1✔
343
                    substr(str_repeat(',DEFAULT', count($allFields)), 1),
1✔
344
                );
1✔
345
            } else {
346
                $sql = 'INSERT INTO ' . $table . ' DEFAULT VALUES';
1✔
347
            }
348

349
            $result = $this->db->query($sql);
1✔
350
        } else {
351
            $result = $builder->insert();
84✔
352
        }
353

354
        // If insertion succeeded then save the insert ID
355
        if ($result) {
85✔
356
            $this->insertID = $this->useAutoIncrement ? $this->db->insertID() : $row[$this->primaryKey];
83✔
357
        }
358

359
        return $result;
85✔
360
    }
361

362
    protected function doInsertBatch(?array $set = null, ?bool $escape = null, int $batchSize = 100, bool $testing = false)
363
    {
364
        if (is_array($set) && ! $this->useAutoIncrement) {
11✔
365
            foreach ($set as $row) {
1✔
366
                // Require non-empty $primaryKey when
367
                // not using auto-increment feature
368
                if (! isset($row[$this->primaryKey])) {
1✔
369
                    throw DataException::forEmptyPrimaryKey('insertBatch');
×
370
                }
371
            }
372
        }
373

374
        return $this->builder()->testMode($testing)->insertBatch($set, $escape, $batchSize);
11✔
375
    }
376

377
    protected function doUpdate($id = null, $row = null): bool
378
    {
379
        $escape       = $this->escape;
37✔
380
        $this->escape = [];
37✔
381

382
        $builder = $this->builder();
37✔
383

384
        if (! in_array($id, [null, '', 0, '0', []], true)) {
37✔
385
            $builder = $builder->whereIn($this->table . '.' . $this->primaryKey, $id);
31✔
386
        }
387

388
        // Must use the set() method to ensure to set the correct escape flag
389
        foreach ($row as $key => $val) {
37✔
390
            $builder->set($key, $val, $escape[$key] ?? null);
37✔
391
        }
392

393
        if ($builder->getCompiledQBWhere() === []) {
37✔
394
            throw new DatabaseException(
1✔
395
                'Updates are not allowed unless they contain a "where" or "like" clause.',
1✔
396
            );
1✔
397
        }
398

399
        return $builder->update();
36✔
400
    }
401

402
    protected function doUpdateBatch(?array $set = null, ?string $index = null, int $batchSize = 100, bool $returnSQL = false)
403
    {
404
        return $this->builder()->testMode($returnSQL)->updateBatch($set, $index, $batchSize);
4✔
405
    }
406

407
    protected function doDelete($id = null, bool $purge = false)
408
    {
409
        $set     = [];
40✔
410
        $builder = $this->builder();
40✔
411

412
        if (! in_array($id, [null, '', 0, '0', []], true)) {
40✔
413
            $builder = $builder->whereIn($this->primaryKey, $id);
21✔
414
        }
415

416
        if ($this->useSoftDeletes && ! $purge) {
40✔
417
            if ($builder->getCompiledQBWhere() === []) {
28✔
418
                throw new DatabaseException(
9✔
419
                    'Deletes are not allowed unless they contain a "where" or "like" clause.',
9✔
420
                );
9✔
421
            }
422

423
            $builder->where($this->deletedField);
19✔
424

425
            $set[$this->deletedField] = $this->setDate();
19✔
426

427
            if ($this->useTimestamps && $this->updatedField !== '') {
18✔
428
                $set[$this->updatedField] = $this->setDate();
1✔
429
            }
430

431
            return $builder->update($set);
18✔
432
        }
433

434
        return $builder->delete();
12✔
435
    }
436

437
    protected function doPurgeDeleted()
438
    {
439
        return $this->builder()
1✔
440
            ->where($this->table . '.' . $this->deletedField . ' IS NOT NULL')
1✔
441
            ->delete();
1✔
442
    }
443

444
    protected function doOnlyDeleted()
445
    {
446
        $this->builder()->where($this->table . '.' . $this->deletedField . ' IS NOT NULL');
1✔
447
    }
448

449
    protected function doReplace(?array $row = null, bool $returnSQL = false)
450
    {
451
        return $this->builder()->testMode($returnSQL)->replace($row);
2✔
452
    }
453

454
    /**
455
     * {@inheritDoc}
456
     *
457
     * The return array should be in the following format:
458
     *  `['source' => 'message']`.
459
     * This method works only with dbCalls.
460
     */
461
    protected function doErrors()
462
    {
463
        // $error is always ['code' => string|int, 'message' => string]
464
        $error = $this->db->error();
2✔
465

466
        if ((int) $error['code'] === 0) {
2✔
467
            return [];
2✔
468
        }
469

470
        return [$this->db::class => $error['message']];
×
471
    }
472

473
    public function getIdValue($row)
474
    {
475
        if (is_object($row)) {
27✔
476
            // Get the raw or mapped primary key value of the Entity.
477
            if ($row instanceof Entity && $row->{$this->primaryKey} !== null) {
17✔
478
                $cast = $row->cast();
9✔
479

480
                // Disable Entity casting, because raw primary key value is needed for database.
481
                $row->cast(false);
9✔
482

483
                $primaryKey = $row->{$this->primaryKey};
9✔
484

485
                // Restore Entity casting setting.
486
                $row->cast($cast);
9✔
487

488
                return $primaryKey;
9✔
489
            }
490

491
            if (! $row instanceof Entity && isset($row->{$this->primaryKey})) {
9✔
492
                return $row->{$this->primaryKey};
5✔
493
            }
494
        }
495

496
        if (is_array($row) && isset($row[$this->primaryKey])) {
15✔
497
            return $row[$this->primaryKey];
4✔
498
        }
499

500
        return null;
11✔
501
    }
502

503
    public function countAllResults(bool $reset = true, bool $test = false)
504
    {
505
        if ($this->tempUseSoftDeletes) {
17✔
506
            $this->builder()->where($this->table . '.' . $this->deletedField, null);
6✔
507
        }
508

509
        $this->tempUseSoftDeletes = $reset
17✔
510
            ? $this->useSoftDeletes
10✔
511
            : ($this->useSoftDeletes ? false : $this->useSoftDeletes);
12✔
512

513
        return $this->builder()->testMode($test)->countAllResults($reset);
17✔
514
    }
515

516
    /**
517
     * {@inheritDoc}
518
     *
519
     * Works with `$this->builder` to get the Compiled select to
520
     * determine the rows to operate on.
521
     * This method works only with dbCalls.
522
     */
523
    public function chunk(int $size, Closure $userFunc)
524
    {
525
        $total  = $this->builder()->countAllResults(false);
1✔
526
        $offset = 0;
1✔
527

528
        while ($offset <= $total) {
1✔
529
            $builder = clone $this->builder();
1✔
530
            $rows    = $builder->get($size, $offset);
1✔
531

532
            if (! $rows) {
1✔
UNCOV
533
                throw DataException::forEmptyDataset('chunk');
×
534
            }
535

536
            $rows = $rows->getResult($this->tempReturnType);
1✔
537

538
            $offset += $size;
1✔
539

540
            if ($rows === []) {
1✔
541
                continue;
1✔
542
            }
543

544
            foreach ($rows as $row) {
1✔
545
                if ($userFunc($row) === false) {
1✔
UNCOV
546
                    return;
×
547
                }
548
            }
549
        }
550
    }
551

552
    /**
553
     * Provides a shared instance of the Query Builder.
554
     *
555
     * @param non-empty-string|null $table
556
     *
557
     * @return BaseBuilder
558
     *
559
     * @throws ModelException
560
     */
561
    public function builder(?string $table = null)
562
    {
563
        // Check for an existing Builder
564
        if ($this->builder instanceof BaseBuilder) {
200✔
565
            // Make sure the requested table matches the builder
566
            if ((string) $table !== '' && $this->builder->getTable() !== $table) {
113✔
567
                return $this->db->table($table);
1✔
568
            }
569

570
            return $this->builder;
113✔
571
        }
572

573
        // We're going to force a primary key to exist
574
        // so we don't have overly convoluted code,
575
        // and future features are likely to require them.
576
        if ($this->primaryKey === '') {
200✔
577
            throw ModelException::forNoPrimaryKey(static::class);
1✔
578
        }
579

580
        $table = ((string) $table === '') ? $this->table : $table;
199✔
581

582
        // Ensure we have a good db connection
583
        if (! $this->db instanceof BaseConnection) {
199✔
UNCOV
584
            $this->db = Database::connect($this->DBGroup);
×
585
        }
586

587
        $builder = $this->db->table($table);
199✔
588

589
        // Only consider it "shared" if the table is correct
590
        if ($table === $this->table) {
199✔
591
            $this->builder = $builder;
199✔
592
        }
593

594
        return $builder;
199✔
595
    }
596

597
    /**
598
     * Captures the builder's set() method so that we can validate the
599
     * data here. This allows it to be used with any of the other
600
     * builder methods and still get validated data, like replace.
601
     *
602
     * @param object|row_array|string           $key    Field name, or an array of field/value pairs, or an object
603
     * @param bool|float|int|object|string|null $value  Field value, if $key is a single field
604
     * @param bool|null                         $escape Whether to escape values
605
     *
606
     * @return $this
607
     */
608
    public function set($key, $value = '', ?bool $escape = null)
609
    {
610
        if (is_object($key)) {
10✔
611
            $key = $key instanceof stdClass ? (array) $key : $this->objectToArray($key);
2✔
612
        }
613

614
        $data = is_array($key) ? $key : [$key => $value];
10✔
615

616
        foreach (array_keys($data) as $k) {
10✔
617
            $this->tempData['escape'][$k] = $escape;
10✔
618
        }
619

620
        $this->tempData['data'] = array_merge($this->tempData['data'] ?? [], $data);
10✔
621

622
        return $this;
10✔
623
    }
624

625
    protected function shouldUpdate($row): bool
626
    {
627
        if (parent::shouldUpdate($row) === false) {
27✔
628
            return false;
12✔
629
        }
630

631
        if ($this->useAutoIncrement === true) {
17✔
632
            return true;
14✔
633
        }
634

635
        // When useAutoIncrement feature is disabled, check
636
        // in the database if given record already exists
637
        return $this->where($this->primaryKey, $this->getIdValue($row))->countAllResults() === 1;
3✔
638
    }
639

640
    public function insert($row = null, bool $returnID = true)
641
    {
642
        if (isset($this->tempData['data'])) {
109✔
643
            if ($row === null) {
2✔
644
                $row = $this->tempData['data'];
1✔
645
            } else {
646
                $row = $this->transformDataToArray($row, 'insert');
1✔
647
                $row = array_merge($this->tempData['data'], $row);
1✔
648
            }
649
        }
650

651
        $this->escape   = $this->tempData['escape'] ?? [];
109✔
652
        $this->tempData = [];
109✔
653

654
        return parent::insert($row, $returnID);
109✔
655
    }
656

657
    protected function doProtectFieldsForInsert(array $row): array
658
    {
659
        if (! $this->protectFields) {
101✔
660
            return $row;
9✔
661
        }
662

663
        if ($this->allowedFields === []) {
92✔
664
            throw DataException::forInvalidAllowedFields(static::class);
1✔
665
        }
666

667
        foreach (array_keys($row) as $key) {
91✔
668
            // Do not remove the non-auto-incrementing primary key data.
669
            if ($this->useAutoIncrement === false && $key === $this->primaryKey) {
90✔
670
                continue;
5✔
671
            }
672

673
            if (! in_array($key, $this->allowedFields, true)) {
90✔
674
                unset($row[$key]);
25✔
675
            }
676
        }
677

678
        return $row;
91✔
679
    }
680

681
    public function update($id = null, $row = null): bool
682
    {
683
        if (isset($this->tempData['data'])) {
46✔
684
            if ($row === null) {
6✔
685
                $row = $this->tempData['data'];
5✔
686
            } else {
687
                $row = $this->transformDataToArray($row, 'update');
1✔
688
                $row = array_merge($this->tempData['data'], $row);
1✔
689
            }
690
        }
691

692
        $this->escape   = $this->tempData['escape'] ?? [];
46✔
693
        $this->tempData = [];
46✔
694

695
        return parent::update($id, $row);
46✔
696
    }
697

698
    protected function objectToRawArray($object, bool $onlyChanged = true, bool $recursive = false): array
699
    {
700
        return parent::objectToRawArray($object, $onlyChanged);
24✔
701
    }
702

703
    /**
704
     * Provides/instantiates the builder/db connection and model's table/primary key names and return type.
705
     *
706
     * @return array<int|string, mixed>|BaseBuilder|bool|float|int|object|string|null
707
     */
708
    public function __get(string $name)
709
    {
710
        if (parent::__isset($name)) {
50✔
711
            return parent::__get($name);
50✔
712
        }
713

714
        return $this->builder()->{$name} ?? null;
1✔
715
    }
716

717
    /**
718
     * Checks for the existence of properties across this model, builder, and db connection.
719
     */
720
    public function __isset(string $name): bool
721
    {
722
        if (parent::__isset($name)) {
47✔
723
            return true;
47✔
724
        }
725

726
        return isset($this->builder()->{$name});
1✔
727
    }
728

729
    /**
730
     * Provides direct access to method in the builder (if available)
731
     * and the database connection.
732
     *
733
     * @return $this|array<int|string, mixed>|BaseBuilder|bool|float|int|object|string|null
734
     */
735
    public function __call(string $name, array $params)
736
    {
737
        $builder = $this->builder();
45✔
738
        $result  = null;
45✔
739

740
        if (method_exists($this->db, $name)) {
45✔
741
            $result = $this->db->{$name}(...$params);
2✔
742
        } elseif (method_exists($builder, $name)) {
44✔
743
            $this->checkBuilderMethod($name);
43✔
744

745
            $result = $builder->{$name}(...$params);
41✔
746
        } else {
747
            throw new BadMethodCallException('Call to undefined method ' . static::class . '::' . $name);
1✔
748
        }
749

750
        if ($result instanceof BaseBuilder) {
42✔
751
            return $this;
41✔
752
        }
753

754
        return $result;
2✔
755
    }
756

757
    /**
758
     * Checks the Builder method name that should not be used in the Model.
759
     */
760
    private function checkBuilderMethod(string $name): void
761
    {
762
        if (in_array($name, $this->builderMethodsNotAvailable, true)) {
43✔
763
            throw ModelException::forMethodNotAvailable(static::class, $name . '()');
2✔
764
        }
765
    }
766
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc