forked from robuust/craft-reverserelations
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseEntries.php
209 lines (182 loc) · 6.39 KB
/
ReverseEntries.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
<?php
namespace robuust\reverserelations\fields;
use Craft;
use craft\base\Element;
use craft\base\ElementInterface;
use craft\base\Field;
use craft\behaviors\EventBehavior;
use craft\db\Query;
use craft\db\Table as DbTable;
use craft\elements\db\ElementQuery;
use craft\events\CancelableEvent;
use craft\fields\BaseRelationField;
use craft\fields\Entries;
use craft\helpers\Db;
use craft\helpers\StringHelper;
/**
* Reverse Relations Entries Field.
*
* @author Bob Olde Hampsink <bob@robuust.digital>
* @copyright Copyright (c) 2019, Robuust
* @license MIT
*
* @see https://robuust.digital
*/
class ReverseEntries extends Entries
{
use ReverseRelationsTrait;
/**
* {@inheritdoc}
*/
public static function displayName(): string
{
return Craft::t('reverserelations', 'Reverse Entry Relations');
}
public static function dbType(): array|string|null
{
return null;
}
/**
* {@inheritdoc}
*/
public function normalizeValue($value, ?ElementInterface $element = null): mixed
{
// Use the canonical element
if ($element) {
$element = $element->getCanonical();
}
/** @var Element|null $element */
$query = parent::normalizeValue($value, $element);
// Overwrite inner join to switch sourceId and targetId
if (!is_array($value) && $value !== '' && $element && $element->id) {
$targetField = Craft::$app->fields->getFieldByUid($this->targetFieldId);
$relationsAlias = sprintf('relations_%s', StringHelper::randomString(10));
$query->attachBehavior(BaseRelationField::class, new EventBehavior([
ElementQuery::EVENT_AFTER_PREPARE => function (
CancelableEvent $event,
ElementQuery $query,
) use ($element, $relationsAlias, $targetField) {
// Make these changes directly on the prepared queries, so `sortOrder` doesn't ever make it into
foreach ([$query->query, $query->subQuery] as $q) {
$q->innerJoin(
[$relationsAlias => DbTable::RELATIONS],
[
'and',
"[[{$relationsAlias}.sourceId]] = [[elements.id]]",
[
"{$relationsAlias}.targetId" => $element->id,
"{$relationsAlias}.fieldId" => $targetField->id,
],
[
'or',
["{$relationsAlias}.sourceSiteId" => null],
["{$relationsAlias}.sourceSiteId" => $element->siteId],
],
]
);
}
},
]));
$inputSourceIds = $this->inputSourceIds();
if ($inputSourceIds !== '*') {
$query->where(['entries.sectionId' => $inputSourceIds]);
}
}
return $query;
}
/**
* Get original relations so we can diff those
* with the new value and find out which ones need to be deleted.
*
* {@inheritdoc}
*/
public function beforeElementSave(ElementInterface $element, bool $isNew): bool
{
if (!$isNew || $element->getIsDerivative()) {
// Get cached element
$entry = Craft::$app->getEntries()->getEntryById($element->getCanonicalId(), $element->siteId);
// Get old sources
if ($entry && $entry->{$this->handle}) {
$this->oldSources = $entry->{$this->handle}->anyStatus()->all();
}
}
return parent::beforeElementSave($element, $isNew);
}
/**
* {@inheritdoc}
*/
public function getEagerLoadingMap(array $sourceElements): array|false|null
{
$targetField = Craft::$app->fields->getFieldByUid($this->targetFieldId);
/** @var Element|null $firstElement */
$firstElement = $sourceElements[0] ?? null;
// Get the source element IDs
$sourceElementIds = [];
foreach ($sourceElements as $sourceElement) {
$sourceElementIds[] = $sourceElement->id;
}
// Return any relation data on these elements, defined with this field
$map = (new Query())
->select(['sourceId as target', 'targetId as source'])
->from('{{%relations}} relations')
->innerJoin('{{%entries}} entries', '[[relations.sourceId]] = [[entries.id]]')
->where([
'and',
[
'fieldId' => $targetField->id,
'targetId' => $sourceElementIds,
],
[
'or',
['sourceSiteId' => $firstElement ? $firstElement->siteId : null],
['sourceSiteId' => null],
],
])
->where(['entries.sectionId' => $this->inputSourceIds()])
->orderBy(['sortOrder' => SORT_ASC])
->all();
// Figure out which target site to use
$targetSite = $this->targetSiteId($firstElement);
return [
'elementType' => static::elementType(),
'map' => $map,
'criteria' => [
'siteId' => $targetSite,
],
];
}
/**
* Get available fields.
*
* @return array
*/
protected function getFields(): array
{
$fields = [];
/** @var Field $field */
foreach (Craft::$app->fields->getAllFields(false) as $field) {
if ($field instanceof Entries && !($field instanceof $this)) {
$fields[$field->uid] = $field->name.' ('.$field->handle.')';
}
}
return $fields;
}
/**
* Get allowed input source ids.
*
* @return array|string
*/
private function inputSourceIds(): array|string
{
$inputSources = $this->getInputSources();
if ($inputSources == '*') {
return $inputSources;
}
$sources = [];
foreach ($inputSources as $source) {
list($type, $uid) = explode(':', $source);
$sources[] = $uid;
}
return Db::idsByUids(DbTable::SECTIONS, $sources);
}
}