NativeFunctionCasingFixer.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. /*
  3. * This file is part of the PHP CS utility.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace Symfony\CS\Fixer\Contrib;
  11. use Symfony\CS\AbstractFixer;
  12. use Symfony\CS\Tokenizer\Tokens;
  13. /**
  14. * @author SpacePossum
  15. */
  16. final class NativeFunctionCasingFixer extends AbstractFixer
  17. {
  18. /**
  19. * {@inheritdoc}
  20. */
  21. public function fix(\SplFileInfo $file, $content)
  22. {
  23. static $nativeFunctionNames = null;
  24. if (null === $nativeFunctionNames) {
  25. $nativeFunctionNames = $this->getNativeFunctionNames();
  26. }
  27. $tokens = Tokens::fromCode($content);
  28. for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) {
  29. // test if we are at a function all
  30. if (!$tokens[$index]->isGivenKind(T_STRING)) {
  31. continue;
  32. }
  33. $next = $tokens->getNextMeaningfulToken($index);
  34. if (!$tokens[$next]->equals('(')) {
  35. $index = $next;
  36. continue;
  37. }
  38. $functionNamePrefix = $tokens->getPrevMeaningfulToken($index);
  39. if ($tokens[$functionNamePrefix]->isGivenKind(array(T_DOUBLE_COLON, T_NEW, T_OBJECT_OPERATOR, T_FUNCTION))) {
  40. continue;
  41. }
  42. // do not though the function call if it is to a function in a namespace other than the default
  43. if (
  44. $tokens[$functionNamePrefix]->isGivenKind(T_NS_SEPARATOR)
  45. && $tokens[$tokens->getPrevMeaningfulToken($functionNamePrefix)]->isGivenKind(T_STRING)
  46. ) {
  47. continue;
  48. }
  49. // test if the function call is to a native PHP function
  50. $lower = strtolower($tokens[$index]->getContent());
  51. if (!array_key_exists($lower, $nativeFunctionNames)) {
  52. continue;
  53. }
  54. $tokens[$index]->setContent($nativeFunctionNames[$lower]);
  55. $index = $next;
  56. }
  57. return $tokens->generateCode();
  58. }
  59. /**
  60. * {@inheritdoc}
  61. */
  62. public function getDescription()
  63. {
  64. return 'Function defined by PHP should be called using the correct casing.';
  65. }
  66. private function getNativeFunctionNames()
  67. {
  68. $allFunctions = get_defined_functions();
  69. $functions = array();
  70. foreach ($allFunctions['internal'] as $function) {
  71. $functions[strtolower($function)] = $function;
  72. }
  73. return $functions;
  74. }
  75. }