暫無描述

Profiler.php 7.3KB

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