<?php

declare (strict_types=1);
namespace Rector\Symfony\Symfony51\Rector\Class_;

use PhpParser\Node;
use PhpParser\Node\Name\FullyQualified;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PHPStan\Type\ObjectType;
use Rector\Rector\AbstractRector;
use Rector\Symfony\Enum\SymfonyClass;
use Rector\Symfony\NodeFactory\GetSubscribedEventsClassMethodFactory;
use Rector\Symfony\NodeFactory\OnLogoutClassMethodFactory;
use Rector\Symfony\ValueObject\EventReferenceToMethodName;
use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample;
use Symplify\RuleDocGenerator\ValueObject\RuleDefinition;
/**
 * @changelog https://github.com/symfony/symfony/pull/36243
 *
 * @see \Rector\Symfony\Tests\Symfony51\Rector\Class_\LogoutHandlerToLogoutEventSubscriberRector\LogoutHandlerToLogoutEventSubscriberRectorTest
 */
final class LogoutHandlerToLogoutEventSubscriberRector extends AbstractRector
{
    /**
     * @readonly
     */
    private OnLogoutClassMethodFactory $onLogoutClassMethodFactory;
    /**
     * @readonly
     */
    private GetSubscribedEventsClassMethodFactory $getSubscribedEventsClassMethodFactory;
    /**
     * @readonly
     */
    private ObjectType $logoutHandlerObjectType;
    public function __construct(OnLogoutClassMethodFactory $onLogoutClassMethodFactory, GetSubscribedEventsClassMethodFactory $getSubscribedEventsClassMethodFactory)
    {
        $this->onLogoutClassMethodFactory = $onLogoutClassMethodFactory;
        $this->getSubscribedEventsClassMethodFactory = $getSubscribedEventsClassMethodFactory;
        $this->logoutHandlerObjectType = new ObjectType(SymfonyClass::LOGOUT_HANDLER_INTERFACE);
    }
    public function getRuleDefinition(): RuleDefinition
    {
        return new RuleDefinition('Change logout handler to an event listener that listens to LogoutEvent', [new CodeSample(<<<'CODE_SAMPLE'
use Symfony\Component\Security\Http\Logout\LogoutHandlerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;

final class SomeLogoutHandler implements LogoutHandlerInterface
{
    public function logout(Request $request, Response $response, TokenInterface $token)
    {
    }
}
CODE_SAMPLE
, <<<'CODE_SAMPLE'
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Http\Event\LogoutEvent;

final class SomeLogoutHandler implements EventSubscriberInterface
{
    public function onLogout(LogoutEvent $logoutEvent): void
    {
        $request = $logoutEvent->getRequest();
        $response = $logoutEvent->getResponse();
        $token = $logoutEvent->getToken();
    }

    /**
     * @return array<string, string[]>
     */
    public static function getSubscribedEvents(): array
    {
        return [
            LogoutEvent::class => ['onLogout'],
        ];
    }
}
CODE_SAMPLE
)]);
    }
    /**
     * @return array<class-string<Node>>
     */
    public function getNodeTypes(): array
    {
        return [Class_::class];
    }
    /**
     * @param Class_ $node
     */
    public function refactor(Node $node): ?Node
    {
        if (!$this->isObjectType($node, $this->logoutHandlerObjectType)) {
            return null;
        }
        // 1. replace LogoutHandlerInterface with EventSubscriberInterface
        foreach ($node->implements as $key => $implement) {
            if ($this->isName($implement, $this->logoutHandlerObjectType->getClassName())) {
                unset($node->implements[$key]);
            }
        }
        $node->implements[] = new FullyQualified(SymfonyClass::EVENT_SUBSCRIBER_INTERFACE);
        // 2. refactor logout() class method to onLogout()
        foreach ($node->stmts as $key => $classStmt) {
            if (!$classStmt instanceof ClassMethod) {
                continue;
            }
            if (!$this->isName($classStmt, 'logout')) {
                continue;
            }
            // replace logout() with onLogout() method
            $node->stmts[$key] = $this->onLogoutClassMethodFactory->createFromLogoutClassMethod($classStmt);
        }
        // 3. add getSubscribedEvents() class method
        $node->stmts[] = $this->createGetSubscribersClassMethod();
        return $node;
    }
    private function createGetSubscribersClassMethod(): ClassMethod
    {
        $classConstFetch = $this->nodeFactory->createClassConstReference(SymfonyClass::LOGOUT_EVENT);
        $eventReferencesToMethodNames = [new EventReferenceToMethodName($classConstFetch, 'onLogout')];
        return $this->getSubscribedEventsClassMethodFactory->create($eventReferencesToMethodNames);
    }
}
