MultilineArrayTrailingCommaFixer.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /*
  3. * This file is part of the Symfony 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\All;
  11. use Symfony\CS\AbstractFixer;
  12. use Symfony\CS\Token;
  13. use Symfony\CS\Tokens;
  14. /**
  15. * @author Sebastiaan Stok <s.stok@rollerscapes.net>
  16. */
  17. class MultilineArrayTrailingCommaFixer extends AbstractFixer
  18. {
  19. /**
  20. * {@inheritdoc}
  21. */
  22. public function fix(\SplFileInfo $file, $content)
  23. {
  24. $tokens = Tokens::fromCode($content);
  25. for ($index = $tokens->count() - 1; $index >= 0; --$index) {
  26. if ($tokens->isArray($index)) {
  27. $this->fixArray($tokens, $index);
  28. }
  29. }
  30. return $tokens->generateCode();
  31. }
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public function getDescription()
  36. {
  37. return 'PHP multi-line arrays should have a trailing comma.';
  38. }
  39. private function fixArray(Tokens $tokens, $index)
  40. {
  41. $bracesLevel = 0;
  42. // Skip only when it is an array, for short arrays we need the brace for correct
  43. // level counting
  44. if ($tokens[$index]->isGivenKind(T_ARRAY)) {
  45. ++$index;
  46. }
  47. if (!$tokens->isArrayMultiLine($index)) {
  48. return ;
  49. }
  50. for ($c = $tokens->count(); $index < $c; ++$index) {
  51. $token = $tokens[$index];
  52. if ('(' === $token->content || '[' === $token->content) {
  53. ++$bracesLevel;
  54. continue;
  55. }
  56. if (')' === $token->content || ']' === $token->content) {
  57. --$bracesLevel;
  58. if (0 !== $bracesLevel) {
  59. continue;
  60. }
  61. $foundIndex = null;
  62. $prevToken = $tokens->getTokenNotOfKindSibling($index, -1, array(array(T_WHITESPACE), array(T_COMMENT), array(T_DOC_COMMENT)), $foundIndex);
  63. if (',' !== $prevToken->content) {
  64. $tokens->insertAt($foundIndex + 1, array(new Token(',')));
  65. }
  66. break;
  67. }
  68. }
  69. }
  70. }