ThrottleTimeRemaining   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 5
dl 0
loc 66
ccs 0
cts 19
cp 0
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A compose() 0 4 1
A getTimeRemaining() 0 14 2
A getCacheKey() 0 12 3
A getSecondsRemaining() 0 4 1
1
<?php
2
3
namespace CodeZero\StageFront\Composers;
4
5
use Carbon\Carbon;
6
use Illuminate\Cache\RateLimiter;
7
use Illuminate\Contracts\View\View;
8
use Illuminate\Support\Facades\App;
9
use Illuminate\Support\Facades\Lang;
10
use Illuminate\Support\Facades\Request;
11
12
class ThrottleTimeRemaining
13
{
14
    /**
15
     * Provide the view with the time remaining on the throttle.
16
     *
17
     * @param \Illuminate\Contracts\View\View $view
18
     *
19
     * @return void
20
     */
21
    public function compose(View $view)
22
    {
23
        $view->with('timeRemaining', $this->getTimeRemaining());
24
    }
25
26
    /**
27
     * Get the time remaining on the throttle in a human readable format.
28
     *
29
     * @return string
30
     */
31
    protected function getTimeRemaining()
32
    {
33
        if ( ! $key = $this->getCacheKey()) {
34
            return Lang::get('stagefront::errors.throttled.moment');
35
        }
36
37
        $secondsRemaining = $this->getSecondsRemaining($key);
38
39
        Carbon::setLocale(App::getLocale());
40
41
        return Carbon::now()
42
            ->addSeconds($secondsRemaining)
43
            ->diffForHumans(null, true);
44
    }
45
46
    /**
47
     * Resolve the cache key for the throttle info.
48
     * See `resolveRequestSignature` method:
49
     * https://github.com/illuminate/routing/blob/master/Middleware/ThrottleRequests.php#L88
50
     *
51
     * @return string|null
52
     */
53
    protected function getCacheKey()
54
    {
55
        if ($user = Request::user()) {
56
            return sha1($user->getAuthIdentifier());
57
        }
58
59
        if ($route = Request::route()) {
60
            return sha1($route->getDomain().'|'.Request::ip());
61
        }
62
63
        return null;
64
    }
65
66
    /**
67
     * Get the remaining seconds on the throttle.
68
     *
69
     * @param string $key
70
     *
71
     * @return mixed
72
     */
73
    protected function getSecondsRemaining($key)
74
    {
75
        return App::make(RateLimiter::class)->availableIn($key);
76
    }
77
}
78