Fix bug with whitespace in Kernel::stripComments()

This commit is contained in:
Martin Auswöger 2020-11-29 22:21:38 +01:00
parent aa5ec20a0c
commit 8d368e1fe3
2 changed files with 40 additions and 16 deletions

View File

@ -858,6 +858,9 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
// replace multiple new lines with a single newline
$rawChunk .= preg_replace(['/\n{2,}/S'], "\n", $token[1]);
} elseif (\in_array($token[0], [\T_COMMENT, \T_DOC_COMMENT])) {
if (!\in_array($rawChunk[\strlen($rawChunk) - 1], [' ', "\n", "\r", "\t"], true)) {
$rawChunk .= ' ';
}
$ignoreSpace = true;
} else {
$rawChunk .= $token[1];
@ -865,6 +868,8 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl
// The PHP-open tag already has a new-line
if (\T_OPEN_TAG === $token[0]) {
$ignoreSpace = true;
} else {
$ignoreSpace = false;
}
}
}

View File

@ -239,10 +239,37 @@ class KernelTest extends TestCase
$kernel->handle($request, $type, $catch);
}
public function testStripComments()
/**
* @dataProvider getStripCommentsCodes
*/
public function testStripComments(string $source, string $expected)
{
$source = <<<'EOF'
$output = Kernel::stripComments($source);
// Heredocs are preserved, making the output mixing Unix and Windows line
// endings, switching to "\n" everywhere on Windows to avoid failure.
if ('\\' === \DIRECTORY_SEPARATOR) {
$expected = str_replace("\r\n", "\n", $expected);
$output = str_replace("\r\n", "\n", $output);
}
$this->assertEquals($expected, $output);
}
public function getStripCommentsCodes(): array
{
return [
['<?php echo foo();', '<?php echo foo();'],
['<?php echo/**/foo();', '<?php echo foo();'],
['<?php echo/** bar */foo();', '<?php echo foo();'],
['<?php /**/echo foo();', '<?php echo foo();'],
['<?php echo \foo();', '<?php echo \foo();'],
['<?php echo/**/\foo();', '<?php echo \foo();'],
['<?php echo/** bar */\foo();', '<?php echo \foo();'],
['<?php /**/echo \foo();', '<?php echo \foo();'],
[<<<'EOF'
<?php
include_once \dirname(__DIR__).'/foo.php';
$string = 'string should not be modified';
@ -280,9 +307,10 @@ class TestClass
// inline comment
}
}
EOF;
$expected = <<<'EOF'
EOF
, <<<'EOF'
<?php
include_once \dirname(__DIR__).'/foo.php';
$string = 'string should not be modified';
$string = 'string should not be
@ -307,18 +335,9 @@ class TestClass
{
}
}
EOF;
$output = Kernel::stripComments($source);
// Heredocs are preserved, making the output mixing Unix and Windows line
// endings, switching to "\n" everywhere on Windows to avoid failure.
if ('\\' === \DIRECTORY_SEPARATOR) {
$expected = str_replace("\r\n", "\n", $expected);
$output = str_replace("\r\n", "\n", $output);
}
$this->assertEquals($expected, $output);
EOF
],
];
}
/**