Skip to content

Generate inverse 'if' expression from Expression AST #102

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: 1.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
->tag('purgatory.subscription_resolver')
->args([
service('property_info.reflection_extractor'),
service('sofascore.purgatory.expression_language')->nullOnInvalid(),
])

->set('sofascore.purgatory.subscription_resolver.embeddable', EmbeddableResolver::class)
Expand Down
40 changes: 39 additions & 1 deletion psalm-baseline.xml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<files psalm-version="6.3.0@222dda8483516044c2ed7a4c3f197d7c9d6c3ddb">
<files psalm-version="6.10.1@f9fd6bc117e9ce1e854c2ed6777e7135aaa4966b">
<file src="src/Cache/Configuration/CachedConfigurationLoader.php">
<MixedArgument>
<code><![CDATA[require $cache->getPath()]]></code>
Expand All @@ -8,6 +8,44 @@
<code><![CDATA[require $cache->getPath()]]></code>
</UnresolvableInclude>
</file>
<file src="src/Cache/PropertyResolver/AssociationResolver.php">
<InternalClass>
<code><![CDATA[GetAttrNode::METHOD_CALL]]></code>
<code><![CDATA[GetAttrNode::PROPERTY_CALL]]></code>
<code><![CDATA[new ArgumentsNode()]]></code>
<code><![CDATA[new ConstantNode(
value: $inverse,
isIdentifier: true,
)]]></code>
<code><![CDATA[new GetAttrNode(
node: new NameNode('obj'),
attribute: new ConstantNode(
value: $inverse,
isIdentifier: true,
),
arguments: new ArgumentsNode(),
type: $type,
)]]></code>
<code><![CDATA[new NameNode('obj')]]></code>
</InternalClass>
<InternalMethod>
<code><![CDATA[new ArgumentsNode()]]></code>
<code><![CDATA[new ConstantNode(
value: $inverse,
isIdentifier: true,
)]]></code>
<code><![CDATA[new GetAttrNode(
node: new NameNode('obj'),
attribute: new ConstantNode(
value: $inverse,
isIdentifier: true,
),
arguments: new ArgumentsNode(),
type: $type,
)]]></code>
<code><![CDATA[new NameNode('obj')]]></code>
</InternalMethod>
</file>
<file src="src/Cache/RouteMetadata/AttributeMetadataProvider.php">
<PossiblyUndefinedArrayOffset>
<code><![CDATA[$method]]></code>
Expand Down
73 changes: 62 additions & 11 deletions src/Cache/PropertyResolver/AssociationResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,23 @@
use Sofascore\PurgatoryBundle\Attribute\RouteParamValue\ValuesInterface;
use Sofascore\PurgatoryBundle\Cache\RouteMetadata\RouteMetadata;
use Sofascore\PurgatoryBundle\Cache\Subscription\PurgeSubscription;
use Sofascore\PurgatoryBundle\Exception\LogicException;
use Sofascore\PurgatoryBundle\Exception\PropertyNotAccessibleException;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\ExpressionLanguage\Node\ArgumentsNode;
use Symfony\Component\ExpressionLanguage\Node\ConstantNode;
use Symfony\Component\ExpressionLanguage\Node\GetAttrNode;
use Symfony\Component\ExpressionLanguage\Node\NameNode;
use Symfony\Component\ExpressionLanguage\Node\Node;
use Symfony\Component\PropertyInfo\PropertyReadInfo;
use Symfony\Component\PropertyInfo\PropertyReadInfoExtractorInterface;

final class AssociationResolver implements SubscriptionResolverInterface
{
public function __construct(
private readonly PropertyReadInfoExtractorInterface $extractor,
private readonly ?ExpressionLanguage $expressionLanguage,
) {
}

Expand Down Expand Up @@ -72,10 +80,7 @@ public function resolveSubscription(
}

if (null !== $if = $routeMetadata->purgeOn->if) {
$expression = (string) $if;
$getter = $this->createGetter($associationClass, $associationTarget);
$inverseIf = str_replace('obj', 'obj.'.$getter, $expression);
$if = new Expression("obj.$getter !== null && ($inverseIf)");
$if = $this->createInverseExpression($if, $associationClass, $associationTarget);
}

yield new PurgeSubscription(
Expand All @@ -96,18 +101,64 @@ private function getInverseValuesFor(ValuesInterface $values, string $associatio
return $values instanceof InverseValuesAwareInterface ? $values->buildInverseValuesFor($associationTarget) : $values;
}

private function createGetter(string $class, string $property): string
{
if (null === $readInfo = $this->extractor->getReadInfo($class, $property)) {
throw new PropertyNotAccessibleException($class, $property);
private function createInverseExpression(
Expression $expression,
string $associationClass,
string $associationTarget,
): Expression {
if (null === $readInfo = $this->extractor->getReadInfo($associationClass, $associationTarget)) {
throw new PropertyNotAccessibleException($associationClass, $associationTarget);
}

/** @var PropertyReadInfo::TYPE_* $type */
$type = $readInfo->getType();
$name = $readInfo->getName();

return match ($type) {
PropertyReadInfo::TYPE_METHOD => $readInfo->getName().'()',
PropertyReadInfo::TYPE_PROPERTY => $readInfo->getName(),
[$callType, $getter] = match ($type) {
PropertyReadInfo::TYPE_METHOD => [GetAttrNode::METHOD_CALL, "$name()"],
PropertyReadInfo::TYPE_PROPERTY => [GetAttrNode::PROPERTY_CALL, $name],
};

$node = $this->getExpressionLanguage()->parse($expression, ['obj'])->getNodes();
$inverseIf = $this->replaceObjWithInverse($node, $name, $callType)->dump();

return new Expression("obj.$getter !== null && ($inverseIf)");
}

/**
* @param GetAttrNode::PROPERTY_CALL|GetAttrNode::METHOD_CALL $type
*/
private function replaceObjWithInverse(Node $node, string $inverse, int $type): Node
{
if ($node instanceof NameNode && 'obj' === $node->attributes['name']) {
return new GetAttrNode(
node: new NameNode('obj'),
attribute: new ConstantNode(
value: $inverse,
isIdentifier: true,
),
arguments: new ArgumentsNode(),
type: $type,
);
}

$newNode = clone $node;
$newNode->nodes = [];

/**
* @var string $key
* @var Node $childNode
*/
foreach ($node->nodes as $key => $childNode) {
$newNode->nodes[$key] = $this->replaceObjWithInverse($childNode, $inverse, $type);
}

return $newNode;
}

private function getExpressionLanguage(): ExpressionLanguage
{
return $this->expressionLanguage
?? throw new LogicException('You cannot use expressions because the Symfony ExpressionLanguage component is not installed. Try running "composer require symfony/expression-language".');
}
}
2 changes: 1 addition & 1 deletion tests/Application/ConfigurationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ public static function configurationWithoutTargetProvider(): iterable
],
],
],
'if' => "obj.owner !== null && (obj.owner.firstName === 'John')",
'if' => 'obj.owner !== null && ((obj.owner.firstName === "John"))',
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

when converting some types of nodes to string, they are wrapped in parentheses so we end up with double parentheses.
not sure if we should handle this or just leave it be.

],
];
}
Expand Down
83 changes: 79 additions & 4 deletions tests/Cache/PropertyResolver/AssociationResolverTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
use Sofascore\PurgatoryBundle\Cache\PropertyResolver\AssociationResolver;
use Sofascore\PurgatoryBundle\Cache\RouteMetadata\RouteMetadata;
use Sofascore\PurgatoryBundle\Cache\Subscription\PurgeSubscription;
use Sofascore\PurgatoryBundle\Exception\PropertyNotAccessibleException;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\PropertyInfo\PropertyReadInfo;
use Symfony\Component\PropertyInfo\PropertyReadInfoExtractorInterface;
Expand Down Expand Up @@ -43,7 +45,10 @@ public function testResolveAssociations(
),
);

$resolver = new AssociationResolver($extractor);
$resolver = new AssociationResolver(
extractor: $extractor,
expressionLanguage: new ExpressionLanguage(),
);

$classMetadata = $this->createMock(ClassMetadata::class);
$classMetadata->method('hasAssociation')
Expand Down Expand Up @@ -104,15 +109,16 @@ classMetadata: $classMetadata,
$subscription[0]->routeParams['param1'],
);
self::assertEquals(new RawValues('const'), $subscription[0]->routeParams['param2']);
self::assertSame('obj.getFoo() !== null && (obj.getFoo().isActive() === true)', (string) $subscription[0]->if);
self::assertSame('obj.getFoo() !== null && ((obj.getFoo().isActive() === true))', (string) $subscription[0]->if);
}

abstract public static function associationProvider(): iterable;

public function testFieldNotAssociation(): void
{
$resolver = new AssociationResolver(
$this->createMock(PropertyReadInfoExtractorInterface::class),
extractor: $this->createMock(PropertyReadInfoExtractorInterface::class),
expressionLanguage: new ExpressionLanguage(),
);

$classMetadata = $this->createMock(ClassMetadata::class);
Expand Down Expand Up @@ -146,7 +152,8 @@ classMetadata: $classMetadata,
public function testInvalidAssociationType(array $associationMapping): void
{
$resolver = new AssociationResolver(
$this->createMock(PropertyReadInfoExtractorInterface::class),
extractor: $this->createMock(PropertyReadInfoExtractorInterface::class),
expressionLanguage: new ExpressionLanguage(),
);

$classMetadata = $this->createMock(ClassMetadata::class);
Expand Down Expand Up @@ -182,4 +189,72 @@ classMetadata: $classMetadata,
}

abstract public static function invalidAssociationProvider(): iterable;

#[DataProvider('associationProvider')]
public function testExceptionIsThrownOnUnreadableAssocationTarget(
array $associationMapping,
bool $isGetAssociationMappedByTargetFieldCalled,
bool $isAssociationInverseSide,
): void {
$extractor = $this->createMock(PropertyReadInfoExtractorInterface::class);
$extractor->expects(self::once())
->method('getReadInfo')
->with('BarEntity', 'barProperty')
->willReturn(null);

$resolver = new AssociationResolver(
extractor: $extractor,
expressionLanguage: new ExpressionLanguage(),
);

$classMetadata = $this->createMock(ClassMetadata::class);
$classMetadata->expects(self::once())
->method('hasAssociation')
->with('fooProperty')
->willReturn(true);
$classMetadata->method('getAssociationMapping')
->with('fooProperty')
->willReturn($this->createAssociationMapping($associationMapping));

$classMetadata->method('isAssociationInverseSide')
->with('fooProperty')
->willReturn($isAssociationInverseSide);

if ($isGetAssociationMappedByTargetFieldCalled) {
$classMetadata->expects(self::once())
->method('getAssociationMappedByTargetField')
->with('fooProperty')
->willReturn('barProperty');
} else {
$classMetadata->expects(self::never())
->method('getAssociationMappedByTargetField');
}

$classMetadata->method('getAssociationTargetClass')
->with('fooProperty')
->willReturn('BarEntity');

$purgeSubscription = $resolver->resolveSubscription(
routeMetadata: new RouteMetadata(
routeName: 'route_foo',
route: new Route('/foo/{param1}/{param2}'),
purgeOn: new PurgeOn(
class: 'FooEntity',
if: new Expression('obj.isActive() === true'),
),
reflectionMethod: null,
),
classMetadata: $classMetadata,
routeParams: [
'param1' => new PropertyValues('bazProperty'),
'param2' => new RawValues('const'),
],
target: 'fooProperty',
);

$this->expectException(PropertyNotAccessibleException::class);
$this->expectExceptionMessage('Unable to create a getter for property "BarEntity::barProperty".');

[...$purgeSubscription];
}
}