Created
July 15, 2022 16:05
-
-
Save imonroe/666c0ef551a69e1e86c2c75b8a01d1e9 to your computer and use it in GitHub Desktop.
Fetch the contents of a single file from a Github repo using Guzzle and return as a string
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
<?php | |
use \GuzzleHttp\Client; | |
use \GuzzleHttp\Psr7; | |
use \GuzzleHttp\Exception\RequestException; | |
/** | |
* Use guzzle to get a single file from github and return it as a string. | |
* | |
* @param string $url The path of the file to fetch | |
* @return string | |
* @throws \Exception | |
*/ | |
public function fetchFileFromGithub(string $url):string | |
{ | |
try { | |
$response = $this->guzzle->request('GET', $url, [ | |
'auth' => [ | |
$this->githubUser, //<-- replace with your username | |
$this->githubToken, //<-- replace with your Github Personal Access Token | |
], | |
'headers' => [ | |
'Accept' => 'application/vnd.github.v3.raw', //<-- This gets you the raw contents of the file. | |
'User-Agent' => 'Your-Application', //<-- Github wants a user agent. | |
] | |
]); | |
} catch (ClientException $e) { | |
throw new \Exception('Guzzle problem: ', Psr7\Message::toString($e->getRequest()), Psr7\Message::toString($e->getResponse())); | |
} | |
if ($response->getStatusCode() == '200') { | |
return (string) $response->getBody(); | |
} else { | |
throw new \Exception('Guzzle bad response code'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment