Skip to content

[Console] Deprecate Helper::strlen() for width() and length() #40695

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions UPGRADE-5.3.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ Asset

* Deprecated `RemoteJsonManifestVersionStrategy`, use `JsonManifestVersionStrategy` instead

Console
-------

* Deprecate `Helper::strlen()`, use `Helper::width()` instead.

DoctrineBridge
--------------

Expand Down
1 change: 1 addition & 0 deletions UPGRADE-6.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Console
-------

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

DependencyInjection
-------------------
Expand Down
10 changes: 5 additions & 5 deletions src/Symfony/Component/Console/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -699,7 +699,7 @@ public function find(string $name)
$abbrevs = array_values($commands);
$maxLen = 0;
foreach ($abbrevs as $abbrev) {
$maxLen = max(Helper::strlen($abbrev), $maxLen);
$maxLen = max(Helper::width($abbrev), $maxLen);
}
$abbrevs = array_map(function ($cmd) use ($commandList, $usableWidth, $maxLen, &$commands) {
if ($commandList[$cmd]->isHidden()) {
Expand All @@ -710,7 +710,7 @@ public function find(string $name)

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

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

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

$len = max($lineLength, $len);
Expand All @@ -839,7 +839,7 @@ protected function doRenderThrowable(\Throwable $e, OutputInterface $output): vo
}
$messages[] = $emptyLine = sprintf('<error>%s</error>', str_repeat(' ', $len));
if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
$messages[] = sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - Helper::strlen($title))));
$messages[] = sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - Helper::width($title))));
}
foreach ($lines as $line) {
$messages[] = sprintf('<error> %s %s</error>', OutputFormatter::escape($line[0]), str_repeat(' ', $len - $line[1]));
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/Console/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ CHANGELOG
* Add option `--short` to the `list` command
* Add support for bright colors
* Add `#[AsCommand]` attribute for declaring commands on PHP 8
* Add `Helper::width()` and `Helper::length()`

5.2.0
-----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ protected function describeCommand(Command $command, array $options = [])
if ($options['short'] ?? false) {
$this->write(
'`'.$command->getName()."`\n"
.str_repeat('-', Helper::strlen($command->getName()) + 2)."\n\n"
.str_repeat('-', Helper::width($command->getName()) + 2)."\n\n"
.($command->getDescription() ? $command->getDescription()."\n\n" : '')
.'### Usage'."\n\n"
.array_reduce($command->getAliases(), function ($carry, $usage) {
Expand All @@ -140,7 +140,7 @@ protected function describeCommand(Command $command, array $options = [])

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

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

foreach ($description->getNamespaces() as $namespace) {
if (ApplicationDescription::GLOBAL_NAMESPACE !== $namespace['id']) {
Expand Down
20 changes: 10 additions & 10 deletions src/Symfony/Component/Console/Descriptor/TextDescriptor.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ protected function describeInputArgument(InputArgument $argument, array $options
$default = '';
}

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

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

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

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

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

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

foreach ($commands as $command) {
if ($command instanceof Command) {
$widths[] = Helper::strlen($command->getName());
$widths[] = Helper::width($command->getName());
foreach ($command->getAliases() as $alias) {
$widths[] = Helper::strlen($alias);
$widths[] = Helper::width($alias);
}
} else {
$widths[] = Helper::strlen($command);
$widths[] = Helper::width($command);
}
}

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

$nameLength += $valueLength;
Expand Down
8 changes: 4 additions & 4 deletions src/Symfony/Component/Console/Helper/FormatterHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,12 @@ public function formatBlock($messages, string $style, bool $large = false)
foreach ($messages as $message) {
$message = OutputFormatter::escape($message);
$lines[] = sprintf($large ? ' %s ' : ' %s ', $message);
$len = max(self::strlen($message) + ($large ? 4 : 2), $len);
$len = max(self::width($message) + ($large ? 4 : 2), $len);
}

$messages = $large ? [str_repeat(' ', $len)] : [];
for ($i = 0; isset($lines[$i]); ++$i) {
$messages[] = $lines[$i].str_repeat(' ', $len - self::strlen($lines[$i]));
$messages[] = $lines[$i].str_repeat(' ', $len - self::width($lines[$i]));
}
if ($large) {
$messages[] = str_repeat(' ', $len);
Expand All @@ -73,9 +73,9 @@ public function formatBlock($messages, string $style, bool $large = false)
*/
public function truncate(string $message, int $length, string $suffix = '...')
{
$computedLength = $length - self::strlen($suffix);
$computedLength = $length - self::width($suffix);

if ($computedLength > self::strlen($message)) {
if ($computedLength > self::width($message)) {
return $message;
}

Expand Down
13 changes: 9 additions & 4 deletions src/Symfony/Component/Console/Helper/Helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,18 +42,20 @@ public function getHelperSet()
/**
* Returns the length of a string, using mb_strwidth if it is available.
*
* @deprecated since 5.3
*
* @return int The length of the string
*/
public static function strlen(?string $string)
{
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__);

return self::width($string);
}

/**
* Returns the width of a string, using mb_strwidth if it is available.
* The width is how many characters positions the string will use.
*
* @internal in Symfony 5.2
*/
public static function width(?string $string): int
{
Expand All @@ -73,8 +75,6 @@ public static function width(?string $string): int
/**
* Returns the length of a string, using mb_strlen if it is available.
* The length is related to how many bytes the string will use.
*
* @internal in Symfony 5.2
*/
public static function length(?string $string): int
{
Expand Down Expand Up @@ -153,8 +153,13 @@ public static function formatMemory(int $memory)
return sprintf('%d B', $memory);
}

/**
* @deprecated since 5.3
*/
public static function strlenWithoutDecoration(OutputFormatterInterface $formatter, ?string $string)
{
trigger_deprecation('symfony/console', '5.3', 'Method "%s()" is deprecated and will be removed in Symfony 6.0. Use Helper::removeDecoration() instead.', __METHOD__);

return self::width(self::removeDecoration($formatter, $string));
}

Expand Down
6 changes: 3 additions & 3 deletions src/Symfony/Component/Console/Helper/ProgressBar.php
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ public function setMaxSteps(int $max)
{
$this->format = null;
$this->max = max(0, $max);
$this->stepWidth = $this->max ? Helper::strlen((string) $this->max) : 4;
$this->stepWidth = $this->max ? Helper::width((string) $this->max) : 4;
}

/**
Expand Down Expand Up @@ -475,7 +475,7 @@ private function overwrite(string $message): void
$messageLines = explode("\n", $message);
$lineCount = \count($messageLines);
foreach ($messageLines as $messageLine) {
$messageLineLength = Helper::strlenWithoutDecoration($this->output->getFormatter(), $messageLine);
$messageLineLength = Helper::width(Helper::removeDecoration($this->output->getFormatter(), $messageLine));
if ($messageLineLength > $this->terminal->getWidth()) {
$lineCount += floor($messageLineLength / $this->terminal->getWidth());
}
Expand Down Expand Up @@ -600,7 +600,7 @@ private function buildLine(): string

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

$linesWidth = max($linesLength);
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Component/Console/Helper/QuestionHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -210,10 +210,10 @@ protected function formatChoiceQuestionChoices(ChoiceQuestion $question, string
{
$messages = [];

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

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

$messages[] = sprintf(" [<$tag>%s$padding</$tag>] %s", $key, $value);
}
Expand Down
16 changes: 8 additions & 8 deletions src/Symfony/Component/Console/Helper/Table.php
Original file line number Diff line number Diff line change
Expand Up @@ -434,11 +434,11 @@ private function renderRowSeparator(int $type = self::SEPARATOR_MID, string $tit
}

if (null !== $title) {
$titleLength = Helper::strlenWithoutDecoration($formatter = $this->output->getFormatter(), $formattedTitle = sprintf($titleFormat, $title));
$markupLength = Helper::strlen($markup);
$titleLength = Helper::width(Helper::removeDecoration($formatter = $this->output->getFormatter(), $formattedTitle = sprintf($titleFormat, $title)));
$markupLength = Helper::width($markup);
if ($titleLength > $limit = $markupLength - 4) {
$titleLength = $limit;
$formatLength = Helper::strlenWithoutDecoration($formatter, sprintf($titleFormat, ''));
$formatLength = Helper::width(Helper::removeDecoration($formatter, sprintf($titleFormat, '')));
$formattedTitle = sprintf($titleFormat, Helper::substr($title, 0, $limit - $formatLength - 3).'...');
}

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

if (isset($this->columnMaxWidths[$column]) && Helper::strlenWithoutDecoration($formatter, $cell) > $this->columnMaxWidths[$column]) {
if (isset($this->columnMaxWidths[$column]) && Helper::width(Helper::removeDecoration($formatter, $cell)) > $this->columnMaxWidths[$column]) {
$cell = $formatter->formatAndWrap($cell, $this->columnMaxWidths[$column] * $colspan);
}
if (!strstr($cell, "\n")) {
Expand Down Expand Up @@ -755,7 +755,7 @@ private function calculateColumnsWidth(iterable $rows)
foreach ($row as $i => $cell) {
if ($cell instanceof TableCell) {
$textContent = Helper::removeDecoration($this->output->getFormatter(), $cell);
$textLength = Helper::strlen($textContent);
$textLength = Helper::width($textContent);
if ($textLength > 0) {
$contentColumns = str_split($textContent, ceil($textLength / $cell->getColspan()));
foreach ($contentColumns as $position => $content) {
Expand All @@ -768,13 +768,13 @@ private function calculateColumnsWidth(iterable $rows)
$lengths[] = $this->getCellWidth($row, $column);
}

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

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

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

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

$columnWidth = $this->columnWidths[$column] ?? 0;
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Component/Console/Output/ConsoleSectionOutput.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,8 @@ private function popStreamContentUntilCurrentSection(int $numberOfLinesToClearFr
return implode('', array_reverse($erasedContent));
}

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