AbstractWebflowApiField.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace App\Http\WebflowApi;
  3. use App\Http\WebflowApiClient;
  4. use RuntimeException;
  5. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  6. abstract class AbstractWebflowApiField extends AbstractWebflowApiClient {
  7. public $data;
  8. private $initialized = false;
  9. private $collections = [];
  10. public function __construct(WebflowApiClient $wfapi, ?array $data)
  11. {
  12. parent::__construct($wfapi);
  13. $this->data = $data;
  14. $this->initialized = !is_null($data);
  15. }
  16. public static function byId(AbstractWebflowApiClient $wfapi, string $id, array $options = []): AbstractWebflowApiField {
  17. $new = new static($wfapi->getClient(), null);
  18. $new->data['_id'] ??= $id;
  19. return $new;
  20. }
  21. public function isInitialized(): bool {
  22. return $this->initialized;
  23. }
  24. public function load(bool $reload = false): self {
  25. if ($this->initialized && !$reload)
  26. return $this;
  27. $req = $this->getClient()->get($this->getLoadScope(), $reload ? -1 : 300);
  28. if ($req->getStatusCode() == 200) {
  29. $this->initialized = true;
  30. $this->data = $req->toArray();
  31. }
  32. return $this;
  33. }
  34. abstract protected function getLoadScope(): string;
  35. protected function loadCollection(string $scope, string $as): ?AbstractWebflowApiCollection {
  36. if (isset($this->collection[$scope]))
  37. return $this->collections[$scope];
  38. if (!class_exists($as))
  39. throw new RuntimeException(sprintf("Collection-class %s does not exist.", $as));
  40. $entClass = rtrim($as, 's');
  41. if (!class_exists($entClass))
  42. throw new RuntimeException(sprintf("Entry-class %s does not exist.", $entClass));
  43. $req = $this->getClient()->get($scope);
  44. if ($req->getStatusCode() != 200)
  45. return null;
  46. $col = $this->collections[$scope] = new $as($this->getClient(), $this);
  47. foreach ($req->toArray() as $key => $entry) {
  48. if (isset(class_implements(get_class($col))[WebflowPaginationInterface::class])) {
  49. switch ($key) {
  50. case 'items':
  51. foreach ($entry as $item)
  52. $col->addEntry($col->createEntry($key, $item));
  53. break;
  54. default:
  55. $method = sprintf('set%s', ucfirst($key));
  56. if (method_exists($col, $method))
  57. [$col, $method]($entry);
  58. }
  59. } else {
  60. if (!is_null($entry = $col->createEntry($key, $entry)))
  61. $col->addEntry($entry);
  62. }
  63. }
  64. return $col;
  65. }
  66. }
  67. ?>