#[repr(C)]
pub struct ZendClassObject<T> { pub obj: Option<T>, pub std: ZendObject, }
Expand description

Representation of a Zend class object in memory.

Fields§

§obj: Option<T>§std: ZendObject

Implementations§

Creates a new ZendClassObject of type T, where T is a RegisteredClass in PHP, storing the given value val inside the object.

Parameters
  • val - The value to store inside the object.
Panics

Panics if memory was unable to be allocated for the new object.

Examples found in repository?
src/types/class_object.rs (line 252)
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
    fn default() -> Self {
        ZendClassObject::new(T::default())
    }
}

impl<T: RegisteredClass + Clone> Clone for ZBox<ZendClassObject<T>> {
    fn clone(&self) -> Self {
        // SAFETY: All constructors of `NewClassObject` guarantee that it will contain a
        // valid pointer. The constructor also guarantees that the internal
        // `ZendClassObject` pointer will contain a valid, initialized `obj`,
        // therefore we can dereference both safely.
        unsafe {
            let mut new = ZendClassObject::new((***self).clone());
            zend_objects_clone_members(&mut new.std, &self.std as *const _ as *mut _);
            new
        }
    }

Creates a new ZendClassObject of type T, with an uninitialized internal object.

Safety

As the object is uninitialized, the caller must ensure the following until the internal object is initialized:

  • The object is never dereferenced to T.
  • The Clone implementation is never called.
  • The Debug implementation is never called.

If any of these conditions are not met while not initialized, the corresponding function will panic. Converting the object into its inner pointer with the into_raw function is valid, however.

Panics

Panics if memory was unable to be allocated for the new object.

Examples found in repository?
src/builders/class.rs (line 167)
164
165
166
167
168
169
        extern "C" fn create_object<T: RegisteredClass>(_: *mut ClassEntry) -> *mut ZendObject {
            // SAFETY: After calling this function, PHP will always call the constructor
            // defined below, which assumes that the object is uninitialized.
            let obj = unsafe { ZendClassObject::<T>::new_uninit() };
            obj.into_raw().get_mut_zend_obj()
        }

Initializes the class object with the value val.

Parameters
  • val - The value to initialize the object with.
Returns

Returns the old value in an Option if the object had already been initialized, None otherwise.

Examples found in repository?
src/builders/class.rs (line 201)
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
            extern fn constructor<T: RegisteredClass>(ex: &mut ExecuteData, _: &mut Zval) {
                let ConstructorMeta { constructor, .. } = match T::CONSTRUCTOR {
                    Some(c) => c,
                    None => {
                        PhpException::default("You cannot instantiate this class from PHP.".into())
                            .throw()
                            .expect("Failed to throw exception when constructing class");
                        return;
                    }
                };

                let this = match constructor(ex) {
                    ConstructorResult::Ok(this) => this,
                    ConstructorResult::Exception(e) => {
                        e.throw()
                            .expect("Failed to throw exception while constructing class");
                        return;
                    }
                    ConstructorResult::ArgError => return,
                };
                let this_obj = match ex.get_object::<T>() {
                    Some(obj) => obj,
                    None => {
                        PhpException::default("Failed to retrieve reference to `this` object.".into())
                            .throw()
                            .expect("Failed to throw exception while constructing class");
                        return;
                    }
                };
                this_obj.initialize(this);
            }

Returns a mutable reference to the ZendClassObject of a given zend object obj. Returns None if the given object is not of the type T.

Parameters
Examples found in repository?
src/types/class_object.rs (line 204)
202
203
204
205
    fn from_zend_object(obj: &'a ZendObject) -> Result<Self> {
        // TODO(david): replace with better error
        ZendClassObject::from_zend_obj(obj).ok_or(Error::InvalidScope)
    }

Returns a mutable reference to the ZendClassObject of a given zend object obj. Returns None if the given object is not of the type T.

Parameters
Examples found in repository?
src/types/class_object.rs (line 218)
217
218
219
    fn from_zend_object_mut(obj: &'a mut ZendObject) -> Result<Self> {
        ZendClassObject::from_zend_obj_mut(obj).ok_or(Error::InvalidScope)
    }
More examples
Hide additional examples
src/zend/ex.rs (line 143)
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
    pub fn parser_method<T: RegisteredClass>(
        &mut self,
    ) -> (ArgParser<'_, '_>, Option<&mut ZendClassObject<T>>) {
        let (parser, obj) = self.parser_object();
        (
            parser,
            obj.and_then(|obj| ZendClassObject::from_zend_obj_mut(obj)),
        )
    }

    /// Attempts to retrieve a reference to the underlying class object of the
    /// Zend object.
    ///
    /// Returns a [`ZendClassObject`] if the execution data contained a valid
    /// object of type `T`, otherwise returns [`None`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ext_php_rs::{types::Zval, zend::ExecuteData, prelude::*};
    ///
    /// #[php_class]
    /// #[derive(Debug)]
    /// struct Example;
    ///
    /// #[no_mangle]
    /// pub extern "C" fn example_fn(ex: &mut ExecuteData, retval: &mut Zval) {
    ///     let this = ex.get_object::<Example>();
    ///     dbg!(this);
    /// }
    ///
    /// #[php_module]
    /// pub fn module(module: ModuleBuilder) -> ModuleBuilder {
    ///     module
    /// }
    /// ```
    pub fn get_object<T: RegisteredClass>(&mut self) -> Option<&mut ZendClassObject<T>> {
        ZendClassObject::from_zend_obj_mut(self.get_self()?)
    }
src/zend/handlers.rs (line 57)
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
    unsafe extern "C" fn free_obj<T: RegisteredClass>(object: *mut ZendObject) {
        let obj = object
            .as_mut()
            .and_then(|obj| ZendClassObject::<T>::from_zend_obj_mut(obj))
            .expect("Invalid object pointer given for `free_obj`");

        // Manually drop the object as we don't want to free the underlying memory.
        ptr::drop_in_place(&mut obj.obj);

        zend_object_std_dtor(object)
    }

    unsafe extern "C" fn read_property<T: RegisteredClass>(
        object: *mut ZendObject,
        member: *mut ZendStr,
        type_: c_int,
        cache_slot: *mut *mut c_void,
        rv: *mut Zval,
    ) -> *mut Zval {
        #[inline(always)]
        unsafe fn internal<T: RegisteredClass>(
            object: *mut ZendObject,
            member: *mut ZendStr,
            type_: c_int,
            cache_slot: *mut *mut c_void,
            rv: *mut Zval,
        ) -> PhpResult<*mut Zval> {
            let obj = object
                .as_mut()
                .and_then(|obj| ZendClassObject::<T>::from_zend_obj_mut(obj))
                .ok_or("Invalid object pointer given")?;
            let prop_name = member
                .as_ref()
                .ok_or("Invalid property name pointer given")?;
            let self_ = &mut **obj;
            let props = T::get_metadata().get_properties();
            let prop = props.get(prop_name.as_str()?);

            // retval needs to be treated as initialized, so we set the type to null
            let rv_mut = rv.as_mut().ok_or("Invalid return zval given")?;
            rv_mut.u1.type_info = ZvalTypeFlags::Null.bits();

            Ok(match prop {
                Some(prop) => {
                    prop.get(self_, rv_mut)?;
                    rv
                }
                None => zend_std_read_property(object, member, type_, cache_slot, rv),
            })
        }

        match internal::<T>(object, member, type_, cache_slot, rv) {
            Ok(rv) => rv,
            Err(e) => {
                let _ = e.throw();
                (*rv).set_null();
                rv
            }
        }
    }

    unsafe extern "C" fn write_property<T: RegisteredClass>(
        object: *mut ZendObject,
        member: *mut ZendStr,
        value: *mut Zval,
        cache_slot: *mut *mut c_void,
    ) -> *mut Zval {
        #[inline(always)]
        unsafe fn internal<T: RegisteredClass>(
            object: *mut ZendObject,
            member: *mut ZendStr,
            value: *mut Zval,
            cache_slot: *mut *mut c_void,
        ) -> PhpResult<*mut Zval> {
            let obj = object
                .as_mut()
                .and_then(|obj| ZendClassObject::<T>::from_zend_obj_mut(obj))
                .ok_or("Invalid object pointer given")?;
            let prop_name = member
                .as_ref()
                .ok_or("Invalid property name pointer given")?;
            let self_ = &mut **obj;
            let props = T::get_metadata().get_properties();
            let prop = props.get(prop_name.as_str()?);
            let value_mut = value.as_mut().ok_or("Invalid return zval given")?;

            Ok(match prop {
                Some(prop) => {
                    prop.set(self_, value_mut)?;
                    value
                }
                None => zend_std_write_property(object, member, value, cache_slot),
            })
        }

        match internal::<T>(object, member, value, cache_slot) {
            Ok(rv) => rv,
            Err(e) => {
                let _ = e.throw();
                value
            }
        }
    }

    unsafe extern "C" fn get_properties<T: RegisteredClass>(
        object: *mut ZendObject,
    ) -> *mut ZendHashTable {
        #[inline(always)]
        unsafe fn internal<T: RegisteredClass>(
            object: *mut ZendObject,
            props: &mut ZendHashTable,
        ) -> PhpResult {
            let obj = object
                .as_mut()
                .and_then(|obj| ZendClassObject::<T>::from_zend_obj_mut(obj))
                .ok_or("Invalid object pointer given")?;
            let self_ = &mut **obj;
            let struct_props = T::get_metadata().get_properties();

            for (name, val) in struct_props {
                let mut zv = Zval::new();
                if val.get(self_, &mut zv).is_err() {
                    continue;
                }
                props.insert(name, zv).map_err(|e| {
                    format!("Failed to insert value into properties hashtable: {:?}", e)
                })?;
            }

            Ok(())
        }

        let props = zend_std_get_properties(object)
            .as_mut()
            .or_else(|| Some(ZendHashTable::new().into_raw()))
            .expect("Failed to get property hashtable");

        if let Err(e) = internal::<T>(object, props) {
            let _ = e.throw();
        }

        props
    }

    unsafe extern "C" fn has_property<T: RegisteredClass>(
        object: *mut ZendObject,
        member: *mut ZendStr,
        has_set_exists: c_int,
        cache_slot: *mut *mut c_void,
    ) -> c_int {
        #[inline(always)]
        unsafe fn internal<T: RegisteredClass>(
            object: *mut ZendObject,
            member: *mut ZendStr,
            has_set_exists: c_int,
            cache_slot: *mut *mut c_void,
        ) -> PhpResult<c_int> {
            let obj = object
                .as_mut()
                .and_then(|obj| ZendClassObject::<T>::from_zend_obj_mut(obj))
                .ok_or("Invalid object pointer given")?;
            let prop_name = member
                .as_ref()
                .ok_or("Invalid property name pointer given")?;
            let props = T::get_metadata().get_properties();
            let prop = props.get(prop_name.as_str()?);
            let self_ = &mut **obj;

            match has_set_exists {
                //
                // * 0 (has) whether property exists and is not NULL
                0 => {
                    if let Some(val) = prop {
                        let mut zv = Zval::new();
                        val.get(self_, &mut zv)?;
                        if !zv.is_null() {
                            return Ok(1);
                        }
                    }
                }
                //
                // * 1 (set) whether property exists and is true
                1 => {
                    if let Some(val) = prop {
                        let mut zv = Zval::new();
                        val.get(self_, &mut zv)?;

                        if zend_is_true(&mut zv) == 1 {
                            return Ok(1);
                        }
                    }
                }
                //
                // * 2 (exists) whether property exists
                2 => {
                    if prop.is_some() {
                        return Ok(1);
                    }
                }
                _ => return Err(
                    "Invalid value given for `has_set_exists` in struct `has_property` function."
                        .into(),
                ),
            };

            Ok(zend_std_has_property(
                object,
                member,
                has_set_exists,
                cache_slot,
            ))
        }

Returns a mutable reference to the underlying Zend object.

Examples found in repository?
src/types/object.rs (line 80)
77
78
79
80
81
    pub fn from_class_object<T: RegisteredClass>(obj: ZBox<ZendClassObject<T>>) -> ZBox<Self> {
        let this = obj.into_raw();
        // SAFETY: Consumed box must produce a well-aligned non-null pointer.
        unsafe { ZBox::from_raw(this.get_mut_zend_obj()) }
    }
More examples
Hide additional examples
src/builders/class.rs (line 168)
164
165
166
167
168
169
        extern "C" fn create_object<T: RegisteredClass>(_: *mut ClassEntry) -> *mut ZendObject {
            // SAFETY: After calling this function, PHP will always call the constructor
            // defined below, which assumes that the object is uninitialized.
            let obj = unsafe { ZendClassObject::<T>::new_uninit() };
            obj.into_raw().get_mut_zend_obj()
        }

Trait Implementations§

Formats the value using the given formatter. Read more
The resulting type after dereferencing.
Dereferences the value.
Mutably dereferences the value.
Extracts Self from the source ZendObject.
Extracts Self from the source ZendObject.
The corresponding type of the implemented value in PHP.
Attempts to retrieve an instance of Self from a reference to a Zval. Read more
The corresponding type of the implemented value in PHP.
Attempts to retrieve an instance of Self from a mutable reference to a Zval. Read more
The corresponding type of the implemented value in PHP.
Sets the content of a pre-existing zval. Returns a result containing nothing if setting the content was successful. Read more
Converts a Rust primitive type into a Zval. Returns a result containing the Zval if successful. Read more
Frees the memory pointed to by self, calling any destructors required in the process.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.