Repository navigation
Expand file tree
/
Copy pathDataFeed.php
More file actions
266 lines (220 loc) · 6.29 KB
/
Copy pathDataFeed.php
File metadata and controls
266 lines (220 loc) · 6.29 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
<?php namespace October\Rain\Database;
use Db;
use Str;
use Closure;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Exception;
/**
* Model Data Feed class.
*
* Combine various models in to a single feed.
*
* @package october\database
* @author Alexey Bobkov, Samuel Georges
*/
class DataFeed
{
/**
* @var string The attribute to use for each model tag name.
*/
public $tagVar = 'tag_name';
/**
* @var string An alias to use for each entries timestamp attribute.
*/
public $sortVar = 'order_by_column_name';
/**
* @var string Default sorting attribute.
*/
public $sortField = 'id';
/**
* @var string Default sorting direction.
*/
public $sortDirection = 'desc';
/**
* @var string Limits the number of results.
*/
public $limitCount = null;
/**
* @var string Set the limit offset.
*/
public $limitOffset = null;
/**
* @var array Model collection pre-query.
*/
protected $collection = [];
/**
* @var Builder Cache containing the generic collection union query.
*/
protected $queryCache;
/**
* @var bool
*/
public $removeDuplicates = false;
/**
* Add a new Builder to the feed collection
*/
public function add($tag, $item, $orderBy = null)
{
if ($item instanceof Closure) {
$item = call_user_func($item);
}
if (!$item)
return;
$keyName = $item instanceof EloquentModel
? $item->getKeyName()
: $item->getModel()->getKeyName();
$this->collection[$tag] = compact('item', 'orderBy', 'keyName');
// Reset the query cache
$this->queryCache = null;
return $this;
}
/**
* Count the number of results from the generic union query
*/
public function count()
{
$query = $this->processCollection();
$result = Db::table(Db::raw("(".$query->toSql().") as records"))->select(Db::raw("COUNT(*) as total"))->first();
return $result->total;
}
/**
* Executes the generic union query and eager loads the results in to the added models
*/
public function get()
{
$query = $this->processCollection();
/*
* Apply constraints to the entire query
*/
$query->limit($this->limitCount);
if ($this->limitOffset) {
$query->offset($this->limitOffset);
}
$query->orderBy($this->sortVar, $this->sortDirection);
$records = $query->get();
/*
* Build a collection of class names and IDs needed
*/
$mixedArray = [];
foreach ($records as $record) {
$tagName = $record->{$this->tagVar};
$mixedArray[$tagName][] = $record->id;
}
/*
* Eager load the data collection
*/
$collectionArray = [];
foreach ($mixedArray as $tagName => $ids) {
$obj = $this->getModelByTag($tagName);
$keyName = $this->getKeyNameByTag($tagName);
$collectionArray[$tagName] = $obj->whereIn($keyName, $ids)->get();
}
/*
* Now load the data objects in to a final array
*/
$dataArray = [];
foreach ($records as $record) {
$tagName = $record->{$this->tagVar};
$obj = $collectionArray[$tagName]->find($record->id);
$obj->{$this->tagVar} = $tagName;
$dataArray[] = $obj;
}
return new Collection($dataArray);
}
/**
* Returns the SQL expression used in the generic union
*/
public function toSql()
{
$query = $this->processCollection();
return $query->toSql();
}
/**
* Sets the default sorting field and direction.
*/
public function orderBy($field, $direction = null)
{
$this->sortField = $field;
if ($direction) {
$this->sortDirection = $direction;
}
return $this;
}
/**
* Limits the number of results displayed.
*/
public function limit($count, $offset = null)
{
$this->limitCount = $count;
if ($offset) {
$this->limitOffset = $offset;
}
return $this;
}
//
// Internals
//
/**
* Creates a generic union query of each added collection
*/
protected function processCollection()
{
if ($this->queryCache !== null)
return $this->queryCache;
$lastQuery = null;
foreach ($this->collection as $tag => $data)
{
extract($data);
$cleanQuery = clone $item->getQuery();
$model = $item->getModel();
$sorting = $model->getTable() . '.';
$sorting .= $orderBy ?: $this->sortField;
/*
* Flush the select, add ID and tag
*/
$cleanQuery = $cleanQuery->select(Db::raw($keyName." as id"));
$cleanQuery = $cleanQuery->addSelect(Db::raw("(SELECT '".$tag."') as ".$this->tagVar));
$cleanQuery = $cleanQuery->addSelect(Db::raw("(SELECT ".$sorting.") as ".$this->sortVar));
/*
* Union this query with the previous one
*/
if ($lastQuery) {
if ($this->removeDuplicates)
$cleanQuery = $lastQuery->union($cleanQuery);
else
$cleanQuery = $lastQuery->unionAll($cleanQuery);
}
$lastQuery = $cleanQuery;
}
return $this->queryCache = $lastQuery;
}
/**
* Returns a prepared model by its tag name.
* @return Model
*/
protected function getModelByTag($tag)
{
extract($this->getDataByTag($tag));
return $item;
}
/**
* Returns a model key name by its tag name.
* @return Model
*/
protected function getKeyNameByTag($tag)
{
extract($this->getDataByTag($tag));
return $keyName;
}
/**
* Returns a data stored about an item by its tag name.
* @return array
*/
protected function getDataByTag($tag)
{
if (!$data = array_get($this->collection, $tag)) {
throw new Exception('Unable to find model in collection with tag: '. $tag);
}
return $data;
}
}