1+ <?php
2+ namespace Intercom \Model \Iterators ;
3+
4+ use Guzzle \Service \Resource \ResourceIterator ;
5+ use Intercom \Exception \IntercomException as IntercomException ;
6+
7+
8+ abstract class AbstractPageIterator extends ResourceIterator
9+ {
10+ /** @var int|null The total number of results this request has available */
11+ protected $ totalResults ;
12+
13+ /** @var string|null The type of object the paginated call returns */
14+ protected $ objectListType ;
15+
16+ protected function sendRequest ()
17+ {
18+ // Match up the page size on the iterator with the one on the command
19+ if ($ this ->pageSize ) {
20+ $ this ->command ->set ('per_page ' , $ this ->pageSize );
21+ }
22+
23+ // If a next token is set, then add it to the command
24+ if ($ this ->nextToken ) {
25+ $ this ->command ->set ('page ' , $ this ->nextToken );
26+ }
27+
28+ // Execute the command and parse the result
29+ $ result = $ this ->command ->execute ();
30+
31+ // Parse the next token
32+ $ this ->nextToken = (isset ($ result ['next_page ' ])) ? $ result ['next_page ' ] : false ;
33+
34+ // Set the total results
35+ $ this ->totalResults = $ result ['total_count ' ];
36+
37+ return $ result ->get ($ this ->getObjectKeyFromListType ($ result ['type ' ]));
38+ }
39+
40+ /**
41+ * Sets the total number of results available from the API for this request
42+ *
43+ * @param int $totalResults
44+ */
45+ protected function setTotalResults ($ totalResults )
46+ {
47+ $ this ->totalResults = $ totalResults ;
48+ }
49+
50+ /**
51+ * Gets the total results available from the API for this request
52+ *
53+ * @return null|int The total results
54+ */
55+ public function getTotalResults ()
56+ {
57+ return $ this ->totalResults ;
58+ }
59+
60+ /**
61+ * Sets the number of results per page
62+ *
63+ * @param int $pageSize The requested page size
64+ * @return $this
65+ * @throws IntercomException If the page size is not between 1 and 60
66+ */
67+ public function setPageSize ($ pageSize )
68+ {
69+ if ($ pageSize < 1 || $ pageSize > 60 ) {
70+ throw new IntercomException ('Page size on the iterator must be between 1 and 60 ' );
71+ }
72+
73+ return parent ::setPageSize ($ pageSize );
74+ }
75+
76+ /**
77+ * Gets the name of the key that contains the results in a paginated API response
78+ *
79+ * @param string $type The returned type
80+ * @return string
81+ * @throws IntercomException If the $type is unknown
82+ */
83+ protected function getObjectKeyFromListType ($ type )
84+ {
85+ switch ($ type ) {
86+ case 'company.list ' :
87+ return 'companies ' ;
88+ case 'conversation.list ' :
89+ return 'conversations ' ;
90+ case 'conversation.part.list ' :
91+ return 'parts ' ;
92+ case 'segment.list ' :
93+ return 'segments ' ;
94+ case 'tag.list ' :
95+ return 'tags ' ;
96+ case 'user.list ' :
97+ return 'users ' ;
98+ default :
99+ throw new IntercomException ("Unknown list type returned ( {$ type }). Unable to use iterator to paginate " );
100+ }
101+ }
102+ }
0 commit comments