|
| 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