123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- <?php
- namespace Symfony\Component\ExpressionLanguage;
- class ExpressionFunction
- {
- private $name;
- private $compiler;
- private $evaluator;
-
- public function __construct(string $name, callable $compiler, callable $evaluator)
- {
- $this->name = $name;
- $this->compiler = $compiler instanceof \Closure ? $compiler : \Closure::fromCallable($compiler);
- $this->evaluator = $evaluator instanceof \Closure ? $evaluator : \Closure::fromCallable($evaluator);
- }
-
- public function getName()
- {
- return $this->name;
- }
-
- public function getCompiler()
- {
- return $this->compiler;
- }
-
- public function getEvaluator()
- {
- return $this->evaluator;
- }
-
- public static function fromPhp(string $phpFunctionName, ?string $expressionFunctionName = null)
- {
- $phpFunctionName = ltrim($phpFunctionName, '\\');
- if (!\function_exists($phpFunctionName)) {
- throw new \InvalidArgumentException(sprintf('PHP function "%s" does not exist.', $phpFunctionName));
- }
- $parts = explode('\\', $phpFunctionName);
- if (!$expressionFunctionName && \count($parts) > 1) {
- throw new \InvalidArgumentException(sprintf('An expression function name must be defined when PHP function "%s" is namespaced.', $phpFunctionName));
- }
- $compiler = function (...$args) use ($phpFunctionName) {
- return sprintf('\%s(%s)', $phpFunctionName, implode(', ', $args));
- };
- $evaluator = function ($p, ...$args) use ($phpFunctionName) {
- return $phpFunctionName(...$args);
- };
- return new self($expressionFunctionName ?: end($parts), $compiler, $evaluator);
- }
- }
|