<?php
namespace IndabaIbexportBundle\EventListener;
use Pimcore\Event\Model\ElementEventInterface;
use Pimcore\Event\Model\DataObjectEvent;
use Pimcore\Event\Model\AssetEvent;
use Pimcore\Event\Model\DocumentEvent;
use Pimcore\Db;
use Pimcore\Model\Asset;
use IndabaIbexportBundle\Model\IBExportConfiguration;
use IndabaPublicationBundle\Service\Helper;
/**
* Description of RelationsUpdateListener
*
* @author PcCom
*/
class RelationsUpdateListener
{
// in new version doesn't need, because they save id and not the filename
public function onPreAssetUpdate(ElementEventInterface $e)
{
if ($e instanceof AssetEvent) {
try {
$obj = $e->getAsset();
$cachedObj = Asset::getById($obj->getId(), ['force' => true]);
if ($cachedObj) {
if ($obj->getType() == "image" && method_exists($cachedObj, "getFilename")) {
$newfile = $obj->getFilename();
$oldfile = $cachedObj->getFilename();
if ($newfile != $oldfile) {
$db = Db::get();
$db->query("UPDATE `schrader_catalogue_structure` SET `configuration` = REPLACE (`configuration`, '" . $oldfile . "', '" . $newfile . "') WHERE `configuration` LIKE '%" . $oldfile . "%';");
}
}
}
} catch (\Exception $e) {
$error = $e->getMessage();
\Pimcore\Log\Simple::log("ObjectEventLog", "IBExportBundle preAssetsUpdate: " . $error);
}
}
}
public function onAssetDeleteInfo(ElementEventInterface $e)
{
if ($e instanceof AssetEvent) {
$asset = $e->getAsset();
if ("folder" != $asset->getType()) {
if ($this->inPublications($asset->getId())) {
$e->setDeletionAllowed(false);
$e->setReason("This asset \"" . $asset->getFilename() . "\" has any relations to publications. You must remove this relations before you can delete this asset");
}
} else {
foreach ($this->getAssetsInFolderIdList($asset) as $id) {
if ($this->inPublications($id)) {
$e->setDeletionAllowed(false);
$e->setReason("The assets in the folder \"" . $asset->getFilename() . "\" have any relations to publications. You must remove this relations before you can delete this folder");
break;
}
}
}
}
}
private function inPublications(int $id) : bool
{
$db = Db::get();
$asset = Asset::getById($id);
$filename = $asset->getFilename();
$query = "SELECT `id` FROM `schrader_catalogue_structure` WHERE `configuration` LIKE '%" . $filename . "%' OR `configuration` LIKE '%\"id\":" . $id . ",%' LIMIT 1;";
\Pimcore\Log\Simple::log("AssetDeleteInfo", $query);
$result = $db->query($query);
return ($result->rowCount() > 0) ? true : false ;
}
private function getAssetsInFolderIdList($asset)
{
$fullPath = $asset->getFullPath();
$list = new \Pimcore\Model\Asset\Listing();
$list->setCondition("path LIKE ? AND type NOT LIKE ?", [$fullPath . "/%", "folder"]);
return $list->loadIdList();
}
}