Skip to content

Commit

Permalink
Fix DumpRecorder: make sure there is always a handler for actual output
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexVanderbist committed Dec 27, 2021
1 parent 2b12ae1 commit d4b462f
Showing 1 changed file with 31 additions and 5 deletions.
36 changes: 31 additions & 5 deletions src/DumpRecorder/DumpRecorder.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace Spatie\LaravelRay\DumpRecorder;

use Illuminate\Contracts\Container\Container;
use ReflectionMethod;
use ReflectionProperty;
use Spatie\LaravelRay\Ray;
use Symfony\Component\VarDumper\VarDumper;

Expand All @@ -29,21 +31,23 @@ public function register(): self
return $multiDumpHandler;
});

if (! static::$registeredHandler) {
if (!static::$registeredHandler) {
static::$registeredHandler = true;

$this->ensureOriginalHandlerExists();

$originalHandler = VarDumper::setHandler(function ($dumpedVariable) use ($multiDumpHandler) {
if ($this->shouldDump()) {
$multiDumpHandler->dump($dumpedVariable);
}
$multiDumpHandler->dump($dumpedVariable);
});

if ($originalHandler) {
$multiDumpHandler->addHandler($originalHandler);
}

$multiDumpHandler->addHandler(function ($dumpedVariable) {
return app(Ray::class)->send($dumpedVariable);
if ($this->shouldDump()) {
app(Ray::class)->send($dumpedVariable);
}
});
}

Expand All @@ -57,4 +61,26 @@ protected function shouldDump(): bool

return $ray->settings->send_dumps_to_ray;
}

/**
* Only the `VarDumper` knows how to create the orignal HTML or CLI VarDumper.
* Using reflection and the private VarDumper::register() method we can force it
* to create and register a new VarDumper::$handler before we'll overwrite it.
* Of course, we only need to do this if there isn't a registered VarDumper::$handler.
*
* @throws \ReflectionException
*/
protected function ensureOriginalHandlerExists(): void
{
$reflectionProperty = new ReflectionProperty(VarDumper::class, 'handler');
$reflectionProperty->setAccessible(true);
$handler = $reflectionProperty->getValue();

if (!$handler) {
// No handler registered yet, so we'll force VarDumper to create one.
$reflectionMethod = new ReflectionMethod(VarDumper::class, 'register');
$reflectionMethod->setAccessible(true);
$reflectionMethod->invoke(null);
}
}
}

0 comments on commit d4b462f

Please sign in to comment.