Completed
Pull Request — master (#40)
by
unknown
01:24
created

listenQueryEvents()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 27

Duplication

Lines 27
Ratio 100 %

Importance

Changes 0
Metric Value
dl 27
loc 27
rs 9.488
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
namespace Understand\UnderstandLaravel5;
4
5
use Exception;
6
use Illuminate\Foundation\AliasLoader;
7
use Illuminate\Support\Str;
8
use Understand\UnderstandLaravel5\Handlers\MonologHandler;
9
use UnderstandMonolog\Handler\UnderstandAsyncHandler;
10
use UnderstandMonolog\Handler\UnderstandSyncHandler;
11
12
class UnderstandLumenServiceProvider extends UnderstandServiceProvider
13
{
14
    /**
15
     * Bootstrap the application events.
16
     *
17
     * @return void
18
     */
19
    public function boot()
20
    {
21
        $this->app->configure('understand-laravel');
0 ignored issues
show
Bug introduced by
The method configure() does not exist on Illuminate\Contracts\Foundation\Application. Did you maybe mean registerConfiguredProviders()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
22
23
        $enabled = $this->app['config']->get('understand-laravel.enabled');
24
25
        if ($enabled)
26
        {
27
            $this->listenLumenEvents();
28
        }
29
30
        if ($enabled && $this->app['config']->get('understand-laravel.sql_enabled'))
31
        {
32
            $this->listenQueryEvents();
33
        }
34
    }
35
36
    /**
37
     * Register bindings in the container.
38
     *
39
     * @return void
40
     */
41
    public function register()
42
    {
43
        $this->registerConfig();
44
        $this->registerFieldProvider();
45
        $this->registerDataCollector();
46
        $this->registerTokenProvider();
47
        $this->registerLogger();
48
        $this->registerExceptionEncoder();
49
        $this->registerEventLoggers();
50
    }
51
52
    /**
53
     * Register field provider
54
     *
55
     * @return void
56
     */
57
    protected function registerFieldProvider()
58
    {
59 View Code Duplication
        $this->app->bind('understand.fieldProvider', function($app)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
60
        {
61
            $fieldProvider = new FieldProvider();
62
63
            if ($app['config']['session.driver'])
64
            {
65
                $fieldProvider->setSessionStore($app['session.store']);
66
            }
67
68
            // router is available only from Lumen 5.5
69
            if (array_has($app->availableBindings, 'router'))
70
            {
71
                $fieldProvider->setRouter($app['router']);
72
            }
73
74
            $fieldProvider->setRequest($app['request']);
75
            $fieldProvider->setEnvironment($app->environment());
76
            $fieldProvider->setTokenProvider($app['understand.tokenProvider']);
77
            $fieldProvider->setDataCollector($app['understand.dataCollector']);
78
            $fieldProvider->setApp($app);
79
80
            return $fieldProvider;
81
        });
82
83
        if (! class_exists('UnderstandFieldProvider'))
84
        {
85
            class_alias('Understand\UnderstandLaravel5\Facades\UnderstandFieldProvider', 'UnderstandFieldProvider');
86
        }
87
    }
88
89
    /**
90
     * Register exception and event logger
91
     *
92
     * @return void
93
     */
94
    protected function registerEventLoggers()
95
    {
96
        parent::registerEventLoggers();
97
98
        if (! class_exists('UnderstandExceptionLogger'))
99
        {
100
            class_alias('Understand\UnderstandLaravel5\Facades\UnderstandExceptionLogger', 'UnderstandExceptionLogger');
101
        }
102
    }
103
104
    /**
105
     * Register understand logger
106
     *
107
     * @return void
108
     */
109
    protected function registerLogger()
110
    {
111
        parent::registerLogger();
112
113
        if (! class_exists('UnderstandLogger'))
114
        {
115
            class_alias('Understand\UnderstandLaravel5\Facades\UnderstandLogger', 'UnderstandLogger');
116
        }
117
    }
118
119
    /**
120
     * Register monolog handler
121
     *
122
     * @return void
123
     */
124
    protected function registerMonologHandler()
125
    {
126
        $this->app['Psr\Log\LoggerInterface']->pushHandler(new MonologHandler());
127
    }
128
129
    /**
130
     * Detect Lumen version
131
     *
132
     * @param array $versions
133
     * @return type
134
     */
135
    protected function detectLumenVersion(array $versions)
136
    {
137
        $re = '/Lumen \((.*)\) \(.*\)/m';
138
139
        $version = $this->app->version();
140
141
        preg_match($re, $version, $matches);
142
143
        return Str::startsWith($matches[1], $versions);
144
    }
145
146
    /**
147
     * Listen Laravel logs and queue events
148
     *
149
     * @return void
150
     */
151
    protected function listenLumenEvents()
152
    {
153
        // Lumen < 5.6 uses Monolog, so we need to manually raise event
154
        if ($this->detectLumenVersion(['5.0', '5.1', '5.2', '5.3', '5.4', '5.5']))
155
        {
156
            $this->registerMonologHandler();
157
158
            // the illuminate.log event is raised
159
            // by our MonologHandler, not by Lumen
160
            $this->app['events']->listen('illuminate.log', function ($log)
161
            {
162
                $this->handleEvent($log['level'], $log['message'], $log['context']);
163
            });
164
        }
165 View Code Duplication
        else
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
166
        {
167
            // starting from Lumen 5.6 MessageLogged event class was introduced
168
            $this->app['events']->listen('Illuminate\Log\Events\MessageLogged', function ($log)
169
            {
170
                $this->handleEvent($log->level, $log->message, $log->context);
171
            });
172
        }
173
174
        // starting from L5.2 JobProcessing event class was introduced
175
        // https://github.com/illuminate/queue/commit/ce2b5518902b1bcb9ef650c41900fc8c6392eb0c
176 View Code Duplication
        if ($this->app->runningInConsole()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
177
            if ($this->detectLumenVersion(['5.0', '5.1'])) {
178
                $this->app['events']->listen('illuminate.queue.after', function () {
179
                    $this->app['understand.tokenProvider']->generate();
180
                    $this->app['understand.dataCollector']->reset();
181
                });
182
183
                $this->app['events']->listen('illuminate.queue.failed', function () {
184
                    $this->app['understand.tokenProvider']->generate();
185
                    $this->app['understand.dataCollector']->reset();
186
                });
187
            } else {
188
                $this->app['events']->listen('Illuminate\Queue\Events\JobProcessing', function () {
189
                    $this->app['understand.tokenProvider']->generate();
190
                    $this->app['understand.dataCollector']->reset();
191
                });
192
            }
193
        }
194
    }
195
196
    /**
197
     * Listen Query events
198
     *
199
     * @return void
200
     */
201 View Code Duplication
    protected function listenQueryEvents()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
202
    {
203
        // only Lumen versions below L5.2 supports `illuminate.query`
204
        if ($this->detectLumenVersion(['5.0', '5.1']))
205
        {
206
            $this->app['events']->listen('illuminate.query', function($query, $bindings, $time)
207
            {
208
                $this->app['understand.dataCollector']->setInArray('sql_queries', [
209
                    'query' => $query,
210
                    'bindings' => $bindings,
211
                    'time' => $time,
212
                ]);
213
            });
214
        }
215
        else
216
        {
217
            // https://laravel.com/api/5.3/Illuminate/Database/Events/QueryExecuted.html
218
            $this->app['events']->listen('Illuminate\Database\Events\QueryExecuted', function($event)
219
            {
220
                $this->app['understand.dataCollector']->setInArray('sql_queries', [
221
                    'query' => $event->sql,
222
                    'bindings' => $event->bindings,
223
                    'time' => $event->time,
224
                ]);
225
            });
226
        }
227
    }
228
229
    /**
230
     * Handle a new log event
231
     *
232
     * @param string $level
233
     * @param mixed $message
234
     * @param array $context
235
     * @return void
236
     */
237
    protected function handleEvent($level, $message, $context)
238
    {
239
        if ($this->shouldIgnoreEvent($level, $message, $context))
240
        {
241
            return;
242
        }
243
244
        // `\Log::info`, `\Log::debug` and NOT `\Exception` or `\Throwable`
245
        if (in_array($level, ['info', 'debug']) && ! ($message instanceof Exception || $message instanceof Throwable))
0 ignored issues
show
Bug introduced by
The class Understand\UnderstandLaravel5\Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
246
        {
247
            $this->app['understand.eventLogger']->logEvent($level, $message, $context);
248
        }
249
        // `\Log::notice`, `\Log::warning`, `\Log::error`, `\Log::critical`, `\Log::alert`, `\Log::emergency` and `\Exception`, `\Throwable`
250
        else if (isset($context['exception']) && ($context['exception'] instanceof Exception || $context['exception'] instanceof Throwable))
0 ignored issues
show
Bug introduced by
The class Understand\UnderstandLaravel5\Throwable does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
251
        {
252
            $exception = $context['exception'];
253
            unset($context['exception']);
254
255
            $this->app['understand.exceptionLogger']->logError($level, $exception, $context);
256
        }
257
        else
258
        {
259
            $this->app['understand.exceptionLogger']->logError($level, $message, $context);
260
        }
261
    }
262
}