Completed
Push — master ( 925ecf...691399 )
by Aivis
08:17 queued 02:32
created

FieldProvider::getArtisanCommandName()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 3
nc 2
nop 0
1
<?php namespace Understand\UnderstandLaravel5;
2
3
use Understand\UnderstandLaravel5\UniqueProcessIdentifier;
4
use \Illuminate\Session\Store AS SessionStore;
5
use \Illuminate\Routing\Router;
6
use Illuminate\Http\Request;
7
use Illuminate\Foundation\Application;
8
9
class FieldProvider
10
{
11
12
    /**
13
     * The registered field providers.
14
     *
15
     * @var array
16
     */
17
    protected $providers = [];
18
19
    /**
20
     * Default field
21
     *
22
     * @var array
23
     */
24
    protected $defaultProviders = [
25
        'getSessionId',
26
        'getRouteName',
27
        'getUrl',
28
        'getRequestMethod',
29
        'getServerIp',
30
        'getClientIp',
31
        'getClientUserAgent',
32
        'getEnvironment',
33
        'getFromSession',
34
        'getProcessIdentifier',
35
        'getUserId',
36
        'getGroupId',
37
        'getLaravelVersion',
38
        'getSqlQueries',
39
        'getArtisanCommandName',
40
        'getRunningInConsole',
41
        'getLoggerVersion',
42
    ];
43
44
    /**
45
     * Session store
46
     *
47
     * @var \Illuminate\Session\Store
48
     */
49
    protected $session;
50
51
    /**
52
     * Router
53
     *
54
     * @var Router
55
     */
56
    protected $router;
57
58
    /**
59
     * Server variable
60
     *
61
     * @var Request
62
     */
63
    protected $request;
64
65
    /**
66
     * Token provider
67
     *
68
     * @var UniqueProcessIdentifier
69
     */
70
    protected $tokenProvider;
71
72
    /**
73
     * Current environment
74
     *
75
     * @var string
76
     */
77
    protected $environment;
78
79
    /**
80
     * @var DataCollector
81
     */
82
    protected $dataCollector;
83
84
    /**
85
     * @var Application
86
     */
87
    protected $app;
88
89
    /**
90
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
91
     */
92
    public function __construct()
93
    {
94
        foreach ($this->defaultProviders as $defaultProviderName)
95
        {
96
            $this->extend($defaultProviderName, [$this, $defaultProviderName]);
97
        }
98
    }
99
100
    /**
101
     * @param Application $app
102
     */
103
    public function setApp(Application $app)
104
    {
105
        $this->app = $app;
106
    }
107
108
    /**
109
     * Set session store
110
     *
111
     * @param type $service
112
     */
113
    public function setSessionStore(SessionStore $service)
114
    {
115
        $this->session = $service;
116
    }
117
118
    /**
119
     * Set router
120
     *
121
     * @param Router $router
122
     */
123
    public function setRouter(Router $router)
124
    {
125
        $this->router = $router;
126
    }
127
128
    /**
129
     * Set request
130
     *
131
     * @param Request $request
132
     */
133
    public function setRequest(Request $request)
0 ignored issues
show
Bug introduced by
You have injected the Request via parameter $request. This is generally not recommended as there might be multiple instances during a request cycle (f.e. when using sub-requests). Instead, it is recommended to inject the RequestStack and retrieve the current request each time you need it via getCurrentRequest().
Loading history...
134
    {
135
        $this->request = $request;
136
    }
137
138
    /**
139
     * Set current environment
140
     *
141
     * @param string $environment
142
     */
143
    public function setEnvironment($environment)
144
    {
145
        $this->environment = $environment;
146
    }
147
148
    /**
149
     * @param DataCollector $dataCollector
150
     */
151
    public function setDataCollector(DataCollector $dataCollector)
152
    {
153
        $this->dataCollector = $dataCollector;
154
    }
155
156
    /**
157
     * Register a custom HTML macro.
158
     *
159
     * @param string $name
160
     * @param  mixed  $macro
0 ignored issues
show
Bug introduced by
There is no parameter named $macro. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
161
     * @return void
162
     */
163
    public function extend($name, $provider)
164
    {
165
        $this->providers[$name] = $provider;
166
    }
167
168
    /**
169
     * Set token provider
170
     *
171
     * @param UniqueProcessIdentifier $tokenProvider
172
     */
173
    public function setTokenProvider(TokenProvider $tokenProvider)
174
    {
175
        $this->tokenProvider = $tokenProvider;
0 ignored issues
show
Documentation Bug introduced by
It seems like $tokenProvider of type object<Understand\Unders...Laravel5\TokenProvider> is incompatible with the declared type object<Understand\Unders...niqueProcessIdentifier> of property $tokenProvider.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
176
    }
177
178
    /**
179
     * Return resolved field-value array
180
     *
181
     * @param array $callbacks
182
     * @param array $log
183
     * @return array
184
     */
185
    public function resolveValues(array $callbacks, array $log)
186
    {
187
        $data = [];
188
189
        foreach ($callbacks as $fieldName => $caller)
190
        {
191
            if (!is_array($caller))
192
            {
193
                $caller = [$caller];
194
            }
195
196
            $callback = array_get($caller, 0);
197
            $args = [$log];
198
199
            $value = call_user_func_array($callback, $args);
200
201
            $data[$fieldName] = $value;
202
        }
203
204
        return $data;
205
    }
206
207
    /**
208
     * Handle class calls
209
     *
210
     * @param string $name
211
     * @param  mixed $params
212
     * @return mixed
213
     *
214
     * @throws \BadMethodCallException
215
     */
216
    public function __call($name, $params)
217
    {
218
        if (isset($this->providers[$name]))
219
        {
220
            return call_user_func_array($this->providers[$name], $params);
221
        }
222
223
        throw new \BadMethodCallException("Method {$name} does not exist.");
224
    }
225
226
    /**
227
     * Return hashed version of session id
228
     *
229
     * @return string
230
     */
231
    protected function getSessionId()
232
    {
233
        if ( ! $this->session)
234
        {
235
            return null;
236
        }
237
238
        $sessionId = $this->session->getId();
239
240
        // by default we provide only hashed version of session id
241
        $hashed = sha1($sessionId);
242
243
        return $hashed;
244
    }
245
246
    /**
247
     * @return string
248
     */
249
    protected function getLaravelVersion()
250
    {
251
        return Application::VERSION;
252
    }
253
254
    /**
255
     * @return array
256
     */
257
    protected function getSqlQueries()
258
    {
259
        if ($this->dataCollector)
260
        {
261
            return $this->dataCollector->getByKey('sql_queries');
262
        }
263
    }
264
265
    /**
266
     * Return current route name
267
     *
268
     * @return string
269
     */
270
    protected function getRouteName()
271
    {
272
        if ( ! $this->router)
273
        {
274
            return null;
275
        }
276
277
        return $this->router->getCurrentRoute()->getName();
278
    }
279
280
    /**
281
     * Return current url
282
     *
283
     * @return string
284
     */
285
    protected function getUrl()
286
    {
287
        if ( ! $this->request)
288
        {
289
            return null;
290
        }
291
292
        $url = $this->request->path();
293
294
        if ( ! starts_with($url, '/'))
295
        {
296
            $url = '/' . $url;
297
        }
298
299
        $queryString = $this->request->getQueryString();
300
301
        if ($queryString)
0 ignored issues
show
Bug Best Practice introduced by
The expression $queryString of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
302
        {
303
            $url .= '?' . $queryString;
304
        }
305
306
        return $url;
307
    }
308
309
    /**
310
     * Return request method
311
     *
312
     * @return string
313
     */
314
    protected function getRequestMethod()
315
    {
316
        if ( ! $this->request)
317
        {
318
            return null;
319
        }
320
321
        return $this->request->method();
322
    }
323
324
    /**
325
     * Return server ip address
326
     *
327
     * @return string
328
     */
329
    protected function getServerIp()
330
    {
331
        if ( ! $this->request)
332
        {
333
            return null;
334
        }
335
336
        return $this->request->server->get('SERVER_ADDR');
337
    }
338
339
    /**
340
     * Return client ip
341
     *
342
     * @return string
343
     */
344
    protected function getClientIp()
345
    {
346
        if ( ! $this->request)
347
        {
348
            return null;
349
        }
350
351
        return $this->request->getClientIp();
352
    }
353
354
    /**
355
     * Return client user agent string
356
     *
357
     * @return string
358
     */
359
    protected function getClientUserAgent()
360
    {
361
        if ( ! $this->request)
362
        {
363
            return null;
364
        }
365
366
        return $this->request->server->get('HTTP_USER_AGENT');
367
    }
368
369
    /**
370
     * Return current enviroment
371
     *
372
     * @return string
373
     */
374
    protected function getEnvironment()
375
    {
376
        return $this->environment;
377
    }
378
379
    /**
380
     * Retrive parameter from current session
381
     *
382
     * @param string $key
383
     * @return string
384
     */
385
    protected function getFromSession($key)
386
    {
387
        if ( ! $this->session)
388
        {
389
            return null;
390
        }
391
392
        return $this->session->get($key);
393
    }
394
395
    /**
396
     * Return group id
397
     *
398
     * @param array $log
399
     * @return string
400
     */
401
    protected function getGroupId(array $log)
402
    {
403
        $parts = [];
404
405
        foreach(['class', 'file', 'line'] as $field)
406
        {
407
            $parts[] = isset($log[$field]) ? (string)$log[$field] : null;
408
        }
409
410
        return sha1(implode('#', $parts));
411
    }
412
413
    /**
414
     * Return current active user id
415
     *
416
     * @return int
417
     */
418
    protected function getUserId()
419
    {
420
        try
421
        {
422
            if (class_exists('\Auth') && ($userId = \Auth::id()))
423
            {
424
                return $userId;
425
            }
426
        }
427
        catch (\Exception $e)
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
428
        {}
429
430
        try
431
        {
432
            if (class_exists('\Sentinel') && ($user = \Sentinel::getUser()))
433
            {
434
                return $user->id;
435
            }
436
        }
437
        catch (\Exception $e)
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
438
        {}
439
440
        try
441
        {
442
            if (class_exists('\Sentry') && ($user = \Sentry::getUser()))
443
            {
444
                return $user->id;
445
            }
446
        }
447
        catch (\Exception $e)
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
448
        {}
449
    }
450
451
    /**
452
     * @return string
453
     */
454
    protected function getArtisanCommandName()
0 ignored issues
show
Coding Style introduced by
getArtisanCommandName uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
455
    {
456
        if ($this->app->runningInConsole() && isset($_SERVER['argv']))
457
        {
458
            return implode(' ', $_SERVER['argv']);
459
        }
460
    }
461
462
    /**
463
     * @return bool
464
     */
465
    protected function getRunningInConsole()
466
    {
467
        return $this->app->runningInConsole();
468
    }
469
470
    /**
471
     * @return float
472
     */
473
    protected function getLoggerVersion()
474
    {
475
        return Logger::VERSION;
476
    }
477
478
    /**
479
     * Return process identifier token
480
     *
481
     * @return string
482
     */
483
    protected function getProcessIdentifier()
484
    {
485
        return $this->tokenProvider->getToken();
486
    }
487
488
}
489