-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathModel.php
More file actions
2080 lines (1907 loc) · 62.9 KB
/
Model.php
File metadata and controls
2080 lines (1907 loc) · 62.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
namespace Freshsauce\Model;
use Freshsauce\Model\Exception\ConfigurationException;
use Freshsauce\Model\Exception\ConnectionException;
use Freshsauce\Model\Exception\InvalidDynamicMethodException;
use Freshsauce\Model\Exception\MissingDataException;
use Freshsauce\Model\Exception\ModelException;
use Freshsauce\Model\Exception\UnknownFieldException;
/**
* Model ORM
*
*
* A simple database abstraction layer for PHP 8.3+ with very minor configuration required
*
* database table columns are auto detected and made available as public members of the class
* provides CRUD, dynamic counters/finders on a database table
* uses PDO for data access and exposes PDO if required
* class members used to do the magic are preceeded with an underscore, be careful of column names starting with _ in your database!
* requires php >=8.3
*
*
* @property string $created_at optional datatime in table that will automatically get updated on insert
* @property string $updated_at optional datatime in table that will automatically get updated on insert/update
*
* @package default
*/
/**
* Class Model
*
* @property string|null $created_at optional datetime in table that will automatically get updated on insert
* @property string|null $updated_at optional datetime in table that will automatically get updated on insert/update
*
* @package Freshsauce\Model
*
* @phpstan-consistent-constructor
*/
class Model
{
// Class configuration
/**
* @var \PDO|null
*/
public static $_db; // all models inherit this db connection
// but can overide in a sub-class by calling subClass::connectDB(...)
// sub class must also redeclare public static $_db;
/**
* @var array<int, array<string, \PDOStatement>>
*/
protected static $_stmt = array(); // prepared statements cache keyed by PDO connection and SQL
/**
* @var string|null
*/
protected static $_identifier_quote_character; // character used to quote table & columns names
/**
* @var array
*/
private static $_tableColumns = array(); // columns in database table populated dynamically
// objects public members are created for each table columns dynamically
/**
* @var \stdClass|null all data is stored here
*/
protected $data;
/**
* @var \stdClass|null whether a field value has changed (become dirty) is stored here
*/
protected $dirty;
/**
* @var string primary key column name, set as appropriate in your sub-class
*/
protected static $_primary_column_name = 'id'; // primary key column
/**
* @var string database table name, set as appropriate in your sub-class
*/
protected static $_tableName = '_the_db_table_name_'; // database table name
/**
* @var bool whether writes to unknown fields should throw immediately
*/
protected static bool $_strict_fields = false;
/**
* @var bool whether built-in automatic timestamp handling is enabled
*/
protected static bool $_auto_timestamps = true;
/**
* @var string|null column name to auto-populate on insert, or null to disable
*/
protected static ?string $_created_at_column = 'created_at';
/**
* @var string|null column name to auto-populate on insert/update, or null to disable
*/
protected static ?string $_updated_at_column = 'updated_at';
/**
* @var array<string, string> field cast map
*/
protected static array $_casts = [];
/**
* Model constructor.
*
* @param array $data
*/
public function __construct(array $data = [])
{
static::getFieldnames(); // only called once first time an object is created
$this->clearDirtyFields();
if (is_array($data)) {
$this->hydrate($data);
}
}
/**
* check if this object has data attached
*
* @return bool
*/
public function hasData(): bool
{
return is_object($this->data);
}
/**
* Returns true if data is present else throws MissingDataException
*
* @return bool
* @throws MissingDataException
*/
public function dataPresent()
{
if (!$this->hasData()) {
throw new MissingDataException('No data');
}
return true;
}
/**
* Set field in data object if doesnt match a native object member
* Initialise the data store if not an object
*
* @param string $name
* @param mixed $value
*
* @return void
*/
public function __set(string $name, mixed $value): void
{
$this->assignAttribute($name, $value);
}
/**
* Mark the field as dirty, so it will be set in inserts and updates
*
* @param string $name
*/
public function markFieldDirty(string $name): void
{
$this->dirty->$name = true; // field became dirty
}
/**
* Return true if filed is dirty else false
*
* @param string $name
*
* @return bool
*/
public function isFieldDirty(string $name): bool
{
return isset($this->dirty->$name) && ($this->dirty->$name == true);
}
/**
* resets what fields have been considered dirty ie. been changed without being saved to the db
*/
public function clearDirtyFields(): void
{
$this->dirty = new \stdClass();
}
/**
* Try and get the object member from the data object
* if it doesnt match a native object member
*
* @param string $name
*
* @return mixed
* @throws MissingDataException
* @throws UnknownFieldException
*/
public function __get(string $name): mixed
{
$data = $this->data;
if (!$data instanceof \stdClass) {
throw new MissingDataException("data property=$name has not been initialised", 1);
}
if (property_exists($data, $name)) {
return $data->$name;
}
$trace = debug_backtrace();
$file = $trace[0]['file'] ?? 'unknown';
$line = $trace[0]['line'] ?? 0;
throw new UnknownFieldException(
'Undefined property via __get(): ' . $name .
' in ' . $file .
' on line ' . $line,
1
);
}
/**
* Test the existence of the object member from the data object
* if it doesnt match a native object member
*
* @param string $name
*
* @return bool
*/
public function __isset(string $name): bool
{
$data = $this->data;
if ($data instanceof \stdClass && property_exists($data, $name)) {
return true;
}
return false;
}
/**
* set the db connection for this and all sub-classes to use
* if a sub class overrides $_db it can have it's own db connection if required
* params are as new PDO(...)
* set PDO to throw exceptions on error
*
* @param string $dsn
* @param string $username
* @param string $password
* @param array $driverOptions
*
* @throws \PDOException
* @throws ModelException
*/
public static function connectDb(string $dsn, string $username, string $password, array $driverOptions = array()): void
{
$previousDb = static::$_db;
if ($previousDb instanceof \PDO) {
unset(static::$_stmt[spl_object_id($previousDb)]);
}
static::$_db = new \PDO($dsn, $username, $password, $driverOptions);
static::$_db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception
static::$_identifier_quote_character = null;
self::$_tableColumns = array();
static::_setup_identifier_quote_character();
}
/**
* Detect and initialise the character used to quote identifiers
* (table names, column names etc).
*
* @return void
* @throws ModelException
*/
public static function _setup_identifier_quote_character(): void
{
if (is_null(static::$_identifier_quote_character)) {
static::$_identifier_quote_character = static::_detect_identifier_quote_character();
}
}
/**
* Return the correct character used to quote identifiers (table
* names, column names etc) by looking at the driver being used by PDO.
*
* @return string
* @throws ModelException
*/
protected static function _detect_identifier_quote_character(): string
{
switch (static::getDriverName()) {
case 'pgsql':
case 'sqlsrv':
case 'dblib':
case 'mssql':
case 'sybase':
return '"';
case 'mysql':
case 'sqlite':
case 'sqlite2':
default:
return '`';
}
}
/**
* return the driver name for the current database connection
*
* @return string
* @throws ConnectionException
* @throws ConfigurationException
*/
protected static function getDriverName(): string
{
$db = static::$_db;
if (!$db) {
throw new ConnectionException('No database connection setup');
}
$driver = $db->getAttribute(\PDO::ATTR_DRIVER_NAME);
if (!is_string($driver)) {
throw new ConfigurationException('Unable to determine database driver');
}
return $driver;
}
/**
* Public accessor for the current PDO driver name.
*
* @return string
* @throws ConnectionException
* @throws ConfigurationException
*/
public static function driverName(): string
{
return static::getDriverName();
}
/**
* Quote a string that is used as an identifier
* (table names, column names, etc). This method can
* also deal with dot-separated identifiers eg table.column
*
* @param string $identifier
*
* @return string
*/
protected static function _quote_identifier(string $identifier): string
{
$class = get_called_class();
$parts = explode('.', $identifier);
$parts = array_map(array(
$class,
'_quote_identifier_part'
), $parts);
return join('.', $parts);
}
/**
* This method performs the actual quoting of a single
* part of an identifier, using the identifier quote
* character specified in the config (or autodetect).
*
* @param string $part
*
* @return string
* @throws ModelException
*/
protected static function _quote_identifier_part(string $part): string
{
if ($part === '*') {
return $part;
}
static::_setup_identifier_quote_character();
$quote = static::$_identifier_quote_character;
if ($quote === null) {
throw new ConfigurationException('Identifier quote character not set');
}
$escaped = str_replace($quote, $quote . $quote, $part);
return $quote . $escaped . $quote;
}
/**
* Get and cache on the first call the column names associated with the current table
*
* @return array of column names for the current table
* @throws \PDOException
* @throws ModelException
*/
protected static function getFieldnames(): array
{
$class = get_called_class();
if (!isset(self::$_tableColumns[$class])) {
$driver = static::getDriverName();
if ($driver === 'pgsql') {
list($schema, $table) = static::splitTableName(static::$_tableName);
$st = static::execute(
'SELECT column_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ? ORDER BY ordinal_position',
array($schema, $table)
);
self::$_tableColumns[$class] = $st->fetchAll(\PDO::FETCH_COLUMN);
} elseif ($driver === 'sqlite' || $driver === 'sqlite2') {
$st = static::execute('PRAGMA table_info(' . static::_quote_identifier(static::$_tableName) . ')');
self::$_tableColumns[$class] = $st->fetchAll(\PDO::FETCH_COLUMN, 1);
} else {
$st = static::execute('DESCRIBE ' . static::_quote_identifier(static::$_tableName));
self::$_tableColumns[$class] = $st->fetchAll(\PDO::FETCH_COLUMN);
}
}
return self::$_tableColumns[$class];
}
/**
* Refresh cached table metadata for the current model class.
*
* @return void
*/
public static function refreshTableMetadata(): void
{
unset(self::$_tableColumns[static::class]);
}
/**
* Split a table name into schema and table, defaulting schema to public.
*
* @param string $tableName
*
* @return string[]
*/
protected static function splitTableName(string $tableName): array
{
$parts = explode('.', $tableName, 2);
if (count($parts) === 2) {
return $parts;
}
return array('public', $tableName);
}
/**
* Given an associative array of key value pairs
* set the corresponding member value if associated with a table column
* ignore keys which don't match a table column name
*
* @param array $data
*
* @return void
* @throws \PDOException
* @throws ModelException
*/
public function hydrate(array $data): void
{
foreach (static::getFieldnames() as $fieldname) {
if (array_key_exists($fieldname, $data)) {
$this->assignAttribute($fieldname, $data[$fieldname]);
} elseif (!isset($this->$fieldname)) { // PDO pre populates fields before calling the constructor, so dont null unless not set
$this->assignAttribute($fieldname, null);
}
}
}
/**
* set all members to null that are associated with table columns
*
* @return void
* @throws \PDOException
* @throws ModelException
*/
public function clear(): void
{
foreach (static::getFieldnames() as $fieldname) {
$this->$fieldname = null;
}
$this->clearDirtyFields();
}
/**
* @return array
*/
public function __sleep()
{
return array('data', 'dirty');
}
/**
* @return array{data: \stdClass, dirty: \stdClass}
*/
public function __serialize(): array
{
return array(
'data' => $this->normaliseSerializedState(isset($this->data) ? $this->data : null),
'dirty' => $this->normaliseSerializedState(isset($this->dirty) ? $this->dirty : null),
);
}
/**
* @param array{data?: mixed, dirty?: mixed} $data
*
* @return void
*/
public function __unserialize(array $data): void
{
$this->data = $this->normaliseSerializedState($data['data'] ?? null);
$this->dirty = $this->normaliseSerializedState($data['dirty'] ?? null);
}
/**
* @return array
* @throws \PDOException
* @throws ModelException
*/
public function toArray()
{
$a = array();
foreach (static::getFieldnames() as $fieldname) {
$a[$fieldname] = $this->$fieldname;
}
return $a;
}
/**
* Get the record with the matching primary key
*
* @param int|string $id
*
* @return static|null
*/
public static function getById(int|string $id): ?static
{
return static::fetchOneWhere(static::_quote_identifier(static::$_primary_column_name) . ' = ?', array($id));
}
/**
* Get the first record in the table
*
* @return static|null
*/
public static function first(): ?static
{
return static::fetchOneWhere('1=1 ORDER BY ' . static::_quote_identifier(static::$_primary_column_name) . ' ASC');
}
/**
* Get the last record in the table
*
* @return static|null
*/
public static function last(): ?static
{
return static::fetchOneWhere('1=1 ORDER BY ' . static::_quote_identifier(static::$_primary_column_name) . ' DESC');
}
/**
* Find records with the matching primary key
*
* @param int|string $id
*
* @return object[] of objects for matching records
*/
public static function find($id)
{
return static::fetchAllWhereMatchingSingleField(static::resolveFieldName(static::$_primary_column_name), $id);
}
/**
* handles calls to non-existent static methods, used to implement dynamic finder and counters ie.
* findByName('tom')
* findByTitle('a great book')
* countByName('tom')
* countByTitle('a great book')
* snake_case dynamic methods remain temporarily supported and trigger a deprecation warning.
*
* @param string $name
* @param array $arguments
*
* @return mixed int|object[]|object
* @throws InvalidDynamicMethodException
* @throws \PDOException
* @throws ModelException
*/
public static function __callStatic($name, $arguments)
{
$match = $arguments[0] ?? null;
$dynamicMethod = static::parseDynamicStaticMethod($name);
if (is_array($dynamicMethod)) {
if ($dynamicMethod['deprecated']) {
static::triggerSnakeCaseDynamicMethodDeprecation($name);
}
return static::dispatchDynamicStaticMethod($dynamicMethod['operation'], $dynamicMethod['fieldname'], $match);
}
throw new InvalidDynamicMethodException(__CLASS__ . ' not such static method[' . $name . ']');
}
/**
* Parse supported dynamic static finder/counter names.
*
* @param string $name
*
* @return array{operation: string, fieldname: string, deprecated: bool}|null
*/
protected static function parseDynamicStaticMethod(string $name): ?array
{
$camelCasePrefixes = array(
'findOneBy' => 'findOne',
'findBy' => 'findAll',
'firstBy' => 'first',
'lastBy' => 'last',
'countBy' => 'count',
);
foreach ($camelCasePrefixes as $prefix => $operation) {
if (str_starts_with($name, $prefix)) {
$fieldname = substr($name, strlen($prefix));
if ($fieldname === '') {
return null;
}
return array(
'operation' => $operation,
'fieldname' => $fieldname,
'deprecated' => false,
);
}
}
$snakeCasePrefixes = array(
'findOne_by_' => 'findOne',
'find_by_' => 'findAll',
'first_by_' => 'first',
'last_by_' => 'last',
'count_by_' => 'count',
);
foreach ($snakeCasePrefixes as $prefix => $operation) {
if (str_starts_with($name, $prefix)) {
$fieldname = substr($name, strlen($prefix));
if ($fieldname === '') {
return null;
}
return array(
'operation' => $operation,
'fieldname' => $fieldname,
'deprecated' => true,
);
}
}
return null;
}
/**
* Execute a parsed dynamic static method.
*
* @param string $operation
* @param string $fieldname
* @param mixed $match
*
* @return mixed
* @throws InvalidDynamicMethodException
* @throws \PDOException
* @throws ModelException
*/
protected static function dispatchDynamicStaticMethod(string $operation, string $fieldname, $match)
{
$resolvedFieldname = static::resolveFieldName($fieldname);
return match ($operation) {
'findAll' => static::fetchAllWhereMatchingSingleField($resolvedFieldname, $match),
'findOne' => static::fetchOneWhereMatchingSingleField($resolvedFieldname, $match, 'ASC'),
'first' => static::fetchOneWhereMatchingSingleField($resolvedFieldname, $match, 'ASC'),
'last' => static::fetchOneWhereMatchingSingleField($resolvedFieldname, $match, 'DESC'),
'count' => static::countByField($resolvedFieldname, $match),
default => throw new InvalidDynamicMethodException(static::class . ' not such static method operation[' . $operation . ']'),
};
}
/**
* Warn when a deprecated snake_case dynamic method is used.
*
* @param string $name
*
* @return void
*/
protected static function triggerSnakeCaseDynamicMethodDeprecation(string $name): void
{
$replacement = static::snakeCaseDynamicMethodToCamelCase($name);
$message = 'Dynamic snake_case model methods are deprecated. Use ' . $replacement . ' instead of ' . $name . '.';
trigger_error($message, E_USER_DEPRECATED);
}
/**
* Convert a snake_case dynamic method name to the camelCase replacement.
*
* @param string $name
*
* @return string
*/
protected static function snakeCaseDynamicMethodToCamelCase(string $name): string
{
$prefixMap = array(
'findOne_by_' => 'findOneBy',
'find_by_' => 'findBy',
'first_by_' => 'firstBy',
'last_by_' => 'lastBy',
'count_by_' => 'countBy',
);
foreach ($prefixMap as $prefix => $replacementPrefix) {
if (str_starts_with($name, $prefix)) {
$fieldname = substr($name, strlen($prefix));
return $replacementPrefix . static::snakeToStudly($fieldname);
}
}
return $name;
}
/**
* Resolve a dynamic field name from snake_case or CamelCase to an actual column name.
*
* @param string $fieldname
*
* @return string
* @throws UnknownFieldException
* @throws \PDOException
* @throws ModelException
*/
protected static function resolveFieldName(string $fieldname): string
{
$fieldnames = static::getFieldnames();
if (in_array($fieldname, $fieldnames, true)) {
return $fieldname;
}
foreach ($fieldnames as $field) {
if (strcasecmp($field, $fieldname) === 0) {
return $field;
}
}
$snake = static::camelToSnake($fieldname);
if (in_array($snake, $fieldnames, true)) {
return $snake;
}
foreach ($fieldnames as $field) {
if (strcasecmp($field, $snake) === 0) {
return $field;
}
}
throw new UnknownFieldException('Unknown field [' . $fieldname . '] for model ' . static::class);
}
/**
* Convert CamelCase or mixedCase to snake_case.
*
* @param string $fieldname
*
* @return string
*/
protected static function camelToSnake(string $fieldname): string
{
$snake = preg_replace('/(?<!^)[A-Z]/', '_$0', $fieldname);
return strtolower($snake ?? $fieldname);
}
/**
* Convert snake_case to StudlyCase for dynamic method generation.
*
* @param string $fieldname
*
* @return string
*/
protected static function snakeToStudly(string $fieldname): string
{
$parts = explode('_', $fieldname);
$parts = array_map(static fn ($part) => ucfirst(strtolower($part)), $parts);
return implode('', $parts);
}
/**
* Count records for a field with either a single value or an array of values.
*
* @param string $fieldname
* @param mixed $match
*
* @return int
*/
protected static function countByField(string $fieldname, mixed $match): int
{
if (static::isEmptyMatchList($match)) {
return 0;
}
if (is_array($match)) {
return static::countAllWhere(static::_quote_identifier($fieldname) . ' IN (' . static::createInClausePlaceholders($match) . ')', $match);
}
return static::countAllWhere(static::_quote_identifier($fieldname) . ' = ?', array($match));
}
/**
* find one match based on a single field and match criteria
*
* @param string $fieldname
* @param mixed $match
* @param string $order ASC|DESC
*
* @return static|null object of calling class
*/
public static function fetchOneWhereMatchingSingleField(string $fieldname, mixed $match, string $order): ?static
{
if (static::isEmptyMatchList($match)) {
return null;
}
if (is_array($match)) {
return static::fetchOneWhere(static::_quote_identifier($fieldname) . ' IN (' . static::createInClausePlaceholders($match) . ') ORDER BY ' . static::_quote_identifier($fieldname) . ' ' . $order, $match);
} else {
return static::fetchOneWhere(static::_quote_identifier($fieldname) . ' = ? ORDER BY ' . static::_quote_identifier($fieldname) . ' ' . $order, array($match));
}
}
/**
* find multiple matches based on a single field and match criteria
*
* @param string $fieldname
* @param mixed $match
*
* @return object[] of objects of calling class
*/
public static function fetchAllWhereMatchingSingleField(string $fieldname, mixed $match): array
{
if (static::isEmptyMatchList($match)) {
return array();
}
if (is_array($match)) {
return static::fetchAllWhere(static::_quote_identifier($fieldname) . ' IN (' . static::createInClausePlaceholders($match) . ')', $match);
} else {
return static::fetchAllWhere(static::_quote_identifier($fieldname) . ' = ?', array($match));
}
}
/**
* for a given array of params to be passed to an IN clause return a string placeholder
*
* @param array $params
*
* @return string
*/
public static function createInClausePlaceholders(array $params): string
{
if (count($params) === 0) {
return 'NULL';
}
return implode(',', array_fill(0, count($params), '?'));
}
/**
* returns number of rows in the table
*
* @return int
*/
public static function count(): int
{
$st = static::execute('SELECT COUNT(*) FROM ' . static::_quote_identifier(static::$_tableName));
return (int)$st->fetchColumn(0);
}
/**
* returns true when the table contains at least one row
*
* @return bool
*/
public static function exists(): bool
{
$st = static::execute(
'SELECT 1 FROM ' . static::_quote_identifier(static::$_tableName) . ' LIMIT 1'
);
return $st->fetchColumn(0) !== false;
}
/**
* returns an integer count of matching rows
*
* @param string $SQLfragment conditions, grouping to apply (to right of WHERE keyword)
* @param array $params optional params to be escaped and injected into the SQL query (standard PDO syntax)
*
* @return integer count of rows matching conditions
*/
public static function countAllWhere(string $SQLfragment = '', array $params = []): int
{
$SQLfragment = self::addWherePrefix($SQLfragment);
$st = static::execute('SELECT COUNT(*) FROM ' . static::_quote_identifier(static::$_tableName) . $SQLfragment, $params);
return (int)$st->fetchColumn(0);
}
/**
* returns true when at least one row matches the conditions
*
* @param string $SQLfragment
* @param array<int, mixed> $params
*
* @return bool
*/
public static function existsWhere(string $SQLfragment = '', array $params = []): bool
{
$SQLfragment = self::addWherePrefix($SQLfragment);
$sql = 'SELECT 1 FROM ' . static::_quote_identifier(static::$_tableName) . $SQLfragment . ' LIMIT 1';
$st = static::execute($sql, $params);
return $st->fetchColumn(0) !== false;
}
/**
* if $SQLfragment is not empty prefix with the WHERE keyword
*
* @param string $SQLfragment
*
* @return string
*/
protected static function addWherePrefix(string $SQLfragment): string
{
return $SQLfragment ? ' WHERE ' . $SQLfragment : $SQLfragment;
}
/**
* Build ORDER BY / LIMIT clauses for helper queries.
*
* @param string|null $orderByField
* @param string $direction
* @param int|null $limit
*
* @return string
* @throws ConfigurationException
* @throws UnknownFieldException
* @throws \PDOException
* @throws ModelException
*/
protected static function buildOrderAndLimitClause(?string $orderByField = null, string $direction = 'ASC', ?int $limit = null): string
{
$suffix = '';
if ($orderByField !== null) {
$suffix .= ' ORDER BY ' . static::_quote_identifier(static::resolveFieldName($orderByField)) . ' ' . static::normaliseOrderDirection($direction);
}
if ($limit !== null) {
if ($limit < 1) {
throw new ConfigurationException('Limit must be greater than zero.');
}
$suffix .= ' LIMIT ' . $limit;
}
return $suffix;
}
/**
* @param string $direction
*
* @return string
* @throws ConfigurationException
*/
protected static function normaliseOrderDirection(string $direction): string
{
$direction = strtoupper($direction);
if (!in_array($direction, ['ASC', 'DESC'], true)) {
throw new ConfigurationException('Unsupported order direction [' . $direction . ']. Use ASC or DESC.');
}
return $direction;
}
/**
* returns an array of objects of the sub-class which match the conditions
*
* @param string $SQLfragment conditions, sorting, grouping and limit to apply (to right of WHERE keywords)
* @param array $params optional params to be escaped and injected into the SQL query (standard PDO syntax)
* @param bool $limitOne if true the first match will be returned
*
* @return array|static|null object[]|object of objects of calling class
*/
protected static function fetchWhereWithSuffix(string $SQLfragment = '', array $params = [], bool $limitOne = false, string $suffix = ''): array|static|null
{
$SQLfragment = self::addWherePrefix($SQLfragment);
$st = static::execute(
'SELECT * FROM ' . static::_quote_identifier(static::$_tableName) . $SQLfragment . $suffix . ($limitOne ? ' LIMIT 1' : ''),
$params
);
$st->setFetchMode(\PDO::FETCH_ASSOC);
if ($limitOne) {
$row = $st->fetch();
if ($row === false) {
return null;
}
if (!is_array($row)) {
throw new ConfigurationException('Expected associative row data from PDO.');
}
return static::newInstanceFromDatabaseRow($row);
}
$results = [];