• 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

96.26
/system/BaseModel.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\BaseConnection;
18
use CodeIgniter\Database\BaseResult;
19
use CodeIgniter\Database\Exceptions\DatabaseException;
20
use CodeIgniter\Database\Exceptions\DataException;
21
use CodeIgniter\Database\Query;
22
use CodeIgniter\DataCaster\Cast\CastInterface;
23
use CodeIgniter\DataConverter\DataConverter;
24
use CodeIgniter\Entity\Cast\CastInterface as EntityCastInterface;
25
use CodeIgniter\Entity\Entity;
26
use CodeIgniter\Exceptions\InvalidArgumentException;
27
use CodeIgniter\Exceptions\ModelException;
28
use CodeIgniter\I18n\Time;
29
use CodeIgniter\Pager\Pager;
30
use CodeIgniter\Validation\ValidationInterface;
31
use Config\Feature;
32
use ReflectionClass;
33
use ReflectionException;
34
use ReflectionProperty;
35
use stdClass;
36

37
/**
38
 * The BaseModel class provides a number of convenient features that
39
 * makes working with a databases less painful. Extending this class
40
 * provide means of implementing various database systems.
41
 *
42
 * It will:
43
 *      - simplifies pagination
44
 *      - allow specifying the return type (array, object, etc) with each call
45
 *      - automatically set and update timestamps
46
 *      - handle soft deletes
47
 *      - ensure validation is run against objects when saving items
48
 *      - process various callbacks
49
 *      - allow intermingling calls to the db connection
50
 *
51
 * @phpstan-type row_array               array<int|string, float|int|null|object|string|bool>
52
 * @phpstan-type event_data_beforeinsert array{data: row_array}
53
 * @phpstan-type event_data_afterinsert  array{id: int|string, data: row_array, result: bool}
54
 * @phpstan-type event_data_beforefind   array{id?: int|string, method: string, singleton: bool, limit?: int, offset?: int}
55
 * @phpstan-type event_data_afterfind    array{id: int|string|null|list<int|string>, data: row_array|list<row_array>|object|null, method: string, singleton: bool}
56
 * @phpstan-type event_data_beforeupdate array{id: null|list<int|string>, data: row_array}
57
 * @phpstan-type event_data_afterupdate  array{id: null|list<int|string>, data: row_array|object, result: bool}
58
 * @phpstan-type event_data_beforedelete array{id: null|list<int|string>, purge: bool}
59
 * @phpstan-type event_data_afterdelete  array{id: null|list<int|string>, data: null, purge: bool, result: bool}
60
 */
61
abstract class BaseModel
62
{
63
    /**
64
     * Pager instance.
65
     *
66
     * Populated after calling `$this->paginate()`.
67
     *
68
     * @var Pager
69
     */
70
    public $pager;
71

72
    /**
73
     * Database Connection.
74
     *
75
     * @var BaseConnection
76
     */
77
    protected $db;
78

79
    /**
80
     * Last insert ID.
81
     *
82
     * @var int|string
83
     */
84
    protected $insertID = 0;
85

86
    /**
87
     * The Database connection group that
88
     * should be instantiated.
89
     *
90
     * @var non-empty-string|null
91
     */
92
    protected $DBGroup;
93

94
    /**
95
     * The format that the results should be returned as.
96
     *
97
     * Will be overridden if the `$this->asArray()`, `$this->asObject()` methods are used.
98
     *
99
     * @var 'array'|'object'|class-string
100
     */
101
    protected $returnType = 'array';
102

103
    /**
104
     * The temporary format of the result.
105
     *
106
     * Used by `$this->asArray()` and `$this->asObject()` to provide
107
     * temporary overrides of model default.
108
     *
109
     * @var 'array'|'object'|class-string
110
     */
111
    protected $tempReturnType;
112

113
    /**
114
     * Array of column names and the type of value to cast.
115
     *
116
     * @var array<string, string> Array order `['column' => 'type']`.
117
     */
118
    protected array $casts = [];
119

120
    /**
121
     * Custom convert handlers.
122
     *
123
     * @var array<string, class-string<CastInterface|EntityCastInterface>> Array order `['type' => 'classname']`.
124
     */
125
    protected array $castHandlers = [];
126

127
    protected ?DataConverter $converter = null;
128

129
    /**
130
     * Determines whether the model should protect field names during
131
     * mass assignment operations such as $this->insert(), $this->update().
132
     *
133
     * When set to `true`, only the fields explicitly defined in the `$allowedFields`
134
     * property will be allowed for mass assignment. This helps prevent
135
     * unintended modification of database fields and improves security
136
     * by avoiding mass assignment vulnerabilities.
137
     *
138
     * @var bool
139
     */
140
    protected $protectFields = true;
141

142
    /**
143
     * An array of field names that are allowed
144
     * to be set by the user in inserts/updates.
145
     *
146
     * @var list<string>
147
     */
148
    protected $allowedFields = [];
149

150
    /**
151
     * If true, will set created_at, and updated_at
152
     * values during insert and update routines.
153
     *
154
     * @var bool
155
     */
156
    protected $useTimestamps = false;
157

158
    /**
159
     * The type of column that created_at and updated_at
160
     * are expected to.
161
     *
162
     * @var 'date'|'datetime'|'int'
163
     */
164
    protected $dateFormat = 'datetime';
165

166
    /**
167
     * The column used for insert timestamps.
168
     *
169
     * @var string
170
     */
171
    protected $createdField = 'created_at';
172

173
    /**
174
     * The column used for update timestamps.
175
     *
176
     * @var string
177
     */
178
    protected $updatedField = 'updated_at';
179

180
    /**
181
     * If this model should use "softDeletes" and
182
     * simply set a date when rows are deleted, or
183
     * do hard deletes.
184
     *
185
     * @var bool
186
     */
187
    protected $useSoftDeletes = false;
188

189
    /**
190
     * Used by $this->withDeleted() to override the
191
     * model's "softDelete" setting.
192
     *
193
     * @var bool
194
     */
195
    protected $tempUseSoftDeletes;
196

197
    /**
198
     * The column used to save soft delete state.
199
     *
200
     * @var string
201
     */
202
    protected $deletedField = 'deleted_at';
203

204
    /**
205
     * Whether to allow inserting empty data.
206
     */
207
    protected bool $allowEmptyInserts = false;
208

209
    /**
210
     * Whether to update Entity's only changed data.
211
     */
212
    protected bool $updateOnlyChanged = true;
213

214
    /**
215
     * Rules used to validate data
216
     * in $this->insert(), $this->update(), $this->save() methods.
217
     *
218
     * The array must match the format of data passed to the `Validation`
219
     * library.
220
     *
221
     * @see https://codeigniter4.github.io/userguide/models/model.html#setting-validation-rules
222
     *
223
     * @var array<string, array<string, array<string, string>|string>|string>|string
224
     */
225
    protected $validationRules = [];
226

227
    /**
228
     * Contains any custom error messages to be
229
     * used during data validation.
230
     *
231
     * @var array<string, array<string, string>> The column is used as the keys.
232
     */
233
    protected $validationMessages = [];
234

235
    /**
236
     * Skip the model's validation.
237
     *
238
     * Used in conjunction with `$this->skipValidation()`
239
     * to skip data validation for any future calls.
240
     *
241
     * @var bool
242
     */
243
    protected $skipValidation = false;
244

245
    /**
246
     * Whether rules should be removed that do not exist
247
     * in the passed data. Used in updates.
248
     *
249
     * @var bool
250
     */
251
    protected $cleanValidationRules = true;
252

253
    /**
254
     * Our validator instance.
255
     *
256
     * @var ValidationInterface|null
257
     */
258
    protected $validation;
259

260
    /*
261
     * Callbacks.
262
     *
263
     * Each array should contain the method names (within the model)
264
     * that should be called when those events are triggered.
265
     *
266
     * "Update" and "delete" methods are passed the same items that
267
     * are given to their respective method.
268
     *
269
     * "Find" methods receive the ID searched for (if present), and
270
     * 'afterFind' additionally receives the results that were found.
271
     */
272

273
    /**
274
     * Whether to trigger the defined callbacks.
275
     *
276
     * @var bool
277
     */
278
    protected $allowCallbacks = true;
279

280
    /**
281
     * Used by $this->allowCallbacks() to override the
282
     * model's $allowCallbacks setting.
283
     *
284
     * @var bool
285
     */
286
    protected $tempAllowCallbacks;
287

288
    /**
289
     * Callbacks for "beforeInsert" event.
290
     *
291
     * @var list<string>
292
     */
293
    protected $beforeInsert = [];
294

295
    /**
296
     * Callbacks for "afterInsert" event.
297
     *
298
     * @var list<string>
299
     */
300
    protected $afterInsert = [];
301

302
    /**
303
     * Callbacks for "beforeUpdate" event.
304
     *
305
     * @var list<string>
306
     */
307
    protected $beforeUpdate = [];
308

309
    /**
310
     * Callbacks for "afterUpdate" event.
311
     *
312
     * @var list<string>
313
     */
314
    protected $afterUpdate = [];
315

316
    /**
317
     * Callbacks for "beforeInsertBatch" event.
318
     *
319
     * @var list<string>
320
     */
321
    protected $beforeInsertBatch = [];
322

323
    /**
324
     * Callbacks for "afterInsertBatch" event.
325
     *
326
     * @var list<string>
327
     */
328
    protected $afterInsertBatch = [];
329

330
    /**
331
     * Callbacks for "beforeUpdateBatch" event.
332
     *
333
     * @var list<string>
334
     */
335
    protected $beforeUpdateBatch = [];
336

337
    /**
338
     * Callbacks for "afterUpdateBatch" event.
339
     *
340
     * @var list<string>
341
     */
342
    protected $afterUpdateBatch = [];
343

344
    /**
345
     * Callbacks for "beforeFind" event.
346
     *
347
     * @var list<string>
348
     */
349
    protected $beforeFind = [];
350

351
    /**
352
     * Callbacks for "afterFind" event.
353
     *
354
     * @var list<string>
355
     */
356
    protected $afterFind = [];
357

358
    /**
359
     * Callbacks for "beforeDelete" event.
360
     *
361
     * @var list<string>
362
     */
363
    protected $beforeDelete = [];
364

365
    /**
366
     * Callbacks for "afterDelete" event.
367
     *
368
     * @var list<string>
369
     */
370
    protected $afterDelete = [];
371

372
    public function __construct(?ValidationInterface $validation = null)
373
    {
374
        $this->tempReturnType     = $this->returnType;
315✔
375
        $this->tempUseSoftDeletes = $this->useSoftDeletes;
315✔
376
        $this->tempAllowCallbacks = $this->allowCallbacks;
315✔
377

378
        $this->validation = $validation;
315✔
379

380
        $this->initialize();
315✔
381
        $this->createDataConverter();
315✔
382
    }
383

384
    /**
385
     * Creates DataConverter instance.
386
     */
387
    protected function createDataConverter(): void
388
    {
389
        if ($this->useCasts()) {
315✔
390
            $this->converter = new DataConverter(
30✔
391
                $this->casts,
30✔
392
                $this->castHandlers,
30✔
393
                $this->db,
30✔
394
            );
30✔
395
        }
396
    }
397

398
    /**
399
     * Are casts used?
400
     */
401
    protected function useCasts(): bool
402
    {
403
        return $this->casts !== [];
315✔
404
    }
405

406
    /**
407
     * Initializes the instance with any additional steps.
408
     * Optionally implemented by child classes.
409
     *
410
     * @return void
411
     */
412
    protected function initialize()
413
    {
414
    }
314✔
415

416
    /**
417
     * Fetches the row(s) of database with a primary key
418
     * matching $id.
419
     * This method works only with DB calls.
420
     *
421
     * @param bool                             $singleton Single or multiple results.
422
     * @param int|list<int|string>|string|null $id        One primary key or an array of primary keys.
423
     *
424
     * @return ($singleton is true ? object|row_array|null : list<object|row_array>) The resulting row of data or `null`.
425
     */
426
    abstract protected function doFind(bool $singleton, $id = null);
427

428
    /**
429
     * Fetches the column of database.
430
     * This method works only with DB calls.
431
     *
432
     * @return list<row_array>|null The resulting row of data or `null` if no data found.
433
     *
434
     * @throws DataException
435
     */
436
    abstract protected function doFindColumn(string $columnName);
437

438
    /**
439
     * Fetches all results, while optionally limiting them.
440
     * This method works only with DB calls.
441
     *
442
     * @return list<object|row_array>
443
     */
444
    abstract protected function doFindAll(?int $limit = null, int $offset = 0);
445

446
    /**
447
     * Returns the first row of the result set.
448
     * This method works only with DB calls.
449
     *
450
     * @return object|row_array|null
451
     */
452
    abstract protected function doFirst();
453

454
    /**
455
     * Inserts data into the current database.
456
     * This method works only with DB calls.
457
     *
458
     * @param row_array $row
459
     *
460
     * @return bool
461
     */
462
    abstract protected function doInsert(array $row);
463

464
    /**
465
     * Compiles batch insert and runs the queries, validating each row prior.
466
     * This method works only with DB calls.
467
     *
468
     * @param list<object|row_array>|null $set       An associative array of insert values.
469
     * @param bool|null                   $escape    Whether to escape values.
470
     * @param int                         $batchSize The size of the batch to run.
471
     * @param bool                        $testing   `true` means only number of records is returned, `false` will execute the query.
472
     *
473
     * @return false|int|list<string> Number of rows affected or `false` on failure, SQL array when test mode
474
     */
475
    abstract protected function doInsertBatch(?array $set = null, ?bool $escape = null, int $batchSize = 100, bool $testing = false);
476

477
    /**
478
     * Updates a single record in the database.
479
     * This method works only with DB calls.
480
     *
481
     * @param int|list<int|string>|string|null $id
482
     * @param row_array|null                   $row
483
     */
484
    abstract protected function doUpdate($id = null, $row = null): bool;
485

486
    /**
487
     * Compiles an update and runs the query.
488
     * This method works only with DB calls.
489
     *
490
     * @param list<object|row_array>|null $set       An associative array of update values.
491
     * @param string|null                 $index     The where key.
492
     * @param int                         $batchSize The size of the batch to run.
493
     * @param bool                        $returnSQL `true` means SQL is returned, `false` will execute the query.
494
     *
495
     * @return false|int|list<string> Number of rows affected or `false` on failure, SQL array when test mode
496
     *
497
     * @throws DatabaseException
498
     */
499
    abstract protected function doUpdateBatch(?array $set = null, ?string $index = null, int $batchSize = 100, bool $returnSQL = false);
500

501
    /**
502
     * Deletes a single record from the database where $id matches
503
     * the table's primary key.
504
     * This method works only with DB calls.
505
     *
506
     * @param int|list<int|string>|string|null $id    The rows primary key(s).
507
     * @param bool                             $purge Allows overriding the soft deletes setting.
508
     *
509
     * @return bool|string Returns a SQL string if in test mode.
510
     *
511
     * @throws DatabaseException
512
     */
513
    abstract protected function doDelete($id = null, bool $purge = false);
514

515
    /**
516
     * Permanently deletes all rows that have been marked as deleted
517
     * through soft deletes (value of column $deletedField is not null).
518
     * This method works only with DB calls.
519
     *
520
     * @return bool|string Returns a SQL string if in test mode.
521
     */
522
    abstract protected function doPurgeDeleted();
523

524
    /**
525
     * Works with the $this->find* methods to return only the rows that
526
     * have been deleted (value of column $deletedField is not null).
527
     * This method works only with DB calls.
528
     *
529
     * @return void
530
     */
531
    abstract protected function doOnlyDeleted();
532

533
    /**
534
     * Compiles a replace and runs the query.
535
     * This method works only with DB calls.
536
     *
537
     * @param row_array|null $row
538
     * @param bool           $returnSQL `true` means SQL is returned, `false` will execute the query.
539
     *
540
     * @return BaseResult|false|Query|string
541
     */
542
    abstract protected function doReplace(?array $row = null, bool $returnSQL = false);
543

544
    /**
545
     * Grabs the last error(s) that occurred from the Database connection.
546
     * This method works only with DB calls.
547
     *
548
     * @return array<string, string>
549
     */
550
    abstract protected function doErrors();
551

552
    /**
553
     * Public getter to return the ID value for the data array or object.
554
     * For example with SQL this will return `$data->{$this->primaryKey}`.
555
     *
556
     * @param object|row_array $row
557
     *
558
     * @return int|string|null
559
     */
560
    abstract public function getIdValue($row);
561

562
    /**
563
     * Override countAllResults to account for soft deleted accounts.
564
     * This method works only with DB calls.
565
     *
566
     * @param bool $reset When `false`, the `$tempUseSoftDeletes` will be
567
     *                    dependent on `$useSoftDeletes` value because we don't
568
     *                    want to add the same "where" condition for the second time.
569
     * @param bool $test  `true` returns the number of all records, `false` will execute the query.
570
     *
571
     * @return int|string Returns a SQL string if in test mode.
572
     */
573
    abstract public function countAllResults(bool $reset = true, bool $test = false);
574

575
    /**
576
     * Loops over records in batches, allowing you to operate on them.
577
     * This method works only with DB calls.
578
     *
579
     * @param Closure(array<string, string>|object): mixed $userFunc
580
     *
581
     * @return void
582
     *
583
     * @throws DataException
584
     */
585
    abstract public function chunk(int $size, Closure $userFunc);
586

587
    /**
588
     * Fetches the row of database.
589
     *
590
     * @param int|list<int|string>|string|null $id One primary key or an array of primary keys.
591
     *
592
     * @return ($id is int|string ? object|row_array|null :  list<object|row_array>)
593
     */
594
    public function find($id = null)
595
    {
596
        $singleton = is_numeric($id) || is_string($id);
58✔
597

598
        if ($this->tempAllowCallbacks) {
58✔
599
            // Call the before event and check for a return
600
            $eventData = $this->trigger('beforeFind', [
55✔
601
                'id'        => $id,
55✔
602
                'method'    => 'find',
55✔
603
                'singleton' => $singleton,
55✔
604
            ]);
55✔
605

606
            if (isset($eventData['returnData']) && $eventData['returnData'] === true) {
55✔
607
                return $eventData['data'];
3✔
608
            }
609
        }
610

611
        $eventData = [
56✔
612
            'id'        => $id,
56✔
613
            'data'      => $this->doFind($singleton, $id),
56✔
614
            'method'    => 'find',
56✔
615
            'singleton' => $singleton,
56✔
616
        ];
56✔
617

618
        if ($this->tempAllowCallbacks) {
55✔
619
            $eventData = $this->trigger('afterFind', $eventData);
52✔
620
        }
621

622
        $this->tempReturnType     = $this->returnType;
55✔
623
        $this->tempUseSoftDeletes = $this->useSoftDeletes;
55✔
624
        $this->tempAllowCallbacks = $this->allowCallbacks;
55✔
625

626
        return $eventData['data'];
55✔
627
    }
628

629
    /**
630
     * Fetches the column of database.
631
     *
632
     * @return list<bool|float|int|list<mixed>|object|string|null>|null The resulting row of data, or `null` if no data found.
633
     *
634
     * @throws DataException
635
     */
636
    public function findColumn(string $columnName)
637
    {
638
        if (str_contains($columnName, ',')) {
3✔
639
            throw DataException::forFindColumnHaveMultipleColumns();
1✔
640
        }
641

642
        $resultSet = $this->doFindColumn($columnName);
2✔
643

644
        return $resultSet !== null ? array_column($resultSet, $columnName) : null;
2✔
645
    }
646

647
    /**
648
     * Fetches all results, while optionally limiting them.
649
     *
650
     * @return list<object|row_array>
651
     */
652
    public function findAll(?int $limit = null, int $offset = 0)
653
    {
654
        $limitZeroAsAll = config(Feature::class)->limitZeroAsAll ?? true;
22✔
655
        if ($limitZeroAsAll) {
22✔
656
            $limit ??= 0;
22✔
657
        }
658

659
        if ($this->tempAllowCallbacks) {
22✔
660
            // Call the before event and check for a return
661
            $eventData = $this->trigger('beforeFind', [
22✔
662
                'method'    => 'findAll',
22✔
663
                'limit'     => $limit,
22✔
664
                'offset'    => $offset,
22✔
665
                'singleton' => false,
22✔
666
            ]);
22✔
667

668
            if (isset($eventData['returnData']) && $eventData['returnData'] === true) {
22✔
669
                return $eventData['data'];
1✔
670
            }
671
        }
672

673
        $eventData = [
22✔
674
            'data'      => $this->doFindAll($limit, $offset),
22✔
675
            'limit'     => $limit,
22✔
676
            'offset'    => $offset,
22✔
677
            'method'    => 'findAll',
22✔
678
            'singleton' => false,
22✔
679
        ];
22✔
680

681
        if ($this->tempAllowCallbacks) {
22✔
682
            $eventData = $this->trigger('afterFind', $eventData);
22✔
683
        }
684

685
        $this->tempReturnType     = $this->returnType;
22✔
686
        $this->tempUseSoftDeletes = $this->useSoftDeletes;
22✔
687
        $this->tempAllowCallbacks = $this->allowCallbacks;
22✔
688

689
        return $eventData['data'];
22✔
690
    }
691

692
    /**
693
     * Returns the first row of the result set.
694
     *
695
     * @return object|row_array|null
696
     */
697
    public function first()
698
    {
699
        if ($this->tempAllowCallbacks) {
24✔
700
            // Call the before event and check for a return
701
            $eventData = $this->trigger('beforeFind', [
24✔
702
                'method'    => 'first',
24✔
703
                'singleton' => true,
24✔
704
            ]);
24✔
705

706
            if (isset($eventData['returnData']) && $eventData['returnData'] === true) {
24✔
707
                return $eventData['data'];
1✔
708
            }
709
        }
710

711
        $eventData = [
24✔
712
            'data'      => $this->doFirst(),
24✔
713
            'method'    => 'first',
24✔
714
            'singleton' => true,
24✔
715
        ];
24✔
716

717
        if ($this->tempAllowCallbacks) {
24✔
718
            $eventData = $this->trigger('afterFind', $eventData);
24✔
719
        }
720

721
        $this->tempReturnType     = $this->returnType;
24✔
722
        $this->tempUseSoftDeletes = $this->useSoftDeletes;
24✔
723
        $this->tempAllowCallbacks = $this->allowCallbacks;
24✔
724

725
        return $eventData['data'];
24✔
726
    }
727

728
    /**
729
     * A convenience method that will attempt to determine whether the
730
     * data should be inserted or updated.
731
     *
732
     * Will work with either an array or object.
733
     * When using with custom class objects,
734
     * you must ensure that the class will provide access to the class
735
     * variables, even if through a magic method.
736
     *
737
     * @param object|row_array $row
738
     *
739
     * @throws ReflectionException
740
     */
741
    public function save($row): bool
742
    {
743
        if ((array) $row === []) {
28✔
744
            return true;
1✔
745
        }
746

747
        if ($this->shouldUpdate($row)) {
27✔
748
            $response = $this->update($this->getIdValue($row), $row);
17✔
749
        } else {
750
            $response = $this->insert($row, false);
14✔
751

752
            if ($response !== false) {
13✔
753
                $response = true;
12✔
754
            }
755
        }
756

757
        return $response;
26✔
758
    }
759

760
    /**
761
     * This method is called on save to determine if entry have to be updated.
762
     * If this method returns `false` insert operation will be executed.
763
     *
764
     * @param object|row_array $row
765
     */
766
    protected function shouldUpdate($row): bool
767
    {
768
        $id = $this->getIdValue($row);
27✔
769

770
        return ! in_array($id, [null, [], ''], true);
27✔
771
    }
772

773
    /**
774
     * Returns last insert ID or 0.
775
     *
776
     * @return int|string
777
     */
778
    public function getInsertID()
779
    {
780
        return is_numeric($this->insertID) ? (int) $this->insertID : $this->insertID;
11✔
781
    }
782

783
    /**
784
     * Inserts data into the database. If an object is provided,
785
     * it will attempt to convert it to an array.
786
     *
787
     * @param object|row_array|null $row
788
     * @param bool                  $returnID Whether insert ID should be returned or not.
789
     *
790
     * @return ($returnID is true ? false|int|string : bool)
791
     *
792
     * @throws ReflectionException
793
     */
794
    public function insert($row = null, bool $returnID = true)
795
    {
796
        $this->insertID = 0;
109✔
797

798
        // Set $cleanValidationRules to false temporary.
799
        $cleanValidationRules       = $this->cleanValidationRules;
109✔
800
        $this->cleanValidationRules = false;
109✔
801

802
        $row = $this->transformDataToArray($row, 'insert');
109✔
803

804
        // Validate data before saving.
805
        if (! $this->skipValidation && ! $this->validate($row)) {
107✔
806
            // Restore $cleanValidationRules
807
            $this->cleanValidationRules = $cleanValidationRules;
19✔
808

809
            return false;
19✔
810
        }
811

812
        // Restore $cleanValidationRules
813
        $this->cleanValidationRules = $cleanValidationRules;
90✔
814

815
        // Must be called first, so we don't
816
        // strip out created_at values.
817
        $row = $this->doProtectFieldsForInsert($row);
90✔
818

819
        // doProtectFields() can further remove elements from
820
        // $row, so we need to check for empty dataset again
821
        if (! $this->allowEmptyInserts && $row === []) {
89✔
822
            throw DataException::forEmptyDataset('insert');
2✔
823
        }
824

825
        // Set created_at and updated_at with same time
826
        $date = $this->setDate();
87✔
827
        $row  = $this->setCreatedField($row, $date);
87✔
828
        $row  = $this->setUpdatedField($row, $date);
87✔
829

830
        $eventData = ['data' => $row];
87✔
831

832
        if ($this->tempAllowCallbacks) {
87✔
833
            $eventData = $this->trigger('beforeInsert', $eventData);
87✔
834
        }
835

836
        $result = $this->doInsert($eventData['data']);
86✔
837

838
        $eventData = [
85✔
839
            'id'     => $this->insertID,
85✔
840
            'data'   => $eventData['data'],
85✔
841
            'result' => $result,
85✔
842
        ];
85✔
843

844
        if ($this->tempAllowCallbacks) {
85✔
845
            // Trigger afterInsert events with the inserted data and new ID
846
            $this->trigger('afterInsert', $eventData);
85✔
847
        }
848

849
        $this->tempAllowCallbacks = $this->allowCallbacks;
85✔
850

851
        // If insertion failed, get out of here
852
        if (! $result) {
85✔
853
            return $result;
2✔
854
        }
855

856
        // otherwise return the insertID, if requested.
857
        return $returnID ? $this->insertID : $result;
83✔
858
    }
859

860
    /**
861
     * Set datetime to created field.
862
     *
863
     * @param row_array  $row
864
     * @param int|string $date Timestamp or datetime string.
865
     *
866
     * @return row_array
867
     */
868
    protected function setCreatedField(array $row, $date): array
869
    {
870
        if ($this->useTimestamps && $this->createdField !== '' && ! array_key_exists($this->createdField, $row)) {
99✔
871
            $row[$this->createdField] = $date;
39✔
872
        }
873

874
        return $row;
99✔
875
    }
876

877
    /**
878
     * Set datetime to updated field.
879
     *
880
     * @param row_array  $row
881
     * @param int|string $date Timestamp or datetime string
882
     *
883
     * @return row_array
884
     */
885
    protected function setUpdatedField(array $row, $date): array
886
    {
887
        if ($this->useTimestamps && $this->updatedField !== '' && ! array_key_exists($this->updatedField, $row)) {
114✔
888
            $row[$this->updatedField] = $date;
43✔
889
        }
890

891
        return $row;
114✔
892
    }
893

894
    /**
895
     * Compiles batch insert runs the queries, validating each row prior.
896
     *
897
     * @param list<object|row_array>|null $set       An associative array of insert values.
898
     * @param bool|null                   $escape    Whether to escape values.
899
     * @param int                         $batchSize The size of the batch to run.
900
     * @param bool                        $testing   `true` means only number of records is returned, `false` will execute the query.
901
     *
902
     * @return false|int|list<string> Number of rows inserted or `false` on failure.
903
     *
904
     * @throws ReflectionException
905
     */
906
    public function insertBatch(?array $set = null, ?bool $escape = null, int $batchSize = 100, bool $testing = false)
907
    {
908
        // Set $cleanValidationRules to false temporary.
909
        $cleanValidationRules       = $this->cleanValidationRules;
14✔
910
        $this->cleanValidationRules = false;
14✔
911

912
        if (is_array($set)) {
14✔
913
            foreach ($set as &$row) {
14✔
914
                $row = $this->transformDataToArray($row, 'insert');
14✔
915

916
                // Validate every row.
917
                if (! $this->skipValidation && ! $this->validate($row)) {
14✔
918
                    // Restore $cleanValidationRules
919
                    $this->cleanValidationRules = $cleanValidationRules;
3✔
920

921
                    return false;
3✔
922
                }
923

924
                // Must be called first so we don't
925
                // strip out created_at values.
926
                $row = $this->doProtectFieldsForInsert($row);
11✔
927

928
                // Set created_at and updated_at with same time
929
                $date = $this->setDate();
11✔
930
                $row  = $this->setCreatedField($row, $date);
11✔
931
                $row  = $this->setUpdatedField($row, $date);
11✔
932
            }
933
        }
934

935
        // Restore $cleanValidationRules
936
        $this->cleanValidationRules = $cleanValidationRules;
11✔
937

938
        $eventData = ['data' => $set];
11✔
939

940
        if ($this->tempAllowCallbacks) {
11✔
941
            $eventData = $this->trigger('beforeInsertBatch', $eventData);
11✔
942
        }
943

944
        $result = $this->doInsertBatch($eventData['data'], $escape, $batchSize, $testing);
11✔
945

946
        $eventData = [
11✔
947
            'data'   => $eventData['data'],
11✔
948
            'result' => $result,
11✔
949
        ];
11✔
950

951
        if ($this->tempAllowCallbacks) {
11✔
952
            // Trigger afterInsert events with the inserted data and new ID
953
            $this->trigger('afterInsertBatch', $eventData);
11✔
954
        }
955

956
        $this->tempAllowCallbacks = $this->allowCallbacks;
11✔
957

958
        return $result;
11✔
959
    }
960

961
    /**
962
     * Updates a single record in the database. If an object is provided,
963
     * it will attempt to convert it into an array.
964
     *
965
     * @param int|list<int|string>|string|null $id
966
     * @param object|row_array|null            $row
967
     *
968
     * @throws ReflectionException
969
     */
970
    public function update($id = null, $row = null): bool
971
    {
972
        if (is_bool($id)) {
46✔
973
            throw new InvalidArgumentException('update(): argument #1 ($id) should not be boolean.');
1✔
974
        }
975

976
        // if (is_numeric($id) || is_string($id)) {
977
        if (! in_array($id, [null, 0, '0'], true) && (is_numeric($id) || is_string($id))) {
45✔
978
            $id = [$id];
38✔
979
        }
980

981
        $row = $this->transformDataToArray($row, 'update');
45✔
982

983
        // Validate data before saving.
984
        if (! $this->skipValidation && ! $this->validate($row)) {
43✔
985
            return false;
4✔
986
        }
987

988
        // Must be called first, so we don't
989
        // strip out updated_at values.
990
        $row = $this->doProtectFields($row);
39✔
991

992
        // doProtectFields() can further remove elements from
993
        // $row, so we need to check for empty dataset again
994
        if ($row === []) {
39✔
995
            throw DataException::forEmptyDataset('update');
2✔
996
        }
997

998
        $row = $this->setUpdatedField($row, $this->setDate());
37✔
999

1000
        $eventData = [
37✔
1001
            'id'   => $id,
37✔
1002
            'data' => $row,
37✔
1003
        ];
37✔
1004

1005
        if ($this->tempAllowCallbacks) {
37✔
1006
            $eventData = $this->trigger('beforeUpdate', $eventData);
37✔
1007
        }
1008

1009
        $eventData = [
37✔
1010
            'id'     => $id,
37✔
1011
            'data'   => $eventData['data'],
37✔
1012
            'result' => $this->doUpdate($id, $eventData['data']),
37✔
1013
        ];
37✔
1014

1015
        if ($this->tempAllowCallbacks) {
36✔
1016
            $this->trigger('afterUpdate', $eventData);
36✔
1017
        }
1018

1019
        $this->tempAllowCallbacks = $this->allowCallbacks;
36✔
1020

1021
        return $eventData['result'];
36✔
1022
    }
1023

1024
    /**
1025
     * Compiles an update and runs the query.
1026
     *
1027
     * @param list<object|row_array>|null $set       An associative array of insert values.
1028
     * @param string|null                 $index     The where key.
1029
     * @param int                         $batchSize The size of the batch to run.
1030
     * @param bool                        $returnSQL `true` means SQL is returned, `false` will execute the query.
1031
     *
1032
     * @return false|int|list<string> Number of rows affected or `false` on failure, SQL array when test mode.
1033
     *
1034
     * @throws DatabaseException
1035
     * @throws ReflectionException
1036
     */
1037
    public function updateBatch(?array $set = null, ?string $index = null, int $batchSize = 100, bool $returnSQL = false)
1038
    {
1039
        if (is_array($set)) {
6✔
1040
            foreach ($set as &$row) {
6✔
1041
                $row = $this->transformDataToArray($row, 'update');
6✔
1042

1043
                // Validate data before saving.
1044
                if (! $this->skipValidation && ! $this->validate($row)) {
6✔
1045
                    return false;
1✔
1046
                }
1047

1048
                // Save updateIndex for later
1049
                $updateIndex = $row[$index] ?? null;
5✔
1050

1051
                if ($updateIndex === null) {
5✔
1052
                    throw new InvalidArgumentException(
1✔
1053
                        'The index ("' . $index . '") for updateBatch() is missing in the data: '
1✔
1054
                        . json_encode($row),
1✔
1055
                    );
1✔
1056
                }
1057

1058
                // Must be called first so we don't
1059
                // strip out updated_at values.
1060
                $row = $this->doProtectFields($row);
4✔
1061

1062
                // Restore updateIndex value in case it was wiped out
1063
                $row[$index] = $updateIndex;
4✔
1064

1065
                $row = $this->setUpdatedField($row, $this->setDate());
4✔
1066
            }
1067
        }
1068

1069
        $eventData = ['data' => $set];
4✔
1070

1071
        if ($this->tempAllowCallbacks) {
4✔
1072
            $eventData = $this->trigger('beforeUpdateBatch', $eventData);
4✔
1073
        }
1074

1075
        $result = $this->doUpdateBatch($eventData['data'], $index, $batchSize, $returnSQL);
4✔
1076

1077
        $eventData = [
4✔
1078
            'data'   => $eventData['data'],
4✔
1079
            'result' => $result,
4✔
1080
        ];
4✔
1081

1082
        if ($this->tempAllowCallbacks) {
4✔
1083
            // Trigger afterInsert events with the inserted data and new ID
1084
            $this->trigger('afterUpdateBatch', $eventData);
4✔
1085
        }
1086

1087
        $this->tempAllowCallbacks = $this->allowCallbacks;
4✔
1088

1089
        return $result;
4✔
1090
    }
1091

1092
    /**
1093
     * Deletes a single record from the database where $id matches.
1094
     *
1095
     * @param int|list<int|string>|string|null $id    The rows primary key(s).
1096
     * @param bool                             $purge Allows overriding the soft deletes setting.
1097
     *
1098
     * @return bool|string Returns a SQL string if in test mode.
1099
     *
1100
     * @throws DatabaseException
1101
     */
1102
    public function delete($id = null, bool $purge = false)
1103
    {
1104
        if (is_bool($id)) {
40✔
UNCOV
1105
            throw new InvalidArgumentException('delete(): argument #1 ($id) should not be boolean.');
×
1106
        }
1107

1108
        if (! in_array($id, [null, 0, '0'], true) && (is_numeric($id) || is_string($id))) {
40✔
1109
            $id = [$id];
20✔
1110
        }
1111

1112
        $eventData = [
40✔
1113
            'id'    => $id,
40✔
1114
            'purge' => $purge,
40✔
1115
        ];
40✔
1116

1117
        if ($this->tempAllowCallbacks) {
40✔
1118
            $this->trigger('beforeDelete', $eventData);
39✔
1119
        }
1120

1121
        $eventData = [
40✔
1122
            'id'     => $id,
40✔
1123
            'data'   => null,
40✔
1124
            'purge'  => $purge,
40✔
1125
            'result' => $this->doDelete($id, $purge),
40✔
1126
        ];
40✔
1127

1128
        if ($this->tempAllowCallbacks) {
27✔
1129
            $this->trigger('afterDelete', $eventData);
26✔
1130
        }
1131

1132
        $this->tempAllowCallbacks = $this->allowCallbacks;
27✔
1133

1134
        return $eventData['result'];
27✔
1135
    }
1136

1137
    /**
1138
     * Permanently deletes all rows that have been marked as deleted
1139
     * through soft deletes (value of column $deletedField is not null).
1140
     *
1141
     * @return bool|string Returns a SQL string if in test mode.
1142
     */
1143
    public function purgeDeleted()
1144
    {
1145
        if (! $this->useSoftDeletes) {
2✔
1146
            return true;
1✔
1147
        }
1148

1149
        return $this->doPurgeDeleted();
1✔
1150
    }
1151

1152
    /**
1153
     * Sets $useSoftDeletes value so that we can temporarily override
1154
     * the soft deletes settings. Can be used for all find* methods.
1155
     *
1156
     * @return $this
1157
     */
1158
    public function withDeleted(bool $val = true)
1159
    {
1160
        $this->tempUseSoftDeletes = ! $val;
23✔
1161

1162
        return $this;
23✔
1163
    }
1164

1165
    /**
1166
     * Works with the $this->find* methods to return only the rows that
1167
     * have been deleted.
1168
     *
1169
     * @return $this
1170
     */
1171
    public function onlyDeleted()
1172
    {
1173
        $this->tempUseSoftDeletes = false;
1✔
1174
        $this->doOnlyDeleted();
1✔
1175

1176
        return $this;
1✔
1177
    }
1178

1179
    /**
1180
     * Compiles a replace and runs the query.
1181
     *
1182
     * @param row_array|null $row
1183
     * @param bool           $returnSQL `true` means SQL is returned, `false` will execute the query.
1184
     *
1185
     * @return BaseResult|false|Query|string
1186
     */
1187
    public function replace(?array $row = null, bool $returnSQL = false)
1188
    {
1189
        // Validate data before saving.
1190
        if (($row !== null) && ! $this->skipValidation && ! $this->validate($row)) {
3✔
1191
            return false;
1✔
1192
        }
1193

1194
        $row = (array) $row;
2✔
1195
        $row = $this->setCreatedField($row, $this->setDate());
2✔
1196
        $row = $this->setUpdatedField($row, $this->setDate());
2✔
1197

1198
        return $this->doReplace($row, $returnSQL);
2✔
1199
    }
1200

1201
    /**
1202
     * Grabs the last error(s) that occurred.
1203
     *
1204
     * If data was validated, it will first check for errors there,
1205
     *  otherwise will try to grab the last error from the Database connection.
1206
     *
1207
     * The return array should be in the following format:
1208
     *  `['source' => 'message']`.
1209
     *
1210
     * @param bool $forceDB Always grab the DB error, not validation.
1211
     *
1212
     * @return array<string, string>
1213
     */
1214
    public function errors(bool $forceDB = false)
1215
    {
1216
        if ($this->validation === null) {
24✔
UNCOV
1217
            return $this->doErrors();
×
1218
        }
1219

1220
        // Do we have validation errors?
1221
        if (! $forceDB && ! $this->skipValidation && ($errors = $this->validation->getErrors()) !== []) {
24✔
1222
            return $errors;
22✔
1223
        }
1224

1225
        return $this->doErrors();
2✔
1226
    }
1227

1228
    /**
1229
     * Works with Pager to get the size and offset parameters.
1230
     * Expects a GET variable (?page=2) that specifies the page of results
1231
     * to display.
1232
     *
1233
     * @param int|null $perPage Items per page.
1234
     * @param string   $group   Will be used by the pagination library to identify a unique pagination set.
1235
     * @param int|null $page    Optional page number (useful when the page number is provided in different way).
1236
     * @param int      $segment Optional URI segment number (if page number is provided by URI segment).
1237
     *
1238
     * @return list<object|row_array>
1239
     */
1240
    public function paginate(?int $perPage = null, string $group = 'default', ?int $page = null, int $segment = 0)
1241
    {
1242
        // Since multiple models may use the Pager, the Pager must be shared.
1243
        $pager = service('pager');
8✔
1244

1245
        if ($segment !== 0) {
8✔
UNCOV
1246
            $pager->setSegment($segment, $group);
×
1247
        }
1248

1249
        $page = $page >= 1 ? $page : $pager->getCurrentPage($group);
8✔
1250
        // Store it in the Pager library, so it can be paginated in the views.
1251
        $this->pager = $pager->store($group, $page, $perPage, $this->countAllResults(false), $segment);
8✔
1252
        $perPage     = $this->pager->getPerPage($group);
8✔
1253
        $offset      = ($pager->getCurrentPage($group) - 1) * $perPage;
8✔
1254

1255
        return $this->findAll($perPage, $offset);
8✔
1256
    }
1257

1258
    /**
1259
     * It could be used when you have to change default or override current allowed fields.
1260
     *
1261
     * @param list<string> $allowedFields Array with names of fields.
1262
     *
1263
     * @return $this
1264
     */
1265
    public function setAllowedFields(array $allowedFields)
1266
    {
1267
        $this->allowedFields = $allowedFields;
10✔
1268

1269
        return $this;
10✔
1270
    }
1271

1272
    /**
1273
     * Sets whether or not we should whitelist data set during
1274
     * updates or inserts against $this->availableFields.
1275
     *
1276
     * @return $this
1277
     */
1278
    public function protect(bool $protect = true)
1279
    {
1280
        $this->protectFields = $protect;
12✔
1281

1282
        return $this;
12✔
1283
    }
1284

1285
    /**
1286
     * Ensures that only the fields that are allowed to be updated are
1287
     * in the data array.
1288
     *
1289
     * @used-by update() to protect against mass assignment vulnerabilities.
1290
     * @used-by updateBatch() to protect against mass assignment vulnerabilities.
1291
     *
1292
     * @param row_array $row
1293
     *
1294
     * @return row_array
1295
     *
1296
     * @throws DataException
1297
     */
1298
    protected function doProtectFields(array $row): array
1299
    {
1300
        if (! $this->protectFields) {
43✔
1301
            return $row;
2✔
1302
        }
1303

1304
        if ($this->allowedFields === []) {
41✔
UNCOV
1305
            throw DataException::forInvalidAllowedFields(static::class);
×
1306
        }
1307

1308
        foreach (array_keys($row) as $key) {
41✔
1309
            if (! in_array($key, $this->allowedFields, true)) {
41✔
1310
                unset($row[$key]);
23✔
1311
            }
1312
        }
1313

1314
        return $row;
41✔
1315
    }
1316

1317
    /**
1318
     * Ensures that only the fields that are allowed to be inserted are in
1319
     * the data array.
1320
     *
1321
     * @used-by insert() to protect against mass assignment vulnerabilities.
1322
     * @used-by insertBatch() to protect against mass assignment vulnerabilities.
1323
     *
1324
     * @param row_array $row
1325
     *
1326
     * @return row_array
1327
     *
1328
     * @throws DataException
1329
     */
1330
    protected function doProtectFieldsForInsert(array $row): array
1331
    {
UNCOV
1332
        return $this->doProtectFields($row);
×
1333
    }
1334

1335
    /**
1336
     * Sets the timestamp or current timestamp if null value is passed.
1337
     *
1338
     * @param int|null $userDate An optional PHP timestamp to be converted
1339
     *
1340
     * @return int|string
1341
     *
1342
     * @throws ModelException
1343
     */
1344
    protected function setDate(?int $userDate = null)
1345
    {
1346
        $currentDate = $userDate ?? Time::now()->getTimestamp();
133✔
1347

1348
        return $this->intToDate($currentDate);
133✔
1349
    }
1350

1351
    /**
1352
     * A utility function to allow child models to use the type of
1353
     * date/time format that they prefer. This is primarily used for
1354
     * setting created_at, updated_at and deleted_at values, but can be
1355
     * used by inheriting classes.
1356
     *
1357
     * The available time formats are:
1358
     *  - 'int'      - Stores the date as an integer timestamp.
1359
     *  - 'datetime' - Stores the data in the SQL datetime format.
1360
     *  - 'date'     - Stores the date (only) in the SQL date format.
1361
     *
1362
     * @return int|string
1363
     *
1364
     * @throws ModelException
1365
     */
1366
    protected function intToDate(int $value)
1367
    {
1368
        return match ($this->dateFormat) {
133✔
1369
            'int'      => $value,
36✔
1370
            'datetime' => date($this->db->dateFormat['datetime'], $value),
95✔
1371
            'date'     => date($this->db->dateFormat['date'], $value),
1✔
1372
            default    => throw ModelException::forNoDateFormat(static::class),
133✔
1373
        };
133✔
1374
    }
1375

1376
    /**
1377
     * Converts Time value to string using $this->dateFormat.
1378
     *
1379
     * The available time formats are:
1380
     *  - 'int'      - Stores the date as an integer timestamp.
1381
     *  - 'datetime' - Stores the data in the SQL datetime format.
1382
     *  - 'date'     - Stores the date (only) in the SQL date format.
1383
     *
1384
     * @return int|string
1385
     */
1386
    protected function timeToDate(Time $value)
1387
    {
1388
        return match ($this->dateFormat) {
5✔
1389
            'datetime' => $value->format($this->db->dateFormat['datetime']),
3✔
1390
            'date'     => $value->format($this->db->dateFormat['date']),
1✔
1391
            'int'      => $value->getTimestamp(),
1✔
1392
            default    => (string) $value,
5✔
1393
        };
5✔
1394
    }
1395

1396
    /**
1397
     * Set the value of the $skipValidation flag.
1398
     *
1399
     * @return $this
1400
     */
1401
    public function skipValidation(bool $skip = true)
1402
    {
1403
        $this->skipValidation = $skip;
2✔
1404

1405
        return $this;
2✔
1406
    }
1407

1408
    /**
1409
     * Allows to set (and reset) validation messages.
1410
     * It could be used when you have to change default or override current validate messages.
1411
     *
1412
     * @param array<string, array<string, string>> $validationMessages
1413
     *
1414
     * @return $this
1415
     */
1416
    public function setValidationMessages(array $validationMessages)
1417
    {
UNCOV
1418
        $this->validationMessages = $validationMessages;
×
1419

UNCOV
1420
        return $this;
×
1421
    }
1422

1423
    /**
1424
     * Allows to set field wise validation message.
1425
     * It could be used when you have to change default or override current validate messages.
1426
     *
1427
     * @param array<string, string> $fieldMessages
1428
     *
1429
     * @return $this
1430
     */
1431
    public function setValidationMessage(string $field, array $fieldMessages)
1432
    {
1433
        $this->validationMessages[$field] = $fieldMessages;
2✔
1434

1435
        return $this;
2✔
1436
    }
1437

1438
    /**
1439
     * Allows to set (and reset) validation rules.
1440
     * It could be used when you have to change default or override current validate rules.
1441
     *
1442
     * @param array<string, array<string, array<string, string>|string>|string> $validationRules
1443
     *
1444
     * @return $this
1445
     */
1446
    public function setValidationRules(array $validationRules)
1447
    {
1448
        $this->validationRules = $validationRules;
2✔
1449

1450
        return $this;
2✔
1451
    }
1452

1453
    /**
1454
     * Allows to set field wise validation rules.
1455
     * It could be used when you have to change default or override current validate rules.
1456
     *
1457
     * @param array<string, array<string, string>|string>|string $fieldRules
1458
     *
1459
     * @return $this
1460
     */
1461
    public function setValidationRule(string $field, $fieldRules)
1462
    {
1463
        $rules = $this->validationRules;
2✔
1464

1465
        // ValidationRules can be either a string, which is the group name,
1466
        // or an array of rules.
1467
        if (is_string($rules)) {
2✔
1468
            $this->ensureValidation();
1✔
1469

1470
            [$rules, $customErrors] = $this->validation->loadRuleGroup($rules);
1✔
1471

1472
            $this->validationRules = $rules;
1✔
1473
            $this->validationMessages += $customErrors;
1✔
1474
        }
1475

1476
        $this->validationRules[$field] = $fieldRules;
2✔
1477

1478
        return $this;
2✔
1479
    }
1480

1481
    /**
1482
     * Should validation rules be removed before saving?
1483
     * Most handy when doing updates.
1484
     *
1485
     * @return $this
1486
     */
1487
    public function cleanRules(bool $choice = false)
1488
    {
1489
        $this->cleanValidationRules = $choice;
2✔
1490

1491
        return $this;
2✔
1492
    }
1493

1494
    /**
1495
     * Validate the row data against the validation rules (or the validation group)
1496
     * specified in the class property, $validationRules.
1497
     *
1498
     * @param object|row_array $row
1499
     */
1500
    public function validate($row): bool
1501
    {
1502
        if ($this->skipValidation) {
151✔
UNCOV
1503
            return true;
×
1504
        }
1505

1506
        $rules = $this->getValidationRules();
151✔
1507

1508
        if ($rules === []) {
151✔
1509
            return true;
105✔
1510
        }
1511

1512
        // Validation requires array, so cast away.
1513
        if (is_object($row)) {
46✔
1514
            $row = (array) $row;
2✔
1515
        }
1516

1517
        if ($row === []) {
46✔
UNCOV
1518
            return true;
×
1519
        }
1520

1521
        $rules = $this->cleanValidationRules ? $this->cleanValidationRules($rules, $row) : $rules;
46✔
1522

1523
        // If no data existed that needs validation
1524
        // our job is done here.
1525
        if ($rules === []) {
46✔
1526
            return true;
2✔
1527
        }
1528

1529
        $this->ensureValidation();
44✔
1530

1531
        $this->validation->reset()->setRules($rules, $this->validationMessages);
44✔
1532

1533
        return $this->validation->run($row, null, $this->DBGroup);
44✔
1534
    }
1535

1536
    /**
1537
     * Returns the model's defined validation rules so that they
1538
     * can be used elsewhere, if needed.
1539
     *
1540
     * @param array{only?: list<string>, except?: list<string>} $options Filter the list of rules
1541
     *
1542
     * @return array<string, array<string, array<string, string>|string>|string>
1543
     */
1544
    public function getValidationRules(array $options = []): array
1545
    {
1546
        $rules = $this->validationRules;
153✔
1547

1548
        // ValidationRules can be either a string, which is the group name,
1549
        // or an array of rules.
1550
        if (is_string($rules)) {
153✔
1551
            $this->ensureValidation();
13✔
1552

1553
            [$rules, $customErrors] = $this->validation->loadRuleGroup($rules);
13✔
1554

1555
            $this->validationMessages += $customErrors;
13✔
1556
        }
1557

1558
        if (isset($options['except'])) {
153✔
UNCOV
1559
            $rules = array_diff_key($rules, array_flip($options['except']));
×
1560
        } elseif (isset($options['only'])) {
153✔
UNCOV
1561
            $rules = array_intersect_key($rules, array_flip($options['only']));
×
1562
        }
1563

1564
        return $rules;
153✔
1565
    }
1566

1567
    protected function ensureValidation(): void
1568
    {
1569
        if ($this->validation === null) {
45✔
1570
            $this->validation = service('validation', null, false);
29✔
1571
        }
1572
    }
1573

1574
    /**
1575
     * Returns the model's validation messages, so they
1576
     * can be used elsewhere, if needed.
1577
     *
1578
     * @return array<string, array<string, string>>
1579
     */
1580
    public function getValidationMessages(): array
1581
    {
1582
        return $this->validationMessages;
2✔
1583
    }
1584

1585
    /**
1586
     * Removes any rules that apply to fields that have not been set
1587
     * currently so that rules don't block updating when only updating
1588
     * a partial row.
1589
     *
1590
     * @param array<string, array<string, array<string, string>|string>|string> $rules
1591
     * @param row_array                                                         $row
1592
     *
1593
     * @return array<string, array<string, array<string, string>|string>|string>
1594
     */
1595
    protected function cleanValidationRules(array $rules, array $row): array
1596
    {
1597
        if ($row === []) {
21✔
1598
            return [];
2✔
1599
        }
1600

1601
        foreach (array_keys($rules) as $field) {
19✔
1602
            if (! array_key_exists($field, $row)) {
19✔
1603
                unset($rules[$field]);
8✔
1604
            }
1605
        }
1606

1607
        return $rules;
19✔
1608
    }
1609

1610
    /**
1611
     * Sets $tempAllowCallbacks value so that we can temporarily override
1612
     * the setting. Resets after the next method that uses triggers.
1613
     *
1614
     * @return $this
1615
     */
1616
    public function allowCallbacks(bool $val = true)
1617
    {
1618
        $this->tempAllowCallbacks = $val;
3✔
1619

1620
        return $this;
3✔
1621
    }
1622

1623
    /**
1624
     * A simple event trigger for Model Events that allows additional
1625
     * data manipulation within the model. Specifically intended for
1626
     * usage by child models this can be used to format data,
1627
     * save/load related classes, etc.
1628
     *
1629
     * It is the responsibility of the callback methods to return
1630
     * the data itself.
1631
     *
1632
     * Each $eventData array MUST have a 'data' key with the relevant
1633
     * data for callback methods (like an array of key/value pairs to insert
1634
     * or update, an array of results, etc.)
1635
     *
1636
     * If callbacks are not allowed then returns $eventData immediately.
1637
     *
1638
     * @template TEventData of array<string, mixed>
1639
     *
1640
     * @param string     $event     Valid property of the model event: $this->before*, $this->after*, etc.
1641
     * @param TEventData $eventData
1642
     *
1643
     * @return TEventData
1644
     *
1645
     * @throws DataException
1646
     */
1647
    protected function trigger(string $event, array $eventData)
1648
    {
1649
        // Ensure it's a valid event
1650
        if (! isset($this->{$event}) || $this->{$event} === []) {
193✔
1651
            return $eventData;
178✔
1652
        }
1653

1654
        foreach ($this->{$event} as $callback) {
15✔
1655
            if (! method_exists($this, $callback)) {
15✔
1656
                throw DataException::forInvalidMethodTriggered($callback);
1✔
1657
            }
1658

1659
            $eventData = $this->{$callback}($eventData);
14✔
1660
        }
1661

1662
        return $eventData;
14✔
1663
    }
1664

1665
    /**
1666
     * Sets the return type of the results to be as an associative array.
1667
     *
1668
     * @return $this
1669
     */
1670
    public function asArray()
1671
    {
1672
        $this->tempReturnType = 'array';
31✔
1673

1674
        return $this;
31✔
1675
    }
1676

1677
    /**
1678
     * Sets the return type to be of the specified type of object.
1679
     * Defaults to a simple object, but can be any class that has
1680
     * class vars with the same name as the collection columns,
1681
     * or at least allows them to be created.
1682
     *
1683
     * @param 'object'|class-string $class
1684
     *
1685
     * @return $this
1686
     */
1687
    public function asObject(string $class = 'object')
1688
    {
1689
        $this->tempReturnType = $class;
18✔
1690

1691
        return $this;
18✔
1692
    }
1693

1694
    /**
1695
     * Takes a class and returns an array of its public and protected
1696
     * properties as an array suitable for use in creates and updates.
1697
     * This method uses `$this->objectToRawArray()` internally and does conversion
1698
     * to string on all Time instances.
1699
     *
1700
     * @param object $object
1701
     * @param bool   $onlyChanged Returns only the changed properties.
1702
     * @param bool   $recursive   If `true`, inner entities will be cast as array as well.
1703
     *
1704
     * @return array<string, mixed>
1705
     *
1706
     * @throws ReflectionException
1707
     */
1708
    protected function objectToArray($object, bool $onlyChanged = true, bool $recursive = false): array
1709
    {
1710
        $properties = $this->objectToRawArray($object, $onlyChanged, $recursive);
24✔
1711

1712
        // Convert any Time instances to appropriate $dateFormat
1713
        return $this->timeToString($properties);
24✔
1714
    }
1715

1716
    /**
1717
     * Convert any Time instances to appropriate $dateFormat.
1718
     *
1719
     * @param array<string, mixed> $properties
1720
     *
1721
     * @return array<string, mixed>
1722
     */
1723
    protected function timeToString(array $properties): array
1724
    {
1725
        if ($properties === []) {
142✔
1726
            return [];
1✔
1727
        }
1728

1729
        return array_map(function ($value) {
141✔
1730
            if ($value instanceof Time) {
141✔
1731
                return $this->timeToDate($value);
5✔
1732
            }
1733

1734
            return $value;
141✔
1735
        }, $properties);
141✔
1736
    }
1737

1738
    /**
1739
     * Takes a class and returns an array of its public and protected
1740
     * properties as an array with raw values.
1741
     *
1742
     * @param object $object
1743
     * @param bool   $onlyChanged Returns only the changed properties.
1744
     * @param bool   $recursive   If `true`, inner entities will be cast as array as well.
1745
     *
1746
     * @return array<string, mixed> Array with raw values
1747
     *
1748
     * @throws ReflectionException
1749
     */
1750
    protected function objectToRawArray($object, bool $onlyChanged = true, bool $recursive = false): array
1751
    {
1752
        // Entity::toRawArray() returns array
1753
        if (method_exists($object, 'toRawArray')) {
24✔
1754
            $properties = $object->toRawArray($onlyChanged, $recursive);
22✔
1755
        } else {
1756
            $mirror = new ReflectionClass($object);
2✔
1757
            $props  = $mirror->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);
2✔
1758

1759
            $properties = [];
2✔
1760

1761
            // Loop over each property,
1762
            // saving the name/value in a new array we can return
1763
            foreach ($props as $prop) {
2✔
1764
                $properties[$prop->getName()] = $prop->getValue($object);
2✔
1765
            }
1766
        }
1767

1768
        return $properties;
24✔
1769
    }
1770

1771
    /**
1772
     * Transform data to array.
1773
     *
1774
     * @param object|row_array|null $row
1775
     *
1776
     * @return array<int|string, mixed>
1777
     *
1778
     * @throws DataException
1779
     * @throws InvalidArgumentException
1780
     * @throws ReflectionException
1781
     *
1782
     * @used-by insert()
1783
     * @used-by insertBatch()
1784
     * @used-by update()
1785
     * @used-by updateBatch()
1786
     */
1787
    protected function transformDataToArray($row, string $type): array
1788
    {
1789
        if (! in_array($type, ['insert', 'update'], true)) {
146✔
1790
            throw new InvalidArgumentException(sprintf('Invalid type "%s" used upon transforming data to array.', $type));
1✔
1791
        }
1792

1793
        if (! $this->allowEmptyInserts && ($row === null || (array) $row === [])) {
145✔
1794
            throw DataException::forEmptyDataset($type);
6✔
1795
        }
1796

1797
        // If it validates with entire rules, all fields are needed.
1798
        if ($this->skipValidation === false && $this->cleanValidationRules === false) {
142✔
1799
            $onlyChanged = false;
123✔
1800
        } else {
1801
            $onlyChanged = ($type === 'update' && $this->updateOnlyChanged);
48✔
1802
        }
1803

1804
        if ($this->useCasts()) {
142✔
1805
            if (is_array($row)) {
27✔
1806
                $row = $this->converter->toDataSource($row);
27✔
1807
            } elseif ($row instanceof stdClass) {
7✔
1808
                $row = (array) $row;
3✔
1809
                $row = $this->converter->toDataSource($row);
3✔
1810
            } elseif ($row instanceof Entity) {
4✔
1811
                $row = $this->converter->extract($row, $onlyChanged);
2✔
1812
            } elseif (is_object($row)) {
2✔
1813
                $row = $this->converter->extract($row, $onlyChanged);
2✔
1814
            }
1815
        }
1816
        // If $row is using a custom class with public or protected
1817
        // properties representing the collection elements, we need to grab
1818
        // them as an array.
1819
        elseif (is_object($row) && ! $row instanceof stdClass) {
115✔
1820
            $row = $this->objectToArray($row, $onlyChanged, true);
23✔
1821
        }
1822

1823
        // If it's still a stdClass, go ahead and convert to
1824
        // an array so doProtectFields and other model methods
1825
        // don't have to do special checks.
1826
        if (is_object($row)) {
142✔
1827
            $row = (array) $row;
13✔
1828
        }
1829

1830
        // If it's still empty here, means $row is no change or is empty object
1831
        if (! $this->allowEmptyInserts && ($row === null || $row === [])) {
142✔
UNCOV
1832
            throw DataException::forEmptyDataset($type);
×
1833
        }
1834

1835
        // Convert any Time instances to appropriate $dateFormat
1836
        return $this->timeToString($row);
142✔
1837
    }
1838

1839
    /**
1840
     * Provides the DB connection and model's properties.
1841
     *
1842
     * @return mixed
1843
     */
1844
    public function __get(string $name)
1845
    {
1846
        if (property_exists($this, $name)) {
50✔
1847
            return $this->{$name};
50✔
1848
        }
1849

1850
        return $this->db->{$name} ?? null;
1✔
1851
    }
1852

1853
    /**
1854
     * Checks for the existence of properties across this model, and DB connection.
1855
     */
1856
    public function __isset(string $name): bool
1857
    {
1858
        if (property_exists($this, $name)) {
50✔
1859
            return true;
50✔
1860
        }
1861

1862
        return isset($this->db->{$name});
1✔
1863
    }
1864

1865
    /**
1866
     * Provides direct access to method in the database connection.
1867
     *
1868
     * @param array<int|string, mixed> $params
1869
     *
1870
     * @return mixed
1871
     */
1872
    public function __call(string $name, array $params)
1873
    {
1874
        if (method_exists($this->db, $name)) {
×
UNCOV
1875
            return $this->db->{$name}(...$params);
×
1876
        }
1877

UNCOV
1878
        return null;
×
1879
    }
1880

1881
    /**
1882
     * Sets $allowEmptyInserts.
1883
     */
1884
    public function allowEmptyInserts(bool $value = true): self
1885
    {
1886
        $this->allowEmptyInserts = $value;
1✔
1887

1888
        return $this;
1✔
1889
    }
1890

1891
    /**
1892
     * Converts database data array to return type value.
1893
     *
1894
     * @param array<string, mixed>          $row        Raw data from database.
1895
     * @param 'array'|'object'|class-string $returnType
1896
     *
1897
     * @return array<string, mixed>|object
1898
     */
1899
    protected function convertToReturnType(array $row, string $returnType): array|object
1900
    {
1901
        if ($returnType === 'array') {
25✔
1902
            return $this->converter->fromDataSource($row);
10✔
1903
        }
1904

1905
        if ($returnType === 'object') {
17✔
1906
            return (object) $this->converter->fromDataSource($row);
5✔
1907
        }
1908

1909
        return $this->converter->reconstruct($returnType, $row);
12✔
1910
    }
1911
}
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