1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Mnabialek\LaravelSqlLogger\Providers; |
4
|
|
|
|
5
|
|
|
use Mnabialek\LaravelSqlLogger\Config; |
6
|
|
|
use Mnabialek\LaravelSqlLogger\SqlLogger; |
7
|
|
|
|
8
|
|
|
class ServiceProvider extends \Illuminate\Support\ServiceProvider |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var Config |
12
|
|
|
*/ |
13
|
|
|
protected $config; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* {@inheritdoc} |
17
|
|
|
*/ |
18
|
|
|
public function __construct($app) |
19
|
|
|
{ |
20
|
|
|
parent::__construct($app); |
21
|
|
|
$this->config = $this->app->make(Config::class); |
22
|
|
|
} |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* {@inheritdoc} |
26
|
|
|
*/ |
27
|
|
|
public function register() |
28
|
|
|
{ |
29
|
|
|
// merge config |
30
|
|
|
$this->mergeConfigFrom($this->configFileLocation(), 'sql_logger'); |
31
|
|
|
|
32
|
|
|
// register files to be published |
33
|
|
|
$this->publishes($this->getPublished()); |
34
|
|
|
|
35
|
|
|
// if no logging is enabled, we can stop here, nothing more should be done |
36
|
|
|
if (! $this->shouldLogAnything()) { |
37
|
|
|
return; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
// create logger class |
41
|
|
|
$logger = $this->app->make(SqlLogger::class); |
42
|
|
|
|
43
|
|
|
// listen to database queries |
44
|
|
|
$this->app['db']->listen($this->getListenClosure($logger)); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Get files to be published. |
49
|
|
|
* |
50
|
|
|
* @return array |
51
|
|
|
*/ |
52
|
|
|
protected function getPublished() |
53
|
|
|
{ |
54
|
|
|
return [ |
55
|
|
|
$this->configFileLocation() => (function_exists('config_path') ? |
56
|
|
|
config_path('sql_logger.php') : |
57
|
|
|
base_path('config/sql_logger.php')), |
58
|
|
|
]; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Verify whether anything should be logged. |
63
|
|
|
* |
64
|
|
|
* @return bool |
65
|
|
|
*/ |
66
|
|
|
protected function shouldLogAnything() |
67
|
|
|
{ |
68
|
|
|
return $this->config->logQueries() || $this->config->logSlowQueries(); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* Get config file location. |
73
|
|
|
* |
74
|
|
|
* @return bool|string |
75
|
|
|
*/ |
76
|
|
|
protected function configFileLocation() |
77
|
|
|
{ |
78
|
|
|
return realpath(__DIR__ . '/../../publish/config/sql_logger.php'); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
/** |
82
|
|
|
* Get closure that will be used for listening executed database queries. |
83
|
|
|
* |
84
|
|
|
* @param SqlLogger $logger |
85
|
|
|
* |
86
|
|
|
* @return \Closure |
87
|
|
|
*/ |
88
|
|
|
protected function getListenClosure(SqlLogger $logger) |
89
|
|
|
{ |
90
|
|
|
return function ($query, $bindings = null, $time = null) use ($logger) { |
91
|
|
|
$logger->log($query, $bindings, $time); |
92
|
|
|
}; |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|