tienvx/assignments-evaluator

Allow assign value of Symfony Expression Language's expressions to variables

Fund package maintenance!
tienvx

v1.0.1 2022-07-12 01:42 UTC

This package is auto-updated.

Last update: 2024-10-12 21:50:59 UTC


README

Symfony Expression Language only return single value per expression. It does not support assignment. This library allow assigning result of that expression's evaluation to a variable. It also support multiple assignments.

Installation

composer require tienvx/assignments-evaluator

Documentation

use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Tienvx\AssignmentsEvaluator\AssignmentsEvaluator;

class Robot
{
    public function sayHi(string $name): string
    {
        return sprintf('Hi %s!', $name);
    }
}

$assignmentsEvaluator = new AssignmentsEvaluator(new ExpressionLanguage());

var_dump($assignmentsEvaluator->evaluate(
    'fullName = firstName~" "~lastName; hello = robot.sayHi(fullName)',
    [
        'firstName' => 'Madonna',
        'lastName' => 'Jenkins',
        'robot' => new Robot(),
    ]
));
/* displays
array(5) {
  ["firstName"]=>
  string(7) "Madonna"
  ["lastName"]=>
  string(7) "Jenkins"
  ["robot"]=>
  object(Robot)#8 (0) {
  }
  ["fullName"]=>
  string(15) "Madonna Jenkins"
  ["hello"]=>
  string(19) "Hi Madonna Jenkins!"
}
*/

$assignmentsEvaluator->lint('title = "Dr."; firstName = "zane"; lastName = "stroman"; name = title~ucfirst(firstName)~" "~ucfirst(lastName)');
/* throw
PHP Fatal error:  Uncaught Tienvx\AssignmentsEvaluator\SyntaxError: Expression "title~ucfirst(firstName)~" "~ucfirst(lastName)" is invalid: The function "ucfirst" does not exist around position 7 for expression `title~ucfirst(firstName)~" "~ucfirst(lastName)`..
*/

License

MIT