-
-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
125c864
commit 84b2d75
Showing
2 changed files
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
]; | ||
|
||
} | ||
} | ||
} |