PerformanceTestRecorder.php in Drupal 10
File
core/lib/Drupal/Core/Test/PerformanceTestRecorder.php
View source
<?php
namespace Drupal\Core\Test;
use Drupal\Core\Routing\RoutingEvents;
use Drupal\Core\State\StateInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Yaml\Yaml;
class PerformanceTestRecorder implements EventSubscriberInterface {
protected $service;
protected static $record = [];
public function __construct(bool $persistent, ?StateInterface $state) {
if ($persistent && !$state) {
throw new \InvalidArgumentException('If $persistent is TRUE then $state must be set');
}
$this->state = $state;
}
public function getCount(string $type, string $name) : int {
$count = 0;
if ($this->state) {
$record = $this->state
->get('drupal.performance_test_recorder', []);
$count += $record[$type][$name] ?? 0;
}
$count += self::$record[$type][$name] ?? 0;
return $count;
}
public function record(string $type, string $name) : void {
if ($this->state) {
$record = $this->state
->get('drupal.performance_test_recorder', []);
isset($record[$type][$name]) ? $record[$type][$name]++ : ($record[$type][$name] = 1);
$this->state
->set('drupal.performance_test_recorder', $record);
}
else {
isset(self::$record[$type][$name]) ? self::$record[$type][$name]++ : (self::$record[$type][$name] = 1);
}
}
public function onRouteBuilderFinish() {
$this
->record('event', RoutingEvents::FINISHED);
}
public static function getSubscribedEvents() : array {
$events = [];
$events[RoutingEvents::FINISHED][] = [
'onRouteBuilderFinish',
-9999999,
];
return $events;
}
public static function registerService(string $services_file, bool $persistent) : void {
$services = Yaml::parse(file_get_contents($services_file));
if (isset($services['services']['core.performance.test.recorder'])) {
$persistent = $persistent || $services['services']['core.performance.test.recorder']['arguments'][0];
}
$services['services']['core.performance.test.recorder'] = [
'class' => PerformanceTestRecorder::class,
'arguments' => [
$persistent,
$persistent ? '@state' : NULL,
],
'tags' => [
[
'name' => 'event_subscriber',
],
],
];
file_put_contents($services_file, Yaml::dump($services));
}
}