Hello,
For a personal project, I'd like to work with dynamic formulas.
I explain you.
A user types a width and a height and the form calculates automatically the surface.
How does the application know what calculation to do ? The formula is somewhere in the database.
How ?
The admin will create a calculation type named "Surface", for this surface, he will create 2 variables : the height and the width.
In the database, this can be for example like this.
calculations
*name
*formula
variables
*name
*unit
*calculation
There will be the Surface calculation and 2 variables (height in meters, width in meters). The formula will be width * height (stored as a string in the database.
From these informations, I will display a form with the title (Surface) and the 2 input fields to type the height and the width.
To display the result, I need to evaluate the formula.
What do you suggest me ?
I have thought about 2 different ways.
First one
I thought about eval(), but it's risky, so I had a look on the web, the ExpressionLanguage class from Symfony looks interesting.
Do you know any equivalent for Laravel ? I have found this package.
https://packagist.org/packages/wuwx/laravel-expression-language
Second one
Or perhaps a way to evaluate an expression securely without any package ? I thought about parsing the formula to identify the variables, validate the values typed by the user and replace the variables by the typed values. And then evaluate the formula with eval().
For this idea, my question is : is there any risk using eval() if I validate correctly each typed value ?
But you have perhaps other suggestions ?
Thanks for your answer.
V