• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

extphprs / ext-php-rs / 30712299702

01 Aug 2026 06:20PM UTC coverage: 66.959% (+0.4%) from 66.524%
30712299702

push

github

web-flow
fix: return errors instead of panicking on engine and user input (#758)

45 of 73 new or added lines in 5 files covered. (61.64%)

5 existing lines in 3 files now uncovered.

8943 of 13356 relevant lines covered (66.96%)

43.41 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/error.rs
1
//! Error and result types returned from the library functions.
2

3
use std::{
4
    error::Error as ErrorTrait,
5
    ffi::{CString, NulError, c_int},
6
    fmt::Display,
7
    num::TryFromIntError,
8
};
9

10
use crate::{
11
    boxed::ZBox,
12
    exception::PhpException,
13
    ffi::php_error_docref,
14
    flags::{ClassFlags, DataType, ErrorType, ZvalTypeFlags},
15
    types::{ZendObject, Zval},
16
};
17

18
/// The main result type which is passed by the library.
19
pub type Result<T, E = Error> = std::result::Result<T, E>;
20

21
/// The main error type which is passed by the library inside the custom
22
/// [`Result`] type.
23
#[derive(Debug)]
24
#[non_exhaustive]
25
pub enum Error {
26
    /// An incorrect number of arguments was given to a PHP function.
27
    ///
28
    /// The enum carries two integers - the first representing the minimum
29
    /// number of arguments expected, and the second representing the number of
30
    /// arguments that were received.
31
    IncorrectArguments(usize, usize),
32
    /// There was an error converting a Zval into a primitive type.
33
    ///
34
    /// The enum carries the data type of the Zval.
35
    ZvalConversion(DataType),
36
    /// The type of the Zval is unknown.
37
    ///
38
    /// The enum carries the integer representation of the type of Zval.
39
    UnknownDatatype(u32),
40
    /// Attempted to convert a [`ZvalTypeFlags`] struct to a [`DataType`].
41
    /// The flags did not contain a datatype.
42
    ///
43
    /// The enum carries the flags that were attempted to be converted to a
44
    /// [`DataType`].
45
    InvalidTypeToDatatype(ZvalTypeFlags),
46
    /// The function called was called in an invalid scope (calling
47
    /// class-related functions inside of a non-class bound function).
48
    InvalidScope,
49
    /// The pointer inside a given type was invalid, either null or pointing to
50
    /// garbage.
51
    InvalidPointer,
52
    /// The given property name does not exist.
53
    InvalidProperty,
54
    /// The string could not be converted into a C-string due to the presence of
55
    /// a NUL character.
56
    InvalidCString,
57
    /// The string could not be converted into a valid Utf8 string
58
    InvalidUtf8,
59
    /// Could not call the given function.
60
    Callable,
61
    /// An object was expected.
62
    Object,
63
    /// The object's class does not implement `__toString()`, so it cannot be
64
    /// converted into a string.
65
    ///
66
    /// The enum carries the name of the class.
67
    NotStringable(String),
68
    /// An invalid exception type was thrown.
69
    InvalidException(ClassFlags),
70
    /// Converting integer arguments resulted in an overflow.
71
    IntegerOverflow,
72
    /// An exception was thrown in a function.
73
    Exception(ZBox<ZendObject>),
74
    /// A failure occurred while registering the stream wrapper
75
    StreamWrapperRegistrationFailure,
76
    /// A failure occurred while unregistering the stream wrapper
77
    StreamWrapperUnregistrationFailure,
78
    /// The SAPI write function is not available
79
    SapiWriteUnavailable,
80
    /// Failed to make an object lazy (PHP 8.4+)
81
    LazyObjectFailed,
82
}
83

84
impl Display for Error {
85
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
×
86
        match self {
×
87
            Error::IncorrectArguments(n, expected) => write!(
×
88
                f,
×
89
                "Expected at least {expected} arguments, got {n} arguments."
90
            ),
91
            Error::ZvalConversion(ty) => write!(
×
92
                f,
×
93
                "Could not convert Zval from type {ty} into primitive type."
94
            ),
95
            Error::UnknownDatatype(dt) => write!(f, "Unknown datatype {dt}."),
×
96
            Error::InvalidTypeToDatatype(dt) => {
×
97
                write!(f, "Type flags did not contain a datatype: {dt:?}")
×
98
            }
99
            Error::InvalidScope => write!(f, "Invalid scope."),
×
100
            Error::InvalidPointer => write!(f, "Invalid pointer."),
×
101
            Error::InvalidProperty => write!(f, "Property does not exist on object."),
×
102
            Error::InvalidCString => write!(
×
103
                f,
×
104
                "String given contains NUL-bytes which cannot be present in a C string."
105
            ),
106
            Error::InvalidUtf8 => write!(f, "Invalid Utf8 byte sequence."),
×
107
            Error::Callable => write!(f, "Could not call given function."),
×
108
            Error::Object => write!(f, "An object was expected."),
×
NEW
109
            Error::NotStringable(class) => {
×
NEW
110
                write!(f, "{class} does not implement __toString().")
×
111
            }
112
            Error::InvalidException(flags) => {
×
113
                write!(f, "Invalid exception type was thrown: {flags:?}")
×
114
            }
115
            Error::IntegerOverflow => {
116
                write!(f, "Converting integer arguments resulted in an overflow.")
×
117
            }
118
            Error::Exception(e) => write!(f, "Exception was thrown: {e:?}"),
×
119
            Error::StreamWrapperRegistrationFailure => {
120
                write!(f, "A failure occurred while registering the stream wrapper")
×
121
            }
122
            Error::StreamWrapperUnregistrationFailure => {
123
                write!(
×
124
                    f,
×
125
                    "A failure occurred while unregistering the stream wrapper"
126
                )
127
            }
128
            Error::SapiWriteUnavailable => {
129
                write!(f, "The SAPI write function is not available")
×
130
            }
131
            Error::LazyObjectFailed => {
132
                write!(f, "Failed to make the object lazy")
×
133
            }
134
        }
135
    }
×
136
}
137

138
impl ErrorTrait for Error {}
139

140
impl From<NulError> for Error {
141
    fn from(_: NulError) -> Self {
×
142
        Self::InvalidCString
×
143
    }
×
144
}
145

146
impl From<TryFromIntError> for Error {
147
    fn from(_value: TryFromIntError) -> Self {
×
148
        Self::IntegerOverflow
×
149
    }
×
150
}
151

152
impl From<Error> for PhpException {
153
    fn from(err: Error) -> Self {
×
NEW
154
        match err {
×
NEW
155
            Error::Exception(mut obj) => {
×
NEW
156
                let message = obj.get_class_name().unwrap_or_else(|_| "Exception".into());
×
NEW
157
                let mut zv = Zval::new();
×
158
                // `set_object` increments the refcount and the `ZBox` releases its own
159
                // when it drops, so the zval ends up owning exactly the one reference
160
                // `obj` held. Attaching it keeps the original class, message and stack
161
                // trace instead of flattening them into a string.
NEW
162
                zv.set_object(&mut obj);
×
NEW
163
                Self::default(message).with_object(zv)
×
164
            }
NEW
165
            err => Self::default(err.to_string()),
×
166
        }
UNCOV
167
    }
×
168
}
169

170
/// Trigger an error that is reported in PHP the same way `trigger_error()` is.
171
///
172
/// See specific error type descriptions at <https://www.php.net/manual/en/errorfunc.constants.php>.
173
///
174
/// Does nothing if `message` contains a NUL byte, or if the error type bits do not
175
/// fit in a C `int`.
176
pub fn php_error(type_: &ErrorType, message: &str) {
×
177
    let Ok(c_string) = CString::new(message) else {
×
178
        return;
×
179
    };
NEW
180
    let Ok(bits) = c_int::try_from(type_.bits()) else {
×
NEW
181
        return;
×
182
    };
183

184
    // SAFETY: `php_error_docref` is declared `PHP_ATTRIBUTE_FORMAT(printf, 3, 4)`, so
185
    // `message` must be passed as a `%s` argument and never as the format itself,
186
    // which would interpret `%` sequences in it as varargs directives. Both pointers
187
    // are NUL-terminated and outlive the call.
188
    unsafe {
×
NEW
189
        php_error_docref(std::ptr::null(), bits, c"%s".as_ptr(), c_string.as_ptr());
×
190
    }
×
191
}
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc