<?php
declare(strict_types=1);
namespace App\Infrastructure\Security\Voter;
use App\Domain\Common\Entity\IzOrderProduct;
use App\Infrastructure\Elasticsearch\Factory\Product\ProductSearchFactory;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
final class ProductVoter extends Voter
{
public const VIEW = 'PRODUCT_VIEW';
private ProductSearchFactory $searchFactory;
public function __construct(ProductSearchFactory $searchFactory)
{
$this->searchFactory = $searchFactory;
}
protected function supports(string $attribute, $subject): bool
{
return self::VIEW === $attribute && $subject instanceof IzOrderProduct;
}
protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
{
if (self::VIEW === $attribute) {
$relatedProducts = $this->searchFactory->buildFromFilters([
/** @var IzOrderProduct $subject */
'recherche' => $subject->getCodeArticle1(),
], 1, 1)->search()->getResults();
return !empty($relatedProducts) && $relatedProducts[0]->getData()['id'] === $subject->getCodeArticle1();
}
return false;
}
}