-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathHasOneSql.php
More file actions
202 lines (166 loc) · 8.3 KB
/
HasOneSql.php
File metadata and controls
202 lines (166 loc) · 8.3 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
<?php
declare(strict_types=1);
namespace Atk4\Data\Reference;
use Atk4\Data\Exception;
use Atk4\Data\Field\SqlExpressionField;
use Atk4\Data\Model;
class HasOneSql extends HasOne
{
/**
* @param ($theirFieldIsTitle is true ? null : string) $theirFieldName
* @param array<string, mixed> $defaults
*/
private function _addField(string $fieldName, bool $theirFieldIsTitle, ?string $theirFieldName, array $defaults): SqlExpressionField
{
$ourModel = $this->getOurModel();
$fieldExpression = $ourModel->addExpression($fieldName, array_merge([
'expr' => function (Model $ourModel) use ($theirFieldIsTitle, $theirFieldName) {
$theirModel = $ourModel->refLink($this->link);
if ($theirFieldIsTitle) {
$theirFieldName = $theirModel->titleField;
}
return $theirModel->action('field', [$theirFieldName]);
},
], $defaults, [
// allow to set our field value by an imported foreign field, but only when the our field value is null
'readOnly' => false,
]));
$this->onHookToOurModel(Model::HOOK_BEFORE_SAVE, function (Model $ourEntity) use ($fieldName, $theirFieldIsTitle, $theirFieldName) {
if ($ourEntity->isDirty($fieldName)) {
$theirModel = $this->createTheirModel();
if ($theirFieldIsTitle) {
$theirFieldName = $theirModel->titleField;
}
// when our field is not null or dirty too, update nothing, but check if the imported
// field was changed to expected value implied by the relation
if ($ourEntity->isDirty($this->getOurFieldName()) || $ourEntity->get($this->getOurFieldName()) !== null) {
$importedFieldValue = $ourEntity->get($fieldName);
$expectedTheirEntity = $theirModel->loadBy($this->getTheirFieldName($theirModel), $ourEntity->get($this->getOurFieldName()));
if (!$expectedTheirEntity->compare($theirFieldName, $importedFieldValue)) {
throw (new Exception('Imported field was changed to an unexpected value'))
->addMoreInfo('ourFieldName', $this->getOurFieldName())
->addMoreInfo('theirFieldName', $this->getTheirFieldName($theirModel))
->addMoreInfo('importedFieldName', $fieldName)
->addMoreInfo('sourceFieldName', $theirFieldName)
->addMoreInfo('importedFieldValue', $importedFieldValue)
->addMoreInfo('sourceFieldValue', $expectedTheirEntity->get($theirFieldName));
}
} else {
$newTheirEntity = $theirModel->loadBy($theirFieldName, $ourEntity->get($fieldName));
$ourEntity->set($this->getOurFieldName(), $newTheirEntity->get($this->getTheirFieldName($theirModel)));
$ourEntity->_unset($fieldName);
}
}
}, [], 20);
return $fieldExpression;
}
private function getLinkNameWithoutReferenceSuffix(Model $theirModel): string
{
$ourModel = $this->getOurModel();
$theirFieldName = $this->getTheirFieldName($theirModel);
return preg_replace('~_(' . preg_quote($theirFieldName, '~') . '|' . preg_quote($ourModel->idField, '~') . '|id)$~', '', $this->link);
}
private function getOurFieldCaptionWithoutReferenceSuffix(Model $theirModel): string
{
$ourModel = $this->getOurModel();
$theirField = $theirModel->getField($this->getTheirFieldName($theirModel));
return preg_replace('~ (' . preg_quote($theirField->getCaption(), '~') . '|' . preg_quote($ourModel->getIdField()->getCaption(), '~') . '|ID)$~i', '', $this->getOurField()->getCaption());
}
/**
* Creates expression which sub-selects a field inside related model.
*
* @param array<string, mixed> $defaults
*/
public function addField(string $fieldName, ?string $theirFieldName = null, array $defaults = []): SqlExpressionField
{
if ($theirFieldName === null) {
$theirFieldName = $fieldName;
}
$ourModel = $this->getOurModel();
$analysingTheirModel = $ourModel->getReference($this->link)->createAnalysingTheirModel();
// if caption/type is not defined in $defaults then infer it from their field
$analysingTheirField = $analysingTheirModel->getField($theirFieldName);
$defaults['type'] ??= $analysingTheirField->type;
$defaults['enum'] ??= $analysingTheirField->enum;
$defaults['values'] ??= $analysingTheirField->values;
$defaults['caption'] ??= $this->getOurFieldCaptionWithoutReferenceSuffix($analysingTheirModel) . ' ' . $analysingTheirField->getCaption();
$defaults['ui'] = array_merge($defaults['ui'] ?? $analysingTheirField->ui, ['editable' => false]);
$fieldExpression = $this->_addField($fieldName, false, $theirFieldName, $defaults);
return $fieldExpression;
}
/**
* Add multiple expressions by calling addField several times. Fields
* may contain 3 types of elements:.
*
* ['name', 'surname'] - will import those fields as-is
* ['full_name' => 'name', 'day_of_birth' => ['dob', 'type' => 'date']] - use alias and options
* [['dob', 'type' => 'date']] - use options
*
* @param array<string, array<mixed>>|array<int, string> $fields
* @param array<string, mixed> $defaults
*
* @return $this
*/
public function addFields(array $fields = [], array $defaults = [])
{
foreach ($fields as $ourFieldName => $ourFieldDefaults) {
$ourFieldDefaults = array_merge($defaults, (array) $ourFieldDefaults);
$theirFieldName = $ourFieldDefaults[0] ?? null;
unset($ourFieldDefaults[0]);
if (is_int($ourFieldName)) {
$ourFieldName = $theirFieldName;
}
$this->addField($ourFieldName, $theirFieldName, $ourFieldDefaults);
}
return $this;
}
#[\Override]
public function ref(Model $ourModelOrEntity, array $defaults = []): Model
{
$this->assertOurModelOrEntity($ourModelOrEntity);
$theirModel = parent::ref($ourModelOrEntity, $defaults);
if ($ourModelOrEntity->isEntity() && $this->getOurFieldValue($ourModelOrEntity) !== null) {
// materialized condition already added in parent/HasOne class
} else {
// handle deep traversal using an expression
$ourFieldExpression = $ourModelOrEntity->action('field', [$this->getOurField()]);
$theirModel->getModel(true)
->addCondition($this->getTheirFieldName($theirModel), 'in', $ourFieldExpression);
}
return $theirModel;
}
/**
* Creates model that can be used for generating sub-query actions.
*
* @param array<string, mixed> $defaults
*/
public function refLink(array $defaults = []): Model
{
$theirModel = $this->createTheirModel($defaults);
$theirModel->addCondition($this->getTheirFieldName($theirModel), $this->referenceOurValue());
return $theirModel;
}
/**
* Add a title of related entity as expression to our field.
*
* $order->hasOne('user_id', ['model' => [User::class]])
* ->addTitle();
*
* This will add expression 'user' equal to ref('user_id')['name'];
*
* @param array<string, mixed> $defaults
*/
public function addTitle(array $defaults = []): SqlExpressionField
{
$ourModel = $this->getOurModel();
$analysingTheirModel = $ourModel->getReference($this->link)->createAnalysingTheirModel();
$fieldName = $defaults['field'] ?? $this->getLinkNameWithoutReferenceSuffix($analysingTheirModel);
$defaults['ui'] = array_merge(['visible' => true], $defaults['ui'] ?? [], ['editable' => false]);
$fieldExpression = $this->_addField($fieldName, true, null, $defaults);
// set ID field as not visible in grid by default
if (!array_key_exists('visible', $this->getOurField()->ui)) {
$this->getOurField()->ui['visible'] = false;
}
return $fieldExpression;
}
}