[TASK] Streamline expressionLanguage usage in core
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / ExpressionLanguage / Resolver.php
1 <?php
2 declare(strict_types = 1);
3 namespace TYPO3\CMS\Core\ExpressionLanguage;
4
5 /*
6 * This file is part of the TYPO3 CMS project.
7 *
8 * It is free software; you can redistribute it and/or modify it under
9 * the terms of the GNU General Public License, either version 2
10 * of the License, or any later version.
11 *
12 * For the full copyright and license information, please read the
13 * LICENSE.txt file that was distributed with this source code.
14 *
15 * The TYPO3 project - inspiring people to share!
16 */
17
18 use Symfony\Component\ExpressionLanguage\ExpressionLanguage;
19 use TYPO3\CMS\Core\Utility\GeneralUtility;
20
21 /**
22 * Class Resolver
23 */
24 class Resolver
25 {
26 /**
27 * @var ProviderInterface
28 */
29 protected $provider;
30
31 /**
32 * @var \Symfony\Component\ExpressionLanguage\ExpressionLanguage
33 */
34 protected $expressionLanguage;
35
36 /**
37 * @var array
38 */
39 public $expressionLanguageVariables = [];
40
41 /**
42 * @param string $context
43 * @param array $variables
44 */
45 public function __construct(string $context, array $variables)
46 {
47 $functionProviderInstances = [];
48 $providers = GeneralUtility::makeInstance(ProviderConfigurationLoader::class)->getExpressionLanguageProviders()[$context] ?? [];
49 // Always add default provider
50 array_unshift($providers, DefaultProvider::class);
51 $providers = array_unique($providers);
52 $functionProviders = [];
53 $generalVariables = [];
54 foreach ($providers as $provider) {
55 /** @var ProviderInterface $providerInstance */
56 $providerInstance = GeneralUtility::makeInstance($provider);
57 $functionProviders[] = $providerInstance->getExpressionLanguageProviders();
58 $generalVariables[] = $providerInstance->getExpressionLanguageVariables();
59 }
60 $functionProviders = array_merge(...$functionProviders);
61 $generalVariables = array_replace_recursive(...$generalVariables);
62 $this->expressionLanguageVariables = array_replace_recursive($generalVariables, $variables);
63 foreach ($functionProviders as $functionProvider) {
64 $functionProviderInstances[] = GeneralUtility::makeInstance($functionProvider);
65 }
66 $this->expressionLanguage = new ExpressionLanguage(null, $functionProviderInstances);
67 }
68
69 /**
70 * Evaluate an expression.
71 *
72 * @param string $condition The expression to parse
73 * @return bool
74 */
75 public function evaluate(string $condition): bool
76 {
77 return (bool)$this->expressionLanguage->evaluate($condition, $this->expressionLanguageVariables);
78 }
79
80 /**
81 * Compiles an expression source code.
82 *
83 * @param string $condition The expression to compile
84 * @return string
85 */
86 public function compile(string $condition): string
87 {
88 return (string)$this->expressionLanguage->compile($condition, array_keys($this->expressionLanguageVariables));
89 }
90 }