Skip to content

Instantly share code, notes, and snippets.

@nesk
Last active July 8, 2019 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nesk/11520ee82cd43ae81be056a749708402 to your computer and use it in GitHub Desktop.
Save nesk/11520ee82cd43ae81be056a749708402 to your computer and use it in GitHub Desktop.
A helper to open the content of a Symfony/Laravel response in your browser, really useful for test debugging.
<?php
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
/**
* Opens a response in the default browser.
*/
function open_response(Response $response): void
{
// Remove the page refresh on redirects, to avoid unwanted redirections.
if ($response instanceof RedirectResponse) {
$crawler = new Crawler($response->getContent());
$crawler->filter('meta[http-equiv=refresh]')->each(function (Crawler $crawler) {
foreach ($crawler as $node) {
$node->parentNode->removeChild($node);
}
});
$response->setContent($crawler->html());
}
// Create a temporary file with the content of the response
$filePath = tempnam('/tmp', 'html-response-');
file_put_contents($filePath, $response->getContent());
// Open the file
$filePath = escapeshellarg($filePath);
switch (php_uname('s')) {
case 'Darwin':
exec("open $filePath");
break;
case 'Windows':
exec("start $filePath");
break;
default:
exec("xdg-open $filePath");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment