<?php
/**
* @author Thomas HERISSON (contact@scaledev.fr)
* @copyright 2021 - ScaleDEV SAS, 12 RUE CHARLES MORET, 10120 ST ANDRE LES VERGERS
* @license commercial
*/
declare(strict_types=1);
namespace Bluue\ProjectsBundle\EventSubscriber\CrmBundle;
use ReflectionClass;
use App\Services\CheckBundleInstall;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Routing\RouterInterface;
use Bluue\CrmBundle\Entity\OpportunityDocument;
use Bluue\ProjectsBundle\Entity\ProjectQuotation;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class OpportunityViewLinksSubscriber implements EventSubscriberInterface
{
/**
* @var TranslatorInterface
*/
private TranslatorInterface $tr;
/**
* @var Security
*/
protected Security $security;
/**
* @var RouterInterface
*/
protected RouterInterface $router;
/**
* @var EntityManagerInterface
*/
protected EntityManagerInterface $em;
/**
* @param TranslatorInterface $tr
* @param Security $security
* @param RouterInterface $router
* @param EntityManagerInterface $em
*/
public function __construct(
TranslatorInterface $tr,
Security $security,
RouterInterface $router,
EntityManagerInterface $em
) {
$this->tr = $tr;
$this->security = $security;
$this->router = $router;
$this->em = $em;
}
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
if (CheckBundleInstall::exist('crm-bundle')) {
$reflectionClass = new ReflectionClass('Bluue\CrmBundle\Event\OpportunityViewLinksEvent');
return [
$reflectionClass->getConstant('LINKS') => 'links'
];
}
return [];
}
/**
* @param object $event
* @return void
*/
public function links(object $event): void
{
if (!$this->security->isGranted('ROLE__PROJECTS__READ_ONLY')) {
return;
}
$opportunityDocuments = $this->em->getRepository(OpportunityDocument::class)
->findBy(['opportunity' => $event->getId()]);
if (empty($opportunityDocuments)) {
return;
}
$projects = $newLinks = [];
foreach ($opportunityDocuments as $opportunityDocument) {
$quotation = $opportunityDocument->getQuotation();
if (!$quotation) {
continue;
}
$projectQuotation = $this->em->getRepository(ProjectQuotation::class)
->findOneBy(['quotation' => $quotation->getId()]);
if (!$projectQuotation) {
continue;
}
$project = $projectQuotation->getProject();
$projectId = (string) $project->getId();
if (!array_key_exists($projectId, $projects)) {
$projects[$projectId] = $project;
}
}
foreach ($projects as $project) {
$href = $this->router->generate(
'projects_bundle__project_view',
['id' => $project->getId(), 'step_id' => $project->getCurrentStep()->getId()]
);
$link = '<a href="' . $href . '" class="btn btn-sm btn-primary mb-2"><i class="fas fa-project-diagram">';
$link .= '</i> ' . $this->tr->trans('Project:', [], 'ProjectsBundle') . ' ' . $project->getName() . '</a>';
$newLinks[] = $link;
}
$event->setLinks(array_merge($event->getLinks(), $newLinks));
}
}