Skip to content

Commit

Permalink
Merge branch '2.7' into 2.8
Browse files Browse the repository at this point in the history
* 2.7:
  Lighten tests output by removing composer suggestions
  CS: Remove invisible chars
  Disable resource tracking if the config component is missing
  [EventDispatcher] Remove unneded count()
  Fix tests expecting a valid date
  [Console] Fix table cell styling
  [Console] Revised exception rendering
  [WebProfilerBundle] Normalize whitespace in exceptions passed in headers
  Disable color support detection for tests
  [Form] Improve the exceptions when trying to get the data in a PRE_SET_DATA listener and the data has not already been set
  • Loading branch information
nicolas-grekas committed Apr 3, 2017
2 parents 994e90c + 85ae039 commit d49005a
Show file tree
Hide file tree
Showing 18 changed files with 169 additions and 25 deletions.
6 changes: 3 additions & 3 deletions .travis.yml
Expand Up @@ -79,7 +79,7 @@ install:
- export COMPOSER_ROOT_VERSION=$SYMFONY_VERSION.x-dev
- if [[ ! $skip && $deps ]]; then export SYMFONY_DEPRECATIONS_HELPER=weak; fi
- if [[ ! $skip && $deps ]]; then mv composer.json.phpunit composer.json; fi
- if [[ ! $skip ]]; then composer update; fi
- if [[ ! $skip ]]; then composer update --no-suggest; fi
- if [[ ! $skip ]]; then ./phpunit install; fi
- if [[ ! $skip && ! $PHP = hhvm* ]]; then php -i; else hhvm --php -r 'print_r($_SERVER);print_r(ini_get_all());'; fi

Expand All @@ -90,5 +90,5 @@ script:
- if [[ ! $deps && ! $PHP = hhvm* ]]; then echo -e "\\nRunning tests requiring tty"; $PHPUNIT --group tty; fi
- if [[ ! $deps && $PHP = hhvm* ]]; then $PHPUNIT --exclude-group benchmark,intl-data; fi
- if [[ ! $deps && $PHP = ${MIN_PHP%.*} ]]; then echo -e "1\\n0" | xargs -I{} sh -c 'echo "\\nPHP --enable-sigchild enhanced={}" && ENHANCE_SIGCHLD={} php-$MIN_PHP/sapi/cli/php .phpunit/phpunit-4.8/phpunit --colors=always src/Symfony/Component/Process/'; fi
- if [[ $deps = high ]]; then echo "$COMPONENTS" | parallel --gnu -j10% 'cd {}; composer update --no-progress --ansi; $PHPUNIT --exclude-group tty,benchmark,intl-data'$LEGACY"$REPORT"; fi
- if [[ $deps = low ]]; then echo "$COMPONENTS" | parallel --gnu -j10% 'cd {}; composer update --no-progress --ansi --prefer-lowest --prefer-stable; $PHPUNIT --exclude-group tty,benchmark,intl-data'"$REPORT"; fi
- if [[ $deps = high ]]; then echo "$COMPONENTS" | parallel --gnu -j10% 'cd {}; composer update --no-progress --no-suggest --ansi; $PHPUNIT --exclude-group tty,benchmark,intl-data'$LEGACY"$REPORT"; fi
- if [[ $deps = low ]]; then echo "$COMPONENTS" | parallel --gnu -j10% 'cd {}; composer update --no-progress --no-suggest --ansi --prefer-lowest --prefer-stable; $PHPUNIT --exclude-group tty,benchmark,intl-data'"$REPORT"; fi
2 changes: 1 addition & 1 deletion appveyor.yml
Expand Up @@ -54,7 +54,7 @@ install:
- copy /Y .composer\* %APPDATA%\Composer\
- php .github/build-packages.php "HEAD^" src\Symfony\Bridge\PhpUnit
- IF %APPVEYOR_REPO_BRANCH%==master (SET COMPOSER_ROOT_VERSION=dev-master) ELSE (SET COMPOSER_ROOT_VERSION=%APPVEYOR_REPO_BRANCH%.x-dev)
- php composer.phar update --no-progress --ansi
- php composer.phar update --no-progress --no-suggest --ansi
- php phpunit install

test_script:
Expand Down
Expand Up @@ -68,7 +68,7 @@ public function onKernelResponse(FilterResponseEvent $event)
$this->urlGenerator->generate('_profiler', array('token' => $response->headers->get('X-Debug-Token')), UrlGeneratorInterface::ABSOLUTE_URL)
);
} catch (\Exception $e) {
$response->headers->set('X-Debug-Error', get_class($e).': '.$e->getMessage());
$response->headers->set('X-Debug-Error', get_class($e).': '.preg_replace('/\s+/', ' ', $e->getMessage()));
}
}

Expand Down
Expand Up @@ -245,6 +245,27 @@ public function testThrowingUrlGenerator()
$this->assertEquals('Exception: foo', $response->headers->get('X-Debug-Error'));
}

public function testThrowingErrorCleanup()
{
$response = new Response();
$response->headers->set('X-Debug-Token', 'xxxxxxxx');

$urlGenerator = $this->getUrlGeneratorMock();
$urlGenerator
->expects($this->once())
->method('generate')
->with('_profiler', array('token' => 'xxxxxxxx'))
->will($this->throwException(new \Exception("This\nmultiline\r\ntabbed text should\tcome out\r on\n \ta single plain\r\nline")))
;

$event = new FilterResponseEvent($this->getKernelMock(), $this->getRequestMock(), HttpKernelInterface::MASTER_REQUEST, $response);

$listener = new WebDebugToolbarListener($this->getTwigMock(), false, WebDebugToolbarListener::ENABLED, 'bottom', $urlGenerator);
$listener->onKernelResponse($event);

$this->assertEquals('Exception: This multiline tabbed text should come out on a single plain line', $response->headers->get('X-Debug-Error'));
}

protected function getRequestMock($isXmlHttpRequest = false, $requestFormat = 'html', $hasSession = true)
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->setMethods(array('getSession', 'isXmlHttpRequest', 'getRequestFormat'))->disableOriginalConstructor()->getMock();
Expand Down
13 changes: 6 additions & 7 deletions src/Symfony/Component/Console/Application.php
Expand Up @@ -653,28 +653,27 @@ public function renderException($e, $output)
if (defined('HHVM_VERSION') && $width > 1 << 31) {
$width = 1 << 31;
}
$formatter = $output->getFormatter();
$lines = array();
foreach (preg_split('/\r?\n/', OutputFormatter::escape($e->getMessage())) as $line) {
foreach (preg_split('/\r?\n/', $e->getMessage()) as $line) {
foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
// pre-format lines to get the right string length
$lineLength = $this->stringWidth(preg_replace('/\[[^m]*m/', '', $formatter->format($line))) + 4;
$lineLength = $this->stringWidth($line) + 4;
$lines[] = array($line, $lineLength);

$len = max($lineLength, $len);
}
}

$messages = array();
$messages[] = $emptyLine = $formatter->format(sprintf('<error>%s</error>', str_repeat(' ', $len)));
$messages[] = $formatter->format(sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - $this->stringWidth($title)))));
$messages[] = $emptyLine = sprintf('<error>%s</error>', str_repeat(' ', $len));
$messages[] = sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - $this->stringWidth($title))));
foreach ($lines as $line) {
$messages[] = $formatter->format(sprintf('<error> %s %s</error>', $line[0], str_repeat(' ', $len - $line[1])));
$messages[] = sprintf('<error> %s %s</error>', OutputFormatter::escape($line[0]), str_repeat(' ', $len - $line[1]));
}
$messages[] = $emptyLine;
$messages[] = '';

$output->writeln($messages, OutputInterface::OUTPUT_RAW | OutputInterface::VERBOSITY_QUIET);
$output->writeln($messages, OutputInterface::VERBOSITY_QUIET);

if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
$output->writeln('<comment>Exception trace:</comment>', OutputInterface::VERBOSITY_QUIET);
Expand Down
7 changes: 6 additions & 1 deletion src/Symfony/Component/Console/Helper/Helper.php
Expand Up @@ -105,6 +105,11 @@ public static function formatMemory($memory)
}

public static function strlenWithoutDecoration(OutputFormatterInterface $formatter, $string)
{
return self::strlen(self::removeDecoration($formatter, $string));
}

public static function removeDecoration(OutputFormatterInterface $formatter, $string)
{
$isDecorated = $formatter->isDecorated();
$formatter->setDecorated(false);
Expand All @@ -114,6 +119,6 @@ public static function strlenWithoutDecoration(OutputFormatterInterface $formatt
$string = preg_replace("/\033\[[^m]*m/", '', $string);
$formatter->setDecorated($isDecorated);

return self::strlen($string);
return $string;
}
}
9 changes: 5 additions & 4 deletions src/Symfony/Component/Console/Helper/Table.php
Expand Up @@ -387,7 +387,7 @@ private function buildTableRows($rows)
if (!strstr($cell, "\n")) {
continue;
}
$lines = explode("\n", $cell);
$lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
foreach ($lines as $lineKey => $line) {
if ($cell instanceof TableCell) {
$line = new TableCell($line, array('colspan' => $cell->getColspan()));
Expand Down Expand Up @@ -428,7 +428,7 @@ private function fillNextRows($rows, $line)
$nbLines = $cell->getRowspan() - 1;
$lines = array($cell);
if (strstr($cell, "\n")) {
$lines = explode("\n", $cell);
$lines = explode("\n", str_replace("\n", "<fg=default;bg=default>\n</>", $cell));
$nbLines = count($lines) > $nbLines ? substr_count($cell, "\n") : $nbLines;

$rows[$line][$column] = new TableCell($lines[0], array('colspan' => $cell->getColspan()));
Expand Down Expand Up @@ -563,9 +563,10 @@ private function calculateColumnsWidth($rows)

foreach ($row as $i => $cell) {
if ($cell instanceof TableCell) {
$textLength = Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
$textContent = Helper::removeDecoration($this->output->getFormatter(), $cell);
$textLength = Helper::strlen($textContent);
if ($textLength > 0) {
$contentColumns = str_split($cell, ceil($textLength / $cell->getColspan()));
$contentColumns = str_split($textContent, ceil($textLength / $cell->getColspan()));
foreach ($contentColumns as $position => $content) {
$row[$i + $position] = $content;
}
Expand Down
4 changes: 1 addition & 3 deletions src/Symfony/Component/Console/Tester/CommandTester.php
Expand Up @@ -70,9 +70,7 @@ public function execute(array $input, array $options = array())
}

$this->output = new StreamOutput(fopen('php://memory', 'w', false));
if (isset($options['decorated'])) {
$this->output->setDecorated($options['decorated']);
}
$this->output->setDecorated(isset($options['decorated']) ? $options['decorated'] : false);
if (isset($options['verbosity'])) {
$this->output->setVerbosity($options['verbosity']);
}
Expand Down
16 changes: 16 additions & 0 deletions src/Symfony/Component/Console/Tests/ApplicationTest.php
Expand Up @@ -595,6 +595,22 @@ public function testRenderExceptionWithDoubleWidthCharacters()
$this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception_doublewidth2.txt', $tester->getDisplay(true), '->renderException() wraps messages when they are bigger than the terminal');
}

public function testRenderExceptionEscapesLines()
{
$application = $this->getMockBuilder('Symfony\Component\Console\Application')->setMethods(array('getTerminalWidth'))->getMock();
$application->setAutoExit(false);
$application->expects($this->any())
->method('getTerminalWidth')
->will($this->returnValue(22));
$application->register('foo')->setCode(function () {
throw new \Exception('dont break here <info>!</info>');
});
$tester = new ApplicationTester($application);

$tester->run(array('command' => 'foo'), array('decorated' => false));
$this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception_escapeslines.txt', $tester->getDisplay(true), '->renderException() escapes lines containing formatting');
}

public function testRun()
{
$application = new Application();
Expand Down
@@ -0,0 +1,9 @@


[Exception]
dont break here <
info>!</info>


foo

29 changes: 29 additions & 0 deletions src/Symfony/Component/Console/Tests/Helper/TableTest.php
Expand Up @@ -511,6 +511,35 @@ public function renderProvider()
| Dante Alighieri | J. R. R. Tolkien | J. R. R |
+-----------------+------------------+---------+
TABLE
,
true,
),
'Row with formatted cells containing a newline' => array(
array(),
array(
array(
new TableCell('<error>Dont break'."\n".'here</error>', array('colspan' => 2)),
),
new TableSeparator(),
array(
'foo',
new TableCell('<error>Dont break'."\n".'here</error>', array('rowspan' => 2)),
),
array(
'bar',
),
),
'default',
<<<'TABLE'
+-------+------------+
| Dont break |
| here |
+-------+------------+
| foo | Dont break |
| bar | here |
+-------+------------+
TABLE
,
true,
Expand Down
10 changes: 9 additions & 1 deletion src/Symfony/Component/DependencyInjection/ContainerBuilder.php
Expand Up @@ -26,6 +26,7 @@
use Symfony\Component\Config\Resource\ResourceInterface;
use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\InstantiatorInterface;
use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;

Expand Down Expand Up @@ -73,7 +74,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
*/
private $compiler;

private $trackResources = true;
private $trackResources;

/**
* @var InstantiatorInterface|null
Expand All @@ -90,6 +91,13 @@ class ContainerBuilder extends Container implements TaggedContainerInterface
*/
private $expressionLanguageProviders = array();

public function __construct(ParameterBagInterface $parameterBag = null)
{
parent::__construct($parameterBag);

$this->trackResources = interface_exists('Symfony\Component\Config\Resource\ResourceInterface');
}

/**
* @var string[] with tag names used by findTaggedServiceIds
*/
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/EventDispatcher/EventDispatcher.php
Expand Up @@ -103,7 +103,7 @@ public function getListenerPriority($eventName, $listener)
*/
public function hasListeners($eventName = null)
{
return (bool) count($this->getListeners($eventName));
return (bool) $this->getListeners($eventName);
}

/**
Expand Down
Expand Up @@ -120,7 +120,7 @@ public function reverseTransform($value)

$formatter = $this->getNumberFormatter();
// replace normal spaces so that the formatter can read them
$value = $formatter->parse(str_replace(' ', ' ', $value));
$value = $formatter->parse(str_replace(' ', "\xc2\xa0", $value));

if (intl_is_failure($formatter->getErrorCode())) {
throw new TransformationFailedException($formatter->getErrorMessage());
Expand Down
Expand Up @@ -60,7 +60,7 @@ public function __construct($validator)

public function loadTypeGuesser()
{
// 2.5 API
// 2.5 API
if ($this->validator instanceof ValidatorInterface) {
return new ValidatorTypeGuesser($this->validator);
}
Expand Down
12 changes: 12 additions & 0 deletions src/Symfony/Component/Form/Form.php
Expand Up @@ -408,6 +408,10 @@ public function getData()
}

if (!$this->defaultDataSet) {
if ($this->lockSetData) {
throw new RuntimeException('A cycle was detected. Listeners to the PRE_SET_DATA event must not call getData() if the form data has not already been set. You should call getData() on the FormEvent object instead.');
}

$this->setData($this->config->getData());
}

Expand All @@ -428,6 +432,10 @@ public function getNormData()
}

if (!$this->defaultDataSet) {
if ($this->lockSetData) {
throw new RuntimeException('A cycle was detected. Listeners to the PRE_SET_DATA event must not call getNormData() if the form data has not already been set.');
}

$this->setData($this->config->getData());
}

Expand All @@ -448,6 +456,10 @@ public function getViewData()
}

if (!$this->defaultDataSet) {
if ($this->lockSetData) {
throw new RuntimeException('A cycle was detected. Listeners to the PRE_SET_DATA event must not call getViewData() if the form data has not already been set.');
}

$this->setData($this->config->getData());
}

Expand Down
Expand Up @@ -608,7 +608,7 @@ public function testIsSynchronizedReturnsTrueIfChoiceAndCompletelyFilled()
));

$form->submit(array(
'day' => '0',
'day' => '1',
'month' => '6',
'year' => '2010',
));
Expand Down
46 changes: 46 additions & 0 deletions src/Symfony/Component/Form/Tests/SimpleFormTest.php
Expand Up @@ -903,6 +903,7 @@ public function testViewDataMustBeObjectIfDataClassIsSet()

/**
* @expectedException \Symfony\Component\Form\Exception\RuntimeException
* @expectedExceptionMessage A cycle was detected. Listeners to the PRE_SET_DATA event must not call setData(). You should call setData() on the FormEvent object instead.
*/
public function testSetDataCannotInvokeItself()
{
Expand Down Expand Up @@ -1084,6 +1085,51 @@ public function testCustomOptionsResolver()
$fooType->setDefaultOptions($resolver);
}

/**
* @expectedException \Symfony\Component\Form\Exception\RuntimeException
* @expectedExceptionMessage A cycle was detected. Listeners to the PRE_SET_DATA event must not call getData() if the form data has not already been set. You should call getData() on the FormEvent object instead.
*/
public function testCannotCallGetDataInPreSetDataListenerIfDataHasNotAlreadyBeenSet()
{
$config = new FormConfigBuilder('name', 'stdClass', $this->dispatcher);
$config->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$event->getForm()->getData();
});
$form = new Form($config);

$form->setData('foo');
}

/**
* @expectedException \Symfony\Component\Form\Exception\RuntimeException
* @expectedExceptionMessage A cycle was detected. Listeners to the PRE_SET_DATA event must not call getNormData() if the form data has not already been set.
*/
public function testCannotCallGetNormDataInPreSetDataListener()
{
$config = new FormConfigBuilder('name', 'stdClass', $this->dispatcher);
$config->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$event->getForm()->getNormData();
});
$form = new Form($config);

$form->setData('foo');
}

/**
* @expectedException \Symfony\Component\Form\Exception\RuntimeException
* @expectedExceptionMessage A cycle was detected. Listeners to the PRE_SET_DATA event must not call getViewData() if the form data has not already been set.
*/
public function testCannotCallGetViewDataInPreSetDataListener()
{
$config = new FormConfigBuilder('name', 'stdClass', $this->dispatcher);
$config->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
$event->getForm()->getViewData();
});
$form = new Form($config);

$form->setData('foo');
}

protected function createForm()
{
return $this->getBuilder()->getForm();
Expand Down

0 comments on commit d49005a

Please sign in to comment.