Skip to main content

speedyspec_php/
area.rs

1//! Native areas: what each part of the speedyspec_wordpress extension adds to PHP (functions, classes) and does at
2//! the start and end of every request. They are given to [`crate::Php::boot`] and fixed for the process.
3
4use std::cell::RefCell;
5use std::rc::Rc;
6
7use ext_php_rs::builders::FunctionBuilder;
8
9/// One area of the extension.
10pub trait NativeArea {
11    /// Global functions this area adds; registered once, at module startup.
12    fn functions(&self) -> Vec<FunctionBuilder<'static>> {
13        Vec::new()
14    }
15
16    /// Registers this area's classes (with `ext_php_rs::builders::ClassBuilder`); runs once, at module startup.
17    fn register_classes(&self) -> Result<(), String> {
18        Ok(())
19    }
20
21    /// Runs after each request has started and the extension's own PHP setup has run, before any other PHP code.
22    fn request_start(&self) {}
23
24    /// Runs as each request ends, also after a fatal error or `exit()` (from the module's request shutdown).
25    fn request_end(&self) {}
26}
27
28thread_local! {
29    static AREAS: RefCell<Vec<Rc<dyn NativeArea>>> = const { RefCell::new(Vec::new()) };
30}
31
32pub(crate) fn install(areas: Vec<Rc<dyn NativeArea>>) {
33    AREAS.with(|a| *a.borrow_mut() = areas);
34}
35
36pub(crate) fn uninstall() {
37    let areas = AREAS.with(|a| std::mem::take(&mut *a.borrow_mut()));
38    drop(areas);
39}
40
41fn each(f: impl Fn(&dyn NativeArea)) {
42    let areas = AREAS.with(|a| a.borrow().clone());
43    for area in &areas {
44        f(area.as_ref());
45    }
46}
47
48pub(crate) fn functions() -> Vec<FunctionBuilder<'static>> {
49    let areas = AREAS.with(|a| a.borrow().clone());
50    areas.iter().flat_map(|area| area.functions()).collect()
51}
52
53pub(crate) fn register_classes() -> Result<(), String> {
54    let areas = AREAS.with(|a| a.borrow().clone());
55    for area in &areas {
56        area.register_classes()?;
57    }
58    Ok(())
59}
60
61pub(crate) fn request_start() {
62    crate::callable::new_request();
63    each(|area| area.request_start());
64}
65
66/// The module's RSHUTDOWN.
67pub(crate) extern "C" fn request_shutdown(_ty: i32, _module_number: i32) -> i32 {
68    let ended = std::panic::catch_unwind(|| each(|area| area.request_end()));
69    if ended.is_ok() { 0 } else { 1 }
70}