<?php
namespace App\Subscriber\UserGroups;
use App\Event\UserGroups\UserGroupPostCreatedEvent;
use App\Service\UserGroups\GroupService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class UserGroupPostSubscriber implements EventSubscriberInterface
{
/**
* @var GroupService
*/
protected $service;
/**
* UserGroupPostSubscriber constructor.
*/
public function __construct(GroupService $service)
{
$this->service = $service;
}
public static function getSubscribedEvents(): array
{
return [
UserGroupPostCreatedEvent::class => [
['onPostCalculateGroupStatPostCount', 0],
['onPostCreatedUpdateLastPostFields', 0],
],
];
}
/**
* @throws \Doctrine\DBAL\Exception
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
*/
public function onPostCalculateGroupStatPostCount(UserGroupPostCreatedEvent $event)
{
$group = $event->getEntity()->getThread()->getUserGroup();
$this->service->calculateUserGroupStatPostCount($group);
}
/**
* @throws \Doctrine\ORM\ORMException
* @throws \Doctrine\ORM\OptimisticLockException
*/
public function onPostCreatedUpdateLastPostFields(UserGroupPostCreatedEvent $event)
{
$post = $event->getEntity();
$thread = $post->getThread();
// update thread
$thread->setLastPost($post);
$thread->setPostCount($thread->getPostCount() + 1);
$this->service->storeEntity($thread);
// update last_post_at datetime
$stat = $thread->getUserGroup()->getUserGroupStat();
$stat->setLastPostAt($post->getCreatedAt());
$this->service->storeEntity($stat);
}
}