locutus
Version:
Locutus other languages' standard libraries to JavaScript for fun and educational purposes
47 lines (46 loc) • 2.08 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolvePhpCallable = resolvePhpCallable;
exports.resolveNumericComparator = resolveNumericComparator;
const _phpRuntimeState_ts_1 = require("./_phpRuntimeState.js");
const _phpTypes_ts_1 = require("./_phpTypes.js");
function resolvePhpCallable(callback, options) {
if ((0, _phpTypes_ts_1.isPhpCallable)(callback)) {
return { fn: callback, scope: null };
}
if (typeof callback === 'string') {
const candidate = (0, _phpRuntimeState_ts_1.getPhpGlobalEntry)(callback);
if ((0, _phpTypes_ts_1.isPhpCallable)(candidate)) {
return { fn: candidate, scope: null };
}
throw new Error(options.invalidMessage);
}
if (Array.isArray(callback) && callback.length >= 2) {
const scopeDescriptor = callback[0];
const callableDescriptor = callback[1];
let scope;
if (typeof scopeDescriptor === 'string') {
scope = (0, _phpRuntimeState_ts_1.getPhpGlobalEntry)(scopeDescriptor);
if (typeof scope === 'undefined' && options.missingScopeMessage) {
throw new Error(options.missingScopeMessage(scopeDescriptor));
}
}
else {
scope = scopeDescriptor;
}
if ((0, _phpTypes_ts_1.isPhpCallable)(callableDescriptor)) {
return { fn: callableDescriptor, scope };
}
if (typeof callableDescriptor === 'string' && ((0, _phpTypes_ts_1.isObjectLike)(scope) || typeof scope === 'function')) {
const candidate = (0, _phpRuntimeState_ts_1.getPhpObjectEntry)(scope, callableDescriptor);
if ((0, _phpTypes_ts_1.isPhpCallable)(candidate)) {
return { fn: candidate, scope };
}
}
}
throw new Error(options.invalidMessage);
}
function resolveNumericComparator(callback, invalidMessage) {
const resolved = resolvePhpCallable(callback, { invalidMessage });
return (left, right) => Number(resolved.fn.apply(resolved.scope, [left, right]));
}