qtools_profiler-8.x-1.x-dev/modules/qtools_profiler_example/src/PerformanceService.php
modules/qtools_profiler_example/src/PerformanceService.php
<?php
namespace Drupal\qtools_profiler_example;
use Drupal\Core\Database\Connection;
/**
* Class PerformanceService.
*
* @package Drupal\qtools_profiler_example
*/
class PerformanceService {
/**
* Drupal\Core\Database\Connection.
*
* @var \Drupal\Core\Database\Connection
*/
protected $connection;
/**
* Entity loads count.
*
* @var int
*/
protected $loadsCount;
// Table names.
const TABLE_LOADS = 'qtools_profiler_example_loads';
/**
* PerformanceService constructor.
*
* @param \Drupal\Core\Database\Connection $connection
* Connection object.
*/
public function __construct(
Connection $connection
) {
$this->connection = $connection;
$this->loadsCount = 0;
}
/**
* Increase entity load count.
*/
public function trackEntityLoad() {
$this->loadsCount++;
}
/**
* Return entity loads count.
*
* @return int
* Value of the counter.
*/
public function getEntityLoadsCount() {
return $this->loadsCount;
}
/**
* Saves performance stats to database.
*
* @param int $rid
* Request ID.
* @param int $stats
* Statistic.gg.
*
* @throws \Exception
*/
public function savePerformanceStats($rid, $stats) {
$query = $this->connection
->insert(static::TABLE_LOADS)
->fields(['rid' => $rid, 'count' => $stats]);
$query->execute();
}
/**
* Saves performance stats to database.
*
* @param int $rid
* Request ID.
*
* @return mixed
* Query result.
*
* @throws \Exception
*/
public function getPerformanceStat($rid) {
// Check if table still exists.
if (!$this->connection->schema()->tableExists(static::TABLE_LOADS)) {
return NULL;
}
$query = $this->connection->select(static::TABLE_LOADS, 'c');
$query->fields('c');
$query->condition('rid', $rid);
return $query->execute()->fetch()->count ?? 0;
}
/**
* Flush all logs.
*/
public function flush() {
$this->connection->truncate(static::TABLE_LOADS)->execute();
}
/**
* Flush all logs up until given request id.
*
* @param int $rid
* Request ID.
*/
public function cleanup($rid) {
// Clean up own tables.
$this->connection->delete(static::TABLE_LOADS)
->condition('rid', $rid, '<')
->execute();
}
}
