Skip to content

Commit

Permalink
Add custom method name
Browse files Browse the repository at this point in the history
  • Loading branch information
guanguans committed Jul 11, 2020
1 parent f2828d4 commit 701735b
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions src/ServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@ class ServiceProvider extends \Illuminate\Support\ServiceProvider
*/
public function boot()
{
$this->setupConfig();

/**
* Register the `toRawSql` macro.
*/
$this->registerBuilderMacro('toRawSql', function ($macro) {
$this->registerBuilderMacro(config('rawsql.to_raw_sql', 'toRawSql'), function ($macro) {
QueryBuilder::macro($macro, function () {
return array_reduce($this->getBindings(), function ($sql, $binding) {
return preg_replace('/\?/', is_numeric($binding) ? $binding : "'".$binding."'", $sql, 1);
Expand All @@ -36,18 +38,18 @@ public function boot()
/**
* Register the `dumpRawSql` macro.
*/
$this->registerBuilderMacro('dumpRawSql', function ($macro) {
$this->registerBuilderMacro(config('rawsql.dump_raw_sql', 'dumpRawSql'), function ($macro) {
QueryBuilder::macro($macro, function () {
dump($this->toRawSql());
dump($this->{config('rawsql.to_raw_sql', 'toRawSql')}());
});
});

/**
* Register the `ddRawSql` macro.
*/
$this->registerBuilderMacro('ddRawSql', function ($macro) {
$this->registerBuilderMacro(config('rawsql.dd_raw_sql', 'ddRawSql'), function ($macro) {
QueryBuilder::macro($macro, function () {
dd($this->toRawSql());
dd($this->{config('rawsql.to_raw_sql', 'toRawSql')}());
});
});
}
Expand Down Expand Up @@ -78,6 +80,10 @@ protected function registerBuilderMacro($macro, Closure $closure)
throw new InvalidArgumentException('Macro name must be a string');
}

if (method_exists(app(QueryBuilder::class), $macro)) {
throw new InvalidArgumentException(sprintf('`Illuminate\Database\Query\Builder` already exists method.:%s', $macro));
}

$closure($macro);

$this->registerEloquentBuilderMacro($macro);
Expand Down

0 comments on commit 701735b

Please sign in to comment.