AbstractWebflowApiField.php 2.5 KB

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