ripht_php_sapi/execution/
hooks.rs

1use std::path::Path;
2
3use super::message::ExecutionMessage;
4use super::result::ExecutionResult;
5
6/// What to do with the PHP output.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8#[non_exhaustive]
9pub enum OutputAction {
10    Continue,
11    Done,
12}
13
14pub struct NoOpHooks;
15
16impl ExecutionHooks for NoOpHooks {}
17
18/// Wraps a closure implementation for streaming output.
19/// Called at least once during execution.
20pub struct StreamingCallback<F> {
21    output_fn: F,
22}
23
24impl<F> StreamingCallback<F>
25where
26    F: FnMut(&[u8]),
27{
28    pub fn new(output_fn: F) -> Self {
29        Self { output_fn }
30    }
31}
32
33impl<F> ExecutionHooks for StreamingCallback<F>
34where
35    F: FnMut(&[u8]),
36{
37    fn on_output(&mut self, data: &[u8]) -> OutputAction {
38        (self.output_fn)(data);
39        OutputAction::Done
40    }
41}
42
43/// Callbacks invoked during PHP request execution.
44///
45/// Default implementations allow for selective participation.
46/// Method names are purposefully self-explanatory/self-documenting.
47pub trait ExecutionHooks {
48    /// Called after server context is created.
49    fn on_context_created(&mut self) {}
50    fn on_request_starting(&mut self) {}
51    fn on_request_started(&mut self) {}
52
53    /// Called before script execution begins.
54    fn on_script_executing(&mut self, script_path: &Path) {
55        let _ = script_path;
56    }
57
58    /// Called after script execution completes.
59    fn on_script_executed(&mut self, success: bool) {
60        let _ = success;
61    }
62
63    /// Called when PHP writes to its output buffer.
64    fn on_output(&mut self, data: &[u8]) -> OutputAction {
65        let _ = data;
66
67        OutputAction::Continue
68    }
69
70    /// Called when PHP flushes output.
71    fn on_flush(&mut self) {}
72
73    /// Called for each response header. Return false to suppress the header.
74    fn on_header(&mut self, name: &str, value: &str) -> bool {
75        let _ = (name, value);
76        true
77    }
78
79    /// Called when HTTP status code is set.
80    fn on_status(&mut self, code: u16) {
81        let _ = code;
82    }
83
84    /// Called for PHP errors, warnings, and notices.
85    fn on_php_message(&mut self, message: &ExecutionMessage) {
86        let _ = message;
87    }
88
89    /// Return false to abort execution (e.g., client disconnected).
90    fn is_connection_alive(&self) -> bool {
91        true
92    }
93
94    /// Called before php_request_shutdown.
95    fn on_request_finishing(&mut self) {}
96
97    /// Called after request completes with the final result.
98    fn on_request_finished(&mut self, result: &ExecutionResult) {
99        let _ = result;
100    }
101}