<?php
namespace App\Traits;
use CoreShop\Component\Core\Model\CustomerInterface;
use Pimcore\Model\DataObject;
use Pimcore\Model\Version;
trait RecentWatches
{
public function saveRecentWatch($product): void
{
$customer = $this->getUser()?->getCustomer();
if (!$customer instanceof CustomerInterface) {
return;
}
$lastViewedWatches = DataObject\LastViewedWatches::getByCustomer($customer)->current();
if (!$lastViewedWatches) {
$lastViewedWatches = new DataObject\LastViewedWatches();
$lastViewedWatches->setCustomer($customer);
try {
Version::disable();
$lastViewedWatches->save();
Version::enable();
} catch (\Exception $e) {
$this->getLogger()->error('Error during saving lastViewedWatches object: ' . $e->getMessage());
return ;
}
}
$watches = $lastViewedWatches->getWatches();
while ((count($watches)) > $this->lastViewedLimit) {
array_pop($watches);#delete last 'x' elem in the array
}
foreach ($watches as $key => $oraId) {
if ($product->getId() == $oraId->getElementId()) {
unset($watches[$key]);#delete it if exists in the array
break;
}
}
$currentWatch = new DataObject\Data\ElementMetadata('watches', ['visitDate'], $product);
$currentWatch->setVisitDate(date("Y-m-d H:i:s"));
array_unshift($watches, $currentWatch);#push currentWatch
$lastViewedWatches->setWatches($watches);
\Pimcore\Model\Version::disable();
$lastViewedWatches->save();
\Pimcore\Model\Version::enable();
}
}