Count #101

Merged
merged 6 commits into from Nov 24, 2012
@@ -11,8 +11,9 @@
*/
abstract class Services_Twilio_ListResource
extends Services_Twilio_Resource
- implements IteratorAggregate
+ implements IteratorAggregate, Countable
{
+
public function __construct($client, $uri) {
$name = $this->getResourceName(true);
/*
@@ -128,6 +129,24 @@ public function getPage(
return new Services_Twilio_Page($page, $list_name, $next_page_uri);
}
+ /**
+ * Get the total number of instance members. Note this will make one small
+ * HTTP request to retrieve the total, every time this method is called.
+ *
+ * If the total is not set or an Exception was thrown, returns 0
+ *
+ * @return integer
+ *
+ */
+ public function count() {
+ try {
+ $page = $this->getPage(0, 1);
+ return $page ? (int)$page->total : 0;
+ } catch (Exception $e) {
+ return 0;
+ }
+ }
+
/**
* Returns an iterable list of InstanceResources
View
@@ -67,6 +67,16 @@ You can create a filtered iterator like this:
print $call->duration . '\n';
}
+Retrieving the Total Number of Resources
+----------------------------------------
+
+Each of the list resources supports the `Countable` interface, which means you
+can retrieve the total number of list items like so:
+
+.. code-block:: php
+
+ echo count($client->account->calls);
+
Getting a Specific Resource
=============================
View
@@ -546,4 +546,31 @@ function testRetryIdempotentFunctionsOnly() {
'+14102221234', 'bar');
}
+ function testCount() {
+ $http = m::mock(new Services_Twilio_TinyHttp);
+ $http->shouldReceive('get')->once()
+ ->with('/2010-04-01/Accounts/AC123/Calls.json?Page=0&PageSize=1')
+ ->andReturn(array(200, array('Content-Type' => 'application/json'),
+ json_encode(array(
+ 'total' => '1474',
+ 'calls' => array(),
+ ))
+ ));
+ $client = new Services_Twilio('AC123', '123', '2010-04-01', $http);
+ $this->assertSame(count($client->account->calls), 1474);
+ }
+
+ function testCountNoTotal() {
+ $http = m::mock(new Services_Twilio_TinyHttp);
+ $http->shouldReceive('get')->once()
+ ->with('/2010-04-01/Accounts/AC123/Calls.json?Page=0&PageSize=1')
+ ->andReturn(array(200, array('Content-Type' => 'application/json'),
+ json_encode(array(
+ 'calls' => array(),
+ ))
+ ));
+ $client = new Services_Twilio('AC123', '123', '2010-04-01', $http);
+ $this->assertSame(count($client->account->calls), 0);
+ }
+
}