Skip to content

Rule: Add a new rule to check constructor for OM #48

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Extdn/Samples/Classes/ObjectManager.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Extdn\Samples\Classes;

use Magento\Framework\App\ObjectManager as CoreObjectManager;
use Magento\Framework\ObjectManagerInterface;

class ObjectManager
{
public function __construct(
ObjectManagerInterface $objectManager1,
CoreObjectManager $objectManager2
) {
}
}
16 changes: 16 additions & 0 deletions Extdn/Sniffs/Classes/ObjectManagerSniff.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Rule: Do not inject the Object Manager
## Background
The Object Manager should never be injected as a dependency into a class constructor. Injecting the Object Manager directly bypasses the DI mechanism that Magento makes flexible. Therefore, injecting the Object Manager in any kind of class is a code smell that leads to inflexibility.

## Reasoning
Whenever the Object Manager is directly injected into the constructor, it should be refactored into something else.

## How it works
This rule uses PHP Reflection to determine the constructor arguments of a parsed class. If one of the arguments contains the word `ObjectManager`, the rule gives a warning.

However, if the parsed class matches one of the following circumstances, the rule is bypassed:
- When the class has a namespace that contains `/Test/`, indicating a test-class;
- When the class has a name ending with `Factory`, `Proxy` or `Builder`;

## How to fix
If there is a match with this rule, the class constructor needs to be refactored so that dependencies are injected directly as a constructor argument, instead of via the Object Manager. Alternatively, this class needs to be created via a `Factory` class so that the `Factory` is able to use the Object Manager as needed.
93 changes: 93 additions & 0 deletions Extdn/Sniffs/Classes/ObjectManagerSniff.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php
/**
* Copyright © ExtDN. All rights reserved.
*/

declare(strict_types=1);

namespace Extdn\Sniffs\Classes;

use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use Extdn\Utils\Reflection;

/**
* Class ObjectManagerSniff
*
* @package Extdn\Sniffs\Classes
*/
class ObjectManagerSniff implements Sniff
{
/**
* @var string
*/
protected $message = 'The ObjectManager should not be injected into the constructor';

/**
* @inheritdoc
*/
public function register()
{
return [T_CLASS];
}

/**
* {@inheritdoc}
*/
public function process(File $phpcsFile, $stackPtr)
{
$className = Reflection::findClassName($phpcsFile);
if (empty($className)) {
return false;
}

// Make sure to load the file itself, so that autoloading can be skipped
include_once($phpcsFile->getFilename());

$dependencyClasses = Reflection::getClassDependencies($className);
foreach ($dependencyClasses as $dependencyClass) {
if ($this->isObjectManagerAllowedWithClass($className)) {
continue;
}

if (!$this->isInstanceOfObjectManager($dependencyClass->getName())) {
continue;
}

$warning = 'The dependency "\\' . $dependencyClass->getName() . '" is not allowed here.';
$phpcsFile->addWarning($warning, null, 'warning');
}
}

/**
* @param string $className
*
* @return bool
*/
private function isObjectManagerAllowedWithClass(string $className): bool
{
if (preg_match('/([a-zA-Z]+)(Factory|Builder)$/', $className)) {
return true;
}

if (preg_match('/Proxy$/', $className)) {
return true;
}

return false;
}

/**
* @param string $className
*
* @return bool
*/
private function isInstanceOfObjectManager(string $className): bool
{
if (strstr($className, 'ObjectManager')) {
return true;
}

return false;
}
}
13 changes: 13 additions & 0 deletions Extdn/Tests/Classes/ObjectManagerUnitTest.1.inc
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php
namespace Extdn\Samples\Classes;

use Magento\Framework\ObjectManager\ObjectManager;

class ObjectManagerUnitTest
{
public function __construct(
ObjectManager $objectManager
) {

}
}
42 changes: 42 additions & 0 deletions Extdn/Tests/Classes/ObjectManagerUnitTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php
/**
* Copyright © ExtDN. All rights reserved.
*/
declare(strict_types=1);

namespace Extdn\Tests\Classes;

use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest;

/**
* Class ObjectManagerUnitTest
*
* @package Extdn\Tests\Classes
*/
class ObjectManagerUnitTest extends AbstractSniffUnitTest
{
protected function setUp()
{
parent::setUp();
}

/**
* @inheritdoc
*/
public function getErrorList()
{
return [];
}

/**
* @inheritdoc
*/
public function getWarningList($testFile = '')
{
if ($testFile === 'ObjectManagerUnitTest.2.inc') {
return [];
}

return [1 => 1];
}
}
1 change: 1 addition & 0 deletions Extdn/ruleset.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@
</rule>
<rule ref="Extdn.Blocks.SetTemplateInBlock"/>
<rule ref="Extdn.Classes.StrictTypes"/>
<rule ref="Extdn.Classes.ObjectManager"/>
<rule ref="Extdn.Templates.TemplateObjectManager"/>
</ruleset>