12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- <?php
- namespace App\Http\WebflowApi;
- use App\Http\WebflowApiClient;
- use RuntimeException;
- use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
- 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(AbstractWebflowApiClient $wfapi, string $id, array $options = []): AbstractWebflowApiField {
- $new = new static($wfapi->getClient(), null);
- $new->data['_id'] ??= $id;
- return $new;
- }
- public function isInitialized(): bool {
- return $this->initialized;
- }
- public function load(bool $reload = false): self {
- if ($this->initialized && !$reload)
- return $this;
- $req = $this->getClient()->get($this->getLoadScope(), $reload ? -1 : 300);
- 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;
- }
- }
- ?>
|