Skip to content
79 changes: 79 additions & 0 deletions Magento2/Sniffs/Methods/DeprecatedModelMethodSniff.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<?php
/**
* Copyright © Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento2\Sniffs\Methods;

use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Util\Tokens;

/**
* Detects possible use of deprecated model methods.
*/
class DeprecatedModelMethodSniff implements Sniff
{
/**
* String representation of warning.
*
* @var string
*/
protected $warningMessage = "Possible use of the deprecated model method 'getResource()'" .
" to '%s' the data detected.";

/**
* Warning violation code.
*
* @var string
*/
protected $warningCode = 'FoundDeprecatedModelMethod';

/**
* List of deprecated method.
*
* @var array
*/
protected $methods = [
'save',
'load',
'delete'
];

protected $severity = 0;

/**
* @inheritdoc
*/
public function register()
{
return [
T_OBJECT_OPERATOR,
T_DOUBLE_COLON
];
}
/**
* @inheritdoc
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
$methodPosition = $phpcsFile->findNext(T_STRING, $stackPtr + 1);

if ($methodPosition !== false &&
in_array($tokens[$methodPosition]['content'], $this->methods)
) {
$resourcePosition = $phpcsFile->findPrevious([T_STRING, T_VARIABLE], $stackPtr - 1);
if ($resourcePosition !== false) {
$methodName = $tokens[$resourcePosition]['content'];
if ($methodName === "getResource") {
$phpcsFile->addWarning(
sprintf($this->warningMessage, $tokens[$methodPosition]['content']),
$stackPtr,
$this->warningCode
);
}
}
}
}
}
4 changes: 4 additions & 0 deletions Magento2/Tests/Methods/DeprecatedModelMethodUnitTest.inc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?php
$model->getResource()->save();
$model->getResource()->load();
$model->getResource()->delete();
31 changes: 31 additions & 0 deletions Magento2/Tests/Methods/DeprecatedModelMethodUnitTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php
/**
* Copyright © Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento2\Tests\Methods;

use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest;

class DeprecatedModelMethodUnitTest extends AbstractSniffUnitTest
{
/**
* @inheritdoc
*/
public function getErrorList()
{
return [];
}

/**
* @inheritdoc
*/
public function getWarningList()
{
return [
2 => 1,
3 => 1,
4 => 1
];
}
}
4 changes: 4 additions & 0 deletions Magento2/ruleset.xml
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,10 @@
<severity>8</severity>
<type>warning</type>
</rule>
<rule ref="Magento2.Methods.DeprecatedModelMethod">
<severity>8</severity>
<type>warning</type>
</rule>

<!-- Severity 7 warnings: General code issues. -->
<rule ref="Generic.Arrays.DisallowLongArraySyntax">
Expand Down