Magento 2: Cleaning up Unused Dependencies
Question
Does anyone know of a code-cleaning/analysis tool that would inform a PHP Magento 2 programmer which DI arguments are not being used?
For example, a tool that would look at the following class
<?php
namespace Namespace\Module\Controller\V1;
class MyClass extends \Magento\Framework\App\Action\Action
{
protected $resultJsonFactory;
protected $metadataService;
protected $urlModel;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
\Namespace\Module\Helper\Api $apiHelper,
) {
parent::__construct($context);
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->metadataService = $metadataServiceInterface;
}
public function execute()
{
$result = $this->resultJsonFactory->create();
return $result->setData($items);
}
}
and tell us that
The class does not use the
$urlModel
propertyThe class only uses the
$metadataService
property when assigning in the constructor
Given how much of Magento programming involves "try this class, no, well maybe this class", I'm finding I leave behind giant constructors with dependencies I'm not longer uses. Having a tool to help clean this up would be great.
Solution
Regarding the urlModel
field, it is possible to get warning if its visibility set to private
and mess detector is configured in PHPStorm with dev/tests/static/testsuite/Magento/Test/Php/_files/phpmd/ruleset.xml
. Otherwise there is a chance that this property is used in child classes and mess detector does not check that.
Case with metadataService
is not covered, because it is initialized and thus considered as used. It is possible to quickly check every field in a class using 'Find usages' feature in PHP Storm, if there are no 'read' usages then most likely it can be safely removed.
General advice is to configure PHP MD and PHP CS (code sniffer) with the same configuration files which are used by Magento static tests, also it make sense to set severity to Error (so PHP Storm underlines mistakes with red wave line). For code sniffer it is located here dev/tests/static/testsuite/Magento/Test/Php/_files/phpcs/ruleset.xml