|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * PHPCSExtra, a collection of sniffs and standards for use with PHP_CodeSniffer. |
| 4 | + * |
| 5 | + * @package PHPCSExtra |
| 6 | + * @copyright 2020 PHPCSExtra Contributors |
| 7 | + * @license https://opensource.org/licenses/LGPL-3.0 LGPL3 |
| 8 | + * @link https://github.com/PHPCSStandards/PHPCSExtra |
| 9 | + */ |
| 10 | + |
| 11 | +namespace PHPCSExtra\Universal\Sniffs\PHP; |
| 12 | + |
| 13 | +use PHP_CodeSniffer\Files\File; |
| 14 | +use PHP_CodeSniffer\Sniffs\Sniff; |
| 15 | + |
| 16 | +/** |
| 17 | + * Enforce that the "PHP" in a PHP open tag is lowercase. |
| 18 | + * |
| 19 | + * @since 1.2.0 |
| 20 | + */ |
| 21 | +final class LowercasePHPTagSniff implements Sniff |
| 22 | +{ |
| 23 | + |
| 24 | + /** |
| 25 | + * Name of the metric. |
| 26 | + * |
| 27 | + * @since 1.2.0 |
| 28 | + * |
| 29 | + * @var string |
| 30 | + */ |
| 31 | + const METRIC_NAME = 'PHP open tag case'; |
| 32 | + |
| 33 | + /** |
| 34 | + * Registers the tokens that this sniff wants to listen for. |
| 35 | + * |
| 36 | + * @since 1.2.0 |
| 37 | + * |
| 38 | + * @return array<int> |
| 39 | + */ |
| 40 | + public function register() |
| 41 | + { |
| 42 | + return [\T_OPEN_TAG]; |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * Processes this test, when one of its tokens is encountered. |
| 47 | + * |
| 48 | + * @since 1.2.0 |
| 49 | + * |
| 50 | + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. |
| 51 | + * @param int $stackPtr The position of the current token |
| 52 | + * in the stack passed in $tokens. |
| 53 | + * |
| 54 | + * @return void |
| 55 | + */ |
| 56 | + public function process(File $phpcsFile, $stackPtr) |
| 57 | + { |
| 58 | + $tokens = $phpcsFile->getTokens(); |
| 59 | + $content = $tokens[$stackPtr]['content']; |
| 60 | + $contentLC = \strtolower($content); |
| 61 | + |
| 62 | + if ($contentLC === $content) { |
| 63 | + $phpcsFile->recordMetric($stackPtr, self::METRIC_NAME, 'lowercase'); |
| 64 | + return; |
| 65 | + } |
| 66 | + |
| 67 | + $errorCode = ''; |
| 68 | + if (\strtoupper($content) === $content) { |
| 69 | + $errorCode = 'Uppercase'; |
| 70 | + $phpcsFile->recordMetric($stackPtr, self::METRIC_NAME, 'uppercase'); |
| 71 | + } else { |
| 72 | + $errorCode = 'Mixedcase'; |
| 73 | + $phpcsFile->recordMetric($stackPtr, self::METRIC_NAME, 'mixed case'); |
| 74 | + } |
| 75 | + |
| 76 | + $fix = $phpcsFile->addFixableError( |
| 77 | + 'The php open tag should be in lowercase. Found: %s', |
| 78 | + $stackPtr, |
| 79 | + $errorCode, |
| 80 | + [\trim($content)] |
| 81 | + ); |
| 82 | + |
| 83 | + if ($fix === true) { |
| 84 | + $phpcsFile->fixer->replaceToken($stackPtr, $contentLC); |
| 85 | + } |
| 86 | + } |
| 87 | +} |
0 commit comments