phper 0.10.2

The framework that allows us to write PHP extensions using pure and safe Rust whenever possible.
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
// Copyright (c) 2022 PHPER Framework Team
// PHPER is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan
// PSL v2. You may obtain a copy of Mulan PSL v2 at:
//          http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.

//! Apis relate to [crate::sys::zend_object].

use crate::{
    alloc::EBox,
    classes::ClassEntry,
    functions::{call_internal, ZendFunc},
    sys::*,
    values::ZVal,
};
use phper_alloc::ToRefOwned;
use std::{
    any::Any,
    borrow::Borrow,
    convert::TryInto,
    fmt::{self, Debug},
    intrinsics::transmute,
    marker::PhantomData,
    mem::{forget, size_of, zeroed, ManuallyDrop},
    ops::{Deref, DerefMut},
    ptr::null_mut,
};

/// Wrapper of [crate::sys::zend_object].
#[repr(transparent)]
pub struct ZObj {
    inner: zend_object,
    _p: PhantomData<*mut ()>,
}

impl ZObj {
    /// Wraps a raw pointer.
    ///
    /// # Safety
    ///
    /// Create from raw pointer.
    ///
    /// # Panics
    ///
    /// Panics if pointer is null.
    #[inline]
    pub unsafe fn from_ptr<'a>(ptr: *const zend_object) -> &'a Self {
        (ptr as *const Self).as_ref().expect("ptr should't be null")
    }

    /// Wraps a raw pointer, return None if pointer is null.
    ///
    /// # Safety
    ///
    /// Create from raw pointer.
    #[inline]
    pub unsafe fn try_from_ptr<'a>(ptr: *const zend_object) -> Option<&'a Self> {
        (ptr as *const Self).as_ref()
    }

    /// Wraps a raw pointer.
    ///
    /// # Safety
    ///
    /// Create from raw pointer.
    ///
    /// # Panics
    ///
    /// Panics if pointer is null.
    #[inline]
    pub unsafe fn from_mut_ptr<'a>(ptr: *mut zend_object) -> &'a mut Self {
        (ptr as *mut Self).as_mut().expect("ptr should't be null")
    }

    /// Wraps a raw pointer, return None if pointer is null.
    ///
    /// # Safety
    ///
    /// Create from raw pointer.
    #[inline]
    pub unsafe fn try_from_mut_ptr<'a>(ptr: *mut zend_object) -> Option<&'a mut Self> {
        (ptr as *mut Self).as_mut()
    }

    /// Returns a raw pointer wrapped.
    pub const fn as_ptr(&self) -> *const zend_object {
        &self.inner
    }

    /// Returns a raw pointer wrapped.
    #[inline]
    pub fn as_mut_ptr(&mut self) -> *mut zend_object {
        &mut self.inner
    }

    /// Upgrade to state obj.
    ///
    /// # Safety
    ///
    /// Should only call this method for the class of object defined by the
    /// extension created by `phper`, otherwise, memory problems will caused.
    pub unsafe fn as_state_obj<T: 'static>(&self) -> &StateObj<T> {
        transmute(self)
    }

    /// Upgrade to mutable state obj.
    ///
    /// # Safety
    ///
    /// Should only call this method for the class of object defined by the
    /// extension created by `phper`, otherwise, memory problems will caused.
    pub unsafe fn as_mut_state_obj<T: 'static>(&mut self) -> &mut StateObj<T> {
        transmute(self)
    }

    /// Get inner state.
    ///
    /// # Safety
    ///
    /// Should only call this method for the class of object defined by the
    /// extension created by `phper`, otherwise, memory problems will caused.
    pub unsafe fn as_state<T: 'static>(&self) -> &T {
        let eo = StateObject::fetch(&self.inner);
        eo.state.downcast_ref().unwrap()
    }

    /// Get inner mutable state.
    ///
    /// # Safety
    ///
    /// Should only call this method for the class of object defined by the
    /// extension created by `phper`, otherwise, memory problems will caused.
    pub unsafe fn as_mut_state<T: 'static>(&mut self) -> &mut T {
        let eo = StateObject::fetch_mut(&mut self.inner);
        eo.state.downcast_mut().unwrap()
    }

    /// Get the inner handle of object.
    #[inline]
    pub fn handle(&self) -> u32 {
        self.inner.handle
    }

    /// Get the class reference of object.
    pub fn get_class(&self) -> &ClassEntry {
        unsafe { ClassEntry::from_ptr(self.inner.ce) }
    }

    /// Get the mutable class reference of object.
    pub fn get_mut_class(&mut self) -> &mut ClassEntry {
        unsafe { ClassEntry::from_mut_ptr(self.inner.ce) }
    }

    /// Get the property by name of object.
    pub fn get_property(&self, name: impl AsRef<str>) -> &ZVal {
        let object = self.as_ptr() as *mut _;
        let prop = Self::inner_get_property(self.inner.ce, object, name);
        unsafe { ZVal::from_ptr(prop) }
    }

    /// Get the mutable property by name of object.
    pub fn get_mut_property(&mut self, name: impl AsRef<str>) -> &mut ZVal {
        let object = self.as_mut_ptr();
        let prop = Self::inner_get_property(self.inner.ce, object, name);
        unsafe { ZVal::from_mut_ptr(prop) }
    }

    #[allow(clippy::useless_conversion)]
    fn inner_get_property(
        scope: *mut zend_class_entry, object: *mut zend_object, name: impl AsRef<str>,
    ) -> *mut zval {
        let name = name.as_ref();

        unsafe {
            #[cfg(phper_major_version = "8")]
            {
                zend_read_property(
                    scope,
                    object,
                    name.as_ptr().cast(),
                    name.len().try_into().unwrap(),
                    true.into(),
                    null_mut(),
                )
            }
            #[cfg(phper_major_version = "7")]
            {
                let mut zv = std::mem::zeroed::<zval>();
                phper_zval_obj(&mut zv, object);
                zend_read_property(
                    scope,
                    &mut zv,
                    name.as_ptr().cast(),
                    name.len().try_into().unwrap(),
                    true.into(),
                    null_mut(),
                )
            }
        }
    }

    /// Set the property by name of object.
    #[allow(clippy::useless_conversion)]
    pub fn set_property(&mut self, name: impl AsRef<str>, val: impl Into<ZVal>) {
        let name = name.as_ref();
        let val = EBox::new(val.into());
        unsafe {
            #[cfg(phper_major_version = "8")]
            {
                zend_update_property(
                    self.inner.ce,
                    &mut self.inner,
                    name.as_ptr().cast(),
                    name.len().try_into().unwrap(),
                    EBox::into_raw(val).cast(),
                )
            }
            #[cfg(phper_major_version = "7")]
            {
                let mut zv = std::mem::zeroed::<zval>();
                phper_zval_obj(&mut zv, self.as_mut_ptr());
                zend_update_property(
                    self.inner.ce,
                    &mut zv,
                    name.as_ptr().cast(),
                    name.len().try_into().unwrap(),
                    EBox::into_raw(val).cast(),
                )
            }
        }
    }

    /// Call the object method by name.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use phper::{alloc::EBox, classes::ClassEntry, values::ZVal};
    ///
    /// fn example() -> phper::Result<ZVal> {
    ///     let mut memcached = ClassEntry::from_globals("Memcached")?.new_object(&mut [])?;
    ///     memcached.call(
    ///         "addServer",
    ///         &mut [ZVal::from("127.0.0.1"), ZVal::from(11211)],
    ///     )?;
    ///     let r = memcached.call("get", &mut [ZVal::from("hello")])?;
    ///     Ok(r)
    /// }
    /// ```
    pub fn call(
        &mut self, method_name: &str, arguments: impl AsMut<[ZVal]>,
    ) -> crate::Result<ZVal> {
        let mut method = method_name.into();
        call_internal(&mut method, Some(self), arguments)
    }

    /// Return bool represents whether the constructor exists.
    pub(crate) fn call_construct(&mut self, arguments: impl AsMut<[ZVal]>) -> crate::Result<bool> {
        unsafe {
            match (*self.inner.handlers).get_constructor {
                Some(get_constructor) => {
                    let f = get_constructor(self.as_mut_ptr());
                    if f.is_null() {
                        Ok(false)
                    } else {
                        let zend_fn = ZendFunc::from_mut_ptr(f);
                        zend_fn.call(Some(self), arguments)?;
                        Ok(true)
                    }
                }
                None => Ok(false),
            }
        }
    }
}

impl ToOwned for ZObj {
    type Owned = ZObject;

    /// The `to_owned` will do the copy like in PHP `$cloned_object = clone
    /// $some_object();`.
    #[inline]
    fn to_owned(&self) -> Self::Owned {
        clone_obj(self.as_ptr())
    }
}

impl ToRefOwned for ZObj {
    type Owned = ZObject;

    fn to_ref_owned(&mut self) -> Self::Owned {
        let mut val = ManuallyDrop::new(ZVal::default());
        unsafe {
            phper_zval_obj(val.as_mut_ptr(), self.as_mut_ptr());
            phper_z_addref_p(val.as_mut_ptr());
            ZObject::from_raw(val.as_mut_z_obj().unwrap().as_mut_ptr())
        }
    }
}

impl Debug for ZObj {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ZObj")
            .field("class", &self.get_class().get_name().to_c_str())
            .field("handle", &self.handle())
            .finish()
    }
}

/// Wrapper of [crate::sys::zend_object].
pub struct ZObject {
    inner: *mut ZObj,
}

impl ZObject {
    /// Another way to new object like [crate::classes::ClassEntry::new_object].
    pub fn new(class_entry: &ClassEntry, arguments: impl AsMut<[ZVal]>) -> crate::Result<Self> {
        class_entry.new_object(arguments)
    }

    /// New object, like `new`, but get class by [`ClassEntry::from_globals`].
    pub fn new_by_class_name(
        class_name: impl AsRef<str>, arguments: &mut [ZVal],
    ) -> crate::Result<Self> {
        let class_entry = ClassEntry::from_globals(class_name)?;
        Self::new(class_entry, arguments)
    }

    /// New object with class `stdClass`.
    pub fn new_by_std_class() -> Self {
        Self::new_by_class_name("stdclass", &mut []).unwrap()
    }

    /// Create owned object From raw pointer, usually used in pairs with
    /// `into_raw`.
    ///
    /// # Safety
    ///
    /// This function is unsafe because improper use may lead to memory
    /// problems. For example, a double-free may occur if the function is called
    /// twice on the same raw pointer.
    #[inline]
    pub unsafe fn from_raw(ptr: *mut zend_object) -> Self {
        Self {
            inner: ZObj::from_mut_ptr(ptr),
        }
    }

    /// Consumes and returning a wrapped raw pointer.
    #[inline]
    pub fn into_raw(mut self) -> *mut zend_object {
        let ptr = self.as_mut_ptr();
        forget(self);
        ptr
    }
}

impl Clone for ZObject {
    /// The clone will do the copy like in PHP `$cloned_object = clone
    /// $some_object();`.
    #[inline]
    fn clone(&self) -> Self {
        clone_obj(self.as_ptr())
    }
}

impl Deref for ZObject {
    type Target = ZObj;

    fn deref(&self) -> &Self::Target {
        unsafe { self.inner.as_ref().unwrap() }
    }
}

impl DerefMut for ZObject {
    fn deref_mut(&mut self) -> &mut Self::Target {
        unsafe { self.inner.as_mut().unwrap() }
    }
}

impl Borrow<ZObj> for ZObject {
    fn borrow(&self) -> &ZObj {
        self.deref()
    }
}

impl Drop for ZObject {
    fn drop(&mut self) {
        unsafe {
            phper_zend_object_release(self.as_mut_ptr());
        }
    }
}

impl Debug for ZObject {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ZObject")
            .field("class", &self.get_class().get_name().to_c_str())
            .field("handle", &self.handle())
            .finish()
    }
}

fn clone_obj(obj: *const zend_object) -> ZObject {
    unsafe {
        ZObject::from_raw({
            let mut zv = zeroed::<zval>();
            phper_zval_obj(&mut zv, obj as *mut _);
            let handlers = phper_z_obj_ht_p(&zv);

            let ptr = {
                #[cfg(phper_major_version = "7")]
                {
                    &mut zv as *mut _
                }
                #[cfg(phper_major_version = "8")]
                {
                    obj as *mut _
                }
            };

            match (*handlers).clone_obj {
                Some(clone_obj) => clone_obj(ptr),
                None => zend_objects_clone_obj(ptr),
            }
        })
    }
}

/// The object owned state, usually as the parameter of method handler.
#[repr(transparent)]
pub struct StateObj<T> {
    inner: ZObj,
    _p: PhantomData<T>,
}

impl<T: 'static> StateObj<T> {
    /// Get inner state.
    pub fn as_state(&self) -> &T {
        unsafe { self.inner.as_state() }
    }

    /// Get inner mutable state.
    pub fn as_mut_state(&mut self) -> &mut T {
        unsafe { self.inner.as_mut_state() }
    }
}

impl<T> Deref for StateObj<T> {
    type Target = ZObj;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<T> DerefMut for StateObj<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

pub(crate) type ManuallyDropState = ManuallyDrop<Box<dyn Any>>;

/// The Object contains `zend_object` and the user defined state data.
#[repr(C)]
pub(crate) struct StateObject {
    state: ManuallyDropState,
    object: zend_object,
}

impl StateObject {
    pub(crate) const fn offset() -> usize {
        size_of::<ManuallyDropState>()
    }

    pub(crate) unsafe fn fetch(object: &zend_object) -> &Self {
        (((object as *const _ as usize) - StateObject::offset()) as *const Self)
            .as_ref()
            .unwrap()
    }

    pub(crate) unsafe fn fetch_mut(object: &mut zend_object) -> &mut Self {
        (((object as *mut _ as usize) - StateObject::offset()) as *mut Self)
            .as_mut()
            .unwrap()
    }

    pub(crate) fn fetch_ptr(object: *mut zend_object) -> *mut Self {
        (object as usize - StateObject::offset()) as *mut Self
    }

    pub(crate) unsafe fn drop_state(this: *mut Self) {
        let state = &mut (*this).state;
        ManuallyDrop::drop(state);
    }

    pub(crate) unsafe fn as_mut_state<'a>(this: *mut Self) -> &'a mut ManuallyDropState {
        &mut (*this).state
    }

    pub(crate) unsafe fn as_mut_object<'a>(this: *mut Self) -> &'a mut zend_object {
        &mut (*this).object
    }
}