-
Notifications
You must be signed in to change notification settings - Fork 159
/
Copy pathTryProcessSystemResourcesSniff.php
81 lines (71 loc) · 1.83 KB
/
TryProcessSystemResourcesSniff.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
/**
* Copyright 2019 Adobe
* All Rights Reserved.
*/
declare(strict_types=1);
namespace Magento2\Sniffs\Exceptions;
use function array_slice;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;
/**
* Detects missing try-catch block when processing system resources.
*/
class TryProcessSystemResourcesSniff implements Sniff
{
/**
* String representation of warning.
*
* @var string
*/
protected $warningMessage = 'The code must be wrapped with a try block if the method uses system resources.';
/**
* Warning violation code.
*
* @var string
*/
protected $warningCode = 'MissingTryCatch';
/**
* Search for functions that start with.
*
* @var array
*/
protected $functions = [
'stream_',
'socket_',
];
/**
* @inheritDoc
*/
public function register()
{
return [T_STRING];
}
/**
* @inheritDoc
*/
public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
foreach ($this->functions as $function) {
if (strpos($tokens[$stackPtr]['content'], $function) !== 0) {
continue;
}
$tryPosition = $phpcsFile->findPrevious(T_TRY, $stackPtr - 1);
if ($tryPosition !== false) {
$tryTag = $tokens[$tryPosition];
$start = $tryTag['scope_opener'];
$end = $tryTag['scope_closer'];
if ($stackPtr > $start && $stackPtr < $end) {
// element is warped by try no check required
return;
}
}
$phpcsFile->addWarning(
$this->warningMessage,
$stackPtr,
$this->warningCode
);
}
}
}