-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRelational.php
More file actions
2534 lines (2239 loc) · 61.7 KB
/
Relational.php
File metadata and controls
2534 lines (2239 loc) · 61.7 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
/**
* @package framework
* @copyright Copyright (c) 2005-2020 The Regents of the University of California.
* @license http://opensource.org/licenses/MIT MIT
*/
namespace Qubeshub\Database;
require_once PATH_APP . DS . 'libraries' . DS . 'Qubeshub' . DS . 'Database' . DS . 'Traits' . DS . 'ErrorBag.php';
require_once PATH_APP . DS . 'libraries' . DS . 'Qubeshub' . DS . 'Database' . DS . 'Rows.php';
require_once PATH_APP . DS . 'libraries' . DS . 'Qubeshub' . DS . 'Database' . DS . 'Rules.php';
use Hubzero\Database\Relationship\BelongsToOne;
use Hubzero\Database\Relationship\OneToMany;
use Hubzero\Database\Relationship\ManyToMany;
use Hubzero\Database\Relationship\OneToManyThrough;
use Hubzero\Database\Relationship\OneToOne;
use Hubzero\Database\Relationship\OneShiftsToMany;
use Hubzero\Database\Relationship\ManyShiftsToMany;
use Hubzero\Error\Exception\BadMethodCallException;
use Hubzero\Error\Exception\RuntimeException;
use Hubzero\Utility\Date;
use Closure;
/**
* Database ORM base class
*
* //@FIXME: handle dates
*
* @uses \Hubzero\Error\Exception\BadMethodCallException to handle calls to undefined methods
* @uses \Hubzero\Error\Exception\RuntimeException to handle scenarios with undefined rows
*/
/** @phpstan-consistent-constructor */
class Relational implements \IteratorAggregate, \ArrayAccess, \Serializable
{
/*
* Errors trait for error message handling
**/
use Traits\ErrorBag;
/**
* Database state constants
**/
const STATE_UNPUBLISHED = 0;
const STATE_PUBLISHED = 1;
const STATE_DELETED = 2;
/**
* Database access constants
**/
const ACCESS_PUBLIC = 1;
const ACCESS_REGISTERED = 2;
const ACCESS_PRIVATE = 4;
/**
* The database model name
*
* This will defined as the static/calling class' name.
* It's used when building relationships between classes.
*
* @var string
**/
private $modelName = null;
/**
* The database model namespace
*
* @var string
**/
private $modelNamespace = null;
/**
* The internal array of methods of this model
*
* We do a lot of reflection checks on the model,
* so this should save us some time by storing the results
* for future reference.
*
* @var array
**/
private $methods = [];
/**
* The database query object
*
* @var \Hubzero\Database\Query
**/
private $query = null;
/**
* The database connection used by the query object
*
* @var \Hubzero\Database\Driver|object
**/
public $connection = null;
/**
* Whether or not we're caching query results
*
* @var string
**/
private $noCache = false;
/**
* The relationships on this model
*
* @var array
**/
private $relationships = [];
/**
* The relationships established at runtime
*
* @var array
**/
private static $acquaintances = [];
/**
* The forwards for the model (i.e. other places to look for attributes)
*
* @var array
**/
private $forwards = [];
/**
* The includes set on the model for eager loading
*
* @var array
**/
private $includes = [];
/**
* The model data returned as the result of a query, or set for saving
*
* @var array
**/
private $attributes = [];
/**
* The parent iterator if this model was retrieved as part of a larger rows collection
*
* @var \Qubeshub\Database\Rows
**/
private $collection = null;
/**
* The table to which the class pertains
*
* This will default to #__{namespace}_{modelName} unless otherwise
* overwritten by a given subclass. Definition of this property likely
* indicates some derivation from standard naming conventions.
*
* @var string
**/
protected $table = null;
/**
* An alias to apply to the table for initial query building
*
* @var string
**/
protected $tableAlias = null;
/**
* The table namespace
*
* This is likely just the component name, and will most likely
* be set by all subclasses. This follows the convention of
* prefixing/namespacing database tables with #__componentname_*.
*
* @FIXME: could we infer this once our models are properly namespaced?
*
* @var string
**/
protected $namespace = null;
/**
* The table primary key name
*
* It defaults to 'id', but can be overwritten by a subclass.
*
* @var string
**/
protected $pk = 'id';
/**
* Fields that have content that can/should be parsed
*
* @var array
**/
protected $parsed = [];
/**
* Fields and their validation criteria
*
* @var array
* @see \Hubzero\Database\Rules
**/
protected $rules = [];
/**
* Default order by for select queries
*
* This can be overwritten in a model or by calling
* the order method on the query object.
*
* @var string
**/
public $orderBy = 'id';
/**
* Default order direction for select queries
*
* @var string
**/
public $orderDir = 'asc';
/**
* The pagination object
*
* This will also get set on the rows object if applicable.
*
* @var \Hubzero\Database\Pagination|null
**/
public $pagination = null;
/**
* Automatic fields to populate every time a row is touched
*
* @var array
**/
public $always = [];
/**
* Automatic fields to populate every time a row is created
*
* @var array
**/
public $initiate = [];
/**
* Automatic fields to populate every time a row is updated
*
* @var array
**/
public $renew = [];
/**
* Any associative elements
*
* @var object
**/
public $associated = null;
/**
* Cached list of class methods
*
* @var array
**/
private static $classMethods = [];
/**
* Table schema cache
*
* @var array
*/
public static $columns = [];
/**
* Constructs an object instance
*
* @return void
* @since 2.0.0
**/
public function __construct()
{
$r = new \ReflectionClass($this);
// Set model name
$this->modelName = $r->getShortName();
$this->modelNamespace = $r->getNamespaceName();
// If table name isn't explicitly set, build it
$namespace = (!$this->namespace ? '' : $this->namespace . '_');
$plural = \Hubzero\Utility\Inflector::pluralize(strtolower($this->getModelName()));
$this->table = $this->table ?: '#__' . $namespace . $plural;
// Set up connection and query object
$this->newQuery();
// Store methods for later
//
// Here we store the methods per class name. This allows for quicker
// lookup and less memory usage when dealing with multiple classes
// of the same type (i.e., a listing of records).
$key = $r->getName();
if (!isset(self::$classMethods[$key]))
{
self::$classMethods[$key] = get_class_methods($this);
$this->methods = self::$classMethods[$key];
}
$this->methods = self::$classMethods[$key];
// Run extra setup. This is so subclasses don't have to overwrite
// the constructor and then call parent::__construct().
// They can instead just add a setup() method.
$this->setup();
}
/**
* Processes calls to inaccessible or undefined instance methods
*
* @param string $name The method name being called
* @param array $arguments The method arguments provided
* @return mixed
* @throws \Hubzero\Error\Exception\BadMethodCallException If called method does not exist in
* this class or the query class, or
* as a helper* method on the current class.
* @since 2.0.0
**/
public function __call($name, $arguments)
{
// See if method is available as a helper method on current class
if ($this->hasHelper($name))
{
return $this->callHelper($name, $arguments);
}
// See if method is available as a transformer on current class
if ($this->hasTransformer($name))
{
return $this->callTransformer($name, $arguments);
}
// Check if it is a parsable field (i.e. wiki/html)
if ($this->isParsable($name))
{
return $this->parse($name, (isset($arguments[0])) ? $arguments[0] : 'parsed');
}
// See if we need to call a query method
if (in_array($name, get_class_methods($this->query)))
{
// @FIXME: hack to fully qualify field names in one location...is there a better way/location?
if ((substr($name, 0, 5) == 'where' || substr($name, 0, 7) == 'orWhere') && $name != 'whereRaw' && $name != 'orWhereRaw')
{
$arguments[0] = (strpos($arguments[0], '.') === false)
? $this->getQualifiedFieldName($arguments[0])
: $arguments[0];
}
// Call method and get type of response
$result = call_user_func_array(array($this->query, $name), $arguments);
$class = 'Hubzero\\Database\\Query';
// We never want to return an instance of the query class, because
// we want to be able to chain methods together that are on the model
// itself. Plus we auto-forward calls to query functions, so they'll
// get there eventually anyway.
return ($result instanceof $class) ? $this : $result;
}
// Finally, check for a dynamic relationship definition
if (array_key_exists($name, self::$acquaintances))
{
return call_user_func_array(self::$acquaintances[$name], [$this]);
}
// This method doesn't exist
throw new BadMethodCallException("'{$name}' method does not exist.", 500);
}
/**
* Processes calls to inaccessible or undefined static methods
*
* This is here primarily so we can statically call query class
* methods directly on a newly created object
* For example: Model::whereEquals('field', 'yes');
*
* @param string $name The method name being called
* @param array $arguments The method arguments provided
* @return mixed
* @since 2.0.0
**/
public static function __callStatic($name, $arguments)
{
return call_user_func_array(array(new static, $name), $arguments);
}
/**
* Gets attributes set on model dynmically
*
* @param string $name The name of the var to retrieve
* @return mixed
* @since 2.0.0
**/
public function __get($name)
{
// First, see if a transformer is available on the model
if ($this->hasTransformer($name))
{
return $this->callTransformer($name);
}
// Check if it is a parsable field (i.e. wiki/html)
if ($this->isParsable($name))
{
return $this->parse($name);
}
// Next check for an attribute on the model
if (isset($this->attributes[$name]))
{
return $this->attributes[$name];
}
// Check forwarding
if (!empty($this->forwards))
{
foreach ($this->forwards as $forward)
{
// We take the first one we find, so in theory, if multiple forwards exist with
// the same name, you'd have to prioritize them somehow.
if ($var = $this->makeRelationship($forward)->getRelationship($forward)->$name)
{
return $var;
}
}
}
// Now, we'll assume we're looking for a relationship
if (in_array($name, $this->methods))
{
return $this->makeRelationship($name)->getRelationship($name);
}
// Finally, check for a dynamic relationship definition
if (array_key_exists($name, self::$acquaintances))
{
return $this->makeAcquaintance($name)->getRelationship($name);
}
}
/**
* Check if attributes (i.e. field) on the model is set
*
* @param string $name The attribute to check if set
* @return boolean
*/
public function __isset($name)
{
return $this->hasAttribute($name);
}
/**
* Sets attributes (i.e. fields) on the model
*
* @param array|string $key The key to set, or array of key/value pairs
* @param mixed $value The value to set if key is string
* @return self
*/
public function __set($key, $value)
{
return $this->set($key, $value);
}
/**
* Intercepts calls to copy the object so we can make a true clone of the attached query
*
* PHP, when cloning, does a shallow copy, hence the need for this intercept.
*
* @return void
* @since 2.0.0
**/
public function __clone()
{
$this->query = clone $this->query;
}
/**
* Serializes the model data for storage
*
* @return string
* @since 2.1.0
**/
#[\ReturnTypeWillChange]
public function serialize()
{
return serialize($this->__serialize());
}
/**
* Serializes the model data for storage
*
* @return array
**/
#[\ReturnTypeWillChange]
public function __serialize()
{
return $this->getAttributes();
}
/**
* Unserializes the data into a new model
*
* @param string $data The data to build from
* @return void
* @since 2.1.0
**/
#[\ReturnTypeWillChange]
public function unserialize($data)
{
$this->__unserialize($data);
}
/**
* Unserializes the data into a new model
*
* @param array $data The data to build from
* @return void
**/
#[\ReturnTypeWillChange]
public function __unserialize($data)
{
$this->__construct();
if (is_string($data))
{
$data = unserialize($data);
}
$this->set($data);
}
/**
* Runs extra setup code when creating a new model
*
* @return void
* @since 2.0.0
**/
public function setup()
{
// Overload in subclass to do something here...nothing by default
}
/**
* Sets the database connection to be used by the query builder
*
* @param object $connection The connection to set
* @return void
* @since 2.0.0
**/
public function setDefaultConnection($connection)
{
$this->connection = $connection;
}
/**
* Disables query caching
*
* @return self
* @since 2.0.0
**/
public function disableCaching()
{
$this->noCache = true;
return $this;
}
/**
* Enables query caching
*
* @return self
* @since 2.0.0
**/
public function enableCaching()
{
$this->noCache = false;
return $this;
}
/**
* Purges the query cache
*
* @return self
* @since 2.0.0
**/
public function purgeCache()
{
$query = $this->query;
$query::purgeCache();
return $this;
}
/**
* Gets an attribute by key
*
* This will not retrieve properties directly attached to the model,
* even if they are public - those should be accessed directly!
*
* Also, make sure to access properties in transformers using the get method.
* Otherwise you'll just get stuck in a loop!
*
* @param string $key The attribute key to get
* @param mixed $default The value to provide, should the key be non-existent
* @return mixed
* @since 2.0.0
**/
public function get($key, $default = null)
{
return $this->hasAttribute($key) ? $this->attributes[$key] : $default;
}
/**
* Sets attributes (i.e. fields) on the model
*
* This must be used when setting data to be saved. Otherwise, the properties
* will be attached directly to the model itself and not included in the save.
*
* @param array|string $key The key to set, or array of key/value pairs
* @param mixed $value The value to set if key is string
* @return self
* @since 2.0.0
**/
public function set($key, $value = null)
{
if (is_array($key) || is_object($key))
{
foreach ($key as $k => $v)
{
$this->attributes[$k] = $v;
}
}
else
{
$this->attributes[$key] = $value;
}
return $this;
}
/**
* Returns a new empty model
*
* @return static
* @since 2.0.0
**/
public static function blank()
{
return new static;
}
/**
* Construct a new object instance, setting the passed in results on the object
*
* @param object $results The results to set on the new model
* @return static
* @since 2.0.0
**/
public static function newFromResults($results)
{
$instance = self::blank();
$instance->set($results);
return $instance;
}
/**
* Copies the current model (likely used to maintain query parameters between multiple queries)
*
* @return self
* @since 2.0.0
**/
public function copy()
{
return clone $this;
}
/**
* Outputs attributes in JSON encoded format
*
* @return string
* @since 2.0.0
**/
public function toJson()
{
return json_encode($this->attributes);
}
/**
* Outputs attributes as array
*
* @return array
* @since 2.0.0
**/
public function toArray()
{
return $this->attributes;
}
/**
* Outputs attributes as object
*
* @return object
* @since 2.0.0
**/
public function toObject()
{
return (object)$this->attributes;
}
/**
* Checks to see if the current model has a helper by the given name
*
* @param string $name The helper name to check for
* @return bool
* @since 2.0.0
**/
public function hasHelper($name)
{
return in_array('helper' . ucfirst($name), $this->methods);
}
/**
* Calls the requested helper, passing the given arguments
*
* @param string $name The helper name to call
* @param array $arguments Arguments to pass with the method call
* @return mixed
* @since 2.0.0
**/
public function callHelper($name, $arguments)
{
return call_user_func_array(array($this, 'helper' . ucfirst($name)), $arguments);
}
/**
* Checks to see if the current model has a transformer by the given name
*
* @param string $name The transformer name to check for
* @return bool
* @since 2.0.0
**/
public function hasTransformer($name)
{
return in_array('transform' . ucfirst($this->snakeToCamel($name)), $this->methods);
}
/**
* Calls the requested transformer, passing the given arguments
*
* @param string $name The transformer name to call
* @param array $arguments Arguments to pass with the method call
* @return mixed
* @since 2.0.0
**/
public function callTransformer($name, $arguments = [])
{
return call_user_func_array(array($this, 'transform' . ucfirst($this->snakeToCamel($name))), $arguments);
}
/**
* Checks to see if the given field is one to be parsed
*
* @param string $field The field to check
* @return bool
* @since 2.0.0
**/
public function isParsable($field)
{
return in_array($field, $this->parsed);
}
/**
* Parses content string as directed
*
* @param string $field The field to parse
* @param string $as The format to return state in
* @return string
* @since 2.0.0
**/
public function parse($field, $as = 'parsed')
{
switch (strtolower($as))
{
case 'parsed':
$property = "_{$field}Parsed";
if (!isset($this->$property))
{
$this->$property = \Hubzero\Html\Builder\Content::prepare($this->get($field, ''));
}
return $this->$property;
break;
case 'raw':
default:
$content = stripslashes($this->get($field, ''));
return preg_replace('/^(<!-- \{FORMAT:.*\} -->)/i', '', $content);
break;
}
}
/**
* Takes a snake-cased string and camel cases it
*
* @param string $text The string to camel case
* @return string
* @since 2.0.0
**/
public function snakeToCamel($text)
{
if (strpos($text, '_') !== false)
{
$bits = explode('_', $text);
$bits = array_map('ucfirst', $bits);
$text = lcfirst(implode('', $bits));
}
return $text;
}
/**
* Resets the current model, likely for another query to be performed on it
*
* @return self
* @since 2.0.0
**/
private function reset()
{
$this->clearAttributes();
$this->newQuery();
return $this;
}
/**
* Gets a fresh query object
*
* @return \Hubzero\Database\Query
* @since 2.0.0
**/
public function getQuery()
{
return new \Hubzero\Database\Query($this->connection);
}
/**
* Gets a fresh structure object
*
* @return \Hubzero\Database\Structure
* @since 2.0.0
**/
public function getStructure()
{
return new \Hubzero\Database\Structure($this->connection);
}
/**
* Sets a fresh query object on the model, seeding it with helpful defaults
*
* @return self
* @since 2.0.0
**/
public function newQuery()
{
$select = ($this->getTableAlias() ? $this->getTableAlias() . '.' : '') . '*';
$this->query = $this->getQuery()->select($select)->from($this->getTableName(), $this->getTableAlias());
return $this;
}
/**
* Checks to see if the requested attribute is set on the model
*
* @return bool
* @since 2.0.0
**/
public function hasAttribute($key)
{
return isset($this->attributes[$key]);
}
/**
* Grabs all of the model attributes
*
* @return array
* @since 2.0.0
**/
public function getAttributes()
{
return $this->attributes;
}
/**
* Removes an attribute
*
* @param string $key The attribute to remove
* @return self
* @since 2.0.0
**/
public function removeAttribute($key)
{
$this->offsetUnset($key);
return $this;
}
/**
* Clears data attributes set on the current model
*
* @return void
* @since 2.0.0
**/
private function clearAttributes()
{
$this->attributes = array();
}
/**
* Determines if the current model is new by looking for the presence of a primary key attribute
*
* @return bool
* @since 2.0.0
**/
public function isNew()
{
return (!$this->hasAttribute($this->getPrimaryKey()) || !$this->{$this->getPrimaryKey()});
}
/**
* Sets an interator parent on the model
*
* @param \Qubeshub\Database\Rows $rows The iterator to set
* @return self
* @since 2.1.0
**/
public function setIterator($rows)
{
$this->collection = $rows;
return $this;
}
/**
* Checks to see if the current item is the first in the list
*
* @return bool
* @since 2.1.0
**/
public function isFirst()
{
if ($this->collection)
{
return $this->collection->isFirst($this->getPkValue());
}
return false;
}
/**
* Checks to see if the current item is the last in the list
*
* @return bool
* @since 2.1.0
**/
public function isLast()
{
if ($this->collection)
{
return $this->collection->isLast($this->getPkValue());
}
return false;
}
/**
* Retrieves the current model's table name
*
* @return string
* @since 2.0.0
**/
public function getTableName()
{
return $this->table;
}
/**
* Retrieves the current model's table alias
*
* @return string
**/
public function getTableAlias()
{