-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathNylasModelCollection.php
More file actions
91 lines (75 loc) · 2.45 KB
/
NylasModelCollection.php
File metadata and controls
91 lines (75 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
namespace Nylas;
class NylasModelCollection {
private $chunkSize = 50;
public function __construct($klass, $api, $namespace=NULL, $filter=array(), $offset=0, $filters=array()) {
$this->klass = $klass;
$this->api = $api;
$this->namespace = $namespace;
$this->filter = $filter;
$this->filters = $filters;
if(!array_key_exists('offset', $filter)) {
$this->filter['offset'] = 0;
}
}
public function items() {
$offset = 0;
while (True) {
$items = $this->_getModelCollection($offset, $this->chunkSize);
if(!$items) {
break;
}
foreach ($items as $item) {
yield $item;
}
if (count($items) < $this->chunkSize) {
break;
}
$offset += count($items);
}
}
public function first() {
$results = $this->_getModelCollection(0, 1);
if ($results) {
return $results[0];
}
return NULL;
}
public function all($limit=INF) {
return $this->_range($this->filter['offset'], $limit);
}
public function where($filter, $filters=array()) {
$this->filter = array_merge($this->filter, $filter);
$this->filter['offset'] = 0;
$collection = clone $this;
$collection->filter = $this->filter;
return $collection;
}
public function find($id) {
return $this->_getModel($id);
}
public function create($data) {
return $this->klass->create($data, $this);
}
private function _range($offset, $limit) {
$result = array();
while (count($result) < $limit) {
$to_fetch = min($limit - count($result), $this->chunkSize);
$data = $this->_getModelCollection($offset+count($result), $to_fetch);
$result = array_merge($result, $data);
if(!$data || count($data) < $to_fetch) {
break;
}
}
return $result;
}
private function _getModel($id) {
// make filter a kwarg filters
return $this->api->getResource($this->namespace, $this->klass, $id, $this->filter);
}
private function _getModelCollection($offset, $limit) {
$this->filter['offset'] = $offset;
$this->filter['limit'] = $limit;
return $this->api->getResources($this->namespace, $this->klass, $this->filter);
}
}