Profiler.php 6.6 KB

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