Last active
July 8, 2019 15:25
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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