Skip to content

Commit 800c3c6

Browse files
committed
added replaceBindings method
1 parent dcb6aee commit 800c3c6

File tree

3 files changed

+41
-12
lines changed

3 files changed

+41
-12
lines changed

README.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,17 @@ User::select('name')
9797
// []
9898
```
9999

100+
#### Listen and replace bindings for all queries
101+
```php
102+
use LaraToolbox\QueryViewer\QueryViewer;
103+
104+
\DB::listen(function ($query) {
105+
logger()->info(
106+
QueryViewer::replaceBindings($query->sql, $query->bindings)
107+
);
108+
});
109+
```
110+
100111
## Testing
101112

102113
``` bash
@@ -119,7 +130,6 @@ If you discover any security related issues, please email instead of using the i
119130
- This package is bootstrapped with the help of [melihovv/laravel-package-generator](https://github.com/melihovv/laravel-package-generator).
120131
- Social image generated by [banners.beyondco.de](https://banners.beyondco.de/).
121132

122-
123133
## License
124134

125135
The MIT License (MIT). Please see [License File](LICENSE) for more information.

src/QueryBuilderMixin.php

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,21 +7,15 @@ class QueryBuilderMixin
77
/**
88
* Returns sql query with binding replaced!
99
*
10-
* Originally Taken from: https://gist.github.com/JesseObrien/7418983
11-
*
1210
* @return string
1311
*/
1412
public function getSql()
1513
{
1614
return function () {
17-
$sql = $this->toSql();
18-
19-
foreach ($this->getBindings() as $binding) {
20-
$value = is_numeric($binding) ? $binding : "'".$binding."'";
21-
$sql = preg_replace('/\?/', $value, $sql, 1);
22-
}
23-
24-
return $sql;
15+
return QueryViewer::replaceBindings(
16+
$this->toSql(),
17+
$this->getBindings()
18+
);
2519
};
2620
}
2721

@@ -48,7 +42,7 @@ public function dumpSql()
4842
public function logSql($prefix = null)
4943
{
5044
return function ($prefix) {
51-
logger()->{config('query-viewer.log_type')}($prefix. ' : '.$this->getSql());
45+
logger()->{config('query-viewer.log_type')}($prefix.' : '.$this->getSql());
5246

5347
return $this;
5448
};

src/QueryViewer.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?php
2+
3+
namespace LaraToolbox\QueryViewer;
4+
5+
class QueryViewer
6+
{
7+
/**
8+
* Replaces question marks with bindings in given sql.
9+
*
10+
* Originally Taken from: https://gist.github.com/JesseObrien/7418983
11+
*
12+
* @param string $sql
13+
* @param array $bindings
14+
* @return string
15+
*/
16+
public static function replaceBindings(string $sql, array $bindings)
17+
{
18+
foreach ($bindings as $binding) {
19+
$value = is_numeric($binding) ? $binding : "'".$binding."'";
20+
$sql = preg_replace('/\?/', $value, $sql, 1);
21+
}
22+
23+
return $sql;
24+
}
25+
}

0 commit comments

Comments
 (0)