-
Notifications
You must be signed in to change notification settings - Fork 243
Expand file tree
/
Copy pathExtendedPMQL.php
More file actions
244 lines (217 loc) · 8.76 KB
/
ExtendedPMQL.php
File metadata and controls
244 lines (217 loc) · 8.76 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
<?php
namespace ProcessMaker\Traits;
use Carbon\Carbon;
use Carbon\CarbonTimeZone;
use Illuminate\Database\Eloquent\Builder;
use ProcessMaker\Models\User;
use ProcessMaker\Query\Expression;
use ProcessMaker\Query\IntervalExpression;
use ProcessMaker\Query\Parser;
use ProcessMaker\Query\Processor;
use ProcessMaker\Query\Traits\PMQL;
use Throwable;
trait ExtendedPMQL
{
use PMQL {
PMQL::scopePMQL as parentScopePMQL;
}
protected $dataStoreTable = '';
protected $dataStoreColumns = [];
/**
* Setup the PMQL to use the data store table
*/
public function useDataStoreTable(Builder $query, string $table, array $map)
{
$this->dataStoreTable = $table;
$this->dataStoreColumns = [];
foreach ($map as $variable) {
$this->dataStoreColumns[$variable['name']] = $variable['column'];
}
// inner join to the data store table
if ($table) {
$query->join($table, $this->getTable() . '.id', '=', $table . '.process_request_id');
}
}
/**
* PMQL scope that extends the standard PMQL scope by supporting any custom
* aliases specified in the model.
*
* @param Builder $builder
* @param string $query
* @param callable $callback
*
* @return mixed
*/
public function scopePMQL(Builder $builder, string $query, ?callable $callback = null, ?User $user = null)
{
if (!$callback) {
// If a callback isn't passed to the scope, we handle it here
return $this->parentScopePMQL($builder, $query, function ($expression) use ($builder, $user) {
return $this->handle($expression, $builder, $user);
});
} else {
// If a callback is passed to the scope, we skip handling it here
return $this->parentScopePMQL($builder, $query, $callback);
}
}
public static function getFields($query)
{
$parser = new Parser;
$tree = $parser->parse($query);
$fields = [];
$fields = collect(self::getFromExpression($tree, $fields))
->flatten()
->unique();
return $fields;
}
private static function getFromExpression($values, $fields)
{
foreach ($values as $value) {
if ($value && !property_exists($value, 'field')) {
$fields[] = self::getFromExpression($value, $fields);
} else {
$fields[] = $value->field->getField();
}
}
return $fields;
}
/**
* Callback function to check for and handle any field aliases, value
* aliases, or field wildcards specified in the given model.
*
* @param Expression $expression
* @param Builder $builder
*
* @return mixed
*/
private function handle(Expression $expression, Builder $builder, ?User $user = null)
{
// Setup our needed variables
$field = $expression->field->field();
$model = $builder->getModel();
// use data store table if field is prefixed with "data." and the field is in the map
if (strpos($field, 'data.') === 0 && isset($this->dataStoreColumns[substr($field, 5)])) {
$variableName = substr($field, 5);
$columnName = $this->dataStoreColumns[$variableName];
$realFieldName = $this->dataStoreTable . '.' . $columnName;
$value = $this->parseValue($expression);
if ($value instanceof IntervalExpression) {
$value = $value->toEloquent();
}
return function ($query) use ($expression, $value, $realFieldName) {
switch ($expression->operator) {
case Expression::OPERATOR_IN:
$query->whereIn($realFieldName, $value);
break;
case Expression::OPERATOR_NOT_IN:
$query->whereNotIn($realFieldName, $value);
break;
default:
$query->where($realFieldName, $expression->operator, $value);
}
};
}
if (is_string($field)) {
// Parse our value
$value = $this->parseValue($expression);
// PMQL Interval expressions do not have values
if (method_exists($expression->value, 'setValue')) {
$expression->value->setValue($value);
}
// Title case our field name so we can suffix it to our method names
$fieldMethodName = ucfirst(strtolower($field));
// A field alias specifies that a field name used in a PMQL query
// translates to a different field name in our database.
$method = "fieldAlias{$fieldMethodName}";
if (method_exists($model, $method)) {
return $expression->field->setField($model->{$method}());
}
// A value alias specifies that a value must be parsed by a callback
// function if its field name matches a specific word.
$method = "valueAlias{$fieldMethodName}";
if (method_exists($model, $method)) {
if (is_array($value)) {
// For "IN" and "NOT IN" Operators, convert to a series of "where"s
return function ($query) use ($model, $method, $value, $expression, $builder, $user) {
$originalOperator = $expression->operator;
// Always use equal operator in alias methods because
// we can negate results with whereNotExists for "not in"
$expression->setOperator('=');
foreach ($value as $v) {
if ($originalOperator === Expression::OPERATOR_IN) {
$query->orWhere(
$model->{$method}($v, $expression, $builder, $user)
);
} else {
$query->whereNotExists(
$model->{$method}($v, $expression, $builder, $user)
);
}
}
};
} else {
return $model->{$method}($value, $expression, $builder, $user);
}
}
// A field wildcard passes any fields not caught by a field or value
// alias to a callback function for any needed processing. If the
// callback returns void, the PMQL is parsed as if there is
// no callback.
$method = 'fieldWildcard';
if (method_exists($model, $method)) {
return $model->{$method}($value, $expression, $builder, $user);
}
}
}
/**
* Set the value as a string if possible. Also convert to the logged-in
* user's timezone if the value is parsable by Carbon as a date.
*
* @param Expression $expression
*
* @return mixed
*/
private function parseValue($expression)
{
// Check the type of our value; set as string if possible
if (is_a($expression->value, 'ProcessMaker\\Query\\LiteralValue')) {
$value = $expression->value->value();
} elseif (is_a($expression->value, 'ProcessMaker\\Query\\ArrayValue')) {
$value = $expression->value->value();
} else {
$value = $expression->value;
}
// Check to see if the value is parsable as a date
if ((is_string($value) && strlen($value) > 1)) {
switch ($value) {
case $value instanceof IntervalExpression:
$value = $this->parseDate($value);
break;
default:
// Check to see if the value is a date/datetime formatted if not return original value
$isDateFormatted = Carbon::hasFormatWithModifiers($value, 'Y#m#d');
$isDateTimeFormatted = Carbon::hasFormatWithModifiers($value, 'Y#m#d H:i:s');
if ($isDateFormatted || $isDateTimeFormatted) {
$value = $this->parseDate($value);
}
break;
}
}
return $value;
}
private function parseDate($value)
{
try {
$parsed = Carbon::parse($value, auth()->user()->timezone);
if ($parsed->isMidnight()) {
return $parsed->toDateString();
} else {
$parsed->setTimezone(config('app.timezone'));
return $parsed->toDateTimeString();
}
} catch (Throwable $e) {
//Ignore parsing errors and just return the original
return $value;
}
}
}