<?php
/**
* Created by PhpStorm.
* User: sebastiantovar
* Date: 2019-04-03
* Time: 16:47
*/
namespace App\EventSubscriber\Vendor;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\App\User;
use App\Entity\App\Vendor;
use App\MessageHandler\Message;
use App\Services\VendorService;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class VendorPostWriteSubscriber implements EventSubscriberInterface
{
private $vendorService;
private $messageBus;
private $parameterBag;
private $tokenStorage;
/**
* VendorPostWriteSubscriber constructor.
* @param TokenStorageInterface $tokenStorage
* @param ParameterBagInterface $parameterBag
* @param VendorService $vendorService
* @param MessageBusInterface $messageBus
*/
public function __construct( TokenStorageInterface $tokenStorage,ParameterBagInterface $parameterBag, VendorService $vendorService, MessageBusInterface $messageBus ) {
$this->vendorService = $vendorService;
$this->messageBus = $messageBus;
$this->parameterBag = $parameterBag;
$this->tokenStorage = $tokenStorage;
}
public function onKernelView(ViewEvent $event)
{
$vendor = $event->getControllerResult();
$request = $event->getRequest();
$method = $request->getMethod();
$route = $request->attributes->get('_route');
if (!($vendor instanceof Vendor))
return;
if (Request::METHOD_POST === $method) {
$data=[];
$userCurrent = $this->tokenStorage->getToken()->getUser();
$data['from'] = $this->parameterBag->has('ONBOARDING_FROM') ? $this->parameterBag->get('ONBOARDING_FROM') : null;
if(!is_null($data['from']) && $userCurrent instanceof User && in_array(trim($userCurrent->getEmail()),explode(",",$data['from']))) {
$data["vendor"] = $vendor;
$data["to"] = $this->parameterBag->has('ONBOARDING_TO') ? $this->parameterBag->get('ONBOARDING_TO') : null;
$this->messageBus->dispatch(new Message(Message::NEW_VENDOR, $data));
}
}
if ('api_vendors_post_collection' == $route || 'api_vendors_put_item' == $route) {
$mediaContent = $vendor->getMediaContent();
if ($mediaContent !== null && $mediaContent !== 0)
$this->vendorService->addMediaContent($vendor, $mediaContent);
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['onKernelView', EventPriorities::POST_WRITE]
];
}
}