/
SelectableAssociationTrait.php
255 lines (226 loc) · 7.42 KB
/
SelectableAssociationTrait.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
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace Cake\ORM\Association;
use Cake\Database\Expression\TupleComparison;
/**
* Represents a type of association that that can be fetched using another query
*/
trait SelectableAssociationTrait {
/**
* Returns true if the eager loading process will require a set of parent table's
* primary keys in order to use them as a filter in the finder query.
*
* @param array $options
* @return boolean true if a list of keys will be required
*/
public function requiresKeys($options = []) {
$strategy = isset($options['strategy']) ? $options['strategy'] : $this->strategy();
return $strategy === $this::STRATEGY_SELECT;
}
/**
* {@inheritdoc}
*
*/
public function eagerLoader(array $options) {
$options = $options + $this->_defaultOptions();
$queryBuilder = false;
if (!empty($options['queryBuilder'])) {
$queryBuilder = $options['queryBuilder'];
unset($options['queryBuilder']);
}
$fetchQuery = $this->_buildQuery($options);
if ($queryBuilder) {
$fetchQuery = $queryBuilder($fetchQuery);
}
$resultMap = $this->_buildResultMap($fetchQuery, $options);
return $this->_resultInjector($fetchQuery, $resultMap, $options);
}
/**
* Returns the default options to use for the eagerLoader
*
* @return array
*/
protected function _defaultOptions() {
return [
'foreignKey' => $this->foreignKey(),
'conditions' => [],
'strategy' => $this->strategy(),
'nestKey' => $this->_name
];
}
/**
* Auxiliary function to construct a new Query object to return all the records
* in the target table that are associated to those specified in $options from
* the source table
*
* @param array $options options accepted by eagerLoader()
* @return \Cake\ORM\Query
* @throws \InvalidArgumentException When a key is required for associations but not selected.
*/
protected function _buildQuery($options) {
$target = $this->target();
$alias = $target->alias();
$key = $this->_linkField($options);
$filter = $options['keys'];
if ($options['strategy'] === $this::STRATEGY_SUBQUERY) {
$filter = $this->_buildSubquery($options['query']);
}
$fetchQuery = $this
->find('all')
->where($options['conditions'])
->eagerLoaded(true)
->hydrate($options['query']->hydrate());
$fetchQuery = $this->_addFilteringCondition($fetchQuery, $key, $filter);
if (!empty($options['fields'])) {
$fields = $fetchQuery->aliasFields($options['fields'], $alias);
if (!in_array($key, $fields)) {
throw new \InvalidArgumentException(
sprintf('You are required to select the "%s" field', $key)
);
}
$fetchQuery->select($fields);
}
if (!empty($options['sort'])) {
$fetchQuery->order($options['sort']);
}
if (!empty($options['contain'])) {
$fetchQuery->contain($options['contain']);
}
if (!empty($options['queryBuilder'])) {
$options['queryBuilder']($fetchQuery);
}
return $fetchQuery;
}
/**
* Appends any conditions required to load the relevant set of records in the
* target table query given a filter key and some filtering values.
*
* @param \Cake\ORM\Query $query Target table's query
* @param string $key the fields that should be used for filtering
* @param mixed $filter the value that should be used to match for $key
* @return \Cake\ORM\Query
*/
protected function _addFilteringCondition($query, $key, $filter) {
if (is_array($key)) {
$types = [];
$defaults = $query->defaultTypes();
foreach ($key as $k) {
if (isset($defaults[$k])) {
$types[] = $defaults[$k];
}
}
return $query->andWhere(new TupleComparison($key, $filter, $types, 'IN'));
}
return $query->andWhere([$key . ' IN' => $filter]);
}
/**
* Generates a string used as a table field that contains the values upon
* which the filter should be applied
*
* @param array $options
* @return string|array
*/
protected abstract function _linkField($options);
/**
* Builds a query to be used as a condition for filtering records in the
* target table, it is constructed by cloning the original query that was used
* to load records in the source table.
*
* @param \Cake\ORM\Query $query the original query used to load source records
* @return \Cake\ORM\Query
*/
protected function _buildSubquery($query) {
$filterQuery = clone $query;
$filterQuery->limit(null);
$filterQuery->contain([], true);
$joins = $filterQuery->join();
foreach ($joins as $i => $join) {
if (strtolower($join['type']) !== 'inner') {
unset($joins[$i]);
}
}
$keys = (array)$query->repository()->primaryKey();
if ($this->type() === $this::MANY_TO_ONE) {
$keys = (array)$this->foreignKey();
}
$filterQuery->join($joins, [], true);
$fields = $query->aliasFields($keys);
return $filterQuery->select($fields, true);
}
/**
* Builds an array containing the results from fetchQuery indexed by
* the foreignKey value corresponding to this association.
*
* @param \Cake\ORM\Query $fetchQuery The query to get results from
* @param array $options The options passed to the eager loader
* @return array
*/
protected abstract function _buildResultMap($fetchQuery, $options);
/**
* Returns a callable to be used for each row in a query result set
* for injecting the eager loaded rows
*
* @param \Cake\ORM\Query $fetchQuery the Query used to fetch results
* @param array $resultMap an array with the foreignKey as keys and
* the corresponding target table results as value.
* @param array $options The options passed to the eagerLoader method
* @return \Closure
*/
protected function _resultInjector($fetchQuery, $resultMap, $options) {
$source = $this->source();
$sAlias = $source->alias();
$keys = $this->type() === $this::MANY_TO_ONE ?
$this->foreignKey() :
$source->primaryKey();
$sourceKeys = [];
foreach ((array)$keys as $key) {
$sourceKeys[] = key($fetchQuery->aliasField($key, $sAlias));
}
$nestKey = $options['nestKey'];
if (count($sourceKeys) > 1) {
return $this->_multiKeysInjector($resultMap, $sourceKeys, $nestKey);
}
$sourceKey = $sourceKeys[0];
return function($row) use ($resultMap, $sourceKey, $nestKey) {
if (isset($resultMap[$row[$sourceKey]])) {
$row[$nestKey] = $resultMap[$row[$sourceKey]];
}
return $row;
};
}
/**
* Returns a callable to be used for each row in a query result set
* for injecting the eager loaded rows when the matching needs to
* be done with multiple foreign keys
*
* @param array $resultMap A keyed arrays containing the target table
* @param array $sourceKeys An array with aliased keys to match
* @param string $nestKey The key under which results should be nested
* @return \Closure
*/
protected function _multiKeysInjector($resultMap, $sourceKeys, $nestKey) {
return function($row) use ($resultMap, $sourceKeys, $nestKey) {
$values = [];
foreach ($sourceKeys as $key) {
$values[] = $row[$key];
}
$key = implode(';', $values);
if (isset($resultMap[$key])) {
$row[$nestKey] = $resultMap[$key];
}
return $row;
};
}
}