LazyResourceList::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Scriptotek\Alma\Model;
4
5
use Scriptotek\Alma\Client;
6
7
/**
8
 * The LazyResourceList extends the LazyResource class with functionality for
9
 * working with non-paginated lists of resources, such as holdings, items, loans, etc.
10
 */
11
abstract class LazyResourceList extends LazyResource implements \Countable
12
{
13
    /* @var integer */
14
    protected $totalRecordCount = null;
15
16
    /* @var array */
17
    protected $resources = [];
18
19
    /**
20
     * The key in the response object that points to the resource list.
21
     *
22
     * @var string
23
     */
24
    protected $responseKey;
25
26
    /**
27
     * LazyResourceList constructor.
28
     *
29
     * @param Client $client
30
     * @param string $responseKey
31
     */
32
    public function __construct(Client $client, $responseKey)
33
    {
34
        parent::__construct($client);
35
        $this->responseKey = $responseKey;
36
    }
37
38
    /**
39
     * Convert a data element to a resource object.
40
     *
41
     * @param $data
42
     *
43
     * @return mixed
44
     */
45
    abstract protected function convertToResource($data);
46
47
    /**
48
     * Called when data is available on the object.
49
     * The resource classes can use this method to process the data.
50
     *
51
     * @param $data
52
     */
53
    protected function onData($data)
54
    {
55
        if (is_null($this->totalRecordCount)) {
56
            $this->totalRecordCount = $data->total_record_count;
57
        }
58
59
        if (!isset($data->{$this->responseKey})) {
60
            return;
61
        }
62
63
        foreach ($data->{$this->responseKey} as $result) {
64
            $this->resources[] = $this->convertToResource($result);
65
        }
66
    }
67
68
    /**
69
     * Check if we have the full representation of our data object.
70
     *
71
     * @param \stdClass $data
72
     *
73
     * @return bool
74
     */
75
    protected function isInitialized($data)
76
    {
77
        return isset($data->total_record_count);
78
    }
79
80
    /**
81
     * Get all the resources.
82
     *
83
     * @return array
84
     */
85
    public function all()
86
    {
87
        return $this->init()->resources;
88
    }
89
90
    /**
91
     * Number of resources.
92
     *
93
     * @link http://php.net/manual/en/countable.count.php
94
     *
95
     * @return int The number of resources as an integer.
96
     */
97
    public function count()
98
    {
99
        return count($this->all());
100
    }
101
}
102