From 5fb6d019ad7c93b407c3baf72bda86c188300c46 Mon Sep 17 00:00:00 2001 From: Dan Wallis Date: Mon, 25 Mar 2024 18:28:26 +0000 Subject: [PATCH] Avoid false positive with 'use function ...' lines --- .../TryProcessSystemResourcesSniff.php | 32 +++++++++++++++++-- .../TryProcessSystemResourcesUnitTest.inc | 6 ++++ .../TryProcessSystemResourcesUnitTest.php | 5 +-- 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/Magento2/Sniffs/Exceptions/TryProcessSystemResourcesSniff.php b/Magento2/Sniffs/Exceptions/TryProcessSystemResourcesSniff.php index 0fa28149..3b26c3ea 100644 --- a/Magento2/Sniffs/Exceptions/TryProcessSystemResourcesSniff.php +++ b/Magento2/Sniffs/Exceptions/TryProcessSystemResourcesSniff.php @@ -1,13 +1,15 @@ getTokens(); + if ($tokens[$stackPtr]['code'] === \T_USE) { + $previousToken = $phpcsFile->findPrevious(Tokens::$emptyTokens, $stackPtr - 1, null, true); + $nextToken = $phpcsFile->findNext(Tokens::$emptyTokens, $stackPtr + 1, null, true); + $semicolon = $phpcsFile->findNext(T_SEMICOLON, $stackPtr + 1); + if ( + $previousToken !== false + && \in_array($tokens[$previousToken]['code'], [\T_OPEN_TAG, \T_SEMICOLON], true) + && $nextToken !== false + && $tokens[$nextToken]['code'] === \T_STRING + && $tokens[$nextToken]['content'] === 'function' + && $semicolon !== false + ) { + // We have found a 'use function ...' statement; skip over this. + return $semicolon; + } + + // This is not a 'use function ...' statement. + return; + } + foreach ($this->functions as $function) { if (strpos($tokens[$stackPtr]['content'], $function) !== 0) { continue; } + $tryPosition = $phpcsFile->findPrevious(T_TRY, $stackPtr - 1); if ($tryPosition !== false) { diff --git a/Magento2/Tests/Exceptions/TryProcessSystemResourcesUnitTest.inc b/Magento2/Tests/Exceptions/TryProcessSystemResourcesUnitTest.inc index 66f23840..b77c421a 100644 --- a/Magento2/Tests/Exceptions/TryProcessSystemResourcesUnitTest.inc +++ b/Magento2/Tests/Exceptions/TryProcessSystemResourcesUnitTest.inc @@ -4,6 +4,8 @@ namespace Foo\Bar; use Exception; +use function stream_get_contents; + class StreamHandler { public function handleException() @@ -26,4 +28,8 @@ function executeStream() socket_bind($sock); // Rule find: Try block detected when processing system resources socket_close($sock); + + $func = function () use (&$strChar) { + $strChar = stream_get_contents(STDIN, 1); + } } diff --git a/Magento2/Tests/Exceptions/TryProcessSystemResourcesUnitTest.php b/Magento2/Tests/Exceptions/TryProcessSystemResourcesUnitTest.php index a8b2d65e..9cbe820c 100644 --- a/Magento2/Tests/Exceptions/TryProcessSystemResourcesUnitTest.php +++ b/Magento2/Tests/Exceptions/TryProcessSystemResourcesUnitTest.php @@ -26,10 +26,11 @@ protected function getErrorList() protected function getWarningList() { return [ - 22 => 1, 24 => 1, 26 => 1, - 28 => 1 + 28 => 1, + 30 => 1, + 33 => 1, ]; } }