<?php
/**
* Created by PhpStorm.
* User: Rémi
* Date: 19/06/2020
* Time: 11:02
*
* Copyright 2018-2019, Rémi Fongaufier, All rights reserved.
*/
namespace App\EventSubscriber;
use App\Entity\Attachment;
use App\Entity\Collection;
use App\Entity\Product;
use App\Entity\Project;
use App\Entity\Section;
use App\Service\FilePathAndUrlService;
use App\Service\LocaleService;
use App\Traits\CustomSlugify;
use Doctrine\ORM\EntityManagerInterface;
use Gedmo\Translatable\TranslatableListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
class EasyAdminSubscriber implements EventSubscriberInterface
{
use CustomSlugify;
private $entityManager;
/**
* @var FilePathAndUrlService
*/
private $filePathAndUrlService;
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var LocaleService
*/
private $localeService;
/**
* @var TranslatableListener
*/
private $projectDir;
public function __construct(EntityManagerInterface $entityManager, FilePathAndUrlService $filePathAndUrlService,
Filesystem $filesystem, LocaleService $localeService, $projectDir)
{
$this->entityManager = $entityManager;
$this->filePathAndUrlService = $filePathAndUrlService;
$this->filesystem = $filesystem;
$this->localeService = $localeService;
$this->projectDir = $projectDir;
}
public static function getSubscribedEvents()
{
return [
'easy_admin.pre_update' => ['preUpdateInitAttachments'],
'easy_admin.pre_persist' => ['prePersistInitAttachments'],
'easy_admin.post_remove' => ['postRemoveEvent'],
];
}
public function preUpdateInitAttachments(GenericEvent $event)
{
$this->renameSection($event);
$this->initAttachments($event);
}
public function prePersistInitAttachments(GenericEvent $event)
{
$this->renameSection($event);
$this->initAttachments($event);
}
public function postRemoveEvent(GenericEvent $event)
{
$this->renameSection($event);
$this->entityManager->flush();
}
public function initAttachments(GenericEvent $event)
{
$subject = $event->getSubject();
if (!($subject instanceof Section || $subject instanceof Project
|| $subject instanceof Product || $subject instanceof Collection))
return;
$currentObject = strtolower(explode('\\', get_class($subject))[2]);
$attachmentsFromFile = [];
if ($event->getArguments()['request']->files->get('collection') !== null || $event->getArguments()['request']->files->get($currentObject) !== null) {
$attachmentsFromFile = $event->getArguments()['request']->files->get('collection') !== null ?
$event->getArguments()['request']->files->get('collection')['attachments'] :
$event->getArguments()['request']->files->get($currentObject)['attachments'];
}
$attachmentsFromRequest = isset($event->getArguments()['request']->request->get($currentObject)['attachments']) ?
$event->getArguments()['request']->request->get($currentObject)['attachments'] : [];
foreach ($attachmentsFromFile as $id => $el) {
if ($el['image'] !== null) {
if (isset($attachmentsFromRequest[$id]) && $this->entityManager->getRepository(Attachment::class)->find($attachmentsFromRequest[$id]['id'])) {
$attachment = $this->entityManager->getRepository(Attachment::class)->find($attachmentsFromRequest[$id]['id']);
if (!$this->filesystem->exists($this->projectDir . '/public/' . $attachment->getFullPath()))
$attachment->setId(null);
} else {
$attachment = new Attachment();
}
$file = $el['image'];
$fileName = $this->filePathAndUrlService->getFileName($subject, $file);
$path = $this->filePathAndUrlService->getFilePath($subject);
$attachment->setName($fileName);
$attachment->setPath($path);
$attachment->setSize($file->getSize());
$attachment->setToShow(isset($attachmentsFromRequest[$id]['toShow']) ? $attachmentsFromRequest[$id]['toShow'] :
(isset($event->getArguments()['request']->request->get('collection')['attachments'][$id]['toShow']) ?
$event->getArguments()['request']->request->get('collection')['attachments'][$id]['toShow'] : false)
);
$attachment->setId((int)$id);
if ($subject instanceof Product)
$attachment->setProduct($subject);
if ($subject instanceof Project)
$attachment->setProject($subject);
if ($subject instanceof Collection)
$attachment->setCollection($subject);
if ($subject instanceof Section)
$attachment->setSection($subject);
$subject->addAttachment($attachment);
//$this->entityManager->persist($attachment);
if (isset($event->getArguments()['request']->request->get('collection')['attachments'][$id]['caption']))
$attachment->setCaption($event->getArguments()['request']->request->get('collection')['attachments'][$id]['caption']);
try {
if (!$this->filesystem->exists($this->projectDir . '/public/' . $attachment->getPath()))
$this->filesystem->mkdir($this->projectDir . '/public/' . $attachment->getPath(), 0777);
$file->move(
$this->projectDir . '/public/' . $attachment->getPath(),
$attachment->getName()
);
} catch (FileException | IOExceptionInterface $e) {
dd($e->getMessage());
}
}
}
$this->saveSubjectTranslations($subject);
$attachments = $subject->getAttachments()->getValues();
foreach ($attachments as $index => $attachment) {
if ($attachment->getId() === null || !$this->filesystem->exists($this->projectDir . '/public/' . $attachment->getFullPath())
|| $attachment->getName() === null) {
$subject->removeAttachment($attachment);
/*$this->entityManager->remove($attachment);*/
unset($attachments[$index]);
}
}
$this->localeService->saveFieldTranslationsFromEntities($attachments, 'caption');
if ($subject instanceof Product) {
$name = $subject->getName();
$slug = $this->slugify($name);
$subject->setSlug($slug);
}
$this->entityManager->persist($subject);
$this->entityManager->flush();
}
public function removeAttachment($attachment, $subject)
{
$subject->removeAttachment($attachment);
$this->entityManager->detach($attachment);
if ($attachment->getId()) {
$conn = $this->entityManager->getConnection();
$sql = "DELETE FROM `ext_translations` " .
"WHERE `object_class` = 'App\\Entity\\Attachment' and `foreign_key` = " . $attachment->getId();
$stmt = $conn->prepare($sql);
$stmt->execute();
$sql = "DELETE FROM `attachment` WHERE `id` = " . $attachment->getId();
$stmt = $conn->prepare($sql);
$stmt->execute();
}
}
public function saveSubjectTranslations($subject)
{
if ($subject instanceof Product) {
$this->localeService->saveFieldTranslationsFromEntity($subject, 'description');
}
if ($subject instanceof Project) {
$this->localeService->saveFieldTranslationsFromEntity($subject, 'description');
}
if ($subject instanceof Collection) {
$this->localeService->saveFieldTranslationsFromEntity($subject, 'description');
}
if ($subject instanceof Section) {
$slugs = [];
foreach ($subject->getDesignation() as $key => $designation) {
$slugs[$key] = $this->slugify($designation);
}
$subject->setName("Section " . (count($subject->getSeoPage()->getSections()) + 1));
$subject->setSlug($slugs);
$this->localeService->saveFieldTranslationsFromEntity($subject, 'slug');
$this->localeService->saveFieldTranslationsFromEntity($subject, 'designation');
$this->localeService->saveFieldTranslationsFromEntity($subject, 'content');
}
}
public function renameSection($event)
{
$subject = $event->getSubject();
if ($subject instanceof Section) {
if ($subject->getSeoPage()) {
$seoPage = $subject->getSeoPage();
$sections = $seoPage->getSections();
if (isset($seoPage)) {
foreach ($sections as $index => $section) {
$section->setName("Section " . ($index + 1));
if ($section->getId() === $subject->getId())
$subject->setName("Section " . ($index + 1));
$this->entityManager->persist($section);
}
}
}
}
}
}