Completed
Push — master ( 2fdbfa...640218 )
by Ivan
01:49
created

ThrottleTimeRemaining::getTimeRemaining()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 0
cts 8
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 0
crap 6
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
9
class ThrottleTimeRemaining
10
{
11
    /**
12
     * Provide the view with the time remaining on the throttle.
13
     *
14
     * @param \Illuminate\Contracts\View\View $view
15
     *
16
     * @return void
17
     */
18
    public function compose(View $view)
19
    {
20
        $view->with('timeRemaining', $this->getTimeRemaining());
21
    }
22
23
    /**
24
     * Get the time remaining on the throttle in a human readable format.
25
     *
26
     * @return string
27
     */
28
    protected function getTimeRemaining()
29
    {
30
        if ( ! $key = $this->getCacheKey()) {
31
            return trans('stagefront::errors.throttled.moment');
32
        }
33
34
        $secondsRemaining = $this->getSecondRemaining($key);
35
36
        Carbon::setLocale(app()->getLocale());
37
38
        return Carbon::now()
39
            ->addSeconds($secondsRemaining)
40
            ->diffForHumans(null, true);
41
    }
42
43
    /**
44
     * Resolve the cache key for the throttle info.
45
     * See `resolveRequestSignature` method:
46
     * https://github.com/illuminate/routing/blob/master/Middleware/ThrottleRequests.php#L88
47
     *
48
     * @return string|null
49
     */
50
    protected function getCacheKey()
51
    {
52
        $request = request();
53
54
        if ($user = $request->user()) {
55
            return sha1($user->getAuthIdentifier());
56
        }
57
58
        if ($route = $request->route()) {
59
            return sha1($route->getDomain().'|'.$request->ip());
60
        }
61
62
        return null;
63
    }
64
65
    /**
66
     * Get the remaining seconds on the throttle.
67
     *
68
     * @param string $key
69
     *
70
     * @return mixed
71
     */
72
    protected function getSecondRemaining($key)
73
    {
74
        return app(RateLimiter::class)->availableIn($key);
75
    }
76
}
77