<?php
declare(strict_types=1);
namespace App\Service\Promocode;
use App\Repository\PromoCodeAdsRepository;
use App\Repository\PromoCodeRepository;
use Exception;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
class PromocodeApply
{
const SESSION_KEY_NAME = '_apply_promocode';
/**
* @var SessionInterface
*/
private $session;
/**
* @var PromoCodeRepository
*/
private $promoCodeRepository;
/**
* @var PromoCodeAdsRepository
*/
private $promoCodeAdsRepository;
public function __construct(
PromoCodeRepository $promoCodeRepository,
PromoCodeAdsRepository $promoCodeAdsRepository,
RequestStack $requestStack
) {
$this->session = $requestStack->getSession();
$this->promoCodeRepository = $promoCodeRepository;
$this->promoCodeAdsRepository = $promoCodeAdsRepository;
}
public function isApplyCode(): bool
{
if (!$this->session->has(self::SESSION_KEY_NAME)) {
return false;
}
if ($this->session->get(self::SESSION_KEY_NAME)) {
return true;
}
return false;
}
public function getCode(): ?string
{
if ($this->isApplyCode()) {
return $this->session->get(self::SESSION_KEY_NAME);
}
return null;
}
/**
* @throws Exception
*/
public function apply(string $code)
{
$adsCodeIsAvailable = $this->promoCodeAdsRepository->checkAvailableCode($code);
if (!$adsCodeIsAvailable) {
$userCodeIsAvailable = $this->promoCodeRepository->checkAvailableCode($code);
if (!$userCodeIsAvailable) {
throw new Exception('Промокод не найден. Попробуйте другой');
}
}
$this->session->set(self::SESSION_KEY_NAME, $code);
}
public function cancel(): void
{
$this->session->remove(self::SESSION_KEY_NAME);
}
}