-
Notifications
You must be signed in to change notification settings - Fork 442
/
Copy pathRelationship.php
730 lines (619 loc) · 20.7 KB
/
Relationship.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
<?php
/**
* @package ActiveRecord
*/
namespace ActiveRecord;
/**
* Interface for a table relationship.
*
* @package ActiveRecord
*/
interface InterfaceRelationship
{
public function __construct($options=array());
public function build_association(Model $model, $attributes=array(), $guard_attributes=true);
public function create_association(Model $model, $attributes=array(), $guard_attributes=true);
}
/**
* Abstract class that all relationships must extend from.
*
* @package ActiveRecord
* @see http://www.phpactiverecord.org/guides/associations
*/
abstract class AbstractRelationship implements InterfaceRelationship
{
/**
* Name to be used that will trigger call to the relationship.
*
* @var string
*/
public $attribute_name;
/**
* Class name of the associated model.
*
* @var string
*/
public $class_name;
/**
* Name of the foreign key.
*
* @var string
*/
public $foreign_key = array();
/**
* Options of the relationship.
*
* @var array
*/
protected $options = array();
/**
* Is the relationship single or multi.
*
* @var boolean
*/
protected $poly_relationship = false;
/**
* List of valid options for relationships.
*
* @var array
*/
static protected $valid_association_options = array('class_name', 'class', 'foreign_key', 'conditions', 'select', 'readonly', 'namespace');
/**
* Constructs a relationship.
*
* @param array $options Options for the relationship (see {@link valid_association_options})
* @return mixed
*/
public function __construct($options=array())
{
$this->attribute_name = $options[0];
$this->options = $this->merge_association_options($options);
$relationship = strtolower(denamespace(get_called_class()));
if ($relationship === 'hasmany' || $relationship === 'hasandbelongstomany')
$this->poly_relationship = true;
if (isset($this->options['conditions']) && !is_array($this->options['conditions']))
$this->options['conditions'] = array($this->options['conditions']);
if (isset($this->options['class']))
$this->set_class_name($this->options['class']);
elseif (isset($this->options['class_name']))
$this->set_class_name($this->options['class_name']);
$this->attribute_name = strtolower(Inflector::instance()->variablize($this->attribute_name));
if (!$this->foreign_key && isset($this->options['foreign_key']))
$this->foreign_key = is_array($this->options['foreign_key']) ? $this->options['foreign_key'] : array($this->options['foreign_key']);
}
protected function get_table()
{
return Table::load($this->class_name);
}
/**
* What is this relationship's cardinality?
*
* @return bool
*/
public function is_poly()
{
return $this->poly_relationship;
}
/**
* Eagerly loads relationships for $models.
*
* This method takes an array of models, collects PK or FK (whichever is needed for relationship), then queries
* the related table by PK/FK and attaches the array of returned relationships to the appropriately named relationship on
* $models.
*
* @param Table $table
* @param $models array of model objects
* @param $attributes array of attributes from $models
* @param $includes array of eager load directives
* @param $query_keys -> key(s) to be queried for on included/related table
* @param $model_values_keys -> key(s)/value(s) to be used in query from model which is including
* @return void
*/
protected function query_and_attach_related_models_eagerly(Table $table, $models, $attributes, $includes=array(), $query_keys=array(), $model_values_keys=array())
{
$values = array();
$options = $this->options;
$inflector = Inflector::instance();
$query_key = $query_keys[0];
$model_values_key = $model_values_keys[0];
foreach ($attributes as $column => $value)
$values[] = $value[$inflector->variablize($model_values_key)];
$values = array($values);
$conditions = SQLBuilder::create_conditions_from_underscored_string($table->conn,$query_key,$values);
if (isset($options['conditions']) && strlen($options['conditions'][0]) > 1)
Utils::add_condition($options['conditions'], $conditions);
else
$options['conditions'] = $conditions;
if (!empty($includes))
$options['include'] = $includes;
if (!empty($options['through'])) {
// save old keys as we will be reseting them below for inner join convenience
$pk = $this->primary_key;
$fk = $this->foreign_key;
$this->set_keys($this->get_table()->class->getName(), true);
if (!isset($options['class_name'])) {
$class = classify($options['through'], true);
if (isset($this->options['namespace']) && !class_exists($class))
$class = $this->options['namespace'].'\\'.$class;
$through_table = $class::table();
} else {
$class = $options['class_name'];
$relation = $class::table()->get_relationship($options['through']);
$through_table = $relation->get_table();
}
$options['joins'] = $this->construct_inner_join_sql($through_table, true);
$query_key = $this->primary_key[0];
// reset keys
$this->primary_key = $pk;
$this->foreign_key = $fk;
}
$options = $this->unset_non_finder_options($options);
$class = $this->class_name;
$related_models = $class::find('all', $options);
$used_models_map = array();
$related_models_map = array();
$model_values_key = $inflector->variablize($model_values_key);
$query_key = $inflector->variablize($query_key);
foreach ($related_models as $related)
{
$related_models_map[$related->$query_key][] = $related;
}
foreach ($models as $model)
{
$key_to_match = $model->$model_values_key;
if (isset($related_models_map[$key_to_match])) {
foreach ($related_models_map[$key_to_match] as $related)
{
$hash = spl_object_hash($related);
if (isset($used_models_map[$hash]))
$model->set_relationship_from_eager_load(clone($related), $this->attribute_name);
else
$model->set_relationship_from_eager_load($related, $this->attribute_name);
$used_models_map[$hash] = true;
}
} else {
$model->set_relationship_from_eager_load(null, $this->attribute_name);
}
}
}
/**
* Creates a new instance of specified {@link Model} with the attributes pre-loaded.
*
* @param Model $model The model which holds this association
* @param array $attributes Hash containing attributes to initialize the model with
* @return Model
*/
public function build_association(Model $model, $attributes=array(), $guard_attributes=true)
{
$class_name = $this->class_name;
return new $class_name($attributes, $guard_attributes);
}
/**
* Creates a new instance of {@link Model} and invokes save.
*
* @param Model $model The model which holds this association
* @param array $attributes Hash containing attributes to initialize the model with
* @return Model
*/
public function create_association(Model $model, $attributes=array(), $guard_attributes=true)
{
$class_name = $this->class_name;
$new_record = $class_name::create($attributes, true, $guard_attributes);
return $this->append_record_to_associate($model, $new_record);
}
protected function append_record_to_associate(Model $associate, Model $record)
{
$association =& $associate->{$this->attribute_name};
if ($this->poly_relationship)
$association[] = $record;
else
$association = $record;
return $record;
}
protected function merge_association_options($options)
{
$available_options = array_merge(self::$valid_association_options,static::$valid_association_options);
$valid_options = array_intersect_key(array_flip($available_options),$options);
foreach ($valid_options as $option => $v)
$valid_options[$option] = $options[$option];
return $valid_options;
}
protected function unset_non_finder_options($options)
{
foreach (array_keys($options) as $option)
{
if (!in_array($option, Model::$VALID_OPTIONS))
unset($options[$option]);
}
return $options;
}
/**
* Infers the $this->class_name based on $this->attribute_name.
*
* Will try to guess the appropriate class by singularizing and uppercasing $this->attribute_name.
*
* @return void
* @see attribute_name
*/
protected function set_inferred_class_name()
{
$singularize = ($this instanceOf HasMany ? true : false);
$this->set_class_name(classify($this->attribute_name, $singularize));
}
protected function set_class_name($class_name)
{
if (!has_absolute_namespace($class_name) && isset($this->options['namespace'])) {
$class_name = $this->options['namespace'].'\\'.$class_name;
}
$reflection = Reflections::instance()->add($class_name)->get($class_name);
if (!$reflection->isSubClassOf('ActiveRecord\\Model'))
throw new RelationshipException("'$class_name' must extend from ActiveRecord\\Model");
$this->class_name = $class_name;
}
protected function create_conditions_from_keys(Model $model, $condition_keys=array(), $value_keys=array())
{
$condition_string = implode('_and_', $condition_keys);
$condition_values = array_values($model->get_values_for($value_keys));
// return null if all the foreign key values are null so that we don't try to do a query like "id is null"
if (all(null,$condition_values))
return null;
$conditions = SQLBuilder::create_conditions_from_underscored_string(Table::load(get_class($model))->conn,$condition_string,$condition_values);
# DO NOT CHANGE THE NEXT TWO LINES. add_condition operates on a reference and will screw options array up
if (isset($this->options['conditions']))
$options_conditions = $this->options['conditions'];
else
$options_conditions = array();
return Utils::add_condition($options_conditions, $conditions);
}
/**
* Creates INNER JOIN SQL for associations.
*
* @param Table $from_table the table used for the FROM SQL statement
* @param bool $using_through is this a THROUGH relationship?
* @param string $alias a table alias for when a table is being joined twice
* @return string SQL INNER JOIN fragment
*/
public function construct_inner_join_sql(Table $from_table, $using_through=false, $alias=null)
{
if ($using_through)
{
$join_table = $from_table;
$join_table_name = $from_table->get_fully_qualified_table_name();
$from_table_name = Table::load($this->class_name)->get_fully_qualified_table_name();
}
else
{
$join_table = Table::load($this->class_name);
$join_table_name = $join_table->get_fully_qualified_table_name();
$from_table_name = $from_table->get_fully_qualified_table_name();
}
// need to flip the logic when the key is on the other table
if ($this instanceof HasMany || $this instanceof HasOne)
{
$this->set_keys($from_table->class->getName());
if ($using_through)
{
$foreign_key = $this->primary_key[0];
$join_primary_key = $this->foreign_key[0];
}
else
{
$join_primary_key = $this->foreign_key[0];
$foreign_key = $this->primary_key[0];
}
}
else
{
$foreign_key = $this->foreign_key[0];
$join_primary_key = $this->primary_key[0];
}
if (!is_null($alias))
{
$aliased_join_table_name = $alias = $this->get_table()->conn->quote_name($alias);
$alias .= ' ';
}
else
$aliased_join_table_name = $join_table_name;
return "INNER JOIN $join_table_name {$alias}ON($from_table_name.$foreign_key = $aliased_join_table_name.$join_primary_key)";
}
/**
* This will load the related model data.
*
* @param Model $model The model this relationship belongs to
*/
abstract function load(Model $model);
}
/**
* One-to-many relationship.
*
* <code>
* # Table: people
* # Primary key: id
* # Foreign key: school_id
* class Person extends ActiveRecord\Model {}
*
* # Table: schools
* # Primary key: id
* class School extends ActiveRecord\Model {
* static $has_many = array(
* array('people')
* );
* });
* </code>
*
* Example using options:
*
* <code>
* class Payment extends ActiveRecord\Model {
* static $belongs_to = array(
* array('person'),
* array('order')
* );
* }
*
* class Order extends ActiveRecord\Model {
* static $has_many = array(
* array('people',
* 'through' => 'payments',
* 'select' => 'people.*, payments.amount',
* 'conditions' => 'payments.amount < 200')
* );
* }
* </code>
*
* @package ActiveRecord
* @see http://www.phpactiverecord.org/guides/associations
* @see valid_association_options
*/
class HasMany extends AbstractRelationship
{
/**
* Valid options to use for a {@link HasMany} relationship.
*
* <ul>
* <li><b>limit/offset:</b> limit the number of records</li>
* <li><b>primary_key:</b> name of the primary_key of the association (defaults to "id")</li>
* <li><b>group:</b> GROUP BY clause</li>
* <li><b>order:</b> ORDER BY clause</li>
* <li><b>through:</b> name of a model</li>
* </ul>
*
* @var array
*/
static protected $valid_association_options = array('primary_key', 'order', 'group', 'having', 'limit', 'offset', 'through', 'source');
protected $primary_key;
private $has_one = false;
private $through;
/**
* Constructs a {@link HasMany} relationship.
*
* @param array $options Options for the association
* @return HasMany
*/
public function __construct($options=array())
{
parent::__construct($options);
if (isset($this->options['through']))
{
$this->through = $this->options['through'];
if (isset($this->options['source']))
$this->set_class_name($this->options['source']);
}
if (!$this->primary_key && isset($this->options['primary_key']))
$this->primary_key = is_array($this->options['primary_key']) ? $this->options['primary_key'] : array($this->options['primary_key']);
if (!$this->class_name)
$this->set_inferred_class_name();
}
protected function set_keys($model_class_name, $override=false)
{
//infer from class_name
if (!$this->foreign_key || $override)
$this->foreign_key = array(Inflector::instance()->keyify($model_class_name));
if (!$this->primary_key || $override)
$this->primary_key = Table::load($model_class_name)->pk;
}
public function load(Model $model)
{
$class_name = $this->class_name;
$this->set_keys(get_class($model));
// since through relationships depend on other relationships we can't do
// this initiailization in the constructor since the other relationship
// may not have been created yet and we only want this to run once
if (!isset($this->initialized))
{
if ($this->through)
{
// verify through is a belongs_to or has_many for access of keys
if (!($through_relationship = $this->get_table()->get_relationship($this->through)))
throw new HasManyThroughAssociationException("Could not find the association $this->through in model " . get_class($model));
if (!($through_relationship instanceof HasMany) && !($through_relationship instanceof BelongsTo))
throw new HasManyThroughAssociationException('has_many through can only use a belongs_to or has_many association');
// save old keys as we will be reseting them below for inner join convenience
$pk = $this->primary_key;
$fk = $this->foreign_key;
$this->set_keys($this->get_table()->class->getName(), true);
$class = $this->class_name;
$relation = $class::table()->get_relationship($this->through);
$through_table = $relation->get_table();
$this->options['joins'] = $this->construct_inner_join_sql($through_table, true);
// reset keys
$this->primary_key = $pk;
$this->foreign_key = $fk;
}
$this->initialized = true;
}
if (!($conditions = $this->create_conditions_from_keys($model, $this->foreign_key, $this->primary_key)))
return null;
$options = $this->unset_non_finder_options($this->options);
$options['conditions'] = $conditions;
return $class_name::find($this->poly_relationship ? 'all' : 'first',$options);
}
/**
* Get an array containing the key and value of the foreign key for the association
*
* @param Model $model
* @access private
* @return array
*/
private function get_foreign_key_for_new_association(Model $model)
{
$this->set_keys($model);
$primary_key = Inflector::instance()->variablize($this->foreign_key[0]);
return array(
$primary_key => $model->id,
);
}
private function inject_foreign_key_for_new_association(Model $model, &$attributes)
{
$primary_key = $this->get_foreign_key_for_new_association($model);
if (!isset($attributes[key($primary_key)]))
$attributes[key($primary_key)] = current($primary_key);
return $attributes;
}
public function build_association(Model $model, $attributes=array(), $guard_attributes=true)
{
$relationship_attributes = $this->get_foreign_key_for_new_association($model);
if ($guard_attributes) {
// First build the record with just our relationship attributes (unguarded)
$record = parent::build_association($model, $relationship_attributes, false);
// Then, set our normal attributes (using guarding)
$record->set_attributes($attributes);
} else {
// Merge our attributes
$attributes = array_merge($relationship_attributes, $attributes);
// First build the record with just our relationship attributes (unguarded)
$record = parent::build_association($model, $attributes, $guard_attributes);
}
return $record;
}
public function create_association(Model $model, $attributes=array(), $guard_attributes=true)
{
$relationship_attributes = $this->get_foreign_key_for_new_association($model);
if ($guard_attributes) {
// First build the record with just our relationship attributes (unguarded)
$record = parent::build_association($model, $relationship_attributes, false);
// Then, set our normal attributes (using guarding)
$record->set_attributes($attributes);
// Save our model, as a "create" instantly saves after building
$record->save();
} else {
// Merge our attributes
$attributes = array_merge($relationship_attributes, $attributes);
// First build the record with just our relationship attributes (unguarded)
$record = parent::create_association($model, $attributes, $guard_attributes);
}
return $record;
}
public function load_eagerly($models=array(), $attributes=array(), $includes, Table $table)
{
$this->set_keys($table->class->name);
$this->query_and_attach_related_models_eagerly($table,$models,$attributes,$includes,$this->foreign_key, $table->pk);
}
}
/**
* One-to-one relationship.
*
* <code>
* # Table name: states
* # Primary key: id
* class State extends ActiveRecord\Model {}
*
* # Table name: people
* # Foreign key: state_id
* class Person extends ActiveRecord\Model {
* static $has_one = array(array('state'));
* }
* </code>
*
* @package ActiveRecord
* @see http://www.phpactiverecord.org/guides/associations
*/
class HasOne extends HasMany
{
}
/**
* @todo implement me
* @package ActiveRecord
* @see http://www.phpactiverecord.org/guides/associations
*/
class HasAndBelongsToMany extends AbstractRelationship
{
public function __construct($options=array())
{
/* options =>
* join_table - name of the join table if not in lexical order
* foreign_key -
* association_foreign_key - default is {assoc_class}_id
* uniq - if true duplicate assoc objects will be ignored
* validate
*/
}
public function load(Model $model)
{
}
}
/**
* Belongs to relationship.
*
* <code>
* class School extends ActiveRecord\Model {}
*
* class Person extends ActiveRecord\Model {
* static $belongs_to = array(
* array('school')
* );
* }
* </code>
*
* Example using options:
*
* <code>
* class School extends ActiveRecord\Model {}
*
* class Person extends ActiveRecord\Model {
* static $belongs_to = array(
* array('school', 'primary_key' => 'school_id')
* );
* }
* </code>
*
* @package ActiveRecord
* @see valid_association_options
* @see http://www.phpactiverecord.org/guides/associations
*/
class BelongsTo extends AbstractRelationship
{
public function __construct($options=array())
{
parent::__construct($options);
if (!$this->class_name)
$this->set_inferred_class_name();
//infer from class_name
if (!$this->foreign_key)
$this->foreign_key = array(Inflector::instance()->keyify($this->class_name));
}
public function __get($name)
{
if($name === 'primary_key' && !isset($this->primary_key)) {
$this->primary_key = array(Table::load($this->class_name)->pk[0]);
}
return $this->$name;
}
public function load(Model $model)
{
$keys = array();
$inflector = Inflector::instance();
foreach ($this->foreign_key as $key)
$keys[] = $inflector->variablize($key);
if (!($conditions = $this->create_conditions_from_keys($model, $this->primary_key, $keys)))
return null;
$options = $this->unset_non_finder_options($this->options);
$options['conditions'] = $conditions;
$class = $this->class_name;
return $class::first($options);
}
public function load_eagerly($models=array(), $attributes, $includes, Table $table)
{
$this->query_and_attach_related_models_eagerly($table,$models,$attributes,$includes, $this->primary_key,$this->foreign_key);
}
}