php-rule-parser icon indicating copy to clipboard operation
php-rule-parser copied to clipboard

How to can I register a new function?

Open dmouse opened this issue 7 years ago • 3 comments

I'm trying to add a new function to use each function in my custom code

dmouse avatar Jan 18 '18 22:01 dmouse

Can you show me an example on how this would look like in your code?

What are you planning to do with this?

nicoSWD avatar Jan 18 '18 23:01 nicoSWD

I was looking to add a modulo function, basically [variable] % 10 == 0.

But I see you allow class to be set as variables.

 class User
{
    // ...

    public function points(): int
    {
        return 1337;    
    }
}

$variables = [
    'user' => new User(),
];

jalite1991 avatar Jan 31 '22 21:01 jalite1991

Hey @jalite1991

you have two options. If you're using Symfony, there's a bundle with native support for custom functions.

The other option is to use a custom class and pass it as variable

<?php

$math = new class
{
    public function mod($x, $y)
    {
        return $x % $y;
    }
};

$rule = new Rule('math.mod(13, 3) === 1', ['math' => $math]);
var_dump($rule->isTrue()); // bool(true)

I hope this helps!

nicoSWD avatar Jan 31 '22 23:01 nicoSWD