Weave 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 Executor Laravel Package

nxp/math-executor

Safely parse and evaluate math expressions from strings in PHP. nxp/math-executor is a lightweight library with variables, functions, custom operators, and caching, ideal for calculators, dynamic pricing, and formula-driven logic in Laravel and PHP apps.

View on GitHub
Deep Wiki
Context7

Product Decisions This Supports

  • Build vs. buy on expression evaluation. Any roadmap item that requires a user, admin, or config author to supply arithmetic at runtime — pricing rules, discount stacking, commission tiers, KPI scorecards, survey scoring, eligibility thresholds, points/gamification, unit conversion, premium or interest estimates — otherwise becomes a bespoke parser project. This package converts a 1–2 sprint build into an afternoon integration, and removes the most common shortcut (eval()) from the design conversation entirely.
  • Ship configuration, not deploys. The strategic value is not "math"; it is moving business-rule changes out of the release train. A PM can commit to "ops can change the volume-discount formula without engineering," which is a measurable reduction in time-to-change for commercial and finance stakeholders.
  • Feature scoping for a "formula field" capability. If the product direction includes spreadsheet-like calculated fields, this defines a credible v1 boundary: arithmetic, variables, parentheses, comparisons and boolean logic, plus our own named functions for anything domain-specific. It explicitly does not buy us Excel compatibility, date math, string manipulation, or a rule-authoring UI — those stay separate roadmap items, and the PM should say so up front to avoid over-promising.
  • Investment tier and ownership. With ~230 stars, zero dependents in the tracked ecosystem, and an MIT license, this is a utility dependency, not a platform bet. That argues for a thin internal adapter interface (FormulaEvaluator port) and a pinned version, not for building product surface directly against its API. The decision it supports is "adopt cheaply, insulate deliberately."
  • Typed failure is now a scoping asset (v2.4.0). Invalid math — divide-by-zero, bad operands, malformed variable values — now raises MathExecutor exceptions instead of leaking native PHP errors (TypeError, DivisionByZeroError, etc.). For the PM this is the difference between "formula validation is a nice-to-have" and "we can surface a specific, user-facing validation message on save and on preview." It makes a preview/validate-before-publish step a credible v1 requirement for the rules UI rather than a later hardening item, and it means support tickets read "your formula has an invalid value in step 3" rather than a 500.
  • Risk posture on untrusted input. Adopting it is a decision to treat expression input as semi-trusted (authored by admins, ops, or customers in a controlled context). If the roadmap ever includes arbitrary end-user formulas at scale, the PM should pre-plan a hardening milestone (input length/depth caps, allow-listed variables and functions, evaluation timeouts) or schedule a migration to a purpose-built rules engine. Note that typed exceptions improve diagnosability, not containment — pathological depth/length DoS is still our problem.
  • Prioritization signal for adjacent work. Because the package handles parsing but not persistence, versioning, previewing, or audit of formulas, the PM can size the real feature honestly: the parser is ~10% of a configurable-rules product; the other 90% is authoring UX, validation, change history, and rollback.

When to Consider This Package

Adopt when most of these hold:

  • The expressions are arithmetic-first: totals, percentages, tiers, thresholds, weighted scores, proration.
  • Formula authors are internal (ops, finance, CS) or a bounded set of customers — not the open internet.
  • You need it now and want a small, MIT-licensed dependency with no service to operate.
  • You need custom domain functions (shipping_cost(), tax_rate()) and custom operators, and want to register them in PHP rather than build a language.
  • You want to eliminate eval()/create_function-style shortcuts from the codebase for security review.
  • You want a single, catchable exception type for bad expression input so validation and preview UX can be built without special-casing engine internals (v2.4.0+).
  • You're comfortable pinning the version and owning a fork if the single maintainer steps away.
  • Money precision is not the dominant constraint (or you're prepared to round at the boundaries and keep authoritative totals in integer/decimal columns).

Look elsewhere when any of these hold:

  • Hardened sandboxing is the requirement. For fully untrusted or high-volume user input, symfony/expression-language is the safer default: larger community, mature sandbox, stricter parsing, and a well-understood security story. Paying the extra integration cost is cheaper than owning a security incident.
  • Money math must be exact. PHP float semantics will bite on tax, payroll, and multi-currency. Pair with brick/math or keep decimals as integers and use the package only for rule shape, not final amounts.
  • Users expect Excel/Sheets semantics. If the pitch includes "it works like a spreadsheet," PhpSpreadsheet's calculation engine is the honest comparison — otherwise you will spend quarters chasing formula-compatibility tickets.
  • You need a rules product: authoring UI, versioning, approvals, audit trail, dry-run against historical data, per-rule ownership. A parser is a component of that, not a substitute, and no single package gets you there.
  • Heavy date, string, or lookup logic. Those need functions you write yourself; at that point evaluate whether a dedicated rules engine is the better long-term home.
  • Denial-of-service exposure. Deeply nested or pathological expressions can burn CPU; if the input path is public and unauthenticated, budget for depth/length limits and a timeout wrapper before launch. Typed exceptions do not solve this.

How to Pitch It (Stakeholders)

To executives: We can offer configurable pricing, scoring, and eligibility rules without putting a release behind every change. This is a small, MIT-licensed PHP library — no vendor contract, no infrastructure, no data leaving our systems — that lets the application evaluate a formula supplied as text, safely, instead of us writing and maintaining a custom calculator. The latest release (v2.4.0) also means bad formulas fail predictably and with a clear error rather than crashing, which is what lets us show a meaningful message in the admin UI instead of a page error. The business outcome is faster commercial iteration and fewer engineering escalations for "change the discount formula." The honest caveats: it is a modestly adopted open-source component with essentially one maintainer, so we will wrap it behind our own interface and pin the version, which keeps the exit cheap. I'd frame this as a two-week enabler for the rules roadmap, not a strategic platform commitment.

To engineering: It solves tokenizing, operator precedence, variables, and function dispatch, so we don't hand-roll a parser or reach for eval(). Integration is a thin service class plus a registry of our own functions; we own allow-listing of variables and functions, input limits, decimal rounding, and caching of parsed expressions per request cycle. v2.4.0 is a behavior change worth catching in review: invalid values in math operations no longer surface as native PHP exceptions but as MathExecutor exceptions. Any existing try/catch around evaluation that targets TypeError / DivisionByZeroError / Error must be re-pointed at the package's exception type (and our adapter should normalize it into a domain-level FormulaEvaluationFailed), otherwise error paths that used to be handled will start bubbling as unhandled. Add a divide-by-zero and a non-numeric-variable case to the characterization suite as part of the bump. Recommended posture otherwise unchanged: depend on it through an internal FormulaEvaluator contract so a swap to symfony/expression-language or a full rules engine is a one-class change, and add characterization tests around our formulas before we let anyone edit them in production.

The ask: approve a short spike — one engineer, a fixed set of real pricing/scoring formulas, precision and performance measured against our money-handling standard — with a go/no-go on the adapter-wrapper approach at the end. Fold the v2.4.0 exception-normalization check into that spike; it is a half-day, not a project.

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.
skyraptor/chatter
edlugz/sasapay
abbasudo/artisan-route
mirvan/ippanel
ignibyte/aic-framework
glavweb/data-schema-bundle
glavweb/datagrid-bundle
tacticmedia/scim-server
uni-method/frame
neika-ai/sdk
adachsoft/php-code-style
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
adachsoft/api-version-bundle
cgv/localized-resource