ext-php-rs 0.17.0

Bindings for the Zend API to build PHP extensions natively in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Types and functions used for throwing exceptions from Rust to PHP.

use std::{fmt::Debug, ptr};

use crate::{
    class::RegisteredClass,
    error::{Error, Result},
    ffi::zend_throw_exception,
    ffi::zend_throw_exception_object,
    flags::ClassFlags,
    types::{ZendStr, Zval},
    zend::{ClassEntry, ExecutorGlobals, ce},
};

/// Result type with the error variant as a [`PhpException`].
pub type PhpResult<T = ()> = std::result::Result<T, PhpException>;

/// Represents a PHP exception which can be thrown using the `throw()` function.
/// Primarily used to return from a [`Result<T, PhpException>`] which can
/// immediately be thrown by the `ext-php-rs` macro API.
///
/// [`From`] is implemented for [`String`], [`&str`], [`crate::error::Error`]
/// and, behind the `anyhow` feature, `anyhow::Error`. Implement [`From<T>`]
/// for your own error type to return it from these functions.
#[derive(Debug)]
pub struct PhpException {
    message: String,
    code: i32,
    ex: &'static ClassEntry,
    object: Option<Zval>,
}

impl PhpException {
    /// Creates a new exception instance.
    ///
    /// # Parameters
    ///
    /// * `message` - Message to contain in the exception.
    /// * `code` - Integer code to go inside the exception.
    /// * `ex` - Exception type to throw.
    #[must_use]
    pub fn new(message: String, code: i32, ex: &'static ClassEntry) -> Self {
        Self {
            message,
            code,
            ex,
            object: None,
        }
    }

    /// Creates a new exception instance from a message, using the default PHP
    /// `Exception` type as the exception type, with an integer code of
    /// zero.
    ///
    /// # Parameters
    ///
    /// * `message` - Message to contain in the exception.
    #[must_use]
    pub fn from_message(message: String) -> Self {
        Self::new(message, 0, ce::exception())
    }

    /// Creates an instance of an exception from a PHP class type and a message.
    ///
    /// # Parameters
    ///
    /// * `message` - Message to contain in the exception.
    #[must_use]
    pub fn from_class<T: RegisteredClass>(message: String) -> Self {
        Self::new(message, 0, T::get_metadata().ce())
    }

    /// Set the Zval object for the exception.
    ///
    /// Exceptions can be based of instantiated Zval objects when you are
    /// throwing a custom exception with stateful properties.
    ///
    /// # Parameters
    ///
    /// * `object` - The Zval object.
    pub fn set_object(&mut self, object: Option<Zval>) {
        self.object = object;
    }

    /// Builder function that sets the Zval object for the exception.
    ///
    /// Exceptions can be based of instantiated Zval objects when you are
    /// throwing a custom exception with stateful properties.
    ///
    /// # Parameters
    ///
    /// * `object` - The Zval object.
    #[must_use]
    pub fn with_object(mut self, object: Zval) -> Self {
        self.object = Some(object);
        self
    }

    /// Throws the exception. Always leaves an exception pending in the engine.
    ///
    /// Does nothing if an exception is already pending: the engine propagates
    /// that one, and throwing over it would discard its class and stack trace.
    ///
    /// When the exception itself cannot be thrown (an interface or abstract
    /// class, a message containing a NUL byte, or an attached value that is not
    /// an object) a plain `Error` is thrown instead. Its message names the
    /// cause and carries the original message, so the failure is reported to
    /// PHP rather than to the Rust caller, which sits inside an `extern "C"`
    /// frame with no way to propagate it.
    pub fn throw(self) {
        if ExecutorGlobals::has_exception() {
            return;
        }

        // The engine can bail out of every call below, and a bailout skips this
        // frame's destructors. So the Rust strings are copied to the Zend heap and
        // dropped first. The Zend allocator frees its copies at request shutdown.
        let Self {
            message,
            code,
            ex,
            object,
        } = self;
        let zend_message = ZendStr::new(&message, false);
        drop(message);

        let result = match object {
            Some(object) => throw_object(object),
            None => throw_zend_str(ex, code, &zend_message),
        };

        if let Err(err) = result {
            let class = ex.name().unwrap_or_default();
            let message = String::from_utf8_lossy(zend_message.as_bytes()).replace('\0', "\\0");
            let fallback = format!("cannot throw {class}: {err}; original message: {message}");
            drop(message);
            let zend_fallback = ZendStr::new(&fallback, false);
            drop(fallback);
            let _ = throw_zend_str(ce::error(), 0, &zend_fallback);
        }
    }
}

impl From<String> for PhpException {
    fn from(str: String) -> Self {
        Self::from_message(str)
    }
}

impl From<&str> for PhpException {
    fn from(str: &str) -> Self {
        Self::from_message(str.into())
    }
}

#[cfg(feature = "anyhow")]
impl From<anyhow::Error> for PhpException {
    fn from(err: anyhow::Error) -> Self {
        Self::new(format!("{err:#}"), 0, crate::zend::ce::exception())
    }
}

/// Throws an exception with a given message. See [`ClassEntry`] for some
/// built-in exception types.
///
/// Returns a result containing nothing if the exception was successfully
/// thrown.
///
/// # Parameters
///
/// * `ex` - The exception type to throw.
/// * `message` - The message to display when throwing the exception.
///
/// # Errors
///
/// * [`Error::InvalidException`] - If the exception type is an interface or
///   abstract class.
/// * If the message contains NUL bytes.
///
/// # Examples
///
/// ```no_run
/// use ext_php_rs::{zend::{ce, ClassEntry}, exception::throw};
///
/// throw(ce::compile_error(), "This is a CompileError.");
/// ```
pub fn throw(ex: &ClassEntry, message: &str) -> Result<()> {
    throw_with_code(ex, 0, message)
}

/// Throws an exception with a given message and status code. See [`ClassEntry`]
/// for some built-in exception types.
///
/// Returns a result containing nothing if the exception was successfully
/// thrown.
///
/// # Parameters
///
/// * `ex` - The exception type to throw.
/// * `code` - The status code to use when throwing the exception.
/// * `message` - The message to display when throwing the exception.
///
/// # Errors
///
/// * [`Error::InvalidException`] - If the exception type is an interface or
///   abstract class.
/// * If the message contains NUL bytes.
///
/// # Examples
///
/// ```no_run
/// use ext_php_rs::{zend::{ce, ClassEntry}, exception::throw_with_code};
///
/// throw_with_code(ce::compile_error(), 123, "This is a CompileError.");
/// ```
pub fn throw_with_code(ex: &ClassEntry, code: i32, message: &str) -> Result<()> {
    throw_zend_str(ex, code, &ZendStr::new(message, false))
}

/// Throws an exception whose message is already on the Zend heap.
fn throw_zend_str(ex: &ClassEntry, code: i32, message: &ZendStr) -> Result<()> {
    let flags = ex.flags();

    // Can't throw an interface or abstract class.
    if flags.contains(ClassFlags::Interface) || flags.contains(ClassFlags::Abstract) {
        return Err(Error::InvalidException(flags));
    }

    let message_ptr = message.as_c_str()?.as_ptr();

    // SAFETY: We are given a reference to a `ClassEntry` therefore when we cast it
    // to a pointer it will be valid. `message` is NUL-terminated and outlives the
    // call; if the engine bails out here the Zend allocator reclaims it at request
    // shutdown, as php-src does for its own copy of the message.
    unsafe { zend_throw_exception(ptr::from_ref(ex).cast_mut(), message_ptr, code.into()) };
    Ok(())
}

/// Throws an exception object.
///
/// Returns a result containing nothing if the exception was successfully
/// thrown.
///
/// # Parameters
///
/// * `object` - The zval of type object
///
/// # Errors
///
/// * [`Error::Object`] - If the zval does not hold an object.
///
/// # Examples
///
/// ```no_run
/// use ext_php_rs::prelude::*;
/// use ext_php_rs::exception::throw_object;
/// use crate::ext_php_rs::convert::IntoZval;
///
/// #[php_class]
/// #[php(extends(ce = ext_php_rs::zend::ce::exception, stub = "\\Exception"))]
/// pub struct JsException {
///     #[php(prop, flags = ext_php_rs::flags::PropertyFlags::Public)]
///     message: String,
///     #[php(prop, flags = ext_php_rs::flags::PropertyFlags::Public)]
///     code: i32,
///     #[php(prop, flags = ext_php_rs::flags::PropertyFlags::Public)]
///     file: String,
/// }
///
/// #[php_module]
/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
///     module
/// }
///
/// let error = JsException { message: "A JS error occurred.".to_string(), code: 100, file: "index.js".to_string() };
/// throw_object( error.into_zval(true).unwrap() );
/// ```
pub fn throw_object(zval: Zval) -> Result<()> {
    if !zval.is_object() {
        return Err(Error::Object);
    }

    let mut zv = core::mem::ManuallyDrop::new(zval);
    unsafe { zend_throw_exception_object(core::ptr::addr_of_mut!(zv).cast()) };
    Ok(())
}

#[cfg(feature = "embed")]
#[cfg(test)]
mod tests {
    #![allow(clippy::assertions_on_constants)]
    use super::*;
    use crate::embed::Embed;

    #[test]
    fn test_new() {
        Embed::run(|| {
            let ex = PhpException::new("Test".into(), 0, ce::exception());
            assert_eq!(ex.message, "Test");
            assert_eq!(ex.code, 0);
            assert_eq!(ex.ex, ce::exception());
            assert!(ex.object.is_none());
        });
    }

    #[test]
    fn test_default() {
        Embed::run(|| {
            let ex = PhpException::from_message("Test".into());
            assert_eq!(ex.message, "Test");
            assert_eq!(ex.code, 0);
            assert_eq!(ex.ex, ce::exception());
            assert!(ex.object.is_none());
        });
    }

    #[test]
    fn test_set_object() {
        Embed::run(|| {
            let mut ex = PhpException::from_message("Test".into());
            assert!(ex.object.is_none());
            let obj = Zval::new();
            ex.set_object(Some(obj));
            assert!(ex.object.is_some());
        });
    }

    #[test]
    fn test_with_object() {
        Embed::run(|| {
            let obj = Zval::new();
            let ex = PhpException::from_message("Test".into()).with_object(obj);
            assert!(ex.object.is_some());
        });
    }

    #[test]
    fn test_from_string() {
        Embed::run(|| {
            let ex: PhpException = "Test".to_string().into();
            assert_eq!(ex.message, "Test");
            assert_eq!(ex.code, 0);
            assert_eq!(ex.ex, ce::exception());
            assert!(ex.object.is_none());
        });
    }

    #[test]
    fn test_from_str() {
        Embed::run(|| {
            let ex: PhpException = "Test str".into();
            assert_eq!(ex.message, "Test str");
            assert_eq!(ex.code, 0);
            assert_eq!(ex.ex, ce::exception());
            assert!(ex.object.is_none());
        });
    }

    #[cfg(feature = "anyhow")]
    #[test]
    fn test_from_anyhow() {
        Embed::run(|| {
            let ex: PhpException = anyhow::anyhow!("Test anyhow").into();
            assert_eq!(ex.message, "Test anyhow");
            assert_eq!(ex.code, 0);
            assert_eq!(ex.ex, ce::exception());
            assert!(ex.object.is_none());
        });
    }

    #[test]
    fn test_throw_ex() {
        Embed::run(|| {
            assert!(throw(ce::exception(), "Test").is_ok());

            assert!(false, "Should not reach here");
        });
    }

    #[test]
    fn test_throw_with_code() {
        Embed::run(|| {
            assert!(throw_with_code(ce::exception(), 1, "Test").is_ok());

            assert!(false, "Should not reach here");
        });
    }

    // TODO: Test abstract class
    #[test]
    fn test_throw_with_code_interface() {
        Embed::run(|| {
            assert!(throw_with_code(ce::arrayaccess(), 0, "Test").is_err());
        });
    }

    #[test]
    fn test_static_throw_object_rejects_a_non_object() {
        Embed::run(|| {
            assert!(matches!(throw_object(Zval::new()), Err(Error::Object)));
        });
    }
}