src/EventListener/ObjectUpdateListener.php line 82

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Model\Product\AutoFields;
  4. use App\Model\Product\LandedCost;
  5. use App\Model\Product\TariffCode;
  6. use App\Model\Product\Wholesale\PriceTable;
  7. use App\Services\ExportService;
  8. use Jabber\GenericBundle\EventListener\PimcoreAdmin;
  9. use Jabber\ObjectDropdownBundle\Cache\Memcached\CacheKeys;
  10. use Jabber\ObjectDropdownBundle\Objects\OptionsProvider;
  11. use Pimcore;
  12. use Pimcore\Event\Model\ElementEventInterface;
  13. use Pimcore\Event\Model\DataObjectEvent;
  14. use Pimcore\Event\Model\AssetEvent;
  15. use Pimcore\Event\Model\DocumentEvent;
  16. use Pimcore\Model\Asset;
  17. use Pimcore\Model\DataObject;
  18. use Pimcore\Model\DataObject\Product;
  19. use Pimcore\Model\DataObject\Retailer;
  20. use Pimcore\Model\DataObject\Size;
  21. use Pimcore\Model\DataObject\SizeGroup;
  22. use Pimcore\Model\DataObject\SizeGroup\Listing;
  23. use Pimcore\Model\User\AbstractUser;
  24. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  25. use Pimcore\Model\DataObject\Barcodes\Listing as BarcodeListing;
  26. use Pimcore\Model\DataObject\Collections;
  27. use Pimcore\Model\DataObject\Colour;
  28. use Pimcore\Model\DataObject\Department;
  29. use Pimcore\Model\DataObject\MainGroup;
  30. use Pimcore\Model\DataObject\SubGroup;
  31. class ObjectUpdateListener {
  32.     private $params;
  33.     public function __construct(ParameterBagInterface $params) {
  34.         $this->params $params;
  35.     }
  36.     private function IsSystemUser($dataObject) {
  37.         $user \Pimcore\Model\User::getById($dataObject->getUserModification());
  38.         if ($user instanceof \Pimcore\Model\User) {
  39.             if ($user->getId() == 0) {
  40.                 return true;
  41.             }
  42.             if (!empty($this->params->get('system_user_id'))) {
  43.                 if ($user->getParentId() == $this->params->get('system_user_id')) {
  44.                     return true;
  45.                 }
  46.             }
  47.         }
  48.         return false;
  49.     }
  50.     public function onPostUpdate (ElementEventInterface $e) {
  51.         if (!$e->hasArgument('isAutoSave')) {
  52.             if($e instanceof AssetEvent) {
  53.                 // do something with the asset
  54.                 $foo $e->getAsset();
  55.             } else if ($e instanceof DocumentEvent) {
  56.                 // do something with the document
  57.                 $foo $e->getDocument();
  58.             } else if ($e instanceof DataObjectEvent) {
  59.                 // do something with the object
  60.                 $dataObject $e->getObject();
  61.                 if ($dataObject instanceof Product) {
  62.                     $dirtyDetection $dataObject->isDirtyDetectionDisabled();
  63.                     
  64.                     if ($dataObject->getType() == "variant") {
  65.                         
  66.                         $this->PublishChildren($dataObject);
  67.                     }
  68.                 } else {
  69.                     $this->ClearCachedData($dataObject); //Has to be within the post and not pre otherwise the updated value will not be read
  70.                 }
  71.             }
  72.         }
  73.     }
  74.     public function onPreUpdate (ElementEventInterface $e) {
  75.         if (!$e->hasArgument('isAutoSave')) {
  76.             if($e instanceof AssetEvent) {
  77.                 // do something with the asset
  78.                 $foo $e->getAsset();
  79.             } else if ($e instanceof DocumentEvent) {
  80.                 // do something with the document
  81.                 $foo $e->getDocument();
  82.             } else if ($e instanceof DataObjectEvent) {
  83.                 // do something with the object
  84.                 $dataObject $e->getObject();
  85.                 if (!$this->IsSystemUser($dataObject)) {
  86.                 
  87.                 
  88.                     $parentPath $dataObject->getParent();
  89.                     $baseFolder $this->GetBaseFolder($parentPath);
  90.                     if ($dataObject instanceof Product) {
  91.                         $autoFields = new AutoFields();
  92.                         $dataObject $autoFields->ProductLevel($dataObject);
  93.                         if ($dataObject->getType() == "variant") {
  94.                             if ($dataObject->isPublished() == false) {
  95.                                 //$dataObject = $this->GenerateSKU($dataObject);
  96.                             }
  97.                             $this->CheckVariantMandatoryFields($dataObject);
  98.                             $dataObject $this->getSizeRange($dataObject);
  99.                             $dataObject $this->AddWholesalePrices($dataObject);
  100.                             $dataObject $this->LandedCostTable($dataObject);
  101.                             //$dataObject = $this->GetBarcode($dataObject);
  102.                             $dataObject $autoFields->LaunchMonth($dataObject);
  103.                             //$dataObject = $this->GetSimilarWeight($dataObject);
  104.                             //$this->ValidateTariffCode($dataObject);
  105.                         } else if ($dataObject->getType() == "object") {
  106.                             //$dataObject = $this->GetClassificationStore($dataObject);
  107.                             $dataObject $this->MoveObject($dataObject);
  108.                             $this->CheckMaterialPercentage($dataObject);
  109.                         }
  110.                         if (method_exists($dataObject"getImages")) {
  111.                             //$this->ChangeImagePaths($dataObject);
  112.                             //$this->AddImageMetaDataAndChangePath($dataObject);
  113.                         }
  114.                     } else if ($dataObject instanceof SizeGroup) {
  115.                         $dataObject $this->ReorderSizeGroup($dataObject);
  116.                     }
  117.                     if (
  118.                         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"
  119.                     ) {
  120.                         $exportCheck $dataObject->getProperty("EXPORTED_PRIAM");
  121.                         if (($exportCheck === false || empty($exportCheck)) && $dataObject->getPublished() == true) {
  122.                             $exportService = new ExportService($this->params);
  123.                             $exportService->GenerateExport([$dataObject], nullnullnulltrue);
  124.                             $dataObject->setProperty("EXPORTED_PRIAM""bool"true);
  125.                         }
  126.                     }
  127.                 }
  128.             }
  129.         }
  130.     }
  131.     private function GetBarcode($dataObject) {
  132.         if ($this->GetLevel($dataObject) == 3) {
  133.             $currentBarcode $dataObject->getEAN();
  134.             if (empty($currentBarcode)) {
  135.                 $barcodeObject = new BarcodeListing();
  136.                 $barcodeObject->filterByUsed(0"=");
  137.                 $barcodeObject->setLimit(1);
  138.                 foreach ($barcodeObject as $barcode) {
  139.                     $barcode->setProduct($dataObject);
  140.                     $barcode->setUsed(true);
  141.                     $barcode->save();
  142.                     $dataObject->setEAN($barcode->getBarcode());
  143.                     break;
  144.                 }
  145.             }
  146.         }
  147.         return $dataObject;
  148.     }
  149.     private function ReorderSizeGroup(SizeGroup $dataObject) {
  150.         $sizeList = [];
  151.         if (is_iterable($dataObject->getSize())) {
  152.             foreach ($dataObject->getSize() as $size) {
  153.                 $sizeList[] = $size;
  154.             }
  155.             sort($sizeList);
  156.             //throw new \Exception(json_encode($sizeList));
  157.             $dataObject->setSize($sizeList);
  158.         }
  159.         return $dataObject;
  160.     }
  161.     private function ValidateTariffCode($dataObject) {
  162.         if ($dataObject->getPublished() == true) {
  163.             $tariffObject = new TariffCode();
  164.             $tariffCode $this->GetInheritedField($dataObject'IETariffCode');
  165.             $validCode $tariffObject->ValidateTariffCode($tariffCode);
  166.             if ($validCode == false) {
  167.                 throw new \Pimcore\Model\Element\ValidationException('The selected tariff code is invalid. Your product cannot be saved');
  168.             }
  169.         }
  170.     }
  171.     private function PublishChildren(DataObject $dataObject) {
  172.         if ($dataObject->getParent()->getType() == "object") {
  173.             if ($dataObject->isPublished()) {
  174.                 foreach ($dataObject->getChildren([DataObject::OBJECT_TYPE_VARIANT], true) as $child) {
  175.                     if (!$child->isPublished()) {
  176.                         $child->setPublished(true);
  177.                         $child->save();
  178.                     }
  179.                 }
  180.             } else {
  181.                 foreach ($dataObject->getChildren([DataObject::OBJECT_TYPE_VARIANT]) as $child) {
  182.                     $child->setPublished(false);
  183.                     $child->save();
  184.                 }
  185.             }    
  186.         }
  187.         
  188.         // if ($dataObject->isPublished()) {
  189.         //     if ($dataObject->getParent()->getType() == "object") {
  190.         //         $versions = $dataObject->getVersions();
  191.         //         if (isset($versions[count($versions)-2])) {
  192.         //             $previousVersion = $versions[count($versions)-2];
  193.         //             $previousObject = $previousVersion->getData();
  194.         //             if ($previousObject->getPublished() == false) {
  195.         //                 // $productQuery = new Product\Listing();
  196.         //                 // $productQuery->filterByPublished(false);
  197.         //                 // $productQuery->setCondition('o_parentId = ?', [$dataObject->getId()]);
  198.         //                 // foreach($productQuery as $child) {
  199.         //                 //     $child->setPublished(true);
  200.         //                 //     $child->save();
  201.         //                 // }
  202.         //                 foreach ($dataObject->getChildren([DataObject::OBJECT_TYPE_VARIANT], true) as $child) {
  203.         //                     if ($child->getPublished() == false) {
  204.         //                         $child->setPublished(true);
  205.         //                         $child->save();
  206.         //                     }
  207.         //                 }
  208.         //             }
  209.         //         } else {
  210.         //             foreach ($dataObject->getChildren([DataObject::OBJECT_TYPE_VARIANT], true) as $child) {
  211.         //                 if ($child->getPublished() == false) {
  212.         //                     $child->setPublished(true);
  213.         //                     $child->save();
  214.         //                 }
  215.         //             }
  216.         //         }
  217.         //     }
  218.         // }
  219.     }
  220.     public function GetInheritedField($product$field$minLevel 0) {
  221.         if (!is_object($product)) {
  222.             $product Product::GetById($productfalse);
  223.         }
  224.         if ($product->getType() == "object" && $minLevel 0) {
  225.             return;
  226.         }
  227.         $function "get$field";
  228.         $responseData $product->$function();
  229.         if (empty($responseData) && $product->getType() != "object") {
  230.             return $this->GetInheritedField($product->getParent(), $field$minLevel);
  231.         } else {
  232.             return $responseData;
  233.         }
  234.     }
  235.     /**
  236.      * Intercepts the users save commmand and checks mandatory data that is not mandatory at the parent level
  237.      *
  238.      * Mandatory fields are specified in the parameter bag in the services file
  239.      *
  240.      * @param DataObject $dataObject
  241.      * @return void
  242.      * @throws \Pimcore\Model\Element\ValidationException
  243.      */
  244.     private function CheckVariantMandatoryFields(DataObject $dataObject) {
  245.         if ($dataObject->getPublished() == true) {
  246.             $variantMandatoryFields $this->params->get('variant_mandatory_fields');
  247.             $productDepth $this->GetLevel($dataObject);
  248.             if (isset($variantMandatoryFields['Product']['Lvl'.$productDepth])) {
  249.                 $fieldList $variantMandatoryFields['Product']['Lvl'.$productDepth];
  250.                 foreach ($fieldList as $requiredField) {
  251.                     $function "get" $requiredField;
  252.                     if (method_exists($dataObject$function)) {
  253.                         if (empty($this->GetInheritedField($dataObject$requiredField0))) {
  254.                             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() . ")");
  255.                         }
  256.                     }
  257.                 }
  258.             }
  259.         }
  260.     }
  261.     
  262.     /**
  263.      * Returns the level of the product so we know if it is a colour or size variant
  264.      *
  265.      * @param DataObject $dataObject
  266.      * @return integer
  267.      */
  268.     private function GetLevel(DataObject $dataObject) {
  269.         $levelCount 0;
  270.         do {
  271.             $levelCount++;
  272.             $dataObject $dataObject->getParent();
  273.             if ($levelCount 5) {
  274.                 break;
  275.             }
  276.         } while ($dataObject->getType() != "folder");
  277.         return $levelCount;
  278.     }
  279.     private function GenerateSKU(DataObject $dataObject) {
  280.         $sku "";
  281.         //$styleCode = explode(".", $dataObject->getSKU())[0];
  282.         $styleCode $dataObject->getSKU();
  283.         if ($dataObject->getType() == "variant") {
  284.             $styleCode $dataObject->getParent()->getSKU();
  285.         }
  286.         $sku $styleCode;
  287.         $colourCode $this->GetColourCode($dataObject);
  288.         $sizeCode $this->GetSizeCode($dataObject);
  289.         if (!empty($colourCode)) {
  290.             $sku $styleCode "." $colourCode;
  291.         }
  292.         if (!empty($sizeCode)) {
  293.             $sku $sku "." $sizeCode;
  294.         }
  295.         if ($dataObject->getSKU() != $sku && $dataObject->getChildAmount(false) > 0) {
  296.             //Change child sku values
  297.             $this->AlterChildSKUs($dataObject$styleCode$colourCode);
  298.         }
  299.         $dataObject->setSKU($sku);
  300.         $dataObject->setKey($sku);
  301.         return $dataObject;
  302.     }
  303.     private function UpdateStatus(DataObject $dataObject) {
  304.         $status "NEW";
  305.         $user AbstractUser::getById($dataObject->getUserModification());
  306.         $userName "system";
  307.         if (!empty($user)) {
  308.             $userName $user->getName();
  309.         }
  310.         if (strpos($dataObject->getFullPath(), "Archive") !== false) {
  311.             $status "ARCHIVED";
  312.         } elseif ($dataObject->getCreationDate() == $dataObject->getModificationDate() || $userName == "system") {
  313.             $status "NEW";
  314.         } else {
  315.             if ($dataObject->getProperty("EXPORTED_PRIAM") == true) {
  316.                 $status "CREATED";
  317.             } else {
  318.                 $status "EDITING";
  319.             }
  320.         }
  321.         $dataObject->setStatus($status);
  322.         return $dataObject;
  323.     }
  324.     private function ClearCachedData($dataObject) {
  325.         if (!$dataObject instanceof Product) {
  326.             $class get_class($dataObject);
  327.             $className str_replace("Pimcore\\Model\\DataObject\\"""$class);
  328.             $cacheKeyProvider = new CacheKeys();
  329.             $response $cacheKeyProvider->DeleteAllKeysContainingString("selectoptions_{$className}_");
  330.             //throw new \Exception(json_encode($keyList));
  331.             $this->RecacheData($className$class);
  332.         }
  333.     }
  334.     private function RecacheData($className$classPath) {
  335.         if (in_array($className, ['Department''MainGroup''SubGroup''Collections''Season''ColourGroup''Size''Colour''SizeGroup''Brand'])) {
  336.             $cacheValues = [];
  337.             
  338.             
  339.             $objectListing = new $classPath();
  340.             $optionsProvider = new OptionsProvider();
  341.             $optionsProvider->GenerateFilteredOptions($objectListing$className);
  342.             // $objectList = $objectListing->getList();
  343.             // $classFiltering = method_exists($objectList->current(), 'getAllowedClasses');
  344.             // $idGetter = method_exists($objectList->current(), 'get' . $className . 'ID') ? 'get' . $className . 'ID' : null;
  345.             // if (!empty($idGetter)) {
  346.             //     foreach ($objectList as $object) {
  347.             //         $cacheValues['all'][] = ["key"=>$object->getName('en_GB'), "value"=>$object->$idGetter()];
  348.             //         if ($classFiltering == true) {
  349.             //             foreach ($object->getAllowedClasses() as $allowedClass) {
  350.             //                 $cacheValues[$allowedClass->__toString()][] = ["key"=>$object->getName('en_GB'), "value"=>$object->$idGetter()];
  351.             //             }
  352.             //         }
  353.             //     }
  354.             //     $cache = new \Memcached();
  355.             //     $cache->addServer('localhost', 11211);
  356.             //     foreach ($cacheValues as $key=>$value) {
  357.             //         $escapedKey = preg_quote($key);
  358.             //         $escapedKey = str_replace(" ", "", $escapedKey);
  359.             //         //apcu_add("selectoptions_{$className}_{$escapedKey}", $value);
  360.             //         $cache->add("selectoptions_{$className}_{$escapedKey}", $value);
  361.             //         //\Pimcore\Log\Simple::log("TestEventListener", "added key: " . "selectoptions_{$className}_{$escapedKey}");
  362.             //     }
  363.             // }
  364.         }
  365.     }
  366.     private function GetClassificationStore(DataObject $dataObject) {
  367.         //$pathArray = explode("/",$dataObject->getPath());
  368.         $classifiction = [];
  369.         $classifiction[] = $dataObject->getDepartment();
  370.         $classifiction[] = $dataObject->getMainGroup();
  371.         $classifiction[] = $dataObject->getSubGroup();
  372.         //
  373.         $storeId 1;
  374.         $groupConfig = new \Pimcore\Model\DataObject\Classificationstore\GroupConfig();
  375.         //$groupConfig->
  376.         $activeGroup = [];
  377.         foreach ($classifiction as $path) {
  378.             if (!empty($path)) {
  379.                 for ($i 0$collection $groupConfig->getByName("{$path}_{$i}"); ++$i) {
  380.                     if (empty($collection)) {
  381.                         break;
  382.                     }
  383.                     $activeGroup[$collection->getId()] = true;
  384.                 }
  385.             }
  386.         }
  387.         $dataObject->getClassificationData()->setActiveGroups($activeGroup);
  388.         return $dataObject;
  389.         //$dataObject->getTestStore()-
  390.     }
  391.     private function LandedCostTable(Product $dataObject) {
  392.         try {
  393.             $landedCost = new LandedCost();
  394.             $dataObject $landedCost->AddToHistory($dataObject);
  395.         } catch (\Exception $e) {
  396.         }
  397.         return $dataObject;
  398.     }
  399.     private function AddWholesalePrices(Product $dataObject) {
  400.         try {
  401.             $wholesaleClass = new PriceTable();
  402.             $newDataObject $wholesaleClass->AddWholesalePrice($dataObject);
  403.             return $newDataObject;
  404.         } catch (\Exception $e) {
  405.             return $dataObject;
  406.         }
  407.     }
  408.     private function getSizeRange($product) {
  409.         //if (empty($product->getSizeGroup())) {
  410.             if (empty($product->getSize()) && empty($product->getSizeGroup())) {
  411.                 $childList $product->getChildren([$product::OBJECT_TYPE_VARIANT]);
  412.                 $sizeList = [];
  413.                 $sizeListNames = [];
  414.                 foreach ($childList as $child) {
  415.                     $sizeName Size::getBySizeID($child->getSize());
  416.                     if (method_exists($sizeName'current') && $sizeName->current() instanceof Size) {
  417.                         $sizeListNames[] = $sizeName->current()->getName();
  418.                         $sizeList[] = $child->getSize();
  419.                     }
  420.                 }
  421.                 $sizeCondition "Size = ',";
  422.                 $sizeCondition .= implode(","$sizeList);
  423.                 $sizeCondition .= ",'";
  424.                 $sizeListing = new \Pimcore\Model\DataObject\SizeGroup\Listing();
  425.                 $sizeListing->setCondition($sizeCondition);
  426.                 if (!empty($sizeListing->current())) {
  427.                     $product->setSizeGroup($sizeListing->current()->getName('en_GB'), 'en_GB');
  428.                     $product->setSizeGroup($sizeListing->current()->getName('en_US'), 'en_US');
  429.                 } else {
  430.                     if (empty($product->getSizeGroup())) {
  431.                         $product->setSizeGroup(implode(","$sizeList));
  432.                     }
  433.                 }
  434.             }
  435.         //}
  436.         return $product;
  437.     }
  438.     /**
  439.      * Reviews the Fabric Composition field on an object to ensure that the percentages are correct and a fabric has not been duplicated
  440.      *
  441.      * @param Product $dataObject
  442.      * @return void
  443.      */
  444.     private function CheckMaterialPercentage(Product $dataObject) {
  445.         $materialComp $dataObject->getFabricComposition();
  446.         $materialArray = [];
  447.         $percentage 0;
  448.         if (is_iterable($materialComp)) {
  449.             foreach ($materialComp as $material) {
  450.                 $percentage += $material->getPercentage();
  451.                 if (key_exists($material->getFabric(), $materialArray)) {
  452.                     throw new \Exception("You have duplicated a fabric in the Fabric Composition field.");
  453.                 }
  454.                 $materialArray[$material->getFabric()] = 1;
  455.                 if ($percentage 100) {
  456.                     throw new \Exception("The cumulative percentage of your Fabric Composition field is greater than 100%. Please correct your percentages to continue.");
  457.                 }
  458.             }
  459.             if ($percentage && $percentage 100) {
  460.                 throw new \Exception("Your Fabric Composition adds up to $percentage%. Please ensure this equals 100% before continuing.");
  461.             }
  462.         }
  463.     }
  464.     /**
  465.      * Moves a product to the correct folder
  466.      *
  467.      * Changes may be made if a product has been archived or department/maingroup/subgroup is modified
  468.      *
  469.      * @param DataObject $dataObject
  470.      * @return DataObject
  471.      */
  472.     private function MoveObject(DataObject $dataObject) {
  473.         
  474.         $dataObject $this->GetParentFromAttributes($dataObject);
  475.         $properties $dataObject->getProperties();
  476.         foreach ($properties as $property) {
  477.             if ($property->getName() == "ARCHIVED") {
  478.                 if ($property->getData() == true) {
  479.                     $parentDirectory $this->GetArchivePath((string) $dataObject->getParent());
  480.                 } else {
  481.                     $parentDirectory $this->GetNonArchivePath((string) $dataObject->getParent());
  482.                 }
  483.                 if ($parentDirectory instanceof DataObject && $parentDirectory->getType() == "folder") {
  484.                     $dataObject->setParent($parentDirectory);
  485.                     return $dataObject;
  486.                 }
  487.             }
  488.         }
  489.         return $dataObject;
  490.     }
  491.     private function GetParentFromAttributes(DataObject $dataObject) {
  492.         $path "/Products";
  493.         
  494.         try {
  495.             if (!empty($dataObject->getDepartment()) && !empty($dataObject->getMainGroup()) && !empty($dataObject->getSubGroup())) {
  496.                 
  497.                 $departmentObject Department::getByDepartmentID($dataObject->getDepartment());
  498.                 $maingroupObject MainGroup::getByMainGroupID($dataObject->getMainGroup());
  499.                 $subgroupObject SubGroup::getBySubGroupID($dataObject->getSubGroup());
  500.                 
  501.                 
  502.                 if (method_exists($departmentObject"current") && method_exists($maingroupObject"current") && method_exists($subgroupObject"current")) {
  503.                     $path .= "/" $departmentObject->current()->getName();
  504.                     $path .= "/" $maingroupObject->current()->getName();
  505.                     $path .= "/" $subgroupObject->current()->getName();     
  506.                     $object = new DataObject();
  507.                     $parentObject $object->getByPath($path);
  508.                     if ($parentObject instanceof DataObject && $parentObject->getType() == "folder") {
  509.                         $dataObject->setParent($parentObject);
  510.                     }                   
  511.                 }
  512.             }
  513.         } catch (\Exception $e) {
  514.             die($e->getMessage());
  515.         }
  516.         return $dataObject;
  517.     }
  518.     /**
  519.      * Retrieves the archive path at the correct level given the passed directory structure
  520.      *
  521.      * @param string $path
  522.      * @param integer $archiveDepth
  523.      * @return DataObject
  524.      */
  525.     private function GetArchivePath($path$archiveDepth 2) {
  526.         $explodedPath explode("/"$path);
  527.         $archiveSections = [];
  528.         foreach ($explodedPath as $key=>$value) {
  529.             $archiveSections[] = $value;
  530.             if ($key == $archiveDepth) {
  531.                 $archiveSections[] = "Archive";
  532.             }
  533.         }
  534.         $archivePath implode("/"$archiveSections);
  535.         $dataObject = new DataObject();
  536.         return $dataObject->getByPath($archivePath);
  537.     }
  538.     private function GetNonArchivePath($path) {
  539.         $path str_replace("/Archive"""$path);
  540.         $dataObject = new DataObject();
  541.         return $dataObject->getByPath($path);
  542.     }
  543.     private function GeneratePriamExport(DataObject $dataObject) {
  544.         if ($dataObject->isPublished()) {
  545.             if (get_class($dataObject) == "Pimcore\Model\DataObject\Colour") {
  546.                 $dirPath $this->params->get('priam_export_colour');
  547.                 $fileName "interface_import_colours_".date("YmdHis").".csv";
  548.                 $data = [
  549.                     ['Season_identifier''Colour_identifier''Description''Short_description'],
  550.                     [null$dataObject->getColourID(), $dataObject->getName(), null]
  551.                 ];
  552.             } else if (get_class($dataObject) == "Pimcore\Model\DataObject\Size") {
  553.                 $dirPath $this->params->get('priam_export_size');
  554.                 $fileName "interface_import_sizes_".date("YmdHis").".csv";
  555.                 $data = [
  556.                     ['Size_code''Description''Short_description'],
  557.                     [$dataObject->getSizeID(), $dataObject->getName(), null]
  558.                 ];
  559.             }
  560.             $fp fopen($dirPath "/" $fileName'w+');
  561.             foreach ($data as $fields) {
  562.                 fputcsv($fp$fields);
  563.             }
  564.             fclose($fp);
  565.         }
  566.     }
  567.     private function CreateERPItem($dataObject) {
  568.         $erpId $dataObject->getProperty("erp_id");
  569.         if (empty($erpId)) {
  570.             $curl curl_init();
  571.             $params = [
  572.                 'ref'=>$dataObject->getSKU(),
  573.                 'label'=>$dataObject->getTitle(),
  574.                 'description'=>$dataObject->getDescription(),
  575.                 'price'=>$dataObject->getPricingCost()
  576.             ];
  577.             curl_setopt_array($curl, array(
  578.             CURLOPT_URL => 'http://erp.thebroady.co.uk/api/index.php/products',
  579.             CURLOPT_RETURNTRANSFER => true,
  580.             CURLOPT_ENCODING => '',
  581.             CURLOPT_MAXREDIRS => 10,
  582.             CURLOPT_TIMEOUT => 0,
  583.             CURLOPT_FOLLOWLOCATION => true,
  584.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  585.             CURLOPT_CUSTOMREQUEST => 'POST',
  586.             CURLOPT_POSTFIELDS => http_build_query($params),
  587.             CURLOPT_HTTPHEADER => array(
  588.                 'DOLAPIKEY: b8eiW04DlZt3Pgp3MAu2n5GFD4CfE02d',
  589.                 'Content-Type: application/x-www-form-urlencoded'
  590.             ),
  591.             ));
  592.             $response curl_exec($curl);
  593.             curl_close($curl);
  594.             $dataObject->setProperty("erp_id","Text",$response);
  595.         }
  596.     }
  597.     /**
  598.      * Renames image paths to become the same as the object
  599.      *
  600.      * @param DataObject $dataObject
  601.      * @param Asset $image
  602.      * @return Asset
  603.      */
  604.     private function ChangeImagePaths($dataObject$image) {
  605.         $assetFolder $this->DoesAssetFolderExist($dataObject);
  606.         $image->setParent($assetFolder);
  607.         return $image;
  608.     }
  609.     private function SaveAsset(Asset\Image $image) {
  610.         $fullPath $image->getParent()->getfullPath() . "/" $image->getFilename();
  611.         $existingAsset Asset::getByPath($fullPath);
  612.         if ($existingAsset instanceof Asset) {
  613.             $existingData $existingAsset->getData();
  614.             $imageData $image->getData();
  615.             if ($existingAsset->getData() == $image->getData()) {
  616.                 $image->save();
  617.                 // The existing image is the same as the one being uploaded
  618.             } else {
  619.                 $pathInfo pathinfo($image->getFilename());
  620.                 $image->setFilename("0_" $pathInfo['filename'] . "." $pathInfo['extension']);
  621.                 $image->save();
  622.             }
  623.         } else {
  624.             $image->save();
  625.         }
  626.     }
  627.     /**
  628.      * Add metadata from the product to the image
  629.      *
  630.      * @param Product $dataObject
  631.      * @return void
  632.      */
  633.     private function AddImageMetaDataAndChangePath(Product $dataObject) {
  634.         $images $dataObject->getImages();
  635.         foreach ($images as $hotspotImage) {
  636.             if (!empty($hotspotImage)) {
  637.                 $image $hotspotImage->getImage();
  638.                 if (!empty($image) && is_object($image)) {
  639.                     if (method_exists($image"addMetadata")) {
  640.                         $image $this->AddImageMetaData($image$dataObject);
  641.                         $image $this->ChangeImagePaths($dataObject$image);
  642.                         
  643.                         $this->SaveAsset($image);
  644.                     }
  645.                 }
  646.             }
  647.         }
  648.         $mannequin $dataObject->getMannequinShot();
  649.         foreach ($mannequin as $hotspotImage) {
  650.             if (!empty($hotspotImage)) {
  651.                 $image $hotspotImage->getImage();
  652.                 if (!empty($image) && is_object($image)) {
  653.                     if (method_exists($image"addMetadata")) {
  654.                         $image $this->AddImageMetaData($image$dataObjectfalsetrue);
  655.                         $image $this->ChangeImagePaths($dataObject$image);
  656.                         $image->save();
  657.                     }
  658.                 }
  659.             }
  660.         }
  661.         $cad $dataObject->getCad();
  662.         if (!empty($cad) && is_object($cad) && method_exists($cad"addMetadata")) {
  663.             $cad $this->AddImageMetaData($cad$dataObjecttrue);
  664.             $cad $this->ChangeImagePaths($dataObject$cad);
  665.             //$cad->save();
  666.         }
  667.     }
  668.     private function AddImageMetaData($image$dataObject$cad false$mannequin false) {
  669.         if ($cad == true) {
  670.             $image->addMetadata("cad""checkbox"true);
  671.         }
  672.         if ($mannequin == true) {
  673.             $image->addMetadata("mannequin""checkbox"true);
  674.         }
  675.         $image->addMetadata("linked_item""object"$dataObject);
  676.         $image->addMetadata("collection""input"$this->GetDropdownValue('Collections'$this->GetInheritedField($dataObject'Collection')));
  677.         $image->addMetadata("department""input"$this->GetDropdownValue('Department'$this->GetInheritedField($dataObject'Department')));
  678.         $image->addMetadata("maingroup""input"$this->GetDropdownValue('MainGroup'$this->GetInheritedField($dataObject'MainGroup')));
  679.         $image->addMetadata("subgroup""input"$this->GetDropdownValue('SubGroup'$this->GetInheritedField($dataObject'SubGroup')));
  680.         //$image->addMetadata("sustainable", "input", $this->GetInheritedField($dataObject, 'Sustainable'));
  681.         //$image->addMetadata("brand", "input", $this->GetInheritedField($dataObject, 'Brand'));
  682.         if ($dataObject->getType() == "object") {
  683.             $image->addMetadata("mpn""input"$dataObject->getSKU());
  684.         } else if (empty($dataObject->getSize())) {
  685.             $parent $dataObject->getParent();
  686.             $image->addMetadata("mpn""input"$parent->getSKU());
  687.             $image->addMetadata("msn""input"$dataObject->getSKU());
  688.             $image->addMetadata("colour""input"$this->GetDropdownValue('Colour'$dataObject->getColour()));
  689.             $image->addMetadata("colourgroup""input"$dataObject->getColourGroup());
  690.             $image->addMetadata("season""input"$this->GetDropdownValue('Season'$this->GetInheritedField($dataObject'Season')));
  691.         }
  692.         return $image;
  693.     }
  694.     /**
  695.      * Gets the value of the select option
  696.      *
  697.      * 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
  698.      *
  699.      * @param string $field Classname
  700.      * @param string $id The ID field that we need to search for
  701.      * @return string
  702.      */
  703.     private function GetDropdownValue($field$id) {
  704.         //$selectOptions = new \App\Controller\Selects\SelectOptions();
  705.         $selectOptions = new OptionsProvider();
  706.         $valuesSingle $selectOptions->GetAllOptions("Pimcore\\Model\\DataObject\\$field"$field"en_GB");
  707.         if (is_object($valuesSingle) || is_array($valuesSingle)) {
  708.             foreach ($valuesSingle as $values) {
  709.                 if ($values['value'] == $id) {
  710.                     return $values['key'];
  711.                 }
  712.             }
  713.         }
  714.         return $id;
  715.     }
  716.     /**
  717.      * Change the child SKU values upon a colour change
  718.      *
  719.      * @param AbstractObject $dataObject
  720.      * @return void
  721.      */
  722.     private function AlterChildSKUs($dataObject$styleCode$colourCode) {
  723.         $children $dataObject->getChildren([DataObject::OBJECT_TYPE_VARIANT]);
  724.         foreach ($children as $child) {
  725.             $sizeCode $this->GetSizeCode($child);
  726.             if (!empty($sizeCode)) {
  727.                 $child->setSKU($styleCode"." .$colourCode "." .$sizeCode);
  728.                 $child->setKey($styleCode"." .$colourCode "." .$sizeCode);
  729.                 $child->save();
  730.             }
  731.         }
  732.     }
  733.     /**
  734.      * Checks for a path matching your product path. If non exists your path is created.
  735.      *
  736.      * The path will be cleaned from the SKU fields and if Archive is stated this will also be removed.
  737.      *
  738.      * @param Product $dataObject
  739.      * @return Asset\Folder
  740.      */
  741.     private function DoesAssetFolderExist($dataObject) {
  742.         //structure based on dept-collection-colour
  743.         $assetStructure = ['Products'];
  744.         $dataObject->setGetInheritedValues(true);
  745.         if (!empty($dataObject->getDepartment())) {
  746.             $departmentObject Department::getByDepartmentID($dataObject->getDepartment());
  747.             if (method_exists($departmentObject'current') && !empty($departmentObject->current())) {
  748.                 $assetStructure[] = str_replace("/""-"$departmentObject->current()->getName());
  749.                 if (!empty($dataObject->getCollection())) {
  750.                     $collectionObject Collections::getByCollectionsID($dataObject->getCollection());
  751.                     if (method_exists($collectionObject'current') && !empty($collectionObject->current())) {
  752.                         $assetStructure[] = str_replace("/""-"$collectionObject->current()->getName());
  753.                         if (!empty($dataObject->getColour())) {
  754.                             $colourObject Colour::getByColourID($dataObject->getColour());
  755.                             if (method_exists($colourObject'current') && !empty($colourObject->current())) {
  756.                                 $assetStructure[] = str_replace("/""-"$colourObject->current()->getName());
  757.                             }
  758.                         }
  759.                     }
  760.                 }
  761.             }
  762.         }
  763.         $fullPath '/' implode('/'$assetStructure);
  764.         $folderExists Asset\Service::pathExists($fullPath);
  765.         if ($folderExists == false) {
  766.             return Asset\Service::createFolderByPath($fullPath);
  767.         } else {
  768.             return Asset\Service::getElementByPath('asset'$fullPath);
  769.         }
  770.         // $objectPath = $dataObject->__toString();
  771.         // $replaceValues = ["/Archive"];
  772.         // switch ($dataObject->getType()) {
  773.         //     case "variant":
  774.         //         $replaceValues[] = "/".$dataObject->getSKU();
  775.         //         $dataObject = $dataObject->getParent();
  776.         //     case "object":
  777.         //         $replaceValues[] = "/".$dataObject->getSKU();
  778.         // }
  779.         // $cleanPath = str_replace($replaceValues, "", $objectPath);
  780.         // $folderExists = Asset\Service::pathExists($cleanPath);
  781.         // if ($folderExists == false) {
  782.         //     return Asset\Service::createFolderByPath($cleanPath);
  783.         // } else {
  784.         //     return Asset\Service::getElementByPath('asset', $cleanPath);
  785.         // }
  786.     }
  787.     private function GenerateChildrenOnTemplateSizes($dataObject) {
  788.         $dataObject $this->RefreshObject($dataObject);
  789.         $brick $dataObject->getSizeGenerator();
  790.         if (!empty($brick->getSizeGen()->getGroupedSize())) {
  791.             foreach ($brick->getSizeGen()->getGroupedSize() as $groupedSize) {
  792.                 $sizeGroupListing = new DataObject\SizeGroup\Listing();
  793.                 $sizeGroupFilter $sizeGroupListing->filterBySizeGroupID($groupedSize);
  794.                 foreach ($sizeGroupFilter as $filteredValue) {
  795.                     foreach ($filteredValue->getCupSizes() as $cupSize) {
  796.                         foreach ($filteredValue->getBackSizes() as $backSize) {
  797.                             $filterResult $this->GetExistingSize($cupSize$backSize);
  798.                             foreach ($filterResult as $result) {
  799.                                 $this->CreateVariant($dataObject$result'size');
  800.                             }
  801.                         }
  802.                     }
  803.                 }
  804.             }
  805.         } else if (!empty($brick->getSizeGen()->getCupSizes())) {
  806.             foreach ($brick->getSizeGen()->getCupSizes() as $cupSize) {
  807.                 foreach ($brick->getSizeGen()->getBackSizes() as $backSize) {
  808.                     $filterResult $this->GetExistingSize($cupSize$backSize);
  809.                     foreach ($filterResult as $result) {
  810.                         $this->CreateVariant($dataObject$result'size');
  811.                     }
  812.                 }
  813.             }
  814.         }
  815.     }
  816.     private function GetExistingSize($cupSize$backSize) {
  817.         $entries = new DataObject\Size\Listing();
  818.         $cupSizeName strtoupper(str_replace(['cup','_'],'',$cupSize));
  819.         $backSizeName strtoupper(str_replace(['back','_'],'',$backSize));
  820.         $filterResult=$entries->setCondition("name LIKE ?", [$backSizeName.$cupSizeName]);
  821.         return $filterResult;
  822.     }
  823.     /**
  824.      * Change the child SKU values upon a colour change
  825.      *
  826.      * @param AbstractObject $dataObject
  827.      * @param AbstractObject $variationObject
  828.      * @param string $variationType
  829.      * @return void
  830.      */
  831.     private function CreateVariant($dataObject$variationObject$variationType) {
  832.         if ($variationType == "size") {
  833.             if (!empty($dataObject) && !$this->DoesChildExist($dataObject$dataObject->getKey().".".$variationObject->getSizeID())) {
  834.                 $objectX = new Product();
  835.                 $objectX->setParent($dataObject);
  836.                 $objectX->setKey($dataObject->getKey().".".$variationObject->getSizeID());
  837.                 $objectX->setSKU($dataObject->getKey().".".$variationObject->getSizeID());
  838.                 $objectX->setSize($variationObject->getName());
  839.                 $objectX->setType(DataObject::OBJECT_TYPE_VARIANT);
  840.                 $objectX->save();
  841.             }
  842.         }
  843.     }
  844.     private function RefreshObject($object) {
  845.         $dataObject = new DataObject();
  846.         $refreshedObject $dataObject->getById($object->getId());
  847.         return $refreshedObject;
  848.     }
  849.     private function DoesChildExist($parentObject$childKey) {
  850.         $children $parentObject->getChildren([DataObject::OBJECT_TYPE_VARIANT], true);
  851.         foreach ($children as $child) {
  852.             if (!empty($child) && $child->getKey() == $childKey) {
  853.                 return true;
  854.             }
  855.         }
  856.         return false;
  857.     }
  858.     /**
  859.      * Gets the colour object from the given data object
  860.      *
  861.      * 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.
  862.      * This has to be done as variant inheritance does not allow the values to be retrieved through the API
  863.      *
  864.      * @param AbstractObject $dataObject
  865.      * @return string
  866.      */
  867.     private function GetColourCode($dataObject) {
  868.         try {
  869.             if (!empty($dataObject->getColour())) {
  870.                 if (is_string($dataObject->getColour()) || is_integer($dataObject->getColour())) {
  871.                     return $dataObject->getColour();
  872.                 } else if (!empty($dataObject->getColour()->getColourBrick())) {
  873.                     return $dataObject->getColour()->getColourBrick()->getColour();
  874.                 }
  875.             } else if (!empty($dataObject->getParent()->getColour())) {
  876.                 if (is_string($dataObject->getParent()->getColour()) || is_integer($dataObject->getParent()->getColour())) {
  877.                     return $dataObject->getParent()->getColour();
  878.                 }
  879.             }
  880.         } catch (\Exception $e) {
  881.         }
  882.     }
  883.     /**
  884.      * Gets the string code for the given product
  885.      *
  886.      * @param AbstractObject $dataObject
  887.      * @return string
  888.      */
  889.     private function GetSizeCode($dataObject) {
  890.         try {
  891.             if (!empty($dataObject->getSize())) {
  892.                 if (is_string($dataObject->getSize()) || is_integer($dataObject->getSize())) {
  893.                     return $dataObject->getSize();
  894.                 } else if (!empty($dataObject->getSize()->getSizeBrick())) {
  895.                     return $dataObject->getSize()->getSizeBrick()->getSize();
  896.                 }
  897.             }
  898.         } catch (\Exception $e) {
  899.         }
  900.     }
  901.     private function GetBaseFolder($parentPath) {
  902.         $baseFolder explode("/"$parentPath);
  903.         if (count($baseFolder) >= 2) {
  904.             return $baseFolder[1];
  905.         }
  906.     }
  907.     private function GetParentKey($parentPath) {
  908.         $pathParts explode("/"$parentPath);
  909.         if (count($pathParts) >= 1) {
  910.             return $pathParts[count($pathParts)-1];
  911.         }
  912.     }
  913.     private function fieldExists($dataObject$field) {
  914.         try {
  915.             $function "get".$field;
  916.             $dataObject->$function();
  917.             return true;
  918.         } catch (\Exception $e) {
  919.             return false;
  920.         }
  921.     }
  922. }