Skip to content

Support class static properties #137

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Nov 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 1 addition & 18 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,61 +47,44 @@ jobs:
args: --manifest-path phper-sys/Cargo.toml
continue-on-error: true

- name: Delay
run: sleep 20

- name: Cargo publish phper-build
uses: actions-rs/cargo@v1
with:
command: publish
args: --manifest-path phper-build/Cargo.toml
continue-on-error: true

- name: Delay
run: sleep 20

- name: Cargo publish phper-macros
uses: actions-rs/cargo@v1
with:
command: publish
args: --manifest-path phper-macros/Cargo.toml
continue-on-error: true

- name: Delay
run: sleep 20

- name: Cargo publish phper-alloc
uses: actions-rs/cargo@v1
with:
command: publish
args: --manifest-path phper-alloc/Cargo.toml
continue-on-error: true

- name: Delay
run: sleep 20

- name: Cargo publish phper-test
uses: actions-rs/cargo@v1
with:
command: publish
args: --manifest-path phper-test/Cargo.toml
continue-on-error: true

- name: Delay
run: sleep 20

- name: Cargo publish phper
uses: actions-rs/cargo@v1
with:
command: publish
args: --manifest-path phper/Cargo.toml
continue-on-error: true

- name: Delay
run: sleep 20

- name: Cargo publish phper-doc
uses: actions-rs/cargo@v1
with:
command: publish
args: --manifest-path phper-doc/Cargo.toml
continue-on-error: true
58 changes: 54 additions & 4 deletions phper/src/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use std::{
ffi::{c_void, CString},
fmt::Debug,
marker::PhantomData,
mem::{size_of, zeroed, ManuallyDrop},
mem::{replace, size_of, zeroed, ManuallyDrop},
os::raw::c_int,
ptr::null_mut,
rc::Rc,
Expand Down Expand Up @@ -181,6 +181,37 @@ impl ClassEntry {
pub fn is_instance_of(&self, parent: &ClassEntry) -> bool {
unsafe { phper_instanceof_function(self.as_ptr(), parent.as_ptr()) }
}

/// Get the static property by name of class.
///
/// Return None when static property hasn't register by
/// [ClassEntity::add_static_property].
pub fn get_static_property(&self, name: impl AsRef<str>) -> Option<&ZVal> {
let ptr = self.as_ptr() as *mut _;
let prop = Self::inner_get_static_property(ptr, name);
unsafe { ZVal::try_from_ptr(prop) }
}

/// Set the static property by name of class.
///
/// Return `Some(x)` where `x` is the previous value of static property, or
/// return `None` when static property hasn't register by
/// [ClassEntity::add_static_property].
pub fn set_static_property(&self, name: impl AsRef<str>, val: impl Into<ZVal>) -> Option<ZVal> {
let ptr = self.as_ptr() as *mut _;
let prop = Self::inner_get_static_property(ptr, name);
let prop = unsafe { ZVal::try_from_mut_ptr(prop) };
prop.map(|prop| replace(prop, val.into()))
}

fn inner_get_static_property(scope: *mut zend_class_entry, name: impl AsRef<str>) -> *mut zval {
let name = name.as_ref();

unsafe {
#[allow(clippy::useless_conversion)]
zend_read_static_property(scope, name.as_ptr().cast(), name.len(), true.into())
}
}
}

impl Debug for ClassEntry {
Expand Down Expand Up @@ -444,6 +475,19 @@ impl<T: 'static> ClassEntity<T> {
.push(PropertyEntity::new(name, visibility, value));
}

/// Declare static property.
///
/// The argument `value` should be `Copy` because 'zend_declare_property'
/// receive only scalar zval , otherwise will report fatal error:
/// "Internal zvals cannot be refcounted".
pub fn add_static_property(
&mut self, name: impl Into<String>, visibility: Visibility, value: impl Into<Scalar>,
) {
let mut entity = PropertyEntity::new(name, visibility, value);
entity.set_vis_static();
self.property_entities.push(entity);
}

/// Register class to `extends` the parent class.
///
/// *Because in the `MINIT` phase, the class starts to register, so the*
Expand Down Expand Up @@ -719,24 +763,30 @@ unsafe extern "C" fn interface_init_handler(
/// Builder for declare class property.
struct PropertyEntity {
name: String,
visibility: Visibility,
visibility: RawVisibility,
value: Scalar,
}

impl PropertyEntity {
fn new(name: impl Into<String>, visibility: Visibility, value: impl Into<Scalar>) -> Self {
Self {
name: name.into(),
visibility,
visibility: visibility as RawVisibility,
value: value.into(),
}
}

#[inline]
pub(crate) fn set_vis_static(&mut self) -> &mut Self {
self.visibility |= ZEND_ACC_STATIC;
self
}

#[allow(clippy::useless_conversion)]
pub(crate) fn declare(&self, ce: *mut zend_class_entry) {
let name = self.name.as_ptr().cast();
let name_length = self.name.len().try_into().unwrap();
let access_type = self.visibility as u32 as i32;
let access_type = self.visibility as i32;

unsafe {
match &self.value {
Expand Down
6 changes: 6 additions & 0 deletions phper/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -507,3 +507,9 @@ pub unsafe fn throw(e: impl Throwable) {
let mut val = ManuallyDrop::new(ZVal::from(obj));
zend_throw_exception_object(val.as_mut_ptr());
}

/// Equivalent to `Ok::<_, phper::Error>(value)`.
#[inline]
pub fn ok<T>(t: T) -> Result<T> {
Ok(t)
}
2 changes: 1 addition & 1 deletion phper/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ pub mod types;
mod utils;
pub mod values;

pub use crate::errors::{Error, Result};
pub use crate::errors::{ok, Error, Result};
pub use phper_alloc as alloc;
pub use phper_macros::*;
pub use phper_sys as sys;
7 changes: 3 additions & 4 deletions phper/src/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
//! Apis relate to [zend_object].

use crate::{
alloc::EBox,
classes::ClassEntry,
functions::{call_internal, call_raw_common, ZFunc},
sys::*,
Expand Down Expand Up @@ -185,7 +184,7 @@ impl ZObj {
#[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());
let mut val = val.into();
unsafe {
#[cfg(phper_major_version = "8")]
{
Expand All @@ -194,7 +193,7 @@ impl ZObj {
&mut self.inner,
name.as_ptr().cast(),
name.len().try_into().unwrap(),
EBox::into_raw(val).cast(),
val.as_mut_ptr(),
)
}
#[cfg(phper_major_version = "7")]
Expand All @@ -206,7 +205,7 @@ impl ZObj {
&mut zv,
name.as_ptr().cast(),
name.len().try_into().unwrap(),
EBox::into_raw(val).cast(),
val.as_mut_ptr(),
)
}
}
Expand Down
31 changes: 29 additions & 2 deletions tests/integration/src/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
use phper::{
alloc::RefClone,
classes::{
array_access_class, iterator_class, ClassEntity, InterfaceEntity, StaticInterface,
StaticStateClass, Visibility,
array_access_class, iterator_class, ClassEntity, ClassEntry, InterfaceEntity,
StaticInterface, StaticStateClass, Visibility,
},
functions::Argument,
modules::Module,
Expand All @@ -24,6 +24,7 @@ pub fn integrate(module: &mut Module) {
integrate_a(module);
integrate_foo(module);
integrate_i_bar(module);
integrate_static_props(module);
}

fn integrate_a(module: &mut Module) {
Expand Down Expand Up @@ -154,3 +155,29 @@ fn integrate_i_bar(module: &mut Module) {

module.add_interface(interface);
}

fn integrate_static_props(module: &mut Module) {
let mut class = ClassEntity::new("IntegrationTest\\PropsHolder");

class.add_static_property("foo", Visibility::Public, "bar");

class.add_static_property("foo1", Visibility::Private, 12345i64);

class.add_static_method("getFoo1", Visibility::Public, |_| {
let val = ClassEntry::from_globals("IntegrationTest\\PropsHolder")?
.get_static_property("foo1")
.map(ToOwned::to_owned)
.unwrap_or_default();
phper::ok(val)
});

class
.add_static_method("setFoo1", Visibility::Public, |params| {
let foo1 = ClassEntry::from_globals("IntegrationTest\\PropsHolder")?
.set_static_property("foo1", params[0].to_owned());
phper::ok(foo1)
})
.argument(Argument::by_val("val"));

module.add_class(class);
}
18 changes: 18 additions & 0 deletions tests/integration/src/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,24 @@ pub fn integrate(module: &mut Module) {
)
.argument(Argument::by_val("obj"));

module.add_function("integrate_objects_set_props", |_| {
let mut o = ZObject::new_by_std_class();

o.set_property("foo", "bar");
assert_eq!(o.get_property("foo").as_z_str().unwrap().to_bytes(), b"bar");

o.set_property("foo", ());
assert_eq!(o.get_property("foo").as_null(), Some(()));

o.set_property("foo", true);
assert_eq!(o.get_property("foo").as_bool(), Some(true));

o.set_property("foo", ZVal::from(100i64));
assert_eq!(o.get_property("foo").as_long(), Some(100i64));

phper::ok(())
});

let class_a =
ClassEntity::new_with_state_constructor("IntegrationTest\\Objects\\A", || 123456i64);
module.add_class(class_a);
Expand Down
8 changes: 8 additions & 0 deletions tests/integration/tests/php/classes.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,11 @@
$doSomethings = $interface->getMethod("doSomethings");
assert_true($doSomethings->isPublic());
assert_true($doSomethings->isAbstract());

// Test get or set static properties.
assert_eq(IntegrationTest\PropsHolder::$foo, "bar");

assert_eq(IntegrationTest\PropsHolder::getFoo1(), 12345);
$pre_foo1 = IntegrationTest\PropsHolder::setFoo1("baz");
assert_eq($pre_foo1, 12345);
assert_eq(IntegrationTest\PropsHolder::getFoo1(), "baz");
1 change: 1 addition & 0 deletions tests/integration/tests/php/objects.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
integrate_objects_call();
integrate_objects_to_ref_owned(new stdClass());
integrate_objects_to_ref_clone(new stdClass());
integrate_objects_set_props();

$a = new IntegrationTest\Objects\A();
assert_throw(function () use ($a) { $a2 = clone $a; }, "Error", 0, "Trying to clone an uncloneable object of class IntegrationTest\\Objects\\A");
Expand Down