locutus
Version:
Locutus other languages' standard libraries to JavaScript for fun and educational purposes
62 lines (61 loc) • 2.63 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.call_user_func_array = call_user_func_array;
const _callbackResolver_ts_1 = require("../_helpers/_callbackResolver.js");
const _phpRuntimeState_ts_1 = require("../_helpers/_phpRuntimeState.js");
const _phpTypes_ts_1 = require("../_helpers/_phpTypes.js");
function call_user_func_array(cb, parameters) {
// discuss at: https://locutus.io/php/call_user_func_array/
// original by: Thiago Mata (https://thiagomata.blog.com)
// revised by: Jon Hohle
// improved by: Brett Zamir (https://brett-zamir.me)
// improved by: Diplom@t (https://difane.com/)
// improved by: Brett Zamir (https://brett-zamir.me)
// note 1: Callback resolution intentionally avoids eval/new Function for security.
// example 1: call_user_func_array('isNaN', ['a'])
// returns 1: true
// example 2: call_user_func_array('isNaN', [1])
// returns 2: false
let func;
let scope = null;
try {
const resolved = (0, _callbackResolver_ts_1.resolvePhpCallable)(cb, { invalidMessage: 'invalid' });
func = resolved.fn;
scope = resolved.scope;
}
catch {
// Fall back to legacy-compatible callback resolution paths below.
}
if (!func && typeof cb === 'string') {
const globalCandidate = (0, _phpRuntimeState_ts_1.getPhpGlobalEntry)(cb);
if ((0, _phpTypes_ts_1.isPhpCallable)(globalCandidate)) {
func = globalCandidate;
}
}
else if (!func && Array.isArray(cb)) {
if (typeof cb[0] === 'string') {
const globalScope = (0, _phpRuntimeState_ts_1.getPhpGlobalEntry)(cb[0]);
if ((0, _phpTypes_ts_1.isObjectLike)(globalScope) || typeof globalScope === 'function') {
const method = (0, _phpRuntimeState_ts_1.getPhpObjectEntry)(globalScope, String(cb[1]));
if ((0, _phpTypes_ts_1.isPhpCallable)(method)) {
func = method;
}
scope = globalScope;
}
}
else if ((0, _phpTypes_ts_1.isObjectLike)(cb[0]) || typeof cb[0] === 'function') {
const method = (0, _phpRuntimeState_ts_1.getPhpObjectEntry)(cb[0], String(cb[1]));
if ((0, _phpTypes_ts_1.isPhpCallable)(method)) {
func = method;
}
scope = cb[0];
}
}
else if (!func && (0, _phpTypes_ts_1.isPhpCallable)(cb)) {
func = cb;
}
if (!func) {
throw new Error(String(cb) + ' is not a valid function');
}
return func.apply(scope, parameters);
}