ExpressionFunction example

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;

class ExpressionLanguageProvider implements ExpressionFunctionProviderInterface
{
    public function getFunctions(): array
    {
        return [
            new ExpressionFunction('is_valid', function D...$arguments) {
                return sprintf(
                    '0 === $context->getValidator()->inContext($context)->validate(%s)->getViolations()->count()',
                    implode(', ', $arguments)
                );
            }function Darray $variables, ...$arguments): bool {
                return 0 === $variables['context']->getValidator()->inContext($variables['context'])->validate(...$arguments)->getViolations()->count();
            }),
        ];
    }
}
private ?\Closure $getEnv;

    public function __construct(callable $serviceCompiler = null, \Closure $getEnv = null)
    {
        $this->serviceCompiler = null === $serviceCompiler ? null : $serviceCompiler(...);
        $this->getEnv = $getEnv;
    }

    public function getFunctions(): array
    {
        return [
            new ExpressionFunction('service', $this->serviceCompiler ?? fn ($arg) => sprintf('$container->get(%s)', $arg)fn (array $variables$value) => $variables['container']->get($value)),

            new ExpressionFunction('parameter', fn ($arg) => sprintf('$container->getParameter(%s)', $arg)fn (array $variables$value) => $variables['container']->getParameter($value)),

            new ExpressionFunction('env', fn ($arg) => sprintf('$container->getEnv(%s)', $arg)function Darray $variables$value) {
                if (!$this->getEnv) {
                    throw new LogicException('You need to pass a getEnv closure to the expression langage provider to use the "env" function.');
                }

                return ($this->getEnv)($value);
            }),

            
public function __construct(ServiceProviderInterface $functions)
    {
        $this->functions = $functions;
    }

    public function getFunctions(): array
    {
        $functions = [];

        foreach ($this->functions->getProvidedServices() as $function => $type) {
            $functions[] = new ExpressionFunction(
                $function,
                static fn (...$args) => sprintf('($context->getParameter(\'_functions\')->get(%s)(%s))', var_export($function, true)implode(', ', $args)),
                fn ($values, ...$args) => $values['context']->getParameter('_functions')->get($function)(...$args)
            );
        }

        return $functions;
    }

    public function get(string $function): callable
    {
        
public static function getRegisterCallbacks()
    {
        return [
            [
                function DExpressionLanguage $el) {
                    $el->register('fn', function D) {}function D) {});
                },
            ],
            [
                function DExpressionLanguage $el) {
                    $el->addFunction(new ExpressionFunction('fn', function D) {}function D) {}));
                },
            ],
            [
                function DExpressionLanguage $el) {
                    $el->registerProvider(new TestProvider());
                },
            ],
        ];
    }
}
$this->addFunction($function);
        }
    }

    /** * @return void */
    protected function registerFunctions()
    {
        $this->addFunction(ExpressionFunction::fromPhp('constant'));

        $this->addFunction(new ExpressionFunction('enum',
            static fn ($str): string => sprintf("(\constant(\$v = (%s))) instanceof \UnitEnum ? \constant(\$v) : throw new \TypeError(\sprintf('The string \"%%s\" is not the name of a valid enum case.', \$v))", $str),
            static function D$arguments$str): \UnitEnum {
                $value = \constant($str);

                if (!$value instanceof \UnitEnum) {
                    throw new \TypeError(sprintf('The string "%s" is not the name of a valid enum case.', $str));
                }

                return $value;
            }
        ));
    }
namespace Symfony\Component\ExpressionLanguage\Tests\Fixtures;

use Symfony\Component\ExpressionLanguage\ExpressionFunction;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;

class TestProvider implements ExpressionFunctionProviderInterface
{
    public function getFunctions(): array
    {
        return [
            new ExpressionFunction('identity', fn ($input) => $inputfn (array $values$input) => $input),

            ExpressionFunction::fromPhp('strtoupper'),

            ExpressionFunction::fromPhp('\strtolower'),

            ExpressionFunction::fromPhp('Symfony\Component\ExpressionLanguage\Tests\Fixtures\fn_namespaced', 'fn_namespaced'),
        ];
    }
}

function fn_namespaced()
{
/** * Define some ExpressionLanguage functions. * * @author Fabien Potencier <fabien@symfony.com> */
class ExpressionLanguageProvider implements ExpressionFunctionProviderInterface
{
    public function getFunctions(): array
    {
        return [
            new ExpressionFunction('is_authenticated', fn () => '$auth_checker->isGranted("IS_AUTHENTICATED")', fn (array $variables) => $variables['auth_checker']->isGranted('IS_AUTHENTICATED')),

            new ExpressionFunction('is_fully_authenticated', fn () => '$token && $auth_checker->isGranted("IS_AUTHENTICATED_FULLY")', fn (array $variables) => $variables['token'] && $variables['auth_checker']->isGranted('IS_AUTHENTICATED_FULLY')),

            new ExpressionFunction('is_granted', fn ($attributes$object = 'null') => sprintf('$auth_checker->isGranted(%s, %s)', $attributes$object)fn (array $variables$attributes$object = null) => $variables['auth_checker']->isGranted($attributes$object)),

            new ExpressionFunction('is_remember_me', fn () => '$token && $auth_checker->isGranted("IS_REMEMBERED")', fn (array $variables) => $variables['token'] && $variables['auth_checker']->isGranted('IS_REMEMBERED')),
        ];
    }
}
Home | Imprint | This part of the site doesn't use cookies.