NewExecutionDirectivesSniff.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. <?php
  2. /**
  3. * PHPCompatibility, an external standard for PHP_CodeSniffer.
  4. *
  5. * @package PHPCompatibility
  6. * @copyright 2012-2019 PHPCompatibility Contributors
  7. * @license https://opensource.org/licenses/LGPL-3.0 LGPL3
  8. * @link https://github.com/PHPCompatibility/PHPCompatibility
  9. */
  10. namespace PHPCompatibility\Sniffs\ControlStructures;
  11. use PHPCompatibility\AbstractNewFeatureSniff;
  12. use PHPCompatibility\PHPCSHelper;
  13. use PHP_CodeSniffer_File as File;
  14. use PHP_CodeSniffer_Tokens as Tokens;
  15. /**
  16. * Check for valid execution directives set with `declare()`.
  17. *
  18. * The sniff contains three distinct checks:
  19. * - Check if the execution directive used is valid. PHP currently only supports
  20. * three execution directives.
  21. * - Check if the execution directive used is available in the PHP versions
  22. * for which support is being checked.
  23. * In the case of the `encoding` directive on PHP 5.3, support is conditional
  24. * on the `--enable-zend-multibyte` compilation option. This will be indicated as such.
  25. * - Check whether the value for the directive is valid.
  26. *
  27. * PHP version All
  28. *
  29. * @link https://www.php.net/manual/en/control-structures.declare.php
  30. * @link https://wiki.php.net/rfc/scalar_type_hints_v5#strict_types_declare_directive
  31. *
  32. * @since 7.0.3
  33. * @since 7.1.0 Now extends the `AbstractNewFeatureSniff` instead of the base `Sniff` class.
  34. */
  35. class NewExecutionDirectivesSniff extends AbstractNewFeatureSniff
  36. {
  37. /**
  38. * A list of new execution directives
  39. *
  40. * The array lists : version number with false (not present) or true (present).
  41. * If the execution order is conditional, add the condition as a string to the version nr.
  42. * If's sufficient to list the first version where the execution directive appears.
  43. *
  44. * @since 7.0.3
  45. *
  46. * @var array(string => array(string => bool|string|array))
  47. */
  48. protected $newDirectives = array(
  49. 'ticks' => array(
  50. '3.1' => false,
  51. '4.0' => true,
  52. 'valid_value_callback' => 'isNumeric',
  53. ),
  54. 'encoding' => array(
  55. '5.2' => false,
  56. '5.3' => '--enable-zend-multibyte', // Directive ignored unless.
  57. '5.4' => true,
  58. 'valid_value_callback' => 'validEncoding',
  59. ),
  60. 'strict_types' => array(
  61. '5.6' => false,
  62. '7.0' => true,
  63. 'valid_values' => array(1),
  64. ),
  65. );
  66. /**
  67. * Tokens to ignore when trying to find the value for the directive.
  68. *
  69. * @since 7.0.3
  70. *
  71. * @var array
  72. */
  73. protected $ignoreTokens = array();
  74. /**
  75. * Returns an array of tokens this test wants to listen for.
  76. *
  77. * @since 7.0.3
  78. *
  79. * @return array
  80. */
  81. public function register()
  82. {
  83. $this->ignoreTokens = Tokens::$emptyTokens;
  84. $this->ignoreTokens[\T_EQUAL] = \T_EQUAL;
  85. return array(\T_DECLARE);
  86. }
  87. /**
  88. * Processes this test, when one of its tokens is encountered.
  89. *
  90. * @since 7.0.3
  91. *
  92. * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
  93. * @param int $stackPtr The position of the current token in
  94. * the stack passed in $tokens.
  95. *
  96. * @return void
  97. */
  98. public function process(File $phpcsFile, $stackPtr)
  99. {
  100. $tokens = $phpcsFile->getTokens();
  101. if (isset($tokens[$stackPtr]['parenthesis_opener'], $tokens[$stackPtr]['parenthesis_closer']) === true) {
  102. $openParenthesis = $tokens[$stackPtr]['parenthesis_opener'];
  103. $closeParenthesis = $tokens[$stackPtr]['parenthesis_closer'];
  104. } else {
  105. if (version_compare(PHPCSHelper::getVersion(), '2.3.4', '>=')) {
  106. return;
  107. }
  108. // Deal with PHPCS 2.3.0-2.3.3 which do not yet set the parenthesis properly for declare statements.
  109. $openParenthesis = $phpcsFile->findNext(\T_OPEN_PARENTHESIS, ($stackPtr + 1), null, false, null, true);
  110. if ($openParenthesis === false || isset($tokens[$openParenthesis]['parenthesis_closer']) === false) {
  111. return;
  112. }
  113. $closeParenthesis = $tokens[$openParenthesis]['parenthesis_closer'];
  114. }
  115. $directivePtr = $phpcsFile->findNext(\T_STRING, ($openParenthesis + 1), $closeParenthesis, false);
  116. if ($directivePtr === false) {
  117. return;
  118. }
  119. $directiveContent = $tokens[$directivePtr]['content'];
  120. if (isset($this->newDirectives[$directiveContent]) === false) {
  121. $error = 'Declare can only be used with the directives %s. Found: %s';
  122. $data = array(
  123. implode(', ', array_keys($this->newDirectives)),
  124. $directiveContent,
  125. );
  126. $phpcsFile->addError($error, $stackPtr, 'InvalidDirectiveFound', $data);
  127. } else {
  128. // Check for valid directive for version.
  129. $itemInfo = array(
  130. 'name' => $directiveContent,
  131. );
  132. $this->handleFeature($phpcsFile, $stackPtr, $itemInfo);
  133. // Check for valid directive value.
  134. $valuePtr = $phpcsFile->findNext($this->ignoreTokens, $directivePtr + 1, $closeParenthesis, true);
  135. if ($valuePtr === false) {
  136. return;
  137. }
  138. $this->addWarningOnInvalidValue($phpcsFile, $valuePtr, $directiveContent);
  139. }
  140. }
  141. /**
  142. * Determine whether an error/warning should be thrown for an item based on collected information.
  143. *
  144. * @since 7.1.0
  145. *
  146. * @param array $errorInfo Detail information about an item.
  147. *
  148. * @return bool
  149. */
  150. protected function shouldThrowError(array $errorInfo)
  151. {
  152. return ($errorInfo['not_in_version'] !== '' || $errorInfo['conditional_version'] !== '');
  153. }
  154. /**
  155. * Get the relevant sub-array for a specific item from a multi-dimensional array.
  156. *
  157. * @since 7.1.0
  158. *
  159. * @param array $itemInfo Base information about the item.
  160. *
  161. * @return array Version and other information about the item.
  162. */
  163. public function getItemArray(array $itemInfo)
  164. {
  165. return $this->newDirectives[$itemInfo['name']];
  166. }
  167. /**
  168. * Get an array of the non-PHP-version array keys used in a sub-array.
  169. *
  170. * @since 7.1.0
  171. *
  172. * @return array
  173. */
  174. protected function getNonVersionArrayKeys()
  175. {
  176. return array(
  177. 'valid_value_callback',
  178. 'valid_values',
  179. );
  180. }
  181. /**
  182. * Retrieve the relevant detail (version) information for use in an error message.
  183. *
  184. * @since 7.1.0
  185. *
  186. * @param array $itemArray Version and other information about the item.
  187. * @param array $itemInfo Base information about the item.
  188. *
  189. * @return array
  190. */
  191. public function getErrorInfo(array $itemArray, array $itemInfo)
  192. {
  193. $errorInfo = parent::getErrorInfo($itemArray, $itemInfo);
  194. $errorInfo['conditional_version'] = '';
  195. $errorInfo['condition'] = '';
  196. $versionArray = $this->getVersionArray($itemArray);
  197. if (empty($versionArray) === false) {
  198. foreach ($versionArray as $version => $present) {
  199. if (\is_string($present) === true && $this->supportsBelow($version) === true) {
  200. // We cannot test for compilation option (ok, except by scraping the output of phpinfo...).
  201. $errorInfo['conditional_version'] = $version;
  202. $errorInfo['condition'] = $present;
  203. }
  204. }
  205. }
  206. return $errorInfo;
  207. }
  208. /**
  209. * Get the error message template for this sniff.
  210. *
  211. * @since 7.1.0
  212. *
  213. * @return string
  214. */
  215. protected function getErrorMsgTemplate()
  216. {
  217. return 'Directive ' . parent::getErrorMsgTemplate();
  218. }
  219. /**
  220. * Generates the error or warning for this item.
  221. *
  222. * @since 7.0.3
  223. * @since 7.1.0 This method now overloads the method from the `AbstractNewFeatureSniff` class.
  224. * - Renamed from `maybeAddError()` to `addError()`.
  225. * - Changed visibility from `protected` to `public`.
  226. *
  227. * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
  228. * @param int $stackPtr The position of the relevant token in
  229. * the stack.
  230. * @param array $itemInfo Base information about the item.
  231. * @param array $errorInfo Array with detail (version) information
  232. * relevant to the item.
  233. *
  234. * @return void
  235. */
  236. public function addError(File $phpcsFile, $stackPtr, array $itemInfo, array $errorInfo)
  237. {
  238. if ($errorInfo['not_in_version'] !== '') {
  239. parent::addError($phpcsFile, $stackPtr, $itemInfo, $errorInfo);
  240. } elseif ($errorInfo['conditional_version'] !== '') {
  241. $error = 'Directive %s is present in PHP version %s but will be disregarded unless PHP is compiled with %s';
  242. $errorCode = $this->stringToErrorCode($itemInfo['name']) . 'WithConditionFound';
  243. $data = array(
  244. $itemInfo['name'],
  245. $errorInfo['conditional_version'],
  246. $errorInfo['condition'],
  247. );
  248. $phpcsFile->addWarning($error, $stackPtr, $errorCode, $data);
  249. }
  250. }
  251. /**
  252. * Generates a error or warning for this sniff.
  253. *
  254. * @since 7.0.3
  255. * @since 7.0.6 Renamed from `addErrorOnInvalidValue()` to `addWarningOnInvalidValue()`.
  256. *
  257. * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
  258. * @param int $stackPtr The position of the execution directive value
  259. * in the token array.
  260. * @param string $directive The directive.
  261. *
  262. * @return void
  263. */
  264. protected function addWarningOnInvalidValue(File $phpcsFile, $stackPtr, $directive)
  265. {
  266. $tokens = $phpcsFile->getTokens();
  267. $value = $tokens[$stackPtr]['content'];
  268. if (isset(Tokens::$stringTokens[$tokens[$stackPtr]['code']]) === true) {
  269. $value = $this->stripQuotes($value);
  270. }
  271. $isError = false;
  272. if (isset($this->newDirectives[$directive]['valid_values'])) {
  273. if (\in_array($value, $this->newDirectives[$directive]['valid_values']) === false) {
  274. $isError = true;
  275. }
  276. } elseif (isset($this->newDirectives[$directive]['valid_value_callback'])) {
  277. $valid = \call_user_func(array($this, $this->newDirectives[$directive]['valid_value_callback']), $value);
  278. if ($valid === false) {
  279. $isError = true;
  280. }
  281. }
  282. if ($isError === true) {
  283. $error = 'The execution directive %s does not seem to have a valid value. Please review. Found: %s';
  284. $errorCode = $this->stringToErrorCode($directive) . 'InvalidValueFound';
  285. $data = array(
  286. $directive,
  287. $value,
  288. );
  289. $phpcsFile->addWarning($error, $stackPtr, $errorCode, $data);
  290. }
  291. }
  292. /**
  293. * Check whether a value is numeric.
  294. *
  295. * Callback function to test whether the value for an execution directive is valid.
  296. *
  297. * @since 7.0.3
  298. *
  299. * @param mixed $value The value to test.
  300. *
  301. * @return bool
  302. */
  303. protected function isNumeric($value)
  304. {
  305. return is_numeric($value);
  306. }
  307. /**
  308. * Check whether a value is a valid encoding.
  309. *
  310. * Callback function to test whether the value for an execution directive is valid.
  311. *
  312. * @since 7.0.3
  313. *
  314. * @param mixed $value The value to test.
  315. *
  316. * @return bool
  317. */
  318. protected function validEncoding($value)
  319. {
  320. static $encodings;
  321. if (isset($encodings) === false && function_exists('mb_list_encodings')) {
  322. $encodings = mb_list_encodings();
  323. }
  324. if (empty($encodings) || \is_array($encodings) === false) {
  325. // If we can't test the encoding, let it pass through.
  326. return true;
  327. }
  328. return \in_array($value, $encodings, true);
  329. }
  330. }