<?php
namespace App\EventSubscriber;
use Pimcore\Event\AdminEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class AdminAssetSubscriber implements EventSubscriberInterface
{
private array $customAssets = [
'css' => [
'/admin/css/custom.css'
],
'js' => [
'/admin/js/custom.js'
]
];
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => 'onKernelResponse',
];
}
public function onKernelResponse(ResponseEvent $event): void
{
if (!$event->isMainRequest()) {
return;
}
$request = $event->getRequest();
$response = $event->getResponse();
// Only inject assets in Pimcore admin area
if (!$this->isAdminRequest($request)) {
return;
}
$content = $response->getContent();
if (!$content || !str_contains($content, '</head>')) {
return;
}
$assetsHtml = $this->generateAssetsHtml();
$content = str_replace('</head>', $assetsHtml . '</head>', $content);
$response->setContent($content);
}
private function isAdminRequest($request): bool
{
$path = $request->getPathInfo();
return str_starts_with($path, '/admin') ||
str_contains($request->getUri(), '/admin/');
}
private function generateAssetsHtml(): string
{
$html = "\n<!-- Custom Admin Assets -->\n";
// Add CSS files
foreach ($this->customAssets['css'] as $cssFile) {
$html .= sprintf('<link rel="stylesheet" type="text/css" href="%s">' . "\n", $cssFile);
}
// Add JS files
foreach ($this->customAssets['js'] as $jsFile) {
$html .= sprintf('<script type="text/javascript" src="%s"></script>' . "\n", $jsFile);
}
return $html;
}
}