*
* @see \Rector\Tests\Console\Formatter\ColorConsoleDiffFormatterTest
*/
final class ColorConsoleDiffFormatter
{
/**
* @var string
* @see https://regex101.com/r/ovLMDF/1
*/
private const PLUS_START_REGEX = '#^(\\+.*)#';
/**
* @var string
* @see https://regex101.com/r/xwywpa/1
*/
private const MINUT_START_REGEX = '#^(\\-.*)#';
/**
* @var string
* @see https://regex101.com/r/CMlwa8/1
*/
private const AT_START_REGEX = '#^(@.*)#';
/**
* @readonly
* @var string
*/
private $template;
public function __construct()
{
$this->template = \sprintf(' ---------- begin diff ----------%s%%s%s ----------- end diff -----------' . \PHP_EOL, \PHP_EOL, \PHP_EOL);
}
public function format(string $diff) : string
{
return $this->formatWithTemplate($diff, $this->template);
}
private function formatWithTemplate(string $diff, string $template) : string
{
$escapedDiff = OutputFormatter::escape(\rtrim($diff));
$escapedDiffLines = NewLineSplitter::split($escapedDiff);
// remove description of added + remove; obvious on diffs
foreach ($escapedDiffLines as $key => $escapedDiffLine) {
if ($escapedDiffLine === '--- Original') {
unset($escapedDiffLines[$key]);
}
if ($escapedDiffLine === '+++ New') {
unset($escapedDiffLines[$key]);
}
}
$coloredLines = \array_map(function (string $string) : string {
$string = $this->makePlusLinesGreen($string);
$string = $this->makeMinusLinesRed($string);
$string = $this->makeAtNoteCyan($string);
if ($string === ' ') {
return '';
}
return $string;
}, $escapedDiffLines);
return \sprintf($template, \implode(\PHP_EOL, $coloredLines));
}
private function makePlusLinesGreen(string $string) : string
{
return Strings::replace($string, self::PLUS_START_REGEX, '$1');
}
private function makeMinusLinesRed(string $string) : string
{
return Strings::replace($string, self::MINUT_START_REGEX, '$1');
}
private function makeAtNoteCyan(string $string) : string
{
return Strings::replace($string, self::AT_START_REGEX, '$1');
}
}