8000 [Console] Deprecate Helper::strlen() for width() and length() · symfony/symfony@3c24aa9 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3c24aa9

Browse files
Nyholmfabpot
authored andcommitted
[Console] Deprecate Helper::strlen() for width() and length()
1 parent 30b73c7 commit 3c24aa9

13 files changed

+58
-46
lines changed

UPGRADE-5.3.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@ Asset
66

77
* Deprecated `RemoteJsonManifestVersionStrategy`, use `JsonManifestVersionStrategy` instead
88

9+
Console
10+
-------
11+
12+
* Deprecate `Helper::strlen()`, use `Helper::width()` instead.
13+
914
DoctrineBridge
1015
--------------
1116

UPGRADE-6.0.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ Console
2323
-------
2424

2525
* `Command::setHidden()` has a default value (`true`) for `$hidden` parameter
26+
* Remove `Helper::strlen()`, use `Helper::width()` instead.
2627

2728
DependencyInjection
2829
-------------------

src/Symfony/Component/Console/Application.php

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -699,7 +699,7 @@ public function find(string $name)
699699
$abbrevs = array_values($commands);
700700
$maxLen = 0;
701701
foreach ($abbrevs as $abbrev) {
702-
$maxLen = max(Helper::strlen($abbrev), $maxLen);
702+
$maxLen = max(Helper::width($abbrev), $maxLen);
703703
}
704704
$abbrevs = array_map(function ($cmd) use ($commandList, $usableWidth, $maxLen, &$commands) {
705705
if ($commandList[$cmd]->isHidden()) {
@@ -710,7 +710,7 @@ public function find(string $name)
710710

711711
$abbrev = str_pad($cmd, $maxLen, ' ').' '.$commandList[$cmd]->getDescription();
712712

713-
return Helper::strlen($abbrev) > $usableWidth ? Helper::substr($abbrev, 0, $usableWidth - 3).'...' : $abbrev;
713+
return Helper::width($abbrev) > $usableWidth ? Helper::substr($abbrev, 0, $usableWidth - 3).'...' : $abbrev;
714714
}, array_values($commands));
715715

716716
if (\count($commands) > 1) {
@@ -810,7 +810,7 @@ protected function doRenderThrowable(\Throwable $e, OutputInterface $output): vo
810810
if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
811811
$class = get_debug_type($e);
812812
$title = sprintf(' [%s%s] ', $class, 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : '');
813-
$len = Helper::strlen($title);
813+
$len = Helper::width($title);
814814
} else {
815815
$len = 0;
816816
}
@@ -826,7 +826,7 @@ protected function doRenderThrowable(\Throwable $e, OutputInterface $output): vo
826826
foreach ('' !== $message ? preg_split('/\r?\n/', $message) : [] as $line) {
827827
foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
828828
// pre-format lines to get the right string length
829-
$lineLength = Helper::strlen($line) + 4;
829+
$lineLength = Helper::width($line) + 4;
830830
$lines[] = [$line, $lineLength];
831831

832832
$len = max($lineLength, $len);
@@ -839,7 +839,7 @@ protected function doRenderThrowable(\Throwable $e, OutputInterface $output): vo
839839
}
840840
$messages[] = $emptyLine = sprintf('<error>%s</error>', str_repeat(' ', $len));
841841
if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
842-
$messages[] = sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - Helper::strlen($title))));
842+
$messages[] = sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - Helper::width($title))));
843843
}
844844
foreach ($lines as $line) {
845845
$messages[] = sprintf('<error> %s %s</error>', OutputFormatter::escape($line[0]), str_repeat(' ', $len - $line[1]));

src/Symfony/Component/Console/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ CHANGELOG
1111
* Add option `--short` to the `list` command
1212
* Add support 10000 for bright colors
1313
* Add `#[AsCommand]` attribute for declaring commands on PHP 8
14+
* Add `Helper::width()` and `Helper::length()`
1415

1516
5.2.0
1617
-----

src/Symfony/Component/Console/Descriptor/MarkdownDescriptor.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ protected function describeCommand(Command $command, array $options = [])
125125
if ($options['short'] ?? false) {
126126
$this->write(
127127
'`'.$command->getName()."`\n"
128-
.str_repeat('-', Helper::strlen($command->getName()) + 2)."\n\n"
128+
.str_repeat('-', Helper::width($command->getName()) + 2)."\n\n"
129129
.($command->getDescription() ? $command->getDescription()."\n\n" : '')
130130
.'### Usage'."\n\n"
131131
.array_reduce($command->getAliases(), function ($carry, $usage) {
@@ -140,7 +140,7 @@ protected function describeCommand(Command $command, array $options = [])
140140

141141
$this->write(
142142
'`'.$command->getName()."`\n"
143-
.str_repeat('-', Helper::strlen($command->getName()) + 2)."\n\n"
143+
.str_repeat('-', Helper::width($command->getName()) + 2)."\n\n"
144144
.($command->getDescription() ? $command->getDescription()."\n\n" : '')
145145
.'### Usage'."\n\n"
146146
.array_reduce(array_merge([$command->getSynopsis()], $command->getAliases(), $command->getUsages()), function ($carry, $usage) {
@@ -169,7 +169,7 @@ protected function describeApplication(Application $application, array $options
169169
$description = new ApplicationDescription($application, $describedNamespace);
170170
$title = $this->getApplicationTitle($application);
171171

172-
$this->write($title."\n".str_repeat('=', Helper::strlen($title)));
172+
$this->write($title."\n".str_repeat('=', Helper::width($title)));
173173

174174
foreach ($description->getNamespaces() as $namespace) {
175175
if (ApplicationDescription::GLOBAL_NAMESPACE !== $namespace['id']) {

src/Symfony/Component/Console/Descriptor/TextDescriptor.php

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ protected function describeInputArgument(InputArgument $argument, array $options
3939
$default = '';
4040
}
4141

42-
$totalWidth = $options['total_width'] ?? Helper::strlen($argument->getName());
42+
$totalWidth = $options['total_width'] ?? Helper::width($argument->getName());
4343
$spacingWidth = $totalWidth - \strlen($argument->getName());
4444

4545
$this->writeText(sprintf(' <info>%s</info> %s%s%s',
@@ -77,7 +77,7 @@ protected function describeInputOption(InputOption $option, array $options = [])
7777
sprintf($option->isNegatable() ? '--%1$s|--no-%1$s' : '--%1$s%2$s', $option->getName(), $value)
7878
);
7979

80-
$spacingWidth = $totalWidth - Helper::strlen($synopsis);
80+
$spacingWidth = $totalWidth - Helper::width($synopsis);
8181

8282
$this->writeText(sprintf(' <info>%s</info> %s%s%s%s',
8383
$synopsis,
@@ -96,7 +96,7 @@ protected function describeInputDefinition(InputDefinition $definition, array $o
9696
{
9797
$totalWidth = $this->calculateTotalWidthForOptions($definition->getOptions());
9898
foreach ($definition->getArguments() as $argument) {
99-
$totalWidth = max($totalWidth, Helper::strlen($argument->getName()));
99+
$totalWidth = max($totalWidth, Helper::width($argument->getName()));
100100
}
101101

102102
if ($definition->getArguments()) {
@@ -234,7 +234,7 @@ protected function describeApplication(Application $application, array $options
234234

235235
foreach ($namespace['commands'] as $name) {
236236
$this->writeText("\n");
237-
$spacingWidth = $width - Helper::strlen($name);
237+
$spacingWidth = $width - Helper::width($name);
238238
$command = $commands[$name];
239239
$commandAliases = $name === $command->getName() ? $this->getCommandAliasesText($command) : '';
240240
$this->writeText(sprintf(' <info>%s</info>%s%s', $name, str_repeat(' ', $spacingWidth), $commandAliases.$command->getDescription()), $options);
@@ -304,12 +304,12 @@ private function getColumnWidth(array $commands): int
304304

305305
foreach ($commands as $command) {
306306
if ($command instanceof Command) {
307-
$widths[] = Helper::strlen($command->getName());
307+
$widths[] = Helper::width($command->getName());
308308
foreach ($command->getAliases() as $alias) {
309-
$widths[] = Helper::strlen($alias);
309+
$widths[] = Helper::width($alias);
310310
}
311311
} else {
312-
$widths[] = Helper::strlen($command);
312+
$widths[] = Helper::width($command);
313313
}
314314
}
315315

@@ -324,11 +324,11 @@ private function calculateTotalWidthForOptions(array $options): int
324324
$totalWidth = 0;
325325
foreach ($options as $option) {
326326
// "-" + shortcut + ", --" + name
327-
$nameLength = 1 + max(Helper::strlen($option->getShortcut()), 1) + 4 + Helper::strlen($option->getName());
327+
$nameLength = 1 + max(Helper::width($option->getShortcut()), 1) + 4 + Helper::width($option->getName());
328328
if ($option->isNegatable()) {
329-
$nameLength += 6 + Helper::strlen($option->getName()); // |--no- + name
329+
$nameLength += 6 + Helper::width($option->getName()); // |--no- + name
330330
} elseif ($option->acceptValue()) {
331-
$valueLength = 1 + Helper::strlen($option->getName()); // = + value
331+
$valueLength = 1 + Helper::width($option->getName()); // = + value
332332
$valueLength += $option->isValueOptional() ? 2 : 0; // [ + ]
333333

334334
$nameLength += $valueLength;

src/Symfony/Component/Console/Helper/FormatterHelper.php

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,12 @@ public function formatBlock($messages, string $style, bool $large = false)
4848
foreach ($messages as $message) {
4949
$message = OutputFormatter::escape($message);
5050
$lines[] = sprintf($large ? ' %s ' : ' %s ', $message);
51-
$len = max(self::strlen($message) + ($large ? 4 : 2), $len);
51+
$len = max(self::width($message) + ($large ? 4 : 2), $len);
5252
}
5353

5454
$messages = $large ? [str_repeat(' ', $len)] : [];
5555
for ($i = 0; isset($lines[$i]); ++$i) {
56-
$messages[] = $lines[$i].str_repeat(' ', $len - self::strlen($lines[$i]));
56+
$messages[] = $lines[$i].str_repeat(' ', $len - self::width($lines[$i]));
5757
}
5858
if ($large) {
5959
$messages[] = str_repeat(' ', $len);
@@ -73,9 +73,9 @@ public function formatBlock($messages, string $style, bool $large = false)
7373
*/
7474
public function truncate(string $message, int $length, string $suffix = '...')
7575
{
76-
$computedLength = $length - self::strlen($suffix);
76+
$computedLength = $length - self::width($suffix);
7777

78-
if ($computedLength > self::strlen($message)) {
78+
if ($computedLength > self::width($message)) {
7979
return $message;
8080
}
8181

src/Symfony/Component/Console/Helper/Helper.php

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,18 +42,20 @@ public function getHelperSet()
4242
/**
4343
* Returns the length of a string, using mb_strwidth if it is available.
4444
*
45+
* @deprecated since 5.3
46+
*
4547
* @return int The length of the string
4648
*/
4749
public static function strlen(?string $string)
4850
{
51+
trigger_deprecation('symfony/console', '5.3', 'Method "%s()" is deprecated and will be removed in Symfony 6.0. Use Helper::width() or Helper::length() instead.', __METHOD__);
52+
4953
return self::width($string);
5054
}
5155

5256
/**
5357
* Returns the width of a string, using mb_strwidth if it is available.
5458
* The width is how many characters positions the string will use.
55-
*
56-
* @internal in Symfony 5.2
5759
*/
5860
public static function width(?string $string): int
5961
{
@@ -73,8 +75,6 @@ public static function width(?string $string): int
7375
/**
7476
* Returns the length of a string, using mb_strlen if it is available.
7577
* The length is related to how many bytes the string will use.
76-
*
77-
* @internal in Symfony 5.2
7878
*/
7979
public static function length(?string $string): int
8080
{
@@ -153,8 +153,13 @@ public static function formatMemory(int $memory)
153153
return sprintf('%d B', $memory);
154154
}
155155

156+
/**
157+
* @deprecated since 5.3
158+
*/
156159
public static function strlenWithoutDecoration(OutputFormatterInt 10000 erface $formatter, ?string $string)
157160
{
161+
trigger_deprecation('symfony/console', '5.3', 'Method "%s()" is deprecated and will be removed in Symfony 6.0. Use Helper::removeDecoration() instead.', __METHOD__);
162+
158163
return self::width(self::removeDecoration($formatter, $string));
159164
}
160165

src/Symfony/Component/Console/Helper/ProgressBar.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,7 @@ public function setMaxSteps(int $max)
388388
{
389389
$this->format = null;
390390
$this->max = max(0, $max);
391-
$this->stepWidth = $this->max ? Helper::strlen((string) $this->max) : 4;
391+
$this->stepWidth = $this->max ? Helper::width((string) $this->max) : 4;
392392
}
393393

394394
/**
@@ -475,7 +475,7 @@ private function overwrite(string $message): void
475475
$messageLines = explode("\n", $message);
476476
$lineCount = \count($messageLines);
477477
foreach ($messageLines as $messageLine) {
478-
$messageLineLength = Helper::strlenWithoutDecoration($this->output->getFormatter(), $messageLine);
478+
$messageLineLength = Helper::width(Helper::removeDecoration($this->output->getFormatter(), $messageLine));
479479
if ($messageLineLength > $this->terminal->getWidth()) {
480480
$lineCount += floor($messageLineLength / $this->terminal->getWidth());
481481
}
@@ -600,7 +600,7 @@ private function buildLine(): string
600600

601601
// gets string length for each sub line with multiline format
602602
$linesLength = array_map(function ($subLine) {
603-
return Helper::strlenWithoutDecoration($this->output->getFormatter(), rtrim($subLine, "\r"));
603+
return Helper::width(Helper::removeDecoration($this->output->getFormatter(), rtrim($subLine, "\r")));
604604
}, explode("\n", $line));
605605

606606
$linesWidth = max($linesLength);

src/Symfony/Component/Console/Helper/QuestionHelper.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -210,10 +210,10 @@ protected function formatChoiceQuestionChoices(ChoiceQuestion $question, string
210210
{
211211
$messages = [];
212212

213-
$maxWidth = max(array_map('self::strlen', array_keys($choices = $question->getChoices())));
213+
$maxWidth = max(array_map('self::width', array_keys($choices = $question->getChoices())));
214214

215215
foreach ($choices as $key => $value) {
216-
$padding = str_repeat(' ', $maxWidth - self::strlen($key));
216+
$padding = str_repeat(' ', $maxWidth - self::width($key));
217217

218218
$messages[] = sprintf(" [<$tag>%s$padding</$tag>] %s", $key, $value);
219219
}

src/Symfony/Component/Console/Helper/Table.php

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -434,11 +434,11 @@ private function renderRowSeparator(int $type = self::SEPARATOR_MID, string $tit
434434
}
435435

436436
if (null !== $title) {
437-
$titleLength = Helper::strlenWithoutDecoration($formatter = $this->output->getFormatter(), $formattedTitle = sprintf($titleFormat, $title));
438-
$markupLength = Helper::strlen($markup);
437+
$titleLength = Helper::width(Helper::removeDecoration($formatter = $this->output->getFormatter(), $formattedTitle = sprintf($titleFormat, $title)));
438+
$markupLength = Helper::width($markup);
439439
if ($titleLength > $limit = $markupLength - 4) {
440440
$titleLength = $limit;
441-
$formatLength = Helper::strlenWithoutDecoration($formatter, sprintf($titleFormat, ''));
441+
$formatLength = Helper::width(Helper::removeDecoration($formatter, sprintf($titleFormat, '')));
442442
$formattedTitle = sprintf($titleFormat, Helper::substr($title, 0, $limit - $formatLength - 3).'...');
443443
}
444444

@@ -569,7 +569,7 @@ private function buildTableRows(array $rows): TableRows
569569
foreach ($rows[$rowKey] as $column => $cell) {
570570
$colspan = $cell instanceof TableCell ? $cell->getColspan() : 1;
571571

572-
if (isset($this->columnMaxWidths[$column]) && Helper::strlenWithoutDecoration($formatter, $cell) > $this->columnMaxWidths[$column]) {
572+
if (isset($this->columnMaxWidths[$column]) && Helper::width(Helper::removeDecoration($formatter, $cell)) > $this->columnMaxWidths[$column]) {
573573
$cell = $formatter->formatAndWrap($cell, $this->columnMaxWidths[$column] * $colspan);
574574
}
575575
if (!strstr($cell, "\n")) {
@@ -755,7 +755,7 @@ private function calculateColumnsWidth(iterable $rows)
755755
foreach ($row as $i => $cell) {
756756
if ($cell instanceof TableCell) {
757757
$textContent = Helper::removeDecoration($this->output->getFormatter(), $cell);
758-
$textLength = Helper::strlen($textContent);
758+
$textLength = Helper::width($textContent);
759759
if ($textLength > 0) {
760760
$contentColumns = str_split($textContent, ceil($textLength / $cell->getColspan()));
761761
foreach ($contentColumns as $position => $content) {
@@ -768,13 +768,13 @@ private function calculateColumnsWidth(iterable $rows)
768768
$lengths[] = $this->getCellWidth($row, $column);
769769
}
770770

771-
$this->effectiveColumnWidths[$column] = max($lengths) + Helper::strlen($this->style->getCellRowContentFormat()) - 2;
771+
$this->effectiveColumnWidths[$column] = max($lengths) + Helper::width($this->style->getCellRowContentFormat()) - 2;
772772
}
773773
}
774774

775775
private function getColumnSeparatorWidth(): int
776776
{
777-
return Helper::strlen(sprintf($this->style->getBorderFormat(), $this->style->getBorderChars()[3]));
777+
return Helper::width(sprintf($this->style->getBorderFormat(), $this->style->getBorderChars()[3]));
778778
}
779779

780780
private function getCellWidth(array $row, int $column): int
@@ -783,7 +783,7 @@ private function getCellWidth(array $row, int $column): int
783783

784784
if (isset($row[$column])) {
785785
$cell = $row[$column];
786-
$cellWidth = Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
786+
$cellWidth = Helper::width(Helper::removeDecoration($this->output->getFormatter(), $cell));
787787
}
788788

789789
$columnWidth = $this->columnWidths[$column] ?? 0;

src/Symfony/Component/Console/Output/ConsoleSectionOutput.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,8 +136,8 @@ private function popStreamContentUntilCurrentSection(int $numberOfLinesToClearFr
136136
return implode('', array_reverse($erasedContent));
137137
}
138138

139-
private function getDisplayLength(string $text): string
139+
private function getDisplayLength(string $text): int
140140
{
141-
return Helper::strlenWithoutDecoration($this->getFormatter(), str_replace("\t", ' ', $text));
141+
return Helper::width(Helper::removeDecoration($this->getFormatter(), str_replace("\t", ' ', $text)));
142142
}
143143
}

0 commit comments

Comments
 (0)
0