RequestDataCollector.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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\HttpFoundation\Cookie;
  12. use Symfony\Component\HttpFoundation\ParameterBag;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  16. use Symfony\Component\HttpKernel\KernelEvents;
  17. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  18. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  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 = array();
  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 = array();
  53. $sessionAttributes = array();
  54. $session = null;
  55. $flashes = array();
  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 = array();
  68. foreach ($response->headers->getCookies() as $cookie) {
  69. $responseCookies[$cookie->getName()] = $cookie;
  70. }
  71. $dotenvVars = array();
  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 = array(
  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_headers' => $request->headers->all(),
  87. 'request_server' => $request->server->all(),
  88. 'request_cookies' => $request->cookies->all(),
  89. 'request_attributes' => $attributes,
  90. 'route' => $route,
  91. 'response_headers' => $response->headers->all(),
  92. 'response_cookies' => $responseCookies,
  93. 'session_metadata' => $sessionMetadata,
  94. 'session_attributes' => $sessionAttributes,
  95. 'flashes' => $flashes,
  96. 'path_info' => $request->getPathInfo(),
  97. 'controller' => 'n/a',
  98. 'locale' => $request->getLocale(),
  99. 'dotenv_vars' => $dotenvVars,
  100. );
  101. if (isset($this->data['request_headers']['php-auth-pw'])) {
  102. $this->data['request_headers']['php-auth-pw'] = '******';
  103. }
  104. if (isset($this->data['request_server']['PHP_AUTH_PW'])) {
  105. $this->data['request_server']['PHP_AUTH_PW'] = '******';
  106. }
  107. if (isset($this->data['request_request']['_password'])) {
  108. $this->data['request_request']['_password'] = '******';
  109. }
  110. foreach ($this->data as $key => $value) {
  111. if (!is_array($value)) {
  112. continue;
  113. }
  114. if ('request_headers' === $key || 'response_headers' === $key) {
  115. $this->data[$key] = array_map(function ($v) { return isset($v[0]) && !isset($v[1]) ? $v[0] : $v; }, $value);
  116. }
  117. }
  118. if (isset($this->controllers[$request])) {
  119. $this->data['controller'] = $this->parseController($this->controllers[$request]);
  120. unset($this->controllers[$request]);
  121. }
  122. if ($request->attributes->has('_redirected') && $redirectCookie = $request->cookies->get('sf_redirect')) {
  123. $this->data['redirect'] = json_decode($redirectCookie, true);
  124. $response->headers->clearCookie('sf_redirect');
  125. }
  126. if ($response->isRedirect()) {
  127. $response->headers->setCookie(new Cookie(
  128. 'sf_redirect',
  129. json_encode(array(
  130. 'token' => $response->headers->get('x-debug-token'),
  131. 'route' => $request->attributes->get('_route', 'n/a'),
  132. 'method' => $request->getMethod(),
  133. 'controller' => $this->parseController($request->attributes->get('_controller')),
  134. 'status_code' => $statusCode,
  135. 'status_text' => Response::$statusTexts[(int) $statusCode],
  136. ))
  137. ));
  138. }
  139. $this->data['identifier'] = $this->data['route'] ?: (is_array($this->data['controller']) ? $this->data['controller']['class'].'::'.$this->data['controller']['method'].'()' : $this->data['controller']);
  140. if ($response->headers->has('x-previous-debug-token')) {
  141. $this->data['forward_token'] = $response->headers->get('x-previous-debug-token');
  142. }
  143. }
  144. public function lateCollect()
  145. {
  146. $this->data = $this->cloneVar($this->data);
  147. }
  148. public function reset()
  149. {
  150. $this->data = array();
  151. $this->controllers = new \SplObjectStorage();
  152. }
  153. public function getMethod()
  154. {
  155. return $this->data['method'];
  156. }
  157. public function getPathInfo()
  158. {
  159. return $this->data['path_info'];
  160. }
  161. public function getRequestRequest()
  162. {
  163. return new ParameterBag($this->data['request_request']->getValue());
  164. }
  165. public function getRequestQuery()
  166. {
  167. return new ParameterBag($this->data['request_query']->getValue());
  168. }
  169. public function getRequestHeaders()
  170. {
  171. return new ParameterBag($this->data['request_headers']->getValue());
  172. }
  173. public function getRequestServer($raw = false)
  174. {
  175. return new ParameterBag($this->data['request_server']->getValue($raw));
  176. }
  177. public function getRequestCookies($raw = false)
  178. {
  179. return new ParameterBag($this->data['request_cookies']->getValue($raw));
  180. }
  181. public function getRequestAttributes()
  182. {
  183. return new ParameterBag($this->data['request_attributes']->getValue());
  184. }
  185. public function getResponseHeaders()
  186. {
  187. return new ParameterBag($this->data['response_headers']->getValue());
  188. }
  189. public function getResponseCookies()
  190. {
  191. return new ParameterBag($this->data['response_cookies']->getValue());
  192. }
  193. public function getSessionMetadata()
  194. {
  195. return $this->data['session_metadata']->getValue();
  196. }
  197. public function getSessionAttributes()
  198. {
  199. return $this->data['session_attributes']->getValue();
  200. }
  201. public function getFlashes()
  202. {
  203. return $this->data['flashes']->getValue();
  204. }
  205. public function getContent()
  206. {
  207. return $this->data['content'];
  208. }
  209. public function getContentType()
  210. {
  211. return $this->data['content_type'];
  212. }
  213. public function getStatusText()
  214. {
  215. return $this->data['status_text'];
  216. }
  217. public function getStatusCode()
  218. {
  219. return $this->data['status_code'];
  220. }
  221. public function getFormat()
  222. {
  223. return $this->data['format'];
  224. }
  225. public function getLocale()
  226. {
  227. return $this->data['locale'];
  228. }
  229. public function getDotenvVars()
  230. {
  231. return new ParameterBag($this->data['dotenv_vars']->getValue());
  232. }
  233. /**
  234. * Gets the route name.
  235. *
  236. * The _route request attributes is automatically set by the Router Matcher.
  237. *
  238. * @return string The route
  239. */
  240. public function getRoute()
  241. {
  242. return $this->data['route'];
  243. }
  244. public function getIdentifier()
  245. {
  246. return $this->data['identifier'];
  247. }
  248. /**
  249. * Gets the route parameters.
  250. *
  251. * The _route_params request attributes is automatically set by the RouterListener.
  252. *
  253. * @return array The parameters
  254. */
  255. public function getRouteParams()
  256. {
  257. return isset($this->data['request_attributes']['_route_params']) ? $this->data['request_attributes']['_route_params']->getValue() : array();
  258. }
  259. /**
  260. * Gets the parsed controller.
  261. *
  262. * @return array|string The controller as a string or array of data
  263. * with keys 'class', 'method', 'file' and 'line'
  264. */
  265. public function getController()
  266. {
  267. return $this->data['controller'];
  268. }
  269. /**
  270. * Gets the previous request attributes.
  271. *
  272. * @return array|bool A legacy array of data from the previous redirection response
  273. * or false otherwise
  274. */
  275. public function getRedirect()
  276. {
  277. return isset($this->data['redirect']) ? $this->data['redirect'] : false;
  278. }
  279. public function getForwardToken()
  280. {
  281. return isset($this->data['forward_token']) ? $this->data['forward_token'] : null;
  282. }
  283. public function onKernelController(FilterControllerEvent $event)
  284. {
  285. $this->controllers[$event->getRequest()] = $event->getController();
  286. }
  287. public function onKernelResponse(FilterResponseEvent $event)
  288. {
  289. if (!$event->isMasterRequest()) {
  290. return;
  291. }
  292. if ($event->getRequest()->cookies->has('sf_redirect')) {
  293. $event->getRequest()->attributes->set('_redirected', true);
  294. }
  295. }
  296. public static function getSubscribedEvents()
  297. {
  298. return array(
  299. KernelEvents::CONTROLLER => 'onKernelController',
  300. KernelEvents::RESPONSE => 'onKernelResponse',
  301. );
  302. }
  303. /**
  304. * {@inheritdoc}
  305. */
  306. public function getName()
  307. {
  308. return 'request';
  309. }
  310. /**
  311. * Parse a controller.
  312. *
  313. * @param mixed $controller The controller to parse
  314. *
  315. * @return array|string An array of controller data or a simple string
  316. */
  317. protected function parseController($controller)
  318. {
  319. if (is_string($controller) && false !== strpos($controller, '::')) {
  320. $controller = explode('::', $controller);
  321. }
  322. if (is_array($controller)) {
  323. try {
  324. $r = new \ReflectionMethod($controller[0], $controller[1]);
  325. return array(
  326. 'class' => is_object($controller[0]) ? get_class($controller[0]) : $controller[0],
  327. 'method' => $controller[1],
  328. 'file' => $r->getFileName(),
  329. 'line' => $r->getStartLine(),
  330. );
  331. } catch (\ReflectionException $e) {
  332. if (is_callable($controller)) {
  333. // using __call or __callStatic
  334. return array(
  335. 'class' => is_object($controller[0]) ? get_class($controller[0]) : $controller[0],
  336. 'method' => $controller[1],
  337. 'file' => 'n/a',
  338. 'line' => 'n/a',
  339. );
  340. }
  341. }
  342. }
  343. if ($controller instanceof \Closure) {
  344. $r = new \ReflectionFunction($controller);
  345. return array(
  346. 'class' => $r->getName(),
  347. 'method' => null,
  348. 'file' => $r->getFileName(),
  349. 'line' => $r->getStartLine(),
  350. );
  351. }
  352. if (is_object($controller)) {
  353. $r = new \ReflectionClass($controller);
  354. return array(
  355. 'class' => $r->getName(),
  356. 'method' => null,
  357. 'file' => $r->getFileName(),
  358. 'line' => $r->getStartLine(),
  359. );
  360. }
  361. return is_string($controller) ? $controller : 'n/a';
  362. }
  363. }