use crate::host::with_host;
use crate::stdlib::common::*;
use fusevm::Value;
pub fn dispatch(name: &str, args: &[Value]) -> Option<Result<Value, String>> {
let v = match name {
"assert" => {
let ok = with_host(|h| h.is_truthy(&arg(args, 0)));
Value::bool(ok)
}
"assert_options" => Value::int(0),
"trigger_error" | "user_error" => {
let msg = str_arg(args, 0);
let level = if args.len() > 1 {
int_arg(args, 1)
} else {
1024 };
if !matches!(level, 256 | 512 | 1024 | 16384) {
return Some(Err(crate::builtins::throws(
"ValueError",
"trigger_error(): Argument #2 ($error_level) must be one of E_USER_ERROR, \
E_USER_WARNING, E_USER_NOTICE, or E_USER_DEPRECATED",
)));
}
if level == 256 {
return Some(user_error_fatal(&msg, args));
}
with_host(|h| {
let line = h.cur_frame_line();
h.diagnose(level_label(level), level, line, &msg);
});
Value::bool(true)
}
"error_log" => {
let msg = str_arg(args, 0);
let msg_type = if args.len() > 1 { int_arg(args, 1) } else { 0 };
if msg_type == 3 && args.len() > 2 {
let dest = str_arg(args, 2);
use std::io::Write;
match std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&dest)
{
Ok(mut f) => {
let _ = f.write_all(msg.as_bytes());
Value::bool(true)
}
Err(_) => Value::bool(false),
}
} else {
eprintln!("{msg}");
Value::bool(true)
}
}
"debug_backtrace" => make_list(vec![]),
"debug_print_backtrace" => Value::Undef,
"set_error_handler" | "set_exception_handler" => Value::Undef,
"restore_error_handler" | "restore_exception_handler" => Value::bool(true),
"register_shutdown_function" => Value::Undef,
"spl_autoload_register" => Value::bool(true),
"spl_autoload_unregister" => Value::bool(true),
"get_defined_vars" => make_list(vec![]),
"class_alias" => {
let orig = str_arg(args, 0);
Value::bool(with_host(|h| h.class_exists(&orig)))
}
_ => return None,
};
Some(Ok(v))
}
fn user_error_fatal(msg: &str, args: &[Value]) -> Result<Value, String> {
with_host(|h| {
let line = h.cur_frame_line();
h.diagnose(
"Deprecated",
crate::errlevel::E_DEPRECATED,
line,
"Passing E_USER_ERROR to trigger_error() is deprecated since 8.4, throw an \
exception or call exit with a string message instead",
);
let argsarr = h.new_array();
for a in args {
h.arr_push_auto(&argsarr, a.clone());
}
h.push_internal_frame("trigger_error", line, argsarr);
let body = format!(
"{msg} in {} on line {line}\nStack trace:\n{}",
h.script_name(),
h.backtrace()
);
h.pop_internal_frame();
h.fatal("Fatal error", &body);
});
crate::host::set_pending_exit(255);
Ok(Value::Undef)
}
fn level_label(level: i64) -> &'static str {
match level {
256 => "Fatal error", 512 => "Warning", 16384 => "Deprecated", _ => "Notice", }
}