Created
August 20, 2022 13:19
-
-
Save ismail1432/de4b0f8b9ec77c14de7b7159d35fcf2f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
namespace App\Debug; | |
use Symfony\Component\HttpKernel\Event\ResponseEvent; | |
use Symfony\Component\EventDispatcher\Attribute\AsEventListener; | |
use Symfony\Component\DependencyInjection\Attribute\When; | |
#[When(env: 'test')] | |
#[AsEventListener] | |
final class OutputContentListener | |
{ | |
private string $logDir; | |
public function __construct(string $logDir) | |
{ | |
$this->logDir = $logDir; | |
} | |
public function __invoke(ResponseEvent $event): void | |
{ | |
$request = $event->getRequest(); | |
$response = $event->getResponse(); | |
$contentType = $response->headers->get('content-type'); | |
$content = $response->getContent(); | |
if (null !== $contentType && str_ends_with($contentType, 'json')) { | |
$suffix = 'json'; | |
} else { | |
$suffix = $content !== strip_tags($content) ? 'html' : 'txt'; | |
} | |
$logDir = $this->logDir.'/responses'; | |
if (false === file_exists($logDir)) { | |
mkdir($logDir); | |
} | |
$fileName = str_replace("/", "_", substr($request->getRequestUri(), 1)); | |
file_put_contents(sprintf("%s/%s_%s.%s", $logDir, strtolower($request->getMethod()), $fileName, $suffix), $content); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't forget to bind $logDir in services.yaml