Skip to content

Improve support for anonymous classes #28218

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
Aug 24, 2018
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
10 changes: 9 additions & 1 deletion src/Symfony/Component/Console/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -753,12 +753,20 @@ protected function doRenderException(\Exception $e, OutputInterface $output)
do {
$message = trim($e->getMessage());
if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
$title = sprintf(' [%s%s] ', \get_class($e), 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : '');
$class = \get_class($e);
$class = 'c' === $class[0] && 0 === strpos($class, "class@anonymous\0") ? get_parent_class($class).'@anonymous' : $class;
Copy link
Member

@Kocal Kocal Aug 17, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm curious about \0, I know it represents a null byte, but it's the first time I see it in PHP code.
Does it improve perf or something like that? 🤔

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You cannot print a null char using null as this would result in an empty string 😃

Copy link
Member Author

@nicolas-grekas nicolas-grekas Aug 25, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's desired, see #28218 (comment) (or maybe you mean something else... :))

$title = sprintf(' [%s%s] ', $class, 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : '');
$len = Helper::strlen($title);
} else {
$len = 0;
}

if (false !== strpos($message, "class@anonymous\0")) {
$message = preg_replace_callback('/class@anonymous\x00.*?\.php0x?[0-9a-fA-F]++/', function ($m) {
return \class_exists($m[0], false) ? get_parent_class($m[0]).'@anonymous' : $m[0];
}, $message);
}

$width = $this->terminal->getWidth() ? $this->terminal->getWidth() - 1 : PHP_INT_MAX;
$lines = array();
foreach ('' !== $message ? preg_split('/\r?\n/', $message) : array() as $line) {
Expand Down
25 changes: 25 additions & 0 deletions src/Symfony/Component/Console/Tests/ApplicationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -824,6 +824,31 @@ public function testRenderExceptionLineBreaks()
$this->assertStringMatchesFormatFile(self::$fixturesPath.'/application_renderexception_linebreaks.txt', $tester->getDisplay(true), '->renderException() keep multiple line breaks');
}

public function testRenderAnonymousException()
{
$application = new Application();
$application->setAutoExit(false);
$application->register('foo')->setCode(function () {
throw new class('') extends \InvalidArgumentException {
};
});
$tester = new ApplicationTester($application);

$tester->run(array('command' => 'foo'), array('decorated' => false));
$this->assertContains('[InvalidArgumentException@anonymous]', $tester->getDisplay(true));

$application = new Application();
$application->setAutoExit(false);
$application->register('foo')->setCode(function () {
throw new \InvalidArgumentException(sprintf('Dummy type "%s" is invalid.', \get_class(new class() {
})));
});
$tester = new ApplicationTester($application);

$tester->run(array('command' => 'foo'), array('decorated' => false));
$this->assertContains('Dummy type "@anonymous" is invalid.', $tester->getDisplay(true));
}

public function testRun()
{
$application = new Application();
Expand Down
18 changes: 13 additions & 5 deletions src/Symfony/Component/Debug/ErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Psr\Log\LogLevel;
use Symfony\Component\Debug\Exception\FatalErrorException;
use Symfony\Component\Debug\Exception\FatalThrowableError;
use Symfony\Component\Debug\Exception\FlattenException;
use Symfony\Component\Debug\Exception\OutOfMemoryException;
use Symfony\Component\Debug\Exception\SilencedErrorContext;
use Symfony\Component\Debug\FatalErrorHandler\ClassNotFoundFatalErrorHandler;
Expand Down Expand Up @@ -405,7 +406,11 @@ public function handleError($type, $message, $file, $line)
$context = $e;
}

$logMessage = $this->levels[$type].': '.$message;
if (false !== strpos($message, "class@anonymous\0")) {
$logMessage = $this->levels[$type].': '.(new FlattenException())->setMessage($message)->getMessage();
} else {
$logMessage = $this->levels[$type].': '.$message;
}

if (null !== self::$toStringException) {
$errorAsException = self::$toStringException;
Expand Down Expand Up @@ -518,21 +523,24 @@ public function handleException($exception, array $error = null)
$handlerException = null;

if (($this->loggedErrors & $type) || $exception instanceof FatalThrowableError) {
if (false !== strpos($message = $exception->getMessage(), "class@anonymous\0")) {
$message = (new FlattenException())->setMessage($message)->getMessage();
}
if ($exception instanceof FatalErrorException) {
if ($exception instanceof FatalThrowableError) {
$error = array(
'type' => $type,
'message' => $message = $exception->getMessage(),
'message' => $message,
'file' => $exception->getFile(),
'line' => $exception->getLine(),
);
} else {
$message = 'Fatal '.$exception->getMessage();
$message = 'Fatal '.$message;
}
} elseif ($exception instanceof \ErrorException) {
$message = 'Uncaught '.$exception->getMessage();
$message = 'Uncaught '.$message;
} else {
$message = 'Uncaught Exception: '.$exception->getMessage();
$message = 'Uncaught Exception: '.$message;
}
}
if ($this->loggedErrors & $type) {
Expand Down
57 changes: 54 additions & 3 deletions src/Symfony/Component/Debug/Exception/FlattenException.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,79 +90,125 @@ public function getStatusCode()
return $this->statusCode;
}

/**
* @return $this
*/
public function setStatusCode($code)
{
$this->statusCode = $code;

return $this;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need fluent interface here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need it. It still makes it easier to use the class.

}

public function getHeaders()
{
return $this->headers;
}

/**
* @return $this
*/
public function setHeaders(array $headers)
{
$this->headers = $headers;

return $this;
}

public function getClass()
{
return $this->class;
}

/**
* @return $this
*/
public function setClass($class)
{
$this->class = $class;
$this->class = 'c' === $class[0] && 0 === strpos($class, "class@anonymous\0") ? get_parent_class($class).'@anonymous' : $class;

return $this;
}

public function getFile()
{
return $this->file;
}

/**
* @return $this
*/
public function setFile($file)
{
$this->file = $file;

return $this;
}

public function getLine()
{
return $this->line;
}

/**
* @return $this
*/
public function setLine($line)
{
$this->line = $line;

return $this;
}

public function getMessage()
{
return $this->message;
}

/**
* @return $this
*/
public function setMessage($message)
{
if (false !== strpos($message, "class@anonymous\0")) {
$message = preg_replace_callback('/class@anonymous\x00.*?\.php0x?[0-9a-fA-F]++/', function ($m) {
return \class_exists($m[0], false) ? get_parent_class($m[0]).'@anonymous' : $m[0];
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

technically this can occur for anon. clases without a parent class.. do we care? Same for setClass.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes we do, and this is handled: the result will be just @anonymous, as the VarDumper component already does.

}, $message);
}

$this->message = $message;

return $this;
}

public function getCode()
{
return $this->code;
}

/**
* @return $this
*/
public function setCode($code)
{
$this->code = $code;

return $this;
}

public function getPrevious()
{
return $this->previous;
}

/**
* @return $this
*/
public function setPrevious(self $previous)
{
$this->previous = $previous;

return $this;
}

public function getAllPrevious()
Expand Down Expand Up @@ -191,11 +237,14 @@ public function setTraceFromException(\Exception $exception)
$this->setTraceFromThrowable($exception);
}

public function setTraceFromThrowable(\Throwable $throwable): void
public function setTraceFromThrowable(\Throwable $throwable)
{
$this->setTrace($throwable->getTrace(), $throwable->getFile(), $throwable->getLine());
return $this->setTrace($throwable->getTrace(), $throwable->getFile(), $throwable->getLine());
}

/**
* @return $this
*/
public function setTrace($trace, $file, $line)
{
$this->trace = array();
Expand Down Expand Up @@ -229,6 +278,8 @@ public function setTrace($trace, $file, $line)
'args' => isset($entry['args']) ? $this->flattenArgs($entry['args']) : array(),
);
}

return $this;
}

private function flattenArgs($args, $level = 0, &$count = 0)
Expand Down
3 changes: 2 additions & 1 deletion src/Symfony/Component/Debug/ExceptionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,8 @@ public function getContent(FlattenException $exception)
} catch (\Exception $e) {
// something nasty happened and we cannot throw an exception anymore
if ($this->debug) {
$title = sprintf('Exception thrown when handling an exception (%s: %s)', \get_class($e), $this->escapeHtml($e->getMessage()));
$e = FlattenException::create($e);
$title = sprintf('Exception thrown when handling an exception (%s: %s)', $e->getClass(), $this->escapeHtml($e->getMessage()));
} else {
$title = 'Whoops, looks like something went wrong.';
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,19 @@ public function testTooBigArray()
$this->assertNotContains('*value1*', $serializeTrace);
}

public function testAnonymousClass()
{
$flattened = FlattenException::create(new class() extends \RuntimeException {
});

$this->assertSame('RuntimeException@anonymous', $flattened->getClass());

$flattened = FlattenException::create(new \Exception(sprintf('Class "%s" blah.', \get_class(new class() extends \RuntimeException {
}))));

$this->assertSame('Class "RuntimeException@anonymous" blah.', $flattened->getMessage());
}

private function createException($foo)
{
return new \Exception();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,9 @@ public function __construct($controller, LoggerInterface $logger = null, $debug

public function logKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
$e = FlattenException::create($event->getException());

$this->logException($exception, sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', \get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine()));
$this->logException($event->getException(), sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', $e->getClass(), $e->getMessage(), $e->getFile(), $e->getLine()));
}

public function onKernelException(GetResponseForExceptionEvent $event)
Expand All @@ -75,7 +75,9 @@ public function onKernelException(GetResponseForExceptionEvent $event)
try {
$response = $event->getKernel()->handle($request, HttpKernelInterface::SUB_REQUEST, false);
} catch (\Exception $e) {
$this->logException($e, sprintf('Exception thrown when handling an exception (%s: %s at %s line %s)', \get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()));
$f = FlattenException::create($e);

$this->logException($e, sprintf('Exception thrown when handling an exception (%s: %s at %s line %s)', $f->getClass(), $f->getMessage(), $e->getFile(), $e->getLine()));

$wrapper = $e;

Expand Down
18 changes: 12 additions & 6 deletions src/Symfony/Component/VarDumper/Caster/ClassStub.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,6 @@ public function __construct(string $identifier, $callable = null)
{
$this->value = $identifier;

if (0 < $i = strrpos($identifier, '\\')) {
$this->attr['ellipsis'] = \strlen($identifier) - $i;
$this->attr['ellipsis-type'] = 'class';
$this->attr['ellipsis-tail'] = 1;
}

try {
if (null !== $callable) {
if ($callable instanceof \Closure) {
Expand Down Expand Up @@ -61,6 +55,12 @@ public function __construct(string $identifier, $callable = null)
}
}

if (false !== strpos($identifier, "class@anonymous\0")) {
$this->value = $identifier = preg_replace_callback('/class@anonymous\x00.*?\.php0x?[0-9a-fA-F]++/', function ($m) {
return \class_exists($m[0], false) ? get_parent_class($m[0]).'@anonymous' : $m[0];
}, $identifier);
}

if (null !== $callable && $r instanceof \ReflectionFunctionAbstract) {
$s = ReflectionCaster::castFunctionAbstract($r, array(), new Stub(), true);
$s = ReflectionCaster::getSignature($s);
Expand All @@ -76,6 +76,12 @@ public function __construct(string $identifier, $callable = null)
}
} catch (\ReflectionException $e) {
return;
} finally {
if (0 < $i = strrpos($identifier, '\\')) {
$this->attr['ellipsis'] = \strlen($identifier) - $i;
$this->attr['ellipsis-type'] = 'class';
$this->attr['ellipsis-tail'] = 1;
}
}

if ($f = $r->getFileName()) {
Expand Down
10 changes: 9 additions & 1 deletion src/Symfony/Component/VarDumper/Caster/ExceptionCaster.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,9 @@ public static function castThrowingCasterException(ThrowingCasterException $e, a

if (isset($a[$xPrefix.'previous'], $a[$trace]) && $a[$xPrefix.'previous'] instanceof \Exception) {
$b = (array) $a[$xPrefix.'previous'];
self::traceUnshift($b[$xPrefix.'trace'], \get_class($a[$xPrefix.'previous']), $b[$prefix.'file'], $b[$prefix.'line']);
$class = \get_class($a[$xPrefix.'previous']);
$class = 'c' === $class[0] && 0 === strpos($class, "class@anonymous\0") ? get_parent_class($class).'@anonymous' : $class;
self::traceUnshift($b[$xPrefix.'trace'], $class, $b[$prefix.'file'], $b[$prefix.'line']);
$a[$trace] = new TraceStub($b[$xPrefix.'trace'], false, 0, -\count($a[$trace]->value));
}

Expand Down Expand Up @@ -279,6 +281,12 @@ private static function filterExceptionArray($xClass, array $a, $xPrefix, $filte
}
unset($a[$xPrefix.'string'], $a[Caster::PREFIX_DYNAMIC.'xdebug_message'], $a[Caster::PREFIX_DYNAMIC.'__destructorException']);

if (isset($a[Caster::PREFIX_PROTECTED.'message']) && false !== strpos($a[Caster::PREFIX_PROTECTED.'message'], "class@anonymous\0")) {
$a[Caster::PREFIX_PROTECTED.'message'] = preg_replace_callback('/class@anonymous\x00.*?\.php0x?[0-9a-fA-F]++/', function ($m) {
return \class_exists($m[0], false) ? get_parent_class($m[0]).'@anonymous' : $m[0];
}, $a[Caster::PREFIX_PROTECTED.'message']);
}

if (isset($a[Caster::PREFIX_PROTECTED.'file'], $a[Caster::PREFIX_PROTECTED.'line'])) {
$a[Caster::PREFIX_PROTECTED.'file'] = new LinkStub($a[Caster::PREFIX_PROTECTED.'file'], $a[Caster::PREFIX_PROTECTED.'line']);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,23 @@ public function testExcludeVerbosity()
#file: "%sExceptionCasterTest.php"
#line: 28
}
EODUMP;

$this->assertDumpMatchesFormat($expectedDump, $e, Caster::EXCLUDE_VERBOSE);
}

public function testAnonymous()
{
$e = new \Exception(sprintf('Boo "%s" ba.', \get_class(new class('Foo') extends \Exception {
})));

$expectedDump = <<<'EODUMP'
Exception {
#message: "Boo "Exception@anonymous" ba."
#code: 0
#file: "%sExceptionCasterTest.php"
#line: %d
}
EODUMP;

$this->assertDumpMatchesFormat($expectedDump, $e, Caster::EXCLUDE_VERBOSE);
Expand Down
Loading