ZeroUnitsSniff.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Sniffs\Less;
  7. use PHP_CodeSniffer\Sniffs\Sniff;
  8. use PHP_CodeSniffer\Files\File;
  9. /**
  10. * Class ZeroUnitsSniff
  11. *
  12. * Ensure that units for 0 is not specified
  13. * Omit leading "0"s in values, use dot instead
  14. *
  15. * @link https://devdocs.magento.com/guides/v2.0/coding-standards/code-standard-less.html#and-units
  16. * @link https://devdocs.magento.com/guides/v2.0/coding-standards/code-standard-less.html#floating-values
  17. */
  18. class ZeroUnitsSniff implements Sniff
  19. {
  20. const CSS_PROPERTY_UNIT_PX = 'px';
  21. const CSS_PROPERTY_UNIT_EM = 'em';
  22. const CSS_PROPERTY_UNIT_REM = 'rem';
  23. /**
  24. * List of available CSS Property units
  25. *
  26. * @var array
  27. */
  28. private $units = [
  29. self::CSS_PROPERTY_UNIT_PX,
  30. self::CSS_PROPERTY_UNIT_EM,
  31. self::CSS_PROPERTY_UNIT_REM,
  32. ];
  33. /**
  34. * A list of tokenizers this sniff supports.
  35. *
  36. * @var array
  37. */
  38. public $supportedTokenizers = [TokenizerSymbolsInterface::TOKENIZER_CSS];
  39. /**
  40. * @inheritdoc
  41. */
  42. public function register()
  43. {
  44. return [T_LNUMBER, T_DNUMBER];
  45. }
  46. /**
  47. * @inheritdoc
  48. */
  49. public function process(File $phpcsFile, $stackPtr)
  50. {
  51. $tokens = $phpcsFile->getTokens();
  52. $tokenCode = $tokens[$stackPtr]['code'];
  53. $tokenContent = $tokens[$stackPtr]['content'];
  54. $nextToken = $tokens[$stackPtr + 1];
  55. if (T_LNUMBER === $tokenCode
  56. && "0" === $tokenContent
  57. && T_STRING === $nextToken['code']
  58. && in_array($nextToken['content'], $this->units)
  59. ) {
  60. $phpcsFile->addError('Units specified for "0" value', $stackPtr, 'ZeroUnitFound');
  61. }
  62. if ((T_DNUMBER === $tokenCode)
  63. && 0 === strpos($tokenContent, "0")
  64. && ((float)$tokenContent < 1)
  65. ) {
  66. $phpcsFile->addError('Values starts from "0"', $stackPtr, 'ZeroUnitFound');
  67. }
  68. }
  69. }