<?php
/**
* @author Quentin CHATELAIN (contact@scaledev.fr)
* @copyright 2021 - ScaleDEV SAS, 12 RUE CHARLES MORET, 10120 ST ANDRE LES VERGERS
* @license commercial
*/
declare(strict_types=1);
namespace App\Services;
use App\Repository\UserContextRepository;
use App\Repository\ContextRepository;
use App\Entity\Context as ContextEntity;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class Context
{
/**
* @var ObjectSerialize
*/
private ObjectSerialize $objectSerialize;
/**
* @var RequestStack
*/
private RequestStack $requestStack;
/**
* @var ContextRepository
*/
private ContextRepository $contextRepo;
/**
* @var TokenStorageInterface
*/
private TokenStorageInterface $tokenStorage;
/**
* @var UserContextRepository
*/
private UserContextRepository $userContextRepo;
/**
* @param ObjectSerialize $objectSerialize
* @param ContextRepository $contextRepo
* @param RequestStack $requestStack
* @param TokenStorageInterface $tokenStorage
* @param UserContextRepository $userContextRepo
*/
public function __construct(
ObjectSerialize $objectSerialize,
ContextRepository $contextRepo,
RequestStack $requestStack,
TokenStorageInterface $tokenStorage,
UserContextRepository $userContextRepo
) {
$this->objectSerialize = $objectSerialize;
$this->contextRepo = $contextRepo;
$this->requestStack = $requestStack;
$this->tokenStorage = $tokenStorage;
$this->userContextRepo = $userContextRepo;
}
/**
* @return ContextEntity|null
*/
public function getActual(): ?ContextEntity
{
$contextActual = null;
if ($this->requestStack->getMainRequest()) {
$AppContextSerialized = $this->requestStack->getSession()->get('_app_context');
if ($AppContextSerialized) {
$context = $this->objectSerialize->decode($AppContextSerialized);
$contextActual = $this->contextRepo->find($context->getId());
}
}
return $contextActual ?: null;
}
/**
* @return ContextEntity
*/
public function getActualOrDefault(): ContextEntity
{
return $this->getActual() ?: $this->contextRepo->getDefault();
}
/**
* @return array
*/
public function getUserContexts(): array
{
$userActive = $this->tokenStorage->getToken()->getUser();
$userContexts = $this->userContextRepo->findBy(['user' => $userActive]);
if ($userContexts) {
$contexts = [];
foreach ($userContexts as $userContext) {
$contexts[] = $userContext->getContext();
}
} else {
$contexts = $this->contextRepo->findAll();
}
return $contexts;
}
/**
* @param ContextEntity $context
* @return void
*/
public function setActual(ContextEntity $context): void
{
if ($this->requestStack->getMainRequest()) {
$this->requestStack->getSession()->set('_app_context', $this->objectSerialize->add($context));
}
}
}