Profiler.php 6.9 KB

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