Skip to content

Commit

Permalink
Add instance_of() and get_class_entry() methods on ZendObject (davidc…
Browse files Browse the repository at this point in the history
…ole1340#197)

* adds `ZendObject::get_class_entry()` to retrieve the class entry of an object without casting pointers
* adds `ZendObject::instance_of()` to allow more idiomatic instanceof checks.
* adds a mention that `ZendObject::is_instance::<T>()` does not check the parent classes or interfaces. This bit me when I tried to check if `my_object.is_instance::<MyInterface>()` and it didn't work.
  • Loading branch information
ju1ius authored Nov 24, 2022
1 parent 580ad9f commit a331213
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/types/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,17 @@ impl ZendObject {
unsafe { ZBox::from_raw(this.get_mut_zend_obj()) }
}

/// Returns the [`ClassEntry`] associated with this object.
///
/// # Panics
///
/// Panics if the class entry is invalid.
pub fn get_class_entry(&self) -> &'static ClassEntry {
// SAFETY: it is OK to panic here since PHP would segfault anyway
// when encountering an object with no class entry.
unsafe { self.ce.as_ref() }.expect("Could not retrieve class entry.")
}

/// Attempts to retrieve the class name of the object.
pub fn get_class_name(&self) -> Result<String> {
unsafe {
Expand All @@ -91,8 +102,21 @@ impl ZendObject {
}
}

/// Returns whether this object is an instance of the given [`ClassEntry`].
///
/// This method checks the class and interface inheritance chain.
///
/// # Panics
///
/// Panics if the class entry is invalid.
pub fn instance_of(&self, ce: &ClassEntry) -> bool {
self.get_class_entry().instance_of(ce)
}

/// Checks if the given object is an instance of a registered class with
/// Rust type `T`.
///
/// This method doesn't check the class and interface inheritance chain.
pub fn is_instance<T: RegisteredClass>(&self) -> bool {
(self.ce as *const ClassEntry).eq(&(T::get_metadata().ce() as *const _))
}
Expand Down

0 comments on commit a331213

Please sign in to comment.