Skip to content

AC-681: Create phpcs static check for PhtmlTemplateTest #306

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

Merged
merged 6 commits into from
Oct 6, 2021
Merged
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
148 changes: 148 additions & 0 deletions Magento2/Sniffs/Legacy/PhtmlTemplateSniff.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types = 1);

namespace Magento2\Sniffs\Legacy;

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

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add declare(strict_types = 1);

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done!

class PhtmlTemplateSniff implements Sniff
{
private const WARNING_CODE = 'PhtmlTemplateObsolete';

private const OBSOLETE_REGEX_IN_SPECIFIC_PHTML_TEMPLATES = [
'/(["\'])jquery\/ui\1/' => 'Please do not use "jquery/ui" library in templates. Use needed jquery ' .
'ui widget instead.',
'/data-mage-init=(?:\'|")(?!\s*{\s*"[^"]+")/' => 'Please do not initialize JS component in php. Do ' .
'it in template.',
'@x-magento-init.>(?!\s*+{\s*"[^"]+"\s*:\s*{\s*"[\w/-]+")@i' => 'Please do not initialize JS component ' .
'in php. Do it in template.',
];

/**
* @inheritdoc
*/
public function register(): array
{
return [
T_OBJECT_OPERATOR,
T_INLINE_HTML,
T_HEREDOC
];
}

/**
* @inheritdoc
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
if ($tokens[$stackPtr]['code'] === T_OBJECT_OPERATOR) {
$this->checkBlockVariable($phpcsFile, $stackPtr, $tokens);
$this->checkThisVariable($phpcsFile, $stackPtr, $tokens);
}
if ($tokens[$stackPtr]['code'] === T_INLINE_HTML || $tokens[$stackPtr]['code'] === T_HEREDOC) {
$this->checkHtml($phpcsFile, $stackPtr);

$file = $phpcsFile->getFilename();

if (strpos($file, '/view/frontend/templates/') !== false
|| strpos($file, '/view/base/templates/') !== false
) {
$this->checkHtmlSpecificFiles($phpcsFile, $stackPtr);
}
}
}

/**
* Check access to protected and private members of Block
*
* @param File $phpcsFile
* @param int $stackPtr
* @param array $tokens
*/
private function checkBlockVariable(File $phpcsFile, int $stackPtr, array $tokens): void
{
$varPos = $phpcsFile->findPrevious(T_VARIABLE, $stackPtr - 1);
if ($tokens[$varPos]['content'] !== '$block') {
return;
}
$stringPos = $phpcsFile->findNext(T_STRING, $stackPtr + 1);
if (strpos($tokens[$stringPos]['content'], '_') === 0) {
$phpcsFile->addWarning(
'Access to protected and private members of Block class is ' .
'obsolete in phtml templates. Use only public members.',
$stringPos,
self::WARNING_CODE
);
}
}

/**
* Check access to members and methods of Block class through $this
*
* @param File $phpcsFile
* @param int $stackPtr
* @param array $tokens
*/
private function checkThisVariable(File $phpcsFile, int $stackPtr, array $tokens): void
{
$varPos = $phpcsFile->findPrevious(T_VARIABLE, $stackPtr - 1);
if ($tokens[$varPos]['content'] !== '$this') {
return;
}
$stringPos = $phpcsFile->findNext(T_STRING, $stackPtr + 1);
if (strpos($tokens[$stringPos]['content'], 'helper') === false) {
$phpcsFile->addWarning(
'Access to members and methods of Block class through $this is ' .
'obsolete in phtml templates. Use only $block instead of $this.',
$stringPos,
self::WARNING_CODE
);
}
}

/**
* Check use of "text/javascript" type
*
* @param File $phpcsFile
* @param int $stackPtr
*/
private function checkHtml(File $phpcsFile, int $stackPtr): void
{
$content = $phpcsFile->getTokensAsString($stackPtr, 1);

if (preg_match('/type="text\/javascript"/', $content)) {
$phpcsFile->addWarning(
'Please do not use "text/javascript" type attribute.',
$stackPtr,
self::WARNING_CODE
);
}
}

/**
* Check of some obsoletes uses in specific files
*
* @param File $phpcsFile
* @param int $stackPtr
*/
private function checkHtmlSpecificFiles(File $phpcsFile, int $stackPtr): void
{
$content = $phpcsFile->getTokensAsString($stackPtr, 1);

foreach (self::OBSOLETE_REGEX_IN_SPECIFIC_PHTML_TEMPLATES as $obsoleteRegex => $errorMessage) {
if (preg_match($obsoleteRegex, $content)) {
$phpcsFile->addWarning(
$errorMessage,
$stackPtr,
self::WARNING_CODE
);
}
}
}
}
82 changes: 82 additions & 0 deletions Magento2/Tests/Legacy/PhtmlTemplateUnitTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento2\Tests\Legacy;

use DirectoryIterator;
use PHP_CodeSniffer\Tests\Standards\AbstractSniffUnitTest;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

class PhtmlTemplateUnitTest extends AbstractSniffUnitTest
{
/**
* @inheritdoc
*/
protected function getTestFiles($testFileBase): array
{
$testFiles = [];

$dir = __DIR__.'/_files/PhtmlTemplateUnitTest';
$di = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));

/**
* @var DirectoryIterator $file
*/
foreach ($di as $file) {
if ($file->isDir()) {
continue;
}
$path = $file->getPathname();
if ($path !== $testFileBase.'php' && substr($path, -5) !== 'fixed' && substr($path, -4) !== '.bak') {
$testFiles[] = $path;
}
}

// Put them in order.
sort($testFiles);

return $testFiles;
}

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

/**
* @inheritdoc
*/
public function getWarningList($testFile = '')
{
if ($testFile === 'PhtmlTemplateUnitTest.1.phtml' || $testFile === 'PhtmlTemplateUnitTest.2.phtml') {
return [
7 => 1,
9 => 1,
13 => 1,
20 => 1,
22 => 1,
23 => 1,
27 => 1,
33 => 1,
39 => 1
];
}
if ($testFile === 'PhtmlTemplateUnitTest.3.phtml')
{
return [
9 => 1,
20 => 1,
22 => 1,
23 => 1,
27 => 1,
];
}
return [];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
?>
<script type="text/x-magento-init">
</script>
<script type="text/javascript">
</script>
<div id="block-testing"
class="block shipping"
data-mage-init='{}'
>
<?php
function _testing()
{
return true;
}
$_productCollection = $block->_getTestFunction();
$block->getTestFunction();
$_something = $this->something();
$block->_getTest();
$block = _testing();
?>
<?php
$block->_getTestAnotherFunction();
?>

<?php $scriptString = <<<script
require([
"jquery",
"jquery/ui",
], function ($, Confirm) {
});
script;
$this->helper();
?>
<script type="jquery/ui">
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
?>
<script type="text/x-magento-init">
</script>
<script type="text/javascript">
</script>
<div id="block-testing"
class="block shipping"
data-mage-init='{}'
>
<?php
function _testing()
{
return true;
}
$_productCollection = $block->_getTestFunction();
$block->getTestFunction();
$_something = $this->something();
$block->_getTest();
$block = _testing();
?>
<?php
$block->_getTestAnotherFunction();
?>

<?php $scriptString = <<<script
require([
"jquery",
"jquery/ui",
], function ($, Confirm) {
});
script;
$this->helper();
?>
<script type="jquery/ui">
</script>
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
?>
<script type="text/x-magento-init">
</script>
<script type="text/javascript">
</script>
<div id="block-testing"
class="block shipping"
data-mage-init='{}'
>
<?php
function _testing()
{
return true;
}
$_productCollection = $block->_getTestFunction();
$block->getTestFunction();
$_something = $this->something();
$block->_getTest();
$block = _testing();
?>
<?php
$block->_getTestAnotherFunction();
?>

<?php $scriptString = <<<script
require([
"jquery",
"jquery/ui",
], function ($, Confirm) {
});
script;
$this->helper();
?>
<script type="jquery/ui">
</script>
5 changes: 5 additions & 0 deletions Magento2/ruleset.xml
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,11 @@
<severity>8</severity>
<type>warning</type>
</rule>
<rule ref="Magento2.Legacy.PhtmlTemplate">
<include-pattern>*\.phtml$</include-pattern>
<severity>8</severity>
<type>warning</type>
</rule>

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