Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Math Parser Laravel Package

mossadal/math-parser

Safe PHP math expression parser/evaluator that builds an AST from user formulas. Supports arithmetic, variables, and elementary functions, plus interpreters for evaluation, symbolic differentiation, and LaTeX pretty-printing; customizable lexer/parser with StdMathParser.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Dynamic Formula Evaluation: Perfect fit for Laravel applications requiring user-submitted math expressions (e.g., pricing calculators, scientific tools, or financial models). The AST-based design ensures modularity and security by avoiding eval().
  • Symbolic Differentiation: Enables advanced use cases like optimization algorithms, physics simulations, or AI training data generation without reinventing symbolic math logic.
  • LaTeX Integration: Supports rich mathematical notation for educational platforms, dashboards, or documentation, leveraging MathJax/KaTeX for frontend rendering.
  • Extensibility: The package’s lexer/parser/interpreter separation allows for custom functions, validation rules, or performance optimizations (e.g., caching parsed ASTs).
  • Laravel Synergy: Lightweight and dependency-free, making it easy to integrate into existing Laravel services, controllers, or API resources.

Integration Feasibility

  • PHP/Laravel Compatibility: Fully compatible with PHP 8.x and Laravel’s ecosystem. No framework-specific dependencies, but integrates seamlessly via Composer.
  • Low Coupling: Can be injected as a service or used ad-hoc in controllers, reducing architectural overhead.
  • Output Flexibility: Supports numeric evaluation, symbolic math, and LaTeX rendering, catering to diverse frontend/backend needs.
  • Validation-Friendly: User input can be pre-validated using Laravel’s Form Requests or API validation, ensuring only safe expressions are parsed.

Technical Risk

  • Security Risks:
    • Code Injection: User input must be whitelisted (e.g., restrict functions/variables via StdMathParser configuration). Mitigate with regex validation and input sanitization.
    • Denial of Service (DoS): Complex expressions could exhaust memory/CPU. Mitigate with expression complexity limits (e.g., max AST depth) and rate limiting.
  • Performance:
    • Parsing Overhead: AST generation may slow down high-frequency evaluations. Mitigate with caching parsed expressions (e.g., Redis).
    • Differentiation Latency: Symbolic differentiation is CPU-intensive for complex formulas. Mitigate with asynchronous processing (e.g., Laravel queues).
  • Edge Cases:
    • Ambiguous Input: Implicit multiplication (e.g., 2x vs. 2*x) may require explicit handling in validation.
    • Precision Issues: Floating-point operations may need custom rounding or big integer libraries (e.g., gmp) for financial/scientific use cases.
    • LaTeX Dependencies: Requires MathJax/KaTeX for rendering; ensure frontend compatibility.

Key Questions

  1. Use Case Prioritization:
    • Will the primary use be evaluation, differentiation, or LaTeX output? This dictates optimization efforts (e.g., skip LaTeX if unused).
  2. Security Model:
    • How will user input be validated? Will a whitelist of allowed functions/variables (e.g., ['sin', 'log', 'sqrt']) be enforced?
    • Are there sandboxing requirements (e.g., isolating user expressions in a separate process)?
  3. Performance Requirements:
    • Will expressions be pre-parsed and cached (e.g., Redis) or parsed per-request?
    • Are there complexity limits (e.g., max AST depth) to prevent DoS?
  4. Error Handling:
    • How will invalid expressions (e.g., 1/0) or type mismatches be handled? Custom exceptions or graceful degradation (e.g., return null with an error message)?
  5. Extensibility Needs:
    • Are custom functions (e.g., myCustomFunc(x)) required? The package supports this but may need wrapper logic for integration.
    • Will new operators or unary functions be added? The lexer/parser can be extended but requires testing.
  6. Testing Coverage:
    • Does the existing test suite cover edge cases (e.g., nested functions, Unicode variables, operator precedence)?
    • Will fuzz testing be used to validate robustness against malicious input?
  7. Monitoring:
    • How will performance metrics (e.g., parsing time, memory usage) be tracked for complex expressions?
    • Will expression usage analytics (e.g., most common formulas) be collected for optimization?

Integration Approach

Stack Fit

  • Laravel Integration Points:
    • Controllers/APIs: Parse and evaluate expressions in request handlers (e.g., MathExpressionController).
    • Services: Encapsulate logic in a dedicated service class (e.g., MathExpressionService) for reusability.
    • Validation: Use Laravel’s Form Requests or API validation to restrict input format (e.g., regex for basic math syntax).
    • Caching: Cache parsed ASTs for frequent expressions (e.g., Redis or Laravel cache).
    • Events: Trigger custom events (e.g., MathExpressionEvaluated) for analytics or logging.
  • Frontend Integration:
    • LaTeX Rendering: Use MathJax or KaTeX in Blade templates or SPAs to display mathematical notation.
    • Dynamic Calculators: Bind to Alpine.js or Vue for real-time updates (e.g., live formula evaluation).
  • Database Storage:
    • Store expressions as JSON (AST) or strings (original input) if persistence is needed. Use indexed columns for frequent queries.

Migration Path

  1. Proof of Concept (PoC):
    • Test basic evaluation with a simple expression (e.g., "2*x + sin(y)" with x=3, y=0).
    • Verify LaTeX output matches expectations (e.g., \\frac{2x + \\sin(y)}{1}).
    • Validate symbolic differentiation for a use case (e.g., derivative of "exp(2*x) - x*y").
  2. Core Integration:
    • Add to composer.json:
      "require": {
          "mossadal/math-parser": "^1.0"
      }
      
    • Configure the parser with allowed functions/variables:
      $parser = new \Mossadal\MathParser\StdMathParser([
          'functions' => ['sin', 'cos', 'log', 'sqrt'],
          'variables' => ['x', 'y', 'z'] // Optional: restrict variables
      ]);
      
    • Create a service class:
      class MathExpressionService {
          public function evaluate(string $expression, array $variables): float {
              $parser = new StdMathParser();
              $ast = $parser->parse($expression);
              $evaluator = new \MathParser\Interpreting\Evaluator();
              $evaluator->setVariables($variables);
              return $ast->accept($evaluator);
          }
      }
      
  3. Validation Layer:
    • Use Laravel’s Form Request validation to restrict input:
      public function rules() {
          return [
              'expression' => [
                  'required',
                  'regex:/^[a-zA-Z0-9+\-*\/^().\s]+$/', // Basic math syntax
                  'max:1000' // Prevent excessively long expressions
              ]
          ];
      }
      
    • Add custom validation for whitelisted functions:
      public function withValidator($validator) {
          $validator->addRules([
              'expression' => ['custom', function ($attribute, $value, $fail) {
                  $allowedFunctions = ['sin', 'cos', 'log', 'sqrt'];
                  preg_match_all('/\b([a-zA-Z]+)\s*\()/',$value, $matches);
                  $foundFunctions = array_unique($matches[1]);
                  $invalidFunctions = array_diff($foundFunctions, $allowedFunctions);
                  if (!empty($invalidFunctions)) {
                      $fail("Function(s) {$invalidFunctions[0]} not allowed.");
                  }
              }]
          ]);
      }
      
  4. Caching Strategy:
    • Cache parsed ASTs for frequent expressions:
      $cacheKey = 'math_ast:' . md5($expression);
      $ast = cache()->remember($cacheKey, now()->addHours(1), function () use ($parser, $expression) {
          return $parser->parse($expression);
      });
      
  5. LaTeX Integration:
    • Generate LaTeX in the backend and pass to the frontend:
      $latexGenerator = new \MathParser\Interpreting\LatexGenerator();
      $latex = $ast->accept($latexGenerator);
      return response()->json(['latex' => $latex]);
      
    • Render in Blade:
      <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
      <div>{{ $latex }}</div>
      

Compatibility

  • PHP Version: Requires **
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky