1<?php 2/** 3 * Ensure colours are defined in upper-case and use shortcuts where possible. 4 * 5 * @author Greg Sherwood <gsherwood@squiz.net> 6 * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) 7 * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence 8 */ 9 10namespace PHP_CodeSniffer\Standards\Squiz\Sniffs\CSS; 11 12use PHP_CodeSniffer\Files\File; 13use PHP_CodeSniffer\Sniffs\Sniff; 14 15class ColourDefinitionSniff implements Sniff 16{ 17 18 /** 19 * A list of tokenizers this sniff supports. 20 * 21 * @var array 22 */ 23 public $supportedTokenizers = ['CSS']; 24 25 26 /** 27 * Returns the token types that this sniff is interested in. 28 * 29 * @return int[] 30 */ 31 public function register() 32 { 33 return [T_COLOUR]; 34 35 }//end register() 36 37 38 /** 39 * Processes the tokens that this sniff is interested in. 40 * 41 * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. 42 * @param int $stackPtr The position in the stack where 43 * the token was found. 44 * 45 * @return void 46 */ 47 public function process(File $phpcsFile, $stackPtr) 48 { 49 $tokens = $phpcsFile->getTokens(); 50 $colour = $tokens[$stackPtr]['content']; 51 52 $expected = strtoupper($colour); 53 if ($colour !== $expected) { 54 $error = 'CSS colours must be defined in uppercase; expected %s but found %s'; 55 $data = [ 56 $expected, 57 $colour, 58 ]; 59 60 $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NotUpper', $data); 61 if ($fix === true) { 62 $phpcsFile->fixer->replaceToken($stackPtr, $expected); 63 } 64 } 65 66 // Now check if shorthand can be used. 67 if (strlen($colour) !== 7) { 68 return; 69 } 70 71 if ($colour[1] === $colour[2] && $colour[3] === $colour[4] && $colour[5] === $colour[6]) { 72 $expected = '#'.$colour[1].$colour[3].$colour[5]; 73 $error = 'CSS colours must use shorthand if available; expected %s but found %s'; 74 $data = [ 75 $expected, 76 $colour, 77 ]; 78 79 $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Shorthand', $data); 80 if ($fix === true) { 81 $phpcsFile->fixer->replaceToken($stackPtr, $expected); 82 } 83 } 84 85 }//end process() 86 87 88}//end class 89