PHPackages                             oxygensuite/php-ast - 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. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. oxygensuite/php-ast

ActivePackage[Parsing &amp; Serialization](/categories/parsing)

oxygensuite/php-ast
===================

A lightweight Abstract Syntax Tree (AST) implementation for PHP, enabling structured parsing, analysis, and transformation of PHP code.

v1.0.0(1mo ago)17↑1185.7%MITPHPPHP ^8.4

Since Mar 11Pushed 1mo agoCompare

[ Source](https://github.com/oxygensuite/php-ast)[ Packagist](https://packagist.org/packages/oxygensuite/php-ast)[ RSS](/packages/oxygensuite-php-ast/feed)WikiDiscussions master Synced 1mo ago

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

oxygensuite/php-ast
===================

[](#oxygensuitephp-ast)

A lightweight formula engine for PHP built on an Abstract Syntax Tree (AST). Parse, evaluate, and transform expressions with support for variables, functions, wildcards, and operator precedence.

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

[](#requirements)

- PHP 8.4+
- ext-ctype
- ext-mbstring

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

[](#installation)

```
composer require oxygensuite/php-ast
```

Quick Start
-----------

[](#quick-start)

```
use OxygenSuite\PhpAst\Formulas\FormulaEvaluator;

$evaluator = new FormulaEvaluator();

$data = [
    'lines' => [
        ['quantity' => 2, 'unit_price' => 10.0, 'discount' => 0],
        ['quantity' => 3, 'unit_price' => 15.0, 'discount' => 5],
        ['quantity' => 1, 'unit_price' =>  8.0, 'discount' => 0],
    ],
];

// Variable access (dot-notation)
$evaluator->evaluate('lines.0.quantity', $data); // 2

// Arithmetic
$evaluator->evaluate('lines.0.quantity * lines.0.unit_price', $data); // 20.0

// Wildcards
$evaluator->evaluate('SUM(lines.*.quantity)', $data); // 6

// Functions
$evaluator->evaluate('MAP(lines; quantity * unit_price - discount)', $data); // [20, 40, 8]
```

Variables
---------

[](#variables)

Variables use **dot-notation** for nested property access. Types are preserved (string, int, float, bool, null, array).

SyntaxResolves to`uid``$data['uid']``lines.0.quantity``$data['lines'][0]['quantity']``a.b.c``$data['a']['b']['c']`Variables can be used directly in expressions:

```
$evaluator->evaluate('lines.0.quantity * lines.0.unit_price', $data);
$evaluator->evaluate('(base_price + tax) * quantity', $data);
```

Wildcards
---------

[](#wildcards)

The `*` wildcard extracts values across all items in an array.

```
// Single-level: lines.*.quantity → PLUCK(lines; "quantity")
$evaluator->evaluate('lines.*.quantity', $data); // [2, 3, 1]

// Multi-level: lines.*.taxes.*.amount → extracts all tax amounts from all lines
$evaluator->evaluate('SUM(lines.*.taxes.*.amount)', $data);
```

Operators
---------

[](#operators)

Listed from highest to lowest precedence:

PrecedenceOperatorsDescription1`**`Exponentiation2`*` `/` `%`Multiplication, division, modulo3`+` `-`Addition, subtraction4`==` `!=` `` `=` ``Comparison5`&&`Logical AND6`||`Logical OR7`??` `?:`Null coalescing, elvisParentheses override precedence: `(a + b) * c`.

Functions
---------

[](#functions)

All functions use **semicolons** (`;`) as argument separators.

### Aggregation

[](#aggregation)

FunctionDescriptionExample`SUM(values)`Sum of numeric values`SUM(lines.*.quantity)``AVG(values)`Average`AVG(lines.*.unit_price)``MIN(values)`Minimum value`MIN(lines.*.unit_price)``MAX(values)`Maximum value`MAX(lines.*.quantity)``COUNT(values)`Number of elements`COUNT(lines.*.quantity)`### Rounding

[](#rounding)

FunctionDescriptionExample`ROUND(value; precision)`Round to precision decimals`ROUND(10.567; 2)` → `10.57``CEIL(value)`Round up`CEIL(10.1)` → `11``FLOOR(value)`Round down`FLOOR(10.9)` → `10`### Array Manipulation

[](#array-manipulation)

FunctionDescriptionExample`PLUCK(array; "key")`Extract column from array of objects`PLUCK(lines; "quantity")``FLAT(array; depth)`Flatten nested arrays (default depth: 1)`FLAT([[1,2],[3,[4,5]]]; 2)``MAP(array; expr)`Apply expression per item`MAP(lines; quantity * unit_price)``FILTER(array; condition)`Filter items by condition`FILTER(lines; unit_price > 10)``GROUP(array; "key")`Group items by key`GROUP(lines; "tax_category")``SORT(array)`Sort array`SORT(lines.*.quantity)``JOIN(array; separator)`Join into string`JOIN(lines.*.quantity; ",")``FIRST(array)`First element`FIRST(lines)``LAST(array)`Last element`LAST(lines)`### Conditional

[](#conditional)

FunctionDescriptionExample`IF(cond; true_val; false_val)`Conditional`IF(quantity > 10; "bulk"; "single")``VALUE(array; "key")`Get value by key`VALUE(line; "quantity")`Composing Functions
-------------------

[](#composing-functions)

Functions can be nested and combined with arithmetic:

```
// Sum of (quantity * unit_price) per line
$evaluator->evaluate('SUM(MAP(lines; quantity * unit_price))', $data);

// Filter then sum
$evaluator->evaluate('SUM(PLUCK(FILTER(lines; tax_category == 1); "net_amount"))', $data);

// Grouped aggregation
$evaluator->evaluate('GROUP(lines; "tax_category")', $data);
// → [1 => [...], 2 => [...], 3 => [...]]

// Arithmetic on aggregated results
$evaluator->evaluate('SUM(lines.*.net_amount) + SUM(lines.*.vat_amount)', $data);
```

Context Providers
-----------------

[](#context-providers)

For injecting external values (e.g., configuration, session data) into formula evaluation:

```
use OxygenSuite\PhpAst\ContextProvider\ContextProvider;

class MyContext implements ContextProvider
{
    public function getContextValue(string $key): mixed
    {
        return match ($key) {
            'tax_rate' => 0.24,
            'currency' => 'EUR',
            default => null,
        };
    }
}

$evaluator = new FormulaEvaluator(new MyContext());
$evaluator->evaluate('unit_price * tax_rate', $data); // uses tax_rate from context
```

Context values take priority over data array values.

Custom Functions
----------------

[](#custom-functions)

### Simple Function

[](#simple-function)

Implement the `Formula` interface:

```
use OxygenSuite\PhpAst\AST\ASTEvaluator;
use OxygenSuite\PhpAst\Formulas\Formula;

readonly class DoubleFunction implements Formula
{
    public function execute(array $arguments, array $data, ASTEvaluator $evaluator): float|int|string|array
    {
        return ($arguments[0] ?? 0) * 2;
    }
}
```

### AST-Aware Function

[](#ast-aware-function)

For functions that need per-item evaluation (like MAP/FILTER), implement `ASTFormula` instead. It receives raw AST nodes so you can evaluate expressions against each item:

```
use OxygenSuite\PhpAst\AST\ASTEvaluator;
use OxygenSuite\PhpAst\Formulas\ASTFormula;

readonly class MyTransform implements ASTFormula
{
    public function execute(array $astNodes, array $data, ASTEvaluator $evaluator): mixed
    {
        [$itemsNode, $callbackNode] = $astNodes;
        $items = $itemsNode->accept($evaluator, $data);

        return array_map(
            fn($item) => $callbackNode->accept($evaluator, $item),
            $items,
        );
    }
}
```

Caching
-------

[](#caching)

Parsed ASTs are automatically cached per evaluator instance (default: 1000 entries). Repeated evaluation of the same formula string skips parsing entirely.

```
$evaluator->getCacheStats(); // ['hits' => 42, 'misses' => 10, 'size' => 10, 'hitRate' => 0.807]
$evaluator->clearCache();
```

Error Handling
--------------

[](#error-handling)

ScenarioBehaviorMissing variableReturns `null`Division by zeroReturns `0`Unknown functionThrows `RuntimeException`Invalid expressionThrows `RuntimeException`Recursion depth &gt; 32Throws `RuntimeException`License
-------

[](#license)

MIT

###  Health Score

42

—

FairBetter than 89% of packages

Maintenance94

Actively maintained with recent releases

Popularity8

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity51

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

59d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/7cc799a66d4c20333f69a890ad17be2e0cbf68a535e9785c1c442c2b07e6a713?d=identicon)[isarantoglou](/maintainers/isarantoglou)

---

Top Contributors

[![ogiritli](https://avatars.githubusercontent.com/u/165646304?v=4)](https://github.com/ogiritli "ogiritli (8 commits)")

---

Tags

phpparserastabstract syntax treecode-transformation

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/oxygensuite-php-ast/health.svg)

```
[![Health](https://phpackages.com/badges/oxygensuite-php-ast/health.svg)](https://phpackages.com/packages/oxygensuite-php-ast)
```

###  Alternatives

[doctrine/lexer

PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.

11.2k910.8M118](/packages/doctrine-lexer)[ajthinking/archetype

Programmatically edit PHP and Laravel files.

2723.4M12](/packages/ajthinking-archetype)[simplehtmldom/simplehtmldom

A fast, simple and reliable HTML document parser for PHP.

1921.3M14](/packages/simplehtmldom-simplehtmldom)[atanamo/php-codeshift

A PHP code transformation toolkit based on 'PHP-Parser'

32158.4k1](/packages/atanamo-php-codeshift)[corveda/php-sandbox

A PHP library that can be used to run PHP code in a sandboxed environment

23483.5k2](/packages/corveda-php-sandbox)[sbsaga/toon

🧠 TOON for Laravel — a compact, human-readable, and token-efficient data format for AI prompts &amp; LLM contexts. Perfect for ChatGPT, Gemini, Claude, Mistral, and OpenAI integrations (JSON ⇄ TOON).

6115.6k](/packages/sbsaga-toon)

PHPackages © 2026

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