123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- <?php
- namespace App\Http\WebflowApi;
- use App\Http\WebflowApiClient;
- use RuntimeException;
- abstract class AbstractWebflowApiField extends AbstractWebflowApiClient {
- public $data;
- private $initialized = false;
- private $collections = [];
- public function __construct(WebflowApiClient $wfapi, ?array $data)
- {
- parent::__construct($wfapi);
- $this->data = $data;
- $this->initialized = !is_null($data);
- }
- public static function byId(WebflowApiClient $wfapi, string $id): AbstractWebflowApiField {
- $new = new static($wfapi, null);
- $new->data['_id'] ??= $id;
- return $new;
- }
- public function isInitialized(): bool {
- return $this->initialized;
- }
- public function load(): self {
- if ($this->initialized)
- return $this;
- $req = $this->getClient()->get($this->getLoadScope());
- if ($req->getStatusCode() == 200) {
- $this->initialized = true;
- $this->data = $req->toArray();
- }
- return $this;
- }
- abstract protected function getLoadScope(): string;
- protected function loadCollection(string $scope, string $as): ?AbstractWebflowApiCollection {
- if (isset($this->collection[$scope]))
- return $this->collections[$scope];
- if (!class_exists($as))
- throw new RuntimeException(sprintf("Collection-class %s does not exist.", $as));
- $entClass = rtrim($as, 's');
- if (!class_exists($entClass))
- throw new RuntimeException(sprintf("Entry-class %s does not exist.", $entClass));
- $req = $this->getClient()->get($scope);
- if ($req->getStatusCode() != 200)
- return null;
- $col = $this->collections[$scope] = new $as($this->getClient(), $this);
- foreach ($req->toArray() as $key => $entry) {
- if (isset(class_implements(get_class($col))[WebflowPaginationInterface::class])) {
- switch ($key) {
- case 'items':
- foreach ($entry as $item)
- $col->addEntry($col->createEntry($key, $item));
- break;
- default:
- $method = sprintf('set%s', ucfirst($key));
- if (method_exists($col, $method))
- [$col, $method]($entry);
- }
- } else {
- if (!is_null($entry = $col->createEntry($key, $entry)))
- $col->addEntry($entry);
- }
- }
- return $col;
- }
- }
- ?>
|