Skip to content
qoliberPublic

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Calculon Logo

Calculon - Mathematical Expression Parser

Tests Coverage Mutation Score PHP Version License PHPStan

A dramatic PHP library for parsing and evaluating mathematical expressions with AST-based architecture. Named after everyone's favorite acting robot from Futurama!

Features

  • Basic arithmetic operations: +, -, *, /, ^ (power)
  • Parentheses for grouping expressions
  • Variables with runtime substitution
  • Percentage calculations (10%)
  • Mathematical functions (sin, cos, sqrt, log, etc.)
  • Built-in constants (PI, E)
  • Custom functions support
  • Custom constants
  • Expression simplification
  • Comprehensive unit test coverage
  • Hilarious Futurama-themed error messages

Requirements

  • PHP 8.1 or higher

Installation

composer require qoliber/calculon

Usage

Basic Arithmetic

use Qoliber\Calculon\Calculon;

$calculon = new Calculon();

echo $calculon->evaluate('2 + 3');        // 5
echo $calculon->evaluate('10 - 3');       // 7
echo $calculon->evaluate('4 * 5');        // 20
echo $calculon->evaluate('20 / 4');       // 5
echo $calculon->evaluate('2 ^ 3');        // 8

Operator Precedence

echo $calculon->evaluate('2 + 3 * 4');    // 14 (not 20)
echo $calculon->evaluate('(2 + 3) * 4');  // 20

Variables

// Pass variables during evaluation
$result = $calculon->evaluate('2*x + 3*y', ['x' => 5, 'y' => 10]);
echo $result; // 40

// Set variables beforehand
$calculon->setVariable('x', 10);
echo $calculon->evaluate('x * 2'); // 20

Percentage

echo $calculon->evaluate('10%');           // 0.1
echo $calculon->evaluate('10 + 10%');      // 10.1
echo $calculon->evaluate('100 * 5%');      // 5

Mathematical Functions

echo $calculon->evaluate('sin(PI / 2)');   // 1
echo $calculon->evaluate('cos(0)');        // 1
echo $calculon->evaluate('sqrt(16)');      // 4
echo $calculon->evaluate('pow(2, 3)');     // 8
echo $calculon->evaluate('abs(-5)');       // 5
echo $calculon->evaluate('log(E)');        // 1
echo $calculon->evaluate('ceil(3.14)');    // 4
echo $calculon->evaluate('floor(3.14)');   // 3
echo $calculon->evaluate('round(3.14, 1)');// 3.1
echo $calculon->evaluate('min(1, 2, 3)');  // 1
echo $calculon->evaluate('max(1, 2, 3)');  // 3

Constants

// Built-in constants
echo $calculon->evaluate('PI');           // 3.14159...
echo $calculon->evaluate('E');            // 2.71828...

// Custom constants
$calculon->setConstant('CUSTOM', 100);
echo $calculon->evaluate('CUSTOM * 2');   // 200

Complex Expressions

// From the original example: (2x + 3x * 5z)^2 - 10 * 1.2%
$result = $calculon->evaluate(
    '(2*x + 3*x * 5*z)^2 - 10 * 1.2%',
    ['x' => 1, 'z' => 1]
);
echo $result; // 288.88

Custom Functions

use Qoliber\Calculon\Context\Function\FunctionInterface;

$customFunction = new class implements FunctionInterface {
    public function getName(): string
    {
        return 'double';
    }

    public function getArgumentCount(): ?int
    {
        return 1; // null for variable argument count
    }

    public function execute(array $arguments): float|int
    {
        return $arguments[0] * 2;
    }
};

$calculon->registerFunction($customFunction);
echo $calculon->evaluate('double(5)'); // 10

Advanced Features

Constant Management

// Get all constants (including built-in PI, E)
$constants = $calculon->getConstants();

// Add custom constant
$calculon->setConstant('TAX_RATE', 0.2);

// Check if constant exists
if ($calculon->hasConstant('TAX_RATE')) {
    $value = $calculon->getConstant('TAX_RATE');
}

// Remove constant
$calculon->removeConstant('TAX_RATE');

Function Management

// Get all registered function names
$functions = $calculon->getFunctionNames();
// Returns: ['sin', 'cos', 'sqrt', 'max', 'min', ...]

// Check if function exists
if ($calculon->hasFunction('sqrt')) {
    // Use it
}

// Remove function
$calculon->removeFunction('sqrt');

Extract Variables from Formula

// Automatically extract all variables from a formula
$formula = '2*x + 3*y - z';
$variables = $calculon->getVariablesFromFormula($formula);
// Returns: ['x', 'y', 'z']

// Excludes constants
$formula = 'x + PI + E';
$variables = $calculon->getVariablesFromFormula($formula);
// Returns: ['x'] (PI and E are constants, not variables)

Validate Formula Without Evaluating

// Validate syntax only
try {
    $calculon->validateFormula('2 + 3 * 4');
    echo "Formula is valid!";
} catch (CalculonException $e) {
    echo "Invalid formula: " . $e->getMessage();
}

// Validate with expected variables
$formula = 'x + y + z';
try {
    $calculon->validateFormula($formula, ['x', 'y', 'z']);
    echo "All variables will be available!";
} catch (CalculonException $e) {
    echo "Missing variables!";
}

// Catches undefined functions
try {
    $calculon->validateFormula('unknownFunc(42)');
} catch (CalculonException $e) {
    echo "Function not found!";
}

Variable Management

// Get all current variables
$variables = $calculon->getVariables();

// Clear all variables
$calculon->clearVariables();

// Note: Clearing variables doesn't affect constants

Complete Workflow Example

// 1. Set up constants
$calculon->setConstant('TAX_RATE', 0.2);
$calculon->setConstant('DISCOUNT_RATE', 0.1);

// 2. Define formula
$formula = 'price * (1 - DISCOUNT_RATE) * (1 + TAX_RATE)';

// 3. Extract required variables
$requiredVars = $calculon->getVariablesFromFormula($formula);
// Returns: ['price']

// 4. Validate formula before using it
$calculon->validateFormula($formula, $requiredVars);

// 5. Evaluate with actual data
$result = $calculon->evaluate($formula, ['price' => 100]);
// 100 * 0.9 * 1.2 = 108

// 6. Later, update constant dynamically
$calculon->setConstant('TAX_RATE', 0.25);
$result = $calculon->evaluate($formula, ['price' => 100]);
// 100 * 0.9 * 1.25 = 112.5

Architecture

Calculon uses a clean AST-based architecture:

  1. Lexer - Tokenizes the input string
  2. Parser - Builds an Abstract Syntax Tree (AST)
  3. AST Nodes - Represent different expression types
  4. Evaluator - Traverses the AST using the Visitor pattern
  5. Context - Manages variables, constants, and functions
src/
├── Lexer/           # Tokenization
├── Parser/          # AST construction
├── AST/             # AST node definitions
├── Evaluator/       # Expression evaluation
├── Context/         # Variables, constants, functions
├── Exception/       # Hilarious error messages
└── Calculon.php     # Main facade

📖 For detailed architecture documentation, see ARCHITECTURE.md ⚡ For performance benchmarks, see BENCHMARKS.md

Error Handling

Calculon throws CalculonException with dramatic error messages:

try {
    $calculon->evaluate('10 / 0');
} catch (CalculonException $e) {
    // "ACTING! *dramatic pose* You cannot divide by zero!
    //  Even I, the great Calculon, cannot compute infinity!"
}

try {
    $calculon->evaluate('unknown_var + 5');
} catch (CalculonException $e) {
    // "I AM NOT PROGRAMMED TO UNDERSTAND THAT!
    //  Undefined variable: 'unknown_var'"
}

Performance

Calculon is fast! ⚡

  • Simple expressions: ~350,000 operations/second
  • Complex expressions: ~50,000-80,000 operations/second
  • E-commerce formulas: ~36,000-58,000 operations/second
  • Average: ~171,000 operations/second

Example: A typical e-commerce pricing formula can perform 57,000 calculations per second - that's 3.4 million per minute or 205 million per hour.

Run Benchmarks

php benchmarks/PerformanceBenchmark.php

See BENCHMARKS.md for detailed performance analysis and optimization recommendations.

Testing & Validation

Calculon provides comprehensive testing and validation tools:

Unit Tests

Run the test suite:

composer install
vendor/bin/phpunit

Test coverage:

  • 192 tests, 495 assertions
  • Unit tests (82 tests): Lexer, Parser, Evaluator, Token, CalculonException
    • 40 Lexer tests with comprehensive edge cases and whitespace handling
    • 19 Parser tests with operator precedence
    • 11 Evaluator tests
    • 10 Token tests
    • 2 CalculonException tests
  • Integration tests (110 tests): Complete workflows
    • Formula validation tests
    • Enhanced features tests
    • Variable management tests
    • Edge case testing
  • 100% passing tests

Code Coverage: 100%

  • Classes: 100% (12/12 classes covered)
  • Methods: 100% (85/85 methods covered)
  • Lines: 100% (433/433 lines covered)
  • Lexer: 100% coverage
  • Parser: 100% coverage
  • Calculon: 100% coverage
  • Context: 100% coverage
  • CalculonException: 100% coverage
  • Evaluator: 100% coverage
  • AST classes: 100% coverage
  • Token: 100% coverage
  • Mutation Score Indicator (MSI): 97% (Covered Code MSI)

Testing Tools

Interactive Formula Tester

Test formulas interactively in the CLI:

php tools/formula-tester.php

Features: Test formulas, validate syntax, analyze structure, random testing, manage constants.

Formula Validator

Validate multiple formulas from a file:

php tools/formula-validator.php examples/formulas-ecommerce.txt

Perfect for CI/CD pipelines and pre-deployment validation.

Test Data Generator

Generate test datasets for formulas:

php tools/test-data-generator.php 'price * (1 + tax/100)' 100 output.csv

Supports CSV and JSON output formats.

📖 For detailed testing guide, see TESTING.md

Code Quality

Calculon maintains high code quality standards:

  • PSR-12 coding standard compliance (custom spacing rule)
  • PHPStan Level 8 static analysis (strictest)
  • 100% test pass rate (192 tests, 495 assertions)
  • 100% code coverage (433/433 lines)
  • 97% Mutation Score (Covered Code MSI)
  • Infection mutation testing configured with 73 mutations tested
  • Comprehensive documentation
  • Docker environment for consistent testing

Run Quality Checks

# Local environment
make qa              # Run all quality checks
make cs-check        # Check PSR-12 compliance
make stan            # Run PHPStan
make test            # Run tests
make mutation        # Run mutation testing (requires Xdebug)

# Docker environment (recommended - no local PHP setup needed)
make docker-build    # Build Docker image (first time only)
make docker-qa       # Run all quality checks in Docker
make docker-test     # Run tests in Docker
make docker-mutation # Run mutation testing in Docker

# Via Composer
composer qa          # Run all checks
composer mutation    # Run mutation testing

License

MIT

Credits

Created by Qoliber - Because even robots need to do math dramatically!


"I WILL DESTROY YOU!" - Calculon (when you divide by zero)

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages