DiffConsoleFormatter.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of PHP CS Fixer.
  5. *
  6. * (c) Fabien Potencier <fabien@symfony.com>
  7. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  8. *
  9. * This source file is subject to the MIT license that is bundled
  10. * with this source code in the file LICENSE.
  11. */
  12. namespace PhpCsFixer\Differ;
  13. use PhpCsFixer\Preg;
  14. use Symfony\Component\Console\Formatter\OutputFormatter;
  15. /**
  16. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  17. *
  18. * @internal
  19. */
  20. final class DiffConsoleFormatter
  21. {
  22. private bool $isDecoratedOutput;
  23. private string $template;
  24. public function __construct(bool $isDecoratedOutput, string $template = '%s')
  25. {
  26. $this->isDecoratedOutput = $isDecoratedOutput;
  27. $this->template = $template;
  28. }
  29. public function format(string $diff, string $lineTemplate = '%s'): string
  30. {
  31. $isDecorated = $this->isDecoratedOutput;
  32. $template = $isDecorated
  33. ? $this->template
  34. : Preg::replace('/<[^<>]+>/', '', $this->template);
  35. return sprintf(
  36. $template,
  37. implode(
  38. PHP_EOL,
  39. array_map(
  40. static function (string $line) use ($isDecorated, $lineTemplate): string {
  41. if ($isDecorated) {
  42. $count = 0;
  43. $line = Preg::replaceCallback(
  44. '/^([+\-@].*)/',
  45. static function (array $matches): string {
  46. if ('+' === $matches[0][0]) {
  47. $colour = 'green';
  48. } elseif ('-' === $matches[0][0]) {
  49. $colour = 'red';
  50. } else {
  51. $colour = 'cyan';
  52. }
  53. return sprintf('<fg=%s>%s</fg=%s>', $colour, OutputFormatter::escape($matches[0]), $colour);
  54. },
  55. $line,
  56. 1,
  57. $count
  58. );
  59. if (0 === $count) {
  60. $line = OutputFormatter::escape($line);
  61. }
  62. }
  63. return sprintf($lineTemplate, $line);
  64. },
  65. Preg::split('#\R#u', $diff)
  66. )
  67. )
  68. );
  69. }
  70. }