Skip to main content

ext_php_rs/zend/
mod.rs

1//! Types used to interact with the Zend engine.
2
3mod _type;
4mod bailout_guard;
5pub mod ce;
6mod class;
7#[cfg(feature = "observer")]
8pub(crate) mod error_observer;
9mod ex;
10#[cfg(feature = "observer")]
11pub(crate) mod exception_observer;
12mod function;
13mod globals;
14mod handlers;
15mod ini_entry_def;
16mod linked_list;
17mod module;
18pub(crate) mod module_globals;
19#[cfg(feature = "observer")]
20pub(crate) mod observer;
21mod streams;
22mod try_catch;
23#[cfg(feature = "observer")]
24pub(crate) mod zend_extension;
25
26use crate::{
27    error::Result,
28    ffi::{php_output_write, php_printf, sapi_module},
29};
30use std::ffi::CString;
31use std::os::raw::c_char;
32
33pub use _type::ZendType;
34pub use bailout_guard::BailoutGuard;
35pub use class::ClassEntry;
36#[cfg(feature = "observer")]
37pub use error_observer::{BacktraceFrame, ErrorInfo, ErrorObserver, ErrorType};
38pub use ex::ExecuteData;
39#[cfg(feature = "observer")]
40pub use exception_observer::{ExceptionInfo, ExceptionObserver};
41pub use function::Function;
42pub use function::FunctionEntry;
43pub(crate) use globals::CompilerGlobals;
44pub use globals::ExecutorGlobals;
45pub use globals::FileGlobals;
46pub use globals::ProcessGlobals;
47pub use globals::SapiGlobals;
48pub use globals::SapiHeader;
49pub use globals::SapiHeaders;
50pub use globals::SapiModule;
51pub use handlers::ZendObjectHandlers;
52pub use ini_entry_def::{IniEntryDef, IniEntryDefs};
53pub use linked_list::ZendLinkedList;
54pub use module::{ModuleAllocations, ModuleEntry, StaticModuleEntry};
55pub use module_globals::{ModuleGlobal, ModuleGlobals};
56#[cfg(feature = "observer")]
57pub use observer::{FcallInfo, FcallObserver};
58pub use streams::*;
59pub(crate) use try_catch::catch_panic;
60pub use try_catch::{CatchError, bailout, run_handler, try_catch, try_catch_first};
61#[cfg(feature = "embed")]
62pub(crate) use try_catch::{CatchFrame, panic_wrapper};
63#[cfg(feature = "observer")]
64pub use zend_extension::{ZendExtensionBuilder, ZendExtensionHandler};
65
66/// Register a `zend_extension` with the PHP engine.
67///
68/// # Safety
69///
70/// * Must be called during `MINIT`.
71/// * The struct's string fields (`name`, `version`, ...) must point at memory
72///   that lives for the process lifetime. PHP copies the struct into its
73///   internal list but keeps those `*const c_char` pointers.
74#[cfg(feature = "observer")]
75pub(crate) unsafe fn register_extension(ext: *mut crate::ffi::zend_extension) {
76    unsafe {
77        crate::ffi::zend_register_extension(ext, std::ptr::null_mut());
78    }
79}
80
81// Used as the format string for `php_printf`.
82const FORMAT_STR: &[u8] = b"%s\0";
83
84/// Prints to stdout using the `php_printf` function.
85///
86/// Also see the [`php_print`] and [`php_println`] macros.
87///
88/// # Arguments
89///
90/// * message - The message to print to stdout.
91///
92/// # Errors
93///
94/// * If the message could not be converted to a [`CString`].
95pub fn printf(message: &str) -> Result<()> {
96    let message = CString::new(message)?;
97    unsafe {
98        php_printf(FORMAT_STR.as_ptr().cast(), message.as_ptr());
99    };
100    Ok(())
101}
102
103/// Writes binary data to PHP's output stream (stdout).
104///
105/// Unlike [`printf`], this function is binary-safe and can handle data
106/// containing NUL bytes. It uses the SAPI module's `ub_write` function
107/// which accepts a pointer and length, allowing arbitrary binary data.
108///
109/// Also see the [`php_write!`] macro.
110///
111/// # Arguments
112///
113/// * `data` - The binary data to write to stdout.
114///
115/// # Returns
116///
117/// The number of bytes written.
118///
119/// # Errors
120///
121/// Returns [`crate::error::Error::SapiWriteUnavailable`] if the SAPI's
122/// `ub_write` function is not available.
123///
124/// # Example
125///
126/// ```ignore
127/// use ext_php_rs::zend::write;
128///
129/// // Write binary data including NUL bytes
130/// let data = b"Hello\x00World";
131/// write(data).expect("Failed to write data");
132/// ```
133pub fn write(data: &[u8]) -> Result<usize> {
134    unsafe {
135        if let Some(ub_write) = sapi_module.ub_write {
136            Ok(ub_write(data.as_ptr().cast::<c_char>(), data.len()))
137        } else {
138            Err(crate::error::Error::SapiWriteUnavailable)
139        }
140    }
141}
142
143/// Writes binary data to PHP's output stream with output buffering support.
144///
145/// This function is binary-safe (can handle NUL bytes) AND respects PHP's
146/// output buffering (`ob_start()`). Use this when you need both binary-safe
147/// output and output buffering compatibility.
148///
149/// # Arguments
150///
151/// * `data` - The binary data to write.
152///
153/// # Returns
154///
155/// The number of bytes written.
156///
157/// # Comparison
158///
159/// | Function | Binary-safe | Output Buffering |
160/// |----------|-------------|------------------|
161/// | [`printf`] | No | Yes |
162/// | [`write()`] | Yes | No (unbuffered) |
163/// | [`output_write`] | Yes | Yes |
164///
165/// # Example
166///
167/// ```ignore
168/// use ext_php_rs::zend::output_write;
169///
170/// // Binary data that will be captured by ob_start()
171/// let data = b"Hello\x00World";
172/// output_write(data);
173/// ```
174#[inline]
175#[must_use]
176pub fn output_write(data: &[u8]) -> usize {
177    unsafe { php_output_write(data.as_ptr().cast::<c_char>(), data.len()) }
178}
179
180/// Get the name of the SAPI module.
181///
182/// Returns `None` if the module name is null or not valid UTF-8.
183#[must_use]
184pub fn php_sapi_name() -> Option<String> {
185    if unsafe { sapi_module.name }.is_null() {
186        return None;
187    }
188    let c_str = unsafe { std::ffi::CStr::from_ptr(sapi_module.name) };
189    c_str.to_str().ok().map(ToString::to_string)
190}