Skip to main content

ext_php_rs/
macros.rs

1//! Macros for interacting with PHP, mainly when the function takes variadic
2//! arguments. Unfortunately, this is the best way to handle these.
3//! Note that most of these will introduce unsafe into your code base.
4
5/// Starts the PHP extension information table displayed when running
6/// `phpinfo();` Must be run *before* rows are inserted into the table.
7#[macro_export]
8macro_rules! info_table_start {
9    () => {
10        unsafe { $crate::ffi::php_info_print_table_start() };
11    };
12}
13
14/// Ends the PHP extension information table. Must be run *after* all rows have
15/// been inserted into the table.
16#[macro_export]
17macro_rules! info_table_end {
18    () => {
19        unsafe { $crate::ffi::php_info_print_table_end() }
20    };
21}
22
23/// Sets the header for the PHP extension information table. Takes as many
24/// string arguments as required.
25#[macro_export]
26macro_rules! info_table_header {
27    ($($element:expr),*) => {$crate::_info_table_row!(php_info_print_table_header, $($element),*)};
28}
29
30/// Adds a row to the PHP extension information table. Takes as many string
31/// arguments as required.
32#[macro_export]
33macro_rules! info_table_row {
34    ($($element:expr),*) => {$crate::_info_table_row!(php_info_print_table_row, $($element),*)};
35}
36
37/// INTERNAL: Calls a variadic C function with the number of parameters, then
38/// following with the parameters.
39#[doc(hidden)]
40#[macro_export]
41macro_rules! _info_table_row {
42    ($fn: ident, $($element: expr),*) => {
43        unsafe {
44            $crate::ffi::$fn($crate::_info_table_row!(@COUNT; $($element),*) as i32, $(::std::ffi::CString::new($element).unwrap().as_ptr()),*);
45        }
46    };
47
48    (@COUNT; $($element: expr),*) => {
49        <[()]>::len(&[$($crate::_info_table_row![@SUBST; $element]),*])
50    };
51    (@SUBST; $_: expr) => { () };
52}
53
54/// Attempts to call a given PHP callable.
55///
56/// # Parameters
57///
58/// * `$fn` - The 'function' to call. Can be an [`Arg`] or a [`Zval`].
59/// * ...`$param` - The parameters to pass to the function. Must be able to be
60///   converted into a [`Zval`].
61///
62/// [`Arg`]: crate::args::Arg
63/// [`Zval`]: crate::types::Zval
64#[macro_export]
65macro_rules! call_user_func {
66    ($fn: expr) => {
67        $fn.try_call(vec![])
68    };
69
70    ($fn: expr, $($param: expr),*) => {
71        $fn.try_call(vec![$(&$param),*])
72    };
73}
74
75/// Attempts to call a given PHP callable with named arguments.
76///
77/// This macro supports PHP 8.0+ named arguments, allowing you to pass
78/// arguments by name rather than position.
79///
80/// # Syntax
81///
82/// ```ignore
83/// // Named arguments only
84/// call_user_func_named!(callable, name1: value1, name2: value2)
85///
86/// // Positional arguments followed by named arguments
87/// call_user_func_named!(callable, [pos1, pos2], name1: value1, name2: value2)
88/// ```
89///
90/// # Parameters
91///
92/// * `$fn` - The 'function' to call. Can be an [`Arg`] or a [`Zval`].
93/// * `$name: $value` - Named parameters as `name: value` pairs.
94/// * `[$($pos),*]` - Optional positional parameters in square brackets.
95///
96/// # Examples
97///
98/// ```ignore
99/// use ext_php_rs::{call_user_func_named, types::ZendCallable};
100///
101/// let str_replace = ZendCallable::try_from_name("str_replace").unwrap();
102///
103/// // Using named arguments only
104/// let result = call_user_func_named!(str_replace,
105///     search: "world",
106///     replace: "PHP",
107///     subject: "Hello world"
108/// ).unwrap();
109///
110/// // Mixing positional and named arguments
111/// let result = call_user_func_named!(str_replace, ["world", "PHP"],
112///     subject: "Hello world"
113/// ).unwrap();
114/// ```
115///
116/// [`Arg`]: crate::args::Arg
117/// [`Zval`]: crate::types::Zval
118/// Note: Parameter names must be valid Rust identifiers.
119/// For other names, use `try_call_named` directly.
120#[macro_export]
121macro_rules! call_user_func_named {
122    // Named arguments only
123    ($fn: expr, $($name: ident : $value: expr),+ $(,)?) => {
124        $fn.try_call_named(&[$((stringify!($name), &$value as &dyn $crate::convert::IntoZvalDyn)),+])
125    };
126
127    // Positional arguments followed by named arguments
128    ($fn: expr, [$($pos: expr),* $(,)?], $($name: ident : $value: expr),+ $(,)?) => {
129        $fn.try_call_with_named(
130            &[$(&$pos as &dyn $crate::convert::IntoZvalDyn),*],
131            &[$((stringify!($name), &$value as &dyn $crate::convert::IntoZvalDyn)),+]
132        )
133    };
134
135}
136
137/// Parses a given list of arguments using the [`ArgParser`] class.
138///
139/// # Examples
140///
141/// This example parses all of the arguments. If one is invalid, execution of
142/// the function will stop at the `parse_args!` macro invocation. The user is
143/// notified via PHP's argument parsing system.
144///
145/// In this case, all of the arguments are required.
146///
147/// ```
148/// # #[macro_use] extern crate ext_php_rs;
149/// use ext_php_rs::{
150///     parse_args,
151///     args::Arg,
152///     flags::DataType,
153///     zend::ExecuteData,
154///     types::Zval,
155/// };
156///
157/// pub extern "C" fn example_fn(execute_data: &mut ExecuteData, _: &mut Zval) {
158///     let mut x = Arg::new("x", DataType::Long);
159///     let mut y = Arg::new("y", DataType::Long);
160///     let mut z = Arg::new("z", DataType::Long);
161///
162///     parse_args!(execute_data, x, y, z);
163/// }
164/// ```
165///
166/// This example is similar to the one above, apart from the fact that the `z`
167/// argument is not required. Note the semicolon separating the first two
168/// arguments from the second.
169///
170/// ```
171/// use ext_php_rs::{
172///     parse_args,
173///     args::Arg,
174///     flags::DataType,
175///     zend::ExecuteData,
176///     types::Zval,
177/// };
178///
179/// pub extern "C" fn example_fn(execute_data: &mut ExecuteData, _: &mut Zval) {
180///     let mut x = Arg::new("x", DataType::Long);
181///     let mut y = Arg::new("y", DataType::Long);
182///     let mut z = Arg::new("z", DataType::Long);
183///
184///     parse_args!(execute_data, x, y; z);
185/// }
186/// ```
187///
188/// [`ArgParser`]: crate::args::ArgParser
189#[macro_export]
190macro_rules! parse_args {
191    ($ed: expr, $($arg: expr),*) => {{
192        let parser = $ed.parser()
193            $(.arg(&mut $arg))*
194            .parse();
195        if parser.is_err() {
196            return;
197        }
198    }};
199
200    ($ed: expr, $($arg: expr),* ; $($opt: expr),*) => {{
201        let parser = $ed.parser()
202            $(.arg(&mut $arg))*
203            .not_required()
204            $(.arg(&mut $opt))*
205            .parse();
206        if parser.is_err() {
207            return;
208        }
209    }};
210}
211
212/// Throws an exception and returns from the current function.
213///
214/// Wraps the [`throw`] function by inserting a `return` statement after
215/// throwing the exception.
216///
217/// [`throw`]: crate::exception::throw
218///
219/// # Examples
220///
221/// ```
222/// use ext_php_rs::{
223///     throw,
224///     zend::{ce, ClassEntry, ExecuteData},
225///     types::Zval,
226/// };
227///
228/// pub extern "C" fn example_fn(execute_data: &mut ExecuteData, _: &mut Zval) {
229///     let something_wrong = true;
230///     if something_wrong {
231///         throw!(ce::exception(), "Something is wrong!");
232///     }
233///
234///     assert!(false); // This will not run.
235/// }
236/// ```
237#[macro_export]
238macro_rules! throw {
239    ($ex: expr, $reason: expr) => {
240        $crate::exception::throw($ex, $reason);
241        return;
242    };
243}
244
245/// Implements a set of traits required to convert types that implement
246/// [`RegisteredClass`] to and from [`ZendObject`]s and [`Zval`]s. Generally,
247/// this macro should not be called directly, as it is called on any type that
248/// uses the [`php_class`] macro.
249///
250/// The following traits are implemented:
251///
252/// * `PhpClass for T`
253/// * `IntoZendObject for T`
254/// * `IntoZval for T`
255///
256/// These implementations are required while we wait on the stabilisation of
257/// specialisation. To read a `T` back from a [`Zval`], use
258/// [`ClassRef`](crate::types::ClassRef) or
259/// [`ClassRefMut`](crate::types::ClassRefMut).
260///
261/// # Examples
262///
263/// ```
264/// # use ext_php_rs::{convert::{IntoZval, FromZval, IntoZvalDyn}, types::{ClassRef, Zval, ZendObject}, class::{RegisteredClass, ConstructorMeta, ClassEntryInfo}, builders::{ClassBuilder, FunctionBuilder}, zend::ClassEntry, flags::{ClassFlags, ConstantFlags, MethodFlags}, describe::DocComments};
265/// use ext_php_rs::class_derives;
266///
267/// struct Test {
268///     a: i32,
269///     b: i64
270/// }
271///
272/// impl RegisteredClass for Test {
273///     const CLASS_NAME: &'static str = "Test";
274///
275///     const BUILDER_MODIFIER: Option<fn(ClassBuilder) -> ClassBuilder> = None;
276///     const EXTENDS: Option<ClassEntryInfo> = None;
277///     const IMPLEMENTS: &'static [ClassEntryInfo] =  &[];
278///     const FLAGS: ClassFlags = ClassFlags::empty();
279///     const DOC_COMMENTS: DocComments = &[];
280///
281///     fn get_metadata() -> &'static ext_php_rs::class::ClassMetadata<Self> {
282///         todo!()
283///     }
284///
285///     fn method_builders() -> Vec<(FunctionBuilder<'static>, MethodFlags)> {
286///         todo!()
287///     }
288///
289///     fn constructor() -> Option<ConstructorMeta<Self>> {
290///         todo!()
291///     }
292///
293///     fn constants() -> &'static [(&'static str, &'static dyn IntoZvalDyn, DocComments, ConstantFlags)] {
294///         todo!()
295///     }
296/// }
297///
298/// class_derives!(Test);
299///
300/// fn into_zval_test() -> Zval {
301///     let x = Test { a: 5, b: 10 };
302///     x.into_zval(false).unwrap()
303/// }
304///
305/// fn from_zval_test<'a>(zv: &'a Zval) -> ClassRef<'a, Test> {
306///     ClassRef::<Test>::from_zval(zv).unwrap()
307/// }
308/// ```
309///
310/// [`RegisteredClass`]: crate::class::RegisteredClass
311/// [`ZendObject`]: crate::types::ZendObject
312/// [`Zval`]: crate::types::Zval
313/// [`php_class`]: crate::php_class
314#[macro_export]
315macro_rules! class_derives {
316    ($type: ty) => {
317        impl $crate::class::PhpClass for $type {}
318
319        impl $crate::convert::IntoZendObject for $type {
320            #[inline]
321            fn into_zend_object(
322                self,
323            ) -> $crate::error::Result<$crate::boxed::ZBox<$crate::types::ZendObject>> {
324                Ok($crate::types::ZendClassObject::new(self).into())
325            }
326        }
327
328        impl $crate::convert::IntoZval for $type {
329            const TYPE: $crate::flags::DataType = $crate::flags::DataType::object(
330                <$type as $crate::class::RegisteredClass>::CLASS_NAME,
331            );
332            const NULLABLE: bool = false;
333
334            #[inline]
335            fn set_zval(
336                self,
337                zv: &mut $crate::types::Zval,
338                persistent: bool,
339            ) -> $crate::error::Result<()> {
340                use $crate::convert::IntoZendObject;
341
342                self.into_zend_object()?.set_zval(zv, persistent)
343            }
344        }
345    };
346}
347
348/// Derives `From<T> for Zval` and `IntoZval` for a given type.
349macro_rules! into_zval {
350    ($type: ty, $fn: ident, $dt: ident) => {
351        impl From<$type> for $crate::types::Zval {
352            fn from(val: $type) -> Self {
353                let mut zv = Self::new();
354                zv.$fn(val);
355                zv
356            }
357        }
358
359        impl $crate::convert::IntoZval for $type {
360            const TYPE: $crate::flags::DataType = $crate::flags::DataType::$dt;
361            const NULLABLE: bool = false;
362
363            fn set_zval(self, zv: &mut $crate::types::Zval, _: bool) -> $crate::error::Result<()> {
364                zv.$fn(self);
365                Ok(())
366            }
367        }
368    };
369}
370
371/// Derives `TryFrom<Zval> for T` and `FromZval for T` on a given type.
372macro_rules! try_from_zval {
373    ($type: ty, $fn: ident, $dt: ident) => {
374        impl $crate::convert::FromZval<'_> for $type {
375            const TYPE: $crate::flags::DataType = $crate::flags::DataType::$dt;
376
377            fn from_zval(zval: &$crate::types::Zval) -> ::std::option::Option<Self> {
378                use ::std::convert::TryInto;
379
380                zval.$fn().and_then(|val| val.try_into().ok())
381            }
382        }
383
384        impl ::std::convert::TryFrom<$crate::types::Zval> for $type {
385            type Error = $crate::error::Error;
386
387            fn try_from(value: $crate::types::Zval) -> $crate::error::Result<Self> {
388                <Self as $crate::convert::FromZval>::from_zval(&value)
389                    .ok_or($crate::error::Error::ZvalConversion(value.get_type()))
390            }
391        }
392    };
393}
394
395/// Prints to the PHP standard output, without a newline.
396///
397/// Acts exactly the same as the built-in [`print`] macro.
398///
399/// # Panics
400///
401/// Panics if the generated string could not be converted to a `CString` due to
402/// `NUL` characters.
403#[macro_export]
404macro_rules! php_print {
405    ($arg: tt) => {{
406        $crate::zend::printf($arg).expect("Failed to print to PHP stdout");
407    }};
408
409    ($($arg: tt) *) => {{
410        let args = format!($($arg)*);
411        $crate::zend::printf(args.as_str()).expect("Failed to print to PHP stdout");
412    }};
413}
414
415/// Prints to the PHP standard output, with a newline.
416///
417/// The newline is only a newline character regardless of platform (no carriage
418/// return).
419///
420/// Acts exactly the same as the built-in [`println`] macro.
421///
422/// # Panics
423///
424/// Panics if the generated string could not be converted to a `CString` due to
425/// `NUL` characters.
426#[macro_export]
427macro_rules! php_println {
428    () => {
429        $crate::php_print!("\n");
430    };
431
432    ($fmt: tt) => {
433        $crate::php_print!(concat!($fmt, "\n"));
434    };
435
436    ($fmt: tt, $($arg: tt) *) => {
437        $crate::php_print!(concat!($fmt, "\n"), $($arg)*);
438    };
439}
440
441/// Writes binary data to the PHP standard output.
442///
443/// Unlike [`php_print!`], this macro is binary-safe and can handle data
444/// containing `NUL` bytes. It uses the SAPI module's `ub_write` function.
445///
446/// # Arguments
447///
448/// * `$data` - A byte slice (`&[u8]`) or byte literal (`b"..."`) to write.
449///
450/// # Returns
451///
452/// A `Result<usize>` containing the number of bytes written.
453///
454/// # Errors
455///
456/// Returns [`Error::SapiWriteUnavailable`] if the SAPI's `ub_write` function
457/// is not available.
458///
459/// [`Error::SapiWriteUnavailable`]: crate::error::Error::SapiWriteUnavailable
460///
461/// # Examples
462///
463/// ```ignore
464/// use ext_php_rs::php_write;
465///
466/// // Write a byte literal
467/// php_write!(b"Hello World").expect("write failed");
468///
469/// // Write binary data with NUL bytes (would panic with php_print!)
470/// php_write!(b"Hello\x00World").expect("write failed");
471///
472/// // Write a byte slice
473/// let data: &[u8] = &[0x48, 0x65, 0x6c, 0x6c, 0x6f];
474/// php_write!(data).expect("write failed");
475/// ```
476#[macro_export]
477macro_rules! php_write {
478    ($data: expr) => {{ $crate::zend::write($data) }};
479}
480
481/// Writes binary data to PHP's output stream with output buffering support.
482///
483/// This macro is both binary-safe (can handle `NUL` bytes) AND respects PHP's
484/// output buffering (`ob_start()`). Use this when you need both capabilities.
485///
486/// # Arguments
487///
488/// * `$data` - A byte slice (`&[u8]`) or byte literal (`b"..."`) to write.
489///
490/// # Returns
491///
492/// The number of bytes written.
493///
494/// # Comparison
495///
496/// | Macro | Binary-safe | Output Buffering |
497/// |-------|-------------|------------------|
498/// | `php_print!` | No | Yes |
499/// | `php_write!` | Yes | No (unbuffered) |
500/// | `php_output!` | Yes | Yes |
501///
502/// # Examples
503///
504/// ```ignore
505/// use ext_php_rs::php_output;
506///
507/// // Write binary data that will be captured by ob_start()
508/// php_output!(b"Hello\x00World");
509///
510/// // Use with output buffering
511/// // ob_start();
512/// // php_output!(b"captured");
513/// // $data = ob_get_clean(); // Contains "captured"
514/// ```
515#[macro_export]
516macro_rules! php_output {
517    ($data: expr) => {{ $crate::zend::output_write($data) }};
518}