qtools_profiler-8.x-1.x-dev/modules/qtools_cache_profiler/src/PlaceholderingRenderCacheWrapper.php
modules/qtools_cache_profiler/src/PlaceholderingRenderCacheWrapper.php
<?php
namespace Drupal\qtools_cache_profiler;
use Drupal\Core\Render\PlaceholderGeneratorInterface;
use Drupal\Core\Render\PlaceholderingRenderCache;
use Drupal\Core\Cache\CacheFactoryInterface;
use Drupal\Core\Cache\Context\CacheContextsManager;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Class PlaceholderingRenderCacheWrapper.
*
* @package Drupal\qtools_cache_profiler
*/
class PlaceholderingRenderCacheWrapper extends PlaceholderingRenderCache {
/**
* Drupal\qtools_cache_profiler\PerformanceService.
*
* @var \Drupal\qtools_cache_profiler\PerformanceService
*/
protected $performanceService;
/**
* Constructs a new PlaceholderingRenderCacheWrapper object.
*/
public function __construct(
RequestStack $request_stack,
CacheFactoryInterface $cache_factory,
CacheContextsManager $cache_contexts_manager,
PlaceholderGeneratorInterface $placeholder_generator,
PerformanceService $performanceService
) {
parent::__construct($request_stack, $cache_factory, $cache_contexts_manager, $placeholder_generator);
$this->performanceService = $performanceService;
}
/**
* {@inheritdoc}
*/
public function get(array $elements) {
$cid = $this->createCacheID($elements);
$result = parent::get($elements);
// Log action.
if (!empty($cid)) {
if (!empty($result)) {
$this->logRenderCacheAction(PerformanceService::CACHE_HIT, $cid, strlen($result['#markup']));
}
else {
$this->logRenderCacheAction(PerformanceService::CACHE_MISS, $cid);
}
}
return $result;
}
/**
* {@inheritdoc}
*/
public function set(array &$elements, array $pre_bubbling_elements) {
$cid = $this->createCacheID($elements);
$result = parent::set($elements, $pre_bubbling_elements);
// Log action.
if (!empty($cid) && $result === NULL) {
$this->logRenderCacheAction(PerformanceService::CACHE_SET, $cid, strlen($elements['#markup']));
}
return $result;
}
/**
* Logs render cache action.
*/
public function logRenderCacheAction($action, $cid, $volume = 0) {
$log = &drupal_static('qtools_cache_profiler:render_cache_actions', []);
$log[] = [$action, $cid, $volume];
}
/**
* Gets stored render cache actions.
*/
public function getPerformanceStats() {
$log = &drupal_static('qtools_cache_profiler:render_cache_actions', []);
$stats = [];
foreach ($log as $item) {
list($action, $cid) = $item;
$stats[$cid] = empty($stats[$cid]) ? $action : max($stats[$cid], $action);
}
return $stats;
}
}
