<?php
namespace DownloadPdfBundle\EventListener;
use Pimcore\Event\Model\DataObjectEvent;
use Pimcore\Event\Model\ElementEventInterface;
use Pimcore\Model\Asset;
use Pimcore\Model\DataObject;
use Pimcore\Model\DataObject\ClassDefinition\CustomLayout;
use Pimcore\Model\DataObject\Service;
use Pimcore\Model\Element\ValidationException;
use Pimcore\Tool;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
class DownloadPdfListener implements EventSubscriberInterface
{
private $workflowRegistry;
protected $slugify;
const DOWNLOADPDF = 'download_pdf';
/**
* @param GenericEvent $event
*/
public function checkPermissions(GenericEvent $event): void
{
$object = $event->getArgument("object");
//data element that is send to Pimcore backend UI
$data = $event->getArgument("data");
$data['hasPreview'] = false;
$currentLayout = explode(",", "-1,1,2");
if ($object instanceof DataObject\DownloadPDF && !in_array($data['currentLayoutId'], $currentLayout)) {
$data = $this->f_setLayout($object, $data);
$event->setArgument("data", $data);
}
}
/**
* @param $object
* @param $data
* @return mixed
*/
public function f_setLayout($object, $data): mixed
{
DataObject\Product::setGetInheritedValues(true);
if ('variant' == $object->gettype()) {
$customLayoutToSelect = 9;
} elseif ($object->getPublished() == false && $object->gettype() != 'variant') {
$customLayoutToSelect = 8;
} elseif ($object->getPublished() == true && $object->gettype() != 'variant') {
$customLayoutToSelect = 10;
} else {
$customLayoutToSelect = 10;
}
if ($customLayoutToSelect != null) {
//set current layout to subcategory layout
$data['currentLayoutId'] = $customLayoutToSelect;
$customLayout = CustomLayout::getById($customLayoutToSelect);
$data['layout'] = $customLayout->getLayoutDefinitions();
Service::enrichLayoutDefinition($data["layout"], $object);
}
if (!empty($layoutsToRemove)) {
//remove master layout from valid layouts
$validLayouts = $data["validLayouts"];
foreach ($validLayouts as $key => $validLayout) {
if (in_array($validLayout['id'], $layoutsToRemove)) {
unset($validLayouts[$key]);
}
}
$data["validLayouts"] = array_values($validLayouts);
}
return $data;
}
/**
* @return array|\string[][]
*/
public static function getSubscribedEvents()
{
return [
'workflow.Download_pdf_Workflow.guard' => ['guardPublish'],
'workflow.Download_pdf_Workflow.leave' => ['onLeave'],
];
}
/**
* @param ElementEventInterface $event
*/
public function onPreUpdate(ElementEventInterface $event): void
{
if ($event instanceof DataObjectEvent) {
$objects = $event->getObject();
$this->checkValidation($objects);
if ($objects instanceof DataObject\DownloadPDF) {
$this->getPdfFiles($objects);
}
}
}
/**
* @param $objects
* @throws ValidationException
*/
public function checkValidation($objects): void
{
$errors =[];
if ($objects instanceof DataObject\DownloadPDF) {
if ($objects instanceof DataObject\DownloadPDF and $objects->gettype() != 'variant') {
$errors = [];
if ($objects->getLinkModel() == null || $objects->getLinkModel() == "" || (empty($objects->getLinkModel()))) {
$message = 'Link Model is required.';
array_push($errors, $message);
} else {
if (($objects->getLinkModel()->getModelCode() == null || $objects->getLinkModel()->getModelCode() == "") && ($objects->getLinkModel()->getType() == "variant")) {
$message = 'Empty Link Model Code Value, Please check Either Product Model or Sku Properly !';
array_push($errors, $message);
} else {
$objects->setKey($objects->getLinkModel()->getModelCode());
$objects->setUniqueCode($objects->getLinkModel()->getModelCode());
}
}
if ($objects->getPdfType() == null || $objects->getPdfType() == "" || (empty($objects->getPdfType()))) {
$message = 'Download Pdf Type is required.';
array_push($errors, $message);
}
} else {
// $downloadPdfCount = $this->getDownloadPdfMaxCount($objects);
$downloadPdfVariantSummaryJson = $this->getDownloadPdfSummary($objects);
if ($objects->getParent()->getUniqueCode() != null || $objects->getParent()->getUniqueCode() != "") {
$this->getDownloadPdfJsonReserve($downloadPdfVariantSummaryJson, $objects->getParent()->getId());
}
}
$this->getExceptionMessage($errors, $objects);
}
}
/**
* @param $skuMessages
* @param $object
* @throws ValidationException
*/
public function getExceptionMessage($skuMessages, $object): void
{
if (!empty($skuMessages)) {
$result = null;
foreach ($skuMessages as $skuMessage) {
$result .= $skuMessage . "<span style='color: red;'>*</span>" . '<br>';
}
throw new ValidationException($result, 403);
}
}
/**
* @param $objects
*/
public function getDownloadPdfSummary($objects): array
{
$downloadPdfSummaryObjects = [];
foreach (Tool::getValidLanguages() as $language) {
$downloadPdfAssetsLanguageDocuments = $objects->getDownloadPdf($language);
if (!empty($downloadPdfAssetsLanguageDocuments)) {
foreach ($downloadPdfAssetsLanguageDocuments as $downloadPdfAssetsLanguageDocument) {
$downloadPdfSummaryObjects[] = [
"$language" => $downloadPdfAssetsLanguageDocument->getElement()->getFileName(),
];
}
} else {
$downloadPdfSummaryObjects[] = [
"$language" => "#############",
];
}
}
$downloadPdfAssetsJsonDetails = [[
"code" => $objects->getUniqueCode(),
"languages" => $downloadPdfSummaryObjects
]];
return ($downloadPdfAssetsJsonDetails);
}
/**
* @param $downloadPdfVariantSummaryJson
* @param $parentUniqueCode
* @throws \Exception
*/
public function getDownloadPdfJsonReserve($downloadPdfVariantSummaryJson, $parentUniqueId)
{
$downloadPdfObjects = DataObject\DownloadPDF::getById($parentUniqueId);
if ($downloadPdfObjects) {
$productModelObject = DataObject\Product::getByModelCode($downloadPdfObjects->getUniqueCode(), 1);
if ($productModelObject) {
if (!empty($productModelObject->getDownloadPdfJson()) || $productModelObject->getDownloadPdfJson() != null || $productModelObject->getDownloadPdfJson() != "") {
$downloadPdfMergeJson = array_values(array_column(array_merge(json_decode($productModelObject->getDownloadPdfJson()), $downloadPdfVariantSummaryJson), null, "code"));
$productModelObject->setDownloadPdfJson(json_encode($downloadPdfMergeJson));
$productModelObject->setSkipValidation(true);
$productModelObject->setOmitMandatoryCheck(true);
$productModelObject->setPublished(true);
$productModelObject->save();
} else {
$productModelObject->setDownloadPdfJson(json_encode($downloadPdfVariantSummaryJson));
$productModelObject->setSkipValidation(true);
$productModelObject->setOmitMandatoryCheck(true);
$productModelObject->setPublished(true);
$productModelObject->save();
}
}
}
}
/**
* @param $objects
* @return int
*/
public function getDownloadPdfMaxCount($objects)
{
$count = 0;
foreach (Tool::getValidLanguages() as $language) {
if (count($objects->getDownloadPdf($language)) > $count) {
$count = count($objects->getDownloadPdf($language));
}
}
return $count;
}
public function getPdfFiles($objects)
{
$error= [];
if ($objects) {
foreach (Tool::getValidLanguages() as $language) {
if ($objects->getDownloadPdf() != null || !empty($objects->getDownloadPdf())) {
$targetPath = self::DOWNLOADPDF . '/' . $objects->getParent()->getUniqueCode() . '/' . $objects->getParent()->getUniqueCode() . '_' . $objects->getPdfTypeVariant() . '/' . 'pdf';
$destinationPath = '/' . self::DOWNLOADPDF . '/' . $objects->getParent()->getUniqueCode() . '/' . $objects->getParent()->getUniqueCode() . '_' . $objects->getPdfTypeVariant() . '/' . 'pdf/';
Asset\Service::createFolderByPath($targetPath);
$targetId = \Pimcore\Model\Asset::getByPath($destinationPath);
foreach ($objects->getDownloadPdf($language) as $obj) {
$this->LinkPdf($obj->getElementId(), $targetId->getId());
// if ($obj->getMimeType() != 'application/pdf') {
// $message = 'please insert pdf file';
// array_push($error, $message);
// continue;
// }
}
}
// $this->getExceptionMessage($error, $objects);
}
}
}
public function LinkPdf($data, $id){
$asset = Asset::getById($data);
$asset->setParentId($id);
$asset->save();
}
}