PHPackages                             kennyth01/php-rules-engine - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. kennyth01/php-rules-engine

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

kennyth01/php-rules-engine
==========================

A PHP rules engine inspired by CacheControl/json-rules-engine, enabling dynamic rule evaluation based on conditions and facts.

1.0.6(2mo ago)07.6k↓19.6%[1 issues](https://github.com/kennyth01/php-rules-engine/issues)MITPHPCI passing

Since Nov 8Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/kennyth01/php-rules-engine)[ Packagist](https://packagist.org/packages/kennyth01/php-rules-engine)[ RSS](/packages/kennyth01-php-rules-engine/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (2)Versions (9)Used By (0)

PHP Rules Engine
================

[](#php-rules-engine)

[![Run tests](https://github.com/kennyth01/php-rules-engine/actions/workflows/php.yml/badge.svg)](https://github.com/kennyth01/php-rules-engine/actions/workflows/php.yml)

`kennyth01/php-rules-engine` is a lightweight and flexible PHP rules engine that evaluates complex conditional logic using JSON-based rule configurations. It is designed to handle dynamic, reusable, and maintainable rule logic, making it ideal for applications with complex business requirements that must adapt to changing conditions.

This library, inspired by the `json-rules-engine`, ([link](https://github.com/CacheControl/json-rules-engine)) enables developers to define rules with nested conditions, logical operators (`all`, `any`, `not`), and rule dependencies.

Features
--------

[](#features)

- **JSON-Configurable Rules**: Easily define rules and conditions in JSON format.
- **Fact-to-Fact Comparison**: Compare two dynamic facts at runtime instead of comparing to static values.
- **Rule Dependencies**: Reference other rules as conditions to create complex evaluations.
- **Logical Operators**: Supports `all` (AND), `any` (OR), and `not` operators, allowing for nested conditions.
- **Custom Events and Failure Messages**: Attach custom messages for success or failure, making evaluations easy to interpret.
- **Interpret Rules**: Outputs a human readable English interpretation of the condition using logical operators.

Installation
------------

[](#installation)

Install via Composer:

```
composer require kennyth01/php-rules-engine
```

Basic Example
-------------

[](#basic-example)

This example demonstrates an engine for detecting whether a basketball player has fouled out (a player who commits five personal fouls over the course of a 40-minute game, or six in a 48-minute game, fouls out).

1. Define the rule (lets assume you store this in `rule.player.isFouledOut.json`)

```
{
   "name":"rule.player.isFouledOut",
   "conditions": {
     "any": [
       {
         "all": [
           {
             "fact": "gameDuration",
             "operator": "equal",
             "value": 40
           },
           {
             "fact": "personalFoulCount",
             "operator": "greaterThanInclusive",
             "value": 5
           }
         ],
         "name": "short foul limit"
       },
       {
         "all": [
           {
             "fact": "gameDuration",
             "operator": "equal",
             "value": 48
           },
           {
             "not": {
               "fact": "personalFoulCount",
               "operator": "lessThan",
               "value": 6
             }
           }
         ],
         "name": "long foul limit"
       }
     ]
   },
   "event": {
     "type": "fouledOut",
     "params": {
       "message": "Player has fouled out!"
     }
   },
   "failureEvent": {
      "type": "fouledOut",
      "params": {
         "message": "Player has not fouled out"
      }
    }
 }
```

2. Trigger the engine and evaluate

```
$engine = new Engine();
$rule = json_decode(file_get_contents('rule.player.isFouledOut.json'), true);

$engine->addRule(new Rule($rule));
$engine->addFact('personalFoulCount', 6);
$engine->addFact('gameDuration', 40);

$engine->setTargetRule('rule.player.isFouledOut');

$result = $engine->evaluate();
print_r($result);
```

3. Output Example

```
[
    'type' => 'fouledOut',
    'params' => [
        'message' => 'Player has fouled out!'
    ],
    'facts' => [
        'personalFoulCount' => 6,
        'gameDuration' => 40

    ],
    'interpretation' => '((gameDuration is equal to 40 AND personalFoulCount is >= 5) OR (gameDuration is equal to 48 AND NOT (personalFoulCount is less than 6)))'
]
```

Advanced Examples
-----------------

[](#advanced-examples)

For other examples, refer to the `tests` directory

### Fact-to-Fact Comparison

[](#fact-to-fact-comparison)

The engine supports comparing two facts dynamically at runtime. This allows for flexible rule evaluation where comparison values can change based on context.

**Example: Speed Limit Check**

```
$engine = new Engine();

$ruleConfig = [
    "name" => "speed.check",
    "conditions" => [
        "all" => [
            [
                "fact" => "currentSpeed",
                "operator" => "lessThanInclusive",
                "value" => ["fact" => "speedLimit"]  // Compare to another fact
            ]
        ]
    ],
    "event" => ["type" => "withinLimit", "params" => ["message" => "Speed is within limit"]],
    "failureEvent" => ["type" => "speeding", "params" => ["message" => "Exceeding speed limit"]]
];

$engine->addRule(new Rule($ruleConfig));
$engine->setTargetRule('speed.check');

// Add both facts dynamically
$engine->addFact('currentSpeed', 55);
$engine->addFact('speedLimit', 60);

$result = $engine->evaluate();
// Result: withinLimit - Speed is within limit
```

**Example: Nested Fact Comparison**

```
$ruleConfig = [
    "name" => "age.verification",
    "conditions" => [
        "all" => [
            [
                "fact" => "user",
                "path" => "$.age",
                "operator" => "greaterThanInclusive",
                "value" => [
                    "fact" => "requirements",
                    "path" => "$.minimumAge"
                ]
            ]
        ]
    ],
    "event" => ["type" => "ageVerified", "params" => []],
    "failureEvent" => ["type" => "ageFailed", "params" => []]
];

$engine->addFact('user', ['age' => 25]);
$engine->addFact('requirements', ['minimumAge' => 18]);
```

Run the test
------------

[](#run-the-test)

```
./vendor/bin/phpunit tests
```

License
-------

[](#license)

[ISC](./LICENSE)

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance85

Actively maintained with recent releases

Popularity24

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~79 days

Recently: every ~113 days

Total

7

Last Release

79d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/387f13e634536601b27f9a058370aa96efc51c9d0ab9aa2165edc2f127e69cfa?d=identicon)[kennyth01](/maintainers/kennyth01)

---

Top Contributors

[![kennyth01](https://avatars.githubusercontent.com/u/14011680?v=4)](https://github.com/kennyth01 "kennyth01 (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/kennyth01-php-rules-engine/health.svg)

```
[![Health](https://phpackages.com/badges/kennyth01-php-rules-engine/health.svg)](https://phpackages.com/packages/kennyth01-php-rules-engine)
```

###  Alternatives

[phpxmlrpc/polyfill-xmlrpc

A pure-php reimplementation of the API exposed by the native XML-RPC extension

12369.8k2](/packages/phpxmlrpc-polyfill-xmlrpc)[duoshuo/uuid

A PHP 5.4+ library for generating RFC 4122 version 1, 3, 4, and 5 universally unique identifiers (UUID)

1039.2k](/packages/duoshuo-uuid)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
