Skip to content

Commit

Permalink
Merge pull request IvanMathy#210 from jtolj/js-to-php
Browse files Browse the repository at this point in the history
Add script to convert JS arrays/objects to PHP associative array.
  • Loading branch information
IvanMathy authored Mar 28, 2021
2 parents 3f6ef0c + 79d1a49 commit 21544d1
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions Scripts/jsToPhp.js
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}]`;
};

0 comments on commit 21544d1

Please sign in to comment.