Magento2.4 – Sidebar\RemoveItem AfterExecute() Must Be an Instance of Magento\Framework\App\Response\Http

magento2.4plugin

I get this error:

TypeError: Argument 2 passed to
..\Plugin\Controller\Checkout\Sidebar\RemoveItemPlugin::afterExecute()
must be an instance of Magento\Framework\App\Response\Http, instance
of Magento\Framework\Controller\Result\Json\Interceptor given

It was working fine on Magento 2.3 but after the upgrade to 2.4, I get the above error. My code:

<?php
namespace Vendor\Vendor\Plugin\Controller\Checkout\Sidebar;

class RemoveItemPlugin
{
    public function afterExecute(
        \Magento\Checkout\Controller\Sidebar\RemoveItem $subject,
        \Magento\Framework\App\Response\Http $result
    ): \Magento\Framework\App\Response\Http {
        /* Do something */
    }
}

Best Answer

In scope of implementation Decomposition of Magento Controllers this controller refactored to returning instance of \Magento\Framework\Controller\Result\Json (which implements \Magento\Framework\Controller\ResultInterface).

Previously this controller used \Magento\Framework\App\Response\Http as return type of execute method.

Anyway, both types are correct according phpdoc of \Magento\Framework\App\ActionInterface::execute method.

/**
 * Execute action based on request and return result
 *
 * @return \Magento\Framework\Controller\ResultInterface|ResponseInterface
 * @throws \Magento\Framework\Exception\NotFoundException
 */
public function execute();

To fix this issue for 2.4 version, you should change type of $result argument to \Magento\Framework\Controller\ResultInterface. To have a fix, which will be compatible with two versions of magento (2.3 and 2.4), just skip defining type from method signature and check type of result using instance of inside of you plugin, if this is required for your case.