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

codeigniter4 / CodeIgniter4 / 8678307574

14 Apr 2024 04:14AM UTC coverage: 84.44%. Remained the same
8678307574

push

github

web-flow
Merge pull request #8783 from codeigniter4/develop

4.5.1 Ready code

24 of 32 new or added lines in 12 files covered. (75.0%)

164 existing lines in 12 files now uncovered.

20318 of 24062 relevant lines covered (84.44%)

188.23 hits per line

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

95.83
/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;
306✔
365
        $this->tempUseSoftDeletes = $this->useSoftDeletes;
306✔
366
        $this->tempAllowCallbacks = $this->allowCallbacks;
306✔
367

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

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

374
    /**
375
     * Creates DataConverter instance.
376
     */
377
    protected function createDataConverter(): void
378
    {
379
        if ($this->useCasts()) {
306✔
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 !== [];
306✔
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
    }
305✔
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
                // Convert any Time instances to appropriate $dateFormat
930
                $row = $this->timeToString($row);
13✔
931

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

937
                    return false;
3✔
938
                }
939

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

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

951
        // Restore $cleanValidationRules
952
        $this->cleanValidationRules = $cleanValidationRules;
10✔
953

954
        $eventData = ['data' => $set];
10✔
955

956
        if ($this->tempAllowCallbacks) {
10✔
957
            $eventData = $this->trigger('beforeInsertBatch', $eventData);
10✔
958
        }
959

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

962
        $eventData = [
10✔
963
            'data'   => $eventData['data'],
10✔
964
            'result' => $result,
10✔
965
        ];
10✔
966

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

972
        $this->tempAllowCallbacks = $this->allowCallbacks;
10✔
973

974
        return $result;
10✔
975
    }
976

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

993
        if (is_numeric($id) || is_string($id)) {
44✔
994
            $id = [$id];
37✔
995
        }
996

997
        $row = $this->transformDataToArray($row, 'update');
44✔
998

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

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

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

1014
        $row = $this->setUpdatedField($row, $this->setDate());
36✔
1015

1016
        $eventData = [
36✔
1017
            'id'   => $id,
36✔
1018
            'data' => $row,
36✔
1019
        ];
36✔
1020

1021
        if ($this->tempAllowCallbacks) {
36✔
1022
            $eventData = $this->trigger('beforeUpdate', $eventData);
36✔
1023
        }
1024

1025
        $eventData = [
36✔
1026
            'id'     => $id,
36✔
1027
            'data'   => $eventData['data'],
36✔
1028
            'result' => $this->doUpdate($id, $eventData['data']),
36✔
1029
        ];
36✔
1030

1031
        if ($this->tempAllowCallbacks) {
35✔
1032
            $this->trigger('afterUpdate', $eventData);
35✔
1033
        }
1034

1035
        $this->tempAllowCallbacks = $this->allowCallbacks;
35✔
1036

1037
        return $eventData['result'];
35✔
1038
    }
1039

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

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

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

1079
                // Save updateIndex for later
1080
                $updateIndex = $row[$index] ?? null;
4✔
1081

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

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

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

1098
                $row = $this->setUpdatedField($row, $this->setDate());
3✔
1099
            }
1100
        }
1101

1102
        $eventData = ['data' => $set];
3✔
1103

1104
        if ($this->tempAllowCallbacks) {
3✔
1105
            $eventData = $this->trigger('beforeUpdateBatch', $eventData);
3✔
1106
        }
1107

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

1110
        $eventData = [
3✔
1111
            'data'   => $eventData['data'],
3✔
1112
            'result' => $result,
3✔
1113
        ];
3✔
1114

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

1120
        $this->tempAllowCallbacks = $this->allowCallbacks;
3✔
1121

1122
        return $result;
3✔
1123
    }
1124

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

1141
        if ($id && (is_numeric($id) || is_string($id))) {
40✔
1142
            $id = [$id];
20✔
1143
        }
1144

1145
        $eventData = [
40✔
1146
            'id'    => $id,
40✔
1147
            'purge' => $purge,
40✔
1148
        ];
40✔
1149

1150
        if ($this->tempAllowCallbacks) {
40✔
1151
            $this->trigger('beforeDelete', $eventData);
39✔
1152
        }
1153

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

1161
        if ($this->tempAllowCallbacks) {
27✔
1162
            $this->trigger('afterDelete', $eventData);
26✔
1163
        }
1164

1165
        $this->tempAllowCallbacks = $this->allowCallbacks;
27✔
1166

1167
        return $eventData['result'];
27✔
1168
    }
1169

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

1182
        return $this->doPurgeDeleted();
1✔
1183
    }
1184

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

1197
        return $this;
23✔
1198
    }
1199

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

1211
        return $this;
1✔
1212
    }
1213

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

1230
        $row = $this->setUpdatedField((array) $row, $this->setDate());
2✔
1231

1232
        return $this->doReplace($row, $returnSQL);
2✔
1233
    }
1234

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

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

1258
        return $this->doErrors();
2✔
1259
    }
1260

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

1278
        if ($segment !== 0) {
8✔
UNCOV
1279
            $pager->setSegment($segment, $group);
×
1280
        }
1281

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

1288
        return $this->findAll($perPage, $offset);
8✔
1289
    }
1290

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

1302
        return $this;
10✔
1303
    }
1304

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

1317
        return $this;
12✔
1318
    }
1319

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

1338
        if ($this->allowedFields === []) {
39✔
UNCOV
1339
            throw DataException::forInvalidAllowedFields(static::class);
×
1340
        }
1341

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

1348
        return $row;
39✔
1349
    }
1350

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

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

1381
        return $this->intToDate($currentDate);
127✔
1382
    }
1383

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

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

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

1444
        return $this;
2✔
1445
    }
1446

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

UNCOV
1459
        return $this;
×
1460
    }
1461

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

1475
        return $this;
2✔
1476
    }
1477

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

1490
        return $this;
2✔
1491
    }
1492

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

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

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

1513
            $this->validationRules = $rules;
1✔
1514
            $this->validationMessages += $customErrors;
1✔
1515
        }
1516

1517
        $this->validationRules[$field] = $fieldRules;
2✔
1518

1519
        return $this;
2✔
1520
    }
1521

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

1534
        return $this;
2✔
1535
    }
1536

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

1550
        $rules = $this->getValidationRules();
145✔
1551

1552
        if ($rules === []) {
145✔
1553
            return true;
99✔
1554
        }
1555

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

1561
        if ($row === []) {
46✔
UNCOV
1562
            return true;
×
1563
        }
1564

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

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

1573
        $this->ensureValidation();
44✔
1574

1575
        $this->validation->reset()->setRules($rules, $this->validationMessages);
44✔
1576

1577
        return $this->validation->run($row, null, $this->DBGroup);
44✔
1578
    }
1579

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

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

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

1597
            $this->validationMessages += $customErrors;
13✔
1598
        }
1599

1600
        if (isset($options['except'])) {
147✔
UNCOV
1601
            $rules = array_diff_key($rules, array_flip($options['except']));
×
1602
        } elseif (isset($options['only'])) {
147✔
UNCOV
1603
            $rules = array_intersect_key($rules, array_flip($options['only']));
×
1604
        }
1605

1606
        return $rules;
147✔
1607
    }
1608

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

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

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

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

1646
        return $rules;
19✔
1647
    }
1648

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

1661
        return $this;
3✔
1662
    }
1663

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

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

1698
            $eventData = $this->{$callback}($eventData);
14✔
1699
        }
1700

1701
        return $eventData;
14✔
1702
    }
1703

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

1713
        return $this;
26✔
1714
    }
1715

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

1730
        return $this;
16✔
1731
    }
1732

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

1751
        // Convert any Time instances to appropriate $dateFormat
1752
        return $this->timeToString($properties);
22✔
1753
    }
1754

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

1768
        return array_map(function ($value) {
131✔
1769
            if ($value instanceof Time) {
131✔
1770
                return $this->timeToDate($value);
5✔
1771
            }
1772

1773
            return $value;
131✔
1774
        }, $properties);
131✔
1775
    }
1776

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

1798
            $properties = [];
2✔
1799

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

1809
        return $properties;
22✔
1810
    }
1811

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

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

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

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

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

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

1874
        // Convert any Time instances to appropriate $dateFormat
1875
        return $this->timeToString($row);
118✔
1876
    }
1877

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

1891
        return $this->db->{$name} ?? null;
1✔
1892
    }
1893

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

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

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

UNCOV
1922
        return null;
×
1923
    }
1924

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

1932
        return $this;
1✔
1933
    }
1934

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

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

1951
        return $this->converter->reconstruct($returnType, $row);
10✔
1952
    }
1953
}
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