forked from IvanMathy/Boop
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request IvanMathy#210 from jtolj/js-to-php
Add script to convert JS arrays/objects to PHP associative array.
- Loading branch information
Showing
1 changed file
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
/** | ||
{ | ||
"api":1, | ||
"name":"JS To PHP", | ||
"description":"Convert JS Object or Array to PHP.", | ||
"author":"jtolj", | ||
"icon":"elephant", | ||
"tags":"js,php,convert" | ||
} | ||
**/ | ||
|
||
function main(state) { | ||
const js = state.text.replace(/\n\n\/\/ Result:[\s\S]*$/, ''); | ||
let output = ''; | ||
try { | ||
const result = new Function(`return ${js}`)(); | ||
output = convert(result) + ';'; | ||
} catch (error) { | ||
state.postError(error.message); | ||
} | ||
state.text = js + "\n\n// Result:\n\n" + output; | ||
} | ||
|
||
const toPHP = function (value, indentation) { | ||
switch (typeof value) { | ||
case 'undefined': | ||
value = null; | ||
break; | ||
case 'object': | ||
if(value !== null) { | ||
value = convert(value, indentation + 1); | ||
} | ||
break; | ||
case 'string': | ||
value = value.replace(/"/g, '\\"'); | ||
value = `"${value}"`; | ||
break; | ||
} | ||
|
||
return value; | ||
}; | ||
|
||
const convert = function (result, indentation = 1) { | ||
const isArray = Array.isArray(result); | ||
let str = Object.keys(result).reduce((acc, key) => { | ||
const value = toPHP(result[key], indentation); | ||
acc += ' '.repeat(indentation * 4); | ||
acc += isArray ? value : `'${key}' => ${value}`; | ||
acc += ',\n'; | ||
return acc; | ||
}, ''); | ||
const endingIndentation = ' '.repeat((indentation - 1) * 4); | ||
return `[\n${str}${endingIndentation}]`; | ||
}; |