Completed
Push — master ( 115a4d...9dc8cf )
by Scott
02:59 queued 52s
created

ResultSet::valid()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 3
nop 0
1
<?php
2
3
namespace exussum12\TripAdvisor;
4
5
use Countable;
6
use exussum12\TripAdvisor\Exceptions\BaseException;
7
use exussum12\TripAdvisor\Exceptions\RateLimit;
8
use Iterator;
9
10
class ResultSet implements Iterator, Countable
11
{
12
    protected $array;
13
    protected $current = 0;
14
    protected $rateLimitRetryAttempts = 5;
15
    protected $rateLimitTimeout = 10;
16
    protected $reviews;
17
18
    public function __construct(Reviews $reviews, array $startingArray)
19
    {
20
        $this->array = $startingArray;
21
        $this->reviews = $reviews;
22
    }
23
24
    public function current()
25
    {
26
        return $this->array[$this->current];
27
    }
28
29
    public function next()
30
    {
31
        $this->current++;
32
    }
33
34
    public function key()
35
    {
36
        return $this->current;
37
    }
38
39
    public function valid()
40
    {
41
        if (isset($this->array[$this->current])) {
42
            return true;
43
        }
44
45
        $settings = $this->reviews->getSettings();
46
        if ($this->current % $settings['limit'] == 0 && $this->current > 0) {
47
            $this->reviews->offset(
48
                $settings['limit'] + $settings['offset']
49
            );
50
51
            $this->getMoreResults();
52
            return isset($this->array[$this->current]);
53
        }
54
55
        return false;
56
    }
57
58
    public function rewind()
59
    {
60
        $this->current = 0;
61
    }
62
63
    public function getArray()
64
    {
65
        return $this->array;
66
    }
67
68
    public function count()
69
    {
70
        return count($this->array);
71
    }
72
73
    protected function getMoreResults()
74
    {
75
        $i = 0;
76
        while ($i++ < $this->rateLimitRetryAttempts) {
77
            try {
78
                $extraResults = $this->reviews->get();
79
                $this->array = array_merge($this->array, $extraResults->getArray());
80
                break;
81
            } catch (RateLimit $exception) {
82
                sleep($exception->getTimeout());
83
                continue;
84
            } catch (BaseException $exception) {
85
                throw $exception;
86
            }
87
        }
88
    }
89
}
90