Newer
Older
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
<?php
/**
* SimpleORMap.class.php
* simple object-relational mapping
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* @author André Noack <noack@data-quest.de>
* @copyright 2010 Stud.IP Core-Group
* @license http://www.gnu.org/licenses/gpl-2.0.html GPL version 2
* @category Stud.IP
*/
class SimpleORMap implements ArrayAccess, Countable, IteratorAggregate
{
const ID_SEPARATOR = '_';
/**
* table row data
* @var array $content
*/
protected $content = [];
/**
* table row data
* @var array $content_db
*/
protected $content_db = [];
/**
* new state of entry
* @var boolean $is_new
*/
protected $is_new = true;
/**
* deleted state of entry
* @var boolean $is_deleted
*/
protected $is_deleted = false;
/**
* name of db table
* @var string $db_table
*/
protected $db_table = '';
/**
* table columns
* @var array $db_fields
*/
protected $db_fields = null;
/**
* primary key columns
* @var array $pk
*/
protected $pk = null;
/**
* default values for columns
* @var array $default_values
*/
protected $default_values = [];
/**
* list of columns to deserialize
* @var array key is name of column, value is name of ArrayObject class
*/
protected $serialized_fields = [];
/**
* db table metadata
* @var array $schemes;
*/
public static $schemes = null;
/**
* configuration data for subclasses
* @see self::configure()
* @var array $config;
*/
protected static $config = [];
/**
* aliases for columns
* alias => column
* @var array $alias_fields
*/
protected $alias_fields = [];
/**
* multi-language fields
* name => boolean
* @var array $i18n_fields
*/
protected $i18n_fields = [];
/**
* additional computed fields
* name => callable
* @var array $additional_fields
*/
protected $additional_fields = [];
/**
* stores instantiated related objects
* @var array $relations
*/
protected $relations = [];
/**
* 1:n relation
* @var array $has_many
*/
protected $has_many = [];
/**
* 1:1 relation
* @var array $has_one
*/
protected $has_one = [];
/**
* n:1 relations
* @var array $belongs_to
*/
protected $belongs_to = [];
/**
* n:m relations
* @var array $has_and_belongs_to_many
*/
protected $has_and_belongs_to_many = [];
/**
* callbacks
* @var array $registered_callbacks
*/
protected $registered_callbacks = [];
/**
* contains an array of all used identifiers for fields
* (db columns + aliased columns + additional columns + relations)
* @var array $known_slots
*/
protected $known_slots = [];
/**
* reserved indentifiers, fields with those names must not have an explicit getXXX() method
* @var array $reserved_slots
*/
protected static $reserved_slots = ['value','newid','iterator','tablemetadata', 'relationvalue','wherequery','relationoptions','data','new','id'];
/**
* assoc array used to map SORM callback to NotificationCenter
* keys are SORM callbacks, values notifications
* eg. 'after_create' => 'FooDidCreate'
*
* @var array $notification_map
*/
protected $notification_map = [];
/**
* assoc array for storing values for additional fields
*
* @var array $additional_data
*/
protected $additional_data = [];
/**
* assoc array for mapping get/set Methods
*
* @var array $getter_setter_map
*/
protected $getter_setter_map = [];
/**
* indicator for batch operations in findEachBySQL
*
* @var bool $batch_operation
*/
protected static $performs_batch_operation = false;
/**
* set configuration data from subclass
*
* @param array $config configuration data
* @return void
*/
protected static function configure($config = [])
{
$class = get_called_class();
if (empty($config['db_table'])) {
$config['db_table'] = strtolower($class);
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
}
if (!isset($config['db_fields'])) {
if (static::tableScheme($config['db_table'])) {
$config['db_fields'] = self::$schemes[$config['db_table']]['db_fields'];
$config['pk'] = self::$schemes[$config['db_table']]['pk'];
}
}
if (isset($config['pk'])
&& !isset($config['db_fields']['id'])
&& !isset($config['alias_fields']['id'])
&& !isset($config['additional_fields']['id'])
) {
if (count($config['pk']) === 1) {
$config['alias_fields']['id'] = $config['pk'][0];
} else {
$config['additional_fields']['id'] = ['get' => '_getId',
'set' => '_setId'];
}
}
if (isset($config['additional_fields'])) {
foreach ($config['additional_fields'] as $a_field => $a_config) {
if (is_array($a_config) && !(isset($a_config['get']) || isset($a_config['set']))) {
list($relation, $relation_field) = $a_config;
if (!$relation) {
list($relation, $relation_field) = explode('_', $a_field);
}
if (!$relation_field || !$relation) {
throw new UnexpectedValueException('no relation found for autoget/set additional field: ' . $a_field);
}
$config['additional_fields'][$a_field] = ['get' => '_getAdditionalValueFromRelation',
'set' => '_setAdditionalValue',
'relation' => $relation,
'relation_field' => $relation_field];
}
}
}
if (isset($config['serialized_fields'])) {
foreach ($config['serialized_fields'] as $a_field => $object_type) {
if (!(is_subclass_of($object_type, 'StudipArrayObject'))) {
throw new UnexpectedValueException(sprintf('serialized field %s must use subclass of StudipArrayObject', $a_field));
}
}
}
foreach (['has_many', 'belongs_to', 'has_one', 'has_and_belongs_to_many'] as $type) {
if (is_array($config[$type])) {
foreach (array_keys($config[$type]) as $one) {
$config['relations'][$one] = null;
}
}
}
$callbacks = ['before_create',
'before_update',
'before_store',
'before_delete',
'before_initialize',
'after_create',
'after_update',
'after_store',
'after_delete',
'after_initialize'];
foreach ($callbacks as $callback) {
if (!isset($config['registered_callbacks'][$callback])) {
$config['registered_callbacks'][$callback] = [];
}
}
if ($config['db_fields'][$config['pk'][0]]['extra'] == 'auto_increment') {
array_unshift($config['registered_callbacks']['before_store'], 'cbAutoIncrementColumn');
array_unshift($config['registered_callbacks']['after_create'], 'cbAutoIncrementColumn');
} elseif (count($config['pk']) === 1) {
array_unshift($config['registered_callbacks']['before_store'], 'cbAutoKeyCreation');
}
$auto_notification_map['after_create'] = $class . 'DidCreate';
$auto_notification_map['after_store'] = $class . 'DidStore';
$auto_notification_map['after_delete'] = $class . 'DidDelete';
$auto_notification_map['after_update'] = $class . 'DidUpdate';
$auto_notification_map['before_create'] = $class . 'WillCreate';
$auto_notification_map['before_store'] = $class . 'WillStore';
$auto_notification_map['before_delete'] = $class . 'WillDelete';
$auto_notification_map['before_update'] = $class . 'WillUpdate';
foreach ($auto_notification_map as $cb => $notification) {
if (isset($config['notification_map'][$cb])) {
if (strpos($config['notification_map'][$cb], $notification) !== false) {
$config['notification_map'][$cb] .= ' ' . $notification;
}
} else {
$config['notification_map'][$cb] = $notification;
}
}
if (is_array($config['notification_map'])) {
foreach (array_keys($config['notification_map']) as $cb) {
$config['registered_callbacks'][$cb][] = 'cbNotificationMapper';
}
}
if (I18N::isEnabled()) {
if (isset($config['i18n_fields']) && count($config['i18n_fields']) > 0) {
Jan-Hendrik Willms
committed
if (count($config['pk']) > 1) {
throw new Exception('Can not define i18n fields on a composite primary key');
}
$config['registered_callbacks']['before_store'][] = 'cbI18N';
$config['registered_callbacks']['after_delete'][] = 'cbI18N';
}
} else {
$config['i18n_fields'] = [];
}
array_unshift($config['registered_callbacks']['after_initialize'], 'cbAfterInitialize');
$config['known_slots'] = array_merge(
array_keys($config['db_fields']),
array_keys($config['alias_fields'] ?: []),
array_keys($config['additional_fields'] ?: []),
array_keys($config['relations'] ?: [])
);
foreach (array_map('strtolower', get_class_methods($class)) as $method) {
if (in_array(substr($method, 0, 3), ['get', 'set'])) {
$verb = substr($method, 0, 3);
$name = substr($method, 3);
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
if (in_array($name, $config['known_slots']) && !in_array($name, static::$reserved_slots) && !isset($config['additional_fields'][$name][$verb])) {
$config['getter_setter_map'][$name][$verb] = $method;
}
}
}
self::$config[$class] = $config;
}
/**
* fetch config data for the called class
*
* @param string $key config key
* @return string value of config key (null if not set)
*/
protected static function config($key)
{
if (!array_key_exists(static::class, self::$config)) {
static::configure();
}
return self::$config[static::class][$key];
}
/**
* fetch table metadata from db or from local cache
*
* @param string $db_table
* @return bool true if metadata could be fetched
*/
public static function tableScheme($db_table)
{
if (self::$schemes === null) {
$cache = StudipCacheFactory::getCache();
self::$schemes = unserialize($cache->read('DB_TABLE_SCHEMES'));
}
if (!isset(self::$schemes[$db_table])) {
$db = DBManager::get()->query("SHOW COLUMNS FROM $db_table");
while($rs = $db->fetch(PDO::FETCH_ASSOC)){
$db_fields[strtolower($rs['Field'])] = [
'name' => $rs['Field'],
'null' => $rs['Null'],
'default' => $rs['Default'],
'type' => $rs['Type'],
'extra' => $rs['Extra']
];
$pk[] = strtolower($rs['Field']);
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
}
}
self::$schemes[$db_table]['db_fields'] = $db_fields;
self::$schemes[$db_table]['pk'] = $pk;
$cache = StudipCacheFactory::getCache();
$cache->write('DB_TABLE_SCHEMES', serialize(self::$schemes));
}
return isset(self::$schemes[$db_table]);
}
/**
* force reload of cached table metadata
*/
public static function expireTableScheme()
{
StudipCacheFactory::getCache()->expire('DB_TABLE_SCHEMES');
self::$schemes = null;
self::$config = [];
}
/**
* returns new instance for given key
* when found in db, else null
* @param string primary key
* @return SimpleORMap|NULL
*/
public static function find($id)
{
$class = get_called_class();
$ref = new ReflectionClass($class);
$record = $ref->newInstanceArgs(func_get_args());
if (!$record->isNew()) {
return $record;
} else {
return null;
}
}
/**
* returns true if given key
* exists in db
* @param string primary key
* @return boolean
*/
public static function exists($id)
{
$ret = false;
$db_table = static::config('db_table');
$class = get_called_class();
$record = new $class();
call_user_func_array([$record, 'setId'], func_get_args());
$where_query = $record->getWhereQuery();
if ($where_query) {
$query = "SELECT 1 FROM `$db_table` WHERE "
. join(" AND ", $where_query);
$ret = (bool)DBManager::get()->query($query)->fetchColumn();
}
return $ret;
}
/**
* returns number of records
*
* @param string sql clause to use on the right side of WHERE
* @param array params for query
* @return number
*/
public static function countBySql($sql = 1, $params = [])
{
$db_table = static::config('db_table');
$db = DBManager::get();
$has_join = stripos($sql, 'JOIN ');
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
if ($has_join === false || $has_join > 10) {
$sql = 'WHERE ' . $sql;
}
$sql = "SELECT count(*) FROM `" . $db_table . "` " . $sql;
$st = $db->prepare($sql);
$st->execute($params);
return (int)$st->fetchColumn();
}
/**
* creates new record with given data in db
* returns the new object or null
* @param array $data assoc array of record
* @return SimpleORMap
*/
public static function create($data)
{
$record = new static();
$record->setData($data, false);
if ($record->store()) {
return $record;
} else {
return null;
}
}
/**
* build object with given data
*
* @param array $data assoc array of record
* @param bool $is_new set object to new state
* @return static
*/
public static function build($data, $is_new = true)
{
$class = get_called_class();
$record = new $class();
$record->setData($data, !$is_new);
$record->setNew($is_new);
return $record;
}
/**
* build object with given data and mark it as existing
*
* @param $data array assoc array of record
* @return static
*/
public static function buildExisting($data)
{
return static::build($data, false);
}
/**
* generate SimpleORMap object structure from assoc array
* if given array contains data of related objects in sub-arrays
* they are also generated. Existing records are updated, new records are created
* (but changes are not yet stored)
*
* @param array $data
* @return static
*/
public static function import($data)
{
$class = get_called_class();
$record_data = [];
$relation_data = [];
foreach ($data as $key => $value) {
if (is_array($value)) {
$relation_data[$key] = $value;
} else {
$record_data[$key] = $value;
}
}
$record = static::toObject($record_data);
if (!$record instanceof $class) {
$record = new $class();
$record->setData($record_data, true);
} else {
$record->setData($record_data);
}
if (is_array($relation_data)) {
foreach ($relation_data as $relation => $data) {
$options = $record->getRelationOptions($relation);
if ($options['type'] == 'has_one') {
$record->{$relation} = call_user_func([$options['class_name'], 'import'], $data);
}
if ($options['type'] == 'has_many' || $options['type'] == 'has_and_belongs_to_many') {
foreach ($data as $one) {
$current = call_user_func([$options['class_name'], 'import'], $one);
if ($options['type'] == 'has_many') {
$foreign_key_value = call_user_func($options['assoc_func_params_func'], $record);
call_user_func($options['assoc_foreign_key_setter'], $current, $foreign_key_value);
}
if ($current->id !== null) {
$existing = $record->{$relation}->find($current->id);
if ($existing) {
$existing->setData($current);
} else {
$record->{$relation}->append($current);
}
} else {
$record->{$relation}->append($current);
}
}
}
}
}
return $record;
}
/**
* returns array of instances of given class filtered by given sql
* @param string sql clause to use on the right side of WHERE
* @param array parameters for query
* @return array array of "self" objects
*/
public static function findBySQL($sql, $params = [])
{
$db_table = static::config('db_table');
$class = get_called_class();
$record = new $class();
$db = DBManager::get();
$has_join = stripos($sql, 'JOIN ');
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
if ($has_join === false || $has_join > 10) {
$sql = 'WHERE ' . $sql;
}
$sql = "SELECT `" . $db_table . "`.* FROM `" . $db_table . "` " . $sql;
$ret = [];
$stmt = DBManager::get()->prepare($sql);
$stmt->execute($params);
$stmt->setFetchMode(PDO::FETCH_INTO , $record);
$record->setNew(false);
while ($record = $stmt->fetch()) {
// Reset all relations
$record->cleanup();
$record->applyCallbacks('after_initialize');
$ret[] = clone $record;
}
return $ret;
}
/**
* returns one instance of given class filtered by given sql
* only first row of query is used
* @param string sql clause to use on the right side of WHERE
* @param array parameters for query
* @return SimpleORMap|NULL
*/
public static function findOneBySQL($where, $params = [])
{
if (stripos($where, 'LIMIT') === false) {
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
$where .= " LIMIT 1";
}
$found = static::findBySQL($where, $params);
return isset($found[0]) ? $found[0] : null;
}
/**
* find related records for a n:m relation (has_many_and_belongs_to_many)
* using a combination table holding the keys
*
* @param string value of foreign key to find related records
* @param array relation options from other side of relation
* @return array of "self" objects
*/
public static function findThru($foreign_key_value, $options)
{
$thru_table = $options['thru_table'];
$thru_key = $options['thru_key'];
$thru_assoc_key = $options['thru_assoc_key'];
$assoc_foreign_key = $options['assoc_foreign_key'];
$db_table = static::config('db_table');
$class = get_called_class();
$record = new $class();
$sql = "SELECT `$db_table`.* FROM `$thru_table`
INNER JOIN `$db_table` ON `$thru_table`.`$thru_assoc_key` = `$db_table`.`$assoc_foreign_key`
WHERE `$thru_table`.`$thru_key` = ? " . $options['order_by'];
$db = DBManager::get();
$st = $db->prepare($sql);
$st->execute([$foreign_key_value]);
$ret = [];
$st->setFetchMode(PDO::FETCH_INTO , $record);
$record->setNew(false);
while ($record = $st->fetch()) {
// Reset all relations
$record->cleanup();
$record->applyCallbacks('after_initialize');
$ret[] = clone $record;
}
return $ret;
}
/**
* passes objects for given sql through given callback
*
* @param callable $callable callback which gets the current record as param
* @param string where clause of sql
* @param array sql statement parameters
* @return integer number of found records
*/
public static function findEachBySQL($callable, $sql, $params = [])
{
$has_join = stripos($sql, 'JOIN ');
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
if ($has_join === false || $has_join > 10) {
$sql = "WHERE {$sql}";
}
$record = new static();
$record->setNew(false);
$db_table = static::config('db_table');
$st = DBManager::get()->prepare("SELECT `{$db_table}`.* FROM `{$db_table}` {$sql}");
$st->execute($params);
$st->setFetchMode(PDO::FETCH_INTO , $record);
// Indicate that we are performing a batch operation
static::$performs_batch_operation = true;
$ret = 0;
while ($record = $st->fetch()) {
// Reset all relations
$record->cleanup();
$record->applyCallbacks('after_initialize');
// Execute callable on current record
$callable(clone $record, $ret++);
}
// Reset batch operation indicator
static::$performs_batch_operation = false;
return $ret;
}
/**
* returns array of instances of given class for by given pks
* @param array array og primary keys
* @param string order by clause
* @return array
*/
public static function findMany($pks = [], $order = '', $order_params = [])
{
$db_table = static::config('db_table');
$pk = static::config('pk');
$db = DBManager::get();
if (count($pk) > 1) {
throw new Exception('not implemented yet');
}
$where = "`$db_table`.`{$pk[0]}` IN (" . $db->quote($pks) . ") ";
return static::findBySQL($where . $order, $order_params);
}
/**
* passes objects for by given pks through given callback
*
* @param callable $callable callback which gets the current record as param
* @param array $pks array of primary keys of called class
* @param string $order order by sql
* @return integer number of found records
*/
public static function findEachMany($callable, $pks = [], $order = '', $order_params = [])
{
$db_table = static::config('db_table');
$pk = static::config('pk');
$db = DBManager::get();
if (count($pk) > 1) {
throw new Exception('not implemented yet');
}
$where = "`$db_table`.`{$pk[0]}` IN (" . $db->quote($pks) . ") ";
return static::findEachBySQL($callable, $where . $order, $order_params);
}
/**
* passes objects for given sql through given callback
* and returns an array of callback return values
*
* @param callable $callable callback which gets the current record as param
* @param string where clause of sql
* @param array sql statement parameters
* @return array return values of callback
*/
public static function findAndMapBySQL($callable, $where, $params = [])
{
$ret = [];
$calleach = function($m) use (&$ret, $callable) {
$ret[] = $callable($m);
};
static::findEachBySQL($calleach, $where, $params);
return $ret;
}
/**
* passes objects for by given pks through given callback
* and returns an array of callback return values
*
* @param callable $callable callback which gets the current record as param
* @param array $pks array of primary keys of called class
* @param string $order order by sql
* @return array return values of callback
*/
public static function findAndMapMany($callable, $pks = [], $order = '', $order_params = [])
{
$ret = [];
$calleach = function($m) use (&$ret, $callable) {
$ret[] = $callable($m);
};
$db_table = static::config('db_table');
$pk = static::config('pk');
$db = DBManager::get();
if (count($pk) > 1) {
throw new Exception('not implemented yet');
}
$where = "`$db_table`.`{$pk[0]}` IN (" . $db->quote($pks) . ") ";
static::findEachBySQL($calleach, $where . $order, $order_params);
return $ret;
}
/**
* deletes objects specified by sql clause
* @param string $where sql clause to use on the right side of WHERE
* @param array $params parameters for query
* @return number
*/
public static function deleteBySQL($where, $params = [])
{
$killeach = function($record) {$record->delete();};
return static::findEachBySQL($killeach, $where, $params);
}
/**
* returns object of given class for given id or null
* the param could be a string, an assoc array containing primary key field
* or an already matching object. In all these cases an object is returned
*
* @param mixed $id_or_object id as string, object or assoc array
* @return static
*/
public static function toObject($id_or_object)
{
$class = get_called_class();
if ($id_or_object instanceof $class) {
return $id_or_object;
}
if (is_array($id_or_object)) {
$pk = static::config('pk');
$key_values = [];
foreach($pk as $key) {
if (array_key_exists($key, $id_or_object)) {
$key_values[] = $id_or_object[$key];
}
}
if (count($pk) === count($key_values)) {
if (count($pk) === 1) {
$id = $key_values[0];
} else {
$id = $key_values;
}
}
} else {
$id = $id_or_object;
}
return call_user_func([$class, 'find'], $id);
}
/**
* interceptor for static findByColumn / findEachByColumn / countByColumn /
* deleteByColumn magic
* @param string $name
* @param array $arguments
* @throws BadMethodCallException
* @return mixed
*/
public static function __callStatic($name, $arguments)
{
$db_table = static::config('db_table');
$alias_fields = static::config('alias_fields');
$db_fields = static::config('db_fields');
$name = strtolower($name);
$class = get_called_class();
$param_arr = [];
$where = '';
$where_param = is_array($arguments[0]) ? $arguments[0] : [$arguments[0]];
$prefix = strstr($name, 'by', true);
$field = substr($name, strlen($prefix) + 2);
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
switch ($prefix) {
case 'findone':
$order = $arguments[1];
$param_arr[0] =& $where;
$param_arr[1] = [$where_param];
$method = 'findonebysql';
break;
case 'find':
case 'findmany':
$order = $arguments[1];
$param_arr[0] =& $where;
$param_arr[1] = [$where_param];
$method = 'findbysql';
break;
case 'findeach':
case 'findeachmany':
$order = $arguments[2];
$param_arr[0] = $arguments[0];
$param_arr[1] =& $where;
$param_arr[2] = [$arguments[1]];
$method = 'findeachbysql';
break;
case 'count':
case 'delete':
$param_arr[0] =& $where;
$param_arr[1] = [$where_param];
$method = "{$prefix}bysql";
break;
default:
throw new BadMethodCallException("Method $class::$name not found");
}
if (isset($alias_fields[$field])) {
$field = $alias_fields[$field];
}
if (isset($db_fields[$field])) {
$where = "`$db_table`.`$field` IN(?) " . $order;
return call_user_func_array([$class, $method], $param_arr);
}
throw new BadMethodCallException("Method $class::$name not found");
}
/**
* constructor, give primary key of record as param to fetch
* corresponding record from db if available, if not preset primary key
* with given value. Give null to create new record
*
* @param mixed $id primary key of table
*/
function __construct($id = null)
{
$class = get_class($this);
//initialize configuration for subclass, only one time
if (!array_key_exists($class, self::$config)) {
static::configure();
}
//if configuration data for subclass is found, point internal properties to it
if (self::$config[$class] !== null) {
foreach (array_keys(self::$config[$class]) as $config_key) {
$this->{$config_key} = self::$config[$class][$config_key];
}
}
if ($id) {
$this->setId($id);
}
$this->restore();
}
/**
* returns internal used id value (multiple keys concatenated with _)
*
*/
protected function _getId($field)
{
return is_null($this->getId())
? null
: implode(self::ID_SEPARATOR, $this->getId());
}
/**
* sets internal used id value (multiple keys concatenated with _)
* @param string $field Field to set (unused since it's always the id)
* @param string $value Value for id field
*/
protected function _setId($field, $value)
{
return $this->setId(explode(self::ID_SEPARATOR, $value));
}
/**
* retrieves an additional field value from relation
*
* @param string $field
* @return multitype:
*/
protected function _getAdditionalValueFromRelation($field)
{
list($relation, $relation_field) = [$this->additional_fields[$field]['relation'],
$this->additional_fields[$field]['relation_field']];
if (!array_key_exists($field, $this->additional_data)) {
$this->_setAdditionalValue($field, $this->getRelationValue($relation, $relation_field));
}
return $this->additional_data[$field];
}
/**
* sets additional value in field imported from relation
*
* @param string $field
* @param mixed $value
* @return multitype:
*/
protected function _setAdditionalValueFromRelation($field, $value)
{
list($relation, $relation_field) = [$this->additional_fields[$field]['relation'],
$this->additional_fields[$field]['relation_field']];
$this->$relation->$field = $value;
unset($this->additional_data[$field]);
return $this->_getAdditionalValueFromRelation($field);
}
/**
* @param string $field
* @return multitype:
*/
protected function _getAdditionalValue($field)
{
return $this->additional_data[$field];
}
/**
* @param string $field
* @param mixed $value
* @return multitype:
*/
protected function _setAdditionalValue($field, $value)
{
return $this->additional_data[$field] = $value;
}
/**
* clean up references after cloning
*
*/
function __clone()
{
//all references link still to old object => reset all aliases
foreach ($this->alias_fields as $alias => $field) {
if (isset($this->db_fields[$field])) {
$content_value = $this->content[$field];
$content_db_value = $this->content_db[$field];
unset($this->content[$alias]);
unset($this->content_db[$alias]);
unset($this->content[$field]);
unset($this->content_db[$field]);
if (is_object($content_value)) {
$this->content[$field] = clone $content_value;
} else {
$this->content[$field] = $content_value;
}
if (is_object($content_db_value)) {
$this->content_db[$field] = clone $content_db_value;
} else {
$this->content_db[$field] = $content_db_value;
}
$this->content[$alias] =& $this->content[$field];
$this->content_db[$alias] =& $this->content_db[$field];
}
}
//unset all relations for now
//TODO: maybe a deep copy of all belonging objects is more appropriate