Files
kupshop/bundles/KupShop/KupShopBundle/Template/CachingWrapperTrait.php
2025-08-02 16:30:27 +02:00

65 lines
1.3 KiB
PHP

<?php
namespace KupShop\KupShopBundle\Template;
use Doctrine\Common\Collections\ArrayCollection;
trait CachingWrapperTrait
{
protected $cached_values = [];
public function __clone()
{
$this->cached_values = [];
}
/**
* @return bool
*/
protected function getCachedValue(&$value)
{
$field = $this->getCachedFieldName();
if (array_key_exists($field, $this->cached_values)) {
$value = $this->cached_values[$field];
return true;
}
return false;
}
protected function setCachedValue(&$value)
{
$field = $this->getCachedFieldName();
$this->cached_values[$field] = $value;
}
protected function getCachedFieldName()
{
$function = @debug_backtrace()[2]['function'];
if (strpos($function, 'field_') !== 0) {
throw new \Exception('Cannot get cached field name');
}
return substr($function, 6);
}
protected function jsonSerializeObject()
{
$data = parent::jsonSerializeObject();
foreach ($this->cached_values as $key => $value) {
if ($value instanceof ArrayCollection) {
$data[$key] = $value->toArray();
continue;
}
$data[$key] = $value;
}
return $data;
}
}