diff --git a/README.md b/README.md index a3eeeff..b5e35f8 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,29 @@ $client->getStories( $data = $client->getStoryContent(); ``` +### Load a list of datasource entries + +```php +// Require composer autoload +require 'vendor/autoload.php'; + +// Initialize +$client = new \Storyblok\Client('your-storyblok-private-token'); + +// Optionally set a cache +$client->setCache('filesytem', array('path' => 'cache')); + +// Get all Stories that start with news +$client->getDatasourceEntries('categories'); + +// will return the whole response +$data = $client->getBody(); + +// will return as ['name']['value'] Array for easy access +$nameValueArray = $client->getAsNameValueArray(); + +``` + ## Clearing the cache (Optionally if using setCache) In order to flush the cache when the user clicks publish, you need to listen to the published event in javascript or define a webhook in the space settings that clears the cache on your server. diff --git a/src/Storyblok/Client.php b/src/Storyblok/Client.php index e0a88dc..7a4440a 100644 --- a/src/Storyblok/Client.php +++ b/src/Storyblok/Client.php @@ -373,6 +373,48 @@ public function getStories($options = array()) return $this; } + /** + * Gets a list of datasource entries + * + * @param string $slug Slug + * @param array $options Options + * @return \Storyblok\Client + */ + public function getDatasourceEntries($slug, $options = array()) + { + $version = 'published'; + $endpointUrl = 'datasource_entries/'; + + if ($this->editModeEnabled) { + $version = 'draft'; + } + + $key = 'datasource_entries/' . $slug . '/' . serialize($options); + + $this->reCacheOnPublish($key); + + if ($version == 'published' && $this->cache && $cachedItem = $this->cache->load($key)) { + $this->responseBody = (array) $cachedItem; + } else { + $options = array_merge($options, array( + 'token' => $this->apiKey, + 'version' => $version, + 'cache_version' => $this->cacheVersion, + 'datasource' => $slug + )); + + $response = $this->get($endpointUrl, $options); + + $this->responseBody = $response->httpResponseBody; + + if ($this->cache && $version == 'published') { + $this->cache->save($this->responseBody, $key); + } + } + + return $this; + } + /** * Gets a list of links * @@ -429,10 +471,31 @@ public function getBody() return array(); } + /** + * Transforms datasources into a ['name']['value'] array. + * + * @return array + */ + public function getAsNameValueArray() + { + if (!isset($this->responseBody)) { + return array(); + } + + $array = []; + + foreach ($this->responseBody['datasource_entries'] as $entry) { + if (!isset($array[$entry['name']])) { + $array[$entry['name']] = $entry['value']; + } + } + + return $array; + } + /** * Transforms links into a tree * - * @param string $slug Slug * @return \Client */ public function getAsTree()