1<?php
2
3declare(strict_types=1);
4
5namespace JMS\Serializer\Exclusion;
6
7use JMS\Serializer\Context;
8use JMS\Serializer\Expression\CompilableExpressionEvaluatorInterface;
9use JMS\Serializer\Expression\Expression;
10use JMS\Serializer\Expression\ExpressionEvaluatorInterface;
11use JMS\Serializer\Metadata\PropertyMetadata;
12use JMS\Serializer\SerializationContext;
13
14/**
15 * Exposes an exclusion strategy based on the Symfony's expression language.
16 * This is not a standard exclusion strategy and can not be used in user applications.
17 *
18 * @internal
19 *
20 * @author Asmir Mustafic <goetas@gmail.com>
21 */
22final class ExpressionLanguageExclusionStrategy
23{
24    /**
25     * @var ExpressionEvaluatorInterface
26     */
27    private $expressionEvaluator;
28
29    public function __construct(ExpressionEvaluatorInterface $expressionEvaluator)
30    {
31        $this->expressionEvaluator = $expressionEvaluator;
32    }
33
34    /**
35     * {@inheritDoc}
36     */
37    public function shouldSkipProperty(PropertyMetadata $property, Context $navigatorContext): bool
38    {
39        if (null === $property->excludeIf) {
40            return false;
41        }
42
43        $variables = [
44            'context' => $navigatorContext,
45            'property_metadata' => $property,
46        ];
47        if ($navigatorContext instanceof SerializationContext) {
48            $variables['object'] = $navigatorContext->getObject();
49        } else {
50            $variables['object'] = null;
51        }
52
53        if (($property->excludeIf instanceof Expression) && ($this->expressionEvaluator instanceof CompilableExpressionEvaluatorInterface)) {
54            return $this->expressionEvaluator->evaluateParsed($property->excludeIf, $variables);
55        }
56
57        return $this->expressionEvaluator->evaluate($property->excludeIf, $variables);
58    }
59}
60