Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
6.5 kB
2
Indexable
Never
<?php

declare(strict_types=1);

namespace App\Events\OncoguideListner;

use App\Helper\AccountHelper;
use App\Helper\OncoguideHelpers\StepSystemHelper;
use eZ\Publish\Core\MVC\Symfony\SiteAccess;
use Exception;
use eZ\Publish\API\Repository\Exceptions\InvalidArgumentException;
use eZ\Publish\API\Repository\Exceptions\NotFoundException;
use eZ\Publish\API\Repository\Exceptions\UnauthorizedException;
use eZ\Publish\API\Repository\Repository;
use eZ\Publish\Core\MVC\Symfony\Templating\GlobalHelper;
use eZ\Publish\Core\MVC\Symfony\View\ContentView;
use Psr\Container\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;

use function count;
use function in_array;

class OncoguideGrisContenuListner implements EventSubscriberInterface
{
    /**
     * @var GlobalHelper
     */
    private $globalHelper;

    /**
     * @var Repository
     */
    private $repository;

    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var AuthorizationCheckerInterface
     */
    private $authorizationChecker;

    /**
     * @var StepSystemHelper
     */
    private $stepSystemHelper;

    /**
     * @var AccountHelper
     */
    private $accountHelper;

    public const USER_CONTENT_TYPE_IDENTIFIER = 'medical_user';

    /**
     * Carrousel50ImageBlockListener constructor.
     */
    public function __construct(
        GlobalHelper $globalHelper,
        Repository $Repository,
        ContainerInterface $container,
        AuthorizationCheckerInterface $authorizationChecker,
        StepSystemHelper $stepSystemHelper,
        AccountHelper $accountHelper
    ) {
        $this->repository = $Repository;
        $this->globalHelper = $globalHelper;
        $this->container = $container;
        $this->authorizationChecker = $authorizationChecker;
        $this->stepSystemHelper = $stepSystemHelper;
        $this->accountHelper = $accountHelper;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::VIEW => 'renderView',
            KernelEvents::RESPONSE => 'onKernelResponse',
        ];
    }

    /**
     * @throws NotFoundException
     * @throws InvalidArgumentException
     * @throws UnauthorizedException
     * @throws Exception
     */
    public function renderView(ViewEvent $event)
    {
        $view = $event->getControllerResult();
        $siteaccess = $event->getRequest()->attributes->get('siteaccess');
        $siteaccessOG = [
            'oncoguide_france_fr' => '/fr-fr',
            'oncoguide_maroc_fr' => '/fr-ma',
            'oncoguide_algerie_fr' => '/fr-dz',
            'oncoguide_tunisie_fr' => '/fr-tn',
            'oncoguide_international_en' => '/en',
        ];
        if (
            $view instanceof ContentView && $view->getViewType() === 'full' && $view->getLocation() &&
            in_array('oncoguide_group', $this->sitaccesGroup()) &&
            $siteaccess instanceof SiteAccess
        ) {
            $locationId = $view->getLocation()->id;
            $siteaccess = $event->getRequest()->attributes->get('siteaccess');
            /** @var $siteaccess SiteAccess  */
            $pathToRedirect = $siteaccessOG[$siteaccess->name];
            $location = $this->repository->getLocationService()->loadLocation($locationId);
            $contentType = $this->repository->getLocationService()->loadLocation($locationId)
                ->contentInfo->getContentType()->identifier;
            $sectionIdentifier = $this->repository->sudo(function () use ($location) {
                return $location->getContent()->contentInfo->getSection()->identifier;
            });
            if ($contentType != 'country_homepage' and $sectionIdentifier != "standard") {
                if (!$this->authorizationChecker->isGranted('ROLE_USER')) {
                    $response = new RedirectResponse($pathToRedirect);
                    $cookie = new Cookie('not_auth', 'True', 0, '/', null, true, false);
                    $cookieRedirect = new Cookie(
                        'redirect_path',
                        $event->getRequest()->getUri(),
                        0,
                        $pathToRedirect,
                        null,
                        true,
                        false
                    );
                    $response->headers->setCookie($cookie);
                    $response->headers->setCookie($cookieRedirect);
                    $response->send();

                    return;
                }
            }

            if ($contentType === 'step' || $contentType === 'formation') {
                $currentUser = $this->accountHelper->currentUser();
                if (
                    $currentUser && $currentUser->getAPIUser()->getContentType()->identifier
                    !== self::USER_CONTENT_TYPE_IDENTIFIER
                ) {
                    return;
                }
                $firstStepLocationId = $this->stepSystemHelper->getFirstStepLocationId($locationId);
                if ($contentType === 'formation' && $firstStepLocationId) {
                    $locationId = $firstStepLocationId;
                }
                $this->stepSystemHelper->saveProgressStep($locationId, $currentUser->getAPIUser()->getUserId());
            }
        }
    }

    public function onKernelResponse(ResponseEvent $event)
    {
        try {
            if ($this->authorizationChecker->isGranted('ROLE_USER')) {
                $response = $event->getResponse();
                $response->headers->removeCookie('not_auth');
                $response->headers->removeCookie('redirect_path');
                $event->setResponse($response);
            }
        } catch (AuthenticationCredentialsNotFoundException $exception) {
            // nothing to do
        }
    }

    public function sitaccesGroup(): array
    {
        $result = [];
        for ($i = 0; $i < count($this->globalHelper->getSiteaccess()->groups); ++$i) {
            $result[$i] = $this->globalHelper->getSiteaccess()->groups[$i]->getName();
        }

        return $result;
    }
}