<?php
namespace AppBundle\EventListener;
use AppBundle\Exception\AssetDeployerException;
use AppBundle\Services\SftpFileTransferService;
use Exception;
use Pimcore;
use Pimcore\Event\Model\AssetEvent;
use Pimcore\Model\Asset;
use Pimcore\Model\WebsiteSetting;
class AssetPreUpdateListener
{
const TWIST_INTERNAL_DEPLOY_FOLDER_NAME = "Dossier pimcore d'assets transferable vers twist (usage interne)";
const IS_DEPLOYED = 'Fichier transféré';
const TARGET_FOLDER = 'Dossier distant de dépot du fichier (pour twist)';
/**
* @param AssetEvent $event
* @throws AssetDeployerException
*/
public function onSaveTwistInternalAsset(AssetEvent $event)
{
if (Pimcore::inAdmin()) {
$asset = $event->getAsset();
if ($this->isAssetInTwistDeployFolder($asset)) {
if (!$this->hasDeployProperties($asset)) {
$this->addDeployProperties($asset);
} else {
if (!$this->isAlreadySent($asset)) {
$this->sendToTwist($asset);
}
}
}
}
}
/**
* @param Asset $asset
* @return bool
*/
protected function isAssetInTwistDeployFolder(Asset $asset): bool
{
$twistDeployFolder = WebsiteSetting::getByName(self::TWIST_INTERNAL_DEPLOY_FOLDER_NAME)->getData();
if ($twistDeployFolder) {
$parent = $asset->getParent();
while ($parent->getId() !== 1) {
if ($parent->getId() === $twistDeployFolder->getId()) {
return true;
}
$parent = $parent->getParent();
}
}
return false;
}
/**
* @param Asset $asset
* @return bool
*/
protected function hasDeployProperties(Asset $asset): bool
{
return $asset->hasProperty(self::IS_DEPLOYED) && $asset->hasProperty(self::TARGET_FOLDER);
}
/**
* @param Asset $asset
*/
protected function addDeployProperties(Asset $asset)
{
$asset->setProperty(self::IS_DEPLOYED, 'bool', false);
$asset->setProperty(self::TARGET_FOLDER, 'text', '');
}
/**
* @param Asset $asset
* @return bool
*/
protected function isAlreadySent(Asset $asset): bool
{
return $asset->getProperty(self::IS_DEPLOYED);
}
/**
* @param Asset $asset
* @throws AssetDeployerException
* @throws Exception
*/
protected function sendToTwist(Asset $asset)
{
$destination = $asset->getProperty(self::TARGET_FOLDER);
if ($destination === '') {
throw new AssetDeployerException('you need to define target path for this feature');
}
SftpFileTransferService::transferFileToTwist($asset->getFileSystemPath(), $destination, $asset->getFilename());
$asset->setProperty(self::IS_DEPLOYED, 'bool', true);
}
}