Completed
Push — master ( 9d90d4...cee823 )
by Dan Michael O.
03:06
created

SimplePaginatedList::fetchBatch()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 7
nop 0
dl 0
loc 24
rs 8.9137
c 0
b 0
f 0
1
<?php
2
3
namespace Scriptotek\Alma\Model;
4
5
use Scriptotek\Alma\Exception\ClientException;
6
7
/**
8
 * A SimplePaginatedList is a list that is paged using the `offset`
9
 * and `limit` parameters and that provides a `totalRecordCount` in the first response,
10
 * so that we can return a count without having to retrieve all the pages.
11
 * A list which is not of this type is the Analytics report row list.
12
 */
13
abstract class SimplePaginatedList extends LazyResourceList
14
{
15
    use PaginatedList;
16
17
    /* @var integer */
18
    protected $offset = 0;
19
20
    /* @var integer */
21
    protected $limit = 10;
22
23
    /* @var integer */
24
    protected $totalRecordCount = null;
25
26
    protected function fetchBatch()
27
    {
28
        if (!is_null($this->totalRecordCount) && $this->offset >= $this->totalRecordCount) {
29
            return;
30
        }
31
32
        $response = $this->client->getJSON($this->url('', [
33
            'offset' => $this->offset,
34
            'limit' => $this->limit,
35
        ]));
36
37
        if (is_null($this->totalRecordCount)) {
38
            $this->totalRecordCount = $response->total_record_count;
39
        }
40
41
        if ($this->totalRecordCount === 0) {
42
            return;
43
        }
44
45
        foreach ($response->{$this->responseKey} as $res) {
46
            $this->resources[] = $this->convertToResource($res);
47
        }
48
        $this->offset = count($this->resources);
49
    }
50
51
    /**
52
     * Check if we have the full representation of our data object.
53
     *
54
     * @param \stdClass $data
55
     * @return boolean
56
     */
57
    protected function isInitialized($data)
58
    {
59
        return count($data) === $this->totalRecordCount;
60
    }
61
62
    /**
63
     * Total number of resources.
64
     * @link http://php.net/manual/en/countable.count.php
65
     * @return int
66
     */
67
    public function count()
68
    {
69
        if (is_null($this->totalRecordCount)) {
70
            $this->fetchBatch();
71
        }
72
73
        return $this->totalRecordCount;
74
    }
75
}
76