Skip to content

Commit dd2f545

Browse files
author
Andrey Helldar
committed
Added Dumper::ddSql() method
1 parent b75a24e commit dd2f545

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

Diff for: src/Facades/Dumper.php

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
3+
namespace Helldar\LaravelSupport\Facades;
4+
5+
use Helldar\LaravelSupport\Support\Dumper as Support;
6+
use Illuminate\Support\Facades\Facade;
7+
8+
/**
9+
* @method static void|string|array ddSql($query, bool $is_short = false, bool $is_return = false)
10+
*/
11+
class Dumper extends Facade
12+
{
13+
protected static function getFacadeAccessor()
14+
{
15+
return Support::class;
16+
}
17+
}

Diff for: src/Support/Dumper.php

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<?php
2+
3+
namespace Helldar\LaravelSupport\Support;
4+
5+
use Illuminate\Database\Eloquent\Builder;
6+
use Illuminate\Database\Query\Builder as QueryBuilder;
7+
8+
class Dumper
9+
{
10+
/**
11+
* Dump the passed variables and end the script.
12+
*
13+
* @see https://gist.github.com/Ellrion/561fc48894a87b853917e0a5cec83181#file-helper-php
14+
*
15+
* @param $query
16+
* @param bool $is_short
17+
* @param bool $is_return
18+
*
19+
* @return array|string
20+
*/
21+
public function ddSql($query, bool $is_short = false, bool $is_return = false)
22+
{
23+
$query = $this->prepareQuery($query);
24+
25+
$sql = $query->toSql();
26+
27+
$bindings = $this->getBindings($query);
28+
29+
$raw = $this->getRaw($sql, $bindings);
30+
31+
$data = $this->getData($is_short, $sql, $query->getRawBindings(), $raw);
32+
33+
if ($is_return) {
34+
return $data;
35+
}
36+
37+
dd($data);
38+
}
39+
40+
protected function prepareQuery($query): QueryBuilder
41+
{
42+
return $query instanceof Builder ? $query->getQuery() : $query;
43+
}
44+
45+
protected function getBindings(QueryBuilder $builder): array
46+
{
47+
return array_map(function ($binding) {
48+
return is_numeric($binding) ? $binding : "'{$binding}'";
49+
}, $builder->getBindings());
50+
}
51+
52+
protected function getData(bool $is_short, string $sql, array $bindings, string $raw)
53+
{
54+
return $is_short ? $raw : compact('sql', 'bindings', 'raw');
55+
}
56+
57+
protected function getRaw(string $sql, array $bindings): string
58+
{
59+
return vsprintf(str_replace(['%', '?'], ['%%', '%s'], $sql), $bindings);
60+
}
61+
}

0 commit comments

Comments
 (0)