RequestDataCollector.php 14 KB

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