|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Shopware\PhpStan\Rule; |
| 6 | + |
| 7 | +use PhpParser\Node; |
| 8 | +use PhpParser\Node\Expr\MethodCall; |
| 9 | +use PHPStan\Analyser\Scope; |
| 10 | +use PHPStan\Rules\Rule; |
| 11 | +use PHPStan\Rules\RuleErrorBuilder; |
| 12 | +use PHPStan\Type\ObjectType; |
| 13 | +use Shopware\Core\Checkout\Payment\Cart\PaymentHandler\AbstractPaymentHandler; |
| 14 | +use Symfony\Component\HttpFoundation\Session\SessionInterface; |
| 15 | +use Symfony\Component\Routing\Annotation\Route as RouteAnnotation; |
| 16 | +use Symfony\Component\Routing\Attribute\Route as RouteAttribute; |
| 17 | + |
| 18 | +/** |
| 19 | + * @implements Rule<MethodCall> |
| 20 | + */ |
| 21 | +class NoSessionInPaymentHandlerAndStoreApiRule implements Rule |
| 22 | +{ |
| 23 | + public function getNodeType(): string |
| 24 | + { |
| 25 | + return MethodCall::class; |
| 26 | + } |
| 27 | + |
| 28 | + public function processNode(Node $node, Scope $scope): array |
| 29 | + { |
| 30 | + $type = $scope->getType($node->var); |
| 31 | + |
| 32 | + // @phpstan-ignore-next-line |
| 33 | + if (!$type instanceof ObjectType) { |
| 34 | + return []; |
| 35 | + } |
| 36 | + |
| 37 | + if (!$type->isInstanceOf(SessionInterface::class)->yes()) { |
| 38 | + return []; |
| 39 | + } |
| 40 | + |
| 41 | + $classReflection = $scope->getClassReflection(); |
| 42 | + |
| 43 | + if ($classReflection === null) { |
| 44 | + return []; |
| 45 | + } |
| 46 | + |
| 47 | + // Check if class extends AbstractPaymentHandler |
| 48 | + if ($classReflection->isSubclassOf(AbstractPaymentHandler::class)) { |
| 49 | + return [ |
| 50 | + RuleErrorBuilder::message('Session usage is not allowed in payment handlers.') |
| 51 | + ->identifier('shopware.sessionUsageInPaymentHandler') |
| 52 | + ->build(), |
| 53 | + ]; |
| 54 | + } |
| 55 | + |
| 56 | + // Check for Store-API route attribute |
| 57 | + $nativeReflection = $classReflection->getNativeReflection(); |
| 58 | + $attributes = array_merge( |
| 59 | + $nativeReflection->getAttributes(RouteAnnotation::class), |
| 60 | + $nativeReflection->getAttributes(RouteAttribute::class), |
| 61 | + ); |
| 62 | + |
| 63 | + foreach ($attributes as $attribute) { |
| 64 | + /** @var array{defaults?: array{_routeScope?: array<string>}} $args */ |
| 65 | + $args = $attribute->getArguments(); |
| 66 | + if (isset($args['defaults']['_routeScope']) && in_array('store-api', (array) $args['defaults']['_routeScope'], true)) { |
| 67 | + return [ |
| 68 | + RuleErrorBuilder::message('Session usage is not allowed in Store-API controllers.') |
| 69 | + ->identifier('shopware.sessionUsageInStoreApi') |
| 70 | + ->build(), |
| 71 | + ]; |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + return []; |
| 76 | + } |
| 77 | +} |
0 commit comments