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

ActiveLibrary

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

Lightweight business rule engine with declarative conditions and actions

v1.0.4(today)11MITPHPPHP ^8.2CI passing

Since Mar 15Pushed todayCompare

[ 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)[ RSS](/packages/philiprehberger-php-rule-engine/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (3)Versions (6)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)[![License](https://camo.githubusercontent.com/03321311f19eb34470ee637133966f65bc132add15c312f03aba3c46c791feef/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f7068696c69707265686265726765722f7068702d72756c652d656e67696e65)](LICENSE)

Lightweight business rule engine with declarative conditions and actions.

---

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

[](#requirements)

DependencyVersionPHP^8.2No external dependencies required.

---

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'],
        ],
    ]);
```

### 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### 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### 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### RuleResult

[](#ruleresult)

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

Development
-----------

[](#development)

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

License
-------

[](#license)

MIT

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance100

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity49

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

5

Last Release

0d 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 (6 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

[pestphp/pest-plugin-stressless

Stressless plugin for Pest

67723.5k15](/packages/pestphp-pest-plugin-stressless)

PHPackages © 2026

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