Symfony Rule Engine Bundle - Parses & Evaluates Rules Written in a JavaScript-like Syntax
Switch branches/tags
Nothing to show
Clone or download
Latest commit 176dfd5 Apr 27, 2018
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src/nicoSWD/RuleBundle Improve autowire Apr 27, 2018
tests/nicoSWD/RuleBundle/Model Cleanup Oct 15, 2017
.gitignore Cleanup Oct 15, 2017
.scrutinizer.yml Add travis / scrutinizer config Oct 13, 2017
.travis.yml Cleanup Oct 15, 2017
LICENSE.md Add license Oct 13, 2017
README.md Update README.md Apr 14, 2018
composer.json Cleanup Oct 15, 2017
phpunit.xml.dist Cleanup Oct 15, 2017

README.md

Symfony Rule Engine Bundle

build coverage Scrutinizer Code Quality Latest Stable Version

SensioLabsInsight

This package bundles nicoSWD/php-rule-parser

Requires PHP >= 7.0

Compatible with Symfony 3 and 4!

Install

$ composer require nicoswd/symfony-rule-engine-bundle
<?php

// in AppKernel::registerBundles()
$bundles = [
    // ...
    new nicoSWD\RuleBundle\RuleBundle(),
    // ...
];

Usage Example

<?php

$rule = '[1, 4, 3].join(glue) === "1-4-3"';
$variables = ['glue' => '-'];

$result = $this->get('rule_parser')->isTrue($rule, $variables);
var_dump($result); // bool(true)

Custom Functions

Custom functions are automatically discovered. They just need to be configured as service with the tag nico_swd.rule.function.

If you have multiple functions inside the same directory, the easiest way to make them visible to the bundle is this:

services.yml

AppBundle\Functions\:
    resource: '../../src/AppBundle/Functions'
    tags: ['nico_swd.rule.function']

Furthermore, custom functions must implement nicoSWD\Rules\Core\CallableUserFunction like in the example below

<?php

namespace AppBundle\Functions;

use nicoSWD\Rules\Core\CallableUserFunction;
use nicoSWD\Rules\Tokens\BaseToken;
use nicoSWD\Rules\Tokens\TokenArray;

class ArrayFilter implements CallableUserFunction
{
    /**
     * @param BaseToken $param
     * @param BaseToken $param ...
     * @return BaseToken
     */
    public function call($param = null)
    {
        // Make sure this functions only works on arrays
        if (!$param instanceof TokenArray) {
            throw new \InvalidArgumentException();
        }

        return new TokenArray(
            array_values(
                array_filter(
                    $param->toArray()
                )
            )
        );
    }

    public function getName(): string
    {
        return 'array_filter';
    }
}

The functions optionally retrieve instances of nicoSWD\Rules\Tokens\BaseToken as arguments, and always must return one as well.

<?php

$rule = 'array_filter([0, false, 1]) === [1]';

$result = $this->get('rule_parser')->isTrue($rule);
var_dump($result); // bool(true)