src/Traits/RecentWatches.php line 11

Open in your IDE?
  1. <?php
  2. namespace App\Traits;
  3. use CoreShop\Component\Core\Model\CustomerInterface;
  4. use Pimcore\Model\DataObject;
  5. use Pimcore\Model\Version;
  6. trait RecentWatches
  7. {
  8.     public function saveRecentWatch($product): void
  9.     {
  10.         $customer $this->getUser()?->getCustomer();
  11.         if (!$customer instanceof CustomerInterface) {
  12.             return;
  13.         }
  14.         $lastViewedWatches DataObject\LastViewedWatches::getByCustomer($customer)->current();
  15.         if (!$lastViewedWatches) {
  16.             $lastViewedWatches = new DataObject\LastViewedWatches();
  17.             $lastViewedWatches->setCustomer($customer);
  18.             try {
  19.                 Version::disable();
  20.                 $lastViewedWatches->save();
  21.                 Version::enable();
  22.             } catch (\Exception $e) {
  23.                 $this->getLogger()->error('Error during saving lastViewedWatches object: ' $e->getMessage());
  24.                 return ;
  25.             }
  26.         }
  27.         $watches $lastViewedWatches->getWatches();
  28.         while ((count($watches)) > $this->lastViewedLimit) {
  29.             array_pop($watches);#delete last 'x' elem in the array
  30.         }
  31.         foreach ($watches as $key => $oraId) {
  32.             if ($product->getId() == $oraId->getElementId()) {
  33.                 unset($watches[$key]);#delete it if exists in the array
  34.                 break;
  35.             }
  36.         }
  37.         $currentWatch = new DataObject\Data\ElementMetadata('watches', ['visitDate'], $product);
  38.         $currentWatch->setVisitDate(date("Y-m-d H:i:s"));
  39.         array_unshift($watches$currentWatch);#push currentWatch
  40.         $lastViewedWatches->setWatches($watches);
  41.         \Pimcore\Model\Version::disable();
  42.         $lastViewedWatches->save();
  43.         \Pimcore\Model\Version::enable();
  44.     }
  45. }