src/BricomanBundle/EventListener/ActivePaginatorListener.php line 113

Open in your IDE?
  1. <?php
  2. /**
  3.  * Active Publishing - Creative Common CC BY 4.0
  4.  *   Full copyright and license information is available in
  5.  *   LICENSE.md which is distributed with this source code.
  6.  *
  7.  * @copyright Copyright (c) Active Publishing (https://activepublishing.fr)
  8.  * @license Creative Common CC BY 4.0
  9.  * @author Active Publishing <contact@active-publishing.fr>
  10.  */
  11. namespace BricomanBundle\EventListener;
  12. use BricomanBundle\BricomanBundle;
  13. use ActivePublishing\Tool\ApTool;
  14. use BricomanBundle\Model\DataObject\ActivePaginatorChapters;
  15. use Pimcore\Db;
  16. use Pimcore\Event\Model\ElementEventInterface;
  17. use Pimcore\Event\Model\DataObjectEvent;
  18. use Pimcore\Model\DataObject;
  19. use Pimcore\Model\Document;
  20. use Pimcore\Model\Element\ValidationException;
  21. use Pimcore\Model\Property;
  22. use Pimcore\Model\User;
  23. use Symfony\Component\Serializer\Encoder\JsonDecode;
  24. /**
  25.  * Class ActivePaginatorListener
  26.  * @package BricomanBundle\EventListener
  27.  */
  28. class ActivePaginatorListener
  29. {
  30.     // -----------------------------------------------------------------------------------------------------------------
  31.     // LISTENERS
  32.     // -----------------------------------------------------------------------------------------------------------------
  33.     /**
  34.      * @param ElementEventInterface $e
  35.      * @throws \Exception
  36.      */
  37.     public function onPostUpdate (ElementEventInterface $e)
  38.     {
  39.         if ($e instanceof DataObjectEvent)
  40.         {
  41.             $object $e->getObject();
  42.             // Update when a ActivePaginator object is saved
  43.             if ($object instanceof DataObject\ActivePaginator)
  44.             {
  45.                 // Update properties of document\printcontainer
  46.                 $dependencies $object->getDependencies();
  47.                 $requiredBy $dependencies->getRequiredBy();
  48.                 if (!empty($requiredBy))
  49.                 {
  50.                     foreach ($requiredBy as $item) {
  51.                         if ($item['type'] == "document")
  52.                         {
  53.                             $document Document::getById($item['id']);
  54.                             $NamespaceCatalog = [
  55.                                 "@AP\ActiveWireframeBundle\Controller\CatalogController",
  56.                                 "@ActiveWireframeBundle\Controller\CatalogController",
  57.                                 "catalog"
  58.                             ];
  59.                             if (in_array($document->getController(), $NamespaceCatalog))
  60.                             {
  61.                                 $document->save();
  62.                             }
  63.                         }
  64.                     }
  65.                 }
  66.                 // Update chapter (In case or the config for recover product data has changed)
  67.                 if ($object->hasChildren())
  68.                 {
  69.                     foreach ($object->getChildren() as $activePaginatorChapters)
  70.                     {
  71.                         if ($activePaginatorChapters instanceof ActivePaginatorChapters)
  72.                         {
  73.                             $activePaginatorChapters->save();
  74.                         }
  75.                     }
  76.                 }
  77.                 // Update declinaison data if saving a "master" ActivePaginator object
  78.                 if (!$object->hasProperty("active_paginator_master_link"))
  79.                 {
  80.                     $this->updateDeclinaison($object);
  81.                 }
  82.             }
  83.             // Update when a ActivePaginatorChapter object is saved
  84.             if ($object instanceof DataObject\ActivePaginatorChapters)
  85.             {
  86.                 $activePaginator $object->getParent();
  87.                 if ($activePaginator instanceof DataObject\ActivePaginator
  88.                     && !$activePaginator->hasProperty("active_paginator_master_link")
  89.                 ) {
  90.                     $this->updateDeclinaison($activePaginator);
  91.                 }
  92.             }
  93.         }
  94.     }
  95.     /**
  96.      * @param ElementEventInterface $e
  97.      * @throws \Exception
  98.      */
  99.     public function onPreUpdate (ElementEventInterface $e)
  100.     {
  101.         if ($e instanceof DataObjectEvent)
  102.         {
  103.             $object $e->getObject();
  104.             // Update RecoverItem before saving Chapter
  105.             if ($object instanceof DataObject\ActivePaginatorChapters)
  106.             {
  107.                 $riOldData $this->getRiOldData($object);
  108.                 $riChangeData = [];
  109.                 $jsonDecode = new JsonDecode(true);
  110.                 if (array_key_exists('data'$_POST) && is_json($_POST['data']))
  111.                 {
  112.                     $riChangeData $this->getRiChangeData($object$jsonDecode->decode($_POST['data'], 'json'));
  113.                 }
  114.                 $recoverItems = [];
  115.                 $items $object->getItems();
  116.                 $parent $object->getParent();
  117.                 $translator = \Pimcore::getContainer()->get('translator');
  118.                 if ($parent instanceof DataObject\ActivePaginator) {
  119.                     foreach ($parent->getProperties() as $property) {
  120.                         if ($property->getName() == 'bricoman_date_pub_obj' || $property->getName() == 'bricoman_date_ref_obj') {
  121.                             if (empty($property->getData())) {
  122.                                 // Si l'Active paginator parent n'est pas sauvegardé au préalable
  123.                                 throw new ValidationException($translator->trans('bricoman_active_paginator_not_save_msg'));
  124.                             }
  125.                         }
  126.                     }
  127.                 }
  128.                 if (!empty($items) && !is_null($items) && $parent instanceof DataObject\ActivePaginator)
  129.                 {
  130.                     $targetObjectData $parent->getBlocTarget();
  131.                     $targetObjectArray = [];
  132.                     if (!empty($targetObjectData)) {
  133.                         foreach ($targetObjectData as $targetObject) {
  134.                             $targetObjectArray[] = $targetObject['targetObject']->getData();
  135.                         }
  136.                     }
  137.                     $elsMetadata = ['wi' => [], 'oi' => []];
  138.                     $recoverItemsData $this->getRi($items$riOldData$riChangeData$targetObjectArray$elsMetadata);
  139.                     ksort($recoverItemsData['wi']);
  140.                     $recoverItems $recoverItemsData['wi'] + $recoverItemsData['oi'];
  141.                 }
  142.                 $object->setRecoverItems($recoverItems);
  143.             }
  144.             // Updating list in chapter config if a object is added or deleted
  145.             if ($object instanceof DataObject\ITNomenclature)
  146.             {
  147.                 if ($object->getDependencies())
  148.                 {
  149.                     $arrayRequiredBy $object->getDependencies()->getRequiredBy();
  150.                     if ($arrayRequiredBy)
  151.                     {
  152.                         foreach ($arrayRequiredBy as $node)
  153.                         {
  154.                             if ($node['type'] == 'object')
  155.                             {
  156.                                 $objectRequiredBy DataObject::getById($node['id']);
  157.                                 if ($objectRequiredBy instanceof DataObject\ActivePaginatorChapters)
  158.                                 {
  159.                                     $objectRequiredBy->save();
  160.                                 }
  161.                             }
  162.                         }
  163.                     }
  164.                 }
  165.             }
  166.             if ($object instanceof DataObject\ActivePaginator)
  167.             {
  168.                 // Gestion des propriétés
  169.                 $this->addProperties($object);
  170.             }
  171.         }
  172.     }
  173.     // -----------------------------------------------------------------------------------------------------------------
  174.     // HELP FUNCTIONS
  175.     // -----------------------------------------------------------------------------------------------------------------
  176.     /**
  177.      * @param $items
  178.      * @param $riOldData
  179.      * @param $riChangeData
  180.      * @param $targetObjectArray
  181.      * @param array $elsMetadata
  182.      * @return array
  183.      */
  184.     private function getRi($items$riOldData$riChangeData$targetObjectArray$elsMetadata = [])
  185.     {
  186.         try {
  187.             foreach ($items as $item) {
  188.                 if ($item instanceof DataObject\Concrete) {
  189.                     if (property_exists($item'products')) {
  190.                         $products $item->getProducts();
  191.                         if (!empty($products)) {
  192.                             foreach ($products as $product) {
  193.                                 if (in_array($product->getClassName(), $targetObjectArray)) {
  194.                                     if (array_key_exists($product->getId(), $riChangeData)) {
  195.                                         $index $riChangeData[$product->getId()]['index'];
  196.                                         $elsMetadata['wi'][$index] = $this->createElementMetadata(
  197.                                             $product$riOldData$riChangeData
  198.                                         );
  199.                                     } else {
  200.                                         $elsMetadata['oi'][] = $this->createElementMetadata(
  201.                                             $product$riOldData$riChangeData
  202.                                         );
  203.                                     }
  204.                                 }
  205.                             }
  206.                         }
  207.                     } else if (in_array($item->getClassName(), $targetObjectArray)) {
  208.                         if (array_key_exists($item->getId(), $riChangeData)) {
  209.                             $index $riChangeData[$item->getId()]['index'];
  210.                             $elsMetadata['wi'][$index] = $this->createElementMetadata($item$riOldData$riChangeData);
  211.                         } else {
  212.                             $elsMetadata['oi'][] = $this->createElementMetadata($item$riOldData$riChangeData);
  213.                         }
  214.                     }
  215.                 }
  216.                 if ($item->hasChildren()) {
  217.                     $elsMetadata $this->getRi(
  218.                         $item->getChildren(), $riOldData$riChangeData$targetObjectArray$elsMetadata
  219.                     );
  220.                 }
  221.             }
  222.         } catch (\Exception $ex) {
  223.             ApTool::log(BricomanBundle::BUNDLE_ID$ex->getTraceAsString());
  224.         }
  225.         return $elsMetadata;
  226.     }
  227.     /**
  228.      * @param $object
  229.      * @param array $riChangeData
  230.      * @return array
  231.      */
  232.     private function getRiChangeData ($object$riChangeData = [])
  233.     {
  234.         $data = [];
  235.         if (array_key_exists('recoverItems'$riChangeData)) {
  236.             if (!empty($riChangeData['recoverItems'])) {
  237.                 foreach ($riChangeData['recoverItems'] as $dataIndex => $dataItem) {
  238.                     $data[$dataItem['id']] = [
  239.                         'publish' => (bool) $dataItem['publish'],
  240.                         'index' => intval($dataIndex)
  241.                     ];
  242.                 }
  243.             }
  244.         } else {
  245.             $database Db::get();
  246.             $cid trim($object->getClassId());
  247.             $oid trim($object->getId());
  248.             if (($cid != "") && ($oid != "")) {
  249.                 $faObjectApc $database->fetchAll("SELECT * FROM `object_$cid` WHERE oo_id = $oid");
  250.                 if (!empty($faObjectApc)) {
  251.                     foreach ($faObjectApc as $dataObjectApc) {
  252.                         $recoverItemsArray explode(","$dataObjectApc['recoverItems']);
  253.                         if (!empty($recoverItemsArray)) {
  254.                             foreach ($recoverItemsArray as $dataIndex => $recoverItemString) {
  255.                                 if ($recoverItemString != "") {
  256.                                     $recoverItemId str_replace("object|"""$recoverItemString);
  257.                                     $faObjectMetaApc $database->fetchAll(
  258.                                         "SELECT * FROM `object_metadata_$cid` WHERE o_id = $oid AND dest_id = $recoverItemId"
  259.                                         " AND `fieldname` = 'recoverItems' AND `column` = 'publish'"
  260.                                     );
  261.                                     if (!empty($faObjectMetaApc)) {
  262.                                         $data[$recoverItemId] = [
  263.                                             'publish' => $faObjectMetaApc[0]['data'],
  264.                                             'index' => intval($dataIndex)
  265.                                         ];
  266.                                     }
  267.                                 }
  268.                             }
  269.                         }
  270.                     }
  271.                 }
  272.             }
  273.         }
  274.         return $data;
  275.     }
  276.     /**
  277.      * @param DataObject\Concrete $object
  278.      * @return array
  279.      */
  280.     private function getRiOldData (DataObject\Concrete $object)
  281.     {
  282.         $database Db::get();
  283.         $cid $object->getClassId();
  284.         $oid $object->getId();
  285.         $data = [];
  286.         if (($cid != "") && ($oid != "")) {
  287.             $fetchAll $database->fetchAll(
  288.                 "SELECT * FROM `object_metadata_$cid` WHERE o_id = $oid"
  289.                 " AND `fieldname` = 'recoverItems' AND `column` = 'publish'"
  290.             );
  291.             if (!empty($fetchAll)) {
  292.                 foreach ($fetchAll as $dataItem) {
  293.                     $data[$dataItem['dest_id']] = [
  294.                         'publish' => (bool)$dataItem['data']
  295.                     ];
  296.                 }
  297.             }
  298.         }
  299.         return $data;
  300.     }
  301.     /**
  302.      * @param DataObject\Concrete $object
  303.      * @param $riOldData
  304.      * @param $riChangeData
  305.      * @return bool|DataObject\Data\ElementMetadata
  306.      */
  307.     private function createElementMetadata (DataObject\Concrete $object$riOldData$riChangeData)
  308.     {
  309.         try {
  310.             $publish true;
  311.             // Get AllData
  312.             if (array_key_exists($object->getId(), $riOldData)) {
  313.                 $publish = (bool) $riOldData[$object->getId()]['publish'];
  314.             }
  315.             // Get New Data
  316.             if (array_key_exists($object->getId(), $riChangeData)) {
  317.                 $publish = (bool) $riChangeData[$object->getId()]['publish'];
  318.             }
  319.             $elementMetadata = new DataObject\Data\ElementMetadata('recoverItems', [
  320.                 'publish',
  321.                 'incoming',
  322.                 'outgoing',
  323.                 'ispublishable',
  324.                 'modificationdatepim',
  325.                 'rang'
  326.             ], $object);
  327.             $elementMetadata->setPublish($publish);
  328.             return $elementMetadata;
  329.         } catch (\Exception $ex) {
  330.             ApTool::log(BricomanBundle::BUNDLE_ID$ex->getTraceAsString());
  331.         }
  332.         return false;
  333.     }
  334.     /**
  335.      * @param DataObject\ActivePaginator $masterConfig
  336.      * @throws \Exception
  337.      */
  338.     private function updateDeclinaison (DataObject\ActivePaginator $masterConfig)
  339.     {
  340.         $rootFolder $masterConfig->getParent();
  341.         $doService = new DataObject\Service(User::getById(0));
  342.         if ($rootFolder instanceof DataObject\Folder && $rootFolder->hasChildren() && $masterConfig->hasChildren())
  343.         {
  344.             foreach ($rootFolder->getChildren() as $configChild)
  345.             {
  346.                 if ($configChild instanceof DataObject\ActivePaginator)
  347.                 {
  348.                     $propertyMasterLink $configChild->hasProperty("active_paginator_master_link")
  349.                         ? $configChild->getProperty("active_paginator_master_link")
  350.                         : null;
  351.                     // Only ActivePaginator declinaison
  352.                     if ($configChild->hasChildren() && $propertyMasterLink instanceof DataObject\ActivePaginator)
  353.                     {
  354.                         // For each chapter in master object
  355.                         foreach ($masterConfig->getChildren() as $masterChapter)
  356.                         {
  357.                             if ($masterChapter instanceof ActivePaginatorChapters)
  358.                             {
  359.                                 $chapterChildPath $configChild->getFullPath() . "/" $masterChapter->getKey();
  360.                                 // Chapter already exist
  361.                                 if (DataObject\Service::pathExists($chapterChildPath))
  362.                                 {
  363.                                     $chapterChild DataObject::getByPath($chapterChildPath);
  364.                                     if ($chapterChild instanceof ActivePaginatorChapters)
  365.                                     {
  366.                                         $chapterChild->setItems($masterChapter->getItems());
  367.                                         $chapterChild->setPublished($masterChapter->isPublished());
  368.                                         $chapterChild->save();
  369.                                     }
  370.                                 }
  371.                                 else // Chapter not exist
  372.                                 {
  373.                                     $doService->copyAsChild($configChild$masterChapter);
  374.                                 }
  375.                             }
  376.                         }
  377.                     }
  378.                 }
  379.             }
  380.         }
  381.     }
  382.     /**
  383.      * Add properties if not exist :
  384.      * <ul>
  385.      * <li>bricoman_date_pub_obj</li>
  386.      * <li>bricoman_date_referent_obj</li>
  387.      * </ul>
  388.      *
  389.      * @param DataObject\ActivePaginator $object
  390.      */
  391.     private function addProperties(DataObject\ActivePaginator $object)
  392.     {
  393.         $propertiesToAdd = [
  394.             'bricoman_date_pub_obj' => 'bricoman_date_pub_obj',
  395.             'bricoman_date_referent_obj' => 'bricoman_date_referent_obj'
  396.         ];
  397.         $properties = array();
  398.         // If properties already exist no need to add them
  399.         if ($object->getProperties()) {
  400.             // Si l'objet a déjà les propriété crées
  401.             $regex_data "/^([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))$/";
  402.             $error_msg "";
  403.             /** @var Property $p */
  404.             foreach($object->getProperties() as $p) {
  405.                 if(in_array($p->getName(), $propertiesToAdd))
  406.                 {
  407.                     $translator = \Pimcore::getContainer()->get('translator');
  408.                     if (!preg_match($regex_data,  $p->getData()))
  409.                     {
  410.                         // Si les valeurs des propriétés ne sont pas sous le format "YYYY-MM-dd", on arrête le script
  411.                         if ($p->getName() == 'bricoman_date_pub_obj') {
  412.                             throw new ValidationException($translator->trans('bricoman_date_pub_obj_no_valid_msg'));
  413.                         } else if ($p->getName() == 'bricoman_date_referent_obj') {
  414.                             throw new ValidationException($translator->trans('bricoman_date_referent_obj_no_valid_msg'));
  415.                         }
  416.                     } else {
  417.                         $properties[$p->getName()] = $p;
  418.                     }
  419.                 }
  420.             }
  421.         } else {
  422.             // Lors du premier save, on vient créer les deux propriétés
  423.             foreach($propertiesToAdd as $key => $p) {
  424.                 $predifinedProperty Property\Predefined::getByKey($p);
  425.                 $property = new Property();
  426.                 $property->setType($predifinedProperty->getType());
  427.                 $property->setCtype($predifinedProperty->getCtype());
  428.                 $property->setName($predifinedProperty->getKey());
  429.                 $property->setInheritable($predifinedProperty->getInheritable());
  430.                 $property->setData("");
  431.                 $properties[$p] = $property;
  432.             }
  433.         }
  434.         // Adding properties to the object
  435.         $object->setProperties($properties);
  436.     }
  437. }