Profiler.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\Profiler;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface;
  16. use Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface;
  17. use Symfony\Contracts\Service\ResetInterface;
  18. /**
  19. * Profiler.
  20. *
  21. * @author Fabien Potencier <fabien@symfony.com>
  22. */
  23. class Profiler implements ResetInterface
  24. {
  25. /**
  26. * @var DataCollectorInterface[]
  27. */
  28. private array $collectors = [];
  29. private bool $initiallyEnabled = true;
  30. public function __construct(
  31. private ProfilerStorageInterface $storage,
  32. private ?LoggerInterface $logger = null,
  33. private bool $enabled = true,
  34. ) {
  35. $this->initiallyEnabled = $enabled;
  36. }
  37. /**
  38. * Disables the profiler.
  39. */
  40. public function disable(): void
  41. {
  42. $this->enabled = false;
  43. }
  44. /**
  45. * Enables the profiler.
  46. */
  47. public function enable(): void
  48. {
  49. $this->enabled = true;
  50. }
  51. public function isEnabled(): bool
  52. {
  53. return $this->enabled;
  54. }
  55. /**
  56. * Loads the Profile for the given Response.
  57. */
  58. public function loadProfileFromResponse(Response $response): ?Profile
  59. {
  60. if (!$token = $response->headers->get('X-Debug-Token')) {
  61. return null;
  62. }
  63. return $this->loadProfile($token);
  64. }
  65. /**
  66. * Loads the Profile for the given token.
  67. */
  68. public function loadProfile(string $token): ?Profile
  69. {
  70. return $this->storage->read($token);
  71. }
  72. /**
  73. * Saves a Profile.
  74. */
  75. public function saveProfile(Profile $profile): bool
  76. {
  77. // late collect
  78. foreach ($profile->getCollectors() as $collector) {
  79. if ($collector instanceof LateDataCollectorInterface) {
  80. $collector->lateCollect();
  81. }
  82. }
  83. if (!($ret = $this->storage->write($profile)) && null !== $this->logger) {
  84. $this->logger->warning('Unable to store the profiler information.', ['configured_storage' => $this->storage::class]);
  85. }
  86. return $ret;
  87. }
  88. /**
  89. * Purges all data from the storage.
  90. */
  91. public function purge(): void
  92. {
  93. $this->storage->purge();
  94. }
  95. /**
  96. * Finds profiler tokens for the given criteria.
  97. *
  98. * @param int|null $limit The maximum number of tokens to return
  99. * @param string|null $start The start date to search from
  100. * @param string|null $end The end date to search to
  101. * @param \Closure|null $filter A filter to apply on the list of tokens
  102. *
  103. * @see https://php.net/datetime.formats for the supported date/time formats
  104. */
  105. public function find(?string $ip, ?string $url, ?int $limit, ?string $method, ?string $start, ?string $end, ?string $statusCode = null, ?\Closure $filter = null): array
  106. {
  107. return $this->storage->find($ip, $url, $limit, $method, $this->getTimestamp($start), $this->getTimestamp($end), $statusCode, $filter);
  108. }
  109. /**
  110. * Collects data for the given Response.
  111. */
  112. public function collect(Request $request, Response $response, ?\Throwable $exception = null): ?Profile
  113. {
  114. if (false === $this->enabled) {
  115. return null;
  116. }
  117. $profile = new Profile(bin2hex(random_bytes(3)));
  118. $profile->setTime(time());
  119. $profile->setUrl($request->getUri());
  120. $profile->setMethod($request->getMethod());
  121. $profile->setStatusCode($response->getStatusCode());
  122. try {
  123. $profile->setIp($request->getClientIp());
  124. } catch (ConflictingHeadersException) {
  125. $profile->setIp('Unknown');
  126. }
  127. if ($request->attributes->has('_virtual_type')) {
  128. $profile->setVirtualType($request->attributes->get('_virtual_type'));
  129. }
  130. if ($prevToken = $response->headers->get('X-Debug-Token')) {
  131. $response->headers->set('X-Previous-Debug-Token', $prevToken);
  132. }
  133. $response->headers->set('X-Debug-Token', $profile->getToken());
  134. foreach ($this->collectors as $collector) {
  135. $collector->collect($request, $response, $exception);
  136. // we need to clone for sub-requests
  137. $profile->addCollector(clone $collector);
  138. }
  139. return $profile;
  140. }
  141. public function reset(): void
  142. {
  143. foreach ($this->collectors as $collector) {
  144. $collector->reset();
  145. }
  146. $this->enabled = $this->initiallyEnabled;
  147. }
  148. /**
  149. * Gets the Collectors associated with this profiler.
  150. */
  151. public function all(): array
  152. {
  153. return $this->collectors;
  154. }
  155. /**
  156. * Sets the Collectors associated with this profiler.
  157. *
  158. * @param DataCollectorInterface[] $collectors An array of collectors
  159. */
  160. public function set(array $collectors = []): void
  161. {
  162. $this->collectors = [];
  163. foreach ($collectors as $collector) {
  164. $this->add($collector);
  165. }
  166. }
  167. /**
  168. * Adds a Collector.
  169. */
  170. public function add(DataCollectorInterface $collector): void
  171. {
  172. $this->collectors[$collector->getName()] = $collector;
  173. }
  174. /**
  175. * Returns true if a Collector for the given name exists.
  176. *
  177. * @param string $name A collector name
  178. */
  179. public function has(string $name): bool
  180. {
  181. return isset($this->collectors[$name]);
  182. }
  183. /**
  184. * Gets a Collector by name.
  185. *
  186. * @param string $name A collector name
  187. *
  188. * @throws \InvalidArgumentException if the collector does not exist
  189. */
  190. public function get(string $name): DataCollectorInterface
  191. {
  192. if (!isset($this->collectors[$name])) {
  193. throw new \InvalidArgumentException(\sprintf('Collector "%s" does not exist.', $name));
  194. }
  195. return $this->collectors[$name];
  196. }
  197. private function getTimestamp(?string $value): ?int
  198. {
  199. if (null === $value || '' === $value) {
  200. return null;
  201. }
  202. try {
  203. $value = new \DateTimeImmutable(is_numeric($value) ? '@'.$value : $value);
  204. } catch (\Exception) {
  205. return null;
  206. }
  207. return $value->getTimestamp();
  208. }
  209. }