4 * This file is part of the Behat.
5 * (c) Konstantin Kudryashov <ever.zet@gmail.com>
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
11 namespace Behat\Behat\Output\Node\Printer\Helper;
13 use Behat\Behat\Definition\Definition;
14 use Behat\Behat\Definition\Pattern\PatternTransformer;
15 use Behat\Testwork\Tester\Result\TestResult;
18 * Paints step text (with tokens) according to found definition.
20 * @author Konstantin Kudryashov <ever.zet@gmail.com>
22 final class StepTextPainter
25 * @var PatternTransformer
27 private $patternTransformer;
29 * @var ResultToStringConverter
31 private $resultConverter;
34 * Initializes painter.
36 * @param PatternTransformer $patternTransformer
37 * @param ResultToStringConverter $resultConverter
39 public function __construct(PatternTransformer $patternTransformer, ResultToStringConverter $resultConverter)
41 $this->patternTransformer = $patternTransformer;
42 $this->resultConverter = $resultConverter;
46 * Colorizes step text arguments according to definition.
49 * @param Definition $definition
50 * @param TestResult $result
54 public function paintText($text, Definition $definition, TestResult $result)
56 $regex = $this->patternTransformer->transformPatternToRegex($definition->getPattern());
57 $style = $this->resultConverter->convertResultToString($result);
58 $paramStyle = $style . '_param';
60 // If it's just a string - skip
61 if ('/' !== substr($regex, 0, 1)) {
65 // Find arguments with offsets
67 preg_match($regex, $text, $matches, PREG_OFFSET_CAPTURE);
68 array_shift($matches);
70 // Replace arguments with colorized ones
72 $lastReplacementPosition = 0;
73 foreach ($matches as $key => $match) {
74 if (!is_numeric($key) || -1 === $match[1] || false !== strpos($match[0], '<')) {
78 $offset = $match[1] + $shift;
82 if ($lastReplacementPosition > $offset) {
85 $lastReplacementPosition = $offset + strlen($value);
87 $begin = substr($text, 0, $offset);
88 $end = substr($text, $lastReplacementPosition);
89 $format = "{-$style}{+$paramStyle}%s{-$paramStyle}{+$style}";
90 $text = sprintf("%s{$format}%s", $begin, $value, $end);
92 // Keep track of how many extra characters are added
93 $shift += strlen($format) - 2;
94 $lastReplacementPosition += strlen($format) - 2;
97 // Replace "<", ">" with colorized ones
100 "{-$style}{+$paramStyle}\$1{-$paramStyle}{+$style}",