-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
69 lines (65 loc) · 1.81 KB
/
index.js
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
var engine = require('php-parser')
var parser = new engine({
parser: { extractDoc: true },
ast: { withPositions: true },
})
/**
* The PHP array parser.
* @param {String} source The PHP source contents.
* @return {Object} The parsed contents.
*/
var parse = function (source) {
var ast = parser.parseEval(source)
var array = ast.children.find((child) => child.kind === 'array')
return parseValue(array)
}
/**
* Parse a PHP expression to JavaScript
* @param {Object} expr The AST PHP expression.
* @return {*} A JavaScript object or value.
*/
function parseValue(expr) {
switch(expr.kind) {
case 'array':
if (expr.items.length === 0) {
return [];
}
var isKeyed = expr.items.every((item) => item.key !== null)
var items = expr.items.map(parseValue)
if (isKeyed) {
items = items.reduce((acc, val) => Object.assign({}, acc, val), {})
}
return items
case 'entry':
if (expr.key) {
return { [parseKey(expr.key)]: parseValue(expr.value) }
}
return parseValue(expr.value)
case 'string':
return expr.value
case 'number':
return parseInt(expr.value, 10)
case 'boolean':
return expr.value
default:
throw new Error(`Unexpected PHP value: "${expr.kind}", details: ${JSON.stringify(expr)}`)
}
}
/**
* Parse a PHP expression to JavaScript
* @param {Object} expr The AST PHP expression.
* @return {*} A JavaScript object or value.
*/
function parseKey(expr) {
switch(expr.kind) {
case 'string':
return expr.value
case 'number':
return parseInt(expr.value, 10)
case 'boolean':
return expr.value ? 1 : 0;
default:
throw new Error(`Unexpected PHP key: "${expr.kind}", details: ${JSON.stringify(expr)}`)
}
}
module.exports = { parse }