Skip to content

Commit

Permalink
Update to 1
Browse files Browse the repository at this point in the history
  • Loading branch information
alecritson committed Jan 24, 2015
1 parent 8cb9bad commit 56d174c
Show file tree
Hide file tree
Showing 3 changed files with 108 additions and 94 deletions.
18 changes: 14 additions & 4 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ Placid allows you to consume RESTful APIs in your Statamic templates, using Guzz
- Access tokens

#### Updates / Changes
- **v1.0.0** - Version 1, fixes and enhancements
- **v0.9.2** - Refactoring and added [API](#api) methods
- **v0.9** - Bug fixes, refactoring, added [default](#defaults) config and reusable [access tokens](#access_tokens)
- **v0.8.9** - Bug fixes, refactoring and added [query](#queries) parameter
Expand All @@ -27,17 +28,17 @@ Copy the placid folder to your **_add-ons** directory and you're good to go
- **URL**: The URL to request
- **refresh** (number): The time in seconds until the cache refreshes (default is 7200 / 2 hours)
- **handle** (string) : The handle specified in the placid config
- **cache** (boolean) : Whether you want the request to be cached (default is true)
- **cache** (boolean) : Whether you want the request to be cached (default is 1)
- **method** (string) : You can set which method to use on the request, default is 'GET'
- **query** (string) : Add your queries here, see [queries](#queries) for more info

- **path** (string) : Add your own custom path, see [paths](#paths) for details

### Saved requests
You can set up requests for placid in **_config/add-ons/placid.yaml** like so:

dribbble:
url: 'http://api.dribbble.com/shots/everyone'
cache: true
cache: 1
refresh: 60

weather_api:
Expand Down Expand Up @@ -73,7 +74,7 @@ To use this plugin in your templates, simply use these tags:

### Example Code Block with manual URL

{{ placid url="http://api.dribbble.com/shots/everyone" cache="false" refresh="1200" }}
{{ placid url="http://api.dribbble.com/shots/everyone" cache="0" refresh="1200" }}
{{ shots }}
{{ title }}
{{ /shots }}
Expand All @@ -96,6 +97,15 @@ You can add queries to the request from the template using a `key:value` pattern

which will work out something like: `http://someapi.co.uk/feed?posts=5&limit=4`

### Paths
You can change the request path without having to keep overwritting the url.

{{ placid handle="stripe" path="/v1/customers/{{ id }}" }}
{{ email }}
{{ /placid }}

So if you have set the url to something like `https://api.stripe.com/v1/charges` in the config, it would be replaced as `https://api.stripe.com/v1/customers/123`, for example.

### Tokens
To reuse access tokens that are stored in your config simply add the `access_token` parameter with the name of the token you want from `placid_tokens` in the placid config file

Expand Down
175 changes: 88 additions & 87 deletions placid/pi.placid.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,25 @@ class Plugin_placid extends Plugin {

var $meta = array(
'name' => 'Placid',
'version' => '0.9.2',
'version' => '1.0.0',
'author' => 'Alec Ritson',
'author_url' => 'http://www.alecritson.co.uk'
);
var $options = array();
var $curlOpts = array();
var $params = array(
'cache',
'refresh',
'curl',
'access_token',
'query',
'path',
'headers',
'url',
);

var $method = 'GET';
var $curlOpts = null;
var $url = null;


public function index()
{
Expand All @@ -19,24 +32,25 @@ public function index()
$handle = $this->fetchParam('handle', null, null, false, false);
$request = $this->fetch($handle, null, null, false, false);

// Get the config from placid.yaml
$options = $this->fetch($handle, [], null, false, false);
$this->params = $this->fetchParams($this->params);

// Set our options
// ---------------------------------------------------------
$options = array(
'cache' => (bool) $this->_getOption($request, 'cache', true, null, true, true),
'cache_length' => (int) $this->_getOption($request, 'refresh', $this->fetch('placid_defaults')['refresh'] ?: 3200),
'method' => $this->_getOption($request, 'method', 'GET'),
'curl' => $this->_getOption($request, 'curl'),
'access_token' => $this->_getOption($request, 'access_token'),
'query' => $this->_getOption($request, 'query'),
'headers' => $this->_getOption($request, 'headers', null)
);
$options = array_merge($options,array_filter($this->params));


if(array_key_exists('url', $options))
{
$this->url = $options['url'];
}

if(!array_key_exists('refresh', $options))
{
$options['refresh'] = 500;
}

// We only want to try and explode the query if it's been set as a parameter,
// not when there is a record.
if($options['query'] && !$request)
if(array_key_exists('query', $options) && !$request)
{
// Get the query parameter as a string and explode it.
$queries = explode(',', $this->fetchParam('query'));
Expand All @@ -53,37 +67,8 @@ public function index()
}
}

// If there is no url specified, return (figure out why throw exception wasnt working...)
if( ! $url = $this->_getUrl($request) ) {
return 'Invalid or missing URL';
}

// Do the cache thing
// ---------------------------------------------------------
if($options['cache'])
{
// Set up the cached_id
$cached_id = base64_encode(urlencode($url));

// Try and get a cached response
$cached_response = $this->cache->getYAML($cached_id);

if($cached_response)
{
// If the cache is older than we want, delete it.
if($this->cache->getAge($cached_id) >= $options['cache_length'])
{
$this->cache->delete($cached_id);
}
else
{
return $cached_response;
}
}
}

// If an access token is set and there is no request we need to make sure the token exists in the config too.
if($options['access_token'] && !$request)
if(array_key_exists('access_token', $options) && !$request)
{
// Try and get the token from the config
try {
Expand All @@ -96,43 +81,80 @@ public function index()
$options['access_token'] = $token;
}

if($options['curl'])

if(array_key_exists('curl', $options))
{
// list($key, $value) = $options['curl'];
foreach($options['curl'] as $key => $value) {
$curlOpts[$key] = $value;
$this->curlOpts[$key] = $value;
}
}

if(array_key_exists('method', $options))
{
$this->method = $options['method'];
}


// Get the request object from the tasks
$request = $this->tasks->client()->request($url, $options['method']);
$request = $this->tasks->client()->request($this->url, $this->method);

if(array_key_exists('path', $options))
{
$request->setPath($options['path']);
}


// Do the cache thing
// ---------------------------------------------------------
if(array_key_exists('cache', $options) && $options['cache'])
{

// Set up the cached_id
$cached_id = base64_encode(urlencode($request->getUrl()));

// Try and get a cached response
$cached_response = $this->cache->getYAML($cached_id);

if($cached_response)
{
// If the cache is older than we want, delete it.
if($this->cache->getAge($cached_id) >= $options['refresh'])
{
$this->cache->delete($cached_id);
}
else
{
return $cached_response;
}
}
}

// Grab the query from the request
$query = $request->getQuery();


// Only do this if the query is an array
if($options['query'] && is_array($options['query']))
if(array_key_exists('query', $options)&& is_array($options['query']))
{
foreach ($options['query'] as $key => $value)
{
$query->set($key, $value);
}
}


// Do headers exist and is it an array?
if($options['headers'] && is_array($options['headers']))
if(array_key_exists('headers', $options) && is_array($options['headers']))
{

foreach ($options['headers'] as $key => $value)
{
$request->setHeader($key, $value);
}
}


// Do we have an access token we need to append?
if($options['access_token'])
if(array_key_exists('access_token', $options))
{
$query->set('access_token', $options['access_token']);
}
Expand All @@ -146,22 +168,19 @@ public function index()
**/

try {

$response = $this->tasks->client()->send($request, $curlOpts);


$response = $this->tasks->client()->send($request, $this->curlOpts);
$result = $response->json();

} catch(\Exception $e)
{
Log::error($e->getMessage());
// If an exception is thrown we set the result to null, this will help with the 'no_results' tag
// The error log bit should go here
$this->log->warn($e->getMessage());
$result = null;
}

// Do we need to cache the request?
if($options['cache']) {
$cacheId = base64_encode(urlencode($url));
if(array_key_exists('cache', $options)) {
$cacheId = base64_encode(urlencode($request->getUrl()));
$this->cache->putYAML($cacheId, $result);
}

Expand All @@ -174,31 +193,13 @@ public function index()
return $result;
}

/**
* Get the url from the tag/record
*
* @param array|null $record The record array from config
*
* @return string The url to request, null if empty
*/
private function _getUrl($record) {

if($record) {
// Does the request have a url?
if( array_key_exists('url', $record) ) {
$url = $record['url'];
} else {
$url = null;
}
} else {
$url = $this->fetchParam('url') ?: null;
}

return $url;
}

private function _getOption($request, $id, $default=NULL, $validity_check=NULL, $is_boolean=FALSE, $force_lower=FALSE)
public function fetchParams($args)
{
return isset($request[$id]) ? $request[$id] : $this->fetchParam($id, $default, $validity_check, $is_boolean, $force_lower);
foreach($args as $arg)
{

$options[$arg] = $this->fetchParam($arg, NULL, NULL, FALSE, FALSE);
}
return array_filter($options);
}
}
9 changes: 6 additions & 3 deletions placid/tasks.placid.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,13 @@ public function request($url, $method = 'GET')
* @return GuzzleHttp\Message\Response Object
**/

public function send($request, $options = array())
public function send($request, $options = null)
{

return $this->client->get($request->getUrl(), $options);
if($options)
{
return $this->client->get($request->getUrl(), $options);
}
return $this->client->send($request);
}

// public function
Expand Down

0 comments on commit 56d174c

Please sign in to comment.