12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- <?php
- namespace App\Http;
- use Symfony\Component\Cache\Adapter\TraceableAdapter;
- use Symfony\Component\HttpClient\CachingHttpClient;
- use Symfony\Component\HttpClient\HttpClient;
- use Symfony\Component\HttpClient\Response\MockResponse;
- use Symfony\Component\HttpKernel\HttpCache\Store;
- use Symfony\Contracts\Cache\ItemInterface;
- use Symfony\Contracts\HttpClient\HttpClientInterface;
- use Symfony\Contracts\HttpClient\ResponseInterface;
- class WebflowApiClient {
- private $client;
- private $cache;
- private $url;
- private $options = [];
- public function __construct(TraceableAdapter $cache, string $token, string $api_url, string $version = '1.0.0', string $cache_dir) {
- $this->url = $api_url;
- $this->options = [
- 'auth_bearer' => $token,
- 'headers' => [
- 'accept-version' => $version,
- ],
- ];
- $this->client = HttpClient::createForBaseUri(
- sprintf('https://%s', $api_url),
- $this->options
- );
-
- $this->cache = $cache;
- dump($this->cache);
- }
- public function scopeFromBase(string $scope): string {
- return sprintf('https://%s/%s', $this->url, ltrim($scope, '/'));
- }
- private function scopeId(string $scope_string): string {
- return "webflow_api_" . sha1($scope_string);
- }
- public function get(string $scope, int $ttl = 300): ResponseInterface {
- $id = $this->scopeId($scope);
- if ($ttl <= 0)
- return $this->client->request('GET',
- $this->scopeFromBase($scope),
- );
- $item = $this->cache->get($id, function (ItemInterface $item) use ($scope, $ttl) {
- $item->expiresAfter($ttl);
- $response = $this->client->request('GET',
- $this->scopeFromBase($scope),
- );
- if ($response->getStatusCode() >= 300)
- return;
- $item->set([
- 'header' => $response->getHeaders(),
- 'content' => $response->getContent(),
- ]);
- $this->cache->save($item);
- return $item->get();
- });
- $this->cache->commit();
- return MockResponse::fromRequest('GET', $scope, $item['header'], new MockResponse($item['content']));
- }
- }
- ?>
|