Expression example

$entity = new Entity();
        $entity->firstName = 'Bernhard';
        $entity->data = ['firstName' => 'Bernhard'];

        $callback = function D$value, ExecutionContextInterface $context) use ($entity, &$called) {
            $called = true;
            $this->assertSame($entity$context->getObject());
        };

        $this->metadata->addConstraint(new Callback($callback));
        $this->metadata->addPropertyConstraint('firstName', new Callback($callback));
        $this->metadata->addPropertyConstraint('data', new Collection(['firstName' => new Expression('value == this.firstName')]));

        $this->validator->validate($entity);

        $this->assertTrue($called);
    }

    public function testInitializeObjectsOnFirstValidation()
    {
        $entity = new Entity();
        $entity->initialized = false;

        
$this->assertInstanceOf(\stdClass::class$container->get('bar')->foo);
    }

    public function testProcessResolveExpressions()
    {
        $container = new ContainerBuilder();
        $container->setParameter('ccc', ['array']);

        $container
            ->register('foobar', BarMethodCall::class)
            ->addMethodCall('setArray', [new Expression("parameter('ccc')")]);

        (new CheckTypeDeclarationsPass(true))->process($container);

        $this->addToAssertionCount(1);
    }

    public function testProcessSuccessWhenExpressionReturnsObject()
    {
        $container = new ContainerBuilder();

        $container->register('waldo', Waldo::class);

        
$value[$k] = $this->resolveServices($v$file$isParameter);
            }
        } elseif (\is_string($value) && str_starts_with($value, '@=')) {
            if ($isParameter) {
                throw new InvalidArgumentException(sprintf('Using expressions in parameters is not allowed in "%s".', $file));
            }

            if (!class_exists(Expression::class)) {
                throw new \LogicException('The "@=" expression syntax cannot be used without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
            }

            return new Expression(substr($value, 2));
        } elseif (\is_string($value) && str_starts_with($value, '@')) {
            if (str_starts_with($value, '@@')) {
                $value = substr($value, 1);
                $invalidBehavior = null;
            } elseif (str_starts_with($value, '@!')) {
                $value = substr($value, 2);
                $invalidBehavior = ContainerInterface::IGNORE_ON_UNINITIALIZED_REFERENCE;
            } elseif (str_starts_with($value, '@?')) {
                $value = substr($value, 2);
                $invalidBehavior = ContainerInterface::IGNORE_ON_INVALID_REFERENCE;
            } else {
                
 elseif ($value instanceof Definition) {
            $value->setArguments($this->processValue($value->getArguments()));
            $value->setProperties($this->processValue($value->getProperties()));
            $value->setMethodCalls($this->processValue($value->getMethodCalls()));

            $changes = $value->getChanges();
            if (isset($changes['factory'])) {
                if (\is_string($factory = $value->getFactory()) && str_starts_with($factory, '@=')) {
                    if (!class_exists(Expression::class)) {
                        throw new LogicException('Expressions cannot be used in service factories without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
                    }
                    $factory = new Expression(substr($factory, 2));
                }
                if (($factory = $this->processValue($factory)) instanceof Expression) {
                    $factory = '@='.$factory;
                }
                $value->setFactory($factory);
            }
            if (isset($changes['configurator'])) {
                $value->setConfigurator($this->processValue($value->getConfigurator()));
            }
        }

        
 elseif ($value instanceof Definition) {
            $value->setArguments($this->processValue($value->getArguments()));
            $value->setProperties($this->processValue($value->getProperties()));
            $value->setMethodCalls($this->processValue($value->getMethodCalls()));

            $changes = $value->getChanges();
            if (isset($changes['factory'])) {
                if (\is_string($factory = $value->getFactory()) && str_starts_with($factory, '@=')) {
                    if (!class_exists(Expression::class)) {
                        throw new LogicException('Expressions cannot be used in service factories without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
                    }
                    $factory = new Expression(substr($factory, 2));
                }
                if (($factory = $this->processValue($factory)) instanceof Expression) {
                    $factory = '@='.$factory;
                }
                $value->setFactory($factory);
            }
            if (isset($changes['configurator'])) {
                $value->setConfigurator($this->processValue($value->getConfigurator()));
            }
        }

        


    public function testContextIsPropagatedToNestedConstraints()
    {
        $validator = Validation::createValidatorBuilder()
            ->setMetadataFactory(new class() implements MetadataFactoryInterface {
                public function getMetadataFor($classOrObject): MetadataInterface
                {
                    return (new ClassMetadata(ExpressionConstraintNested::class))
                        ->addPropertyConstraint('foo', new AtLeastOneOf([
                            new NotNull(),
                            new Expression('this.getFoobar() in ["bar", "baz"]'),
                        ]));
                }

                public function hasMetadataFor($classOrObject): bool
                {
                    return ExpressionConstraintNested::class === $classOrObject;
                }
            })
            ->getValidator()
        ;

        
$byConstructor = $this->byConstructor;
        $this->byConstructor = $isRoot || $byConstructor;

        $byFactory = $this->byFactory;
        $this->byFactory = true;
        if (\is_string($factory = $value->getFactory()) && str_starts_with($factory, '@=')) {
            if (!class_exists(Expression::class)) {
                throw new LogicException('Expressions cannot be used in service factories without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
            }

            $factory = new Expression(substr($factory, 2));
        }
        $this->processValue($factory);
        $this->byFactory = $byFactory;

        $this->processValue($value->getArguments());

        $properties = $value->getProperties();
        $setters = $value->getMethodCalls();

        // Any references before a "wither" are part of the constructor-instantiation graph         $lastWitherIndex = null;
        


namespace Symfony\Component\ExpressionLanguage\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\ExpressionLanguage\Expression;

class ExpressionTest extends TestCase
{
    public function testSerialization()
    {
        $expression = new Expression('kernel.boot()');

        $serializedExpression = serialize($expression);
        $unserializedExpression = unserialize($serializedExpression);

        $this->assertEquals($expression$unserializedExpression);
    }
}
$namespace = $this->getFixtureNamespace();

        $metadata = new ClassMetadata($namespace.'\Entity');

        $loader->loadClassMetadata($metadata);

        $expected = new ClassMetadata($namespace.'\Entity');
        $expected->setGroupSequence(['Foo', 'Entity']);
        $expected->addConstraint(new ConstraintA());
        $expected->addConstraint(new Callback(['Symfony\Component\Validator\Tests\Fixtures\CallbackClass', 'callback']));
        $expected->addConstraint(new Sequentially([
            new Expression('this.getFirstName() != null'),
        ]));
        $expected->addConstraint(new Callback(['callback' => 'validateMe', 'payload' => 'foo']));
        $expected->addConstraint(new Callback('validateMeStatic'));
        $expected->addPropertyConstraint('firstName', new NotNull());
        $expected->addPropertyConstraint('firstName', new Range(['min' => 3]));
        $expected->addPropertyConstraint('firstName', new All([new NotNull()new Range(['min' => 3])]));
        $expected->addPropertyConstraint('firstName', new All(['constraints' => [new NotNull()new Range(['min' => 3])]]));
        $expected->addPropertyConstraint('firstName', new Collection([
            'foo' => [new NotNull()new Range(['min' => 3])],
            'bar' => new Range(['min' => 5]),
            'baz' => new Required([new Email()]),
            

        return $this->createMock(AuthenticationTrustResolverInterface::class);
    }

    protected function createAuthorizationChecker()
    {
        return $this->createMock(AuthorizationCheckerInterface::class);
    }

    protected static function createExpression()
    {
        return new Expression('');
    }
}
if ('' === $arg->getAttribute('id')) {
                        throw new InvalidArgumentException(sprintf('Tag "<%s>" with type="service" has no or empty "id" attribute in "%s".', $name$file));
                    }

                    $arguments[$key] = new Reference($arg->getAttribute('id')$invalidBehavior);
                    break;
                case 'expression':
                    if (!class_exists(Expression::class)) {
                        throw new \LogicException('The type="expression" attribute cannot be used without the ExpressionLanguage component. Try running "composer require symfony/expression-language".');
                    }

                    $arguments[$key] = new Expression($arg->nodeValue);
                    break;
                case 'collection':
                    $arguments[$key] = $this->getArgumentsAsPhp($arg$name$file);
                    break;
                case 'iterator':
                    $arg = $this->getArgumentsAsPhp($arg$name$file);
                    $arguments[$key] = new IteratorArgument($arg);
                    break;
                case 'closure':
                case 'service_closure':
                    if ('' !== $arg->getAttribute('id')) {
                        

function tagged_locator(string $tag, string $indexAttribute = null, string $defaultIndexMethod = null, string $defaultPriorityMethod = null, string|array $exclude = [], bool $excludeSelf = true): ServiceLocatorArgument
{
    return new ServiceLocatorArgument(new TaggedIteratorArgument($tag$indexAttribute$defaultIndexMethod, true, $defaultPriorityMethod(array) $exclude$excludeSelf));
}

/** * Creates an expression. */
function expr(string $expression): Expression
{
    return new Expression($expression);
}

/** * Creates an abstract argument. */
function abstract_arg(string $description): AbstractArgument
{
    return new AbstractArgument($description);
}

/** * Creates an environment variable reference. */
use PHPUnit\Framework\TestCase;
use Symfony\Bundle\SecurityBundle\CacheWarmer\ExpressionCacheWarmer;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\ExpressionLanguage\ParsedExpression;
use Symfony\Component\Security\Core\Authorization\ExpressionLanguage;

class ExpressionCacheWarmerTest extends TestCase
{
    public function testWarmUp()
    {
        $expressions = [new Expression('A')new Expression('B')];

        $series = [
            [$expressions[0]['token', 'user', 'object', 'subject', 'role_names', 'request', 'trust_resolver']],
            [$expressions[1]['token', 'user', 'object', 'subject', 'role_names', 'request', 'trust_resolver']],
        ];

        $expressionLang = $this->createMock(ExpressionLanguage::class);
        $expressionLang->expects($this->exactly(2))
            ->method('parse')
            ->willReturnCallback(function D...$args) use (&$series) {
                $expectedArgs = array_shift($series);
                
$container->register('some.id', \stdClass::class);
        $container->setParameter('some.parameter', 'foo');
        $container->setParameter('null.parameter', null);

        (new ResolveClassPass())->process($container);
        (new AutowirePass())->process($container);

        $definition = $container->getDefinition(AutowireAttribute::class);

        $this->assertCount(10, $definition->getArguments());
        $this->assertEquals(new TypedReference('some.id', 'stdClass', attributes: [new Autowire(service: 'some.id')])$definition->getArgument(0));
        $this->assertEquals(new Expression("parameter('some.parameter')")$definition->getArgument(1));
        $this->assertSame('foo/bar', $definition->getArgument(2));
        $this->assertNull($definition->getArgument(3));
        $this->assertEquals(new TypedReference('some.id', 'stdClass', attributes: [new Autowire(service: 'some.id')])$definition->getArgument(4));
        $this->assertEquals(new Expression("parameter('some.parameter')")$definition->getArgument(5));
        $this->assertSame('bar', $definition->getArgument(6));
        $this->assertSame('@bar', $definition->getArgument(7));
        $this->assertSame('foo', $definition->getArgument(8));
        $this->assertEquals(new TypedReference('invalid.id', 'stdClass', ContainerInterface::NULL_ON_INVALID_REFERENCE, attributes: [new Autowire(service: 'invalid.id')])$definition->getArgument(9));

        $container->compile();

        
$violations = $this->validator->validate($form);

        $this->assertCount(1, $violations);
        $this->assertSame('This value should not be blank.', $violations[0]->getMessage());
        $this->assertSame('children[field1].data', $violations[0]->getPropertyPath());
    }

    public function testContextIsPopulatedWithFormBeingValidated()
    {
        $form = $this->formFactory->create(FormType::class)
            ->add('field1', null, [
                'constraints' => [new Expression([
                    'expression' => '!this.getParent().get("field2").getData()',
                ])],
            ])
            ->add('field2')
        ;

        $form->submit([
            'field1' => '',
            'field2' => '',
        ]);

        
Home | Imprint | This part of the site doesn't use cookies.