ServiceProvider::boot()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 12
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 23
rs 9.8666
1
<?php
2
3
namespace Sulao\RawSql;
4
5
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
6
use Illuminate\Database\Query\Builder as QueryBuilder;
7
8
/**
9
 * Class ServiceProvider
10
 *
11
 * @package Sulao\RawSql
12
 */
13
class ServiceProvider extends \Illuminate\Support\ServiceProvider
14
{
15
    /**
16
     * Bootstrap any application services.
17
     *
18
     * @return void
19
     */
20
    public function boot()
21
    {
22
        QueryBuilder::macro('toRawSql', function () {
23
            /**
24
             * @var $this QueryBuilder
25
             */
26
            $sql = $this->toSql();
27
            $bindings = $this->getBindings();
28
            $bindings = $this->getConnection()->prepareBindings($bindings);
29
            $bindings = array_map(function ($binding) {
30
                return is_numeric($binding)
31
                    ? $binding
32
                    : "'" . addslashes($binding) . "'";
33
            }, $bindings);
34
35
            return sprintf(str_replace('?', '%s', $sql), ...$bindings);
36
        });
37
38
        EloquentBuilder::macro('toRawSql', function () {
39
            /**
40
             * @var $this EloquentBuilder
41
             */
42
            return $this->toBase()->toRawSql();
43
        });
44
    }
45
}
46