/**
  * {@inheritdoc}
  */
 public function getSlice($offset, $length)
 {
     $packages = array();
     $resources = parent::getSlice($offset, $length);
     try {
         foreach ($resources as $itemData) {
             $packages[] = new Package($itemData);
         }
         if ($this->resolveAssociations) {
             foreach ($packages as $id => $package) {
                 $associations = $this->apiInstance->getAssociationsFromPackage($package);
                 $packages[$id] = $this->apiInstance->injectAssociations($package, $associations);
             }
         }
     } catch (Exception $e) {
         throw new InvalidDataException('Could not convert resources to packages.', $e->getCode(), $e);
     }
     return $packages;
 }
 /**
  * Get all feed entries as a parser instance
  *
  * @param \Newscoop\IngestPluginBundle\Entity\Feed $feedEntity Feed entity
  *
  * @return array Array should contain feed entries
  */
 public static function getStories(Feed $feedEntity)
 {
     $entries = array();
     $data = array();
     $clientConfig = array('base_uri' => $feedEntity->getUrl(), 'options' => '');
     $client = new GuzzleClient($clientConfig);
     $sdk = new ContentApiSdk($client);
     $parameters = array('start_date' => date('Y-m-d', strtotime('-3 days')));
     try {
         $data = $sdk->getPackages($parameters, true);
     } catch (ContentApiException $e) {
         throw new NewscoopException($e->getMessage(), $e->getCode(), $e);
     }
     // Convert all $data into entries
     foreach ($data as $package) {
         $entryPackage = new SuperdeskContentApiParser($package);
         $images = $entryPackage->getImages();
         if (property_exists($package->associations, 'main') && empty($images)) {
             continue;
         }
         $entries[] = $entryPackage;
     }
     return $entries;
 }
 /**
  * Returns id extracted from uri. Uses getIdFromUri method in ContentApiSdk
  * class.
  *
  * @return string Urldecoded id
  */
 public function getId()
 {
     return ContentApiSdk::getIdFromUri($this->uri);
 }
예제 #4
0
define('API_HOST', '');
define('API_PORT', 80);
define('API_PROTOCOL', null);
define('API_CLIENT_ID', '');
define('API_USERNAME', '');
define('API_PASSWORD', '');
/**
 * End of configuration
 */
$parameters = new RequestParameters();
$parameters->setStartDate(date('Y-m-d', strtotime('-1 year')))->setPage(1)->setMaxResults(1);
$genericClient = new CurlClient();
$authentication = new OAuthPasswordAuthentication($genericClient);
$authentication->setClientId(API_CLIENT_ID)->setUsername(API_USERNAME)->setPassword(API_PASSWORD);
$apiClient = new DefaultApiClient($genericClient, $authentication);
$contentApi = new ContentApiSdk($apiClient, API_HOST, API_PORT, API_PROTOCOL);
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";
echo "Total pages: {$items->getNbPages()}\n\n";
// Some limit, so we dont accicentally get every item
$maxPages = $items->getNbPages() < 10 ? $items->getNbPages() : 10;
if ($items->haveToPaginate()) {
    for ($i = 1; $i <= $maxPages; $i++) {
        echo "Current page: {$items->getCurrentPage()}\n";
        $data = $items->getCurrentPageResults();
        foreach ($data as $item) {
            echo "Item headline: {$item->headline}\n";
 /**
  * Adds version to request uri.
  *
  * @return self
  */
 public function addVersion()
 {
     $this->setUri(sprintf('%s/%s', ContentApiSdk::getVersionURL(), ltrim($this->getUri(), '/')));
     return $this;
 }
예제 #6
0
 /**
  * Sets properties based on response body.
  *
  * @throws ResponseException
  */
 private function processRawBody()
 {
     switch ($this->contentType) {
         case self::CONTENT_TYPE_JSON:
             try {
                 $responseJson = ContentApiSdk::getValidJsonObj($this->rawBody);
             } catch (InvalidDataException $e) {
                 throw new ResponseException($e->getMessage(), $e->getCode(), $e);
             }
             $this->type = $responseJson->_links->self->title;
             $this->href = $responseJson->_links->self->href;
             if (property_exists($responseJson, '_meta')) {
                 $this->page = $responseJson->_meta->page;
                 $this->maxResults = $responseJson->_meta->max_results;
                 $this->total = $responseJson->_meta->total;
                 $this->nextPage = property_exists($responseJson->_links, 'next') ? $this->page + 1 : $this->page;
                 $this->prevPage = property_exists($responseJson->_links, 'prev') ? $this->page - 1 : $this->page;
                 $this->lastPage = property_exists($responseJson->_links, 'last') ? (int) ceil($this->total / $this->maxResults) : $this->page;
                 $this->resources = $responseJson->_items;
             } else {
                 $resourceObj = new stdClass();
                 foreach ($responseJson as $key => $value) {
                     if (in_array($key, $this->metaKeys)) {
                         continue;
                     }
                     $resourceObj->{$key} = $value;
                 }
                 $this->resources = $resourceObj;
             }
             break;
         case self::CONTENT_TYPE_XML:
             break;
     }
     return;
 }
 /**
  * {@inheritdoc}
  */
 public function getAuthenticationTokens()
 {
     try {
         $response = $this->client->makeCall($this->getAuthenticationUrl(), array(), array(), 'POST', array('client_id' => $this->getClientId(), 'grant_type' => self::AUTHENTICATION_GRANT_TYPE, 'username' => $this->getUsername(), 'password' => $this->getPassword()));
     } catch (ClientException $e) {
         throw new AuthenticationException('Could not request access token.', $e->getCode(), $e);
     }
     if ($response['status'] === 200) {
         try {
             $responseObj = ContentApiSdk::getValidJsonObj($response['body']);
         } catch (InvalidDataException $e) {
             throw new AuthenticationException('Authentication response body is not (valid) json.', $e->getCode(), $e);
         }
         if (property_exists($responseObj, 'access_token')) {
             $this->accessToken = $responseObj->access_token;
             return true;
         }
         throw new AuthenticationException('The server returned an unexpected response body.');
     }
     throw new AuthenticationException(sprintf('The server returned an error with status %s.', $response['status']), $response['status']);
 }
 /**
  * Process request parameters.
  *
  * @param mixed $params
  *
  * @return array
  */
 private function processParameters($params)
 {
     if (!is_array($params)) {
         return $params;
     }
     $validParameters = ContentApiSdk::getValidParameters();
     foreach ($params as $key => $value) {
         if (!in_array($key, $validParameters)) {
             unset($params[$key]);
         }
     }
     return $params;
 }
 /**
  * Tries to find a valid id in an uri, both item as package uris. The id
  * is returned urldecoded.
  *
  * @param  string $uri Item or package uri
  *
  * @return string      Urldecoded id
  */
 public static function getIdFromUri($uri)
 {
     /*
      * Works for package and item uris
      *   http://publicapi:5050/packages/tag%3Ademodata.org%2C0012%3Aninjs_XYZ123
      *   http://publicapi:5050/items/tag%3Ademodata.org%2C0003%3Aninjs_XYZ123
      */
     $uriPath = parse_url($uri, PHP_URL_PATH);
     $objectId = str_replace(ContentApiSdk::getAvailableEndpoints(), '', $uriPath);
     // Remove possible slashes and spaces, since we're working with urls
     $objectId = trim($objectId, '/ ');
     $objectId = urldecode($objectId);
     return $objectId;
 }
예제 #10
0
 /**
  * Check if the supplied endpoint is supported by the SDK.
  *
  * @param string $endpoint Endpoint url (/ will be automatically prepended)
  *
  * @return bool
  */
 private function isValidEndpoint($endpoint)
 {
     return !in_array(sprintf('/%s', ltrim($endpoint, '/')), ContentApiSdk::getAvailableEndpoints());
 }