TwitApps::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
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