<?php
namespace Kobizo\Bundle\CoreBundle\Controller;
use Kobizo\Component\Configuration\Backend\AdminUrlConfig;
use Kobizo\Component\Configuration\Frontend\TemplateConfig;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
abstract class KobizoFeAbstractController extends AbstractController
{
protected AdminUrlConfig $adminUrlConfig;
protected TemplateConfig $templateConfig;
public function __construct(
AdminUrlConfig $adminUrlConfig,
TemplateConfig $templateConfig
) {
$this->adminUrlConfig = $adminUrlConfig;
$this->templateConfig = $templateConfig;
}
/**
* Merge {admin} slug, which is needed for path generation, before redirecting.
*/
protected function redirectToRoute(string $route, array $parameters = [], int $status = 302, bool $inclDefaultParams = false): RedirectResponse
{
if ($inclDefaultParams) {
$parameters = array_merge($this->getDefaultParameters(), $parameters);
}
return parent::redirectToRoute($route, $parameters, $status);
}
/**
* Renders a view regarding to its existence in App and in current Bundle, where the function is called.
* The view of the App will have a higher priority against the view of Bundle.
*
* For example:
* In DefaultController.php, when $this->render('@KobizoCore/frontend/default/index.twig', [..]) is called
* This function will replace '@KobizoCore/frontend' with 'template_name' (eg. `asia-ho`)
* then will check if `App/templates/`asia-ho`/default/index.twig` exists to use it
* Otherwise the template of current bundle `@KobizoCore/frontend/default/index.twig will be used.
*/
protected function render(string $view, array $parameters = [], Response $response = null): Response
{
$parameters = array_merge($this->getDefaultParameters(), $parameters);
//.twig file in APP if exists...
$appView = str_replace('@KobizoCore/frontend', $this->templateConfig->getValue(null, true), $view);
//... then render this file from APP template folder
if ($this->get('twig')->getLoader()->exists($appView)) {
return parent::render($appView, $parameters, $response);
}
//if not then render original template file from this ecommerce bundle
return parent::render($view, $parameters, $response);
}
private function getDefaultParameters()
{
return [
'admin' => $this->adminUrlConfig->getValue(),
];
}
}