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

codeigniter4 / CodeIgniter4 / 8586246081

07 Apr 2024 04:43AM UTC coverage: 86.602% (+1.0%) from 85.607%
8586246081

push

github

web-flow
Merge pull request #8720 from codeigniter4/4.5

Merge 4.5 into develop

2273 of 2603 new or added lines in 188 files covered. (87.32%)

53 existing lines in 18 files now uncovered.

19947 of 23033 relevant lines covered (86.6%)

189.35 hits per line

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

95.59
/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\DataConverter\DataConverter;
23
use CodeIgniter\Entity\Entity;
24
use CodeIgniter\Exceptions\ModelException;
25
use CodeIgniter\I18n\Time;
26
use CodeIgniter\Pager\Pager;
27
use CodeIgniter\Validation\ValidationInterface;
28
use Config\Feature;
29
use Config\Services;
30
use InvalidArgumentException;
31
use ReflectionClass;
32
use ReflectionException;
33
use ReflectionProperty;
34
use stdClass;
35

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

70
    /**
71
     * Database Connection
72
     *
73
     * @var BaseConnection
74
     */
75
    protected $db;
76

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

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

92
    /**
93
     * The format that the results should be returned as.
94
     * Will be overridden if the as* methods are used.
95
     *
96
     * @var string
97
     */
98
    protected $returnType = 'array';
99

100
    /**
101
     * Used by asArray() and asObject() to provide
102
     * temporary overrides of model default.
103
     *
104
     * @var 'array'|'object'|class-string
105
     */
106
    protected $tempReturnType;
107

108
    /**
109
     * Array of column names and the type of value to cast.
110
     *
111
     * @var array<string, string> [column => type]
112
     */
113
    protected array $casts = [];
114

115
    /**
116
     * Custom convert handlers.
117
     *
118
     * @var array<string, class-string> [type => classname]
119
     */
120
    protected array $castHandlers = [];
121

122
    protected ?DataConverter $converter = null;
123

124
    /**
125
     * If this model should use "softDeletes" and
126
     * simply set a date when rows are deleted, or
127
     * do hard deletes.
128
     *
129
     * @var bool
130
     */
131
    protected $protectFields = true;
132

133
    /**
134
     * An array of field names that are allowed
135
     * to be set by the user in inserts/updates.
136
     *
137
     * @var list<string>
138
     */
139
    protected $allowedFields = [];
140

141
    /**
142
     * If true, will set created_at, and updated_at
143
     * values during insert and update routines.
144
     *
145
     * @var bool
146
     */
147
    protected $useTimestamps = false;
148

149
    /**
150
     * The type of column that created_at and updated_at
151
     * are expected to.
152
     *
153
     * Allowed: 'datetime', 'date', 'int'
154
     *
155
     * @var string
156
     */
157
    protected $dateFormat = 'datetime';
158

159
    /**
160
     * The column used for insert timestamps
161
     *
162
     * @var string
163
     */
164
    protected $createdField = 'created_at';
165

166
    /**
167
     * The column used for update timestamps
168
     *
169
     * @var string
170
     */
171
    protected $updatedField = 'updated_at';
172

173
    /**
174
     * If this model should use "softDeletes" and
175
     * simply set a date when rows are deleted, or
176
     * do hard deletes.
177
     *
178
     * @var bool
179
     */
180
    protected $useSoftDeletes = false;
181

182
    /**
183
     * Used by withDeleted to override the
184
     * model's softDelete setting.
185
     *
186
     * @var bool
187
     */
188
    protected $tempUseSoftDeletes;
189

190
    /**
191
     * The column used to save soft delete state
192
     *
193
     * @var string
194
     */
195
    protected $deletedField = 'deleted_at';
196

197
    /**
198
     * Whether to allow inserting empty data.
199
     */
200
    protected bool $allowEmptyInserts = false;
201

202
    /**
203
     * Whether to update Entity's only changed data.
204
     */
205
    protected bool $updateOnlyChanged = true;
206

207
    /**
208
     * Rules used to validate data in insert(), update(), and save() methods.
209
     *
210
     * The array must match the format of data passed to the Validation
211
     * library.
212
     *
213
     * @see https://codeigniter4.github.io/userguide/models/model.html#setting-validation-rules
214
     *
215
     * @var array<string, array<string, array<string, string>|string>|string>|string
216
     */
217
    protected $validationRules = [];
218

219
    /**
220
     * Contains any custom error messages to be
221
     * used during data validation.
222
     *
223
     * @var array<string, array<string, string>>
224
     */
225
    protected $validationMessages = [];
226

227
    /**
228
     * Skip the model's validation. Used in conjunction with skipValidation()
229
     * to skip data validation for any future calls.
230
     *
231
     * @var bool
232
     */
233
    protected $skipValidation = false;
234

235
    /**
236
     * Whether rules should be removed that do not exist
237
     * in the passed data. Used in updates.
238
     *
239
     * @var bool
240
     */
241
    protected $cleanValidationRules = true;
242

243
    /**
244
     * Our validator instance.
245
     *
246
     * @var ValidationInterface|null
247
     */
248
    protected $validation;
249

250
    /*
251
     * Callbacks.
252
     *
253
     * Each array should contain the method names (within the model)
254
     * that should be called when those events are triggered.
255
     *
256
     * "Update" and "delete" methods are passed the same items that
257
     * are given to their respective method.
258
     *
259
     * "Find" methods receive the ID searched for (if present), and
260
     * 'afterFind' additionally receives the results that were found.
261
     */
262

263
    /**
264
     * Whether to trigger the defined callbacks
265
     *
266
     * @var bool
267
     */
268
    protected $allowCallbacks = true;
269

270
    /**
271
     * Used by allowCallbacks() to override the
272
     * model's allowCallbacks setting.
273
     *
274
     * @var bool
275
     */
276
    protected $tempAllowCallbacks;
277

278
    /**
279
     * Callbacks for beforeInsert
280
     *
281
     * @var list<string>
282
     */
283
    protected $beforeInsert = [];
284

285
    /**
286
     * Callbacks for afterInsert
287
     *
288
     * @var list<string>
289
     */
290
    protected $afterInsert = [];
291

292
    /**
293
     * Callbacks for beforeUpdate
294
     *
295
     * @var list<string>
296
     */
297
    protected $beforeUpdate = [];
298

299
    /**
300
     * Callbacks for afterUpdate
301
     *
302
     * @var list<string>
303
     */
304
    protected $afterUpdate = [];
305

306
    /**
307
     * Callbacks for beforeInsertBatch
308
     *
309
     * @var list<string>
310
     */
311
    protected $beforeInsertBatch = [];
312

313
    /**
314
     * Callbacks for afterInsertBatch
315
     *
316
     * @var list<string>
317
     */
318
    protected $afterInsertBatch = [];
319

320
    /**
321
     * Callbacks for beforeUpdateBatch
322
     *
323
     * @var list<string>
324
     */
325
    protected $beforeUpdateBatch = [];
326

327
    /**
328
     * Callbacks for afterUpdateBatch
329
     *
330
     * @var list<string>
331
     */
332
    protected $afterUpdateBatch = [];
333

334
    /**
335
     * Callbacks for beforeFind
336
     *
337
     * @var list<string>
338
     */
339
    protected $beforeFind = [];
340

341
    /**
342
     * Callbacks for afterFind
343
     *
344
     * @var list<string>
345
     */
346
    protected $afterFind = [];
347

348
    /**
349
     * Callbacks for beforeDelete
350
     *
351
     * @var list<string>
352
     */
353
    protected $beforeDelete = [];
354

355
    /**
356
     * Callbacks for afterDelete
357
     *
358
     * @var list<string>
359
     */
360
    protected $afterDelete = [];
361

362
    public function __construct(?ValidationInterface $validation = null)
363
    {
364
        $this->tempReturnType     = $this->returnType;
305✔
365
        $this->tempUseSoftDeletes = $this->useSoftDeletes;
305✔
366
        $this->tempAllowCallbacks = $this->allowCallbacks;
305✔
367

368
        $this->validation = $validation;
305✔
369

370
        $this->initialize();
305✔
371
        $this->createDataConverter();
305✔
372
    }
373

374
    /**
375
     * Creates DataConverter instance.
376
     */
377
    protected function createDataConverter(): void
378
    {
379
        if ($this->useCasts()) {
305✔
380
            $this->converter = new DataConverter(
23✔
381
                $this->casts,
23✔
382
                $this->castHandlers,
23✔
383
                $this->db
23✔
384
            );
23✔
385
        }
386
    }
387

388
    /**
389
     * Are casts used?
390
     */
391
    protected function useCasts(): bool
392
    {
393
        return $this->casts !== [];
305✔
394
    }
395

396
    /**
397
     * Initializes the instance with any additional steps.
398
     * Optionally implemented by child classes.
399
     *
400
     * @return void
401
     */
402
    protected function initialize()
403
    {
404
    }
304✔
405

406
    /**
407
     * Fetches the row of database.
408
     * This method works only with dbCalls.
409
     *
410
     * @param bool                  $singleton Single or multiple results
411
     * @param array|int|string|null $id        One primary key or an array of primary keys
412
     *
413
     * @return array|object|null The resulting row of data, or null.
414
     */
415
    abstract protected function doFind(bool $singleton, $id = null);
416

417
    /**
418
     * Fetches the column of database.
419
     * This method works only with dbCalls.
420
     *
421
     * @param string $columnName Column Name
422
     *
423
     * @return array|null The resulting row of data, or null if no data found.
424
     *
425
     * @throws DataException
426
     */
427
    abstract protected function doFindColumn(string $columnName);
428

429
    /**
430
     * Fetches all results, while optionally limiting them.
431
     * This method works only with dbCalls.
432
     *
433
     * @param int|null $limit  Limit
434
     * @param int      $offset Offset
435
     *
436
     * @return array
437
     */
438
    abstract protected function doFindAll(?int $limit = null, int $offset = 0);
439

440
    /**
441
     * Returns the first row of the result set.
442
     * This method works only with dbCalls.
443
     *
444
     * @return array|object|null
445
     */
446
    abstract protected function doFirst();
447

448
    /**
449
     * Inserts data into the current database.
450
     * This method works only with dbCalls.
451
     *
452
     * @param         array     $row Row data
453
     * @phpstan-param row_array $row
454
     *
455
     * @return bool
456
     */
457
    abstract protected function doInsert(array $row);
458

459
    /**
460
     * Compiles batch insert and runs the queries, validating each row prior.
461
     * This method works only with dbCalls.
462
     *
463
     * @param array|null $set       An associative array of insert values
464
     * @param bool|null  $escape    Whether to escape values
465
     * @param int        $batchSize The size of the batch to run
466
     * @param bool       $testing   True means only number of records is returned, false will execute the query
467
     *
468
     * @return bool|int Number of rows inserted or FALSE on failure
469
     */
470
    abstract protected function doInsertBatch(?array $set = null, ?bool $escape = null, int $batchSize = 100, bool $testing = false);
471

472
    /**
473
     * Updates a single record in the database.
474
     * This method works only with dbCalls.
475
     *
476
     * @param         array|int|string|null $id  ID
477
     * @param         array|null            $row Row data
478
     * @phpstan-param row_array|null        $row
479
     */
480
    abstract protected function doUpdate($id = null, $row = null): bool;
481

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

497
    /**
498
     * Deletes a single record from the database where $id matches.
499
     * This method works only with dbCalls.
500
     *
501
     * @param array|int|string|null $id    The rows primary key(s)
502
     * @param bool                  $purge Allows overriding the soft deletes setting.
503
     *
504
     * @return bool|string
505
     *
506
     * @throws DatabaseException
507
     */
508
    abstract protected function doDelete($id = null, bool $purge = false);
509

510
    /**
511
     * Permanently deletes all rows that have been marked as deleted.
512
     * through soft deletes (deleted = 1).
513
     * This method works only with dbCalls.
514
     *
515
     * @return bool|string Returns a string if in test mode.
516
     */
517
    abstract protected function doPurgeDeleted();
518

519
    /**
520
     * Works with the find* methods to return only the rows that
521
     * have been deleted.
522
     * This method works only with dbCalls.
523
     *
524
     * @return void
525
     */
526
    abstract protected function doOnlyDeleted();
527

528
    /**
529
     * Compiles a replace and runs the query.
530
     * This method works only with dbCalls.
531
     *
532
     * @param         array|null     $row       Row data
533
     * @phpstan-param row_array|null $row
534
     * @param         bool           $returnSQL Set to true to return Query String
535
     *
536
     * @return BaseResult|false|Query|string
537
     */
538
    abstract protected function doReplace(?array $row = null, bool $returnSQL = false);
539

540
    /**
541
     * Grabs the last error(s) that occurred from the Database connection.
542
     * This method works only with dbCalls.
543
     *
544
     * @return array|null
545
     */
546
    abstract protected function doErrors();
547

548
    /**
549
     * Public getter to return the id value using the idValue() method.
550
     * For example with SQL this will return $data->$this->primaryKey.
551
     *
552
     * @param         array|object     $row Row data
553
     * @phpstan-param row_array|object $row
554
     *
555
     * @return array|int|string|null
556
     */
557
    abstract public function getIdValue($row);
558

559
    /**
560
     * Override countAllResults to account for soft deleted accounts.
561
     * This method works only with dbCalls.
562
     *
563
     * @param bool $reset Reset
564
     * @param bool $test  Test
565
     *
566
     * @return int|string
567
     */
568
    abstract public function countAllResults(bool $reset = true, bool $test = false);
569

570
    /**
571
     * Loops over records in batches, allowing you to operate on them.
572
     * This method works only with dbCalls.
573
     *
574
     * @param int     $size     Size
575
     * @param Closure $userFunc Callback Function
576
     *
577
     * @return void
578
     *
579
     * @throws DataException
580
     */
581
    abstract public function chunk(int $size, Closure $userFunc);
582

583
    /**
584
     * Fetches the row of database.
585
     *
586
     * @param array|int|string|null $id One primary key or an array of primary keys
587
     *
588
     * @return         array|object|null                                                    The resulting row of data, or null.
589
     * @phpstan-return ($id is int|string ? row_array|object|null : list<row_array|object>)
590
     */
591
    public function find($id = null)
592
    {
593
        $singleton = is_numeric($id) || is_string($id);
54✔
594

595
        if ($this->tempAllowCallbacks) {
54✔
596
            // Call the before event and check for a return
597
            $eventData = $this->trigger('beforeFind', [
51✔
598
                'id'        => $id,
51✔
599
                'method'    => 'find',
51✔
600
                'singleton' => $singleton,
51✔
601
            ]);
51✔
602

603
            if (isset($eventData['returnData']) && $eventData['returnData'] === true) {
51✔
604
                return $eventData['data'];
3✔
605
            }
606
        }
607

608
        $eventData = [
52✔
609
            'id'        => $id,
52✔
610
            'data'      => $this->doFind($singleton, $id),
52✔
611
            'method'    => 'find',
52✔
612
            'singleton' => $singleton,
52✔
613
        ];
52✔
614

615
        if ($this->tempAllowCallbacks) {
51✔
616
            $eventData = $this->trigger('afterFind', $eventData);
48✔
617
        }
618

619
        $this->tempReturnType     = $this->returnType;
51✔
620
        $this->tempUseSoftDeletes = $this->useSoftDeletes;
51✔
621
        $this->tempAllowCallbacks = $this->allowCallbacks;
51✔
622

623
        return $eventData['data'];
51✔
624
    }
625

626
    /**
627
     * Fetches the column of database.
628
     *
629
     * @param string $columnName Column Name
630
     *
631
     * @return array|null The resulting row of data, or null if no data found.
632
     *
633
     * @throws DataException
634
     */
635
    public function findColumn(string $columnName)
636
    {
637
        if (str_contains($columnName, ',')) {
3✔
638
            throw DataException::forFindColumnHaveMultipleColumns();
1✔
639
        }
640

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

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

646
    /**
647
     * Fetches all results, while optionally limiting them.
648
     *
649
     * @param int $limit  Limit
650
     * @param int $offset Offset
651
     *
652
     * @return array
653
     */
654
    public function findAll(?int $limit = null, int $offset = 0)
655
    {
656
        $limitZeroAsAll = config(Feature::class)->limitZeroAsAll ?? true;
21✔
657
        if ($limitZeroAsAll) {
21✔
658
            $limit ??= 0;
21✔
659
        }
660

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

670
            if (isset($eventData['returnData']) && $eventData['returnData'] === true) {
21✔
671
                return $eventData['data'];
1✔
672
            }
673
        }
674

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

683
        if ($this->tempAllowCallbacks) {
21✔
684
            $eventData = $this->trigger('afterFind', $eventData);
21✔
685
        }
686

687
        $this->tempReturnType     = $this->returnType;
21✔
688
        $this->tempUseSoftDeletes = $this->useSoftDeletes;
21✔
689
        $this->tempAllowCallbacks = $this->allowCallbacks;
21✔
690

691
        return $eventData['data'];
21✔
692
    }
693

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

708
            if (isset($eventData['returnData']) && $eventData['returnData'] === true) {
23✔
709
                return $eventData['data'];
1✔
710
            }
711
        }
712

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

719
        if ($this->tempAllowCallbacks) {
23✔
720
            $eventData = $this->trigger('afterFind', $eventData);
23✔
721
        }
722

723
        $this->tempReturnType     = $this->returnType;
23✔
724
        $this->tempUseSoftDeletes = $this->useSoftDeletes;
23✔
725
        $this->tempAllowCallbacks = $this->allowCallbacks;
23✔
726

727
        return $eventData['data'];
23✔
728
    }
729

730
    /**
731
     * A convenience method that will attempt to determine whether the
732
     * data should be inserted or updated. Will work with either
733
     * an array or object. 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         array|object     $row Row data
738
     * @phpstan-param row_array|object $row
739
     *
740
     * @throws ReflectionException
741
     */
742
    public function save($row): bool
743
    {
744
        if ((array) $row === []) {
27✔
745
            return true;
1✔
746
        }
747

748
        if ($this->shouldUpdate($row)) {
26✔
749
            $response = $this->update($this->getIdValue($row), $row);
16✔
750
        } else {
751
            $response = $this->insert($row, false);
13✔
752

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

758
        return $response;
25✔
759
    }
760

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

772
        return ! ($id === null || $id === [] || $id === '');
26✔
773
    }
774

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

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

802
        // Set $cleanValidationRules to false temporary.
803
        $cleanValidationRules       = $this->cleanValidationRules;
105✔
804
        $this->cleanValidationRules = false;
105✔
805

806
        $row = $this->transformDataToArray($row, 'insert');
105✔
807

808
        // Validate data before saving.
809
        if (! $this->skipValidation && ! $this->validate($row)) {
103✔
810
            // Restore $cleanValidationRules
811
            $this->cleanValidationRules = $cleanValidationRules;
19✔
812

813
            return false;
19✔
814
        }
815

816
        // Restore $cleanValidationRules
817
        $this->cleanValidationRules = $cleanValidationRules;
86✔
818

819
        // Must be called first, so we don't
820
        // strip out created_at values.
821
        $row = $this->doProtectFieldsForInsert($row);
86✔
822

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

829
        // Set created_at and updated_at with same time
830
        $date = $this->setDate();
83✔
831
        $row  = $this->setCreatedField($row, $date);
83✔
832
        $row  = $this->setUpdatedField($row, $date);
83✔
833

834
        $eventData = ['data' => $row];
83✔
835

836
        if ($this->tempAllowCallbacks) {
83✔
837
            $eventData = $this->trigger('beforeInsert', $eventData);
83✔
838
        }
839

840
        $result = $this->doInsert($eventData['data']);
82✔
841

842
        $eventData = [
81✔
843
            'id'     => $this->insertID,
81✔
844
            'data'   => $eventData['data'],
81✔
845
            'result' => $result,
81✔
846
        ];
81✔
847

848
        if ($this->tempAllowCallbacks) {
81✔
849
            // Trigger afterInsert events with the inserted data and new ID
850
            $this->trigger('afterInsert', $eventData);
81✔
851
        }
852

853
        $this->tempAllowCallbacks = $this->allowCallbacks;
81✔
854

855
        // If insertion failed, get out of here
856
        if (! $result) {
81✔
857
            return $result;
2✔
858
        }
859

860
        // otherwise return the insertID, if requested.
861
        return $returnID ? $this->insertID : $result;
79✔
862
    }
863

864
    /**
865
     * Set datetime to created field.
866
     *
867
     * @phpstan-param row_array  $row
868
     * @param         int|string $date timestamp or datetime string
869
     */
870
    protected function setCreatedField(array $row, $date): array
871
    {
872
        if ($this->useTimestamps && $this->createdField !== '' && ! array_key_exists($this->createdField, $row)) {
93✔
873
            $row[$this->createdField] = $date;
35✔
874
        }
875

876
        return $row;
93✔
877
    }
878

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

891
        return $row;
108✔
892
    }
893

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

913
        if (is_array($set)) {
13✔
914
            foreach ($set as &$row) {
13✔
915
                // If $row is using a custom class with public or protected
916
                // properties representing the collection elements, we need to grab
917
                // them as an array.
918
                if (is_object($row) && ! $row instanceof stdClass) {
13✔
919
                    $row = $this->objectToArray($row, false, true);
1✔
920
                }
921

922
                // If it's still a stdClass, go ahead and convert to
923
                // an array so doProtectFields and other model methods
924
                // don't have to do special checks.
925
                if (is_object($row)) {
13✔
926
                    $row = (array) $row;
×
927
                }
928

929
                // Validate every row.
930
                if (! $this->skipValidation && ! $this->validate($row)) {
13✔
931
                    // Restore $cleanValidationRules
932
                    $this->cleanValidationRules = $cleanValidationRules;
3✔
933

934
                    return false;
3✔
935
                }
936

937
                // Must be called first so we don't
938
                // strip out created_at values.
939
                $row = $this->doProtectFieldsForInsert($row);
10✔
940

941
                // Set created_at and updated_at with same time
942
                $date = $this->setDate();
10✔
943
                $row  = $this->setCreatedField($row, $date);
10✔
944
                $row  = $this->setUpdatedField($row, $date);
10✔
945
            }
946
        }
947

948
        // Restore $cleanValidationRules
949
        $this->cleanValidationRules = $cleanValidationRules;
10✔
950

951
        $eventData = ['data' => $set];
10✔
952

953
        if ($this->tempAllowCallbacks) {
10✔
954
            $eventData = $this->trigger('beforeInsertBatch', $eventData);
10✔
955
        }
956

957
        $result = $this->doInsertBatch($eventData['data'], $escape, $batchSize, $testing);
10✔
958

959
        $eventData = [
10✔
960
            'data'   => $eventData['data'],
10✔
961
            'result' => $result,
10✔
962
        ];
10✔
963

964
        if ($this->tempAllowCallbacks) {
10✔
965
            // Trigger afterInsert events with the inserted data and new ID
966
            $this->trigger('afterInsertBatch', $eventData);
10✔
967
        }
968

969
        $this->tempAllowCallbacks = $this->allowCallbacks;
10✔
970

971
        return $result;
10✔
972
    }
973

974
    /**
975
     * Updates a single record in the database. If an object is provided,
976
     * it will attempt to convert it into an array.
977
     *
978
     * @param         array|int|string|null $id
979
     * @param         array|object|null     $row Row data
980
     * @phpstan-param row_array|object|null $row
981
     *
982
     * @throws ReflectionException
983
     */
984
    public function update($id = null, $row = null): bool
985
    {
986
        if (is_bool($id)) {
45✔
987
            throw new InvalidArgumentException('update(): argument #1 ($id) should not be boolean.');
1✔
988
        }
989

990
        if (is_numeric($id) || is_string($id)) {
44✔
991
            $id = [$id];
37✔
992
        }
993

994
        $row = $this->transformDataToArray($row, 'update');
44✔
995

996
        // Validate data before saving.
997
        if (! $this->skipValidation && ! $this->validate($row)) {
42✔
998
            return false;
4✔
999
        }
1000

1001
        // Must be called first, so we don't
1002
        // strip out updated_at values.
1003
        $row = $this->doProtectFields($row);
38✔
1004

1005
        // doProtectFields() can further remove elements from
1006
        // $row, so we need to check for empty dataset again
1007
        if ($row === []) {
38✔
1008
            throw DataException::forEmptyDataset('update');
2✔
1009
        }
1010

1011
        $row = $this->setUpdatedField($row, $this->setDate());
36✔
1012

1013
        $eventData = [
36✔
1014
            'id'   => $id,
36✔
1015
            'data' => $row,
36✔
1016
        ];
36✔
1017

1018
        if ($this->tempAllowCallbacks) {
36✔
1019
            $eventData = $this->trigger('beforeUpdate', $eventData);
36✔
1020
        }
1021

1022
        $eventData = [
36✔
1023
            'id'     => $id,
36✔
1024
            'data'   => $eventData['data'],
36✔
1025
            'result' => $this->doUpdate($id, $eventData['data']),
36✔
1026
        ];
36✔
1027

1028
        if ($this->tempAllowCallbacks) {
35✔
1029
            $this->trigger('afterUpdate', $eventData);
35✔
1030
        }
1031

1032
        $this->tempAllowCallbacks = $this->allowCallbacks;
35✔
1033

1034
        return $eventData['result'];
35✔
1035
    }
1036

1037
    /**
1038
     * Compiles an update and runs the query.
1039
     *
1040
     * @param         list<array|object>|null     $set       an associative array of insert values
1041
     * @phpstan-param list<row_array|object>|null $set
1042
     * @param         string|null                 $index     The where key
1043
     * @param         int                         $batchSize The size of the batch to run
1044
     * @param         bool                        $returnSQL True means SQL is returned, false will execute the query
1045
     *
1046
     * @return false|int|list<string> Number of rows affected or FALSE on failure, SQL array when testMode
1047
     *
1048
     * @throws DatabaseException
1049
     * @throws ReflectionException
1050
     */
1051
    public function updateBatch(?array $set = null, ?string $index = null, int $batchSize = 100, bool $returnSQL = false)
1052
    {
1053
        if (is_array($set)) {
5✔
1054
            foreach ($set as &$row) {
5✔
1055
                // If $row is using a custom class with public or protected
1056
                // properties representing the collection elements, we need to grab
1057
                // them as an array.
1058
                if (is_object($row) && ! $row instanceof stdClass) {
5✔
1059
                    // For updates the index field is needed even if it is not changed.
1060
                    // So set $onlyChanged to false.
1061
                    $row = $this->objectToArray($row, false, true);
1✔
1062
                }
1063

1064
                // If it's still a stdClass, go ahead and convert to
1065
                // an array so doProtectFields and other model methods
1066
                // don't have to do special checks.
1067
                if (is_object($row)) {
5✔
1068
                    $row = (array) $row;
×
1069
                }
1070

1071
                // Validate data before saving.
1072
                if (! $this->skipValidation && ! $this->validate($row)) {
5✔
1073
                    return false;
1✔
1074
                }
1075

1076
                // Save updateIndex for later
1077
                $updateIndex = $row[$index] ?? null;
4✔
1078

1079
                if ($updateIndex === null) {
4✔
1080
                    throw new InvalidArgumentException(
1✔
1081
                        'The index ("' . $index . '") for updateBatch() is missing in the data: '
1✔
1082
                        . json_encode($row)
1✔
1083
                    );
1✔
1084
                }
1085

1086
                // Must be called first so we don't
1087
                // strip out updated_at values.
1088
                $row = $this->doProtectFields($row);
3✔
1089

1090
                // Restore updateIndex value in case it was wiped out
1091
                if ($updateIndex !== null) {
3✔
1092
                    $row[$index] = $updateIndex;
3✔
1093
                }
1094

1095
                $row = $this->setUpdatedField($row, $this->setDate());
3✔
1096
            }
1097
        }
1098

1099
        $eventData = ['data' => $set];
3✔
1100

1101
        if ($this->tempAllowCallbacks) {
3✔
1102
            $eventData = $this->trigger('beforeUpdateBatch', $eventData);
3✔
1103
        }
1104

1105
        $result = $this->doUpdateBatch($eventData['data'], $index, $batchSize, $returnSQL);
3✔
1106

1107
        $eventData = [
3✔
1108
            'data'   => $eventData['data'],
3✔
1109
            'result' => $result,
3✔
1110
        ];
3✔
1111

1112
        if ($this->tempAllowCallbacks) {
3✔
1113
            // Trigger afterInsert events with the inserted data and new ID
1114
            $this->trigger('afterUpdateBatch', $eventData);
3✔
1115
        }
1116

1117
        $this->tempAllowCallbacks = $this->allowCallbacks;
3✔
1118

1119
        return $result;
3✔
1120
    }
1121

1122
    /**
1123
     * Deletes a single record from the database where $id matches.
1124
     *
1125
     * @param array|int|string|null $id    The rows primary key(s)
1126
     * @param bool                  $purge Allows overriding the soft deletes setting.
1127
     *
1128
     * @return BaseResult|bool
1129
     *
1130
     * @throws DatabaseException
1131
     */
1132
    public function delete($id = null, bool $purge = false)
1133
    {
1134
        if (is_bool($id)) {
40✔
1135
            throw new InvalidArgumentException('delete(): argument #1 ($id) should not be boolean.');
×
1136
        }
1137

1138
        if ($id && (is_numeric($id) || is_string($id))) {
40✔
1139
            $id = [$id];
20✔
1140
        }
1141

1142
        $eventData = [
40✔
1143
            'id'    => $id,
40✔
1144
            'purge' => $purge,
40✔
1145
        ];
40✔
1146

1147
        if ($this->tempAllowCallbacks) {
40✔
1148
            $this->trigger('beforeDelete', $eventData);
39✔
1149
        }
1150

1151
        $eventData = [
40✔
1152
            'id'     => $id,
40✔
1153
            'data'   => null,
40✔
1154
            'purge'  => $purge,
40✔
1155
            'result' => $this->doDelete($id, $purge),
40✔
1156
        ];
40✔
1157

1158
        if ($this->tempAllowCallbacks) {
27✔
1159
            $this->trigger('afterDelete', $eventData);
26✔
1160
        }
1161

1162
        $this->tempAllowCallbacks = $this->allowCallbacks;
27✔
1163

1164
        return $eventData['result'];
27✔
1165
    }
1166

1167
    /**
1168
     * Permanently deletes all rows that have been marked as deleted
1169
     * through soft deletes (deleted = 1).
1170
     *
1171
     * @return bool|string Returns a string if in test mode.
1172
     */
1173
    public function purgeDeleted()
1174
    {
1175
        if (! $this->useSoftDeletes) {
2✔
1176
            return true;
1✔
1177
        }
1178

1179
        return $this->doPurgeDeleted();
1✔
1180
    }
1181

1182
    /**
1183
     * Sets $useSoftDeletes value so that we can temporarily override
1184
     * the soft deletes settings. Can be used for all find* methods.
1185
     *
1186
     * @param bool $val Value
1187
     *
1188
     * @return $this
1189
     */
1190
    public function withDeleted(bool $val = true)
1191
    {
1192
        $this->tempUseSoftDeletes = ! $val;
23✔
1193

1194
        return $this;
23✔
1195
    }
1196

1197
    /**
1198
     * Works with the find* methods to return only the rows that
1199
     * have been deleted.
1200
     *
1201
     * @return $this
1202
     */
1203
    public function onlyDeleted()
1204
    {
1205
        $this->tempUseSoftDeletes = false;
1✔
1206
        $this->doOnlyDeleted();
1✔
1207

1208
        return $this;
1✔
1209
    }
1210

1211
    /**
1212
     * Compiles a replace and runs the query.
1213
     *
1214
     * @param         array|null     $row       Row data
1215
     * @phpstan-param row_array|null $row
1216
     * @param         bool           $returnSQL Set to true to return Query String
1217
     *
1218
     * @return BaseResult|false|Query|string
1219
     */
1220
    public function replace(?array $row = null, bool $returnSQL = false)
1221
    {
1222
        // Validate data before saving.
1223
        if (($row !== null) && ! $this->skipValidation && ! $this->validate($row)) {
3✔
1224
            return false;
1✔
1225
        }
1226

1227
        $row = $this->setUpdatedField((array) $row, $this->setDate());
2✔
1228

1229
        return $this->doReplace($row, $returnSQL);
2✔
1230
    }
1231

1232
    /**
1233
     * Grabs the last error(s) that occurred. If data was validated,
1234
     * it will first check for errors there, otherwise will try to
1235
     * grab the last error from the Database connection.
1236
     *
1237
     * The return array should be in the following format:
1238
     *  ['source' => 'message']
1239
     *
1240
     * @param bool $forceDB Always grab the db error, not validation
1241
     *
1242
     * @return array<string,string>
1243
     */
1244
    public function errors(bool $forceDB = false)
1245
    {
1246
        if ($this->validation === null) {
24✔
NEW
1247
            return $this->doErrors();
×
1248
        }
1249

1250
        // Do we have validation errors?
1251
        if (! $forceDB && ! $this->skipValidation && ($errors = $this->validation->getErrors())) {
24✔
1252
            return $errors;
22✔
1253
        }
1254

1255
        return $this->doErrors();
2✔
1256
    }
1257

1258
    /**
1259
     * Works with Pager to get the size and offset parameters.
1260
     * Expects a GET variable (?page=2) that specifies the page of results
1261
     * to display.
1262
     *
1263
     * @param int|null $perPage Items per page
1264
     * @param string   $group   Will be used by the pagination library to identify a unique pagination set.
1265
     * @param int|null $page    Optional page number (useful when the page number is provided in different way)
1266
     * @param int      $segment Optional URI segment number (if page number is provided by URI segment)
1267
     *
1268
     * @return array|null
1269
     */
1270
    public function paginate(?int $perPage = null, string $group = 'default', ?int $page = null, int $segment = 0)
1271
    {
1272
        // Since multiple models may use the Pager, the Pager must be shared.
1273
        $pager = service('pager');
8✔
1274

1275
        if ($segment !== 0) {
8✔
1276
            $pager->setSegment($segment, $group);
×
1277
        }
1278

1279
        $page = $page >= 1 ? $page : $pager->getCurrentPage($group);
8✔
1280
        // Store it in the Pager library, so it can be paginated in the views.
1281
        $this->pager = $pager->store($group, $page, $perPage, $this->countAllResults(false), $segment);
8✔
1282
        $perPage     = $this->pager->getPerPage($group);
8✔
1283
        $offset      = ($pager->getCurrentPage($group) - 1) * $perPage;
8✔
1284

1285
        return $this->findAll($perPage, $offset);
8✔
1286
    }
1287

1288
    /**
1289
     * It could be used when you have to change default or override current allowed fields.
1290
     *
1291
     * @param array $allowedFields Array with names of fields
1292
     *
1293
     * @return $this
1294
     */
1295
    public function setAllowedFields(array $allowedFields)
1296
    {
1297
        $this->allowedFields = $allowedFields;
10✔
1298

1299
        return $this;
10✔
1300
    }
1301

1302
    /**
1303
     * Sets whether or not we should whitelist data set during
1304
     * updates or inserts against $this->availableFields.
1305
     *
1306
     * @param bool $protect Value
1307
     *
1308
     * @return $this
1309
     */
1310
    public function protect(bool $protect = true)
1311
    {
1312
        $this->protectFields = $protect;
12✔
1313

1314
        return $this;
12✔
1315
    }
1316

1317
    /**
1318
     * Ensures that only the fields that are allowed to be updated are
1319
     * in the data array.
1320
     *
1321
     * @used-by update() to protect against mass assignment vulnerabilities.
1322
     * @used-by updateBatch() to protect against mass assignment vulnerabilities.
1323
     *
1324
     * @param         array     $row Row data
1325
     * @phpstan-param row_array $row
1326
     *
1327
     * @throws DataException
1328
     */
1329
    protected function doProtectFields(array $row): array
1330
    {
1331
        if (! $this->protectFields) {
41✔
1332
            return $row;
2✔
1333
        }
1334

1335
        if ($this->allowedFields === []) {
39✔
1336
            throw DataException::forInvalidAllowedFields(static::class);
×
1337
        }
1338

1339
        foreach (array_keys($row) as $key) {
39✔
1340
            if (! in_array($key, $this->allowedFields, true)) {
39✔
1341
                unset($row[$key]);
21✔
1342
            }
1343
        }
1344

1345
        return $row;
39✔
1346
    }
1347

1348
    /**
1349
     * Ensures that only the fields that are allowed to be inserted are in
1350
     * the data array.
1351
     *
1352
     * @used-by insert() to protect against mass assignment vulnerabilities.
1353
     * @used-by insertBatch() to protect against mass assignment vulnerabilities.
1354
     *
1355
     * @param         array     $row Row data
1356
     * @phpstan-param row_array $row
1357
     *
1358
     * @throws DataException
1359
     */
1360
    protected function doProtectFieldsForInsert(array $row): array
1361
    {
1362
        return $this->doProtectFields($row);
×
1363
    }
1364

1365
    /**
1366
     * Sets the date or current date if null value is passed.
1367
     *
1368
     * @param int|null $userData An optional PHP timestamp to be converted.
1369
     *
1370
     * @return int|string
1371
     *
1372
     * @throws ModelException
1373
     */
1374
    protected function setDate(?int $userData = null)
1375
    {
1376
        $currentDate = $userData ?? Time::now()->getTimestamp();
127✔
1377

1378
        return $this->intToDate($currentDate);
127✔
1379
    }
1380

1381
    /**
1382
     * A utility function to allow child models to use the type of
1383
     * date/time format that they prefer. This is primarily used for
1384
     * setting created_at, updated_at and deleted_at values, but can be
1385
     * used by inheriting classes.
1386
     *
1387
     * The available time formats are:
1388
     *  - 'int'      - Stores the date as an integer timestamp
1389
     *  - 'datetime' - Stores the data in the SQL datetime format
1390
     *  - 'date'     - Stores the date (only) in the SQL date format.
1391
     *
1392
     * @param int $value value
1393
     *
1394
     * @return int|string
1395
     *
1396
     * @throws ModelException
1397
     */
1398
    protected function intToDate(int $value)
1399
    {
1400
        return match ($this->dateFormat) {
127✔
1401
            'int'      => $value,
127✔
1402
            'datetime' => date($this->db->dateFormat['datetime'], $value),
127✔
1403
            'date'     => date($this->db->dateFormat['date'], $value),
127✔
1404
            default    => throw ModelException::forNoDateFormat(static::class),
127✔
1405
        };
127✔
1406
    }
1407

1408
    /**
1409
     * Converts Time value to string using $this->dateFormat.
1410
     *
1411
     * The available time formats are:
1412
     *  - 'int'      - Stores the date as an integer timestamp
1413
     *  - 'datetime' - Stores the data in the SQL datetime format
1414
     *  - 'date'     - Stores the date (only) in the SQL date format.
1415
     *
1416
     * @param Time $value value
1417
     *
1418
     * @return int|string
1419
     */
1420
    protected function timeToDate(Time $value)
1421
    {
1422
        return match ($this->dateFormat) {
5✔
1423
            'datetime' => $value->format($this->db->dateFormat['datetime']),
5✔
1424
            'date'     => $value->format($this->db->dateFormat['date']),
5✔
1425
            'int'      => $value->getTimestamp(),
5✔
1426
            default    => (string) $value,
5✔
1427
        };
5✔
1428
    }
1429

1430
    /**
1431
     * Set the value of the skipValidation flag.
1432
     *
1433
     * @param bool $skip Value
1434
     *
1435
     * @return $this
1436
     */
1437
    public function skipValidation(bool $skip = true)
1438
    {
1439
        $this->skipValidation = $skip;
2✔
1440

1441
        return $this;
2✔
1442
    }
1443

1444
    /**
1445
     * Allows to set (and reset) validation messages.
1446
     * It could be used when you have to change default or override current validate messages.
1447
     *
1448
     * @param array $validationMessages Value
1449
     *
1450
     * @return $this
1451
     */
1452
    public function setValidationMessages(array $validationMessages)
1453
    {
1454
        $this->validationMessages = $validationMessages;
×
1455

1456
        return $this;
×
1457
    }
1458

1459
    /**
1460
     * Allows to set field wise validation message.
1461
     * It could be used when you have to change default or override current validate messages.
1462
     *
1463
     * @param string $field         Field Name
1464
     * @param array  $fieldMessages Validation messages
1465
     *
1466
     * @return $this
1467
     */
1468
    public function setValidationMessage(string $field, array $fieldMessages)
1469
    {
1470
        $this->validationMessages[$field] = $fieldMessages;
2✔
1471

1472
        return $this;
2✔
1473
    }
1474

1475
    /**
1476
     * Allows to set (and reset) validation rules.
1477
     * It could be used when you have to change default or override current validate rules.
1478
     *
1479
     * @param array<string, array<string, array<string, string>|string>|string> $validationRules Value
1480
     *
1481
     * @return $this
1482
     */
1483
    public function setValidationRules(array $validationRules)
1484
    {
1485
        $this->validationRules = $validationRules;
2✔
1486

1487
        return $this;
2✔
1488
    }
1489

1490
    /**
1491
     * Allows to set field wise validation rules.
1492
     * It could be used when you have to change default or override current validate rules.
1493
     *
1494
     * @param string       $field      Field Name
1495
     * @param array|string $fieldRules Validation rules
1496
     *
1497
     * @return $this
1498
     */
1499
    public function setValidationRule(string $field, $fieldRules)
1500
    {
1501
        $rules = $this->validationRules;
2✔
1502

1503
        // ValidationRules can be either a string, which is the group name,
1504
        // or an array of rules.
1505
        if (is_string($rules)) {
2✔
1506
            $this->ensureValidation();
1✔
1507

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

1510
            $this->validationRules = $rules;
1✔
1511
            $this->validationMessages += $customErrors;
1✔
1512
        }
1513

1514
        $this->validationRules[$field] = $fieldRules;
2✔
1515

1516
        return $this;
2✔
1517
    }
1518

1519
    /**
1520
     * Should validation rules be removed before saving?
1521
     * Most handy when doing updates.
1522
     *
1523
     * @param bool $choice Value
1524
     *
1525
     * @return $this
1526
     */
1527
    public function cleanRules(bool $choice = false)
1528
    {
1529
        $this->cleanValidationRules = $choice;
2✔
1530

1531
        return $this;
2✔
1532
    }
1533

1534
    /**
1535
     * Validate the row data against the validation rules (or the validation group)
1536
     * specified in the class property, $validationRules.
1537
     *
1538
     * @param         array|object     $row Row data
1539
     * @phpstan-param row_array|object $row
1540
     */
1541
    public function validate($row): bool
1542
    {
1543
        if ($this->skipValidation) {
145✔
NEW
1544
            return true;
×
1545
        }
1546

1547
        $rules = $this->getValidationRules();
145✔
1548

1549
        if ($rules === []) {
145✔
1550
            return true;
99✔
1551
        }
1552

1553
        // Validation requires array, so cast away.
1554
        if (is_object($row)) {
46✔
1555
            $row = (array) $row;
2✔
1556
        }
1557

1558
        if ($row === []) {
46✔
UNCOV
1559
            return true;
×
1560
        }
1561

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

1564
        // If no data existed that needs validation
1565
        // our job is done here.
1566
        if ($rules === []) {
46✔
1567
            return true;
2✔
1568
        }
1569

1570
        $this->ensureValidation();
44✔
1571

1572
        $this->validation->reset()->setRules($rules, $this->validationMessages);
44✔
1573

1574
        return $this->validation->run($row, null, $this->DBGroup);
44✔
1575
    }
1576

1577
    /**
1578
     * Returns the model's defined validation rules so that they
1579
     * can be used elsewhere, if needed.
1580
     *
1581
     * @param array $options Options
1582
     */
1583
    public function getValidationRules(array $options = []): array
1584
    {
1585
        $rules = $this->validationRules;
147✔
1586

1587
        // ValidationRules can be either a string, which is the group name,
1588
        // or an array of rules.
1589
        if (is_string($rules)) {
147✔
1590
            $this->ensureValidation();
13✔
1591

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

1594
            $this->validationMessages += $customErrors;
13✔
1595
        }
1596

1597
        if (isset($options['except'])) {
147✔
1598
            $rules = array_diff_key($rules, array_flip($options['except']));
×
1599
        } elseif (isset($options['only'])) {
147✔
1600
            $rules = array_intersect_key($rules, array_flip($options['only']));
×
1601
        }
1602

1603
        return $rules;
147✔
1604
    }
1605

1606
    protected function ensureValidation(): void
1607
    {
1608
        if ($this->validation === null) {
45✔
1609
            $this->validation = Services::validation(null, false);
29✔
1610
        }
1611
    }
1612

1613
    /**
1614
     * Returns the model's validation messages, so they
1615
     * can be used elsewhere, if needed.
1616
     */
1617
    public function getValidationMessages(): array
1618
    {
1619
        return $this->validationMessages;
2✔
1620
    }
1621

1622
    /**
1623
     * Removes any rules that apply to fields that have not been set
1624
     * currently so that rules don't block updating when only updating
1625
     * a partial row.
1626
     *
1627
     * @param         array     $rules Array containing field name and rule
1628
     * @param         array     $row   Row data (@TODO Remove null in param type)
1629
     * @phpstan-param row_array $row
1630
     */
1631
    protected function cleanValidationRules(array $rules, ?array $row = null): array
1632
    {
1633
        if ($row === null || $row === []) {
21✔
1634
            return [];
2✔
1635
        }
1636

1637
        foreach (array_keys($rules) as $field) {
19✔
1638
            if (! array_key_exists($field, $row)) {
19✔
1639
                unset($rules[$field]);
8✔
1640
            }
1641
        }
1642

1643
        return $rules;
19✔
1644
    }
1645

1646
    /**
1647
     * Sets $tempAllowCallbacks value so that we can temporarily override
1648
     * the setting. Resets after the next method that uses triggers.
1649
     *
1650
     * @param bool $val value
1651
     *
1652
     * @return $this
1653
     */
1654
    public function allowCallbacks(bool $val = true)
1655
    {
1656
        $this->tempAllowCallbacks = $val;
3✔
1657

1658
        return $this;
3✔
1659
    }
1660

1661
    /**
1662
     * A simple event trigger for Model Events that allows additional
1663
     * data manipulation within the model. Specifically intended for
1664
     * usage by child models this can be used to format data,
1665
     * save/load related classes, etc.
1666
     *
1667
     * It is the responsibility of the callback methods to return
1668
     * the data itself.
1669
     *
1670
     * Each $eventData array MUST have a 'data' key with the relevant
1671
     * data for callback methods (like an array of key/value pairs to insert
1672
     * or update, an array of results, etc.)
1673
     *
1674
     * If callbacks are not allowed then returns $eventData immediately.
1675
     *
1676
     * @param string $event     Event
1677
     * @param array  $eventData Event Data
1678
     *
1679
     * @return array
1680
     *
1681
     * @throws DataException
1682
     */
1683
    protected function trigger(string $event, array $eventData)
1684
    {
1685
        // Ensure it's a valid event
1686
        if (! isset($this->{$event}) || $this->{$event} === []) {
184✔
1687
            return $eventData;
169✔
1688
        }
1689

1690
        foreach ($this->{$event} as $callback) {
15✔
1691
            if (! method_exists($this, $callback)) {
15✔
1692
                throw DataException::forInvalidMethodTriggered($callback);
1✔
1693
            }
1694

1695
            $eventData = $this->{$callback}($eventData);
14✔
1696
        }
1697

1698
        return $eventData;
14✔
1699
    }
1700

1701
    /**
1702
     * Sets the return type of the results to be as an associative array.
1703
     *
1704
     * @return $this
1705
     */
1706
    public function asArray()
1707
    {
1708
        $this->tempReturnType = 'array';
26✔
1709

1710
        return $this;
26✔
1711
    }
1712

1713
    /**
1714
     * Sets the return type to be of the specified type of object.
1715
     * Defaults to a simple object, but can be any class that has
1716
     * class vars with the same name as the collection columns,
1717
     * or at least allows them to be created.
1718
     *
1719
     * @param 'object'|class-string $class Class Name
1720
     *
1721
     * @return $this
1722
     */
1723
    public function asObject(string $class = 'object')
1724
    {
1725
        $this->tempReturnType = $class;
16✔
1726

1727
        return $this;
16✔
1728
    }
1729

1730
    /**
1731
     * Takes a class and returns an array of its public and protected
1732
     * properties as an array suitable for use in creates and updates.
1733
     * This method uses objectToRawArray() internally and does conversion
1734
     * to string on all Time instances
1735
     *
1736
     * @param object $object      Object
1737
     * @param bool   $onlyChanged Only Changed Property
1738
     * @param bool   $recursive   If true, inner entities will be cast as array as well
1739
     *
1740
     * @return array<string, mixed>
1741
     *
1742
     * @throws ReflectionException
1743
     */
1744
    protected function objectToArray($object, bool $onlyChanged = true, bool $recursive = false): array
1745
    {
1746
        $properties = $this->objectToRawArray($object, $onlyChanged, $recursive);
22✔
1747

1748
        // Convert any Time instances to appropriate $dateFormat
1749
        return $this->timeToString($properties);
22✔
1750
    }
1751

1752
    /**
1753
     * Convert any Time instances to appropriate $dateFormat.
1754
     *
1755
     * @param array<string, mixed> $properties
1756
     *
1757
     * @return array<string, mixed>
1758
     */
1759
    protected function timeToString(array $properties): array
1760
    {
1761
        if ($properties === []) {
24✔
1762
            return [];
×
1763
        }
1764

1765
        return array_map(function ($value) {
24✔
1766
            if ($value instanceof Time) {
24✔
1767
                return $this->timeToDate($value);
5✔
1768
            }
1769

1770
            return $value;
24✔
1771
        }, $properties);
24✔
1772
    }
1773

1774
    /**
1775
     * Takes a class and returns an array of its public and protected
1776
     * properties as an array with raw values.
1777
     *
1778
     * @param object $object      Object
1779
     * @param bool   $onlyChanged Only Changed Property
1780
     * @param bool   $recursive   If true, inner entities will be casted as array as well
1781
     *
1782
     * @return array<string, mixed> Array with raw values.
1783
     *
1784
     * @throws ReflectionException
1785
     */
1786
    protected function objectToRawArray($object, bool $onlyChanged = true, bool $recursive = false): array
1787
    {
1788
        // Entity::toRawArray() returns array.
1789
        if (method_exists($object, 'toRawArray')) {
22✔
1790
            $properties = $object->toRawArray($onlyChanged, $recursive);
20✔
1791
        } else {
1792
            $mirror = new ReflectionClass($object);
2✔
1793
            $props  = $mirror->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);
2✔
1794

1795
            $properties = [];
2✔
1796

1797
            // Loop over each property,
1798
            // saving the name/value in a new array we can return.
1799
            foreach ($props as $prop) {
2✔
1800
                // Must make protected values accessible.
1801
                $prop->setAccessible(true);
2✔
1802
                $properties[$prop->getName()] = $prop->getValue($object);
2✔
1803
            }
1804
        }
1805

1806
        return $properties;
22✔
1807
    }
1808

1809
    /**
1810
     * Transform data to array.
1811
     *
1812
     * @param         array|object|null     $row  Row data
1813
     * @phpstan-param row_array|object|null $row
1814
     * @param         string                $type Type of data (insert|update)
1815
     *
1816
     * @throws DataException
1817
     * @throws InvalidArgumentException
1818
     * @throws ReflectionException
1819
     *
1820
     * @used-by insert()
1821
     * @used-by update()
1822
     */
1823
    protected function transformDataToArray($row, string $type): array
1824
    {
1825
        if (! in_array($type, ['insert', 'update'], true)) {
122✔
1826
            throw new InvalidArgumentException(sprintf('Invalid type "%s" used upon transforming data to array.', $type));
1✔
1827
        }
1828

1829
        if (! $this->allowEmptyInserts && ($row === null || (array) $row === [])) {
121✔
1830
            throw DataException::forEmptyDataset($type);
6✔
1831
        }
1832

1833
        // If it validates with entire rules, all fields are needed.
1834
        if ($this->skipValidation === false && $this->cleanValidationRules === false) {
118✔
1835
            $onlyChanged = false;
105✔
1836
        } else {
1837
            $onlyChanged = ($type === 'update' && $this->updateOnlyChanged);
41✔
1838
        }
1839

1840
        if ($this->useCasts()) {
118✔
1841
            if (is_array($row)) {
23✔
1842
                $row = $this->converter->toDataSource($row);
23✔
1843
            } elseif ($row instanceof stdClass) {
7✔
1844
                $row = (array) $row;
3✔
1845
                $row = $this->converter->toDataSource($row);
3✔
1846
            } elseif ($row instanceof Entity) {
4✔
1847
                $row = $this->converter->extract($row, $onlyChanged);
2✔
1848
                // Convert any Time instances to appropriate $dateFormat
1849
                $row = $this->timeToString($row);
2✔
1850
            } elseif (is_object($row)) {
2✔
1851
                $row = $this->converter->extract($row, $onlyChanged);
2✔
1852
            }
1853
        }
1854
        // If $row is using a custom class with public or protected
1855
        // properties representing the collection elements, we need to grab
1856
        // them as an array.
1857
        elseif (is_object($row) && ! $row instanceof stdClass) {
95✔
1858
            $row = $this->objectToArray($row, $onlyChanged, true);
19✔
1859
        }
1860

1861
        // If it's still a stdClass, go ahead and convert to
1862
        // an array so doProtectFields and other model methods
1863
        // don't have to do special checks.
1864
        if (is_object($row)) {
118✔
1865
            $row = (array) $row;
13✔
1866
        }
1867

1868
        // If it's still empty here, means $row is no change or is empty object
1869
        if (! $this->allowEmptyInserts && ($row === null || $row === [])) {
118✔
1870
            throw DataException::forEmptyDataset($type);
×
1871
        }
1872

1873
        return $row;
118✔
1874
    }
1875

1876
    /**
1877
     * Provides the db connection and model's properties.
1878
     *
1879
     * @param string $name Name
1880
     *
1881
     * @return array|bool|float|int|object|string|null
1882
     */
1883
    public function __get(string $name)
1884
    {
1885
        if (property_exists($this, $name)) {
48✔
1886
            return $this->{$name};
48✔
1887
        }
1888

1889
        return $this->db->{$name} ?? null;
1✔
1890
    }
1891

1892
    /**
1893
     * Checks for the existence of properties across this model, and db connection.
1894
     *
1895
     * @param string $name Name
1896
     */
1897
    public function __isset(string $name): bool
1898
    {
1899
        if (property_exists($this, $name)) {
48✔
1900
            return true;
48✔
1901
        }
1902

1903
        return isset($this->db->{$name});
1✔
1904
    }
1905

1906
    /**
1907
     * Provides direct access to method in the database connection.
1908
     *
1909
     * @param string $name   Name
1910
     * @param array  $params Params
1911
     *
1912
     * @return $this|null
1913
     */
1914
    public function __call(string $name, array $params)
1915
    {
1916
        if (method_exists($this->db, $name)) {
×
1917
            return $this->db->{$name}(...$params);
×
1918
        }
1919

1920
        return null;
×
1921
    }
1922

1923
    /**
1924
     * Sets $allowEmptyInserts.
1925
     */
1926
    public function allowEmptyInserts(bool $value = true): self
1927
    {
1928
        $this->allowEmptyInserts = $value;
1✔
1929

1930
        return $this;
1✔
1931
    }
1932

1933
    /**
1934
     * Converts database data array to return type value.
1935
     *
1936
     * @param array<string, mixed>          $row        Raw data from database
1937
     * @param 'array'|'object'|class-string $returnType
1938
     */
1939
    protected function convertToReturnType(array $row, string $returnType): array|object
1940
    {
1941
        if ($returnType === 'array') {
23✔
1942
            return $this->converter->fromDataSource($row);
10✔
1943
        }
1944

1945
        if ($returnType === 'object') {
15✔
1946
            return (object) $this->converter->fromDataSource($row);
5✔
1947
        }
1948

1949
        return $this->converter->reconstruct($returnType, $row);
10✔
1950
    }
1951
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc