profiler.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php namespace Laravel\Profiling;
  2. use Laravel\View;
  3. use Laravel\File;
  4. use Laravel\Event;
  5. use Laravel\Config;
  6. use Laravel\Request;
  7. class Profiler {
  8. /**
  9. * An array of the recorded Profiler data.
  10. *
  11. * @var array
  12. */
  13. protected static $data = array('queries' => array(), 'logs' => array());
  14. /**
  15. * Get the rendered contents of the Profiler.
  16. *
  17. * @param Response $response
  18. * @return string
  19. */
  20. public static function render($response)
  21. {
  22. // We only want to send the profiler toolbar if the request is not an AJAX
  23. // request, as sending it on AJAX requests could mess up JSON driven API
  24. // type applications, so we will not send anything in those scenarios.
  25. if ( ! Request::ajax())
  26. {
  27. return render('path: '.__DIR__.'/template'.BLADE_EXT, static::$data);
  28. }
  29. }
  30. /**
  31. * Add a log entry to the log entries array.
  32. *
  33. * @return void
  34. */
  35. public static function log($type, $message)
  36. {
  37. static::$data['logs'][] = array($type, $message);
  38. }
  39. /**
  40. * Add a performed SQL query to the Profiler.
  41. *
  42. * @param string $sql
  43. * @param array $bindings
  44. * @param float $time
  45. * @return void
  46. */
  47. public static function query($sql, $bindings, $time)
  48. {
  49. foreach ($bindings as $binding)
  50. {
  51. $sql = preg_replace('/\?/', $binding, $sql, 1);
  52. }
  53. static::$data['queries'][] = array($sql, $time);
  54. }
  55. /**
  56. * Attach the Profiler's event listeners.
  57. *
  58. * @return void
  59. */
  60. public static function attach()
  61. {
  62. // First we'll attach to the query and log events. These allow us to catch
  63. // all of the SQL queries and log messages that come through Laravel,
  64. // and we will pass them onto the Profiler for simple storage.
  65. Event::listen('laravel.log', function($type, $message)
  66. {
  67. Profiler::log($type, $message);
  68. });
  69. Event::listen('laravel.query', function($sql, $bindings, $time)
  70. {
  71. Profiler::query($sql, $bindings, $time);
  72. });
  73. // We'll attach the profiler to the "done" event so that we can easily
  74. // attach the profiler output to the end of the output sent to the
  75. // browser. This will display the profiler's nice toolbar.
  76. Event::listen('laravel.done', function($response)
  77. {
  78. echo Profiler::render($response);
  79. });
  80. }
  81. }