TwitApps::waitTime()   A
last analyzed

Complexity

Conditions 3
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 3
eloc 5
c 1
b 1
f 0
nc 1
nop 0
dl 0
loc 9
ccs 0
cts 7
cp 0
crap 12
rs 10
1
<?php
2
3
namespace Tequilarapido\Twit;
4
5
use Illuminate\Support\Collection;
6
7
class TwitApps
8
{
9
    /** @var Collection */
10
    private $pool;
11
12
    /** @var TwitApp */
13
    private $current;
14
15
    public function __construct($apps)
16
    {
17
        $this->pool = collect($apps)->map(function ($config, $key) {
18
            return new TwitApp($key, $config);
19
        });
20
    }
21
22
    /** @return TwitApp */
23
    public function getAvailable()
24
    {
25
        $this->current = $this->pool->first(function (TwitApp $app) {
26
            return $app->available();
27
        });
28
29
        if (! $this->current) {
30
            // We will return the first one to get the rate limits so we can sleep
31
            // and wait for reset
32
            $this->current = $this->pool->get(0);
33
        }
34
35
        return $this->current;
36
    }
37
38
    public function waitTime()
39
    {
40
        $waitTime = $this->pool->map(function (TwitApp $app) {
41
            if ($app->rateLimits) {
42
                return $app->rateLimits->waitTime();
43
            }
44
        })->filter()->min();
45
46
        return $waitTime ?: 0;
47
    }
48
49
    public function resetRateLimits()
50
    {
51
        $this->pool->each(function (TwitApp $app) {
52
            return $app->rateLimits = null;
53
        });
54
    }
55
}
56