diff --git a/README.md b/README.md index 1f2147db..16dddd41 100644 --- a/README.md +++ b/README.md @@ -367,8 +367,12 @@ It reports: - An argument that isn't a scalar or `NULL` (`lazyBuilder.nonScalarArgument`). - Properties or children other than `#cache`, `#create_placeholder`, `#lazy_builder_preview`, `#placeholder_strategy_denylist`, `#preview` and `#weight` next to `#lazy_builder` (`lazyBuilder.unsupportedProperty`). - A callback method whose return type can't be an array (`lazyBuilder.nonArrayReturn`). +- Fewer arguments than the callback method requires, or more than it accepts when it isn't variadic (`lazyBuilder.argumentCount`). +- An argument that the callback method's native parameter type doesn't accept (`lazyBuilder.argumentType`). Drupal calls the callback without `strict_types`, so an argument PHP can coerce, like `'5'` for an `int` parameter, isn't reported. -The first one fails on every request. The others fail `assert()` calls, so they only throw with assertions on. Without assertions, Drupal renders the element wrong. +Drupal passes the arguments by position, after `array_values()`, so string keys in the arguments array don't name parameters. + +The first one fails on every request. So do too few arguments and arguments of the wrong type: Drupal throws an `ArgumentCountError` or a `TypeError` when it renders the placeholder. PHP ignores extra arguments. The others fail `assert()` calls, so they only throw with assertions on. Without assertions, Drupal renders the element wrong. Only array literals are checked. An element built across several statements, such as `$build['#lazy_builder'] = ...` followed by `$build['#title'] = ...`, is not. diff --git a/src/Rules/Drupal/RenderCallback/LazyBuilderRule.php b/src/Rules/Drupal/RenderCallback/LazyBuilderRule.php index 6a93de74..cbc80c28 100644 --- a/src/Rules/Drupal/RenderCallback/LazyBuilderRule.php +++ b/src/Rules/Drupal/RenderCallback/LazyBuilderRule.php @@ -9,6 +9,7 @@ use PhpParser\Node\Scalar\String_; use PHPStan\Analyser\DependencyTracker; use PHPStan\Analyser\Scope; +use PHPStan\Reflection\ExtendedMethodReflection; use PHPStan\Reflection\ParametersAcceptorSelector; use PHPStan\Rules\IdentifierRuleError; use PHPStan\Rules\Rule; @@ -18,6 +19,7 @@ use PHPStan\Type\Type; use PHPStan\Type\VerbosityLevel; use function array_diff; +use function array_filter; use function array_keys; use function array_map; use function array_pop; @@ -133,7 +135,7 @@ public function processNode(Node $node, Scope $scope): array if (!$hasUnknownKeys) { $errors = [...$errors, ...$this->checkUnsupportedKeys($itemsByKey, $lazyBuilder)]; } - return [...$errors, ...$this->checkCallbackReturnType($lazyBuilder, $scope)]; + return [...$errors, ...$this->checkCallback($lazyBuilder, $scope)]; } /** @@ -333,15 +335,18 @@ private function findUnsupportedKeys(array $itemsByKey): array } /** + * Checks the callback method's return type and parameters. + * * @param Scope&DependencyTracker $scope * @return list */ - private function checkCallbackReturnType(ArrayItem $lazyBuilder, Scope $scope): array + private function checkCallback(ArrayItem $lazyBuilder, Scope $scope): array { $callbackExpressions = $this->renderCallbackResolver->findCallbackExpressions(self::LAZY_BUILDER, $lazyBuilder->value); if ($callbackExpressions === null || count($callbackExpressions) === 0) { return []; } + $arguments = $this->findArguments($lazyBuilder, $scope); $errors = []; foreach ($this->renderCallbackResolver->resolveType($callbackExpressions[0], $scope)->getConstantArrays() as $callbackArray) { if (!$callbackArray->isCallable()->yes()) { @@ -354,22 +359,156 @@ private function checkCallbackReturnType(ArrayItem $lazyBuilder, Scope $scope): continue; } $method = $type->getMethod($methodName, $scope); - $returnType = ParametersAcceptorSelector::combineAcceptors($method->getVariants())->getReturnType(); - // A method that always throws never returns. - if (!$returnType->isArray()->no() || (new NeverType())->isSuperTypeOf($returnType)->yes()) { - continue; + $errors = [...$errors, ...$this->checkReturnType($lazyBuilder, $method)]; + if ($arguments !== null) { + $errors = [...$errors, ...$this->checkArguments($lazyBuilder, $method, $arguments)]; } - $errors[] = RuleErrorBuilder::message(sprintf( - '#lazy_builder callback %s::%s() returns %s, but it must return a render array.', - $method->getDeclaringClass()->getName(), - $method->getName(), - $returnType->describe(VerbosityLevel::typeOnly()) + } + } + return $errors; + } + + /** + * @return list + */ + private function checkReturnType(ArrayItem $lazyBuilder, ExtendedMethodReflection $method): array + { + $returnType = ParametersAcceptorSelector::combineAcceptors($method->getVariants())->getReturnType(); + // A method that always throws never returns. + if (!$returnType->isArray()->no() || (new NeverType())->isSuperTypeOf($returnType)->yes()) { + return []; + } + return [ + RuleErrorBuilder::message(sprintf( + '#lazy_builder callback %s() returns %s, but it must return a render array.', + $this->describeMethod($method), + $returnType->describe(VerbosityLevel::typeOnly()) + )) + ->line($lazyBuilder->getStartLine()) + ->identifier('lazyBuilder.nonArrayReturn') + ->build(), + ]; + } + + /** + * Finds the #lazy_builder arguments, in the order Drupal passes them. + * + * Drupal calls array_values() on the arguments, so string keys don't name + * parameters. Returns NULL when the arguments aren't one constant array. + * + * @return list|null + */ + private function findArguments(ArrayItem $lazyBuilder, Scope $scope): ?array + { + $constantArrays = $scope->getType($lazyBuilder->value)->getConstantArrays(); + if (count($constantArrays) !== 1) { + return null; + } + $argumentsOffset = new ConstantIntegerType(1); + if (!$constantArrays[0]->hasOffsetValueType($argumentsOffset)->yes()) { + return null; + } + $argumentArrays = $constantArrays[0]->getOffsetValueType($argumentsOffset)->getConstantArrays(); + if (count($argumentArrays) !== 1 || count($argumentArrays[0]->getOptionalKeys()) > 0) { + return null; + } + return array_values($argumentArrays[0]->getValueTypes()); + } + + /** + * Checks the #lazy_builder arguments against the callback's parameters. + * + * Drupal calls the callback with call_user_func_array() from a file that + * doesn't declare strict_types, so PHP coerces scalar arguments. Only + * native parameter types are checked, because they cause the TypeError. + * + * @see \Drupal\Core\Security\DoTrustedCallbackTrait::doTrustedCallback() + * + * @param list $arguments + * @return list + */ + private function checkArguments(ArrayItem $lazyBuilder, ExtendedMethodReflection $method, array $arguments): array + { + $variants = $method->getVariants(); + if (count($variants) !== 1) { + return []; + } + $parameters = $variants[0]->getParameters(); + $requiredCount = count(array_filter($parameters, static fn ($parameter) => !$parameter->isOptional())); + $lastParameter = $parameters[count($parameters) - 1] ?? null; + $variadicParameter = $lastParameter !== null && $lastParameter->isVariadic() ? $lastParameter : null; + // PHPStan also treats a method that calls func_get_args() as variadic. + $maxCount = $variants[0]->isVariadic() ? null : count($parameters); + $argumentCount = count($arguments); + + if ($argumentCount < $requiredCount) { + return [ + RuleErrorBuilder::message(sprintf( + '#lazy_builder callback %s() requires %s%s, but %s given. Drupal throws an ArgumentCountError when it renders this element.', + $this->describeMethod($method), + $requiredCount === $maxCount ? '' : 'at least ', + $this->describeArgumentCount($requiredCount), + $this->describeGivenCount($argumentCount) )) ->line($lazyBuilder->getStartLine()) - ->identifier('lazyBuilder.nonArrayReturn') - ->build(); + ->identifier('lazyBuilder.argumentCount') + ->build(), + ]; + } + + $errors = []; + if ($maxCount !== null && $argumentCount > $maxCount) { + $errors[] = RuleErrorBuilder::message(sprintf( + '#lazy_builder callback %s() accepts %s%s, but %s given. PHP ignores the extra arguments.', + $this->describeMethod($method), + $requiredCount === $maxCount ? '' : 'at most ', + $this->describeArgumentCount($maxCount), + $this->describeGivenCount($argumentCount) + )) + ->line($lazyBuilder->getStartLine()) + ->identifier('lazyBuilder.argumentCount') + ->build(); + } + + foreach ($arguments as $position => $argument) { + $parameter = $parameters[$position] ?? $variadicParameter; + // Non-scalar arguments are already reported. + if ($parameter === null || $this->isNonScalarArgument($argument)) { + continue; + } + $parameterType = $parameter->getNativeType(); + if (!$parameterType->accepts($argument->toCoercedArgumentType(false), false)->no()) { + continue; } + $verbosityLevel = VerbosityLevel::getRecommendedLevelByType($parameterType, $argument); + $errors[] = RuleErrorBuilder::message(sprintf( + 'Parameter #%d %s$%s of #lazy_builder callback %s() expects %s, %s given. Drupal throws a TypeError when it renders this element.', + $position + 1, + $parameter->isVariadic() ? '...' : '', + $parameter->getName(), + $this->describeMethod($method), + $parameterType->describe($verbosityLevel), + $argument->describe($verbosityLevel) + )) + ->line($lazyBuilder->getStartLine()) + ->identifier('lazyBuilder.argumentType') + ->build(); } return $errors; } + + private function describeMethod(ExtendedMethodReflection $method): string + { + return $method->getDeclaringClass()->getName() . '::' . $method->getName(); + } + + private function describeArgumentCount(int $count): string + { + return $count === 1 ? '1 argument' : sprintf('%d arguments', $count); + } + + private function describeGivenCount(int $count): string + { + return $count === 1 ? '1 is' : sprintf('%d are', $count); + } } diff --git a/src/Rules/Drupal/RenderCallbackRule.php b/src/Rules/Drupal/RenderCallbackRule.php index c8ebb26c..9ffc17bc 100644 --- a/src/Rules/Drupal/RenderCallbackRule.php +++ b/src/Rules/Drupal/RenderCallbackRule.php @@ -59,7 +59,6 @@ public function processNode(Node $node, Scope $scope): array return []; } - // @todo take the #lazy_builder arguments and validate parameters against the callback. $callbacks = $this->renderCallbackResolver->findCallbackExpressions($keyChecked, $node->value); if ($callbacks === null && $keyChecked === '#lazy_builder') { return [ diff --git a/tests/src/Rules/LazyBuilderRuleTest.php b/tests/src/Rules/LazyBuilderRuleTest.php index ae1f0f4e..087ecce9 100644 --- a/tests/src/Rules/LazyBuilderRuleTest.php +++ b/tests/src/Rules/LazyBuilderRuleTest.php @@ -45,6 +45,10 @@ public function testRule(): void 52, $argumentTip, ], + [ + '#lazy_builder callback LazyBuilder\Builder::build() accepts 1 argument, but 4 are given. PHP ignores the extra arguments.', + 52, + ], [ 'An element with #lazy_builder can only have #cache, #create_placeholder, #lazy_builder_preview, #placeholder_strategy_denylist, #preview and #weight next to it. Found: #title, child.', 55, @@ -69,6 +73,38 @@ public function testRule(): void 129, 'Return these properties and children from the #lazy_builder callback instead.', ], + [ + '#lazy_builder callback LazyBuilder\Builder::buildTwo() requires 2 arguments, but 1 is given. Drupal throws an ArgumentCountError when it renders this element.', + 170, + ], + [ + '#lazy_builder callback LazyBuilder\Builder::buildOptional() requires at least 1 argument, but 0 are given. Drupal throws an ArgumentCountError when it renders this element.', + 173, + ], + [ + '#lazy_builder callback LazyBuilder\Builder::build() accepts 1 argument, but 2 are given. PHP ignores the extra arguments.', + 176, + ], + [ + '#lazy_builder callback LazyBuilder\Builder::buildOptional() accepts at most 2 arguments, but 3 are given. PHP ignores the extra arguments.', + 179, + ], + [ + 'Parameter #1 $node_id of #lazy_builder callback LazyBuilder\Builder::buildTwo() expects int, string given. Drupal throws a TypeError when it renders this element.', + 182, + ], + [ + 'Parameter #1 $id of #lazy_builder callback LazyBuilder\Builder::build() expects int, null given. Drupal throws a TypeError when it renders this element.', + 185, + ], + [ + 'Parameter #3 ...$ids of #lazy_builder callback LazyBuilder\Builder::buildVariadic() expects int, string given. Drupal throws a TypeError when it renders this element.', + 188, + ], + [ + 'Parameter #1 $node_id of #lazy_builder callback LazyBuilder\Builder::buildTwo() expects int, string given. Drupal throws a TypeError when it renders this element.', + 191, + ], ]); } } diff --git a/tests/src/Rules/data/lazy-builder.php b/tests/src/Rules/data/lazy-builder.php index 57984ac2..22ecbefb 100644 --- a/tests/src/Rules/data/lazy-builder.php +++ b/tests/src/Rules/data/lazy-builder.php @@ -27,7 +27,7 @@ public static function buildString(int $id): string return ''; } - public static function buildUntyped($id) + public static function buildUntyped($id, $label = null, $weight = null, $enabled = null) { return []; } @@ -139,4 +139,95 @@ public function reviewCases(array $entities): array ], ]; } + + public static function buildTwo(int $node_id, string $view_mode): array + { + return []; + } + + public static function buildOptional(int $node_id, string $view_mode = 'full'): array + { + return []; + } + + public static function buildVariadic(int $node_id, int ...$ids): array + { + return []; + } + + /** + * @param positive-int $node_id + */ + public static function buildPhpDocType(int $node_id): array + { + return []; + } + + public function argumentErrors(): array + { + return [ + 'too_few' => [ + '#lazy_builder' => [static::class . '::buildTwo', [1]], + ], + 'too_few_with_optional' => [ + '#lazy_builder' => [static::class . '::buildOptional', []], + ], + 'too_many' => [ + '#lazy_builder' => [static::class . '::build', [1, 2]], + ], + 'too_many_with_optional' => [ + '#lazy_builder' => [static::class . '::buildOptional', [1, 'full', 3]], + ], + 'not_coercible' => [ + '#lazy_builder' => [static::class . '::buildTwo', ['teaser', 1]], + ], + 'null_for_int' => [ + '#lazy_builder' => [static::class . '::build', [null]], + ], + 'variadic_type' => [ + '#lazy_builder' => [static::class . '::buildVariadic', [1, 2, 'three']], + ], + 'string_keys' => [ + '#lazy_builder' => [static::class . '::buildTwo', ['view_mode' => 'teaser', 'node_id' => 1]], + ], + ]; + } + + public function validArguments(?int $maybeId, mixed $unknown): array + { + return [ + 'numeric_string' => [ + '#lazy_builder' => [static::class . '::build', ['5']], + ], + 'coerced_to_string' => [ + '#lazy_builder' => [static::class . '::buildTwo', [1, 2]], + ], + 'optional_omitted' => [ + '#lazy_builder' => [static::class . '::buildOptional', [1]], + ], + 'variadic_extra' => [ + '#lazy_builder' => [static::class . '::buildVariadic', [1, 2, 3]], + ], + 'string_keys_in_order' => [ + '#lazy_builder' => [static::class . '::buildTwo', ['node_id' => 1, 'view_mode' => 'teaser']], + ], + 'maybe_null' => [ + '#lazy_builder' => [static::class . '::build', [$maybeId]], + ], + 'mixed' => [ + '#lazy_builder' => [static::class . '::buildTwo', [$unknown, $unknown]], + ], + 'phpdoc_type_only' => [ + '#lazy_builder' => [static::class . '::buildPhpDocType', [0]], + ], + 'func_get_args' => [ + '#lazy_builder' => [static::class . '::buildFromAllArguments', [1, 2]], + ], + ]; + } + + public static function buildFromAllArguments(): array + { + return ['#markup' => implode(',', func_get_args())]; + } }