<?php
/**
* @copyright Copyright (C) Ibexa AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
declare(strict_types=1);
namespace Ibexa\Bundle\Shipping\EventSubscriber;
use Ibexa\Bundle\Shipping\Form\Type\ShippingMethod\ShippingMethodBulkDeleteType;
use Ibexa\Bundle\Shipping\Form\Type\ShippingMethod\ShippingMethodDefinitionPreCreateType;
use Ibexa\Bundle\Shipping\View\ShippingMethodListView;
use Ibexa\Contracts\ProductCatalog\PermissionResolverInterface;
use Ibexa\Contracts\Shipping\ShippingMethod\Permission\Create;
use Ibexa\Contracts\Shipping\ShippingMethod\Permission\Edit;
use Ibexa\Core\MVC\Symfony\Event\PreContentViewEvent;
use Ibexa\Core\MVC\Symfony\MVCEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
final class ShippingMethodListViewSubscriber implements EventSubscriberInterface
{
private PermissionResolverInterface $permissionResolver;
private FormFactoryInterface $formFactory;
private UrlGeneratorInterface $urlGenerator;
public function __construct(
PermissionResolverInterface $permissionResolver,
FormFactoryInterface $formFactory,
UrlGeneratorInterface $urlGenerator
) {
$this->permissionResolver = $permissionResolver;
$this->formFactory = $formFactory;
$this->urlGenerator = $urlGenerator;
}
public static function getSubscribedEvents(): array
{
return [
MVCEvents::PRE_CONTENT_VIEW => 'onPreContentView',
];
}
public function onPreContentView(PreContentViewEvent $event): void
{
$view = $event->getContentView();
if (!$view instanceof ShippingMethodListView) {
return;
}
$view->addParameters([
'can_create' => $this->canCreate(),
'can_edit' => $this->canEdit(),
'bulk_delete_form' => $this->createBulkDeleteForm()->createView(),
'pre_create_form' => $this->createPreCreateForm()->createView(),
]);
}
private function canCreate(): bool
{
return $this->permissionResolver->canUser(new Create());
}
private function canEdit(): bool
{
return $this->permissionResolver->canUser(new Edit());
}
private function createBulkDeleteForm(): FormInterface
{
return $this->formFactory->create(ShippingMethodBulkDeleteType::class, null, [
'method' => Request::METHOD_POST,
'action' => $this->urlGenerator->generate('ibexa.shipping.shipping_method.bulk_delete'),
]);
}
private function createPreCreateForm(): FormInterface
{
return $this->formFactory->create(ShippingMethodDefinitionPreCreateType::class, null, [
'action' => $this->urlGenerator->generate('ibexa.shipping.shipping_method.pre_create'),
'method' => Request::METHOD_POST,
]);
}
}