/
model.php
2408 lines (2148 loc) · 54.5 KB
/
model.php
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
/**
* Fuel
*
* Fuel is a fast, lightweight, community driven PHP5 framework.
*
* @package Fuel
* @version 1.8
* @author Fuel Development Team
* @license MIT License
* @copyright 2010 - 2016 Fuel Development Team
* @link http://fuelphp.com
*/
namespace Orm;
/**
* Record Not Found Exception
*/
class RecordNotFound extends \OutOfBoundsException {}
/**
* Frozen Object Exception
*/
class FrozenObject extends \RuntimeException {}
class Model implements \ArrayAccess, \Iterator, \Sanitization
{
/* ---------------------------------------------------------------------------
* Static usage
* --------------------------------------------------------------------------- */
/**
* @var string connection to use
*/
// protected static $_connection = null;
/**
* @var string write connection to use
*/
// protected static $_write_connection = null;
/**
* @var string table name to overwrite assumption
*/
// protected static $_table_name;
/**
* @var array array of object properties
*/
// protected static $_properties;
/**
* @var array array of views with additional properties
*/
// protected static $_views;
/**
* @var array array of observer classes to use
*/
// protected static $_observers;
/**
* @var array relationship properties
*/
// protected static $_has_one;
// protected static $_belongs_to;
// protected static $_has_many;
// protected static $_many_many;
// protected static $_eav;
/**
* @var array name or names of the primary keys
*/
protected static $_primary_key = array('id');
/**
* @var array name or columns that need to be excluded from any to_array() result
*/
protected static $_to_array_exclude = array();
/**
* @var array cached tables
*/
protected static $_table_names_cached = array();
/**
* @var array cached properties
*/
protected static $_properties_cached = array();
/**
* @var array cached properties
*/
protected static $_views_cached = array();
/**
* @var string relationships
*/
protected static $_relations_cached = array();
/**
* @var array cached observers
*/
protected static $_observers_cached = array();
/**
* @var array array of fetched objects
*/
protected static $_cached_objects = array();
/**
* @var string Name of DB connection to use
*/
protected static $_connection = null;
/**
* @var string Name of the DB connection to use when writing
*/
protected static $_write_connection = null;
/**
* @var array array of valid relation types
*/
protected static $_valid_relations = array(
'belongs_to' => 'Orm\\BelongsTo',
'has_one' => 'Orm\\HasOne',
'has_many' => 'Orm\\HasMany',
'many_many' => 'Orm\\ManyMany',
);
/**
* @var array global array to track circular references in to_array()
*/
protected static $to_array_references = array();
/**
* Create a new model instance
*/
public static function forge($data = array(), $new = true, $view = null, $cache = true)
{
return new static($data, $new, $view, $cache);
}
/**
* Fetch the database connection name to use
*
* @param bool if true return the writeable connection (if set)
* @return null|string
*/
public static function connection($writeable = false)
{
$class = get_called_class();
if ($writeable and property_exists($class, '_write_connection') && static::$_write_connection !== null)
{
return static::$_write_connection;
}
return property_exists($class, '_connection') ? static::$_connection : null;
}
/**
* Sets the connection to use for this model.
* @param string $connection
*/
public static function set_connection($connection)
{
static::$_connection = $connection;
}
/**
* Sets the write connection to use for this model.
* @param string $connection
*/
public static function set_write_connection($connection)
{
static::$_write_connection = $connection;
}
/**
* Get the table name for this class
*
* @return string
*/
public static function table()
{
$class = get_called_class();
// Table name unknown
if ( ! array_key_exists($class, static::$_table_names_cached))
{
// Table name set in Model
if (property_exists($class, '_table_name'))
{
static::$_table_names_cached[$class] = static::$_table_name;
}
else
{
static::$_table_names_cached[$class] = \Inflector::tableize($class);
}
}
return static::$_table_names_cached[$class];
}
/**
* Get a defined condition for this class
*
* @param string type of condition to return
* @return array
*/
public static function condition($type = null)
{
$class = get_called_class();
// a specific condition requested?
if (property_exists($class, '_conditions'))
{
if ($type !== null)
{
return isset(static::$_conditions[$type]) ? static::$_conditions[$type] : array();
}
else
{
return static::$_conditions;
}
}
else
{
return array();
}
}
/**
* Attempt to retrieve an earlier loaded object
*
* @param array|Model $obj
* @param null|string $class
* @return Model|false
*/
public static function cached_object($obj, $class = null)
{
$class = $class ?: get_called_class();
$id = (is_int($obj) or is_string($obj)) ? (string) $obj : $class::implode_pk($obj);
$result = ( ! empty(static::$_cached_objects[$class][$id])) ? static::$_cached_objects[$class][$id] : false;
return $result;
}
/**
* Get the primary key(s) of this class
*
* @return array
*/
public static function primary_key()
{
return static::$_primary_key;
}
/**
* Implode the primary keys within the data into a string
*
* @param array
* @return string
*/
public static function implode_pk($data)
{
if (count(static::$_primary_key) == 1)
{
$p = reset(static::$_primary_key);
return (is_object($data)
? strval($data->{$p})
: (isset($data[$p])
? strval($data[$p])
: null));
}
$pk = '';
foreach (static::$_primary_key as $p)
{
if (is_null((is_object($data) ? $data->{$p} : (isset($data[$p]) ? $data[$p] : null))))
{
return null;
}
$pk .= '['.(is_object($data) ? $data->{$p} : $data[$p]).']';
}
return $pk;
}
/**
* Get the class's properties
*
* @throws \FuelException Listing columns failed
*
* @return array
*/
public static function properties()
{
$class = get_called_class();
// If already determined
if (array_key_exists($class, static::$_properties_cached))
{
return static::$_properties_cached[$class];
}
// Try to grab the properties from the class...
if (property_exists($class, '_properties'))
{
$properties = static::$_properties;
foreach ($properties as $key => $p)
{
if (is_string($p))
{
unset($properties[$key]);
$properties[$p] = array();
}
}
}
// ...if the above failed, run DB query to fetch properties
if (empty($properties))
{
try
{
$properties = \DB::list_columns(static::table(), null, static::connection());
}
catch (\Exception $e)
{
throw new \FuelException('Listing columns failed, you have to set the model properties with a '.
'static $_properties setting in the model. Original exception: '.$e->getMessage());
}
}
// cache the properties for next usage
static::$_properties_cached[$class] = $properties;
return static::$_properties_cached[$class];
}
/**
* Fetches a property description array, or specific data from it
*
* @param string property or property.key
* @param mixed return value when key not present
* @return mixed
*/
public static function property($key, $default = null)
{
$class = get_called_class();
// If already determined
if ( ! array_key_exists($class, static::$_properties_cached))
{
static::properties();
}
return \Arr::get(static::$_properties_cached[$class], $key, $default);
}
/**
* Fetch the model's views
*
* @throws \InvalidArgumentException Database view is defined without columns
*
* @return array
*/
public static function views()
{
$class = get_called_class();
if ( ! isset(static::$_views_cached[$class]))
{
static::$_views_cached[$class] = array();
if (property_exists($class, '_views'))
{
$views = $class::$_views;
foreach ($views as $k => $v)
{
if ( ! isset($v['columns']))
{
throw new \InvalidArgumentException('Database view '.$k.' is defined without columns.');
}
$v['columns'] = (array) $v['columns'];
if ( ! isset($v['view']))
{
$v['view'] = $k;
}
static::$_views_cached[$class][$k] = $v;
}
}
}
return static::$_views_cached[$class];
}
/**
* Get the class's relations
*
* @param bool $specific
* @return HasOne|HasMany|ManyMany|Belongsto|HasOne[]|HasMany[]|ManyMany[]|Belongsto[]
*/
public static function relations($specific = false)
{
$class = get_called_class();
if ( ! array_key_exists($class, static::$_relations_cached))
{
$relations = array();
foreach (static::$_valid_relations as $rel_name => $rel_class)
{
if (property_exists($class, '_'.$rel_name))
{
foreach (static::${'_'.$rel_name} as $key => $settings)
{
$name = is_string($settings) ? $settings : $key;
$settings = is_array($settings) ? $settings : array();
$relations[$name] = new $rel_class($class, $name, $settings);
}
}
}
static::$_relations_cached[$class] = $relations;
}
if ($specific === false)
{
return static::$_relations_cached[$class];
}
else
{
if ( ! array_key_exists($specific, static::$_relations_cached[$class]))
{
return false;
}
return static::$_relations_cached[$class][$specific];
}
}
/**
* Get the name of the class that defines a relation
*
* @param string
* @return array
*/
public static function related_class($relation)
{
$class = get_called_class();
foreach (static::$_valid_relations as $rel_name => $rel_class)
{
if (property_exists($class, '_'.$rel_name))
{
if (isset(static::${'_'.$rel_name}[$relation]))
{
return static::${'_'.$rel_name}[$relation]['model_to'];
}
}
}
return null;
}
/**
* Get the class's observers and what they observe
*
* @param string specific observer to retrieve info of, allows direct param access by using dot notation
* @param mixed default return value when specific key wasn't found
* @return array
*/
public static function observers($specific = null, $default = null)
{
$class = get_called_class();
if ( ! array_key_exists($class, static::$_observers_cached))
{
$observers = array();
if (property_exists($class, '_observers'))
{
foreach (static::$_observers as $obs_k => $obs_v)
{
if (is_int($obs_k))
{
$observers[$obs_v] = array();
}
else
{
if (is_string($obs_v) or (is_array($obs_v) and is_int(key($obs_v))))
{
// @TODO deprecated until v1.4
logger(\Fuel::L_WARNING, 'Passing observer events as array is deprecated, they must be
inside another array under a key "events". Check the docs for more info.', __METHOD__);
$observers[$obs_k] = array('events' => (array) $obs_v);
}
else
{
$observers[$obs_k] = $obs_v;
}
}
}
}
static::$_observers_cached[$class] = $observers;
}
if ($specific)
{
return \Arr::get(static::$_observers_cached[$class], $specific, $default);
}
return static::$_observers_cached[$class];
}
/**
* Register an observer
*
* @param string class name of the observer (including namespace)
* @param mixed observer options
*
* @return void
*/
public static function register_observer($name, $options = array())
{
$class = get_called_class();
static::$_observers_cached[$class] = static::observers() + array($name => $options);
}
/**
* Unregister an observer
*
* @param string class name of the observer (including namespace)
* @return void
*/
public static function unregister_observer($name)
{
$class = get_called_class();
foreach (static::observers() as $key => $value)
{
if ((is_array($value) and $key == $name) or $value == $name)
{
unset(static::$_observers_cached[$class][$key]);
}
}
}
/**
* Find one or more entries
*
* @param int|null $id
* @param array $options
*
* @throws \FuelException
*
* @return Model|Model[]
*/
public static function find($id = null, array $options = array())
{
// deal with null valued PK's
if (is_null($id))
{
// if no options are present, simply return null. a PK with a null value can exist
return func_num_args() === 2 ? static::query($options) : null;
}
// Return all that match $options array
elseif ($id === 'all')
{
return static::query($options)->get();
}
// Return first or last row that matches $options array
elseif ($id === 'first' or $id === 'last')
{
$query = static::query($options);
foreach(static::primary_key() as $pk)
{
$query->order_by($pk, $id == 'first' ? 'ASC' : 'DESC');
}
return $query->get_one();
}
// Return specific request row by ID
else
{
$cache_pk = $where = array();
$id = (array) $id;
foreach (static::primary_key() as $pk)
{
$where[] = array($pk, '=', current($id));
$cache_pk[$pk] = current($id);
next($id);
}
if (array_key_exists(get_called_class(), static::$_cached_objects)
and array_key_exists(static::implode_pk($cache_pk), static::$_cached_objects[get_called_class()])
and (! isset($options['from_cache']) or $options['from_cache'] == true))
{
return static::$_cached_objects[get_called_class()][static::implode_pk($cache_pk)];
}
array_key_exists('where', $options) and $where = array_merge($options['where'], $where);
$options['where'] = $where;
return static::query($options)->get_one();
}
}
/**
* Creates a new query with optional settings up front
*
* @param array
* @return Query
*/
public static function query($options = array())
{
return Query::forge(get_called_class(), array(static::connection(), static::connection(true)), $options);
}
/**
* Count entries, optionally only those matching the $options
*
* @param array
* @return int
*/
public static function count(array $options = array())
{
return static::query($options)->count();
}
/**
* Find the maximum
*
* @param mixed
* @param array
* @return bool|int Maximum value or false
*/
public static function max($key = null)
{
return static::query()->max($key ?: static::primary_key());
}
/**
* Find the minimum
*
* @param mixed
* @param array
* @return object|array
*/
public static function min($key = null)
{
return static::query()->min($key ?: static::primary_key());
}
public static function __callStatic($method, $args)
{
// Start with count_by? Get counting!
if (strpos($method, 'count_by') === 0)
{
$find_type = 'count';
$fields = substr($method, 9);
}
// Otherwise, lets find stuff
elseif (strpos($method, 'find_') === 0)
{
if ($method == 'find_by')
{
$find_type = 'all';
$fields = array_shift($args);
}
else
{
$find_type = strncmp($method, 'find_all_by_', 12) === 0 ? 'all' : (strncmp($method, 'find_by_', 8) === 0 ? 'first' : false);
$fields = $find_type === 'first' ? substr($method, 8) : substr($method, 12);
}
}
// God knows, complain
else
{
throw new \FuelException('Invalid method call. Method '.$method.' does not exist.', 0);
}
$where = $or_where = array();
if (($and_parts = explode('_and_', $fields)))
{
foreach ($and_parts as $and_part)
{
$or_parts = explode('_or_', $and_part);
if (count($or_parts) == 1)
{
$where[] = array($or_parts[0], array_shift($args));
}
else
{
foreach($or_parts as $or_part)
{
$or_where[] = array($or_part, array_shift($args));
}
}
}
}
$options = count($args) > 0 ? array_pop($args) : array();
if ( ! empty($where))
{
if ( ! array_key_exists('where', $options))
{
$options['where'] = $where;
}
else
{
$options['where'] = array_merge($where, $options['where']);
}
}
if ( ! empty($or_where))
{
if ( ! array_key_exists('or_where', $options))
{
$options['or_where'] = $or_where;
}
else
{
$options['or_where'] = array_merge($or_where, $options['or_where']);
}
}
if ($find_type == 'count')
{
return static::count($options);
}
else
{
return static::find($find_type, $options);
}
// min_...($options)
// max_...($options)
}
/* ---------------------------------------------------------------------------
* Object usage
* --------------------------------------------------------------------------- */
/**
* @var bool keeps track of whether it's a new object
*/
protected $_is_new = true;
/**
* @var bool keeps to object frozen
*/
protected $_frozen = false;
/**
* @var bool $_sanitization_enabled If this is a records data will be sanitized on get
*/
protected $_sanitization_enabled = false;
/**
* @var array keeps the current state of the object
*/
protected $_data = array();
/**
* @var array storage for custom properties on this object
*/
protected $_custom_data = array();
/**
* @var array keeps a copy of the object as it was retrieved from the database
*/
protected $_original = array();
/**
* @var array
*/
protected $_data_relations = array();
/**
* @var array keeps a copy of the relation ids that were originally retrieved from the database
*/
protected $_original_relations = array();
/**
* @var array keeps track of relations that need to be reset before saving the new ones
*/
protected $_reset_relations = array();
/**
* @var array disabled observer events
*/
protected $_disabled_events = array();
/**
* @var string view name when used
*/
protected $_view;
/**
* Constructor
*
* @param array
* @param bool
*/
public function __construct(array $data = array(), $new = true, $view = null, $cache = true)
{
// This is to deal with PHP's native hydration that happens before constructor is called
// for some weird reason, for example using the DB's as_object() function
if( ! empty($this->_data) or ! empty($this->_custom_data))
{
// merge the injected data with the passed data
$data = array_merge($this->_custom_data, $this->_data, $data);
// and reset them
$this->_data = array();
$this->_custom_data = array();
// and mark it as existing data
$new = false;
}
// move the passed data to the correct container
$properties = $this->properties();
foreach ($properties as $prop => $settings)
{
// do we have data for this this model property?
if (array_key_exists($prop, $data))
{
// store it in the data container
$this->_data[$prop] = $data[$prop];
unset($data[$prop]);
}
// property not present, do we have a default value?
elseif ($new and array_key_exists('default', $settings))
{
$this->_data[$prop] = $settings['default'];
}
}
// store the remainder in the custom data store
$this->_custom_data = $data;
// store the view, if one was passed
if ($view and array_key_exists($view, $this->views()))
{
$this->_view = $view;
}
if ($new === false)
{
// update the original datastore and the related datastore
$this->_update_original($this->_data);
// update the object cache if needed
$cache and static::$_cached_objects[get_class($this)][static::implode_pk($this->_data)] = $this;
// mark the object as existing
$this->_is_new = false;
// and fire the after-load observers
$this->observe('after_load');
}
else
{
// new object, fire the after-create observers
$this->observe('after_create');
}
}
/**
* Update the original setting for this object
*
* @param array|null $original
*/
public function _update_original($original = null)
{
$original = is_null($original) ? $this->_data : $original;
$this->_original = array_merge($this->_original, $original);
$this->_update_original_relations();
}
/**
* Update the original relations for this object
*/
public function _update_original_relations($relations = null)
{
if (is_null($relations))
{
$this->_original_relations = array();
$relations = $this->_data_relations;
}
else
{
foreach ($relations as $key => $rel)
{
// Unload the just fetched relation from the originals
unset($this->_original_relations[$rel]);
// Unset the numeric key and set the data to update by the relation name
unset($relations[$key]);
$relations[$rel] = $this->_data_relations[$rel];
}
}
foreach ($relations as $rel => $data)
{
if (is_array($data))
{
$this->_original_relations[$rel] = array();
foreach ($data as $obj)
{
if ($obj and ! $obj->is_new())
{
$this->_original_relations[$rel][] = $obj->implode_pk($obj);
}
}
}
else
{
$this->_original_relations[$rel] = null;
if ($data and ! $data->is_new())
{
$this->_original_relations[$rel] = $data->implode_pk($data);
}
}
}
}
/**
* Fetch or set relations on this object
* To be used only after having fetched them from the database!
*
* @param array|bool|null $rels
*
* @throws \FuelException Invalid input for _relate(), should be an array
* @throws FrozenObject No changes allowed
*
* @return void|array
*/
public function _relate($rels = false)
{
if ($rels === false)
{
return $this->_data_relations;
}
elseif (is_array($rels))
{
if ($this->_frozen)
{
throw new FrozenObject('No changes allowed.');
}
$this->_data_relations = $rels;
}
else
{
throw new \FuelException('Invalid input for _relate(), should be an array.');
}
}
/**
* Fetch a property or relation
*
* @param string
* @return mixed
*/
public function & __get($property)
{
return $this->get($property);
}
/**
* Set a property or relation
*
* @param string
* @param mixed
*
* @return Model
*/
public function __set($property, $value)
{
return $this->set($property, $value);
}
/**
* Check whether a property exists, only return true for table columns, relations, eav and custom data
*
* @param string $property
* @return bool