WebflowApiClient.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Http;
  3. use Symfony\Component\Cache\Adapter\TraceableAdapter;
  4. use Symfony\Component\HttpClient\CachingHttpClient;
  5. use Symfony\Component\HttpClient\HttpClient;
  6. use Symfony\Component\HttpClient\Response\MockResponse;
  7. use Symfony\Component\HttpKernel\HttpCache\Store;
  8. use Symfony\Contracts\Cache\ItemInterface;
  9. use Symfony\Contracts\HttpClient\HttpClientInterface;
  10. use Symfony\Contracts\HttpClient\ResponseInterface;
  11. class WebflowApiClient {
  12. private $client;
  13. private $cache;
  14. private $url;
  15. private $options = [];
  16. public function __construct(TraceableAdapter $cache, string $token, string $api_url, string $version = '1.0.0', string $cache_dir) {
  17. $this->url = $api_url;
  18. $this->options = [
  19. 'auth_bearer' => $token,
  20. 'headers' => [
  21. 'accept-version' => $version,
  22. ],
  23. ];
  24. $this->client = HttpClient::createForBaseUri(
  25. sprintf('https://%s', $api_url),
  26. $this->options
  27. );
  28. $this->cache = $cache;
  29. dump($this->cache);
  30. }
  31. public function scopeFromBase(string $scope): string {
  32. return sprintf('https://%s/%s', $this->url, ltrim($scope, '/'));
  33. }
  34. private function scopeId(string $scope_string): string {
  35. return "webflow_api_" . sha1($scope_string);
  36. }
  37. public function get(string $scope, int $ttl = 300): ResponseInterface {
  38. $id = $this->scopeId($scope);
  39. if ($ttl <= 0)
  40. return $this->client->request('GET',
  41. $this->scopeFromBase($scope),
  42. );
  43. $item = $this->cache->get($id, function (ItemInterface $item) use ($scope, $ttl) {
  44. $item->expiresAfter($ttl);
  45. $response = $this->client->request('GET',
  46. $this->scopeFromBase($scope),
  47. );
  48. if ($response->getStatusCode() >= 300)
  49. return;
  50. $item->set([
  51. 'header' => $response->getHeaders(),
  52. 'content' => $response->getContent(),
  53. ]);
  54. $this->cache->save($item);
  55. return $item->get();
  56. });
  57. $this->cache->commit();
  58. return MockResponse::fromRequest('GET', $scope, $item['header'], new MockResponse($item['content']));
  59. }
  60. }
  61. ?>