Skip to content

Commit

Permalink
feature #47062 [Console] Don't cut Urls wrapped in SymfonyStyle block…
Browse files Browse the repository at this point in the history
… (fchris82, GromNaN)

This PR was merged into the 6.2 branch.

Discussion
----------

[Console] Don't cut Urls wrapped in SymfonyStyle block

| Q             | A
| ------------- | ---
| Branch?       | 6.2
| Bug fix?      | no
| New feature?  | yes
| Deprecations? | no
| Tickets       | #30920
| License       | MIT
| Doc PR        | symfony/symfony-docs#16476

Continuation of #45318 by fchris82

Commits
-------

b317f06 Remove OutputWrapperInterface
2bc2571 Console output formatter improvement
  • Loading branch information
fabpot committed Jul 26, 2022
2 parents 3633475 + b317f06 commit b1b77f3
Show file tree
Hide file tree
Showing 9 changed files with 194 additions and 14 deletions.
1 change: 1 addition & 0 deletions src/Symfony/Component/Console/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ CHANGELOG

* Add support to display table vertically when calling setVertical()
* Add method `__toString()` to `InputInterface`
* Added `OutputWrapper` to prevent truncated URL in `SymfonyStyle::createBlock`.
* Deprecate `Command::$defaultName` and `Command::$defaultDescription`, use the `AsCommand` attribute instead
* Add suggested values for arguments and options in input definition, for input completion
* Add `$resumeAt` parameter to `ProgressBar#start()`, so that one can easily 'resume' progress on longer tasks, and still get accurate `getEstimate()` and `getRemaining()` results.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ public function formatAndWrap(?string $message, int $width)
$offset = $pos + \strlen($text);

// opening tag?
if ($open = '/' != $text[1]) {
if ($open = '/' !== $text[1]) {
$tag = $matches[1][$i][0];
} else {
$tag = $matches[3][$i][0] ?? '';
Expand Down
76 changes: 76 additions & 0 deletions src/Symfony/Component/Console/Helper/OutputWrapper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Console\Helper;

/**
* Simple output wrapper for "tagged outputs" instead of wordwrap(). This solution is based on a StackOverflow
* answer: https://stackoverflow.com/a/20434776/1476819 from user557597 (alias SLN).
*
* (?:
* # -- Words/Characters
* ( # (1 start)
* (?> # Atomic Group - Match words with valid breaks
* .{1,16} # 1-N characters
* # Followed by one of 4 prioritized, non-linebreak whitespace
* (?: # break types:
* (?<= [^\S\r\n] ) # 1. - Behind a non-linebreak whitespace
* [^\S\r\n]? # ( optionally accept an extra non-linebreak whitespace )
* | (?= \r? \n ) # 2. - Ahead a linebreak
* | $ # 3. - EOS
* | [^\S\r\n] # 4. - Accept an extra non-linebreak whitespace
* )
* ) # End atomic group
* |
* .{1,16} # No valid word breaks, just break on the N'th character
* ) # (1 end)
* (?: \r? \n )? # Optional linebreak after Words/Characters
* |
* # -- Or, Linebreak
* (?: \r? \n | $ ) # Stand alone linebreak or at EOS
* )
*
* @author Krisztián Ferenczi <ferenczi.krisztian@gmail.com>
*
* @see https://stackoverflow.com/a/20434776/1476819
*/
final class OutputWrapper
{
private const TAG_OPEN_REGEX_SEGMENT = '[a-z](?:[^\\\\<>]*+ | \\\\.)*';
private const TAG_CLOSE_REGEX_SEGMENT = '[a-z][^<>]*+';
private const URL_PATTERN = 'https?://\S+';

public function __construct(
private bool $allowCutUrls = false
) {
}

public function wrap(string $text, int $width, string $break = "\n"): string
{
if (!$width) {
return $text;
}

$tagPattern = sprintf('<(?:(?:%s)|/(?:%s)?)>', self::TAG_OPEN_REGEX_SEGMENT, self::TAG_CLOSE_REGEX_SEGMENT);
$limitPattern = "{1,$width}";
$patternBlocks = [$tagPattern];
if (!$this->allowCutUrls) {
$patternBlocks[] = self::URL_PATTERN;
}
$patternBlocks[] = '.';
$blocks = implode('|', $patternBlocks);
$rowPattern = "(?:$blocks)$limitPattern";
$pattern = sprintf('#(?:((?>(%1$s)((?<=[^\S\r\n])[^\S\r\n]?|(?=\r?\n)|$|[^\S\r\n]))|(%1$s))(?:\r?\n)?|(?:\r?\n|$))#imux', $rowPattern);
$output = rtrim(preg_replace($pattern, '\\1'.$break, $text), $break);

return str_replace(' '.$break, $break, $output);
}
}
18 changes: 11 additions & 7 deletions src/Symfony/Component/Console/Style/SymfonyStyle.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Component\Console\Exception\RuntimeException;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\Console\Helper\OutputWrapper;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Helper\SymfonyQuestionHelper;
use Symfony\Component\Console\Helper\Table;
Expand Down Expand Up @@ -456,22 +457,25 @@ private function createBlock(iterable $messages, string $type = null, string $st

if (null !== $type) {
$type = sprintf('[%s] ', $type);
$indentLength = \strlen($type);
$indentLength = Helper::width($type);
$lineIndentation = str_repeat(' ', $indentLength);
}

// wrap and add newlines for each element
$outputWrapper = new OutputWrapper();
foreach ($messages as $key => $message) {
if ($escape) {
$message = OutputFormatter::escape($message);
}

$decorationLength = Helper::width($message) - Helper::width(Helper::removeDecoration($this->getFormatter(), $message));
$messageLineLength = min($this->lineLength - $prefixLength - $indentLength + $decorationLength, $this->lineLength);
$messageLines = explode(\PHP_EOL, wordwrap($message, $messageLineLength, \PHP_EOL, true));
foreach ($messageLines as $messageLine) {
$lines[] = $messageLine;
}
$lines = array_merge(
$lines,
explode(\PHP_EOL, $outputWrapper->wrap(
$message,
$this->lineLength - $prefixLength - $indentLength,
\PHP_EOL
))
);

if (\count($messages) > 1 && $key < \count($messages) - 1) {
$lines[] = '';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,6 @@
$output->setDecorated(true);
$output = new SymfonyStyle($input, $output);
$output->comment(
'Lorem ipsum dolor sit <comment>amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</comment> Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum'
'Árvíztűrőtükörfúrógép 🎼 Lorem ipsum dolor sit <comment>💕 amet, consectetur adipisicing elit, sed do eiusmod tempor incididu labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</comment> Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum'
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

// ensure that nested tags have no effect on the color of the '//' prefix
return function (InputInterface $input, OutputInterface $output) {
$output->setDecorated(true);
$output = new SymfonyStyle($input, $output);
$output->block(
'Árvíztűrőtükörfúrógép Lorem ipsum dolor sit <comment>amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</comment> Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum',
'', // UTF-8 star!
null,
'<fg=default;bg=default> ║ </>', // UTF-8 double line!
false,
false
);
};
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

 // Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore 
 // magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo 
 // consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla 
 // pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
 // est laborum
 // Árvíztűrőtükörfúrógép 🎼 Lorem ipsum dolor sit 💕 amet, consectetur adipisicing elit, sed do eiusmod tempor incididu
 // labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
 // ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla 
 // pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
 // laborum

Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

 ║ [★] Árvíztűrőtükörfúrógép Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt 
 ║  ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut 
 ║  aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu 
 ║  fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit
 ║  anim id est laborum

73 changes: 73 additions & 0 deletions src/Symfony/Component/Console/Tests/Helper/OutputWrapperTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Console\Tests\Helper;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Helper\OutputWrapper;

class OutputWrapperTest extends TestCase
{
/**
* @dataProvider textProvider
*/
public function testBasicWrap(string $text, int $width, bool $allowCutUrls, string $expected)
{
$wrapper = new OutputWrapper($allowCutUrls);
$result = $wrapper->wrap($text, $width);
$this->assertEquals($expected, $result);
}

public static function textProvider(): iterable
{
$baseTextWithUtf8AndUrl = 'Árvíztűrőtükörfúrógép https://github.com/symfony/symfony Lorem ipsum <comment>dolor</comment> sit amet, consectetur adipiscing elit. Praesent vestibulum nulla quis urna maximus porttitor. Donec ullamcorper risus at <error>libero ornare</error> efficitur.';

yield 'Default URL cut' => [
$baseTextWithUtf8AndUrl,
20,
false,
<<<'EOS'
Árvíztűrőtükörfúrógé
p https://github.com/symfony/symfony Lorem ipsum
<comment>dolor</comment> sit amet,
consectetur
adipiscing elit.
Praesent vestibulum
nulla quis urna
maximus porttitor.
Donec ullamcorper
risus at <error>libero
ornare</error> efficitur.
EOS,
];

yield 'Allow URL cut' => [
$baseTextWithUtf8AndUrl,
20,
true,
<<<'EOS'
Árvíztűrőtükörfúrógé
p
https://github.com/s
ymfony/symfony Lorem
ipsum <comment>dolor</comment> sit
amet, consectetur
adipiscing elit.
Praesent vestibulum
nulla quis urna
maximus porttitor.
Donec ullamcorper
risus at <error>libero
ornare</error> efficitur.
EOS,
];
}
}

0 comments on commit b1b77f3

Please sign in to comment.