PHPackages                             philiprehberger/php-rule-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. philiprehberger/php-rule-engine

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

philiprehberger/php-rule-engine
===============================

Lightweight business rule engine with declarative conditions and actions

v1.1.0(2mo ago)138MITPHPPHP ^8.2CI passing

Since Mar 15Pushed 1mo agoCompare

[ Source](https://github.com/philiprehberger/php-rule-engine)[ Packagist](https://packagist.org/packages/philiprehberger/php-rule-engine)[ Docs](https://github.com/philiprehberger/php-rule-engine)[ GitHub Sponsors](https://github.com/philiprehberger)[ RSS](/packages/philiprehberger-php-rule-engine/feed)WikiDiscussions main Synced 3w ago

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

PHP Rule Engine
===============

[](#php-rule-engine)

[![Tests](https://github.com/philiprehberger/php-rule-engine/actions/workflows/tests.yml/badge.svg)](https://github.com/philiprehberger/php-rule-engine/actions/workflows/tests.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/5d2f6a092b3dd1c850391dc4257b428b566e6deb3da2b03a77335db7b4596ea8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7068696c69707265686265726765722f7068702d72756c652d656e67696e652e737667)](https://packagist.org/packages/philiprehberger/php-rule-engine)[![Last updated](https://camo.githubusercontent.com/93df1213292c2434aa894725e982b669393580ddbb71acf95c63efff07b36850/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f7068696c69707265686265726765722f7068702d72756c652d656e67696e65)](https://github.com/philiprehberger/php-rule-engine/commits/main)

Lightweight business rule engine with declarative conditions and actions.

Requirements
------------

[](#requirements)

- PHP 8.2+

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

[](#installation)

```
composer require philiprehberger/php-rule-engine
```

Usage
-----

[](#usage)

### Basic Rule

[](#basic-rule)

```
use PhilipRehberger\RuleEngine\RuleEngine;

$result = RuleEngine::create()
    ->rule('adult')
    ->when('age', '>=', 18)
    ->then(fn ($ctx) => "Welcome, {$ctx['name']}!")
    ->build()
    ->evaluate(['name' => 'Alice', 'age' => 25]);

$result->hasMatches(); // true
$result->first()->actionResult; // "Welcome, Alice!"
```

### Multiple Conditions

[](#multiple-conditions)

```
$result = RuleEngine::create()
    ->rule('vip-discount')
    ->when('role', '=', 'vip')
    ->andWhen('total', '>=', 100)
    ->then(fn () => ['discount' => 0.2])
    ->build()
    ->rule('bulk-discount')
    ->when('quantity', '>=', 50)
    ->orWhen('total', '>=', 500)
    ->then(fn () => ['discount' => 0.1])
    ->build()
    ->evaluate(['role' => 'vip', 'total' => 150, 'quantity' => 10]);
```

### Negated Conditions

[](#negated-conditions)

```
$engine = RuleEngine::create()
    ->rule('active-non-banned')
    ->when('active', '=', true)
    ->notWhen('status', '=', 'banned')
    ->then(fn () => 'access granted')
    ->build();
```

### Priority and Stop-on-Match

[](#priority-and-stop-on-match)

```
$engine = RuleEngine::create()
    ->rule('high-priority')
    ->when('value', '>', 0)
    ->then(fn () => 'important')
    ->priority(10)
    ->stopOnMatch()
    ->build()
    ->rule('low-priority')
    ->when('value', '>', 0)
    ->then(fn () => 'fallback')
    ->priority(1)
    ->build();

$result = $engine->evaluate(['value' => 5]);
// Only 'high-priority' matches because stopOnMatch is set
```

### First Match Only

[](#first-match-only)

```
$result = $engine->evaluateFirst(['value' => 5]);
// Returns a single RuleResult or null
```

### Nested Context with Dot Notation

[](#nested-context-with-dot-notation)

```
$result = RuleEngine::create()
    ->rule('city-check')
    ->when('user.address.city', '=', 'Vienna')
    ->then(fn () => 'local')
    ->build()
    ->evaluate([
        'user' => [
            'address' => ['city' => 'Vienna'],
        ],
    ]);
```

### Compiled Rule Engine

[](#compiled-rule-engine)

```
$compiled = RuleEngine::create()
    ->rule('adult')
    ->when('age', '>=', 18)
    ->then(fn () => 'allowed')
    ->build()
    ->compile();

// Evaluate multiple contexts with pre-compiled closures
$result = $compiled->evaluate(['age' => 25]);
$first = $compiled->evaluateFirst(['age' => 25]);
```

### Audit Mode

[](#audit-mode)

```
$result = RuleEngine::create()
    ->rule('a')
    ->when('x', '>', 0)
    ->then(fn () => 'matched')
    ->build()
    ->withAudit()
    ->evaluate(['x' => 5]);

$result->auditEntries(); // Array of AuditEntry objects
$result->evaluatedCount(); // Number of rules evaluated
$result->skippedCount(); // Number of rules skipped
```

### Rule Validation

[](#rule-validation)

```
$engine = RuleEngine::create();
$engine->addRule(new Rule('no-conditions', [], fn () => 'x'));

$warnings = $engine->validate();
// ["Rule 'no-conditions' has no conditions and will always match."]
```

### Custom Context Accessor

[](#custom-context-accessor)

Implement `ContextAccessor` to read values from any data structure:

```
use PhilipRehberger\RuleEngine\Contracts\ContextAccessor;

class EloquentAccessor implements ContextAccessor
{
    public function get(mixed $context, string $path): mixed
    {
        return data_get($context, $path);
    }

    public function has(mixed $context, string $path): bool
    {
        return data_get($context, $path) !== null;
    }
}

$engine = RuleEngine::create(new EloquentAccessor());
```

API
---

[](#api)

### RuleEngine

[](#ruleengine)

MethodDescription`RuleEngine::create(?ContextAccessor $accessor = null): self`Create a new engine instance`->rule(string $name): RuleBuilder`Begin defining a named rule`->evaluate(mixed $context): EvaluationResult`Evaluate all rules, return all matches`->evaluateFirst(mixed $context): ?RuleResult`Evaluate rules, return first match only`->compile(): CompiledRuleEngine`Pre-compile rules into optimized closures`->withAudit(): self`Enable audit mode for detailed tracking`->validate(): array`Validate rule configuration, return warnings### RuleBuilder

[](#rulebuilder)

MethodDescription`->when(string $path, string $operator, mixed $value)`Add the first condition`->andWhen(string $path, string $operator, mixed $value)`Add an AND condition`->orWhen(string $path, string $operator, mixed $value)`Add an OR condition`->notWhen(string $path, string $operator, mixed $value)`Add a negated AND condition`->then(callable $action)`Set the action to execute on match`->priority(int $priority)`Set rule priority (higher runs first)`->stopOnMatch(bool $stop = true)`Stop evaluation after this rule matches`->build(): RuleEngine`Build the rule and return the engine### CompiledRuleEngine

[](#compiledruleengine)

MethodDescription`->evaluate(mixed $context): EvaluationResult`Evaluate compiled rules, return all matches`->evaluateFirst(mixed $context): ?RuleResult`Evaluate compiled rules, return first match only### Operators

[](#operators)

OperatorDescription`=`, `==`Loose equality`===`Strict equality`!=`, ``Loose inequality`!==`Strict inequality`>`, `=`, `hasMatches(): bool`Whether any rules matched`->count(): int`Number of matched rules`->first(): ?RuleResult`First matched result or null`->actionResults(): array`All action return values`->ruleNames(): array`All matched rule names### AuditResult (extends EvaluationResult)

[](#auditresult-extends-evaluationresult)

MethodDescription`->auditEntries(): array`All audit entries`->evaluatedCount(): int`Number of rules evaluated`->skippedCount(): int`Number of rules skipped### RuleResult

[](#ruleresult)

PropertyTypeDescription`$ruleName``string`Name of the matched rule`$actionResult``mixed`Return value of the actionDevelopment
-----------

[](#development)

```
composer install
vendor/bin/phpunit
vendor/bin/pint --test
```

Support
-------

[](#support)

If you find this project useful:

⭐ [Star the repo](https://github.com/philiprehberger/php-rule-engine)

🐛 [Report issues](https://github.com/philiprehberger/php-rule-engine/issues?q=is%3Aissue+is%3Aopen+label%3Abug)

💡 [Suggest features](https://github.com/philiprehberger/php-rule-engine/issues?q=is%3Aissue+is%3Aopen+label%3Aenhancement)

❤️ [Sponsor development](https://github.com/sponsors/philiprehberger)

🌐 [All Open Source Projects](https://philiprehberger.com/open-source-packages)

💻 [GitHub Profile](https://github.com/philiprehberger)

🔗 [LinkedIn Profile](https://www.linkedin.com/in/philiprehberger)

License
-------

[](#license)

[MIT](LICENSE)

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance88

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity52

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 ~1 days

Total

8

Last Release

88d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/cfd7d24cbbf32400fa13ce0bbe7a31edd2d66a6d4488eafdb3d64c5337bf0435?d=identicon)[philiprehberger](/maintainers/philiprehberger)

---

Top Contributors

[![philiprehberger](https://avatars.githubusercontent.com/u/8218077?v=4)](https://github.com/philiprehberger "philiprehberger (13 commits)")

---

Tags

phpEvaluationbusiness-rulesconditionsrule-engine

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/philiprehberger-php-rule-engine/health.svg)

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

###  Alternatives

[imanghafoori/laravel-anypass

A minimal yet powerful package to help you in development.

21422.6k](/packages/imanghafoori-laravel-anypass)

PHPackages © 2026

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