|
| 1 | +<?php |
| 2 | +declare(strict_types=1); |
| 3 | + |
| 4 | +namespace Sitegeist\FluidComponentsLinter\CodeQuality\Check; |
| 5 | + |
| 6 | +use Sitegeist\FluidComponentsLinter\CodeQuality\Component; |
| 7 | +use Sitegeist\FluidComponentsLinter\Exception\CodeQualityException; |
| 8 | +use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\ObjectAccessorNode; |
| 9 | +use TYPO3Fluid\Fluid\Core\Parser\SyntaxTree\ViewHelperNode; |
| 10 | + |
| 11 | +class ComponentVariablesCheck extends AbstractCheck |
| 12 | +{ |
| 13 | + protected $predefinedVariables = [ |
| 14 | + 'settings(\.|$)', |
| 15 | + 'class$', |
| 16 | + 'content$', |
| 17 | + 'component\.(class|prefix|namespace)$' |
| 18 | + ]; |
| 19 | + |
| 20 | + public function check(): array |
| 21 | + { |
| 22 | + $allowedVariables = array_merge($this->predefinedVariables, $this->generateParamNamePatterns()); |
| 23 | + $allowedVariablesPattern = '#^(' . implode('|', $allowedVariables) . ')#'; |
| 24 | + |
| 25 | + $usedVariables = $this->fluidService->extractNodeType( |
| 26 | + $this->component->rootNode, |
| 27 | + ObjectAccessorNode::class |
| 28 | + ); |
| 29 | + $usedVariableNames = array_map(function (ObjectAccessorNode $node) { |
| 30 | + return $node->getObjectPath(); |
| 31 | + }, $usedVariables); |
| 32 | + |
| 33 | + $invalidVariables = array_filter( |
| 34 | + $usedVariableNames, |
| 35 | + function (string $usedVariable) use ($allowedVariablesPattern) { |
| 36 | + return !preg_match($allowedVariablesPattern, $usedVariable); |
| 37 | + } |
| 38 | + ); |
| 39 | + |
| 40 | + if (!empty($invalidVariables)) { |
| 41 | + throw new CodeQualityException(sprintf( |
| 42 | + 'The following variables are used in the component, but were never defined: %s', |
| 43 | + '{' . implode('}, {', $invalidVariables) . '}' |
| 44 | + ), 1595870402); |
| 45 | + } |
| 46 | + |
| 47 | + return []; |
| 48 | + } |
| 49 | + |
| 50 | + protected function generateParamNamePatterns(): array |
| 51 | + { |
| 52 | + return array_map(function (ViewHelperNode $node) { |
| 53 | + return preg_quote((string) $node->getArguments()['name'], '#') . '(\.|$)'; |
| 54 | + }, $this->component->paramNodes); |
| 55 | + } |
| 56 | +} |
0 commit comments