-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathAbstractRelationship.php
More file actions
406 lines (342 loc) · 13.7 KB
/
AbstractRelationship.php
File metadata and controls
406 lines (342 loc) · 13.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
<?php
namespace ActiveRecord\Relationship;
use function ActiveRecord\all;
use function ActiveRecord\classify;
use ActiveRecord\Exception\RelationshipException;
use function ActiveRecord\has_absolute_namespace;
use ActiveRecord\Inflector;
use ActiveRecord\Model;
use ActiveRecord\Reflections;
use ActiveRecord\Relation;
use ActiveRecord\Table;
use ActiveRecord\Utils;
use ActiveRecord\WhereClause;
/**
* Abstract class that all relationships must extend from.
*
* @phpstan-import-type Attributes from Model
*
* @see http://www.phpactiverecord.org/guides/associations
*/
abstract class AbstractRelationship
{
/**
* Name to be used that will trigger call to the relationship.
*/
public string $attribute_name;
/**
* Class name of the associated model.
*
* @var class-string
*/
public string $class_name;
/**
* Name of the foreign key.
*
* @var string[]
*/
public array $foreign_key = [];
/**
* Options of the relationship.
*
* @var array<string, mixed>
*/
protected array $options = [];
/**
* List of valid options for relationships.
*
* @var list<string>
*/
protected static $valid_association_options = [
'association_foreign_key',
'class_name',
'foreign_key',
'conditions',
'select',
'join_table',
'readonly',
'namespace'
];
/**
* Constructs a relationship.
*
* @param array<mixed> $options Options for the relationship (see {@link valid_association_options})
*/
public function __construct(string $attribute_name, array $options = [])
{
$this->attribute_name = $attribute_name;
$this->options = $this->merge_association_options($options);
$this->options['conditions'] = [];
if (isset($options['conditions'])) {
$this->options['conditions'][] = WhereClause::from_arg($options['conditions']);
}
if (isset($this->options['class_name'])) {
$this->set_class_name($this->inferred_class_name($this->options['class_name']));
}
$this->attribute_name = strtolower(Inflector::variablize($this->attribute_name));
$this->foreign_key = (array) ($this->options['foreign_key'] ?? []);
}
protected function get_table(): Table
{
return Table::load($this->class_name);
}
/**
* @param list<Model> $models of model objects
* @param list<Attributes> $attributes of attributes from $models
* @param list<mixed> $includes of eager load directives
*/
abstract public function load_eagerly(array $models, array $attributes, array $includes, Table $table): void;
/**
* What is this relationship's cardinality?
*/
public function is_poly(): bool
{
return false;
}
/**
* 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 list<Model> $models of model objects
* @param list<Attributes> $attributes of attributes from $models
* @param array<mixed> $includes of eager load directives
* @param list<string> $query_keys -> key(s) to be queried for on included/related table
* @param list<string> $model_values_keys -> key(s)/value(s) to be used in query from model which is including
*/
protected function query_and_attach_related_models_eagerly(Table $table, array $models, array $attributes, array $includes = [], array $query_keys = [], array $model_values_keys = []): void
{
$values = [];
$options = $this->options;
$query_key = $query_keys[0];
$model_values_key = $model_values_keys[0];
foreach ($attributes as $value) {
$values[] = $value[Inflector::variablize($model_values_key)];
}
$values = [$values];
$options['conditions'] ??= [];
$options['conditions'][] = WhereClause::from_underscored_string($table->conn, $query_key, $values);
if (!empty($includes)) {
$options['include'] = $includes;
}
if ($this instanceof HasMany && !empty($options['through'])) {
// save old keys as we will be resetting 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;
}
assert(class_exists($class));
$through_table = Table::load($class);
} else {
$class = $options['class_name'];
if (isset($this->options['namespace']) && !class_exists($class)) {
$class = $this->options['namespace'] . '\\' . $class;
}
$relation = Table::load($class)->get_relationship($options['through']);
assert(!is_null($relation));
$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;
}
$class = $this->class_name;
$rel = new Relation($class, [], $options);
$related_models = $rel->to_a();
$used_models_map = [];
$related_models_map = [];
$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);
}
}
}
/**
* Checks if the given string matches this relationship's attribute name.
*
* @param string $other the string to compare with this relationship's attribute name
*/
public function is_string_this_relationship(string $other): bool
{
return $this->attribute_name === $other;
}
/**
* Creates a new instance of specified {@link Model} with the attributes pre-loaded.
*
* @param Model $model The model which holds this association
* @param Attributes $attributes Hash containing attributes to initialize the model with
* @param bool $guard_attributes Set to true to guard protected/non-accessible attributes on the new instance
*/
public function build_association(Model $model, array $attributes = [], bool $guard_attributes = true): Model
{
$class_name = $this->class_name;
$model = new $class_name($attributes, $guard_attributes);
assert($model instanceof Model);
return $model;
}
/**
* Creates a new instance of {@link Model} and invokes save.
*
* @param Model $model The model which holds this association
* @param Attributes $attributes Hash containing attributes to initialize the model with
* @param bool $guard_attributes Set to true to guard protected/non-accessible attributes on the new instance
*/
public function create_association(Model $model, array $attributes = [], bool $guard_attributes = true): Model
{
$new_record = static::build_association($model, $attributes, true);
$new_record->save();
return $this->append_record_to_associate($model, $new_record);
}
protected function append_record_to_associate(Model $associate, Model $record): Model
{
$association = &$associate->{$this->attribute_name};
if ($this->is_poly()) {
$association[] = $record;
} else {
$association = $record;
}
return $record;
}
/**
* @param array<string,mixed> $options
*
* @return array<string,mixed>
*/
protected function merge_association_options(array $options): array
{
$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;
}
/**
* @return class-string
*/
protected function inferred_class_name(string $rawName): string
{
$name = $rawName;
if (!class_exists($name) && !has_absolute_namespace($name) && isset($this->options['namespace'])) {
if (!isset($this->options['class_name'])) {
$name = classify($name, $this instanceof HasMany);
}
$name = $this->options['namespace'] . '\\' . $name;
}
if (!class_exists($name)) {
throw new \ReflectionException('Unknown class name: ' . $name);
}
return $name;
}
/**
* @param class-string $class_name
*
* @throws RelationshipException
* @throws \ActiveRecord\Exception\ActiveRecordException
*/
protected function set_class_name(string $class_name): void
{
$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;
}
/**
* @param list<string> $condition_keys
* @param list<string> $value_keys
*
* @return list<mixed>
*/
protected function create_conditions_from_keys(Model $model, array $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[] = WhereClause::from_underscored_string(
Table::load(get_class($model))->conn,
$condition_string,
$condition_values
);
return $conditions; // 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, bool $using_through = false, ?string $alias = null)
{
if ($using_through) {
$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
/* @phpstan-ignore-next-line */
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];
}
} elseif ($this instanceof BelongsTo) {
$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;
}
assert(isset($foreign_key), 'foreign key must be set');
assert(isset($join_primary_key), 'join primary key must be set');
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
*
* @return Model|array<Model>|null
*/
abstract public function load(Model $model): mixed;
}