profiler.php 2.14 KB
Newer Older
Taylor Otwell committed
1 2 3 4 5 6
<?php namespace Laravel\Profiling;

use Laravel\View;
use Laravel\File;
use Laravel\Event;
use Laravel\Config;
7
use Laravel\Request;
Taylor Otwell committed
8 9 10 11 12 13 14 15 16 17 18 19 20

class Profiler {

	/**
	 * An array of the recorded Profiler data.
	 *
	 * @var array
	 */
	protected static $data = array('queries' => array(), 'logs' => array());

	/**
	 * Get the rendered contents of the Profiler.
	 *
Taylor Otwell committed
21
	 * @param  Response  $response
Taylor Otwell committed
22 23
	 * @return string
	 */
Taylor Otwell committed
24
	public static function render($response)
Taylor Otwell committed
25
	{
Taylor Otwell committed
26 27 28
		// We only want to send the profiler toolbar if the request is not an AJAX
		// request, as sending it on AJAX requests could mess up JSON driven API
		// type applications, so we will not send anything in those scenarios.
29 30 31 32
		if ( ! Request::ajax())
		{
			return render('path: '.__DIR__.'/template'.BLADE_EXT, static::$data);
		}
Taylor Otwell committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
	}

	/**
	 * Add a log entry to the log entries array.
	 *
	 * @return void
	 */
	public static function log($type, $message)
	{
		static::$data['logs'][] = array($type, $message);
	}

	/**
	 * Add a performed SQL query to the Profiler.
	 *
	 * @param 	string 	$sql
	 * @param 	array 	$bindings
	 * @param 	float 	$time
	 * @return 	void
	 */
	public static function query($sql, $bindings, $time)
	{
		foreach ($bindings as $binding)
		{
			$sql = preg_replace('/\?/', $binding, $sql, 1);
		}

		static::$data['queries'][] = array($sql, $time);
	}

	/**
	 * Attach the Profiler's event listeners.
	 *
	 * @return void
	 */
	public static function attach()
	{
		// First we'll attach to the query and log events. These allow us to catch
		// all of the SQL queries and log messages that come through Laravel,
		// and we will pass them onto the Profiler for simple storage.
		Event::listen('laravel.log', function($type, $message)
		{
			Profiler::log($type, $message);
		});

		Event::listen('laravel.query', function($sql, $bindings, $time)
		{
			Profiler::query($sql, $bindings, $time);			
		});

		// We'll attach the profiler to the "done" event so that we can easily
		// attach the profiler output to the end of the output sent to the
		// browser. This will display the profiler's nice toolbar.
86
		Event::listen('laravel.done', function($response)
Taylor Otwell committed
87
		{
Taylor Otwell committed
88
			echo Profiler::render($response);
Taylor Otwell committed
89 90 91 92
		});
	}

}