<?php
namespace App\EventListener;
use App\Model\Product\AutoFields;
use App\Model\Product\LandedCost;
use App\Model\Product\TariffCode;
use App\Model\Product\Wholesale\PriceTable;
use App\Services\ExportService;
use Jabber\GenericBundle\EventListener\PimcoreAdmin;
use Jabber\ObjectDropdownBundle\Cache\Memcached\CacheKeys;
use Jabber\ObjectDropdownBundle\Objects\OptionsProvider;
use Pimcore;
use Pimcore\Event\Model\ElementEventInterface;
use Pimcore\Event\Model\DataObjectEvent;
use Pimcore\Event\Model\AssetEvent;
use Pimcore\Event\Model\DocumentEvent;
use Pimcore\Model\Asset;
use Pimcore\Model\DataObject;
use Pimcore\Model\DataObject\Product;
use Pimcore\Model\DataObject\Retailer;
use Pimcore\Model\DataObject\Size;
use Pimcore\Model\DataObject\SizeGroup;
use Pimcore\Model\DataObject\SizeGroup\Listing;
use Pimcore\Model\User\AbstractUser;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Pimcore\Model\DataObject\Barcodes\Listing as BarcodeListing;
use Pimcore\Model\DataObject\Collections;
use Pimcore\Model\DataObject\Colour;
use Pimcore\Model\DataObject\Department;
use Pimcore\Model\DataObject\MainGroup;
use Pimcore\Model\DataObject\SubGroup;
class ObjectUpdateListener {
private $params;
public function __construct(ParameterBagInterface $params) {
$this->params = $params;
}
private function IsSystemUser($dataObject) {
$user = \Pimcore\Model\User::getById($dataObject->getUserModification());
if ($user instanceof \Pimcore\Model\User) {
if ($user->getId() == 0) {
return true;
}
if (!empty($this->params->get('system_user_id'))) {
if ($user->getParentId() == $this->params->get('system_user_id')) {
return true;
}
}
}
return false;
}
public function onPostUpdate (ElementEventInterface $e) {
if (!$e->hasArgument('isAutoSave')) {
if($e instanceof AssetEvent) {
// do something with the asset
$foo = $e->getAsset();
} else if ($e instanceof DocumentEvent) {
// do something with the document
$foo = $e->getDocument();
} else if ($e instanceof DataObjectEvent) {
// do something with the object
$dataObject = $e->getObject();
if ($dataObject instanceof Product) {
$dirtyDetection = $dataObject->isDirtyDetectionDisabled();
if ($dataObject->getType() == "variant") {
$this->PublishChildren($dataObject);
}
} else {
$this->ClearCachedData($dataObject); //Has to be within the post and not pre otherwise the updated value will not be read
}
}
}
}
public function onPreUpdate (ElementEventInterface $e) {
if (!$e->hasArgument('isAutoSave')) {
if($e instanceof AssetEvent) {
// do something with the asset
$foo = $e->getAsset();
} else if ($e instanceof DocumentEvent) {
// do something with the document
$foo = $e->getDocument();
} else if ($e instanceof DataObjectEvent) {
// do something with the object
$dataObject = $e->getObject();
if (!$this->IsSystemUser($dataObject)) {
$parentPath = $dataObject->getParent();
$baseFolder = $this->GetBaseFolder($parentPath);
if ($dataObject instanceof Product) {
$autoFields = new AutoFields();
$dataObject = $autoFields->ProductLevel($dataObject);
if ($dataObject->getType() == "variant") {
if ($dataObject->isPublished() == false) {
//$dataObject = $this->GenerateSKU($dataObject);
}
$this->CheckVariantMandatoryFields($dataObject);
$dataObject = $this->getSizeRange($dataObject);
$dataObject = $this->AddWholesalePrices($dataObject);
$dataObject = $this->LandedCostTable($dataObject);
//$dataObject = $this->GetBarcode($dataObject);
$dataObject = $autoFields->LaunchMonth($dataObject);
//$dataObject = $this->GetSimilarWeight($dataObject);
//$this->ValidateTariffCode($dataObject);
} else if ($dataObject->getType() == "object") {
//$dataObject = $this->GetClassificationStore($dataObject);
$dataObject = $this->MoveObject($dataObject);
$this->CheckMaterialPercentage($dataObject);
}
if (method_exists($dataObject, "getImages")) {
//$this->ChangeImagePaths($dataObject);
//$this->AddImageMetaDataAndChangePath($dataObject);
}
} else if ($dataObject instanceof SizeGroup) {
$dataObject = $this->ReorderSizeGroup($dataObject);
}
if (
get_class($dataObject) == "Pimcore\Model\DataObject\Colour" || get_class($dataObject) == "Pimcore\Model\DataObject\Size" || get_class($dataObject) == "Pimcore\Model\DataObject\Supplier" || get_class($dataObject) == "Pimcore\Model\DataObject\Contact"
) {
$exportCheck = $dataObject->getProperty("EXPORTED_PRIAM");
if (($exportCheck === false || empty($exportCheck)) && $dataObject->getPublished() == true) {
$exportService = new ExportService($this->params);
$exportService->GenerateExport([$dataObject], null, null, null, true);
$dataObject->setProperty("EXPORTED_PRIAM", "bool", true);
}
}
}
}
}
}
private function GetBarcode($dataObject) {
if ($this->GetLevel($dataObject) == 3) {
$currentBarcode = $dataObject->getEAN();
if (empty($currentBarcode)) {
$barcodeObject = new BarcodeListing();
$barcodeObject->filterByUsed(0, "=");
$barcodeObject->setLimit(1);
foreach ($barcodeObject as $barcode) {
$barcode->setProduct($dataObject);
$barcode->setUsed(true);
$barcode->save();
$dataObject->setEAN($barcode->getBarcode());
break;
}
}
}
return $dataObject;
}
private function ReorderSizeGroup(SizeGroup $dataObject) {
$sizeList = [];
if (is_iterable($dataObject->getSize())) {
foreach ($dataObject->getSize() as $size) {
$sizeList[] = $size;
}
sort($sizeList);
//throw new \Exception(json_encode($sizeList));
$dataObject->setSize($sizeList);
}
return $dataObject;
}
private function ValidateTariffCode($dataObject) {
if ($dataObject->getPublished() == true) {
$tariffObject = new TariffCode();
$tariffCode = $this->GetInheritedField($dataObject, 'IETariffCode');
$validCode = $tariffObject->ValidateTariffCode($tariffCode);
if ($validCode == false) {
throw new \Pimcore\Model\Element\ValidationException('The selected tariff code is invalid. Your product cannot be saved');
}
}
}
private function PublishChildren(DataObject $dataObject) {
if ($dataObject->getParent()->getType() == "object") {
if ($dataObject->isPublished()) {
foreach ($dataObject->getChildren([DataObject::OBJECT_TYPE_VARIANT], true) as $child) {
if (!$child->isPublished()) {
$child->setPublished(true);
$child->save();
}
}
} else {
foreach ($dataObject->getChildren([DataObject::OBJECT_TYPE_VARIANT]) as $child) {
$child->setPublished(false);
$child->save();
}
}
}
// if ($dataObject->isPublished()) {
// if ($dataObject->getParent()->getType() == "object") {
// $versions = $dataObject->getVersions();
// if (isset($versions[count($versions)-2])) {
// $previousVersion = $versions[count($versions)-2];
// $previousObject = $previousVersion->getData();
// if ($previousObject->getPublished() == false) {
// // $productQuery = new Product\Listing();
// // $productQuery->filterByPublished(false);
// // $productQuery->setCondition('o_parentId = ?', [$dataObject->getId()]);
// // foreach($productQuery as $child) {
// // $child->setPublished(true);
// // $child->save();
// // }
// foreach ($dataObject->getChildren([DataObject::OBJECT_TYPE_VARIANT], true) as $child) {
// if ($child->getPublished() == false) {
// $child->setPublished(true);
// $child->save();
// }
// }
// }
// } else {
// foreach ($dataObject->getChildren([DataObject::OBJECT_TYPE_VARIANT], true) as $child) {
// if ($child->getPublished() == false) {
// $child->setPublished(true);
// $child->save();
// }
// }
// }
// }
// }
}
public function GetInheritedField($product, $field, $minLevel = 0) {
if (!is_object($product)) {
$product = Product::GetById($product, false);
}
if ($product->getType() == "object" && $minLevel > 0) {
return;
}
$function = "get$field";
$responseData = $product->$function();
if (empty($responseData) && $product->getType() != "object") {
return $this->GetInheritedField($product->getParent(), $field, $minLevel);
} else {
return $responseData;
}
}
/**
* Intercepts the users save commmand and checks mandatory data that is not mandatory at the parent level
*
* Mandatory fields are specified in the parameter bag in the services file
*
* @param DataObject $dataObject
* @return void
* @throws \Pimcore\Model\Element\ValidationException
*/
private function CheckVariantMandatoryFields(DataObject $dataObject) {
if ($dataObject->getPublished() == true) {
$variantMandatoryFields = $this->params->get('variant_mandatory_fields');
$productDepth = $this->GetLevel($dataObject);
if (isset($variantMandatoryFields['Product']['Lvl'.$productDepth])) {
$fieldList = $variantMandatoryFields['Product']['Lvl'.$productDepth];
foreach ($fieldList as $requiredField) {
$function = "get" . $requiredField;
if (method_exists($dataObject, $function)) {
if (empty($this->GetInheritedField($dataObject, $requiredField, 0))) {
throw new \Pimcore\Model\Element\ValidationException("The mandatory field $requiredField has not been populated. To publish your product this data first needs to be entered. (" . $dataObject->getId() . " - ". $dataObject->getUserModification() . ")");
}
}
}
}
}
}
/**
* Returns the level of the product so we know if it is a colour or size variant
*
* @param DataObject $dataObject
* @return integer
*/
private function GetLevel(DataObject $dataObject) {
$levelCount = 0;
do {
$levelCount++;
$dataObject = $dataObject->getParent();
if ($levelCount > 5) {
break;
}
} while ($dataObject->getType() != "folder");
return $levelCount;
}
private function GenerateSKU(DataObject $dataObject) {
$sku = "";
//$styleCode = explode(".", $dataObject->getSKU())[0];
$styleCode = $dataObject->getSKU();
if ($dataObject->getType() == "variant") {
$styleCode = $dataObject->getParent()->getSKU();
}
$sku = $styleCode;
$colourCode = $this->GetColourCode($dataObject);
$sizeCode = $this->GetSizeCode($dataObject);
if (!empty($colourCode)) {
$sku = $styleCode . "." . $colourCode;
}
if (!empty($sizeCode)) {
$sku = $sku . "." . $sizeCode;
}
if ($dataObject->getSKU() != $sku && $dataObject->getChildAmount(false) > 0) {
//Change child sku values
$this->AlterChildSKUs($dataObject, $styleCode, $colourCode);
}
$dataObject->setSKU($sku);
$dataObject->setKey($sku);
return $dataObject;
}
private function UpdateStatus(DataObject $dataObject) {
$status = "NEW";
$user = AbstractUser::getById($dataObject->getUserModification());
$userName = "system";
if (!empty($user)) {
$userName = $user->getName();
}
if (strpos($dataObject->getFullPath(), "Archive") !== false) {
$status = "ARCHIVED";
} elseif ($dataObject->getCreationDate() == $dataObject->getModificationDate() || $userName == "system") {
$status = "NEW";
} else {
if ($dataObject->getProperty("EXPORTED_PRIAM") == true) {
$status = "CREATED";
} else {
$status = "EDITING";
}
}
$dataObject->setStatus($status);
return $dataObject;
}
private function ClearCachedData($dataObject) {
if (!$dataObject instanceof Product) {
$class = get_class($dataObject);
$className = str_replace("Pimcore\\Model\\DataObject\\", "", $class);
$cacheKeyProvider = new CacheKeys();
$response = $cacheKeyProvider->DeleteAllKeysContainingString("selectoptions_{$className}_");
//throw new \Exception(json_encode($keyList));
$this->RecacheData($className, $class);
}
}
private function RecacheData($className, $classPath) {
if (in_array($className, ['Department', 'MainGroup', 'SubGroup', 'Collections', 'Season', 'ColourGroup', 'Size', 'Colour', 'SizeGroup', 'Brand'])) {
$cacheValues = [];
$objectListing = new $classPath();
$optionsProvider = new OptionsProvider();
$optionsProvider->GenerateFilteredOptions($objectListing, $className);
// $objectList = $objectListing->getList();
// $classFiltering = method_exists($objectList->current(), 'getAllowedClasses');
// $idGetter = method_exists($objectList->current(), 'get' . $className . 'ID') ? 'get' . $className . 'ID' : null;
// if (!empty($idGetter)) {
// foreach ($objectList as $object) {
// $cacheValues['all'][] = ["key"=>$object->getName('en_GB'), "value"=>$object->$idGetter()];
// if ($classFiltering == true) {
// foreach ($object->getAllowedClasses() as $allowedClass) {
// $cacheValues[$allowedClass->__toString()][] = ["key"=>$object->getName('en_GB'), "value"=>$object->$idGetter()];
// }
// }
// }
// $cache = new \Memcached();
// $cache->addServer('localhost', 11211);
// foreach ($cacheValues as $key=>$value) {
// $escapedKey = preg_quote($key);
// $escapedKey = str_replace(" ", "", $escapedKey);
// //apcu_add("selectoptions_{$className}_{$escapedKey}", $value);
// $cache->add("selectoptions_{$className}_{$escapedKey}", $value);
// //\Pimcore\Log\Simple::log("TestEventListener", "added key: " . "selectoptions_{$className}_{$escapedKey}");
// }
// }
}
}
private function GetClassificationStore(DataObject $dataObject) {
//$pathArray = explode("/",$dataObject->getPath());
$classifiction = [];
$classifiction[] = $dataObject->getDepartment();
$classifiction[] = $dataObject->getMainGroup();
$classifiction[] = $dataObject->getSubGroup();
//
$storeId = 1;
$groupConfig = new \Pimcore\Model\DataObject\Classificationstore\GroupConfig();
//$groupConfig->
$activeGroup = [];
foreach ($classifiction as $path) {
if (!empty($path)) {
for ($i = 0; $collection = $groupConfig->getByName("{$path}_{$i}"); ++$i) {
if (empty($collection)) {
break;
}
$activeGroup[$collection->getId()] = true;
}
}
}
$dataObject->getClassificationData()->setActiveGroups($activeGroup);
return $dataObject;
//$dataObject->getTestStore()-
}
private function LandedCostTable(Product $dataObject) {
try {
$landedCost = new LandedCost();
$dataObject = $landedCost->AddToHistory($dataObject);
} catch (\Exception $e) {
}
return $dataObject;
}
private function AddWholesalePrices(Product $dataObject) {
try {
$wholesaleClass = new PriceTable();
$newDataObject = $wholesaleClass->AddWholesalePrice($dataObject);
return $newDataObject;
} catch (\Exception $e) {
return $dataObject;
}
}
private function getSizeRange($product) {
//if (empty($product->getSizeGroup())) {
if (empty($product->getSize()) && empty($product->getSizeGroup())) {
$childList = $product->getChildren([$product::OBJECT_TYPE_VARIANT]);
$sizeList = [];
$sizeListNames = [];
foreach ($childList as $child) {
$sizeName = Size::getBySizeID($child->getSize());
if (method_exists($sizeName, 'current') && $sizeName->current() instanceof Size) {
$sizeListNames[] = $sizeName->current()->getName();
$sizeList[] = $child->getSize();
}
}
$sizeCondition = "Size = ',";
$sizeCondition .= implode(",", $sizeList);
$sizeCondition .= ",'";
$sizeListing = new \Pimcore\Model\DataObject\SizeGroup\Listing();
$sizeListing->setCondition($sizeCondition);
if (!empty($sizeListing->current())) {
$product->setSizeGroup($sizeListing->current()->getName('en_GB'), 'en_GB');
$product->setSizeGroup($sizeListing->current()->getName('en_US'), 'en_US');
} else {
if (empty($product->getSizeGroup())) {
$product->setSizeGroup(implode(",", $sizeList));
}
}
}
//}
return $product;
}
/**
* Reviews the Fabric Composition field on an object to ensure that the percentages are correct and a fabric has not been duplicated
*
* @param Product $dataObject
* @return void
*/
private function CheckMaterialPercentage(Product $dataObject) {
$materialComp = $dataObject->getFabricComposition();
$materialArray = [];
$percentage = 0;
if (is_iterable($materialComp)) {
foreach ($materialComp as $material) {
$percentage += $material->getPercentage();
if (key_exists($material->getFabric(), $materialArray)) {
throw new \Exception("You have duplicated a fabric in the Fabric Composition field.");
}
$materialArray[$material->getFabric()] = 1;
if ($percentage > 100) {
throw new \Exception("The cumulative percentage of your Fabric Composition field is greater than 100%. Please correct your percentages to continue.");
}
}
if ($percentage > 0 && $percentage < 100) {
throw new \Exception("Your Fabric Composition adds up to $percentage%. Please ensure this equals 100% before continuing.");
}
}
}
/**
* Moves a product to the correct folder
*
* Changes may be made if a product has been archived or department/maingroup/subgroup is modified
*
* @param DataObject $dataObject
* @return DataObject
*/
private function MoveObject(DataObject $dataObject) {
$dataObject = $this->GetParentFromAttributes($dataObject);
$properties = $dataObject->getProperties();
foreach ($properties as $property) {
if ($property->getName() == "ARCHIVED") {
if ($property->getData() == true) {
$parentDirectory = $this->GetArchivePath((string) $dataObject->getParent());
} else {
$parentDirectory = $this->GetNonArchivePath((string) $dataObject->getParent());
}
if ($parentDirectory instanceof DataObject && $parentDirectory->getType() == "folder") {
$dataObject->setParent($parentDirectory);
return $dataObject;
}
}
}
return $dataObject;
}
private function GetParentFromAttributes(DataObject $dataObject) {
$path = "/Products";
try {
if (!empty($dataObject->getDepartment()) && !empty($dataObject->getMainGroup()) && !empty($dataObject->getSubGroup())) {
$departmentObject = Department::getByDepartmentID($dataObject->getDepartment());
$maingroupObject = MainGroup::getByMainGroupID($dataObject->getMainGroup());
$subgroupObject = SubGroup::getBySubGroupID($dataObject->getSubGroup());
if (method_exists($departmentObject, "current") && method_exists($maingroupObject, "current") && method_exists($subgroupObject, "current")) {
$path .= "/" . $departmentObject->current()->getName();
$path .= "/" . $maingroupObject->current()->getName();
$path .= "/" . $subgroupObject->current()->getName();
$object = new DataObject();
$parentObject = $object->getByPath($path);
if ($parentObject instanceof DataObject && $parentObject->getType() == "folder") {
$dataObject->setParent($parentObject);
}
}
}
} catch (\Exception $e) {
die($e->getMessage());
}
return $dataObject;
}
/**
* Retrieves the archive path at the correct level given the passed directory structure
*
* @param string $path
* @param integer $archiveDepth
* @return DataObject
*/
private function GetArchivePath($path, $archiveDepth = 2) {
$explodedPath = explode("/", $path);
$archiveSections = [];
foreach ($explodedPath as $key=>$value) {
$archiveSections[] = $value;
if ($key == $archiveDepth) {
$archiveSections[] = "Archive";
}
}
$archivePath = implode("/", $archiveSections);
$dataObject = new DataObject();
return $dataObject->getByPath($archivePath);
}
private function GetNonArchivePath($path) {
$path = str_replace("/Archive", "", $path);
$dataObject = new DataObject();
return $dataObject->getByPath($path);
}
private function GeneratePriamExport(DataObject $dataObject) {
if ($dataObject->isPublished()) {
if (get_class($dataObject) == "Pimcore\Model\DataObject\Colour") {
$dirPath = $this->params->get('priam_export_colour');
$fileName = "interface_import_colours_".date("YmdHis").".csv";
$data = [
['Season_identifier', 'Colour_identifier', 'Description', 'Short_description'],
[null, $dataObject->getColourID(), $dataObject->getName(), null]
];
} else if (get_class($dataObject) == "Pimcore\Model\DataObject\Size") {
$dirPath = $this->params->get('priam_export_size');
$fileName = "interface_import_sizes_".date("YmdHis").".csv";
$data = [
['Size_code', 'Description', 'Short_description'],
[$dataObject->getSizeID(), $dataObject->getName(), null]
];
}
$fp = fopen($dirPath . "/" . $fileName, 'w+');
foreach ($data as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
}
}
private function CreateERPItem($dataObject) {
$erpId = $dataObject->getProperty("erp_id");
if (empty($erpId)) {
$curl = curl_init();
$params = [
'ref'=>$dataObject->getSKU(),
'label'=>$dataObject->getTitle(),
'description'=>$dataObject->getDescription(),
'price'=>$dataObject->getPricingCost()
];
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://erp.thebroady.co.uk/api/index.php/products',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => http_build_query($params),
CURLOPT_HTTPHEADER => array(
'DOLAPIKEY: b8eiW04DlZt3Pgp3MAu2n5GFD4CfE02d',
'Content-Type: application/x-www-form-urlencoded'
),
));
$response = curl_exec($curl);
curl_close($curl);
$dataObject->setProperty("erp_id","Text",$response);
}
}
/**
* Renames image paths to become the same as the object
*
* @param DataObject $dataObject
* @param Asset $image
* @return Asset
*/
private function ChangeImagePaths($dataObject, $image) {
$assetFolder = $this->DoesAssetFolderExist($dataObject);
$image->setParent($assetFolder);
return $image;
}
private function SaveAsset(Asset\Image $image) {
$fullPath = $image->getParent()->getfullPath() . "/" . $image->getFilename();
$existingAsset = Asset::getByPath($fullPath);
if ($existingAsset instanceof Asset) {
$existingData = $existingAsset->getData();
$imageData = $image->getData();
if ($existingAsset->getData() == $image->getData()) {
$image->save();
// The existing image is the same as the one being uploaded
} else {
$pathInfo = pathinfo($image->getFilename());
$image->setFilename("0_" . $pathInfo['filename'] . "." . $pathInfo['extension']);
$image->save();
}
} else {
$image->save();
}
}
/**
* Add metadata from the product to the image
*
* @param Product $dataObject
* @return void
*/
private function AddImageMetaDataAndChangePath(Product $dataObject) {
$images = $dataObject->getImages();
foreach ($images as $hotspotImage) {
if (!empty($hotspotImage)) {
$image = $hotspotImage->getImage();
if (!empty($image) && is_object($image)) {
if (method_exists($image, "addMetadata")) {
$image = $this->AddImageMetaData($image, $dataObject);
$image = $this->ChangeImagePaths($dataObject, $image);
$this->SaveAsset($image);
}
}
}
}
$mannequin = $dataObject->getMannequinShot();
foreach ($mannequin as $hotspotImage) {
if (!empty($hotspotImage)) {
$image = $hotspotImage->getImage();
if (!empty($image) && is_object($image)) {
if (method_exists($image, "addMetadata")) {
$image = $this->AddImageMetaData($image, $dataObject, false, true);
$image = $this->ChangeImagePaths($dataObject, $image);
$image->save();
}
}
}
}
$cad = $dataObject->getCad();
if (!empty($cad) && is_object($cad) && method_exists($cad, "addMetadata")) {
$cad = $this->AddImageMetaData($cad, $dataObject, true);
$cad = $this->ChangeImagePaths($dataObject, $cad);
//$cad->save();
}
}
private function AddImageMetaData($image, $dataObject, $cad = false, $mannequin = false) {
if ($cad == true) {
$image->addMetadata("cad", "checkbox", true);
}
if ($mannequin == true) {
$image->addMetadata("mannequin", "checkbox", true);
}
$image->addMetadata("linked_item", "object", $dataObject);
$image->addMetadata("collection", "input", $this->GetDropdownValue('Collections', $this->GetInheritedField($dataObject, 'Collection')));
$image->addMetadata("department", "input", $this->GetDropdownValue('Department', $this->GetInheritedField($dataObject, 'Department')));
$image->addMetadata("maingroup", "input", $this->GetDropdownValue('MainGroup', $this->GetInheritedField($dataObject, 'MainGroup')));
$image->addMetadata("subgroup", "input", $this->GetDropdownValue('SubGroup', $this->GetInheritedField($dataObject, 'SubGroup')));
//$image->addMetadata("sustainable", "input", $this->GetInheritedField($dataObject, 'Sustainable'));
//$image->addMetadata("brand", "input", $this->GetInheritedField($dataObject, 'Brand'));
if ($dataObject->getType() == "object") {
$image->addMetadata("mpn", "input", $dataObject->getSKU());
} else if (empty($dataObject->getSize())) {
$parent = $dataObject->getParent();
$image->addMetadata("mpn", "input", $parent->getSKU());
$image->addMetadata("msn", "input", $dataObject->getSKU());
$image->addMetadata("colour", "input", $this->GetDropdownValue('Colour', $dataObject->getColour()));
$image->addMetadata("colourgroup", "input", $dataObject->getColourGroup());
$image->addMetadata("season", "input", $this->GetDropdownValue('Season', $this->GetInheritedField($dataObject, 'Season')));
}
return $image;
}
/**
* Gets the value of the select option
*
* This is required as selected values are often other objects within Pimcore. Due to the additional filtering of options we've used I also have to get the values from our custom class
*
* @param string $field Classname
* @param string $id The ID field that we need to search for
* @return string
*/
private function GetDropdownValue($field, $id) {
//$selectOptions = new \App\Controller\Selects\SelectOptions();
$selectOptions = new OptionsProvider();
$valuesSingle = $selectOptions->GetAllOptions("Pimcore\\Model\\DataObject\\$field", $field, "en_GB");
if (is_object($valuesSingle) || is_array($valuesSingle)) {
foreach ($valuesSingle as $values) {
if ($values['value'] == $id) {
return $values['key'];
}
}
}
return $id;
}
/**
* Change the child SKU values upon a colour change
*
* @param AbstractObject $dataObject
* @return void
*/
private function AlterChildSKUs($dataObject, $styleCode, $colourCode) {
$children = $dataObject->getChildren([DataObject::OBJECT_TYPE_VARIANT]);
foreach ($children as $child) {
$sizeCode = $this->GetSizeCode($child);
if (!empty($sizeCode)) {
$child->setSKU($styleCode. "." .$colourCode . "." .$sizeCode);
$child->setKey($styleCode. "." .$colourCode . "." .$sizeCode);
$child->save();
}
}
}
/**
* Checks for a path matching your product path. If non exists your path is created.
*
* The path will be cleaned from the SKU fields and if Archive is stated this will also be removed.
*
* @param Product $dataObject
* @return Asset\Folder
*/
private function DoesAssetFolderExist($dataObject) {
//structure based on dept-collection-colour
$assetStructure = ['Products'];
$dataObject->setGetInheritedValues(true);
if (!empty($dataObject->getDepartment())) {
$departmentObject = Department::getByDepartmentID($dataObject->getDepartment());
if (method_exists($departmentObject, 'current') && !empty($departmentObject->current())) {
$assetStructure[] = str_replace("/", "-", $departmentObject->current()->getName());
if (!empty($dataObject->getCollection())) {
$collectionObject = Collections::getByCollectionsID($dataObject->getCollection());
if (method_exists($collectionObject, 'current') && !empty($collectionObject->current())) {
$assetStructure[] = str_replace("/", "-", $collectionObject->current()->getName());
if (!empty($dataObject->getColour())) {
$colourObject = Colour::getByColourID($dataObject->getColour());
if (method_exists($colourObject, 'current') && !empty($colourObject->current())) {
$assetStructure[] = str_replace("/", "-", $colourObject->current()->getName());
}
}
}
}
}
}
$fullPath = '/' . implode('/', $assetStructure);
$folderExists = Asset\Service::pathExists($fullPath);
if ($folderExists == false) {
return Asset\Service::createFolderByPath($fullPath);
} else {
return Asset\Service::getElementByPath('asset', $fullPath);
}
// $objectPath = $dataObject->__toString();
// $replaceValues = ["/Archive"];
// switch ($dataObject->getType()) {
// case "variant":
// $replaceValues[] = "/".$dataObject->getSKU();
// $dataObject = $dataObject->getParent();
// case "object":
// $replaceValues[] = "/".$dataObject->getSKU();
// }
// $cleanPath = str_replace($replaceValues, "", $objectPath);
// $folderExists = Asset\Service::pathExists($cleanPath);
// if ($folderExists == false) {
// return Asset\Service::createFolderByPath($cleanPath);
// } else {
// return Asset\Service::getElementByPath('asset', $cleanPath);
// }
}
private function GenerateChildrenOnTemplateSizes($dataObject) {
$dataObject = $this->RefreshObject($dataObject);
$brick = $dataObject->getSizeGenerator();
if (!empty($brick->getSizeGen()->getGroupedSize())) {
foreach ($brick->getSizeGen()->getGroupedSize() as $groupedSize) {
$sizeGroupListing = new DataObject\SizeGroup\Listing();
$sizeGroupFilter = $sizeGroupListing->filterBySizeGroupID($groupedSize);
foreach ($sizeGroupFilter as $filteredValue) {
foreach ($filteredValue->getCupSizes() as $cupSize) {
foreach ($filteredValue->getBackSizes() as $backSize) {
$filterResult = $this->GetExistingSize($cupSize, $backSize);
foreach ($filterResult as $result) {
$this->CreateVariant($dataObject, $result, 'size');
}
}
}
}
}
} else if (!empty($brick->getSizeGen()->getCupSizes())) {
foreach ($brick->getSizeGen()->getCupSizes() as $cupSize) {
foreach ($brick->getSizeGen()->getBackSizes() as $backSize) {
$filterResult = $this->GetExistingSize($cupSize, $backSize);
foreach ($filterResult as $result) {
$this->CreateVariant($dataObject, $result, 'size');
}
}
}
}
}
private function GetExistingSize($cupSize, $backSize) {
$entries = new DataObject\Size\Listing();
$cupSizeName = strtoupper(str_replace(['cup','_'],'',$cupSize));
$backSizeName = strtoupper(str_replace(['back','_'],'',$backSize));
$filterResult=$entries->setCondition("name LIKE ?", [$backSizeName.$cupSizeName]);
return $filterResult;
}
/**
* Change the child SKU values upon a colour change
*
* @param AbstractObject $dataObject
* @param AbstractObject $variationObject
* @param string $variationType
* @return void
*/
private function CreateVariant($dataObject, $variationObject, $variationType) {
if ($variationType == "size") {
if (!empty($dataObject) && !$this->DoesChildExist($dataObject, $dataObject->getKey().".".$variationObject->getSizeID())) {
$objectX = new Product();
$objectX->setParent($dataObject);
$objectX->setKey($dataObject->getKey().".".$variationObject->getSizeID());
$objectX->setSKU($dataObject->getKey().".".$variationObject->getSizeID());
$objectX->setSize($variationObject->getName());
$objectX->setType(DataObject::OBJECT_TYPE_VARIANT);
$objectX->save();
}
}
}
private function RefreshObject($object) {
$dataObject = new DataObject();
$refreshedObject = $dataObject->getById($object->getId());
return $refreshedObject;
}
private function DoesChildExist($parentObject, $childKey) {
$children = $parentObject->getChildren([DataObject::OBJECT_TYPE_VARIANT], true);
foreach ($children as $child) {
if (!empty($child) && $child->getKey() == $childKey) {
return true;
}
}
return false;
}
/**
* Gets the colour object from the given data object
*
* If the colour can not be identified against this variaition product it will have a look at the parent to see if the value has been filled out.
* This has to be done as variant inheritance does not allow the values to be retrieved through the API
*
* @param AbstractObject $dataObject
* @return string
*/
private function GetColourCode($dataObject) {
try {
if (!empty($dataObject->getColour())) {
if (is_string($dataObject->getColour()) || is_integer($dataObject->getColour())) {
return $dataObject->getColour();
} else if (!empty($dataObject->getColour()->getColourBrick())) {
return $dataObject->getColour()->getColourBrick()->getColour();
}
} else if (!empty($dataObject->getParent()->getColour())) {
if (is_string($dataObject->getParent()->getColour()) || is_integer($dataObject->getParent()->getColour())) {
return $dataObject->getParent()->getColour();
}
}
} catch (\Exception $e) {
}
}
/**
* Gets the string code for the given product
*
* @param AbstractObject $dataObject
* @return string
*/
private function GetSizeCode($dataObject) {
try {
if (!empty($dataObject->getSize())) {
if (is_string($dataObject->getSize()) || is_integer($dataObject->getSize())) {
return $dataObject->getSize();
} else if (!empty($dataObject->getSize()->getSizeBrick())) {
return $dataObject->getSize()->getSizeBrick()->getSize();
}
}
} catch (\Exception $e) {
}
}
private function GetBaseFolder($parentPath) {
$baseFolder = explode("/", $parentPath);
if (count($baseFolder) >= 2) {
return $baseFolder[1];
}
}
private function GetParentKey($parentPath) {
$pathParts = explode("/", $parentPath);
if (count($pathParts) >= 1) {
return $pathParts[count($pathParts)-1];
}
}
private function fieldExists($dataObject, $field) {
try {
$function = "get".$field;
$dataObject->$function();
return true;
} catch (\Exception $e) {
return false;
}
}
}