Debian Codegraph @

vendor/symfony/console/Helper/ProgressIndicator.php

raw
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Console\Helper;
13
14 use Symfony\Component\Console\Exception\InvalidArgumentException;
15 use Symfony\Component\Console\Exception\LogicException;
16 use Symfony\Component\Console\Output\ConsoleSectionOutput;
17 use Symfony\Component\Console\Output\OutputInterface;
18
19 /**
20 * @author Kevin Bond <[email protected]>
21 */
22 class ProgressIndicator
23 {
24 private const FORMATS = [
25 'normal' => ' %indicator% %message%',
26 'normal_no_ansi' => ' %message%',
27
28 'verbose' => ' %indicator% %message% (%elapsed:6s%)',
29 'verbose_no_ansi' => ' %message% (%elapsed:6s%)',
30
31 'very_verbose' => ' %indicator% %message% (%elapsed:6s%, %memory:6s%)',
32 'very_verbose_no_ansi' => ' %message% (%elapsed:6s%, %memory:6s%)',
33 ];
34
35 private int $startTime;
36 private ?string $format = null;
37 private ?string $message = null;
38 private array $indicatorValues;
39 private int $indicatorCurrent;
40 private string $finishedIndicatorValue;
41 private float $indicatorUpdateTime;
42 private bool $started = false;
43 private bool $finished = false;
44
45 /**
46 * @var array<string, callable>
47 */
48 private static array $formatters;
49
50 /**
51 * @param int $indicatorChangeInterval Change interval in milliseconds
52 * @param array|null $indicatorValues Animated indicator characters
53 */
54 public function __construct(
55 private OutputInterface $output,
56 ?string $format = null,
57 private int $indicatorChangeInterval = 100,
58 ?array $indicatorValues = null,
59 ?string $finishedIndicatorValue = null,
60 ) {
61 $format ??= $this->determineBestFormat();
62 $indicatorValues ??= ['-', '\\', '|', '/'];
63 $indicatorValues = array_values($indicatorValues);
64 $finishedIndicatorValue ??= '✔';
65
66 if (2 > \count($indicatorValues)) {
67 throw new InvalidArgumentException('Must have at least 2 indicator value characters.');
68 }
69
70 $this->format = self::getFormatDefinition($format);
71 $this->indicatorValues = $indicatorValues;
72 $this->finishedIndicatorValue = $finishedIndicatorValue;
73 $this->startTime = time();
74 }
75
76 /**
77 * Sets the current indicator message.
78 */
79 public function setMessage(?string $message): void
80 {
81 $this->message = $message;
82
83 $this->display();
84 }
85
86 /**
87 * Starts the indicator output.
88 */
89 public function start(string $message): void
90 {
91 if ($this->started) {
92 throw new LogicException('Progress indicator already started.');
93 }
94
95 $this->message = $message;
96 $this->started = true;
97 $this->finished = false;
98 $this->startTime = time();
99 $this->indicatorUpdateTime = $this->getCurrentTimeInMilliseconds() + $this->indicatorChangeInterval;
100 $this->indicatorCurrent = 0;
101
102 $this->display();
103 }
104
105 /**
106 * Advances the indicator.
107 */
108 public function advance(): void
109 {
110 if (!$this->started) {
111 throw new LogicException('Progress indicator has not yet been started.');
112 }
113
114 if (!$this->output->isDecorated()) {
115 return;
116 }
117
118 $currentTime = $this->getCurrentTimeInMilliseconds();
119
120 if ($currentTime < $this->indicatorUpdateTime) {
121 return;
122 }
123
124 $this->indicatorUpdateTime = $currentTime + $this->indicatorChangeInterval;
125 ++$this->indicatorCurrent;
126
127 $this->display();
128 }
129
130 /**
131 * Finish the indicator with message.
132 *
133 * @param ?string $finishedIndicator
134 */
135 public function finish(string $message/* , ?string $finishedIndicator = null */): void
136 {
137 $finishedIndicator = 1 < \func_num_args() ? func_get_arg(1) : null;
138 if (null !== $finishedIndicator && !\is_string($finishedIndicator)) {
139 throw new \TypeError(\sprintf('Argument 2 passed to "%s()" must be of the type string or null, "%s" given.', __METHOD__, get_debug_type($finishedIndicator)));
140 }
141
142 if (!$this->started) {
143 throw new LogicException('Progress indicator has not yet been started.');
144 }
145
146 if (null !== $finishedIndicator) {
147 $this->finishedIndicatorValue = $finishedIndicator;
148 }
149
150 $this->finished = true;
151 $this->message = $message;
152 $this->display();
153 if (!$this->output instanceof ConsoleSectionOutput) {
154 $this->output->writeln('');
155 }
156 $this->started = false;
157 }
158
159 /**
160 * Gets the format for a given name.
161 */
162 public static function getFormatDefinition(string $name): ?string
163 {
164 return self::FORMATS[$name] ?? null;
165 }
166
167 /**
168 * Sets a placeholder formatter for a given name.
169 *
170 * This method also allow you to override an existing placeholder.
171 */
172 public static function setPlaceholderFormatterDefinition(string $name, callable $callable): void
173 {
174 self::$formatters ??= self::initPlaceholderFormatters();
175
176 self::$formatters[$name] = $callable;
177 }
178
179 /**
180 * Gets the placeholder formatter for a given name (including the delimiter char like %).
181 */
182 public static function getPlaceholderFormatterDefinition(string $name): ?callable
183 {
184 self::$formatters ??= self::initPlaceholderFormatters();
185
186 return self::$formatters[$name] ?? null;
187 }
188
189 private function display(): void
190 {
191 if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) {
192 return;
193 }
194
195 $this->overwrite(preg_replace_callback('{%([a-z\-_]+)(?:\:([^%]+))?%}i', function ($matches) {
196 if ($formatter = self::getPlaceholderFormatterDefinition($matches[1])) {
197 return $formatter($this);
198 }
199
200 return $matches[0];
201 }, $this->format ?? ''));
202 }
203
204 private function determineBestFormat(): string
205 {
206 return match ($this->output->getVerbosity()) {
207 // OutputInterface::VERBOSITY_QUIET: display is disabled anyway
208 OutputInterface::VERBOSITY_VERBOSE => $this->output->isDecorated() ? 'verbose' : 'verbose_no_ansi',
209 OutputInterface::VERBOSITY_VERY_VERBOSE,
210 OutputInterface::VERBOSITY_DEBUG => $this->output->isDecorated() ? 'very_verbose' : 'very_verbose_no_ansi',
211 default => $this->output->isDecorated() ? 'normal' : 'normal_no_ansi',
212 };
213 }
214
215 /**
216 * Overwrites a previous message to the output.
217 */
218 private function overwrite(string $message): void
219 {
220 if ($this->output instanceof ConsoleSectionOutput) {
221 $this->output->overwrite($message);
222 } elseif ($this->output->isDecorated()) {
223 $this->output->write("\x0D\x1B[2K");
224 $this->output->write($message);
225 } else {
226 $this->output->writeln($message);
227 }
228 }
229
230 private function getCurrentTimeInMilliseconds(): float
231 {
232 return round(microtime(true) * 1000);
233 }
234
235 /**
236 * @return array<string, \Closure>
237 */
238 private static function initPlaceholderFormatters(): array
239 {
240 return [
241 'indicator' => static fn (self $indicator) => $indicator->finished ? $indicator->finishedIndicatorValue : $indicator->indicatorValues[$indicator->indicatorCurrent % \count($indicator->indicatorValues)],
242 'message' => static fn (self $indicator) => $indicator->message,
243 'elapsed' => static fn (self $indicator) => Helper::formatTime(time() - $indicator->startTime, 2),
244 'memory' => static fn () => Helper::formatMemory(memory_get_usage(true)),
245 ];
246 }
247 }