Skip to content
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

Add FromZval derive macro #75

Closed
davidcole1340 opened this issue Sep 20, 2021 · 1 comment · Fixed by #78
Closed

Add FromZval derive macro #75

davidcole1340 opened this issue Sep 20, 2021 · 1 comment · Fixed by #78
Labels
enhancement New feature or request

Comments

@davidcole1340
Copy link
Owner

Ability to derive FromZval (and potentially IntoZval) using a derive macro. Could be used in two situations:

  • Enums. Data type would be mixed, and would act as a mixed type parameter. Example:
#[derive(FromZval)]
pub enum IntOrBool {
    Integer(u32),
    Boolean(bool),
}

// translates to

impl FromZval<'_> for IntOrBool {
    const TYPE: DataType = DataType::Mixed;
    fn from_zval(zval: &'_ Zval) -> Option<Self> {
        if let Some(integer) = u32::from_zval(zval) {
            Some(integer)
        } else if let Some(boolean) = bool::from_zval(zval) {
            Some(boolean)
        } else {
            None
        }
    }
}
  • Structs. Data type would be object, and the struct fields would be read from the objects properties. Primarily for passing stdClass into Rust. Example:
#[derive(FromZval)]
pub struct ExampleStdClass {
    a: i32,
    b: String,
    c: bool,
}

// translates to

impl FromZval<'_> for ExampleStdClass {
    const TYPE: DataType = DataType::Object(None);

    fn from_zval(zval: &'_ Zval) -> Option<Self> {
        let obj = zval.object()?;

        Some(Self {
            a: obj.get_property("a").ok()?,
            b: obj.get_property("b").ok()?,
            c: obj.get_property("c").ok()?,
        })
    }
}
@vodik
Copy link
Collaborator

vodik commented Sep 21, 2021

I like it. It should be paired with a IntoZval as well.

Something worth keeping an eye on is PHP 8.1 enums. I don't think this should conflict through: a reasonable approach is probably to either add a new #[php_enum] attribute (or make php_class smarter - idk how its implemented under the hood) and make sure that its mutually exclusive from these derive macros.

@davidcole1340 davidcole1340 added the enhancement New feature or request label Oct 1, 2021
@davidcole1340 davidcole1340 linked a pull request Oct 1, 2021 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants