diff --git a/app/code/Magento/Config/Observer/Config/Backend/Admin/AfterCustomUrlChangedObserver.php b/app/code/Magento/Config/Observer/Config/Backend/Admin/AfterCustomUrlChangedObserver.php index bf414890d0ed..830b6376c94b 100644 --- a/app/code/Magento/Config/Observer/Config/Backend/Admin/AfterCustomUrlChangedObserver.php +++ b/app/code/Magento/Config/Observer/Config/Backend/Admin/AfterCustomUrlChangedObserver.php @@ -3,10 +3,17 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Config\Observer\Config\Backend\Admin; use Magento\Framework\Event\ObserverInterface; +/** + * Class AfterCustomUrlChangedObserver redirects to new custom admin URL. + * + * @SuppressWarnings(PHPMD.CookieAndSessionMisuse) + */ class AfterCustomUrlChangedObserver implements ObserverInterface { /** @@ -56,7 +63,6 @@ public function __construct( * * @param \Magento\Framework\Event\Observer $observer * @return void - * @SuppressWarnings(PHPMD.ExitExpression) * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function execute(\Magento\Framework\Event\Observer $observer) @@ -68,6 +74,7 @@ public function execute(\Magento\Framework\Event\Observer $observer) $this->_authSession->destroy(); $adminUrl = $this->_backendData->getHomePageUrl(); $this->_response->setRedirect($adminUrl)->sendResponse(); + // phpcs:ignore Magento2.Security.LanguageConstruct.ExitUsage exit(0); } } diff --git a/app/code/Magento/Customer/Controller/Adminhtml/Index/Viewfile.php b/app/code/Magento/Customer/Controller/Adminhtml/Index/Viewfile.php index 20d330354bce..02a045086224 100644 --- a/app/code/Magento/Customer/Controller/Adminhtml/Index/Viewfile.php +++ b/app/code/Magento/Customer/Controller/Adminhtml/Index/Viewfile.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Customer\Controller\Adminhtml\Index; use Magento\Customer\Api\AccountManagementInterface; @@ -17,7 +19,10 @@ use Magento\Framework\DataObjectFactory; /** + * Class Viewfile serves to show file or image by file/image name provided in request parameters. + * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + * @SuppressWarnings(PHPMD.AllPurposeAction) */ class Viewfile extends \Magento\Customer\Controller\Adminhtml\Index { @@ -127,8 +132,6 @@ public function __construct( * * @return \Magento\Framework\Controller\ResultInterface|void * @throws NotFoundException - * - * @SuppressWarnings(PHPMD.ExitExpression) */ public function execute() { @@ -146,6 +149,7 @@ public function execute() } if ($plain) { + // phpcs:ignore Magento2.Functions.DiscouragedFunction $extension = pathinfo($path, PATHINFO_EXTENSION); switch (strtolower($extension)) { case 'gif': @@ -175,6 +179,7 @@ public function execute() $resultRaw->setContents($directory->readFile($fileName)); return $resultRaw; } else { + // phpcs:ignore Magento2.Functions.DiscouragedFunction $name = pathinfo($path, PATHINFO_BASENAME); $this->_fileFactory->create( $name, diff --git a/app/code/Magento/Deploy/Process/Queue.php b/app/code/Magento/Deploy/Process/Queue.php index c4c31b8ff77b..fd7aad44e0a5 100644 --- a/app/code/Magento/Deploy/Process/Queue.php +++ b/app/code/Magento/Deploy/Process/Queue.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Deploy\Process; use Magento\Deploy\Package\Package; @@ -125,6 +127,8 @@ public function __construct( } /** + * Adds deployment package. + * * @param Package $package * @param Package[] $dependencies * @return bool true on success @@ -140,6 +144,8 @@ public function add(Package $package, array $dependencies = []) } /** + * Returns packages array. + * * @return Package[] */ public function getPackages() @@ -162,6 +168,7 @@ public function process() $this->assertAndExecute($name, $packages, $packageJob); } $this->logger->info('.'); + // phpcs:ignore Magento2.Functions.DiscouragedFunction sleep(3); foreach ($this->inProgress as $name => $package) { if ($this->isDeployed($package)) { @@ -209,6 +216,8 @@ private function assertAndExecute($name, array & $packages, array $packageJob) } /** + * Executes deployment package. + * * @param Package $package * @param string $name * @param array $packages @@ -244,6 +253,7 @@ private function awaitForAllProcesses() } } $this->logger->info('.'); + // phpcs:ignore Magento2.Functions.DiscouragedFunction sleep(5); } if ($this->isCanBeParalleled()) { @@ -253,6 +263,8 @@ private function awaitForAllProcesses() } /** + * Checks if can be parallel. + * * @return bool */ private function isCanBeParalleled() @@ -261,9 +273,11 @@ private function isCanBeParalleled() } /** + * Executes the process. + * * @param Package $package * @return bool true on success for main process and exit for child process - * @SuppressWarnings(PHPMD.ExitExpression) + * @throws \RuntimeException */ private function execute(Package $package) { @@ -291,6 +305,7 @@ function () use ($package) { ); if ($this->isCanBeParalleled()) { + // phpcs:ignore Magento2.Functions.DiscouragedFunction $pid = pcntl_fork(); if ($pid === -1) { throw new \RuntimeException('Unable to fork a new process'); @@ -305,6 +320,7 @@ function () use ($package) { // process child process $this->inProgress = []; $this->deployPackageService->deploy($package, $this->options, true); + // phpcs:ignore Magento2.Security.LanguageConstruct.ExitUsage exit(0); } else { $this->deployPackageService->deploy($package, $this->options); @@ -313,6 +329,8 @@ function () use ($package) { } /** + * Checks if package is deployed. + * * @param Package $package * @return bool */ @@ -320,11 +338,13 @@ private function isDeployed(Package $package) { if ($this->isCanBeParalleled()) { if ($package->getState() === null) { + // phpcs:ignore Magento2.Functions.DiscouragedFunction $pid = pcntl_waitpid($this->getPid($package), $status, WNOHANG); if ($pid === $this->getPid($package)) { $package->setState(Package::STATE_COMPLETED); unset($this->inProgress[$package->getPath()]); + // phpcs:ignore Magento2.Functions.DiscouragedFunction return pcntl_wexitstatus($status) === 0; } return false; @@ -334,17 +354,19 @@ private function isDeployed(Package $package) } /** + * Returns process ID or null if not found. + * * @param Package $package * @return int|null */ private function getPid(Package $package) { - return isset($this->processIds[$package->getPath()]) - ? $this->processIds[$package->getPath()] - : null; + return isset($this->processIds[$package->getPath()]) ?? null; } /** + * Checks timeout. + * * @return bool */ private function checkTimeout() @@ -357,11 +379,13 @@ private function checkTimeout() * * Protect against zombie process * + * @throws \RuntimeException * @return void */ public function __destruct() { foreach ($this->inProgress as $package) { + // phpcs:ignore Magento2.Functions.DiscouragedFunction if (pcntl_waitpid($this->getPid($package), $status) === -1) { throw new \RuntimeException( 'Error while waiting for package deployed: ' . $this->getPid($package) . '; Status: ' . $status diff --git a/app/code/Magento/Downloadable/Controller/Download/Link.php b/app/code/Magento/Downloadable/Controller/Download/Link.php index 765546d080e5..4766f1699afb 100644 --- a/app/code/Magento/Downloadable/Controller/Download/Link.php +++ b/app/code/Magento/Downloadable/Controller/Download/Link.php @@ -1,15 +1,21 @@ setStatus(PurchasedLink::LINK_STATUS_EXPIRED); } $linkPurchasedItem->save(); + // phpcs:ignore Magento2.Security.LanguageConstruct.ExitUsage exit(0); } catch (\Exception $e) { $this->messageManager->addError(__('Something went wrong while getting the requested content.')); diff --git a/app/code/Magento/Downloadable/Controller/Download/LinkSample.php b/app/code/Magento/Downloadable/Controller/Download/LinkSample.php index 76ec791611c9..f40df744dd3e 100644 --- a/app/code/Magento/Downloadable/Controller/Download/LinkSample.php +++ b/app/code/Magento/Downloadable/Controller/Download/LinkSample.php @@ -1,21 +1,26 @@ _processDownload($resource, $resourceType); + // phpcs:ignore Magento2.Security.LanguageConstruct.ExitUsage exit(0); } catch (\Exception $e) { $this->messageManager->addError( diff --git a/app/code/Magento/Downloadable/Controller/Download/Sample.php b/app/code/Magento/Downloadable/Controller/Download/Sample.php index 4a4f88d81b37..ac9eeac678f8 100644 --- a/app/code/Magento/Downloadable/Controller/Download/Sample.php +++ b/app/code/Magento/Downloadable/Controller/Download/Sample.php @@ -1,21 +1,26 @@ _processDownload($resource, $resourceType); + // phpcs:ignore Magento2.Security.LanguageConstruct.ExitUsage exit(0); } catch (\Exception $e) { $this->messageManager->addError( diff --git a/app/code/Magento/Indexer/Model/ProcessManager.php b/app/code/Magento/Indexer/Model/ProcessManager.php index 04cd713fffb1..2f2c500e028c 100644 --- a/app/code/Magento/Indexer/Model/ProcessManager.php +++ b/app/code/Magento/Indexer/Model/ProcessManager.php @@ -71,6 +71,7 @@ public function execute($userFunctions) private function simpleThreadExecute($userFunctions) { foreach ($userFunctions as $userFunction) { + // phpcs:ignore Magento2.Functions.DiscouragedFunction call_user_func($userFunction); } } @@ -79,6 +80,7 @@ private function simpleThreadExecute($userFunctions) * Execute user functions in multiThreads mode * * @param \Traversable $userFunctions + * @throws \RuntimeException * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ private function multiThreadsExecute($userFunctions) @@ -86,6 +88,7 @@ private function multiThreadsExecute($userFunctions) $this->resource->closeConnection(null); $threadNumber = 0; foreach ($userFunctions as $userFunction) { + // phpcs:ignore Magento2.Functions.DiscouragedFunction $pid = pcntl_fork(); if ($pid == -1) { throw new \RuntimeException('Unable to fork a new process'); @@ -95,6 +98,7 @@ private function multiThreadsExecute($userFunctions) $this->startChildProcess($userFunction); } } + // phpcs:ignore Magento2.CodeAnalysis.EmptyBlock,Magento2.Functions.DiscouragedFunction while (pcntl_waitpid(0, $status) != -1) { //Waiting for the completion of child processes } @@ -128,12 +132,13 @@ private function isSetupMode(): bool * Start child process * * @param callable $userFunction - * @SuppressWarnings(PHPMD.ExitExpression) */ private function startChildProcess(callable $userFunction) { + // phpcs:ignore Magento2.Functions.DiscouragedFunction $status = call_user_func($userFunction); - $status = is_integer($status) ? $status : 0; + $status = is_int($status) ? $status : 0; + // phpcs:ignore Magento2.Security.LanguageConstruct.ExitUsage exit($status); } @@ -146,8 +151,10 @@ private function executeParentProcess(int &$threadNumber) { $threadNumber++; if ($threadNumber >= $this->threadsCount) { + // phpcs:disable Magento2.Functions.DiscouragedFunction pcntl_wait($status); if (pcntl_wexitstatus($status) !== 0) { + // phpcs:enable $this->failInChildProcess = true; } $threadNumber--; diff --git a/app/code/Magento/MessageQueue/Model/CallbackInvoker.php b/app/code/Magento/MessageQueue/Model/CallbackInvoker.php index f37f2157c357..f6305363fc1a 100644 --- a/app/code/Magento/MessageQueue/Model/CallbackInvoker.php +++ b/app/code/Magento/MessageQueue/Model/CallbackInvoker.php @@ -46,7 +46,6 @@ public function __construct( /** * @inheritdoc - * @SuppressWarnings(PHPMD.ExitExpression) */ public function invoke(QueueInterface $queue, $maxNumberOfMessages, $callback) { @@ -54,9 +53,11 @@ public function invoke(QueueInterface $queue, $maxNumberOfMessages, $callback) for ($i = $maxNumberOfMessages; $i > 0; $i--) { do { $message = $queue->dequeue(); + // phpcs:ignore Magento2.Functions.DiscouragedFunction } while ($message === null && (sleep(1) === 0)); if (false === $this->poisonPillCompare->isLatestVersion($this->poisonPillVersion)) { $queue->reject($message); + // phpcs:ignore Magento2.Security.LanguageConstruct.ExitUsage exit(0); } $callback($message); diff --git a/app/code/Magento/Paypal/Controller/Ipn/Index.php b/app/code/Magento/Paypal/Controller/Ipn/Index.php index 4bcc3a9b3606..a879266bc191 100644 --- a/app/code/Magento/Paypal/Controller/Ipn/Index.php +++ b/app/code/Magento/Paypal/Controller/Ipn/Index.php @@ -4,6 +4,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Paypal\Controller\Ipn; @@ -16,6 +17,8 @@ /** * Unified IPN controller for all supported PayPal methods + * + * @SuppressWarnings(PHPMD.AllPurposeAction) */ class Index extends \Magento\Framework\App\Action\Action implements CsrfAwareActionInterface { @@ -73,7 +76,6 @@ public function validateForCsrf(RequestInterface $request): ?bool * Instantiate IPN model and pass IPN request to it * * @return void - * @SuppressWarnings(PHPMD.ExitExpression) */ public function execute() { @@ -95,6 +97,7 @@ public function execute() $this->_logger->critical($e); $this->getResponse()->setStatusHeader(503, '1.1', 'Service Unavailable')->sendResponse(); /** @todo eliminate usage of exit statement */ + // phpcs:ignore Magento2.Security.LanguageConstruct.ExitUsage exit; } catch (\Exception $e) { $this->_logger->critical($e); diff --git a/app/code/Magento/Sales/Controller/Download/DownloadCustomOption.php b/app/code/Magento/Sales/Controller/Download/DownloadCustomOption.php index d30839e96dcc..fc4e238d47c9 100644 --- a/app/code/Magento/Sales/Controller/Download/DownloadCustomOption.php +++ b/app/code/Magento/Sales/Controller/Download/DownloadCustomOption.php @@ -4,6 +4,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Sales\Controller\Download; @@ -121,10 +122,10 @@ public function execute() * Ends execution process * * @return void - * @SuppressWarnings(PHPMD.ExitExpression) */ protected function endExecute() { + // phpcs:ignore Magento2.Security.LanguageConstruct.ExitUsage exit(0); } } diff --git a/app/code/Magento/Wishlist/Controller/Index/DownloadCustomOption.php b/app/code/Magento/Wishlist/Controller/Index/DownloadCustomOption.php index b87afa8e5d0c..742b2a91e931 100644 --- a/app/code/Magento/Wishlist/Controller/Index/DownloadCustomOption.php +++ b/app/code/Magento/Wishlist/Controller/Index/DownloadCustomOption.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Wishlist\Controller\Index; use Magento\Framework\App\Action; @@ -51,7 +53,6 @@ public function __construct( * * @return \Magento\Framework\Controller\Result\Forward * @SuppressWarnings(PHPMD.CyclomaticComplexity) - * @SuppressWarnings(PHPMD.ExitExpression) */ public function execute() { diff --git a/composer.json b/composer.json index 50b22238e0d0..aa4976aa50a9 100644 --- a/composer.json +++ b/composer.json @@ -82,15 +82,16 @@ "zendframework/zend-view": "~2.10.0" }, "require-dev": { + "allure-framework/allure-phpunit": "~1.2.0", "friendsofphp/php-cs-fixer": "~2.13.0", "lusitanian/oauth": "~0.8.10", + "magento/magento-coding-standard": "~1.0.0", "magento/magento2-functional-testing-framework": "~2.3.14", "pdepend/pdepend": "2.5.2", "phpmd/phpmd": "@stable", "phpunit/phpunit": "~6.5.0", "sebastian/phpcpd": "~3.0.0", - "squizlabs/php_codesniffer": "3.3.1", - "allure-framework/allure-phpunit": "~1.2.0" + "squizlabs/php_codesniffer": "3.3.1" }, "suggest": { "ext-pcntl": "Need for run processes in parallel mode" diff --git a/composer.lock b/composer.lock index a7131f4a16ee..e2d00ad07c79 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "60007664938710edf52eadddd7551867", + "content-hash": "825a03a040f3eff4ea6ea537b7530f15", "packages": [ { "name": "braintree/braintree_php", @@ -6618,6 +6618,36 @@ ], "time": "2018-02-14T22:37:14+00:00" }, + { + "name": "magento/magento-coding-standard", + "version": "1.0.0", + "source": { + "type": "git", + "url": "https://github.com/magento/magento-coding-standard.git", + "reference": "b79055fdd16e0657c95ee214ebb81466c5f08745" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/magento/magento-coding-standard/zipball/b79055fdd16e0657c95ee214ebb81466c5f08745", + "reference": "b79055fdd16e0657c95ee214ebb81466c5f08745", + "shasum": "" + }, + "require": { + "php": ">=5.6.0", + "squizlabs/php_codesniffer": "~3.3.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0" + }, + "type": "phpcodesniffer-standard", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "description": "A set of Magento specific PHP CodeSniffer rules.", + "time": "2019-03-27T14:17:16+00:00" + }, { "name": "magento/magento2-functional-testing-framework", "version": "2.3.14", diff --git a/dev/tests/functional/lib/Magento/Mtf/EntryPoint/EntryPoint.php b/dev/tests/functional/lib/Magento/Mtf/EntryPoint/EntryPoint.php index 745f97b9b43f..836cc486cb0f 100644 --- a/dev/tests/functional/lib/Magento/Mtf/EntryPoint/EntryPoint.php +++ b/dev/tests/functional/lib/Magento/Mtf/EntryPoint/EntryPoint.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Mtf\EntryPoint; @@ -10,8 +11,8 @@ /** * Class EntryPoint - * Application entry point, used to bootstrap and run application * + * Application entry point, used to bootstrap and run application */ class EntryPoint { @@ -36,7 +37,6 @@ class EntryPoint * @param string $rootDir * @param array $parameters * @param ObjectManager $objectManager - * @SuppressWarnings(PHPMD.ExitExpression) */ public function __construct( $rootDir, @@ -51,7 +51,7 @@ public function __construct( /** * Run a Mtf application * - * @param $applicationName + * @param string $applicationName * @param array $arguments * @return mixed * @throws \DomainException diff --git a/dev/tests/integration/testsuite/Magento/Framework/Code/GeneratorTest/ParentClassWithNamespace.php b/dev/tests/integration/testsuite/Magento/Framework/Code/GeneratorTest/ParentClassWithNamespace.php index e42a79aa5259..01e63126e5cd 100644 --- a/dev/tests/integration/testsuite/Magento/Framework/Code/GeneratorTest/ParentClassWithNamespace.php +++ b/dev/tests/integration/testsuite/Magento/Framework/Code/GeneratorTest/ParentClassWithNamespace.php @@ -7,6 +7,9 @@ use Zend\Code\Generator\DocBlockGenerator; +/** + * phpcs:ignoreFile + */ class ParentClassWithNamespace { /** @@ -78,9 +81,6 @@ public static function publicParentStatic() { } - /** - * @SuppressWarnings(PHPMD.FinalImplementation) Suppressed as is a fixture but not a real code - */ final public function publicParentFinal() { } diff --git a/dev/tests/integration/testsuite/Magento/Framework/Code/GeneratorTest/SourceClassWithNamespace.php b/dev/tests/integration/testsuite/Magento/Framework/Code/GeneratorTest/SourceClassWithNamespace.php index e5bce7c52db7..b9fc351ff64e 100644 --- a/dev/tests/integration/testsuite/Magento/Framework/Code/GeneratorTest/SourceClassWithNamespace.php +++ b/dev/tests/integration/testsuite/Magento/Framework/Code/GeneratorTest/SourceClassWithNamespace.php @@ -8,7 +8,7 @@ use Zend\Code\Generator\ClassGenerator; /** - * Class SourceClassWithNamespace + * phpcs:ignoreFile */ class SourceClassWithNamespace extends ParentClassWithNamespace { @@ -115,8 +115,6 @@ public static function publicChildStatic() /** * Test method - * - * @SuppressWarnings(PHPMD.FinalImplementation) Suppressed as is a fixture but not a real code */ final public function publicChildFinal() { diff --git a/dev/tests/integration/testsuite/Magento/Framework/Interception/Fixture/Intercepted.php b/dev/tests/integration/testsuite/Magento/Framework/Interception/Fixture/Intercepted.php index 0a75aba5c9c4..a35596cf0f90 100644 --- a/dev/tests/integration/testsuite/Magento/Framework/Interception/Fixture/Intercepted.php +++ b/dev/tests/integration/testsuite/Magento/Framework/Interception/Fixture/Intercepted.php @@ -8,7 +8,7 @@ namespace Magento\Framework\Interception\Fixture; /** - * @codingStandardsIgnoreStart + * phpcs:ignoreFile */ class Intercepted extends InterceptedParent implements InterceptedInterface { @@ -49,7 +49,6 @@ public function D($param1) /** * @SuppressWarnings(PHPMD.ShortMethodName) - * @SuppressWarnings(PHPMD.FinalImplementation) Suppressed as is a fixture but not a real code */ final public function E($param1) { diff --git a/dev/tests/static/framework/Magento/CodeMessDetector/Rule/Design/FinalImplementation.php b/dev/tests/static/framework/Magento/CodeMessDetector/Rule/Design/FinalImplementation.php deleted file mode 100644 index 22c008b05806..000000000000 --- a/dev/tests/static/framework/Magento/CodeMessDetector/Rule/Design/FinalImplementation.php +++ /dev/null @@ -1,29 +0,0 @@ -isFinal()) { - $this->addViolation($node, [$node->getType(), $node->getFullQualifiedName()]); - } - } -} diff --git a/dev/tests/static/framework/Magento/CodeMessDetector/Test/Unit/Rule/Design/FinalImplementationTest.php b/dev/tests/static/framework/Magento/CodeMessDetector/Test/Unit/Rule/Design/FinalImplementationTest.php deleted file mode 100644 index ca944b5c60e1..000000000000 --- a/dev/tests/static/framework/Magento/CodeMessDetector/Test/Unit/Rule/Design/FinalImplementationTest.php +++ /dev/null @@ -1,128 +0,0 @@ -createFinalizableNodeMock($nodeType); - $finalizableNode->method('isFinal')->willReturn(false); - - $rule = new FinalImplementation(); - $this->expectsRuleViolation($rule, $this->never()); - $rule->apply($finalizableNode); - } - - /** - * @param string $nodeType - * - * @dataProvider finalizableNodeTypesProvider - */ - public function testRuleAppliesToFinalFinalizable($nodeType) - { - $finalizableNode = $this->createFinalizableNodeMock($nodeType); - $finalizableNode->method('isFinal')->willReturn(true); - - $rule = new FinalImplementation(); - $this->expectsRuleViolation($rule, $this->once()); - $rule->apply($finalizableNode); - } - - /** - * @param string $nodeType - * - * @dataProvider finalizableNodeTypesProvider - */ - public function testRuleVerifiesFinalizableNodes($nodeType) - { - $finalizableNode = $this->createFinalizableNodeMock($nodeType); - - $finalizableNode->expects($this->atLeastOnce()) - ->method('isFinal'); - - $rule = new FinalImplementation(); - $rule->apply($finalizableNode); - } - - /** - * @expectedException BadMethodCallException - */ - public function testRuleFailsOnNotFinalizableNodes() - { - $someNode = $this->getMockBuilder(AbstractNode::class) - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - - $rule = new FinalImplementation(); - $rule->apply($someNode); - } - - /** - * "final" keyword may be applied only to classes and methods - * - * @return array - */ - public function finalizableNodeTypesProvider() - { - return [ - [ClassNode::class], - [MethodNode::class], - ]; - } - - /** - * If node is finalizable it has "isFinal" magic PHP method - * - * @param string $nodeType - * @return ClassNode|MethodNode|MockObject - */ - private function createFinalizableNodeMock($nodeType) - { - $finalizableNode = $this->getMockBuilder($nodeType) - ->disableOriginalConstructor() - ->disableProxyingToOriginalMethods() - ->setMethods([ - 'isFinal', - // disable name lookup from AST artifact - 'getNamespaceName', - 'getParentName', - 'getName', - ]) - ->getMock(); - return $finalizableNode; - } - - /** - * @param FinalImplementation $rule - * @param InvokedRecorder $violationExpectation - * @return InvocationMocker - */ - private function expectsRuleViolation(FinalImplementation $rule, InvokedRecorder $violationExpectation) - { - $report = $this->getMockBuilder(Report::class)->getMock(); - $invokation = $report->expects($violationExpectation)->method('addRuleViolation'); - $rule->setReport($report); - return $invokation; - } -} diff --git a/dev/tests/static/framework/Magento/CodeMessDetector/resources/rulesets/design.xml b/dev/tests/static/framework/Magento/CodeMessDetector/resources/rulesets/design.xml index 73354c46d76b..53f2fe4a0084 100644 --- a/dev/tests/static/framework/Magento/CodeMessDetector/resources/rulesets/design.xml +++ b/dev/tests/static/framework/Magento/CodeMessDetector/resources/rulesets/design.xml @@ -10,29 +10,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pmd.sf.net/ruleset/1.0.0 http://pmd.sf.net/ruleset_xml_schema.xsd" xsi:noNamespaceSchemaLocation="http://pmd.sf.net/ruleset_xml_schema.xsd"> - - - - - 1 - - - - - diff --git a/dev/tests/static/framework/Magento/Sniffs/Arrays/ShortArraySyntaxSniff.php b/dev/tests/static/framework/Magento/Sniffs/Arrays/ShortArraySyntaxSniff.php deleted file mode 100644 index 5ce1ac333cc1..000000000000 --- a/dev/tests/static/framework/Magento/Sniffs/Arrays/ShortArraySyntaxSniff.php +++ /dev/null @@ -1,35 +0,0 @@ -addError( - 'Short array syntax must be used; expected "[]" but found "array()"', - $stackPtr, - 'ShortArraySyntax' - ); - } -} diff --git a/dev/tests/static/framework/Magento/Sniffs/EchoTags/ShortEchoSyntaxSniff.php b/dev/tests/static/framework/Magento/Sniffs/EchoTags/ShortEchoSyntaxSniff.php deleted file mode 100644 index 9d0d58950c4f..000000000000 --- a/dev/tests/static/framework/Magento/Sniffs/EchoTags/ShortEchoSyntaxSniff.php +++ /dev/null @@ -1,47 +0,0 @@ -getTokens(); - $openTag = $tokens[$stackPtr]; - - // HHVM Will classify findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true); - if ($tokens[$nextToken]['code'] == T_ECHO) { - $phpcsFile->addError( - 'Short echo tag syntax must be used; expected "previousLineContent) !== 0; - $this->previousLineContent = $lineContent; - if (! $currentLineMatch && !$previousLineMatch) { - parent::checkLineLength($phpcsFile, $stackPtr, $lineContent); - } - } -} diff --git a/dev/tests/static/framework/Magento/Sniffs/Functions/OutputBufferingSniff.php b/dev/tests/static/framework/Magento/Sniffs/Functions/OutputBufferingSniff.php deleted file mode 100644 index d2bf2de418c2..000000000000 --- a/dev/tests/static/framework/Magento/Sniffs/Functions/OutputBufferingSniff.php +++ /dev/null @@ -1,31 +0,0 @@ - null]; - - /** - * @inheritdoc - */ - protected function addError($phpcsFile, $stackPtr, $function, $pattern = null) - { - $data = [$function]; - $error = 'The usage of %s() is forbidden'; - $type = 'Found'; - - if ($this->error === true) { - $phpcsFile->addError($error, $stackPtr, $type, $data); - } else { - $phpcsFile->addWarning($error, $stackPtr, $type, $data); - } - } -} diff --git a/dev/tests/static/framework/Magento/Sniffs/LanguageConstructs/LanguageConstructsSniff.php b/dev/tests/static/framework/Magento/Sniffs/LanguageConstructs/LanguageConstructsSniff.php deleted file mode 100644 index 575b39542311..000000000000 --- a/dev/tests/static/framework/Magento/Sniffs/LanguageConstructs/LanguageConstructsSniff.php +++ /dev/null @@ -1,77 +0,0 @@ -getTokens(); - if ($tokens[$stackPtr]['code'] === T_BACKTICK) { - if ($phpcsFile->findNext(T_BACKTICK, $stackPtr + 1)) { - return; - } - $phpcsFile->addError($this->errorMessageBacktick, $stackPtr, $this->backtickCode); - return; - } - $phpcsFile->addError($this->errorMessage, $stackPtr, $this->directOutput, [$tokens[$stackPtr]['content']]); - } -} diff --git a/dev/tests/static/framework/Magento/Sniffs/LiteralNamespaces/LiteralNamespacesSniff.php b/dev/tests/static/framework/Magento/Sniffs/LiteralNamespaces/LiteralNamespacesSniff.php deleted file mode 100644 index b6af3f37cf11..000000000000 --- a/dev/tests/static/framework/Magento/Sniffs/LiteralNamespaces/LiteralNamespacesSniff.php +++ /dev/null @@ -1,75 +0,0 @@ -getTokens(); - if ($sourceFile->findPrevious(T_STRING_CONCAT, $stackPtr, $stackPtr - 3) || - $sourceFile->findNext(T_STRING_CONCAT, $stackPtr, $stackPtr + 3) - ) { - return; - } - - $content = trim($tokens[$stackPtr]['content'], "\"'"); - // replace double slashes from class name for avoiding problems with class autoload - if (strpos($content, '\\') !== false) { - $content = preg_replace('|\\\{2,}|', '\\', $content); - } - - if (preg_match($this->literalNamespacePattern, $content) === 1 && $this->classExists($content)) { - $sourceFile->addError( - "Use ::class notation instead.", - $stackPtr, - 'LiteralClassUsage' - ); - } - } - - /** - * @param string $className - * @return bool - */ - private function classExists($className) - { - if (!isset($this->classNames[$className])) { - $this->classNames[$className] = class_exists($className) || interface_exists($className); - } - return $this->classNames[$className]; - } -} diff --git a/dev/tests/static/framework/Magento/Sniffs/MicroOptimizations/IsNullSniff.php b/dev/tests/static/framework/Magento/Sniffs/MicroOptimizations/IsNullSniff.php deleted file mode 100644 index 928fc3a0defd..000000000000 --- a/dev/tests/static/framework/Magento/Sniffs/MicroOptimizations/IsNullSniff.php +++ /dev/null @@ -1,40 +0,0 @@ -getTokens(); - if ($tokens[$stackPtr]['content'] === $this->blacklist) { - $sourceFile->addError( - "is_null must be avoided. Use strict comparison instead.", - $stackPtr, - 'IsNullUsage' - ); - } - } -} diff --git a/dev/tests/static/framework/Magento/Sniffs/NamingConventions/InterfaceNameSniff.php b/dev/tests/static/framework/Magento/Sniffs/NamingConventions/InterfaceNameSniff.php deleted file mode 100644 index 6a7a0d2b1432..000000000000 --- a/dev/tests/static/framework/Magento/Sniffs/NamingConventions/InterfaceNameSniff.php +++ /dev/null @@ -1,49 +0,0 @@ -getTokens(); - $declarationLine = $tokens[$stackPtr]['line']; - $suffixLength = strlen(self::INTERFACE_SUFFIX); - // Find first T_STRING after 'interface' keyword in the line and verify it - while ($tokens[$stackPtr]['line'] == $declarationLine) { - if ($tokens[$stackPtr]['type'] == 'T_STRING') { - if (substr($tokens[$stackPtr]['content'], 0 - $suffixLength) != self::INTERFACE_SUFFIX) { - $sourceFile->addError( - 'Interface should have name that ends with "Interface" suffix.', - $stackPtr, - 'WrongInterfaceName' - ); - } - break; - } - $stackPtr++; - } - } -} diff --git a/dev/tests/static/framework/Magento/Sniffs/NamingConventions/ReservedWordsSniff.php b/dev/tests/static/framework/Magento/Sniffs/NamingConventions/ReservedWordsSniff.php deleted file mode 100644 index b81c250338e1..000000000000 --- a/dev/tests/static/framework/Magento/Sniffs/NamingConventions/ReservedWordsSniff.php +++ /dev/null @@ -1,116 +0,0 @@ - '7', - 'float' => '7', - 'bool' => '7', - 'string' => '7', - 'true' => '7', - 'false' => '7', - 'null' => '7', - 'void' => '7.1', - 'iterable' => '7.1', - 'resource' => '7', - 'object' => '7', - 'mixed' => '7', - 'numeric' => '7', - ]; - - /** - * @inheritdoc - */ - public function register() - { - return [T_CLASS, T_INTERFACE, T_TRAIT, T_NAMESPACE]; - } - - /** - * Check all namespace parts - * - * @param File $sourceFile - * @param int $stackPtr - * @return void - */ - protected function validateNamespace(File $sourceFile, $stackPtr) - { - $stackPtr += 2; - $tokens = $sourceFile->getTokens(); - while ($stackPtr < $sourceFile->numTokens && $tokens[$stackPtr]['code'] !== T_SEMICOLON) { - if ($tokens[$stackPtr]['code'] === T_WHITESPACE || $tokens[$stackPtr]['code'] === T_NS_SEPARATOR) { - $stackPtr++; //skip "namespace" and whitespace - continue; - } - $namespacePart = $tokens[$stackPtr]['content']; - if (isset($this->reservedWords[strtolower($namespacePart)])) { - $sourceFile->addError( - 'Cannot use "%s" in namespace as it is reserved since PHP %s', - $stackPtr, - 'Namespace', - [$namespacePart, $this->reservedWords[strtolower($namespacePart)]] - ); - } - $stackPtr++; - } - } - - /** - * Check class name not having reserved words - * - * @param File $sourceFile - * @param int $stackPtr - * @return void - */ - protected function validateClass(File $sourceFile, $stackPtr) - { - $tokens = $sourceFile->getTokens(); - $stackPtr += 2; //skip "class" and whitespace - $className = strtolower($tokens[$stackPtr]['content']); - if (isset($this->reservedWords[$className])) { - $sourceFile->addError( - 'Cannot use "%s" as class name as it is reserved since PHP %s', - $stackPtr, - 'Class', - [$className, $this->reservedWords[$className]] - ); - } - } - - /** - * @inheritdoc - */ - public function process(File $sourceFile, $stackPtr) - { - $tokens = $sourceFile->getTokens(); - switch ($tokens[$stackPtr]['code']) { - case T_CLASS: - case T_INTERFACE: - case T_TRAIT: - $this->validateClass($sourceFile, $stackPtr); - break; - case T_NAMESPACE: - $this->validateNamespace($sourceFile, $stackPtr); - break; - } - } -} diff --git a/dev/tests/static/framework/Magento/Sniffs/Security/ExecutableRegExSniff.php b/dev/tests/static/framework/Magento/Sniffs/Security/ExecutableRegExSniff.php deleted file mode 100644 index 54cf1d462c30..000000000000 --- a/dev/tests/static/framework/Magento/Sniffs/Security/ExecutableRegExSniff.php +++ /dev/null @@ -1,87 +0,0 @@ -getTokens(); - if ($tokens[$stackPtr]['content'] !== $this->function) { - return; - } - $prevToken = $phpcsFile->findPrevious(T_WHITESPACE, $stackPtr - 1, null, true); - if (in_array($tokens[$prevToken]['code'], $this->ignoreTokens)) { - return; - } - $nextToken = $phpcsFile->findNext([T_WHITESPACE, T_OPEN_PARENTHESIS], $stackPtr + 1, null, true); - if (in_array($tokens[$nextToken]['code'], Tokens::$stringTokens) - && preg_match('/[#\/|~\}\)][imsxADSUXJu]*e[imsxADSUXJu]*.$/', $tokens[$nextToken]['content']) - ) { - $phpcsFile->addError( - $this->errorMessage, - $stackPtr, - $this->errorCode, - [$tokens[$stackPtr]['content']] - ); - } - } -} diff --git a/dev/tests/static/framework/Magento/Sniffs/Strings/StringPositionSniff.php b/dev/tests/static/framework/Magento/Sniffs/Strings/StringPositionSniff.php deleted file mode 100644 index aea1ddc1efa9..000000000000 --- a/dev/tests/static/framework/Magento/Sniffs/Strings/StringPositionSniff.php +++ /dev/null @@ -1,168 +0,0 @@ -tokens = $phpcsFile->getTokens(); - $this->file = $phpcsFile; - $this->leftLimit = $open = $this->tokens[$stackPtr]['parenthesis_opener']; - $this->rightLimit = $close = $this->tokens[$stackPtr]['parenthesis_closer']; - for ($i = ($open + 1); $i < $close; $i++) { - if (($this->tokens[$i]['code'] === T_STRING && in_array($this->tokens[$i]['content'], $this->functions)) - && (!$this->findIdentical($i - 1, $this->findFunctionParenthesisCloser($i) + 1)) - ) { - $foundFunctionName = $this->tokens[$i]['content']; - $phpcsFile->addError($this->errorMessage, $i, $this->errorCode, [$foundFunctionName]); - } - } - } - - /** - * Recursively finds identical operators in current scope. - * - * @param int $leftCurrentPosition - * @param int $rightCurrentPosition - * @return bool - */ - protected function findIdentical($leftCurrentPosition, $rightCurrentPosition) - { - $leftBound = $this->file->findPrevious($this->leftRangeTokens, $leftCurrentPosition, $this->leftLimit - 1); - $rightBound = $this->file->findNext($this->rightRangeTokens, $rightCurrentPosition, $this->rightLimit + 1); - $leftToken = $this->tokens[$leftBound]; - $rightToken = $this->tokens[$rightBound]; - if ($leftToken['code'] === T_OPEN_PARENTHESIS && $rightToken['code'] === T_CLOSE_PARENTHESIS) { - return $this->findIdentical($leftBound - 1, $rightBound + 1); - } else { - return ( - in_array($leftToken['code'], $this->identical) || in_array($rightToken['code'], $this->identical) - ) ?: false; - } - } - - /** - * Finds the position of close parenthesis of detected function. - * - * @param int $currentPosition - * @return mixed - */ - protected function findFunctionParenthesisCloser($currentPosition) - { - $nextOpenParenthesis = $this->file->findNext(T_OPEN_PARENTHESIS, $currentPosition, $this->rightLimit); - return $nextOpenParenthesis ? $this->tokens[$nextOpenParenthesis]['parenthesis_closer'] : false; - } -} diff --git a/dev/tests/static/framework/Magento/Sniffs/Translation/ConstantUsageSniff.php b/dev/tests/static/framework/Magento/Sniffs/Translation/ConstantUsageSniff.php deleted file mode 100644 index 50fddb240b30..000000000000 --- a/dev/tests/static/framework/Magento/Sniffs/Translation/ConstantUsageSniff.php +++ /dev/null @@ -1,99 +0,0 @@ -getTokens(); - - // Make sure this is the first open tag - $previousOpenTag = $phpcsFile->findPrevious(T_OPEN_TAG, ($stackPtr - 1)); - if ($previousOpenTag !== false) { - return; - } - - $tokenCount = 0; - $currentLineContent = ''; - $currentLine = 1; - - for (; $tokenCount < $phpcsFile->numTokens; $tokenCount++) { - if ($tokens[$tokenCount]['line'] === $currentLine) { - $currentLineContent .= $tokens[$tokenCount]['content']; - } else { - $this->checkIfFirstArgumentConstant($phpcsFile, ($tokenCount - 1), $currentLineContent); - $currentLineContent = $tokens[$tokenCount]['content']; - $currentLine++; - } - } - - $this->checkIfFirstArgumentConstant($phpcsFile, ($tokenCount - 1), $currentLineContent); - } - - /** - * Checks if first argument of \Magento\Framework\Phrase or translation function is a constant - * - * @param File $phpcsFile - * @param int $stackPtr - * @param string $lineContent - * @return void - */ - private function checkIfFirstArgumentConstant( - File $phpcsFile, - $stackPtr, - $lineContent - ) { - $previousLineRegexp = '/(__|Phrase)\($/im'; - $currentLineRegexp = '/(__|Phrase)\(.+\)/'; - $currentLineMatch = preg_match($currentLineRegexp, $lineContent) !== 0; - $previousLineMatch = preg_match($previousLineRegexp, $this->previousLineContent) !== 0; - $this->previousLineContent = $lineContent; - $error = 'Constants are not allowed as the first argument of translation function, use string literal instead'; - $constantRegexp = '[^\$\'"]+::[A-Z_0-9]+.*'; - if ($currentLineMatch) { - $variableRegexp = "/(__|Phrase)\({$constantRegexp}\)/"; - if (preg_match($variableRegexp, $lineContent) !== 0) { - $phpcsFile->addError($error, $stackPtr, 'VariableTranslation'); - } - } elseif ($previousLineMatch) { - $variableRegexp = "/^{$constantRegexp}/"; - if (preg_match($variableRegexp, $lineContent) !== 0) { - $phpcsFile->addError($error, $stackPtr, 'VariableTranslation'); - } - } - } -} diff --git a/dev/tests/static/framework/Magento/Sniffs/Variables/GlobalVariablesSniff.php b/dev/tests/static/framework/Magento/Sniffs/Variables/GlobalVariablesSniff.php deleted file mode 100644 index 2c4ce8f94af4..000000000000 --- a/dev/tests/static/framework/Magento/Sniffs/Variables/GlobalVariablesSniff.php +++ /dev/null @@ -1,40 +0,0 @@ -getTokens(); - if (preg_match('/^\$[_A-Z0-9]+$/', $tokens[$stackPtr]['content'])) { - $phpcsFile->addError( - 'Usage of global variables is not allowed: ' . $tokens[$stackPtr]['content'], - $stackPtr, - 'ERROR' - ); - return; - } - } -} diff --git a/dev/tests/static/framework/Magento/Sniffs/Whitespace/EmptyLineMissedSniff.php b/dev/tests/static/framework/Magento/Sniffs/Whitespace/EmptyLineMissedSniff.php deleted file mode 100644 index 8e34727533bd..000000000000 --- a/dev/tests/static/framework/Magento/Sniffs/Whitespace/EmptyLineMissedSniff.php +++ /dev/null @@ -1,68 +0,0 @@ -getTokens(); - if ($this->doCheck($phpcsFile, $stackPtr, $tokens)) { - $previous = $phpcsFile->findPrevious(T_WHITESPACE, $stackPtr - 1, null, true); - if ($tokens[$stackPtr]['line'] - $tokens[$previous]['line'] < 2) { - $error = 'Empty line missed'; - $phpcsFile->addError($error, $stackPtr, '', null); - } - } - } - - /** - * Execute empty line missed check. - * - * @param File $phpcsFile - * @param int $stackPtr - * @param array $tokens - * @return bool - */ - private function doCheck(File $phpcsFile, $stackPtr, $tokens) - { - $result = false; - if ($phpcsFile->hasCondition($stackPtr, T_CLASS) || $phpcsFile->hasCondition($stackPtr, T_INTERFACE)) { - $result = true; - } - - if ($phpcsFile->hasCondition($stackPtr, T_FUNCTION)) { - $result = false; - } - $previous = $phpcsFile->findPrevious(T_WHITESPACE, $stackPtr - 1, null, true); - if ($tokens[$previous]['type'] === 'T_OPEN_CURLY_BRACKET') { - $result = false; - } - - if (strpos($tokens[$stackPtr]['content'], '/**') === false) { - $result = false; - } - - return $result; - } -} diff --git a/dev/tests/static/framework/Magento/Sniffs/Whitespace/MultipleEmptyLinesSniff.php b/dev/tests/static/framework/Magento/Sniffs/Whitespace/MultipleEmptyLinesSniff.php deleted file mode 100644 index c862b019ae10..000000000000 --- a/dev/tests/static/framework/Magento/Sniffs/Whitespace/MultipleEmptyLinesSniff.php +++ /dev/null @@ -1,49 +0,0 @@ -getTokens(); - if ($phpcsFile->hasCondition($stackPtr, T_FUNCTION) - || $phpcsFile->hasCondition($stackPtr, T_CLASS) - || $phpcsFile->hasCondition($stackPtr, T_INTERFACE) - ) { - if ($tokens[($stackPtr - 1)]['line'] < $tokens[$stackPtr]['line'] - && $tokens[($stackPtr - 2)]['line'] === $tokens[($stackPtr - 1)]['line'] - ) { - // This is an empty line and the line before this one is not - // empty, so this could be the start of a multiple empty line block - $next = $phpcsFile->findNext(T_WHITESPACE, $stackPtr, null, true); - $lines = $tokens[$next]['line'] - $tokens[$stackPtr]['line']; - if ($lines > 1) { - $error = 'Code must not contain multiple empty lines in a row; found %s empty lines'; - $data = [$lines]; - $phpcsFile->addError($error, $stackPtr, 'MultipleEmptyLines', $data); - } - } - } - } -} diff --git a/dev/tests/static/framework/Magento/TestFramework/CodingStandard/Tool/CodeSniffer.php b/dev/tests/static/framework/Magento/TestFramework/CodingStandard/Tool/CodeSniffer.php index 225be94958d0..2cd1d0969c4b 100644 --- a/dev/tests/static/framework/Magento/TestFramework/CodingStandard/Tool/CodeSniffer.php +++ b/dev/tests/static/framework/Magento/TestFramework/CodingStandard/Tool/CodeSniffer.php @@ -54,6 +54,7 @@ class CodeSniffer implements ToolInterface, ExtensionInterface public function __construct($rulesetDir, $reportFile, Wrapper $wrapper) { $this->rulesetDir = $rulesetDir; + // phpcs:ignore Magento2.Functions.DiscouragedFunction if (!file_exists($rulesetDir) && file_exists($fullPath = realpath(__DIR__ . '/../../../../' . $rulesetDir))) { $this->rulesetDir = $fullPath; } @@ -62,7 +63,7 @@ public function __construct($rulesetDir, $reportFile, Wrapper $wrapper) } /** - * {@inheritdoc} + * @inheritdoc */ public function setExtensions(array $extensions) { @@ -80,7 +81,7 @@ public function canRun() } /** - * {@inheritdoc} + * @inheritdoc */ public function run(array $whiteList) { @@ -97,10 +98,10 @@ public function run(array $whiteList) $settings['files'] = $whiteList; $settings['standards'] = [$this->rulesetDir]; $settings['extensions'] = $this->extensions; - $settings['warningSeverity'] = 0; $settings['reports']['full'] = $this->reportFile; $this->wrapper->setSettings($settings); + // phpcs:ignore Magento2.Functions.DiscouragedFunction ob_start(); $result = $this->wrapper->runPHPCS(); ob_end_clean(); diff --git a/dev/tests/static/framework/Magento/TestFramework/Utility/XssOutputValidator.php b/dev/tests/static/framework/Magento/TestFramework/Utility/XssOutputValidator.php deleted file mode 100644 index 516f169227a9..000000000000 --- a/dev/tests/static/framework/Magento/TestFramework/Utility/XssOutputValidator.php +++ /dev/null @@ -1,441 +0,0 @@ -getXssUnsafeBlocks($fileContent); - - $lines = []; - foreach ($xssUnsafeBlocks as $block) { - $lines = array_merge($lines, $this->findBlockLineNumbers($block, $fileContent)); - } - - if (count($lines)) { - $lines = array_unique($lines); - sort($lines); - return implode(',', $lines); - } - - return ''; - } - - /** - * Find block line numbers - * - * @param string $block - * @param string $content - * @return array - */ - private function findBlockLineNumbers($block, $content) - { - $results = []; - $pos = strpos($content, $block, 0); - while ($pos !== false) { - $contentBeforeString = substr($content, 0, $pos); - if ($this->isNotEscapeMarkedBlock($contentBeforeString) - && $this->isNotInCommentBlock($contentBeforeString) - ) { - $results[] = count(explode(PHP_EOL, $contentBeforeString)); - } - $pos = strpos($content, $block, $pos + 1); - } - - return $results; - } - - /** - * Get XSS unsafe output blocks - * - * @param string $fileContent - * @return array - */ - public function getXssUnsafeBlocks($fileContent) - { - $results = []; - - $fileContent = $this->replacePhpQuoteWithPlaceholders($fileContent); - $fileContent = $this->replacePhpCommentsWithPlaceholders($fileContent); - - $this->addOriginReplacement('\'\'', "'-*=single=*-'"); - $this->addOriginReplacement('""', '"-*=double=*-"'); - - if (preg_match_all('/<[?](php|=)(.*?)[?]>/sm', $fileContent, $phpBlockMatches)) { - foreach ($phpBlockMatches[2] as $index => $phpBlock) { - $phpCommands = explode(';', $phpBlock); - if ($phpBlockMatches[1][$index] == 'php') { - $echoCommands = preg_grep('#( |^|/\*.*?\*/)echo[\s(]+.*#sm', $phpCommands); - } else { - $echoCommands[] = $phpBlockMatches[0][$index]; - } - $results = array_merge( - $results, - $this->getEchoUnsafeCommands($echoCommands) - ); - } - } - - $this->clearOriginReplacements(); - $results = array_unique($results); - - return $results; - } - - /** - * @param array $echoCommands - * @return array - */ - private function getEchoUnsafeCommands(array $echoCommands) - { - $results = []; - foreach ($echoCommands as $echoCommand) { - if ($this->isNotEscapeMarkedCommand($echoCommand)) { - $echoCommand = preg_replace('/^(.*?)echo/sim', 'echo', $echoCommand); - $preparedEchoCommand = $this->prepareEchoCommand($echoCommand); - $isEscapeFunctionArgument = preg_match( - '/->(' . implode('|', $this->escapeFunctions) . ')\(.*?\)$/sim', - $preparedEchoCommand - ); - $xssUnsafeCommands = array_filter( - $isEscapeFunctionArgument ? [$preparedEchoCommand] : explode('.', $preparedEchoCommand), - [$this, 'isXssUnsafeCommand'] - ); - if (count($xssUnsafeCommands)) { - $results[] = str_replace( - $this->getReplacements(), - $this->getOrigins(), - $echoCommand - ); - } - } - } - - return $results; - } - - /** - * @param string $command - * @return string - */ - private function prepareEchoCommand($command) - { - $command = preg_replace('/<[?]=(.*?)[?]>/sim', '\1', $command); - return trim(ltrim(explode(';', $command)[0], 'echo')); - } - - /** - * @param string $contentBeforeString - * @return bool - */ - private function isNotEscapeMarkedBlock($contentBeforeString) - { - return !preg_match( - '%(' . self::ESCAPE_NOT_VERIFIED_PATTERN . '|' . self::ESCAPED_PATTERN . ')$%sim', - trim($contentBeforeString) - ); - } - - /** - * @param string $contentBeforeString - * @return bool - */ - private function isNotInCommentBlock($contentBeforeString) - { - $contentBeforeString = explode('(' . implode('|', $this->escapeFunctions) . '|.*html.*)\(/simU', - $this->getLastMethod($command) - ): - return false; - case preg_match('/^\((int|bool|float)\)/sim', $command): - return false; - case preg_match('/^count\(/sim', $command): - return false; - case preg_match("/^'.*'$/sim", $command): - return false; - case preg_match('/^".*?"$/sim', $command, $matches): - return $this->isContainPhpVariables($this->getOrigin($matches[0])); - default: - return true; - } - } - - /** - * @param string $command - * @return string - */ - private function getLastMethod($command) - { - if (preg_match_all( - '/->.*?\(.*?\)/sim', - $this->clearMethodBracketContent($command), - $matches - )) { - $command = end($matches[0]); - $command = substr($command, 0, strpos($command, '(') + 1); - } - - return $command; - } - - /** - * @param string $command - * @return string - */ - private function clearMethodBracketContent($command) - { - $bracketInterval = []; - $bracketOpenPos = []; - $command = str_split($command); - foreach ($command as $index => $character) { - if ($character == '(') { - array_push($bracketOpenPos, $index); - } - if (count($bracketOpenPos)) { - if ($character == ')') { - $lastOpenPos = array_pop($bracketOpenPos); - if (count($bracketOpenPos) == 0) { - $bracketInterval[] = [$lastOpenPos, $index]; - } - } - } - } - foreach ($bracketInterval as $interval) { - for ($i = $interval[0] + 1; $i < $interval[1]; $i++) { - unset($command[$i]); - } - } - $command = implode('', $command); - - return $command; - } - - /** - * @param string $content - * @return int - */ - private function isContainPhpVariables($content) - { - return preg_match('/[^\\\\]\$[a-z_\x7f-\xff]/sim', $content); - } - - /** - * @param string $fileContent - * @return string - */ - private function replacePhpQuoteWithPlaceholders($fileContent) - { - $origins = []; - $replacements = []; - if (preg_match_all('/<[?](php|=)(.*?)[?]>/sm', $fileContent, $phpBlockMatches)) { - foreach ($phpBlockMatches[2] as $phpBlock) { - $phpBlockQuoteReplaced = preg_replace( - ['/([^\\\\])\'\'/si', '/([^\\\\])""/si'], - ["\1'-*=single=*-'", '\1"-*=double=*-"'], - $phpBlock - ); - - $this->addQuoteOriginsReplacements( - $phpBlockQuoteReplaced, - [ - '/([^\\\\])([\'])(.*?)([^\\\\])([\'])/sim' - ] - ); - $this->addQuoteOriginsReplacements( - $phpBlockQuoteReplaced, - [ - '/([^\\\\])(["])(.*?)([^\\\\])(["])/sim', - ] - ); - - $origins[] = $phpBlock; - $replacements[] = str_replace( - $this->getOrigins(), - $this->getReplacements(), - $phpBlockQuoteReplaced - ); - } - } - - return str_replace($origins, $replacements, $fileContent); - } - - /** - * @param string $fileContent - * @return string - */ - private function replacePhpCommentsWithPlaceholders($fileContent) - { - $origins= []; - $replacements = []; - if (preg_match_all('%/\*.*?\*/%simu', $fileContent, $docCommentMatches, PREG_SET_ORDER)) { - foreach ($docCommentMatches as $docCommentMatch) { - if ($this->isNotEscapeMarkedCommand($docCommentMatch[0]) - && !$this->issetOrigin($docCommentMatch[0])) { - $origin = $docCommentMatch[0]; - $replacement = '-*!' . count($this->getOrigins()) . '!*-'; - $origins[] = $origin; - $replacements[] = $replacement; - $this->addOriginReplacement( - $origin, - $replacement - ); - } - } - } - - return str_replace($origins, $replacements, $fileContent); - } - - /** - * Add replacements for expressions in single and double quotes - * - * @param string $phpBlock - * @param array $patterns - * @return void - */ - private function addQuoteOriginsReplacements($phpBlock, array $patterns) - { - foreach ($patterns as $pattern) { - if (preg_match_all($pattern, $phpBlock, $quoteMatches, PREG_SET_ORDER)) { - foreach ($quoteMatches as $quoteMatch) { - $origin = $quoteMatch[2] . $quoteMatch[3] . $quoteMatch[4] . $quoteMatch[5]; - if (!$this->issetOrigin($origin)) { - $this->addOriginReplacement( - $origin, - $quoteMatch[2] . '-*=' . count($this->getOrigins()) . '=*-' . $quoteMatch[5] - ); - } - } - } - } - } - - /** - * @param string $origin - * @param string $replacement - * @return void - */ - private function addOriginReplacement($origin, $replacement) - { - $this->origins[$replacement] = $origin; - $this->replacements[$replacement] = $replacement; - } - - /** - * Clear origins and replacements - * - * @return void - */ - private function clearOriginReplacements() - { - $this->origins = []; - $this->replacements = []; - } - - /** - * @return array - */ - private function getOrigins() - { - return $this->origins; - } - - /** - * @param string $key - * @return string|null - */ - private function getOrigin($key) - { - return array_key_exists($key, $this->origins) ? $this->origins[$key] : null; - } - - /** - * @param string $origin - * @return bool - */ - private function issetOrigin($origin) - { - return in_array($origin, $this->origins); - } - - /** - * @return array - */ - private function getReplacements() - { - return $this->replacements; - } -} diff --git a/dev/tests/static/framework/Magento/ruleset.xml b/dev/tests/static/framework/Magento/ruleset.xml index 9dde4b7bd7d3..70d1810d1eb2 100644 --- a/dev/tests/static/framework/Magento/ruleset.xml +++ b/dev/tests/static/framework/Magento/ruleset.xml @@ -7,83 +7,12 @@ --> Custom Magento coding standard. + - - - - *.phtml - - - - - - - - - - */app/code/*\.(?!phtml) - - - */_files/* - - + + */_files/* */Test/* *Test.php - */Magento/Inventory*/* - - *\.(php) - */Test/* - *Test.php - */_files/* - */Magento/Inventory*/* - - - *\.(php) - */Test/* - *Test.php - */_files/* - */Magento/Inventory*/* - - - */(app/code|vendor|setup/src|lib/internal/Magento)/* - */lib/internal/Magento/Framework/Image/Adapter/Gd2.php - */lib/internal/Magento/Framework/View/Result/Page.php - */lib/internal/Magento/Framework/View/TemplateEngine/Php.php - */Test/Unit/* - - - */(app/code|vendor|setup/src)/* - */setup/src/Magento/Setup/Controller/WebConfiguration.php - */setup/src/Magento/Setup/Mvc/Bootstrap/InitParamListener.php - */app/code/Magento/Eav/Model/Attribute/Data/File.php - */app/code/Magento/Config/Model/Config/Reader/Source/Deployed/SettingChecker.php - */app/code/Magento/Backend/App/Area/FrontNameResolver.php - */app/code/Magento/Indexer/Console/Command/AbstractIndexerCommand.php - */app/code/Magento/Catalog/Model/Product/Option/Type/File/ValidatorFile.php - */app/code/Magento/Cron/Console/Command/CronCommand.php - */app/code/Magento/ImportExport/Controller/Adminhtml/Import/Validate.php - */app/code/Magento/OfflineShipping/Model/ResourceModel/Carrier/Tablerate.php - */app/code/Magento/Store/Model/Store.php - */app/code/Magento/Config/Model/Config/Processor/EnvironmentPlaceholder.php - */app/code/Magento/Config/Model/Config/Backend/Email/Logo.php - */app/code/Magento/Config/Model/Config/Backend/File/RequestData.php - */app/code/Magento/Config/App/Config/Source/EnvironmentConfigSource.php - */app/code/Magento/Theme/Controller/Adminhtml/Design/Config/FileUploader/Save.php - */app/code/Magento/Customer/Model/Metadata/Form/File.php - */app/code/Magento/Customer/Model/FileUploader.php - */app/code/Magento/Customer/Controller/Adminhtml/File/Address/Upload.php - */app/code/Magento/Customer/Controller/Adminhtml/File/Customer/Upload.php - */Test/Unit/* - - - - - - - - - - diff --git a/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/EchoTags/ShortEchoSyntaxSniffTest.php b/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/EchoTags/ShortEchoSyntaxSniffTest.php deleted file mode 100644 index 0601c3eb2669..000000000000 --- a/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/EchoTags/ShortEchoSyntaxSniffTest.php +++ /dev/null @@ -1,82 +0,0 @@ -fileMock = $this->getMock(\PHP_CodeSniffer_File::class, [], [], '', false); - $this->shortEchoUsageSniff = new ShortEchoSyntaxSniff(); - } - - /** - * @param string $file - * @param int $incorrectUsages - * @dataProvider processDataProvider - */ - public function testEchoTagSniff($file, $stackPtr, $incorrectUsages) - { - $fileContent = file_get_contents(__DIR__ . '/_files/' . $file); - $tokens = $this->tokenizeString($fileContent); - - $this->fileMock->expects($this->any()) - ->method('findNext') - ->with([T_WHITESPACE, T_COMMENT, T_DOC_COMMENT], $stackPtr + 1, null, true) - ->willReturn($stackPtr + 1); - - $this->fileMock->expects($this->once()) - ->method('getTokens') - ->willReturn($tokens); - - $this->fileMock->expects($this->exactly($incorrectUsages)) - ->method('addError') - ->with('Short echo tag syntax must be used; expected "shortEchoUsageSniff->process($this->fileMock, $stackPtr); - } - - /** - * Get tokens for a string - * - * @param string $fileContent - * @return array - */ - private function tokenizeString($fileContent) - { - $tokens = token_get_all($fileContent); - $snifferTokens = []; - for ($i = 0; $i < count($tokens); $i++) { - $code = is_array($tokens[$i]) ? $tokens[$i][0] : $tokens[$i]; - $content = is_array($tokens[$i]) ? $tokens[$i][1] : $tokens[$i]; - $snifferTokens[$i]['code'] = $code; - $snifferTokens[$i]['content'] = $content; - } - return $snifferTokens; - } - - /** - * @return array - */ - public function processDataProvider() - { - return [ - ['incorrect_echotag.txt', 1, 1], - ['correct_noecho.txt', 1, 0], - ['correct_echotag.txt', 1, 0] - ]; - } -} diff --git a/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/EchoTags/_files/correct_echotag.txt b/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/EchoTags/_files/correct_echotag.txt deleted file mode 100644 index fd8027e1e23e..000000000000 --- a/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/EchoTags/_files/correct_echotag.txt +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - - diff --git a/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/EchoTags/_files/correct_noecho.txt b/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/EchoTags/_files/correct_noecho.txt deleted file mode 100644 index 5b003e1e5cfb..000000000000 --- a/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/EchoTags/_files/correct_noecho.txt +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - - diff --git a/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/EchoTags/_files/incorrect_echotag.txt b/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/EchoTags/_files/incorrect_echotag.txt deleted file mode 100644 index 84d72334bf85..000000000000 --- a/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/EchoTags/_files/incorrect_echotag.txt +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Copyright © Magento, Inc. All rights reserved. - * See COPYING.txt for license details. - */ - - diff --git a/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/Translation/ConstantUsageSniffTest.php b/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/Translation/ConstantUsageSniffTest.php deleted file mode 100644 index 65512653ce3f..000000000000 --- a/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/Translation/ConstantUsageSniffTest.php +++ /dev/null @@ -1,98 +0,0 @@ -fileMock = $this->createMock(File::class); - $this->constantUsageSniff = new ConstantUsageSniff(); - } - - /** - * @param string $file - * @param int $numIncorrectUsages - * @dataProvider processDataProvider - */ - public function testProcessIncorrectArguments($file, $numIncorrectUsages) - { - $stackPtr = 10; - $fileContent = file_get_contents(__DIR__ . '/_files/' . $file); - $tokens = $this->tokenizeString($fileContent); - $this->fileMock->expects($this->once()) - ->method('findPrevious') - ->with( - T_OPEN_TAG, - $stackPtr - 1 - ) - ->willReturn(false); - $this->fileMock->expects($this->once()) - ->method('getTokens') - ->willReturn($tokens); - $this->fileMock->numTokens = count($tokens); - $this->fileMock->expects($this->exactly($numIncorrectUsages)) - ->method('addError') - ->with( - 'Constants are not allowed as the first argument of translation function, use string literal instead', - $this->anything(), - 'VariableTranslation' - ); - $this->constantUsageSniff->process($this->fileMock, $stackPtr); - } - - /** - * Get tokens for a string - * - * @param string $fileContent - * @return array - */ - private function tokenizeString($fileContent) - { - $lineNumber = 1; - $tokens = token_get_all($fileContent); - $snifferTokens = []; - for ($i = 0, $count = count($tokens); $i < $count; $i++) { - $content = is_array($tokens[$i]) ? $tokens[$i][1] : $tokens[$i]; - $snifferTokens[$i]['line'] = $lineNumber; - $snifferTokens[$i]['content'] = $content; - $trimmedContent = trim($content, ' '); - if ($trimmedContent == PHP_EOL || $trimmedContent == PHP_EOL . PHP_EOL) { - $lineNumber++; - } - } - return $snifferTokens; - } - - /** - * @return array - */ - public function processDataProvider() - { - return [ - [ - 'incorrect_arguments.txt', - 9 - ], - [ - 'correct_arguments.txt', - 0 - ] - ]; - } -} diff --git a/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/Translation/_files/correct_arguments.txt b/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/Translation/_files/correct_arguments.txt deleted file mode 100644 index 8446fe75cf11..000000000000 --- a/dev/tests/static/framework/tests/unit/testsuite/Magento/Sniffs/Translation/_files/correct_arguments.txt +++ /dev/null @@ -1,29 +0,0 @@ - $whiteList, 'standards' => [self::RULE_SET], 'extensions' => $extensions, - 'warningSeverity' => 0, 'reports' => ['full' => self::REPORT_FILE], ]; diff --git a/dev/tests/static/framework/tests/unit/testsuite/Magento/TestFramework/Utility/XssOutputValidatorTest.php b/dev/tests/static/framework/tests/unit/testsuite/Magento/TestFramework/Utility/XssOutputValidatorTest.php deleted file mode 100644 index ed9d8115cca4..000000000000 --- a/dev/tests/static/framework/tests/unit/testsuite/Magento/TestFramework/Utility/XssOutputValidatorTest.php +++ /dev/null @@ -1,33 +0,0 @@ -getLinesWithXssSensitiveOutput($file); - static::assertEquals($expectedResults, $lines); - } - - /** - * @return array - */ - public function getLinesWithXssSensitiveOutputDataProvider() - { - $fixturePath = __DIR__ . '/_files/'; - return [ - 'xss_safe' => [$fixturePath . 'xss_safe.phtml', ''], - 'xss_unsafe' => [$fixturePath . 'xss_unsafe.phtml', '9,10,11,12,13,14,15,16,18,22,23'], - ]; - } -} diff --git a/dev/tests/static/framework/tests/unit/testsuite/Magento/TestFramework/Utility/_files/xss_safe.phtml b/dev/tests/static/framework/tests/unit/testsuite/Magento/TestFramework/Utility/_files/xss_safe.phtml deleted file mode 100644 index 50d2503514d1..000000000000 --- a/dev/tests/static/framework/tests/unit/testsuite/Magento/TestFramework/Utility/_files/xss_safe.phtml +++ /dev/null @@ -1,48 +0,0 @@ - - -getSomeData() ?> -getSomeData() ?> - - - -escapeCss('value') ?> -echo $var; -getHtmlId("some value") ?> -getIdHtml("some value") ?> -getIdHtml("some value") ?> - - - - - - - -methodHtml() ?> - -methodHtml() . - (bool)$var . - $block->escapeUrl("some value"); -?> -escapeHtml($data['parentSymbol']) . '\'' ?> -getExtendedElement($switchAttributeCode)->toHtml() ?> -escapeHtml($_filter->getFilter()->getClearLinkText()) ?> - - - tags from the code. */ -/* foreach ($block->getColumns() as $_column): ?> - getProperty() ?> /> - - -escapeHtmlAttr($block->getParamValue('title_' . $store['value'])) ?> diff --git a/dev/tests/static/framework/tests/unit/testsuite/Magento/TestFramework/Utility/_files/xss_unsafe.phtml b/dev/tests/static/framework/tests/unit/testsuite/Magento/TestFramework/Utility/_files/xss_unsafe.phtml deleted file mode 100644 index bf3aec540b81..000000000000 --- a/dev/tests/static/framework/tests/unit/testsuite/Magento/TestFramework/Utility/_files/xss_unsafe.phtml +++ /dev/null @@ -1,29 +0,0 @@ - -getSomeData() ?> -getTitle() ?> -getSomeMethod($block->getHtmlId()) ?> - -escapeUrl($var) . $var . 'value' ?> - - - - -methodHtml() . - $var . - $block->getSomeData(); -?> -escapeHtml($data['parentSymbol']) . '\'' ?> -escapeHtml($data['parentSymbol']) . "\"" ?> - - tags from the code. */ -/* foreach ($block->getColumns() as $_column): ?> - getProperty() ?> /> - diff --git a/dev/tests/static/phpunit.xml.dist b/dev/tests/static/phpunit.xml.dist index 8ed80df002df..6c02ec138256 100644 --- a/dev/tests/static/phpunit.xml.dist +++ b/dev/tests/static/phpunit.xml.dist @@ -24,9 +24,6 @@ testsuite/Magento/Test/Integrity - - testsuite/Magento/Test/Php/XssPhtmlTemplateTest.php - diff --git a/dev/tests/static/testsuite/Magento/Test/Legacy/UnsecureFunctionsUsageTest.php b/dev/tests/static/testsuite/Magento/Test/Legacy/UnsecureFunctionsUsageTest.php index 6edc46090d54..2ce9934c6c1a 100644 --- a/dev/tests/static/testsuite/Magento/Test/Legacy/UnsecureFunctionsUsageTest.php +++ b/dev/tests/static/testsuite/Magento/Test/Legacy/UnsecureFunctionsUsageTest.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Test\Legacy; use Magento\Framework\App\Utility\Files; @@ -42,7 +44,6 @@ class UnsecureFunctionsUsageTest extends \PHPUnit\Framework\TestCase */ public static function setUpBeforeClass() { - self::loadData(self::$phpUnsecureFunctions, 'unsecure_php_functions*.php'); self::loadData(self::$jsUnsecureFunctions, 'unsecure_js_functions*.php'); } diff --git a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php b/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php deleted file mode 100644 index 10c0da47cb2d..000000000000 --- a/dev/tests/static/testsuite/Magento/Test/Legacy/_files/security/unsecure_php_functions.php +++ /dev/null @@ -1,87 +0,0 @@ - will be suggested to be used instead. - * Use to specify files and directories that are allowed to use function. - * - * Format: [ - * => [ - * 'replacement' => , - * 'exclude' => [ - * , - * , - * ] - * ] - */ -return [ - 'unserialize' => [ - 'replacement' => '\Magento\Framework\Serialize\SerializerInterface::unserialize', - 'exclude' => [ - ['type' => 'library', 'name' => 'magento/framework', 'path' => 'DB/Adapter/Pdo/Mysql.php'], - ['type' => 'library', 'name' => 'magento/framework', 'path' => 'Serialize/Serializer/Serialize.php'], - ] - ], - 'serialize' => [ - 'replacement' => '\Magento\Framework\Serialize\SerializerInterface::serialize', - 'exclude' => [ - ['type' => 'library', 'name' => 'magento/framework', 'path' => 'DB/Adapter/Pdo/Mysql.php'], - ['type' => 'library', 'name' => 'magento/framework', 'path' => 'Serialize/Serializer/Serialize.php'], - ] - ], - 'eval' => [ - 'replacement' => '', - 'exclude' => [] - ], - 'md5' => [ - 'replacement' => '', - 'exclude' => [ - /* - * Usage of md5 in MessageQueue key generation algorithm - * added to exclude list to avoid backward incompatible changes - */ - [ - 'type' => 'library', - 'name' => 'magento/framework', - 'path' => 'MessageQueue/Rpc/Publisher.php', - ], - [ - 'type' => 'library', - 'name' => 'magento/framework', - 'path' => 'MessageQueue/MessageController.php', - ], - [ - 'type' => 'library', - 'name' => 'magento/framework', - 'path' => 'MessageQueue/Publisher.php', - ], - [ - 'type' => 'module', - 'name' => 'Magento_AsynchronousOperations', - 'path' => 'Model/ResourceModel/System/Message/Collection/Synchronized/Plugin.php' - ], - [ - 'type' => 'module', - 'name' => 'Magento_AuthorizenetAcceptjs', - 'path' => 'Gateway/Validator/TransactionHashValidator.php' - ], - [ - 'type' => 'module', - 'name' => 'Magento_Authorizenet', - 'path' => 'Model/Directpost/Response.php' - ] - ] - ], - 'srand' => [ - 'replacement' => '', - 'exclude' => [] - ], - 'mt_srand' => [ - 'replacement' => '', - 'exclude' => [] - ], -]; diff --git a/dev/tests/static/testsuite/Magento/Test/Php/LiveCodeTest.php b/dev/tests/static/testsuite/Magento/Test/Php/LiveCodeTest.php index 21ca0a495dd1..76c0d047bcbb 100644 --- a/dev/tests/static/testsuite/Magento/Test/Php/LiveCodeTest.php +++ b/dev/tests/static/testsuite/Magento/Test/Php/LiveCodeTest.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Test\Php; @@ -116,8 +117,10 @@ private static function getChangedFilesList($changedFilesBaseDir) 'changed_files*', function () { // if no list files, probably, this is the dev environment + // phpcs:disable Generic.PHP.NoSilencedErrors,Magento2.Security.InsecureFunction @exec('git diff --name-only', $changedFiles); @exec('git diff --cached --name-only', $addedFiles); + // phpcs:enable $changedFiles = array_unique(array_merge($changedFiles, $addedFiles)); return $changedFiles; } @@ -137,6 +140,7 @@ private static function getAddedFilesList($changedFilesBaseDir) 'changed_files*.added.*', function () { // if no list files, probably, this is the dev environment + // phpcs:ignore Generic.PHP.NoSilencedErrors,Magento2.Security.InsecureFunction @exec('git diff --cached --name-only', $addedFiles); return $addedFiles; } @@ -158,7 +162,7 @@ private static function getFilesFromListFile($listsBaseDir, $listFilePattern, $n $globFilesListPattern = ($listsBaseDir ?: self::getChangedFilesBaseDir()) . '/_files/' . $listFilePattern; $listFiles = glob($globFilesListPattern); - if (count($listFiles)) { + if (!empty($listFiles)) { foreach ($listFiles as $listFile) { $filesDefinedInList = array_merge( $filesDefinedInList, diff --git a/dev/tests/static/testsuite/Magento/Test/Php/XssPhtmlTemplateTest.php b/dev/tests/static/testsuite/Magento/Test/Php/XssPhtmlTemplateTest.php deleted file mode 100644 index fac14af5ecab..000000000000 --- a/dev/tests/static/testsuite/Magento/Test/Php/XssPhtmlTemplateTest.php +++ /dev/null @@ -1,89 +0,0 @@ -{suffix}Html{postfix}() ). - * Data is ready for the HTML output. Test is green. - * 3. AbstractBlock methods escapeHtml, escapeUrl, escapeQuote, escapeXssInUrl are allowed. Test is green. - * 4. Type casting and php function count() are allowed - * (e.g. echo (int)$var, echo (float)$var, echo (bool)$var, echo count($var)). Test is green. - * 5. Output in single quotes (e.g. echo 'some text'). Test is green. - * 6. Output in double quotes without variables (e.g. echo "some text"). Test is green. - * 7. Other of p.1-6. Output is not escaped. Test is red. - * - * @param string $file - */ - function ($file) use ($xssOutputValidator) { - $lines = $xssOutputValidator->getLinesWithXssSensitiveOutput($file); - $this->assertEmpty( - $lines, - "Potentially XSS vulnerability. " . - "Please verify that output is escaped at lines " . $lines - ); - }, - Files::init()->getPhtmlFiles() - ); - } - - /** - * @return void - */ - public function testAbsenceOfEscapeNotVerifiedAnnotationInRefinedModules() - { - $componentRegistrar = new ComponentRegistrar(); - $exemptModules = []; - foreach (array_diff(scandir(__DIR__ . '/_files/whitelist/exempt_modules'), ['..', '.']) as $file) { - $exemptModules = array_merge( - $exemptModules, - include(__DIR__ . '/_files/whitelist/exempt_modules/' . $file) - ); - } - - $result = ""; - foreach ($componentRegistrar->getPaths(ComponentRegistrar::MODULE) as $moduleName => $modulePath) { - if (in_array($moduleName, $exemptModules)) { - continue; - } - foreach (Files::init()->getFiles([$modulePath], '*.phtml') as $file) { - $fileContents = file_get_contents($file); - $pattern = "/\\/* @escapeNotVerified \\*\\/ echo (?!__).+/"; - $instances = preg_grep($pattern, explode("\n", $fileContents)); - if (!empty($instances)) { - foreach (array_keys($instances) as $line) { - $result .= $file . ':' . ($line + 1) . "\n"; - } - } - } - } - $this->assertEmpty( - $result, - "@escapeNotVerified annotation detected.\n" . - "Please use the correct escape strategy and remove annotation at:\n" . $result - ); - } -} diff --git a/dev/tests/static/testsuite/Magento/Test/Php/_files/phpmd/ruleset.xml b/dev/tests/static/testsuite/Magento/Test/Php/_files/phpmd/ruleset.xml index 7a402818eb0b..0e3b5fa3d341 100644 --- a/dev/tests/static/testsuite/Magento/Test/Php/_files/phpmd/ruleset.xml +++ b/dev/tests/static/testsuite/Magento/Test/Php/_files/phpmd/ruleset.xml @@ -29,9 +29,6 @@ - - - @@ -46,7 +43,6 @@ - diff --git a/lib/internal/Magento/Framework/App/Bootstrap.php b/lib/internal/Magento/Framework/App/Bootstrap.php index 904c41ab9ec3..717b810cffd2 100644 --- a/lib/internal/Magento/Framework/App/Bootstrap.php +++ b/lib/internal/Magento/Framework/App/Bootstrap.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Framework\App; @@ -245,6 +246,8 @@ public function createApplication($type, $arguments = []) * * @param \Magento\Framework\AppInterface $application * @return void + * + * phpcs:disable Magento2.Exceptions,Squiz.Commenting.FunctionCommentThrowTag */ public function run(AppInterface $application) { @@ -267,13 +270,15 @@ public function run(AppInterface $application) } catch (\Exception $e) { $this->terminate($e); } - } + } // phpcs:enable /** * Asserts maintenance mode * * @return void * @throws \Exception + * + * phpcs:disable Magento2.Exceptions */ protected function assertMaintenance() { @@ -299,7 +304,7 @@ protected function assertMaintenance() $this->errorCode = self::ERR_MAINTENANCE; throw new \Exception('Unable to proceed: the maintenance mode must be enabled first. '); } - } + } // phpcs:enable /** * Asserts whether application is installed @@ -316,10 +321,12 @@ protected function assertInstalled() $isInstalled = $this->isInstalled(); if (!$isInstalled && $isExpected) { $this->errorCode = self::ERR_IS_INSTALLED; + // phpcs:ignore Magento2.Exceptions.DirectThrow throw new \Exception('Error: Application is not installed yet. '); } if ($isInstalled && !$isExpected) { $this->errorCode = self::ERR_IS_INSTALLED; + // phpcs:ignore Magento2.Exceptions.DirectThrow throw new \Exception('Error: Application is already installed. '); } } @@ -413,10 +420,12 @@ public function isDeveloperMode() * * @param \Exception $e * @return void - * @SuppressWarnings(PHPMD.ExitExpression) + * + * phpcs:disable Magento2.Security.LanguageConstruct, Squiz.Commenting.FunctionCommentThrowTag */ protected function terminate(\Exception $e) { + if ($this->isDeveloperMode()) { echo $e; } else { @@ -433,4 +442,5 @@ protected function terminate(\Exception $e) } exit(1); } + // phpcs:enable } diff --git a/lib/internal/Magento/Framework/App/Console/Response.php b/lib/internal/Magento/Framework/App/Console/Response.php index 6255aaa3d87a..853c3d5ca269 100644 --- a/lib/internal/Magento/Framework/App/Console/Response.php +++ b/lib/internal/Magento/Framework/App/Console/Response.php @@ -3,10 +3,12 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Framework\App\Console; /** - * @SuppressWarnings(PHPMD.ExitExpression) + * HTTP response implementation. */ class Response implements \Magento\Framework\App\ResponseInterface { @@ -53,9 +55,11 @@ class Response implements \Magento\Framework\App\ResponseInterface public function sendResponse() { if (!empty($this->body)) { + // phpcs:ignore Magento2.Security.LanguageConstruct.DirectOutput echo $this->body; } if ($this->terminateOnSend) { + // phpcs:ignore Magento2.Security.LanguageConstruct.ExitUsage exit($this->code); } return $this->code; diff --git a/lib/internal/Magento/Framework/App/Response/Http/FileFactory.php b/lib/internal/Magento/Framework/App/Response/Http/FileFactory.php index 19a89681a2d5..d599f91ca8ca 100644 --- a/lib/internal/Magento/Framework/App/Response/Http/FileFactory.php +++ b/lib/internal/Magento/Framework/App/Response/Http/FileFactory.php @@ -1,13 +1,17 @@ isFile($file)) { + // phpcs:ignore Magento2.Exceptions.DirectThrow throw new \Exception((string)new \Magento\Framework\Phrase('File not found')); } $contentLength = $dir->stat($file)['size']; @@ -86,6 +90,7 @@ public function create( if ($isFile) { $stream = $dir->openFile($file, 'r'); while (!$stream->eof()) { + // phpcs:ignore Magento2.Security.LanguageConstruct.DirectOutput echo $stream->read(1024); } } else { @@ -93,6 +98,7 @@ public function create( $file = $fileName; $stream = $dir->openFile($fileName, 'r'); while (!$stream->eof()) { + // phpcs:ignore Magento2.Security.LanguageConstruct.DirectOutput echo $stream->read(1024); } } diff --git a/lib/internal/Magento/Framework/App/Router/Base.php b/lib/internal/Magento/Framework/App/Router/Base.php index f810adcfd349..fcce821858eb 100644 --- a/lib/internal/Magento/Framework/App/Router/Base.php +++ b/lib/internal/Magento/Framework/App/Router/Base.php @@ -5,6 +5,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Framework\App\Router; /** @@ -346,7 +348,6 @@ public function getActionClassName($module, $actionPath) * @param \Magento\Framework\App\RequestInterface $request * @param string $path * @return void - * @SuppressWarnings(PHPMD.ExitExpression) */ protected function _checkShouldBeSecure(\Magento\Framework\App\RequestInterface $request, $path = '') { @@ -361,6 +362,7 @@ protected function _checkShouldBeSecure(\Magento\Framework\App\RequestInterface } $this->_responseFactory->create()->setRedirect($url)->sendResponse(); + // phpcs:ignore Magento2.Security.LanguageConstruct.ExitUsage exit; } } diff --git a/lib/internal/Magento/Framework/App/Test/Unit/Router/BaseTest.php b/lib/internal/Magento/Framework/App/Test/Unit/Router/BaseTest.php index 3d44073a24b8..94a7330c322b 100644 --- a/lib/internal/Magento/Framework/App/Test/Unit/Router/BaseTest.php +++ b/lib/internal/Magento/Framework/App/Test/Unit/Router/BaseTest.php @@ -7,6 +7,9 @@ */ namespace Magento\Framework\App\Test\Unit\Router; +/** + * Base router unit test. + */ class BaseTest extends \Magento\Framework\TestFramework\Unit\BaseTestCase { /** @@ -83,11 +86,13 @@ public function testMatch() $actionClassName = \Magento\Framework\App\Action\Action::class; $moduleName = 'module name'; $moduleList = [$moduleName]; + $paramList = $moduleFrontName . '/' . $actionPath . '/' . $actionName . '/key/val/key2/val2/'; // Stubs $this->requestMock->expects($this->any())->method('getModuleName')->willReturn($moduleFrontName); $this->requestMock->expects($this->any())->method('getControllerName')->willReturn($actionPath); $this->requestMock->expects($this->any())->method('getActionName')->willReturn($actionName); + $this->requestMock->expects($this->any())->method('getPathInfo')->willReturn($paramList); $this->routeConfigMock->expects($this->any())->method('getModulesByFrontName')->willReturn($moduleList); $this->appStateMock->expects($this->any())->method('isInstalled')->willReturn(true); $this->actionListMock->expects($this->any())->method('get')->willReturn($actionClassName); @@ -140,6 +145,7 @@ public function testMatchUseDefaultPath() $actionClassName = \Magento\Framework\App\Action\Action::class; $moduleName = 'module name'; $moduleList = [$moduleName]; + $paramList = $moduleFrontName . '/' . $actionPath . '/' . $actionName . '/key/val/key2/val2/'; // Stubs $defaultReturnMap = [ @@ -147,6 +153,7 @@ public function testMatchUseDefaultPath() ['controller', $actionPath], ['action', $actionName], ]; + $this->requestMock->expects($this->any())->method('getPathInfo')->willReturn($paramList); $this->defaultPathMock->expects($this->any())->method('getPart')->willReturnMap($defaultReturnMap); $this->routeConfigMock->expects($this->any())->method('getModulesByFrontName')->willReturn($moduleList); $this->appStateMock->expects($this->any())->method('isInstalled')->willReturn(false); @@ -171,9 +178,11 @@ public function testMatchEmptyModuleList() $actionName = 'action name'; $actionClassName = \Magento\Framework\App\Action\Action::class; $emptyModuleList = []; + $paramList = $moduleFrontName . '/' . $actionPath . '/' . $actionName . '/key/val/key2/val2/'; // Stubs $this->requestMock->expects($this->any())->method('getModuleName')->willReturn($moduleFrontName); + $this->requestMock->expects($this->any())->method('getPathInfo')->willReturn($paramList); $this->routeConfigMock->expects($this->any())->method('getModulesByFrontName')->willReturn($emptyModuleList); $this->requestMock->expects($this->any())->method('getControllerName')->willReturn($actionPath); $this->requestMock->expects($this->any())->method('getActionName')->willReturn($actionName); @@ -195,9 +204,11 @@ public function testMatchEmptyActionInstance() $actionClassName = \Magento\Framework\App\Action\Action::class; $moduleName = 'module name'; $moduleList = [$moduleName]; + $paramList = $moduleFrontName . '/' . $actionPath . '/' . $actionName . '/key/val/key2/val2/'; // Stubs $this->requestMock->expects($this->any())->method('getModuleName')->willReturn($moduleFrontName); + $this->requestMock->expects($this->any())->method('getPathInfo')->willReturn($paramList); $this->routeConfigMock->expects($this->any())->method('getModulesByFrontName')->willReturn($moduleList); $this->requestMock->expects($this->any())->method('getControllerName')->willReturn($actionPath); $this->requestMock->expects($this->any())->method('getActionName')->willReturn($actionName); diff --git a/lib/internal/Magento/Framework/Code/Test/Unit/Generator/TestAsset/ParentClass.php b/lib/internal/Magento/Framework/Code/Test/Unit/Generator/TestAsset/ParentClass.php index be34b2f8c696..4565620a7557 100644 --- a/lib/internal/Magento/Framework/Code/Test/Unit/Generator/TestAsset/ParentClass.php +++ b/lib/internal/Magento/Framework/Code/Test/Unit/Generator/TestAsset/ParentClass.php @@ -7,6 +7,9 @@ use Zend\Code\Generator\DocBlockGenerator; +/** + * phpcs:ignoreFile + */ class ParentClass { /** @@ -78,9 +81,6 @@ public static function publicParentStatic() { } - /** - * @SuppressWarnings(PHPMD.FinalImplementation) Suppressed as is a fixture but not a real code - */ final public function publicParentFinal() { } diff --git a/lib/internal/Magento/Framework/Code/Test/Unit/Generator/TestAsset/SourceClass.php b/lib/internal/Magento/Framework/Code/Test/Unit/Generator/TestAsset/SourceClass.php index 6d0e28db65f8..5ba3031a2ae4 100644 --- a/lib/internal/Magento/Framework/Code/Test/Unit/Generator/TestAsset/SourceClass.php +++ b/lib/internal/Magento/Framework/Code/Test/Unit/Generator/TestAsset/SourceClass.php @@ -7,6 +7,9 @@ use Zend\Code\Generator\ClassGenerator; +/** + * phpcs:ignoreFile + */ class SourceClass extends ParentClass { /** @@ -111,10 +114,7 @@ public function publicChildWithoutParameters() public static function publicChildStatic() { } - - /** - * @SuppressWarnings(PHPMD.FinalImplementation) Suppressed as is a fixture but not a real code - */ + final public function publicChildFinal() { } diff --git a/lib/internal/Magento/Framework/Console/Cli.php b/lib/internal/Magento/Framework/Console/Cli.php index e629a41056e6..fac588f1fbc1 100644 --- a/lib/internal/Magento/Framework/Console/Cli.php +++ b/lib/internal/Magento/Framework/Console/Cli.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Framework\Console; use Magento\Framework\App\Bootstrap; @@ -22,9 +24,10 @@ /** * Magento 2 CLI Application. + * * This is the hood for all command line tools supported by Magento. * - * {@inheritdoc} + * @inheritdoc * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ class Cli extends Console\Application @@ -61,11 +64,11 @@ class Cli extends Console\Application /** * @param string $name the application name * @param string $version the application version - * @SuppressWarnings(PHPMD.ExitExpression) */ public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN') { try { + // phpcs:ignore Magento2.Security.IncludeFile $configuration = require BP . '/setup/config/application.config.php'; $bootstrapApplication = new Application(); $application = $bootstrapApplication->bootstrap($configuration); @@ -78,7 +81,7 @@ public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN') $output->writeln( '' . $exception->getMessage() . '' ); - + // phpcs:ignore Magento2.Security.LanguageConstruct.ExitUsage exit(static::RETURN_FAILURE); } @@ -93,7 +96,7 @@ public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN') } /** - * {@inheritdoc} + * @inheritdoc * * @throws \Exception The exception in case of unexpected error */ @@ -109,7 +112,7 @@ public function doRun(Console\Input\InputInterface $input, Console\Output\Output } /** - * {@inheritdoc} + * @inheritdoc */ protected function getDefaultCommands() { @@ -217,8 +220,7 @@ protected function getVendorCommands($objectManager) } /** - * Provides updated configuration in - * accordance to document root settings. + * Provides updated configuration in accordance to document root settings. * * @param array $config * @return array diff --git a/lib/internal/Magento/Framework/DB/Tree.php b/lib/internal/Magento/Framework/DB/Tree.php index 9890c6ef0d24..1aeaf122131f 100644 --- a/lib/internal/Magento/Framework/DB/Tree.php +++ b/lib/internal/Magento/Framework/DB/Tree.php @@ -3,6 +3,7 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Magento\Framework\DB; @@ -15,6 +16,7 @@ * Magento Library * * @SuppressWarnings(PHPMD.CouplingBetweenObjects) + * phpcs:ignoreFile * * @deprecated Not used anymore. */ @@ -300,7 +302,6 @@ public function getNodeInfo($nodeId) * @param string|int $nodeId * @param array $data * @return false|string - * @SuppressWarnings(PHPMD.ExitExpression) * * @deprecated Not used anymore. */ @@ -477,7 +478,6 @@ public function removeNode($nodeId) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.UnusedFormalParameter) - * @SuppressWarnings(PHPMD.ExitExpression) * * @deprecated Not used anymore. */ @@ -814,7 +814,6 @@ public function moveNode($eId, $pId, $aId = 0) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) * @SuppressWarnings(PHPMD.UnusedLocalVariable) - * @SuppressWarnings(PHPMD.ExitExpression) * * @deprecated Not used anymore. */ @@ -1041,7 +1040,6 @@ protected function _addExtTablesToSelect(Select &$select) * @param int $startLevel * @param int $endLevel * @return NodeSet - * @SuppressWarnings(PHPMD.ExitExpression) * * @deprecated Not used anymore. */ diff --git a/lib/internal/Magento/Framework/Data/Collection/Filesystem.php b/lib/internal/Magento/Framework/Data/Collection/Filesystem.php index 330ff4e975e8..b2bd352ea279 100644 --- a/lib/internal/Magento/Framework/Data/Collection/Filesystem.php +++ b/lib/internal/Magento/Framework/Data/Collection/Filesystem.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Framework\Data\Collection; use Magento\Framework\Data\Collection; @@ -27,63 +29,63 @@ class Filesystem extends \Magento\Framework\Data\Collection { /** - * Target directory + * Target directory. * * @var string */ protected $_targetDirs = []; /** - * Whether to collect files + * Whether to collect files. * * @var bool */ protected $_collectFiles = true; /** - * Whether to collect directories before files + * Whether to collect directories before files. * * @var bool */ protected $_dirsFirst = true; /** - * Whether to collect recursively + * Whether to collect recursively. * * @var bool */ protected $_collectRecursively = true; /** - * Whether to collect dirs + * Whether to collect dirs. * * @var bool */ protected $_collectDirs = false; /** - * \Directory names regex pre-filter + * \Directory names regex pre-filter. * * @var string */ protected $_allowedDirsMask = '/^[a-z0-9\.\-\_]+$/i'; /** - * Filenames regex pre-filter + * Filenames regex pre-filter. * * @var string */ protected $_allowedFilesMask = '/^[a-z0-9\.\-\_]+\.[a-z0-9]+$/i'; /** - * Disallowed filenames regex pre-filter match for better versatility + * Disallowed filenames regex pre-filter match for better versatility. * * @var string */ protected $_disallowedFilesMask = ''; /** - * Filter rendering helper variable + * Filter rendering helper variable. * * @var int * @see Collection::$_filter @@ -92,7 +94,7 @@ class Filesystem extends \Magento\Framework\Data\Collection private $_filterIncrement = 0; /** - * Filter rendering helper variable + * Filter rendering helper variable. * * @var array * @see Collection::$_filter @@ -101,7 +103,7 @@ class Filesystem extends \Magento\Framework\Data\Collection private $_filterBrackets = []; /** - * Filter rendering helper variable + * Filter rendering helper variable. * * @var string * @see Collection::$_filter @@ -110,22 +112,21 @@ class Filesystem extends \Magento\Framework\Data\Collection private $_filterEvalRendered = ''; /** - * Collecting items helper variable + * Collecting items helper variable. * * @var array */ protected $_collectedDirs = []; /** - * Collecting items helper variable + * Collecting items helper variable. * * @var array */ protected $_collectedFiles = []; /** - * Allowed dirs mask setter - * Set empty to not filter + * Allowed dirs mask setter. Set empty to not filter. * * @param string $regex * @return $this @@ -137,8 +138,7 @@ public function setDirsFilter($regex) } /** - * Allowed files mask setter - * Set empty to not filter + * Allowed files mask setter. Set empty to not filter. * * @param string $regex * @return $this @@ -150,8 +150,7 @@ public function setFilesFilter($regex) } /** - * Disallowed files mask setter - * Set empty value to not use this filter + * Disallowed files mask setter. Set empty value to not use this filter. * * @param string $regex * @return $this @@ -163,7 +162,7 @@ public function setDisallowedFilesFilter($regex) } /** - * Set whether to collect dirs + * Set whether to collect dirs. * * @param bool $value * @return $this @@ -175,7 +174,7 @@ public function setCollectDirs($value) } /** - * Set whether to collect files + * Set whether to collect files. * * @param bool $value * @return $this @@ -187,7 +186,7 @@ public function setCollectFiles($value) } /** - * Set whether to collect recursively + * Set whether to collect recursively. * * @param bool $value * @return $this @@ -199,7 +198,7 @@ public function setCollectRecursively($value) } /** - * Target directory setter. Adds directory to be scanned + * Target directory setter. Adds directory to be scanned. * * @param string $value * @return $this @@ -209,6 +208,7 @@ public function addTargetDir($value) { $value = (string)$value; if (!is_dir($value)) { + // phpcs:ignore Magento2.Exceptions.DirectThrow throw new \Exception('Unable to set target directory.'); } $this->_targetDirs[$value] = $value; @@ -216,8 +216,7 @@ public function addTargetDir($value) } /** - * Set whether to collect directories before files - * Works *before* sorting. + * Set whether to collect directories before files. Works *before* sorting. * * @param bool $value * @return $this @@ -229,7 +228,7 @@ public function setDirsFirst($value) } /** - * Get files from specified directory recursively (if needed) + * Get files from specified directory recursively (if needed). * * @param string|array $dir * @return void @@ -281,7 +280,7 @@ protected function _collectRecursive($dir) } /** - * Lauch data collecting + * Launch data collecting. * * @param bool $printQuery * @param bool $logQuery @@ -295,6 +294,7 @@ public function loadData($printQuery = false, $logQuery = false) return $this; } if (empty($this->_targetDirs)) { + // phpcs:disable Magento2.Exceptions.DirectThrow throw new \Exception('Please specify at least one target directory.'); } @@ -364,25 +364,22 @@ private function _generateAndFilterAndSort($attributeName) } /** - * Callback for sorting items - * Currently supports only sorting by one column + * Callback for sorting items. Currently supports only sorting by one column. * * @param array $a * @param array $b - * @return int|void + * @return int */ protected function _usort($a, $b) { foreach ($this->_orders as $key => $direction) { $result = $a[$key] > $b[$key] ? 1 : ($a[$key] < $b[$key] ? -1 : 0); return self::SORT_ORDER_ASC === strtoupper($direction) ? $result : -$result; - break; } } /** - * Set select order - * Currently supports only sorting by one column + * Set select order. Currently supports only sorting by one column. * * @param string $field * @param string $direction @@ -395,7 +392,7 @@ public function setOrder($field, $direction = self::SORT_ORDER_DESC) } /** - * Generate item row basing on the filename + * Generate item row basing on the filename. * * @param string $filename * @return array @@ -433,13 +430,11 @@ public function addCallbackFilter($field, $value, $type, $callback, $isInverted } /** - * The filters renderer and caller - * Applies to each row, renders once. + * The filters renderer and caller. Applies to each row, renders once. * * @param array $row * @return bool * @SuppressWarnings(PHPMD.UnusedFormalParameter) - * @SuppressWarnings(PHPMD.EvalExpression) */ protected function _filterRow($row) { @@ -469,14 +464,14 @@ protected function _filterRow($row) } $result = false; if ($this->_filterEvalRendered) { + // phpcs:ignore Squiz.PHP.Eval eval('$result = ' . $this->_filterEvalRendered . ';'); } return $result; } /** - * Invokes specified callback - * Skips, if there is no filtered key in the row + * Invokes specified callback. Skips, if there is no filtered key in the row. * * @param callback $callback * @param array $callbackParams @@ -493,7 +488,7 @@ protected function _invokeFilter($callback, $callbackParams) } /** - * Fancy field filter + * Fancy field filter. * * @param string $field * @param mixed $cond @@ -626,7 +621,7 @@ public function addFieldToFilter($field, $cond, $type = 'and') } /** - * Prepare a bracket into filters + * Prepare a bracket into filters. * * @param string $bracket * @param bool $isAnd @@ -643,7 +638,7 @@ protected function _addFilterBracket($bracket = '(', $isAnd = true) } /** - * Render condition sign before element, if required + * Render condition sign before element, if required. * * @param int $increment * @param bool $isAnd @@ -666,7 +661,8 @@ protected function _renderConditionBeforeFilterElement($increment, $isAnd) } /** - * Does nothing. Intentionally disabled parent method + * Does nothing. Intentionally disabled parent method. + * * @param string $field * @param string $value * @param string $type @@ -679,7 +675,7 @@ public function addFilter($field, $value, $type = 'and') } /** - * Get all ids of collected items + * Get all ids of collected items. * * @return array */ @@ -689,7 +685,7 @@ public function getAllIds() } /** - * Callback method for 'like' fancy filter + * Callback method for 'like' fancy filter. * * @param string $field * @param mixed $filterValue @@ -700,6 +696,9 @@ public function getAllIds() */ public function filterCallbackLike($field, $filterValue, $row) { + // Forced to do this in order to keep backward compatibility for @api class. + // Strict typing must be added to this method next major release. + $filterValue = (string)$filterValue; $filterValue = trim(stripslashes($filterValue), '\''); $filterValue = trim($filterValue, '%'); $filterValueRegex = '(.*?)' . preg_quote($filterValue, '/') . '(.*?)'; @@ -708,7 +707,7 @@ public function filterCallbackLike($field, $filterValue, $row) } /** - * Callback method for 'eq' fancy filter + * Callback method for 'eq' fancy filter. * * @param string $field * @param mixed $filterValue @@ -723,7 +722,7 @@ public function filterCallbackEq($field, $filterValue, $row) } /** - * Callback method for 'in' fancy filter + * Callback method for 'in' fancy filter. * * @param string $field * @param mixed $filterValue @@ -738,7 +737,7 @@ public function filterCallbackInArray($field, $filterValue, $row) } /** - * Callback method for 'isnull' fancy filter + * Callback method for 'isnull' fancy filter. * * @param string $field * @param mixed $filterValue @@ -754,7 +753,7 @@ public function filterCallbackIsNull($field, $filterValue, $row) } /** - * Callback method for 'moreq' fancy filter + * Callback method for 'moreq' fancy filter. * * @param string $field * @param mixed $filterValue @@ -769,7 +768,7 @@ public function filterCallbackIsMoreThan($field, $filterValue, $row) } /** - * Callback method for 'lteq' fancy filter + * Callback method for 'lteq' fancy filter. * * @param string $field * @param mixed $filterValue diff --git a/lib/internal/Magento/Framework/Webapi/ErrorProcessor.php b/lib/internal/Magento/Framework/Webapi/ErrorProcessor.php index 6ffcaa0676a0..f9b6a32fc567 100644 --- a/lib/internal/Magento/Framework/Webapi/ErrorProcessor.php +++ b/lib/internal/Magento/Framework/Webapi/ErrorProcessor.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Framework\Webapi; use Magento\Framework\App\Filesystem\DirectoryList; @@ -172,7 +174,6 @@ public function maskException(\Exception $exception) * @param \Exception $exception * @param int $httpCode * @return void - * @SuppressWarnings(PHPMD.ExitExpression) */ public function renderException(\Exception $exception, $httpCode = self::DEFAULT_ERROR_HTTP_CODE) { @@ -188,6 +189,7 @@ public function renderException(\Exception $exception, $httpCode = self::DEFAULT $httpCode ); } + // phpcs:ignore Magento2.Security.LanguageConstruct.ExitUsage exit; } @@ -232,6 +234,7 @@ public function renderErrorMessage( header('HTTP/1.1 ' . ($httpCode ? $httpCode : self::DEFAULT_ERROR_HTTP_CODE)); header('Content-Type: ' . $mimeType . '; charset=' . self::DEFAULT_RESPONSE_CHARSET); } + // phpcs:ignore Magento2.Security.LanguageConstruct.DirectOutput echo $output; } diff --git a/pub/errors/processor.php b/pub/errors/processor.php index cff3a14921d3..ab21f791bc02 100644 --- a/pub/errors/processor.php +++ b/pub/errors/processor.php @@ -3,6 +3,8 @@ * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Magento\Framework\Error; use Magento\Framework\Serialize\Serializer\Json; @@ -11,6 +13,7 @@ * Error processor * * @SuppressWarnings(PHPMD.TooManyFields) + * phpcs:ignoreFile */ class Processor { @@ -501,7 +504,6 @@ public function saveReport($reportData) * * @param int $reportId * @return void - * @SuppressWarnings(PHPMD.ExitExpression) */ public function loadReport($reportId) {