This repository was archived by the owner on Jun 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathbuildQuery.js
More file actions
61 lines (52 loc) · 2.18 KB
/
buildQuery.js
File metadata and controls
61 lines (52 loc) · 2.18 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
'use strict'
const Method = require('../Methods/Method')
const Builder = require('../../Builder')
const NonCapture = require('../../Builder/NonCapture')
const SyntaxException = require('../../Exceptions/Syntax')
/**
* After the query was resolved, it can be built and thus executed.
*
* @param array $query
* @param Builder|null $builder If no Builder is given, the default Builder will be taken.
* @return Builder
* @throws SyntaxException
*/
function buildQuery(query, builder = new Builder()) {
for (let i = 0; i < query.length; i++) {
const method = query[i]
if (Array.isArray(method)) {
builder.and(buildQuery(method, new NonCapture()))
continue
}
if (!method instanceof Method) {
// At this point, there should only be methods left, since all parameters are already taken care of.
// If that's not the case, something didn't work out.
throw new SyntaxException(`Unexpected statement: ${method}`)
}
const parameters = []
// If there are parameters, walk through them and apply them if they don't start a new method.
while (query[i + 1] && !(query[i + 1] instanceof Method)) {
parameters.push(query[i + 1])
// Since the parameters will be appended to the method object, they are already parsed and can be
// removed from further parsing. Don't use unset to keep keys incrementing.
query.splice(i + 1, 1)
}
try {
// Now, append that method to the builder object.
method.setParameters(parameters).callMethodOn(builder)
} catch (e) {
const lastIndex = parameters.length - 1
if (Array.isArray(parameters[lastIndex])) {
if (lastIndex !== 0) {
method.setParameters(parameters.slice(0, lastIndex))
}
method.callMethodOn(builder)
builder.and(buildQuery(parameters[lastIndex], new NonCapture()))
} else {
throw new SyntaxException(`Invalid parameter given for ${method.origin}`)
}
}
}
return builder
}
module.exports = buildQuery