Skip to content

Commit

Permalink
Merge pull request #21 from m038/master
Browse files Browse the repository at this point in the history
Adds method for retrieving Param Object method when only key is available
  • Loading branch information
Paweł Mikołajczuk committed Jan 18, 2016
2 parents 9787b31 + 1b6f06e commit bd326e3
Show file tree
Hide file tree
Showing 6 changed files with 109 additions and 32 deletions.
13 changes: 11 additions & 2 deletions sample/default-client/example.php
Expand Up @@ -26,7 +26,7 @@

$parameters = new RequestParameters();
$parameters
->setStartDate(date('Y-m-d', strtotime('-7 days')))
->setStartDate(date('Y-m-d', strtotime('-1 year')))
->setPage(1)
->setMaxResults(1);

Expand All @@ -44,6 +44,8 @@
echo ".: Getting items :.\n\n";

$items = $contentApi->getItems($parameters);
$items->setMaxPerPage($parameters->getMaxResults());
$items->setCurrentPage($parameters->getPage());

echo "Total items: {$items->getNbResults()}\n";
echo "Items per page: {$items->getMaxPerPage()}\n";
Expand Down Expand Up @@ -75,10 +77,17 @@
}



echo "\n\n.: Getting packages :.\n\n";

// Reset parameters
$parameters
->setPage(1)
->setMaxResults(1);

$packages = $contentApi->getPackages($parameters, true);
$packages->setMaxPerPage($parameters->getMaxResults());
$packages->setCurrentPage($parameters->getPage());


echo "Total packages: {$packages->getNbResults()}\n";
echo "Packages per page: {$packages->getMaxPerPage()}\n";
Expand Down
19 changes: 19 additions & 0 deletions spec/Superdesk/ContentApiSdk/API/Request/RequestParametersSpec.php
Expand Up @@ -182,4 +182,23 @@ function it_should_throw_an_exception_on_invalid_exclude_fields()
{
$this->shouldThrow('\Superdesk\ContentApiSdk\Exception\InvalidArgumentException')->duringSetExcludeFields(123456789);
}

function its_method_set_query_parameter_array_should_set_the_properties_from_an_array()
{
$queryParameterArray = array(
'q' => 'some_text',
'start_date' => '2015-01-01'
);
$this->setQueryParameterArray($queryParameterArray);
$this->getQuery()->shouldReturn($queryParameterArray['q']);
$this->getStartDate()->format('Y-m-d')->shouldReturn($queryParameterArray['start_date']);
}

function its_method_set_query_parameter_array_should_ignore_invalid_keys_and_not_throw_an_exception()
{
$queryParameterArray = array(
'some_invalid_key' => 'some_value'
);
$this->setQueryParameterArray($queryParameterArray);
}
}
Expand Up @@ -51,7 +51,7 @@ public function __construct(ApiClientInterface $client, RequestInterface $reques
}

/**
* Make call HTTP call.
* Make HTTP call.
*
* @return \Superdesk\ContentApiSdk\API\Response API Response object
*/
Expand Down
57 changes: 49 additions & 8 deletions src/Superdesk/ContentApiSdk/API/Request/RequestParameters.php
Expand Up @@ -81,13 +81,13 @@ class RequestParameters
* @var string[]
*/
protected $propertyMapping = array(
'start_date' => 'getStartDate',
'end_date' => 'getEndDate',
'q' => 'getQuery',
'page' => 'getPage',
'max_results' => 'getMaxResults',
'include_fields' => 'getIncludeFields',
'exclude_fields' => 'getExcludeFields',
'start_date' => 'StartDate',
'end_date' => 'EndDate',
'q' => 'Query',
'page' => 'Page',
'max_results' => 'MaxResults',
'include_fields' => 'IncludeFields',
'exclude_fields' => 'ExcludeFields',
);

/**
Expand Down Expand Up @@ -359,6 +359,25 @@ private function setProperty($property, $value, $validator)
}
}

/**
* Internal method to get the correct method when only a query parameter
* key is available.
*
* @param string $queryKey [description]
* @param string $action This will be prepended to the method name,
* defaults to 'get'.
*
* @return string|null Returns the method or null when the key doesn't exist.
*/
private function getMethodForQueryKey($queryKey, $action = 'get')
{
if (isset($this->propertyMapping[$queryKey])) {
return sprintf('%s%s', $action, $this->propertyMapping[$queryKey]);
}

return null;
}

/**
* Returns all properties either as an array or http query string.
*
Expand All @@ -370,8 +389,9 @@ public function getAllParameters($buildHttpQuery = false)
{
$httpQuery = array();

foreach ($this->propertyMapping as $uriParameter => $method) {
foreach ($this->propertyMapping as $uriParameter => $methodPart) {

$method = $this->getMethodForQueryKey($uriParameter);
$value = $this->$method();

if ($value instanceof DateTIme) {
Expand All @@ -383,4 +403,25 @@ public function getAllParameters($buildHttpQuery = false)

return ($buildHttpQuery) ? http_build_query($httpQuery) : $httpQuery;
}

/**
* Uses an array of query parameters and sets the values for the current
* RequestParameters object. Does an internal check whether the query key
* is a valid API query key.
*
* @param array $requestParameters
*
* @return self Returns the current object with the properties set
*/
public function setQueryParameterArray(array $requestParameters = array())
{
foreach ($requestParameters as $key => $value) {
if (isset($this->propertyMapping[$key])) {
$method = $this->getMethodForQueryKey($key, 'set');
$this->$method($value);
}
}

return $this;
}
}
29 changes: 14 additions & 15 deletions src/Superdesk/ContentApiSdk/Client/DefaultApiClient.php
Expand Up @@ -49,25 +49,24 @@ public function makeApiCall(RequestInterface $request)

$response = $this->sendRequest($this->authenticateRequest($request));

if ($response['status'] === 200) {
switch ($response['status']) {
case 200:
$this->resetAuthenticationRetryAttempt();

$this->resetAuthenticationRetryAttempt();
return $this->createResponseObject($response);
case 401:
$this->incrementAuthenticationRetryAttempt();

return $this->createResponseObject($response);
} elseif ($response['status'] === 401) {
if ($this->isAuthenticationRetryLimitReached()) {
throw new AccessDeniedException('Authentication retry limit reached.');
}

$this->incrementAuthenticationRetryAttempt();
// Once SD-3820 is fixed, implement SWP-92 branch, it will use
// the refresh token functionality, instead of request a new token
// each time this method is called.
$this->getNewToken($request);

if ($this->isAuthenticationRetryLimitReached()) {
throw new AccessDeniedException('Authentication retry limit reached.');
}

// Once SD-3820 is fixed, implement SWP-92 branch, it will use
// the refresh token functionality, instead of request a new token
// each time this method is called.
$this->getNewToken($request);

return $this->makeApiCall($request);
return $this->makeApiCall($request);
}

throw new ClientException(sprintf('The server returned an error with status %s.', $response['status']), $response['status']);
Expand Down
21 changes: 15 additions & 6 deletions src/Superdesk/ContentApiSdk/ContentApiSdk.php
Expand Up @@ -19,6 +19,7 @@
use Superdesk\ContentApiSdk\API\Response;
use Superdesk\ContentApiSdk\API\Pagerfanta\ItemAdapter;
use Superdesk\ContentApiSdk\API\Pagerfanta\PackageAdapter;
use Superdesk\ContentApiSdk\API\Pagerfanta\ResourceAdapter;
use Superdesk\ContentApiSdk\API\Pagerfanta\ResourceCollection;
use Superdesk\ContentApiSdk\Client\ApiClientInterface;
use Superdesk\ContentApiSdk\Data\Item;
Expand Down Expand Up @@ -250,14 +251,12 @@ public function getItem($itemId)
*/
public function getItems(RequestParameters $paramObj)
{
$itemCollection = new ResourceCollection(
return $this->getNewResourceCollection(
new ItemAdapter(
$this->client,
$this->getNewRequest(self::SUPERDESK_ENDPOINT_ITEMS, $paramObj)
)
);

return $itemCollection;
}

/**
Expand Down Expand Up @@ -298,16 +297,14 @@ public function getPackages(
RequestParameters $paramObj,
$resolveAssociations = false
) {
$packageCollection = new ResourceCollection(
return $this->getNewResourceCollection(
new PackageAdapter(
$this->client,
$this->getNewRequest(self::SUPERDESK_ENDPOINT_PACKAGES, $paramObj),
$this,
$resolveAssociations
)
);

return $packageCollection;
}

/**
Expand Down Expand Up @@ -389,6 +386,18 @@ public function getNewRequest($uri, RequestParameters $parameters = null)
return $request;
}

/**
* Shortcut to get a new ResourceCollection object.
*
* @param ResourceAdapter $resourceAdapter
*
* @return ResourceCollection
*/
private function getNewResourceCollection(ResourceAdapter $resourceAdapter)
{
return new ResourceCollection($resourceAdapter);
}

/**
* Tries to find a valid id in an uri, both item as package uris. The id
* is returned urldecoded.
Expand Down

0 comments on commit bd326e3

Please sign in to comment.