<?php
namespace App\Event\Admin;
use App\EasyAdmin\Dto\Tag;
use App\Entity\BlogPost;
use App\Entity\BlogTag;
use App\Repository\BlogContentRepository;
use App\Repository\BlogTagRepository;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\String\Slugger\AsciiSlugger;
class BlogPostSubscriber implements EventSubscriberInterface
{
/** @var BlogTagRepository */
private $tagRepository;
/** @var BlogContentRepository */
private $blogContentRepository;
public function __construct(
BlogTagRepository $tagRepository,
BlogContentRepository $blogContentRepository
)
{
$this->tagRepository = $tagRepository;
$this->blogContentRepository = $blogContentRepository;
}
public function onBeforeEntityPersistedEvent(BeforeEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if (!$entity instanceof BlogPost) {
return;
}
$this->prepareTags($entity);
$this->setContent($entity);
}
public function onBeforeEntityUpdatedEvent(BeforeEntityUpdatedEvent $event)
{
$entity = $event->getEntityInstance();
if (!$entity instanceof BlogPost) {
return;
}
$this->prepareTags($entity);
$this->setContent($entity);
}
private function setContent(BlogPost $post)
{
$contents = $post->getBlock();
foreach ($contents as $block) {
$this->blogContentRepository->add($block);
$block->setPost($post);
}
foreach ($post->getBlogContents() as $content) {
if (!$contents->contains($content)) {
$post->removeBlogContent($content);
}
}
}
private function prepareTags(BlogPost $post)
{
if (!$post->getRawTagValues()) {
return;
}
$dto = $post->getRawTagValues();
$names = array_map(function (Tag $tag) {
return mb_strtolower($tag->getTag());
}, $dto);
$tags = $this->tagRepository
->findByNames($names);
foreach ($tags as $tag) {
$post->addTag($tag);
$names = array_filter($names, function (string $v) use ($tag) {
return $v !== $tag->getName();
});
}
$slugger = new AsciiSlugger();
if (!empty($names)) {
foreach ($names as $newTag) {
$tag = new BlogTag();
$tag->setName($newTag);
$tag->setSlug($slugger->slug($newTag));
$this->tagRepository->add($tag);
$post->addTag($tag);
}
}
}
public static function getSubscribedEvents(): array
{
return [
BeforeEntityPersistedEvent::class => 'onBeforeEntityPersistedEvent',
BeforeEntityUpdatedEvent::class => 'onBeforeEntityUpdatedEvent'
];
}
}