DebugBar.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. <?php
  2. /*
  3. * This file is part of the DebugBar package.
  4. *
  5. * (c) 2013 Maxime Bouroumeau-Fuseau
  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 DebugBar;
  11. use ArrayAccess;
  12. use DebugBar\DataCollector\DataCollectorInterface;
  13. use DebugBar\Storage\StorageInterface;
  14. /**
  15. * Main DebugBar object
  16. *
  17. * Manages data collectors. DebugBar provides an array-like access
  18. * to collectors by name.
  19. *
  20. * <code>
  21. * $debugbar = new DebugBar();
  22. * $debugbar->addCollector(new DataCollector\MessagesCollector());
  23. * $debugbar['messages']->addMessage("foobar");
  24. * </code>
  25. */
  26. class DebugBar implements ArrayAccess
  27. {
  28. public static $useOpenHandlerWhenSendingDataHeaders = false;
  29. protected $collectors = array();
  30. protected $data;
  31. protected $jsRenderer;
  32. protected $requestIdGenerator;
  33. protected $requestId;
  34. protected $storage;
  35. protected $httpDriver;
  36. protected $stackSessionNamespace = 'PHPDEBUGBAR_STACK_DATA';
  37. protected $stackAlwaysUseSessionStorage = false;
  38. /**
  39. * Adds a data collector
  40. *
  41. * @param DataCollectorInterface $collector
  42. *
  43. * @throws DebugBarException
  44. * @return $this
  45. */
  46. public function addCollector(DataCollectorInterface $collector)
  47. {
  48. if ($collector->getName() === '__meta') {
  49. throw new DebugBarException("'__meta' is a reserved name and cannot be used as a collector name");
  50. }
  51. if (isset($this->collectors[$collector->getName()])) {
  52. throw new DebugBarException("'{$collector->getName()}' is already a registered collector");
  53. }
  54. $this->collectors[$collector->getName()] = $collector;
  55. return $this;
  56. }
  57. /**
  58. * Checks if a data collector has been added
  59. *
  60. * @param string $name
  61. * @return boolean
  62. */
  63. public function hasCollector($name)
  64. {
  65. return isset($this->collectors[$name]);
  66. }
  67. /**
  68. * Returns a data collector
  69. *
  70. * @param string $name
  71. * @return DataCollectorInterface
  72. * @throws DebugBarException
  73. */
  74. public function getCollector($name)
  75. {
  76. if (!isset($this->collectors[$name])) {
  77. throw new DebugBarException("'$name' is not a registered collector");
  78. }
  79. return $this->collectors[$name];
  80. }
  81. /**
  82. * Returns an array of all data collectors
  83. *
  84. * @return array[DataCollectorInterface]
  85. */
  86. public function getCollectors()
  87. {
  88. return $this->collectors;
  89. }
  90. /**
  91. * Sets the request id generator
  92. *
  93. * @param RequestIdGeneratorInterface $generator
  94. * @return $this
  95. */
  96. public function setRequestIdGenerator(RequestIdGeneratorInterface $generator)
  97. {
  98. $this->requestIdGenerator = $generator;
  99. return $this;
  100. }
  101. /**
  102. * @return RequestIdGeneratorInterface
  103. */
  104. public function getRequestIdGenerator()
  105. {
  106. if ($this->requestIdGenerator === null) {
  107. $this->requestIdGenerator = new RequestIdGenerator();
  108. }
  109. return $this->requestIdGenerator;
  110. }
  111. /**
  112. * Returns the id of the current request
  113. *
  114. * @return string
  115. */
  116. public function getCurrentRequestId()
  117. {
  118. if ($this->requestId === null) {
  119. $this->requestId = $this->getRequestIdGenerator()->generate();
  120. }
  121. return $this->requestId;
  122. }
  123. /**
  124. * Sets the storage backend to use to store the collected data
  125. *
  126. * @param StorageInterface $storage
  127. * @return $this
  128. */
  129. public function setStorage(StorageInterface $storage = null)
  130. {
  131. $this->storage = $storage;
  132. return $this;
  133. }
  134. /**
  135. * @return StorageInterface
  136. */
  137. public function getStorage()
  138. {
  139. return $this->storage;
  140. }
  141. /**
  142. * Checks if the data will be persisted
  143. *
  144. * @return boolean
  145. */
  146. public function isDataPersisted()
  147. {
  148. return $this->storage !== null;
  149. }
  150. /**
  151. * Sets the HTTP driver
  152. *
  153. * @param HttpDriverInterface $driver
  154. * @return $this
  155. */
  156. public function setHttpDriver(HttpDriverInterface $driver)
  157. {
  158. $this->httpDriver = $driver;
  159. return $this;
  160. }
  161. /**
  162. * Returns the HTTP driver
  163. *
  164. * If no http driver where defined, a PhpHttpDriver is automatically created
  165. *
  166. * @return HttpDriverInterface
  167. */
  168. public function getHttpDriver()
  169. {
  170. if ($this->httpDriver === null) {
  171. $this->httpDriver = new PhpHttpDriver();
  172. }
  173. return $this->httpDriver;
  174. }
  175. /**
  176. * Collects the data from the collectors
  177. *
  178. * @return array
  179. */
  180. public function collect()
  181. {
  182. if (php_sapi_name() === 'cli') {
  183. $ip = gethostname();
  184. if ($ip) {
  185. $ip = gethostbyname($ip);
  186. } else {
  187. $ip = '127.0.0.1';
  188. }
  189. $request_variables = array(
  190. 'method' => 'CLI',
  191. 'uri' => isset($_SERVER['SCRIPT_FILENAME']) ? realpath($_SERVER['SCRIPT_FILENAME']) : null,
  192. 'ip' => $ip
  193. );
  194. } else {
  195. $request_variables = array(
  196. 'method' => isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : null,
  197. 'uri' => isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : null,
  198. 'ip' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null
  199. );
  200. }
  201. $this->data = array(
  202. '__meta' => array_merge(
  203. array(
  204. 'id' => $this->getCurrentRequestId(),
  205. 'datetime' => date('Y-m-d H:i:s'),
  206. 'utime' => microtime(true)
  207. ),
  208. $request_variables
  209. )
  210. );
  211. foreach ($this->collectors as $name => $collector) {
  212. $this->data[$name] = $collector->collect();
  213. }
  214. // Remove all invalid (non UTF-8) characters
  215. array_walk_recursive($this->data, function (&$item) {
  216. if (is_string($item) && !mb_check_encoding($item, 'UTF-8')) {
  217. $item = mb_convert_encoding($item, 'UTF-8', 'UTF-8');
  218. }
  219. });
  220. if ($this->storage !== null) {
  221. $this->storage->save($this->getCurrentRequestId(), $this->data);
  222. }
  223. return $this->data;
  224. }
  225. /**
  226. * Returns collected data
  227. *
  228. * Will collect the data if none have been collected yet
  229. *
  230. * @return array
  231. */
  232. public function getData()
  233. {
  234. if ($this->data === null) {
  235. $this->collect();
  236. }
  237. return $this->data;
  238. }
  239. /**
  240. * Returns an array of HTTP headers containing the data
  241. *
  242. * @param string $headerName
  243. * @param integer $maxHeaderLength
  244. * @return array
  245. */
  246. public function getDataAsHeaders($headerName = 'phpdebugbar', $maxHeaderLength = 4096, $maxTotalHeaderLength = 250000)
  247. {
  248. $data = rawurlencode(json_encode(array(
  249. 'id' => $this->getCurrentRequestId(),
  250. 'data' => $this->getData()
  251. )));
  252. if (strlen($data) > $maxTotalHeaderLength) {
  253. $data = rawurlencode(json_encode(array(
  254. 'error' => 'Maximum header size exceeded'
  255. )));
  256. }
  257. $chunks = array();
  258. while (strlen($data) > $maxHeaderLength) {
  259. $chunks[] = substr($data, 0, $maxHeaderLength);
  260. $data = substr($data, $maxHeaderLength);
  261. }
  262. $chunks[] = $data;
  263. $headers = array();
  264. for ($i = 0, $c = count($chunks); $i < $c; $i++) {
  265. $name = $headerName . ($i > 0 ? "-$i" : '');
  266. $headers[$name] = $chunks[$i];
  267. }
  268. return $headers;
  269. }
  270. /**
  271. * Sends the data through the HTTP headers
  272. *
  273. * @param bool $useOpenHandler
  274. * @param string $headerName
  275. * @param integer $maxHeaderLength
  276. * @return $this
  277. */
  278. public function sendDataInHeaders($useOpenHandler = null, $headerName = 'phpdebugbar', $maxHeaderLength = 4096)
  279. {
  280. if ($useOpenHandler === null) {
  281. $useOpenHandler = self::$useOpenHandlerWhenSendingDataHeaders;
  282. }
  283. if ($useOpenHandler && $this->storage !== null) {
  284. $this->getData();
  285. $headerName .= '-id';
  286. $headers = array($headerName => $this->getCurrentRequestId());
  287. } else {
  288. $headers = $this->getDataAsHeaders($headerName, $maxHeaderLength);
  289. }
  290. $this->getHttpDriver()->setHeaders($headers);
  291. return $this;
  292. }
  293. /**
  294. * Stacks the data in the session for later rendering
  295. */
  296. public function stackData()
  297. {
  298. $http = $this->initStackSession();
  299. $data = null;
  300. if (!$this->isDataPersisted() || $this->stackAlwaysUseSessionStorage) {
  301. $data = $this->getData();
  302. } elseif ($this->data === null) {
  303. $this->collect();
  304. }
  305. $stack = $http->getSessionValue($this->stackSessionNamespace);
  306. $stack[$this->getCurrentRequestId()] = $data;
  307. $http->setSessionValue($this->stackSessionNamespace, $stack);
  308. return $this;
  309. }
  310. /**
  311. * Checks if there is stacked data in the session
  312. *
  313. * @return boolean
  314. */
  315. public function hasStackedData()
  316. {
  317. try {
  318. $http = $this->initStackSession();
  319. } catch (DebugBarException $e) {
  320. return false;
  321. }
  322. return count($http->getSessionValue($this->stackSessionNamespace)) > 0;
  323. }
  324. /**
  325. * Returns the data stacked in the session
  326. *
  327. * @param boolean $delete Whether to delete the data in the session
  328. * @return array
  329. */
  330. public function getStackedData($delete = true)
  331. {
  332. $http = $this->initStackSession();
  333. $stackedData = $http->getSessionValue($this->stackSessionNamespace);
  334. if ($delete) {
  335. $http->deleteSessionValue($this->stackSessionNamespace);
  336. }
  337. $datasets = array();
  338. if ($this->isDataPersisted() && !$this->stackAlwaysUseSessionStorage) {
  339. foreach ($stackedData as $id => $data) {
  340. $datasets[$id] = $this->getStorage()->get($id);
  341. }
  342. } else {
  343. $datasets = $stackedData;
  344. }
  345. return $datasets;
  346. }
  347. /**
  348. * Sets the key to use in the $_SESSION array
  349. *
  350. * @param string $ns
  351. * @return $this
  352. */
  353. public function setStackDataSessionNamespace($ns)
  354. {
  355. $this->stackSessionNamespace = $ns;
  356. return $this;
  357. }
  358. /**
  359. * Returns the key used in the $_SESSION array
  360. *
  361. * @return string
  362. */
  363. public function getStackDataSessionNamespace()
  364. {
  365. return $this->stackSessionNamespace;
  366. }
  367. /**
  368. * Sets whether to only use the session to store stacked data even
  369. * if a storage is enabled
  370. *
  371. * @param boolean $enabled
  372. * @return $this
  373. */
  374. public function setStackAlwaysUseSessionStorage($enabled = true)
  375. {
  376. $this->stackAlwaysUseSessionStorage = $enabled;
  377. return $this;
  378. }
  379. /**
  380. * Checks if the session is always used to store stacked data
  381. * even if a storage is enabled
  382. *
  383. * @return boolean
  384. */
  385. public function isStackAlwaysUseSessionStorage()
  386. {
  387. return $this->stackAlwaysUseSessionStorage;
  388. }
  389. /**
  390. * Initializes the session for stacked data
  391. * @return HttpDriverInterface
  392. * @throws DebugBarException
  393. */
  394. protected function initStackSession()
  395. {
  396. $http = $this->getHttpDriver();
  397. if (!$http->isSessionStarted()) {
  398. throw new DebugBarException("Session must be started before using stack data in the debug bar");
  399. }
  400. if (!$http->hasSessionValue($this->stackSessionNamespace)) {
  401. $http->setSessionValue($this->stackSessionNamespace, array());
  402. }
  403. return $http;
  404. }
  405. /**
  406. * Returns a JavascriptRenderer for this instance
  407. * @param string $baseUrl
  408. * @param string $basePath
  409. * @return JavascriptRenderer
  410. */
  411. public function getJavascriptRenderer($baseUrl = null, $basePath = null)
  412. {
  413. if ($this->jsRenderer === null) {
  414. $this->jsRenderer = new JavascriptRenderer($this, $baseUrl, $basePath);
  415. }
  416. return $this->jsRenderer;
  417. }
  418. // --------------------------------------------
  419. // ArrayAccess implementation
  420. public function offsetSet($key, $value)
  421. {
  422. throw new DebugBarException("DebugBar[] is read-only");
  423. }
  424. public function offsetGet($key)
  425. {
  426. return $this->getCollector($key);
  427. }
  428. public function offsetExists($key)
  429. {
  430. return $this->hasCollector($key);
  431. }
  432. public function offsetUnset($key)
  433. {
  434. throw new DebugBarException("DebugBar[] is read-only");
  435. }
  436. }