ResultSet::next()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 1
c 1
b 1
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
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(): mixed
25
    {
26
        return $this->array[$this->current];
27
    }
28
29
    public function next(): void
30
    {
31
        $this->current++;
32
    }
33
34
    public function key(): mixed
35
    {
36
        return $this->current;
37
    }
38
39
    public function valid(): bool
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(): void
59
    {
60
        $this->current = 0;
61
    }
62
63
    public function getArray(): array
64
    {
65
        return $this->array;
66
    }
67
68
    public function count():int
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