Completed
Push — master ( 47778c...ba169d )
by Dan Michael O.
10:36
created

SimplePagedLazyResourceList::findKey()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 9
rs 9.9666
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 SimplePagedLazyResourceList 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 SimplePagedLazyResourceList extends PagedLazyResourceList
14
{
15
    /* @var integer */
16
    protected $offset = 0;
17
18
    /* @var integer */
19
    protected $limit = 10;
20
21
    /* @var integer */
22
    protected $totalRecordCount = null;
23
24
    protected function findKey($data)
25
    {
26
        foreach (array_keys((array) $data) as $key) {
27
            if ($key != 'total_record_count') {
28
                return $key;
29
            }
30
        }
31
        throw new ClientException('No resource key found in response object');
32
    }
33
34
    protected function fetchBatch()
35
    {
36
        if (!is_null($this->totalRecordCount) && $this->offset >= $this->totalRecordCount) {
37
            return;
38
        }
39
40
        $response = $this->client->getJSON($this->url('', [
41
            'offset' => $this->offset,
42
            'limit' => $this->limit,
43
        ]));
44
45
        if (is_null($this->totalRecordCount)) {
46
            $this->totalRecordCount = $response->total_record_count;
47
        }
48
49
        if ($this->totalRecordCount === 0) {
50
            return;
51
        }
52
53
        $key = $this->findKey($response);
54
        foreach ($response->{$key} as $res) {
55
            $this->resources[] = $this->convertToResource($res);
56
        }
57
        $this->offset = count($this->resources);
58
    }
59
60
    /**
61
     * Check if we have the full representation of our data object.
62
     *
63
     * @param \stdClass $data
64
     * @return boolean
65
     */
66
    protected function isInitialized($data)
67
    {
68
        return count($data) === $this->totalRecordCount;
69
    }
70
71
    /**
72
     * Total number of resources.
73
     * @link http://php.net/manual/en/countable.count.php
74
     * @return int
75
     */
76
    public function count()
77
    {
78
        if (is_null($this->totalRecordCount)) {
79
            $this->fetchBatch();
80
        }
81
82
        return $this->totalRecordCount;
83
    }
84
}
85