vendor/symfony/http-kernel/DataCollector/RequestDataCollector.php line 370

Open in your IDE?
  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\DataCollector;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\Component\HttpFoundation\Cookie;
  13. use Symfony\Component\HttpFoundation\ParameterBag;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\RequestStack;
  16. use Symfony\Component\HttpFoundation\Response;
  17. use Symfony\Component\HttpFoundation\Session\SessionBagInterface;
  18. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  19. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  20. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  21. use Symfony\Component\HttpKernel\KernelEvents;
  22. use Symfony\Component\VarDumper\Cloner\Data;
  23. /**
  24. * @author Fabien Potencier <fabien@symfony.com>
  25. *
  26. * @final
  27. */
  28. class RequestDataCollector extends DataCollector implements EventSubscriberInterface, LateDataCollectorInterface
  29. {
  30. /**
  31. * @var \SplObjectStorage<Request, callable>
  32. */
  33. private $controllers;
  34. private $sessionUsages = [];
  35. private $requestStack;
  36. public function __construct(?RequestStack $requestStack = null)
  37. {
  38. $this->controllers = new \SplObjectStorage();
  39. $this->requestStack = $requestStack;
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. public function collect(Request $request, Response $response, ?\Throwable $exception = null)
  45. {
  46. // attributes are serialized and as they can be anything, they need to be converted to strings.
  47. $attributes = [];
  48. $route = '';
  49. foreach ($request->attributes->all() as $key => $value) {
  50. if ('_route' === $key) {
  51. $route = \is_object($value) ? $value->getPath() : $value;
  52. $attributes[$key] = $route;
  53. } else {
  54. $attributes[$key] = $value;
  55. }
  56. }
  57. $content = $request->getContent();
  58. $sessionMetadata = [];
  59. $sessionAttributes = [];
  60. $flashes = [];
  61. if (!$request->attributes->getBoolean('_stateless') && $request->hasSession()) {
  62. $session = $request->getSession();
  63. if ($session->isStarted()) {
  64. $sessionMetadata['Created'] = date(\DATE_RFC822, $session->getMetadataBag()->getCreated());
  65. $sessionMetadata['Last used'] = date(\DATE_RFC822, $session->getMetadataBag()->getLastUsed());
  66. $sessionMetadata['Lifetime'] = $session->getMetadataBag()->getLifetime();
  67. $sessionAttributes = $session->all();
  68. $flashes = $session->getFlashBag()->peekAll();
  69. }
  70. }
  71. $statusCode = $response->getStatusCode();
  72. $responseCookies = [];
  73. foreach ($response->headers->getCookies() as $cookie) {
  74. $responseCookies[$cookie->getName()] = $cookie;
  75. }
  76. $dotenvVars = [];
  77. foreach (explode(',', $_SERVER['SYMFONY_DOTENV_VARS'] ?? $_ENV['SYMFONY_DOTENV_VARS'] ?? '') as $name) {
  78. if ('' !== $name && isset($_ENV[$name])) {
  79. $dotenvVars[$name] = $_ENV[$name];
  80. }
  81. }
  82. $this->data = [
  83. 'method' => $request->getMethod(),
  84. 'format' => $request->getRequestFormat(),
  85. 'content_type' => $response->headers->get('Content-Type', 'text/html'),
  86. 'status_text' => Response::$statusTexts[$statusCode] ?? '',
  87. 'status_code' => $statusCode,
  88. 'request_query' => $request->query->all(),
  89. 'request_request' => $request->request->all(),
  90. 'request_files' => $request->files->all(),
  91. 'request_headers' => $request->headers->all(),
  92. 'request_server' => $request->server->all(),
  93. 'request_cookies' => $request->cookies->all(),
  94. 'request_attributes' => $attributes,
  95. 'route' => $route,
  96. 'response_headers' => $response->headers->all(),
  97. 'response_cookies' => $responseCookies,
  98. 'session_metadata' => $sessionMetadata,
  99. 'session_attributes' => $sessionAttributes,
  100. 'session_usages' => array_values($this->sessionUsages),
  101. 'stateless_check' => $this->requestStack && ($mainRequest = $this->requestStack->getMainRequest()) && $mainRequest->attributes->get('_stateless', false),
  102. 'flashes' => $flashes,
  103. 'path_info' => $request->getPathInfo(),
  104. 'controller' => 'n/a',
  105. 'locale' => $request->getLocale(),
  106. 'dotenv_vars' => $dotenvVars,
  107. ];
  108. if (isset($this->data['request_headers']['php-auth-pw'])) {
  109. $this->data['request_headers']['php-auth-pw'] = '******';
  110. }
  111. if (isset($this->data['request_server']['PHP_AUTH_PW'])) {
  112. $this->data['request_server']['PHP_AUTH_PW'] = '******';
  113. }
  114. if (isset($this->data['request_request']['_password'])) {
  115. $encodedPassword = rawurlencode($this->data['request_request']['_password']);
  116. $content = str_replace('_password='.$encodedPassword, '_password=******', $content);
  117. $this->data['request_request']['_password'] = '******';
  118. }
  119. $this->data['content'] = $content;
  120. foreach ($this->data as $key => $value) {
  121. if (!\is_array($value)) {
  122. continue;
  123. }
  124. if ('request_headers' === $key || 'response_headers' === $key) {
  125. $this->data[$key] = array_map(function ($v) { return isset($v[0]) && !isset($v[1]) ? $v[0] : $v; }, $value);
  126. }
  127. }
  128. if (isset($this->controllers[$request])) {
  129. $this->data['controller'] = $this->parseController($this->controllers[$request]);
  130. unset($this->controllers[$request]);
  131. }
  132. if ($request->attributes->has('_redirected') && $redirectCookie = $request->cookies->get('sf_redirect')) {
  133. $this->data['redirect'] = json_decode($redirectCookie, true);
  134. $response->headers->clearCookie('sf_redirect');
  135. }
  136. if ($response->isRedirect()) {
  137. $response->headers->setCookie(new Cookie(
  138. 'sf_redirect',
  139. json_encode([
  140. 'token' => $response->headers->get('x-debug-token'),
  141. 'route' => $request->attributes->get('_route', 'n/a'),
  142. 'method' => $request->getMethod(),
  143. 'controller' => $this->parseController($request->attributes->get('_controller')),
  144. 'status_code' => $statusCode,
  145. 'status_text' => Response::$statusTexts[$statusCode],
  146. ]),
  147. 0, '/', null, $request->isSecure(), true, false, 'lax'
  148. ));
  149. }
  150. $this->data['identifier'] = $this->data['route'] ?: (\is_array($this->data['controller']) ? $this->data['controller']['class'].'::'.$this->data['controller']['method'].'()' : $this->data['controller']);
  151. if ($response->headers->has('x-previous-debug-token')) {
  152. $this->data['forward_token'] = $response->headers->get('x-previous-debug-token');
  153. }
  154. }
  155. public function lateCollect()
  156. {
  157. $this->data = $this->cloneVar($this->data);
  158. }
  159. public function reset()
  160. {
  161. $this->data = [];
  162. $this->controllers = new \SplObjectStorage();
  163. $this->sessionUsages = [];
  164. }
  165. public function getMethod()
  166. {
  167. return $this->data['method'];
  168. }
  169. public function getPathInfo()
  170. {
  171. return $this->data['path_info'];
  172. }
  173. public function getRequestRequest()
  174. {
  175. return new ParameterBag($this->data['request_request']->getValue());
  176. }
  177. public function getRequestQuery()
  178. {
  179. return new ParameterBag($this->data['request_query']->getValue());
  180. }
  181. public function getRequestFiles()
  182. {
  183. return new ParameterBag($this->data['request_files']->getValue());
  184. }
  185. public function getRequestHeaders()
  186. {
  187. return new ParameterBag($this->data['request_headers']->getValue());
  188. }
  189. public function getRequestServer(bool $raw = false)
  190. {
  191. return new ParameterBag($this->data['request_server']->getValue($raw));
  192. }
  193. public function getRequestCookies(bool $raw = false)
  194. {
  195. return new ParameterBag($this->data['request_cookies']->getValue($raw));
  196. }
  197. public function getRequestAttributes()
  198. {
  199. return new ParameterBag($this->data['request_attributes']->getValue());
  200. }
  201. public function getResponseHeaders()
  202. {
  203. return new ParameterBag($this->data['response_headers']->getValue());
  204. }
  205. public function getResponseCookies()
  206. {
  207. return new ParameterBag($this->data['response_cookies']->getValue());
  208. }
  209. public function getSessionMetadata()
  210. {
  211. return $this->data['session_metadata']->getValue();
  212. }
  213. public function getSessionAttributes()
  214. {
  215. return $this->data['session_attributes']->getValue();
  216. }
  217. public function getStatelessCheck()
  218. {
  219. return $this->data['stateless_check'];
  220. }
  221. public function getSessionUsages()
  222. {
  223. return $this->data['session_usages'];
  224. }
  225. public function getFlashes()
  226. {
  227. return $this->data['flashes']->getValue();
  228. }
  229. public function getContent()
  230. {
  231. return $this->data['content'];
  232. }
  233. public function isJsonRequest()
  234. {
  235. return 1 === preg_match('{^application/(?:\w+\++)*json$}i', $this->data['request_headers']['content-type']);
  236. }
  237. public function getPrettyJson()
  238. {
  239. $decoded = json_decode($this->getContent());
  240. return \JSON_ERROR_NONE === json_last_error() ? json_encode($decoded, \JSON_PRETTY_PRINT) : null;
  241. }
  242. public function getContentType()
  243. {
  244. return $this->data['content_type'];
  245. }
  246. public function getStatusText()
  247. {
  248. return $this->data['status_text'];
  249. }
  250. public function getStatusCode()
  251. {
  252. return $this->data['status_code'];
  253. }
  254. public function getFormat()
  255. {
  256. return $this->data['format'];
  257. }
  258. public function getLocale()
  259. {
  260. return $this->data['locale'];
  261. }
  262. public function getDotenvVars()
  263. {
  264. return new ParameterBag($this->data['dotenv_vars']->getValue());
  265. }
  266. /**
  267. * Gets the route name.
  268. *
  269. * The _route request attributes is automatically set by the Router Matcher.
  270. */
  271. public function getRoute(): string
  272. {
  273. return $this->data['route'];
  274. }
  275. public function getIdentifier()
  276. {
  277. return $this->data['identifier'];
  278. }
  279. /**
  280. * Gets the route parameters.
  281. *
  282. * The _route_params request attributes is automatically set by the RouterListener.
  283. */
  284. public function getRouteParams(): array
  285. {
  286. return isset($this->data['request_attributes']['_route_params']) ? $this->data['request_attributes']['_route_params']->getValue() : [];
  287. }
  288. /**
  289. * Gets the parsed controller.
  290. *
  291. * @return array|string|Data The controller as a string or array of data
  292. * with keys 'class', 'method', 'file' and 'line'
  293. */
  294. public function getController()
  295. {
  296. return $this->data['controller'];
  297. }
  298. /**
  299. * Gets the previous request attributes.
  300. *
  301. * @return array|Data|false A legacy array of data from the previous redirection response
  302. * or false otherwise
  303. */
  304. public function getRedirect()
  305. {
  306. return $this->data['redirect'] ?? false;
  307. }
  308. public function getForwardToken()
  309. {
  310. return $this->data['forward_token'] ?? null;
  311. }
  312. public function onKernelController(ControllerEvent $event)
  313. {
  314. $this->controllers[$event->getRequest()] = $event->getController();
  315. }
  316. public function onKernelResponse(ResponseEvent $event)
  317. {
  318. if (!$event->isMainRequest()) {
  319. return;
  320. }
  321. if ($event->getRequest()->cookies->has('sf_redirect')) {
  322. $event->getRequest()->attributes->set('_redirected', true);
  323. }
  324. }
  325. public static function getSubscribedEvents(): array
  326. {
  327. return [
  328. KernelEvents::CONTROLLER => 'onKernelController',
  329. KernelEvents::RESPONSE => 'onKernelResponse',
  330. ];
  331. }
  332. /**
  333. * {@inheritdoc}
  334. */
  335. public function getName(): string
  336. {
  337. return 'request';
  338. }
  339. public function collectSessionUsage(): void
  340. {
  341. $trace = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS);
  342. $traceEndIndex = \count($trace) - 1;
  343. for ($i = $traceEndIndex; $i > 0; --$i) {
  344. if (null !== ($class = $trace[$i]['class'] ?? null) && (is_subclass_of($class, SessionInterface::class) || is_subclass_of($class, SessionBagInterface::class))) {
  345. $traceEndIndex = $i;
  346. break;
  347. }
  348. }
  349. if ((\count($trace) - 1) === $traceEndIndex) {
  350. return;
  351. }
  352. // Remove part of the backtrace that belongs to session only
  353. array_splice($trace, 0, $traceEndIndex);
  354. // Merge identical backtraces generated by internal call reports
  355. $name = sprintf('%s:%s', $trace[1]['class'] ?? $trace[0]['file'], $trace[0]['line']);
  356. if (!\array_key_exists($name, $this->sessionUsages)) {
  357. $this->sessionUsages[$name] = [
  358. 'name' => $name,
  359. 'file' => $trace[0]['file'],
  360. 'line' => $trace[0]['line'],
  361. 'trace' => $trace,
  362. ];
  363. }
  364. }
  365. /**
  366. * @param string|object|array|null $controller The controller to parse
  367. *
  368. * @return array|string An array of controller data or a simple string
  369. */
  370. private function parseController($controller)
  371. {
  372. if (\is_string($controller) && str_contains($controller, '::')) {
  373. $controller = explode('::', $controller);
  374. }
  375. if (\is_array($controller)) {
  376. try {
  377. $r = new \ReflectionMethod($controller[0], $controller[1]);
  378. return [
  379. 'class' => \is_object($controller[0]) ? get_debug_type($controller[0]) : $controller[0],
  380. 'method' => $controller[1],
  381. 'file' => $r->getFileName(),
  382. 'line' => $r->getStartLine(),
  383. ];
  384. } catch (\ReflectionException $e) {
  385. if (\is_callable($controller)) {
  386. // using __call or __callStatic
  387. return [
  388. 'class' => \is_object($controller[0]) ? get_debug_type($controller[0]) : $controller[0],
  389. 'method' => $controller[1],
  390. 'file' => 'n/a',
  391. 'line' => 'n/a',
  392. ];
  393. }
  394. }
  395. }
  396. if ($controller instanceof \Closure) {
  397. $r = new \ReflectionFunction($controller);
  398. $controller = [
  399. 'class' => $r->getName(),
  400. 'method' => null,
  401. 'file' => $r->getFileName(),
  402. 'line' => $r->getStartLine(),
  403. ];
  404. if (str_contains($r->name, '{closure')) {
  405. return $controller;
  406. }
  407. $controller['method'] = $r->name;
  408. if ($class = \PHP_VERSION_ID >= 80111 ? $r->getClosureCalledClass() : $r->getClosureScopeClass()) {
  409. $controller['class'] = $class->name;
  410. } else {
  411. return $r->name;
  412. }
  413. return $controller;
  414. }
  415. if (\is_object($controller)) {
  416. $r = new \ReflectionClass($controller);
  417. return [
  418. 'class' => $r->getName(),
  419. 'method' => null,
  420. 'file' => $r->getFileName(),
  421. 'line' => $r->getStartLine(),
  422. ];
  423. }
  424. return \is_string($controller) ? $controller : 'n/a';
  425. }
  426. }