暫無描述

RequestDataCollector.php 14KB

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