JavascriptRenderer.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  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 DebugBar\DataCollector\AssetProvider;
  12. use DebugBar\DataCollector\Renderable;
  13. /**
  14. * Renders the debug bar using the client side javascript implementation
  15. *
  16. * Generates all the needed initialization code of controls
  17. */
  18. class JavascriptRenderer
  19. {
  20. const INITIALIZE_CONSTRUCTOR = 2;
  21. const INITIALIZE_CONTROLS = 4;
  22. const REPLACEABLE_TAG = "{--DEBUGBAR_OB_START_REPLACE_ME--}";
  23. const RELATIVE_PATH = 'path';
  24. const RELATIVE_URL = 'url';
  25. protected $debugBar;
  26. protected $baseUrl;
  27. protected $basePath;
  28. protected $cssVendors = array(
  29. 'fontawesome' => 'vendor/font-awesome/css/font-awesome.min.css',
  30. 'highlightjs' => 'vendor/highlightjs/styles/github.css'
  31. );
  32. protected $jsVendors = array(
  33. 'jquery' => 'vendor/jquery/dist/jquery.min.js',
  34. 'highlightjs' => 'vendor/highlightjs/highlight.pack.js'
  35. );
  36. protected $includeVendors = true;
  37. protected $cssFiles = array('debugbar.css', 'widgets.css', 'openhandler.css');
  38. protected $jsFiles = array('debugbar.js', 'widgets.js', 'openhandler.js');
  39. protected $additionalAssets = array();
  40. protected $javascriptClass = 'PhpDebugBar.DebugBar';
  41. protected $variableName = 'phpdebugbar';
  42. protected $enableJqueryNoConflict = true;
  43. protected $initialization;
  44. protected $controls = array();
  45. protected $ignoredCollectors = array();
  46. protected $ajaxHandlerClass = 'PhpDebugBar.AjaxHandler';
  47. protected $ajaxHandlerBindToJquery = true;
  48. protected $ajaxHandlerBindToXHR = false;
  49. protected $openHandlerClass = 'PhpDebugBar.OpenHandler';
  50. protected $openHandlerUrl;
  51. /**
  52. * @param \DebugBar\DebugBar $debugBar
  53. * @param string $baseUrl
  54. * @param string $basePath
  55. */
  56. public function __construct(DebugBar $debugBar, $baseUrl = null, $basePath = null)
  57. {
  58. $this->debugBar = $debugBar;
  59. if ($baseUrl === null) {
  60. $baseUrl = '/vendor/maximebf/debugbar/src/DebugBar/Resources';
  61. }
  62. $this->baseUrl = $baseUrl;
  63. if ($basePath === null) {
  64. $basePath = __DIR__ . DIRECTORY_SEPARATOR . 'Resources';
  65. }
  66. $this->basePath = $basePath;
  67. // bitwise operations cannot be done in class definition :(
  68. $this->initialization = self::INITIALIZE_CONSTRUCTOR | self::INITIALIZE_CONTROLS;
  69. }
  70. /**
  71. * Sets options from an array
  72. *
  73. * Options:
  74. * - base_path
  75. * - base_url
  76. * - include_vendors
  77. * - javascript_class
  78. * - variable_name
  79. * - initialization
  80. * - enable_jquery_noconflict
  81. * - controls
  82. * - disable_controls
  83. * - ignore_collectors
  84. * - ajax_handler_classname
  85. * - ajax_handler_bind_to_jquery
  86. * - open_handler_classname
  87. * - open_handler_url
  88. *
  89. * @param array $options [description]
  90. */
  91. public function setOptions(array $options)
  92. {
  93. if (array_key_exists('base_path', $options)) {
  94. $this->setBasePath($options['base_path']);
  95. }
  96. if (array_key_exists('base_url', $options)) {
  97. $this->setBaseUrl($options['base_url']);
  98. }
  99. if (array_key_exists('include_vendors', $options)) {
  100. $this->setIncludeVendors($options['include_vendors']);
  101. }
  102. if (array_key_exists('javascript_class', $options)) {
  103. $this->setJavascriptClass($options['javascript_class']);
  104. }
  105. if (array_key_exists('variable_name', $options)) {
  106. $this->setVariableName($options['variable_name']);
  107. }
  108. if (array_key_exists('initialization', $options)) {
  109. $this->setInitialization($options['initialization']);
  110. }
  111. if (array_key_exists('enable_jquery_noconflict', $options)) {
  112. $this->setEnableJqueryNoConflict($options['enable_jquery_noconflict']);
  113. }
  114. if (array_key_exists('controls', $options)) {
  115. foreach ($options['controls'] as $name => $control) {
  116. $this->addControl($name, $control);
  117. }
  118. }
  119. if (array_key_exists('disable_controls', $options)) {
  120. foreach ((array) $options['disable_controls'] as $name) {
  121. $this->disableControl($name);
  122. }
  123. }
  124. if (array_key_exists('ignore_collectors', $options)) {
  125. foreach ((array) $options['ignore_collectors'] as $name) {
  126. $this->ignoreCollector($name);
  127. }
  128. }
  129. if (array_key_exists('ajax_handler_classname', $options)) {
  130. $this->setAjaxHandlerClass($options['ajax_handler_classname']);
  131. }
  132. if (array_key_exists('ajax_handler_bind_to_jquery', $options)) {
  133. $this->setBindAjaxHandlerToJquery($options['ajax_handler_bind_to_jquery']);
  134. }
  135. if (array_key_exists('open_handler_classname', $options)) {
  136. $this->setOpenHandlerClass($options['open_handler_classname']);
  137. }
  138. if (array_key_exists('open_handler_url', $options)) {
  139. $this->setOpenHandlerUrl($options['open_handler_url']);
  140. }
  141. }
  142. /**
  143. * Sets the path which assets are relative to
  144. *
  145. * @param string $path
  146. */
  147. public function setBasePath($path)
  148. {
  149. $this->basePath = $path;
  150. return $this;
  151. }
  152. /**
  153. * Returns the path which assets are relative to
  154. *
  155. * @return string
  156. */
  157. public function getBasePath()
  158. {
  159. return $this->basePath;
  160. }
  161. /**
  162. * Sets the base URL from which assets will be served
  163. *
  164. * @param string $url
  165. */
  166. public function setBaseUrl($url)
  167. {
  168. $this->baseUrl = $url;
  169. return $this;
  170. }
  171. /**
  172. * Returns the base URL from which assets will be served
  173. *
  174. * @return string
  175. */
  176. public function getBaseUrl()
  177. {
  178. return $this->baseUrl;
  179. }
  180. /**
  181. * Whether to include vendor assets
  182. *
  183. * You can only include js or css vendors using
  184. * setIncludeVendors('css') or setIncludeVendors('js')
  185. *
  186. * @param boolean $enabled
  187. */
  188. public function setIncludeVendors($enabled = true)
  189. {
  190. if (is_string($enabled)) {
  191. $enabled = array($enabled);
  192. }
  193. $this->includeVendors = $enabled;
  194. if (!$enabled || (is_array($enabled) && !in_array('js', $enabled))) {
  195. // no need to call jQuery.noConflict() if we do not include our own version
  196. $this->enableJqueryNoConflict = false;
  197. }
  198. return $this;
  199. }
  200. /**
  201. * Checks if vendors assets are included
  202. *
  203. * @return boolean
  204. */
  205. public function areVendorsIncluded()
  206. {
  207. return $this->includeVendors !== false;
  208. }
  209. /**
  210. * Disable a specific vendor's assets.
  211. *
  212. * @param string $name "jquery", "fontawesome", "highlightjs"
  213. *
  214. * @return void
  215. */
  216. public function disableVendor($name)
  217. {
  218. if (array_key_exists($name, $this->cssVendors)) {
  219. unset($this->cssVendors[$name]);
  220. }
  221. if (array_key_exists($name, $this->jsVendors)) {
  222. unset($this->jsVendors[$name]);
  223. }
  224. }
  225. /**
  226. * Sets the javascript class name
  227. *
  228. * @param string $className
  229. */
  230. public function setJavascriptClass($className)
  231. {
  232. $this->javascriptClass = $className;
  233. return $this;
  234. }
  235. /**
  236. * Returns the javascript class name
  237. *
  238. * @return string
  239. */
  240. public function getJavascriptClass()
  241. {
  242. return $this->javascriptClass;
  243. }
  244. /**
  245. * Sets the variable name of the class instance
  246. *
  247. * @param string $name
  248. */
  249. public function setVariableName($name)
  250. {
  251. $this->variableName = $name;
  252. return $this;
  253. }
  254. /**
  255. * Returns the variable name of the class instance
  256. *
  257. * @return string
  258. */
  259. public function getVariableName()
  260. {
  261. return $this->variableName;
  262. }
  263. /**
  264. * Sets what should be initialized
  265. *
  266. * - INITIALIZE_CONSTRUCTOR: only initializes the instance
  267. * - INITIALIZE_CONTROLS: initializes the controls and data mapping
  268. * - INITIALIZE_CONSTRUCTOR | INITIALIZE_CONTROLS: initialize everything (default)
  269. *
  270. * @param integer $init
  271. */
  272. public function setInitialization($init)
  273. {
  274. $this->initialization = $init;
  275. return $this;
  276. }
  277. /**
  278. * Returns what should be initialized
  279. *
  280. * @return integer
  281. */
  282. public function getInitialization()
  283. {
  284. return $this->initialization;
  285. }
  286. /**
  287. * Sets whether to call jQuery.noConflict()
  288. *
  289. * @param boolean $enabled
  290. */
  291. public function setEnableJqueryNoConflict($enabled = true)
  292. {
  293. $this->enableJqueryNoConflict = $enabled;
  294. return $this;
  295. }
  296. /**
  297. * Checks if jQuery.noConflict() will be called
  298. *
  299. * @return boolean
  300. */
  301. public function isJqueryNoConflictEnabled()
  302. {
  303. return $this->enableJqueryNoConflict;
  304. }
  305. /**
  306. * Adds a control to initialize
  307. *
  308. * Possible options:
  309. * - icon: icon name
  310. * - tooltip: string
  311. * - widget: widget class name
  312. * - title: tab title
  313. * - map: a property name from the data to map the control to
  314. * - default: a js string, default value of the data map
  315. *
  316. * "icon" or "widget" are at least needed
  317. *
  318. * @param string $name
  319. * @param array $options
  320. */
  321. public function addControl($name, array $options)
  322. {
  323. if (count(array_intersect(array_keys($options), array('icon', 'widget', 'tab', 'indicator'))) === 0) {
  324. throw new DebugBarException("Not enough options for control '$name'");
  325. }
  326. $this->controls[$name] = $options;
  327. return $this;
  328. }
  329. /**
  330. * Disables a control
  331. *
  332. * @param string $name
  333. */
  334. public function disableControl($name)
  335. {
  336. $this->controls[$name] = null;
  337. return $this;
  338. }
  339. /**
  340. * Returns the list of controls
  341. *
  342. * This does not include controls provided by collectors
  343. *
  344. * @return array
  345. */
  346. public function getControls()
  347. {
  348. return $this->controls;
  349. }
  350. /**
  351. * Ignores widgets provided by a collector
  352. *
  353. * @param string $name
  354. */
  355. public function ignoreCollector($name)
  356. {
  357. $this->ignoredCollectors[] = $name;
  358. return $this;
  359. }
  360. /**
  361. * Returns the list of ignored collectors
  362. *
  363. * @return array
  364. */
  365. public function getIgnoredCollectors()
  366. {
  367. return $this->ignoredCollectors;
  368. }
  369. /**
  370. * Sets the class name of the ajax handler
  371. *
  372. * Set to false to disable
  373. *
  374. * @param string $className
  375. */
  376. public function setAjaxHandlerClass($className)
  377. {
  378. $this->ajaxHandlerClass = $className;
  379. return $this;
  380. }
  381. /**
  382. * Returns the class name of the ajax handler
  383. *
  384. * @return string
  385. */
  386. public function getAjaxHandlerClass()
  387. {
  388. return $this->ajaxHandlerClass;
  389. }
  390. /**
  391. * Sets whether to call bindToJquery() on the ajax handler
  392. *
  393. * @param boolean $bind
  394. */
  395. public function setBindAjaxHandlerToJquery($bind = true)
  396. {
  397. $this->ajaxHandlerBindToJquery = $bind;
  398. return $this;
  399. }
  400. /**
  401. * Checks whether bindToJquery() will be called on the ajax handler
  402. *
  403. * @return boolean
  404. */
  405. public function isAjaxHandlerBoundToJquery()
  406. {
  407. return $this->ajaxHandlerBindToJquery;
  408. }
  409. /**
  410. * Sets whether to call bindToXHR() on the ajax handler
  411. *
  412. * @param boolean $bind
  413. */
  414. public function setBindAjaxHandlerToXHR($bind = true)
  415. {
  416. $this->ajaxHandlerBindToXHR = $bind;
  417. return $this;
  418. }
  419. /**
  420. * Checks whether bindToXHR() will be called on the ajax handler
  421. *
  422. * @return boolean
  423. */
  424. public function isAjaxHandlerBoundToXHR()
  425. {
  426. return $this->ajaxHandlerBindToXHR;
  427. }
  428. /**
  429. * Sets the class name of the js open handler
  430. *
  431. * @param string $className
  432. */
  433. public function setOpenHandlerClass($className)
  434. {
  435. $this->openHandlerClass = $className;
  436. return $this;
  437. }
  438. /**
  439. * Returns the class name of the js open handler
  440. *
  441. * @return string
  442. */
  443. public function getOpenHandlerClass()
  444. {
  445. return $this->openHandlerClass;
  446. }
  447. /**
  448. * Sets the url of the open handler
  449. *
  450. * @param string $url
  451. */
  452. public function setOpenHandlerUrl($url)
  453. {
  454. $this->openHandlerUrl = $url;
  455. return $this;
  456. }
  457. /**
  458. * Returns the url for the open handler
  459. *
  460. * @return string
  461. */
  462. public function getOpenHandlerUrl()
  463. {
  464. return $this->openHandlerUrl;
  465. }
  466. /**
  467. * Add assets to render in the head
  468. *
  469. * @param array $cssFiles An array of filenames
  470. * @param array $jsFiles An array of filenames
  471. * @param string $basePath Base path of those files
  472. * @param string $baseUrl Base url of those files
  473. */
  474. public function addAssets($cssFiles, $jsFiles, $basePath = null, $baseUrl = null)
  475. {
  476. $this->additionalAssets[] = array(
  477. 'base_path' => $basePath,
  478. 'base_url' => $baseUrl,
  479. 'css' => (array) $cssFiles,
  480. 'js' => (array) $jsFiles
  481. );
  482. return $this;
  483. }
  484. /**
  485. * Returns the list of asset files
  486. *
  487. * @param string $type Only return css or js files
  488. * @param string $relativeTo The type of path to which filenames must be relative (path, url or null)
  489. * @return array
  490. */
  491. public function getAssets($type = null, $relativeTo = self::RELATIVE_PATH)
  492. {
  493. $cssFiles = $this->cssFiles;
  494. $jsFiles = $this->jsFiles;
  495. if ($this->includeVendors !== false) {
  496. if ($this->includeVendors === true || in_array('css', $this->includeVendors)) {
  497. $cssFiles = array_merge($this->cssVendors, $cssFiles);
  498. }
  499. if ($this->includeVendors === true || in_array('js', $this->includeVendors)) {
  500. $jsFiles = array_merge($this->jsVendors, $jsFiles);
  501. }
  502. }
  503. if ($relativeTo) {
  504. $root = $this->getRelativeRoot($relativeTo, $this->basePath, $this->baseUrl);
  505. $cssFiles = $this->makeUriRelativeTo($cssFiles, $root);
  506. $jsFiles = $this->makeUriRelativeTo($jsFiles, $root);
  507. }
  508. $additionalAssets = $this->additionalAssets;
  509. // finds assets provided by collectors
  510. foreach ($this->debugBar->getCollectors() as $collector) {
  511. if (($collector instanceof AssetProvider) && !in_array($collector->getName(), $this->ignoredCollectors)) {
  512. $additionalAssets[] = $collector->getAssets();
  513. }
  514. }
  515. foreach ($additionalAssets as $assets) {
  516. $basePath = isset($assets['base_path']) ? $assets['base_path'] : null;
  517. $baseUrl = isset($assets['base_url']) ? $assets['base_url'] : null;
  518. $root = $this->getRelativeRoot($relativeTo,
  519. $this->makeUriRelativeTo($basePath, $this->basePath),
  520. $this->makeUriRelativeTo($baseUrl, $this->baseUrl));
  521. $cssFiles = array_merge($cssFiles, $this->makeUriRelativeTo((array) $assets['css'], $root));
  522. $jsFiles = array_merge($jsFiles, $this->makeUriRelativeTo((array) $assets['js'], $root));
  523. }
  524. return $this->filterAssetArray(array($cssFiles, $jsFiles), $type);
  525. }
  526. /**
  527. * Returns the correct base according to the type
  528. *
  529. * @param string $relativeTo
  530. * @param string $basePath
  531. * @param string $baseUrl
  532. * @return string
  533. */
  534. protected function getRelativeRoot($relativeTo, $basePath, $baseUrl)
  535. {
  536. if ($relativeTo === self::RELATIVE_PATH) {
  537. return $basePath;
  538. }
  539. if ($relativeTo === self::RELATIVE_URL) {
  540. return $baseUrl;
  541. }
  542. return null;
  543. }
  544. /**
  545. * Makes a URI relative to another
  546. *
  547. * @param string|array $uri
  548. * @param string $root
  549. * @return string
  550. */
  551. protected function makeUriRelativeTo($uri, $root)
  552. {
  553. if (!$root) {
  554. return $uri;
  555. }
  556. if (is_array($uri)) {
  557. $uris = array();
  558. foreach ($uri as $u) {
  559. $uris[] = $this->makeUriRelativeTo($u, $root);
  560. }
  561. return $uris;
  562. }
  563. if (substr($uri, 0, 1) === '/' || preg_match('/^([a-zA-Z]+:\/\/|[a-zA-Z]:\/|[a-zA-Z]:\\\)/', $uri)) {
  564. return $uri;
  565. }
  566. return rtrim($root, '/') . "/$uri";
  567. }
  568. /**
  569. * Filters a tuple of (css, js) assets according to $type
  570. *
  571. * @param array $array
  572. * @param string $type 'css', 'js' or null for both
  573. * @return array
  574. */
  575. protected function filterAssetArray($array, $type = null)
  576. {
  577. $type = strtolower($type);
  578. if ($type === 'css') {
  579. return $array[0];
  580. }
  581. if ($type === 'js') {
  582. return $array[1];
  583. }
  584. return $array;
  585. }
  586. /**
  587. * Returns a tuple where the both items are Assetic AssetCollection,
  588. * the first one being css files and the second js files
  589. *
  590. * @param string $type Only return css or js collection
  591. * @return array or \Assetic\Asset\AssetCollection
  592. */
  593. public function getAsseticCollection($type = null)
  594. {
  595. list($cssFiles, $jsFiles) = $this->getAssets();
  596. return $this->filterAssetArray(array(
  597. $this->createAsseticCollection($cssFiles),
  598. $this->createAsseticCollection($jsFiles)
  599. ), $type);
  600. }
  601. /**
  602. * Create an Assetic AssetCollection with the given files.
  603. * Filenames will be converted to absolute path using
  604. * the base path.
  605. *
  606. * @param array $files
  607. * @return \Assetic\Asset\AssetCollection
  608. */
  609. protected function createAsseticCollection($files)
  610. {
  611. $assets = array();
  612. foreach ($files as $file) {
  613. $assets[] = new \Assetic\Asset\FileAsset($file);
  614. }
  615. return new \Assetic\Asset\AssetCollection($assets);
  616. }
  617. /**
  618. * Write all CSS assets to standard output or in a file
  619. *
  620. * @param string $targetFilename
  621. */
  622. public function dumpCssAssets($targetFilename = null)
  623. {
  624. $this->dumpAssets($this->getAssets('css'), $targetFilename);
  625. }
  626. /**
  627. * Write all JS assets to standard output or in a file
  628. *
  629. * @param string $targetFilename
  630. */
  631. public function dumpJsAssets($targetFilename = null)
  632. {
  633. $this->dumpAssets($this->getAssets('js'), $targetFilename);
  634. }
  635. /**
  636. * Write assets to standard output or in a file
  637. *
  638. * @param array $files
  639. * @param string $targetFilename
  640. */
  641. protected function dumpAssets($files, $targetFilename = null)
  642. {
  643. $content = '';
  644. foreach ($files as $file) {
  645. $content .= file_get_contents($file) . "\n";
  646. }
  647. if ($targetFilename !== null) {
  648. file_put_contents($targetFilename, $content);
  649. } else {
  650. echo $content;
  651. }
  652. }
  653. /**
  654. * Renders the html to include needed assets
  655. *
  656. * Only useful if Assetic is not used
  657. *
  658. * @return string
  659. */
  660. public function renderHead()
  661. {
  662. list($cssFiles, $jsFiles) = $this->getAssets(null, self::RELATIVE_URL);
  663. $html = '';
  664. foreach ($cssFiles as $file) {
  665. $html .= sprintf('<link rel="stylesheet" type="text/css" href="%s">' . "\n", $file);
  666. }
  667. foreach ($jsFiles as $file) {
  668. $html .= sprintf('<script type="text/javascript" src="%s"></script>' . "\n", $file);
  669. }
  670. if ($this->enableJqueryNoConflict) {
  671. $html .= '<script type="text/javascript">jQuery.noConflict(true);</script>' . "\n";
  672. }
  673. return $html;
  674. }
  675. /**
  676. * Register shutdown to display the debug bar
  677. *
  678. * @param boolean $here Set position of HTML. True if is to current position or false for end file
  679. * @param boolean $initialize Whether to render the de bug bar initialization code
  680. * @return string Return "{--DEBUGBAR_OB_START_REPLACE_ME--}" or return an empty string if $here == false
  681. */
  682. public function renderOnShutdown($here = true, $initialize = true, $renderStackedData = true, $head = false)
  683. {
  684. register_shutdown_function(array($this, "replaceTagInBuffer"), $here, $initialize, $renderStackedData, $head);
  685. if (ob_get_level() === 0) {
  686. ob_start();
  687. }
  688. return ($here) ? self::REPLACEABLE_TAG : "";
  689. }
  690. /**
  691. * Same as renderOnShutdown() with $head = true
  692. *
  693. * @param boolean $here
  694. * @param boolean $initialize
  695. * @param boolean $renderStackedData
  696. * @return string
  697. */
  698. public function renderOnShutdownWithHead($here = true, $initialize = true, $renderStackedData = true)
  699. {
  700. return $this->renderOnShutdown($here, $initialize, $renderStackedData, true);
  701. }
  702. /**
  703. * Is callback function for register_shutdown_function(...)
  704. *
  705. * @param boolean $here Set position of HTML. True if is to current position or false for end file
  706. * @param boolean $initialize Whether to render the de bug bar initialization code
  707. */
  708. public function replaceTagInBuffer($here = true, $initialize = true, $renderStackedData = true, $head = false)
  709. {
  710. $render = ($head ? $this->renderHead() : "")
  711. . $this->render($initialize, $renderStackedData);
  712. $current = ($here && ob_get_level() > 0) ? ob_get_clean() : self::REPLACEABLE_TAG;
  713. echo str_replace(self::REPLACEABLE_TAG, $render, $current, $count);
  714. if ($count === 0) {
  715. echo $render;
  716. }
  717. }
  718. /**
  719. * Returns the code needed to display the debug bar
  720. *
  721. * AJAX request should not render the initialization code.
  722. *
  723. * @param boolean $initialize Whether to render the de bug bar initialization code
  724. * @return string
  725. */
  726. public function render($initialize = true, $renderStackedData = true)
  727. {
  728. $js = '';
  729. if ($initialize) {
  730. $js = $this->getJsInitializationCode();
  731. }
  732. if ($renderStackedData && $this->debugBar->hasStackedData()) {
  733. foreach ($this->debugBar->getStackedData() as $id => $data) {
  734. $js .= $this->getAddDatasetCode($id, $data, '(stacked)');
  735. }
  736. }
  737. $suffix = !$initialize ? '(ajax)' : null;
  738. $js .= $this->getAddDatasetCode($this->debugBar->getCurrentRequestId(), $this->debugBar->getData(), $suffix);
  739. return "<script type=\"text/javascript\">\n$js\n</script>\n";
  740. }
  741. /**
  742. * Returns the js code needed to initialize the debug bar
  743. *
  744. * @return string
  745. */
  746. protected function getJsInitializationCode()
  747. {
  748. $js = '';
  749. if (($this->initialization & self::INITIALIZE_CONSTRUCTOR) === self::INITIALIZE_CONSTRUCTOR) {
  750. $js .= sprintf("var %s = new %s();\n", $this->variableName, $this->javascriptClass);
  751. }
  752. if (($this->initialization & self::INITIALIZE_CONTROLS) === self::INITIALIZE_CONTROLS) {
  753. $js .= $this->getJsControlsDefinitionCode($this->variableName);
  754. }
  755. if ($this->ajaxHandlerClass) {
  756. $js .= sprintf("%s.ajaxHandler = new %s(%s);\n", $this->variableName, $this->ajaxHandlerClass, $this->variableName);
  757. if ($this->ajaxHandlerBindToXHR) {
  758. $js .= sprintf("%s.ajaxHandler.bindToXHR();\n", $this->variableName);
  759. } elseif ($this->ajaxHandlerBindToJquery) {
  760. $js .= sprintf("if (jQuery) %s.ajaxHandler.bindToJquery(jQuery);\n", $this->variableName);
  761. }
  762. }
  763. if ($this->openHandlerUrl !== null) {
  764. $js .= sprintf("%s.setOpenHandler(new %s(%s));\n", $this->variableName,
  765. $this->openHandlerClass,
  766. json_encode(array("url" => $this->openHandlerUrl)));
  767. }
  768. return $js;
  769. }
  770. /**
  771. * Returns the js code needed to initialized the controls and data mapping of the debug bar
  772. *
  773. * Controls can be defined by collectors themselves or using {@see addControl()}
  774. *
  775. * @param string $varname Debug bar's variable name
  776. * @return string
  777. */
  778. protected function getJsControlsDefinitionCode($varname)
  779. {
  780. $js = '';
  781. $dataMap = array();
  782. $excludedOptions = array('indicator', 'tab', 'map', 'default', 'widget', 'position');
  783. // finds controls provided by collectors
  784. $widgets = array();
  785. foreach ($this->debugBar->getCollectors() as $collector) {
  786. if (($collector instanceof Renderable) && !in_array($collector->getName(), $this->ignoredCollectors)) {
  787. if ($w = $collector->getWidgets()) {
  788. $widgets = array_merge($widgets, $w);
  789. }
  790. }
  791. }
  792. $controls = array_merge($widgets, $this->controls);
  793. foreach (array_filter($controls) as $name => $options) {
  794. $opts = array_diff_key($options, array_flip($excludedOptions));
  795. if (isset($options['tab']) || isset($options['widget'])) {
  796. if (!isset($opts['title'])) {
  797. $opts['title'] = ucfirst(str_replace('_', ' ', $name));
  798. }
  799. $js .= sprintf("%s.addTab(\"%s\", new %s({%s%s}));\n",
  800. $varname,
  801. $name,
  802. isset($options['tab']) ? $options['tab'] : 'PhpDebugBar.DebugBar.Tab',
  803. substr(json_encode($opts, JSON_FORCE_OBJECT), 1, -1),
  804. isset($options['widget']) ? sprintf('%s"widget": new %s()', count($opts) ? ', ' : '', $options['widget']) : ''
  805. );
  806. } elseif (isset($options['indicator']) || isset($options['icon'])) {
  807. $js .= sprintf("%s.addIndicator(\"%s\", new %s(%s), \"%s\");\n",
  808. $varname,
  809. $name,
  810. isset($options['indicator']) ? $options['indicator'] : 'PhpDebugBar.DebugBar.Indicator',
  811. json_encode($opts, JSON_FORCE_OBJECT),
  812. isset($options['position']) ? $options['position'] : 'right'
  813. );
  814. }
  815. if (isset($options['map']) && isset($options['default'])) {
  816. $dataMap[$name] = array($options['map'], $options['default']);
  817. }
  818. }
  819. // creates the data mapping object
  820. $mapJson = array();
  821. foreach ($dataMap as $name => $values) {
  822. $mapJson[] = sprintf('"%s": ["%s", %s]', $name, $values[0], $values[1]);
  823. }
  824. $js .= sprintf("%s.setDataMap({\n%s\n});\n", $varname, implode(",\n", $mapJson));
  825. // activate state restoration
  826. $js .= sprintf("%s.restoreState();\n", $varname);
  827. return $js;
  828. }
  829. /**
  830. * Returns the js code needed to add a dataset
  831. *
  832. * @param string $requestId
  833. * @param array $data
  834. * @return string
  835. */
  836. protected function getAddDatasetCode($requestId, $data, $suffix = null)
  837. {
  838. $js = sprintf("%s.addDataSet(%s, \"%s\"%s);\n",
  839. $this->variableName,
  840. json_encode($data),
  841. $requestId,
  842. $suffix ? ", " . json_encode($suffix) : ''
  843. );
  844. return $js;
  845. }
  846. }