Skip to content

Commit

Permalink
Added fetch() twig extension
Browse files Browse the repository at this point in the history
  • Loading branch information
lukeyouell authored Feb 24, 2018
1 parent 125c864 commit 84b2d75
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/Fetch.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
namespace lukeyouell\fetch;

use lukeyouell\fetch\variables\FetchVariable;
use lukeyouell\fetch\twigextensions\FetchTwigExtension;

use Craft;
use craft\base\Plugin;
Expand Down Expand Up @@ -49,6 +50,8 @@ public function init()
parent::init();
self::$plugin = $this;

Craft::$app->view->registerTwigExtension(new FetchTwigExtension());

Event::on(
CraftVariable::class,
CraftVariable::EVENT_INIT,
Expand Down
59 changes: 59 additions & 0 deletions src/twigextensions/FetchTwigExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php
/**
* Fetch plugin for Craft CMS 3.x
*
* Utilise the Guzzle HTTP client from within your Craft templates.
*
* @link https://github.com/lukeyouell
* @copyright Copyright (c) 2018 Luke Youell
*/

namespace lukeyouell\fetch\twigextensions;

use lukeyouell\fetch\Fetch;

use Craft;

/**
* @author Luke Youell
* @package Fetch
* @since 1.1.0
*/
class FetchTwigExtension extends \Twig_Extension
{
public function getName()
{
return 'Fetch';
}

public function getFunctions()
{
return [
new \Twig_SimpleFunction('fetch', [$this, 'fetch']),
];
}

public function fetch($client, $method, $destination, $request = [])
{
$client = new \GuzzleHttp\Client($client);

try {

$response = $client->request($method, $destination, $request);

return [
'statusCode' => $response->getStatusCode(),
'reason' => $response->getReasonPhrase(),
'body' => json_decode($response->getBody(), true)
];

} catch (\Exception $e) {

return [
'error' => true,
'reason' => $e->getMessage()
];

}
}
}

0 comments on commit 84b2d75

Please sign in to comment.