Merge branch '4.4' into 5.2

* 4.4:
  [Console] Fix line wrapping for decorated text in block output
  [Inflector] Fixed pluralize "coupon"
  [PhpUnitBridge] fix compat with symfony/debug
  [VarDumper] Adds support for ReflectionUnionType to VarDumper
  Correctly clear lines for multi-line progress bar messages.
This commit is contained in:
Nicolas Grekas 2021-03-17 17:55:51 +01:00
commit 98fce3ee7f
14 changed files with 246 additions and 46 deletions

View File

@ -11,6 +11,8 @@
namespace Symfony\Bridge\PhpUnit\DeprecationErrorHandler;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Util\Test;
use Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerFor;
use Symfony\Component\Debug\DebugClassLoader as LegacyDebugClassLoader;
@ -87,41 +89,45 @@ class Deprecation
}
}
if (isset($line['object']) || isset($line['class'])) {
set_error_handler(function () {});
$parsedMsg = unserialize($this->message);
restore_error_handler();
if ($parsedMsg && isset($parsedMsg['deprecation'])) {
$this->message = $parsedMsg['deprecation'];
$this->originClass = $parsedMsg['class'];
$this->originMethod = $parsedMsg['method'];
if (isset($parsedMsg['files_stack'])) {
$this->originalFilesStack = $parsedMsg['files_stack'];
}
// If the deprecation has been triggered via
// \Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerTrait::endTest()
// then we need to use the serialized information to determine
// if the error has been triggered from vendor code.
if (isset($parsedMsg['triggering_file'])) {
$this->triggeringFile = $parsedMsg['triggering_file'];
}
if (!isset($line['object']) && !isset($line['class'])) {
return;
}
return;
set_error_handler(function () {});
$parsedMsg = unserialize($this->message);
restore_error_handler();
if ($parsedMsg && isset($parsedMsg['deprecation'])) {
$this->message = $parsedMsg['deprecation'];
$this->originClass = $parsedMsg['class'];
$this->originMethod = $parsedMsg['method'];
if (isset($parsedMsg['files_stack'])) {
$this->originalFilesStack = $parsedMsg['files_stack'];
}
// If the deprecation has been triggered via
// \Symfony\Bridge\PhpUnit\Legacy\SymfonyTestsListenerTrait::endTest()
// then we need to use the serialized information to determine
// if the error has been triggered from vendor code.
if (isset($parsedMsg['triggering_file'])) {
$this->triggeringFile = $parsedMsg['triggering_file'];
}
if (!isset($line['class'], $trace[$i - 2]['function']) || 0 !== strpos($line['class'], SymfonyTestsListenerFor::class)) {
$this->originClass = isset($line['object']) ? \get_class($line['object']) : $line['class'];
$this->originMethod = $line['function'];
return;
}
return;
}
if (!isset($line['class'], $trace[$i - 2]['function']) || 0 !== strpos($line['class'], SymfonyTestsListenerFor::class)) {
$this->originClass = isset($line['object']) ? \get_class($line['object']) : $line['class'];
$this->originMethod = $line['function'];
if ('trigger_error' !== $trace[$i - 2]['function'] || isset($trace[$i - 2]['class'])) {
$this->originClass = \get_class($line['args'][0]);
$this->originMethod = $line['args'][0]->getName();
return;
}
return;
}
$test = $line['args'][0] ?? null;
if (($test instanceof TestCase || $test instanceof TestSuite) && ('trigger_error' !== $trace[$i - 2]['function'] || isset($trace[$i - 2]['class']))) {
$this->originClass = \get_class($line['args'][0]);
$this->originMethod = $line['args'][0]->getName();
return;
}
}

View File

@ -462,8 +462,15 @@ final class ProgressBar
if ($this->overwrite) {
if (null !== $this->previousMessage) {
if ($this->output instanceof ConsoleSectionOutput) {
$lines = floor(Helper::strlenWithoutDecoration($this->output->getFormatter(), $message) / $this->terminal->getWidth()) + $this->formatLineCount + 1;
$this->output->clear($lines);
$messageLines = explode("\n", $message);
$lineCount = \count($messageLines);
foreach ($messageLines as $messageLine) {
$messageLineLength = Helper::strlenWithoutDecoration($this->output->getFormatter(), $messageLine);
if ($messageLineLength > $this->terminal->getWidth()) {
$lineCount += floor($messageLineLength / $this->terminal->getWidth());
}
}
$this->output->clear($lineCount);
} else {
if ($this->formatLineCount > 0) {
$this->cursor->moveUp($this->formatLineCount);

View File

@ -476,7 +476,12 @@ class SymfonyStyle extends OutputStyle
$message = OutputFormatter::escape($message);
}
$lines = array_merge($lines, explode(\PHP_EOL, wordwrap($message, $this->lineLength - $prefixLength - $indentLength, \PHP_EOL, true)));
$decorationLength = Helper::strlen($message) - Helper::strlenWithoutDecoration($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;
}
if (\count($messages) > 1 && $key < \count($messages) - 1) {
$lines[] = '';
@ -496,7 +501,9 @@ class SymfonyStyle extends OutputStyle
}
$line = $prefix.$line;
$line .= str_repeat(' ', $this->lineLength - Helper::strlenWithoutDecoration($this->getFormatter(), $line));
$decorationLength = Helper::strlen($line) - Helper::strlenWithoutDecoration($this->getFormatter(), $line);
$messageLineLength = min($this->lineLength - $prefixLength - $indentLength + $decorationLength, $this->lineLength);
$line .= str_repeat(' ', max($this->lineLength - Helper::strlenWithoutDecoration($this->getFormatter(), $line), 0));
if ($style) {
$line = sprintf('<%s>%s</>', $style, $line);

View File

@ -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
 // 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

View File

@ -397,6 +397,34 @@ class ProgressBarTest extends TestCase
);
}
public function testOverwriteWithSectionOutputWithNewlinesInMessage()
{
$sections = [];
$stream = $this->getOutputStream(true);
$output = new ConsoleSectionOutput($stream->getStream(), $sections, $stream->getVerbosity(), $stream->isDecorated(), new OutputFormatter());
ProgressBar::setFormatDefinition('test', '%current%/%max% [%bar%] %percent:3s%% %message% Fruitcake marzipan toffee. Cupcake gummi bears tart dessert ice cream chupa chups cupcake chocolate bar sesame snaps. Croissant halvah cookie jujubes powder macaroon. Fruitcake bear claw bonbon jelly beans oat cake pie muffin Fruitcake marzipan toffee.');
$bar = new ProgressBar($output, 50, 0);
$bar->setFormat('test');
$bar->start();
$bar->display();
$bar->setMessage("Twas brillig, and the slithy toves. Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe.\nBeware the Jabberwock, my son! The jaws that bite, the claws that catch! Beware the Jubjub bird, and shun The frumious Bandersnatch!");
$bar->advance();
$bar->setMessage("He took his vorpal sword in hand; Long time the manxome foe he sought— So rested he by the Tumtum tree And stood awhile in thought.\nAnd, as in uffish thought he stood, The Jabberwock, with eyes of flame, Came whiffling through the tulgey wood, And burbled as it came!");
$bar->advance();
rewind($output->getStream());
$this->assertEquals(
' 0/50 [>] 0% %message% Fruitcake marzipan toffee. Cupcake gummi bears tart dessert ice cream chupa chups cupcake chocolate bar sesame snaps. Croissant halvah cookie jujubes powder macaroon. Fruitcake bear claw bonbon jelly beans oat cake pie muffin Fruitcake marzipan toffee.'.\PHP_EOL.
"\x1b[6A\x1b[0J 1/50 [>] 2% Twas brillig, and the slithy toves. Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe.
Beware the Jabberwock, my son! The jaws that bite, the claws that catch! Beware the Jubjub bird, and shun The frumious Bandersnatch! Fruitcake marzipan toffee. Cupcake gummi bears tart dessert ice cream chupa chups cupcake chocolate bar sesame snaps. Croissant halvah cookie jujubes powder macaroon. Fruitcake bear claw bonbon jelly beans oat cake pie muffin Fruitcake marzipan toffee.".\PHP_EOL.
"\x1b[6A\x1b[0J 2/50 [>] 4% He took his vorpal sword in hand; Long time the manxome foe he sought— So rested he by the Tumtum tree And stood awhile in thought.
And, as in uffish thought he stood, The Jabberwock, with eyes of flame, Came whiffling through the tulgey wood, And burbled as it came! Fruitcake marzipan toffee. Cupcake gummi bears tart dessert ice cream chupa chups cupcake chocolate bar sesame snaps. Croissant halvah cookie jujubes powder macaroon. Fruitcake bear claw bonbon jelly beans oat cake pie muffin Fruitcake marzipan toffee.".\PHP_EOL,
stream_get_contents($output->getStream())
);
}
public function testMultipleSectionsWithCustomFormat()
{
$sections = [];

View File

@ -204,6 +204,7 @@ class InflectorTest extends TestCase
['crisis', 'crises'],
['criteria', 'criterion'],
['cup', 'cups'],
['coupon', 'coupons'],
['data', 'data'],
['day', 'days'],
['disco', 'discos'],

View File

@ -226,6 +226,9 @@ final class EnglishInflector implements InflectorInterface
// bacteria (bacterium), criteria (criterion), phenomena (phenomenon)
['noi', 3, true, true, 'ions'],
// coupon (coupons)
['nop', 3, true, true, 'pons'],
// seasons (season), treasons (treason), poisons (poison), lessons (lesson)
['nos', 3, true, true, 'sons'],

View File

@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/
namespace Symfony\Component\String\Tests;
namespace Symfony\Component\String\Tests\Inflector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\String\Inflector\EnglishInflector;
@ -58,6 +58,7 @@ class EnglishInflectorTest extends TestCase
['crises', ['cris', 'crise', 'crisis']],
['criteria', ['criterion', 'criterium']],
['cups', 'cup'],
['coupon', 'coupons'],
['data', 'data'],
['days', 'day'],
['discos', 'disco'],

View File

@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/
namespace Symfony\Component\String\Tests;
namespace Symfony\Component\String\Tests\Inflector;
use PHPUnit\Framework\TestCase;
use Symfony\Component\String\Inflector\FrenchInflector;

View File

@ -96,11 +96,20 @@ class ReflectionCaster
{
$prefix = Caster::PREFIX_VIRTUAL;
$a += [
$prefix.'name' => $c instanceof \ReflectionNamedType ? $c->getName() : (string) $c,
$prefix.'allowsNull' => $c->allowsNull(),
$prefix.'isBuiltin' => $c->isBuiltin(),
];
if ($c instanceof \ReflectionNamedType || \PHP_VERSION_ID < 80000) {
$a += [
$prefix.'name' => $c instanceof \ReflectionNamedType ? $c->getName() : (string) $c,
$prefix.'allowsNull' => $c->allowsNull(),
$prefix.'isBuiltin' => $c->isBuiltin(),
];
} elseif ($c instanceof \ReflectionUnionType) {
$a[$prefix.'allowsNull'] = $c->allowsNull();
self::addMap($a, $c, [
'types' => 'getTypes',
]);
} else {
$a[$prefix.'allowsNull'] = $c->allowsNull();
}
return $a;
}

View File

@ -14,9 +14,12 @@ namespace Symfony\Component\VarDumper\Tests\Caster;
use PHPUnit\Framework\TestCase;
use Symfony\Component\VarDumper\Caster\Caster;
use Symfony\Component\VarDumper\Test\VarDumperTestTrait;
use Symfony\Component\VarDumper\Tests\Fixtures\ExtendsReflectionTypeFixture;
use Symfony\Component\VarDumper\Tests\Fixtures\GeneratorDemo;
use Symfony\Component\VarDumper\Tests\Fixtures\LotsOfAttributes;
use Symfony\Component\VarDumper\Tests\Fixtures\NotLoadableClass;
use Symfony\Component\VarDumper\Tests\Fixtures\ReflectionNamedTypeFixture;
use Symfony\Component\VarDumper\Tests\Fixtures\ReflectionUnionTypeFixture;
/**
* @author Nicolas Grekas <p@tchwork.com>
@ -91,7 +94,7 @@ Closure($x) {
$b: & 123
}
file: "%sReflectionCasterTest.php"
line: "84 to 84"
line: "87 to 87"
}
EOTXT
, $var
@ -227,6 +230,104 @@ EOTXT
);
}
/**
* @requires PHP 7.4
*/
public function testReflectionPropertyScalar()
{
$var = new \ReflectionProperty(ReflectionNamedTypeFixture::class, 'a');
$this->assertDumpMatchesFormat(
<<<'EOTXT'
ReflectionProperty {
+name: "a"
+class: "Symfony\Component\VarDumper\Tests\Fixtures\ReflectionNamedTypeFixture"
modifiers: "public"
}
EOTXT
, $var
);
}
/**
* @requires PHP 7.4
*/
public function testReflectionNamedType()
{
$var = (new \ReflectionProperty(ReflectionNamedTypeFixture::class, 'a'))->getType();
$this->assertDumpMatchesFormat(
<<<'EOTXT'
ReflectionNamedType {
name: "int"
allowsNull: false
isBuiltin: true
}
EOTXT
, $var
);
}
/**
* @requires PHP 8
*/
public function testReflectionUnionType()
{
$var = (new \ReflectionProperty(ReflectionUnionTypeFixture::class, 'a'))->getType();
$this->assertDumpMatchesFormat(
<<<'EOTXT'
ReflectionUnionType {
allowsNull: false
types: array:2 [
0 => ReflectionNamedType {
name: "string"
allowsNull: false
isBuiltin: true
}
1 => ReflectionNamedType {
name: "int"
allowsNull: false
isBuiltin: true
}
]
}
EOTXT
, $var
);
}
/**
* @requires PHP 8
*/
public function testExtendsReflectionType()
{
$var = new ExtendsReflectionTypeFixture();
$this->assertDumpMatchesFormat(
<<<'EOTXT'
Symfony\Component\VarDumper\Tests\Fixtures\ExtendsReflectionTypeFixture {
allowsNull: false
}
EOTXT
, $var
);
}
/**
* @requires PHP < 8
*/
public function testLegacyExtendsReflectionType()
{
$var = new ExtendsReflectionTypeFixture();
$this->assertDumpMatchesFormat(
<<<'EOTXT'
Symfony\Component\VarDumper\Tests\Fixtures\ExtendsReflectionTypeFixture {
name: "fake"
allowsNull: false
isBuiltin: false
}
EOTXT
, $var
);
}
public function testReturnType()
{
$f = eval('return function ():int {};');

View File

@ -0,0 +1,21 @@
<?php
namespace Symfony\Component\VarDumper\Tests\Fixtures;
class ExtendsReflectionTypeFixture extends \ReflectionType
{
public function allowsNull(): bool
{
return false;
}
public function isBuiltin(): bool
{
return false;
}
public function __toString(): string
{
return 'fake';
}
}

View File

@ -0,0 +1,8 @@
<?php
namespace Symfony\Component\VarDumper\Tests\Fixtures;
class ReflectionNamedTypeFixture
{
public int $a;
}

View File

@ -0,0 +1,8 @@
<?php
namespace Symfony\Component\VarDumper\Tests\Fixtures;
class ReflectionUnionTypeFixture
{
public int|string $a;
}