PHPackages                             mb4it/conditionable - 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. mb4it/conditionable

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

mb4it/conditionable
===================

A lightweight PHP library providing a fluent API for building and evaluating complex conditional logic structures.

1.0.0(4mo ago)03521MITPHPPHP &gt;=8.1

Since Feb 5Pushed 1mo agoCompare

[ Source](https://github.com/Dictator90/mb-conditionable)[ Packagist](https://packagist.org/packages/mb4it/conditionable)[ RSS](/packages/mb4it-conditionable/feed)WikiDiscussions master Synced today

READMEChangelog (1)Dependencies (1)Versions (2)Used By (1)

Conditionable
=============

[](#conditionable)

Легковесная PHP-библиотека с fluent API для построения и вычисления сложных условных логических структур.

Возможности
-----------

[](#возможности)

- **Fluent API**: Интуитивно понятный интерфейс для построения условий
- **Гибкие операторы**: Поддержка множества операторов сравнения и проверки типов
- **Контекстная система**: Разрешение значений из объектов, массивов и классов
- **Вложенные условия**: Создание сложных логических деревьев с AND/OR
- **Trait-интеграция**: Встроенный трейт для добавления возможностей в ваши классы
- **Расширяемость**: Легкое добавление пользовательских операторов

Установка
---------

[](#установка)

Требуется PHP 8.1 или выше.

```
composer require mb4it/conditionable
```

Быстрый старт
-------------

[](#быстрый-старт)

### Простые условия

[](#простые-условия)

```
$result = (new ConditionTree())
    ->where(fn() => time(), '>', 0)
    ->result();
//true

//Или использовать функцию
$result = condition()
    ->where(fn() => time(), '>', 0)
    ->result();
// true
```

### Контекст объекта

[](#контекст-объекта)

```
class User {
    public string $name = 'John';
    public int $age = 25;
}

$user = new User();

$result = condition()
    ->context($user, 'u')
    ->where('u.name', 'John')
    ->where('u.age', '>=', 18)
    ->result();
// true

// или
$result = condition(['u' => $user])
    ->where('u.name', 'John')
    ->where('u.age', '>=', 18)
    ->result();
// true
```

### Использование Trait

[](#использование-trait)

```
use MB\Support\Conditionable\Traits\Conditionable;

class Product {
    use Conditionable;

    public float $price = 150.0;
    public string $category = 'electronics';
}

$product = new Product();

// При использовании Trait классе
// Его алиас для контекста -> this
$result = $product->condition()
    ->where('this.price', '>', 100)
    ->where('this.category', 'electronics')
    ->result();

// true
```

Или используйте метод `check()` для быстрой проверки:

```
$result = $product->check(['this.price', '>', 100], ['this.category', 'electronics']);
// true
```

Доступные операторы
-------------------

[](#доступные-операторы)

### Операторы сравнения

[](#операторы-сравнения)

ОператорОписаниеПример`=`Равно`where('field', '=', 'value')``` или `!=`Не равно`where('field', '', 'value')``===`Строгое равенство`where('field', '===', 'value')``!==`Строгое неравенство`where('field', '!==', 'value')``>`Больше`where('field', '>', 10)``>=`Больше или равно`where('field', '>=', 10)``where('field1', 'value1')
    ->where('field2', 'value2')
    ->calculate()
    ->result();

// Или
condition()
    ->orGroup(
        function(ConditionTree $tree) {
            $tree
                ->where('field1', 'value1')
                ->where('field2', 'value2');
        }
    )
    ->result();
```

### Отрицание условий

[](#отрицание-условий)

```
// Отрицание всего условия
$tree = condition()
    ->where('field', 'value')
    ->negative()
    ->result();

// Отрицание отдельного условия
condition()
    ->notGroup(fn (ConditionTree $cond) => $cond->where('field', 'value'))
    ->result();
```

### Вложенные условия

[](#вложенные-условия)

```
$inner = condition()
    ->logicOr()
    ->where('field1', 'value1')
    ->where('field2', 'value2')

$result = condition()
    ->where('mainField', 'mainValue')
    ->where($inner)
    ->result();
```

### Разрешение значений из контекста

[](#разрешение-значений-из-контекста)

```
$array = ['age' => 25];
$policy = ['minAge' => 18];

condition()
    ->context($array, 'data')
    ->context($policy, 'rule')
    ->where('data.age', '>=', 'rule.minAge')
    ->result();
```

### Поддержка callable

[](#поддержка-callable)

```
condition()
    ->where(fn() => getValue(), '>', 10)
    ->where([SomeClass::class, 'staticMethod'], '=', 'expected')
    ->result();
```

### Callback при выполнении условия

[](#callback-при-выполнении-условия)

```
$result = condition()
    ->where('field', 'value')
    ->calculate()
    ->then(
        function(bool $isTrue, Registry $context) { ... }
    )
    ->result();
```

Создание пользовательских операторов
------------------------------------

[](#создание-пользовательских-операторов)

Реализуйте интерфейс `ActionInterface` и зарегистрируйте действие:

```
use MB\Support\Conditionable\Contracts\ActionInterface;
use MB\Support\Conditionable\Actions\ActionRegistry;

class CustomAction implements ActionInterface
{
    public static function operator(): string
    {
        return 'custom_operator';
    }

    public static function handle($a, $b): bool
    {
        // ваша логика
        return $a === $b;
    }
}

// Регистрация
ActionRegistry::register(CustomAction::class);

// Использование
condition()
    ->where('field', 'custom_operator', 'value')
    ->result();
```

Тестирование
------------

[](#тестирование)

```
# Установка зависимостей
composer install

# Запуск тестов
./vendor/bin/phpunit
```

Структура проекта
-----------------

[](#структура-проекта)

```
├── src/
│   ├── Actions/           # Реализации операторов
│   │   └── Class/        # Операторы для работы с классами
│   ├── Context/          # Система контекстов
│   ├── Contracts/        # Интерфейсы
│   ├── Traits/          # Трейты для интеграции
│   ├── Condition.php    # Условие
│   ├── ConditionTree.php # Дерево условий
│   └── functions.php    # Глобальные функции
├── tests/               # Тесты PHPUnit
└── composer.json

```

Лицензия
--------

[](#лицензия)

MIT

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance83

Actively maintained with recent releases

Popularity17

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity43

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

Unknown

Total

1

Last Release

148d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/75324054?v=4)[Maxim Bezvodinskikh](/maintainers/Dictator90)[@Dictator90](https://github.com/Dictator90)

---

Top Contributors

[![Dictator90](https://avatars.githubusercontent.com/u/75324054?v=4)](https://github.com/Dictator90 "Dictator90 (3 commits)")

---

Tags

checkconditionablecondition

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mb4it-conditionable/health.svg)

```
[![Health](https://phpackages.com/badges/mb4it-conditionable/health.svg)](https://phpackages.com/packages/mb4it-conditionable)
```

###  Alternatives

[consistence/consistence

Consistence - consistent approach and additions to PHP's functionality

1841.1M18](/packages/consistence-consistence)[silverstripe/environmentcheck

Provides an API for building environment tests

35516.6k14](/packages/silverstripe-environmentcheck)[org_heigl/holidaychecker

Check for holidays - localeaware

844.1k](/packages/org-heigl-holidaychecker)

PHPackages © 2026

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