Skip to content

Commit

Permalink
Avoid false positive with 'use function ...' lines
Browse files Browse the repository at this point in the history
  • Loading branch information
fredden committed Mar 25, 2024
1 parent 7521587 commit 53ea429
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 5 deletions.
31 changes: 28 additions & 3 deletions Magento2/Sniffs/Exceptions/TryProcessSystemResourcesSniff.php
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
<?php

/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

namespace Magento2\Sniffs\Exceptions;

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

/**
* Detects missing try-catch block when processing system resources.
Expand Down Expand Up @@ -43,7 +45,10 @@ class TryProcessSystemResourcesSniff implements Sniff
*/
public function register()
{
return [T_STRING];
return [
\T_USE,
\T_STRING,
];
}

/**
Expand All @@ -53,10 +58,30 @@ public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ namespace Foo\Bar;

use Exception;

use function stream_get_contents;

class StreamHandler
{
public function handleException()
Expand All @@ -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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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,
];
}
}

0 comments on commit 53ea429

Please sign in to comment.