<?php
use ForestAdmin\AgentPHP\DatasourceToolkit\Collection;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Caller;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Contracts\DatasourceContract;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\Filters\Filter;
use ForestAdmin\AgentPHP\DatasourceToolkit\Components\Query\Projection\Projection;
use ForestAdmin\AgentPHP\DatasourceToolkit\Schema\ColumnSchema;
use GuzzleHttp\Client;
class MyCollection extends Collection
{
public function __construct(DatasourceContract $datasource)
{
parent::__construct(
$datasource,
'MyCollection'
);
$this->addField('id', new ColumnSchema(
// ...
isReadOnly: true,
));
$this->addField('title', new ColumnSchema(
// ...
isReadOnly: false,
));
$this->client = new Client([
'base_uri' => 'https://my-api/',
'timeout' => 5.0,
]);
}
public function create(Caller $caller, array $records)
{
$results = [];
foreach ($records as $record) {
try {
$response = $this->httpClient->post(
'my-collection',
['json' => $record]
);
$results[] = json_decode($response->getBody()->getContents(), true);
} catch (\Exception $e) {
throw new \Exception("Error creating record: " . $e->getMessage(), 0, $e);
}
}
return $results;
}
public function update(Caller $caller, Filter $filter, array $patch)
{
$recordIds = $this->list($caller, $filter, new Projection('id'));
foreach ($recordIds as $record) {
try {
$this->client->patch("my-collection/{$record['id']}", [
'json' => $patch,
]);
} catch (\Exception $e) {
throw new \Exception("Error updating record {$record['id']}: " . $e->getMessage());
}
}
}
public function delete(Caller $caller, Filter $filter): void
{
$recordIds = $this->list($caller, $filter, new Projection('id'));
foreach ($recordIds as $record) {
try {
$this->client->delete("my-collection/{$record['id']}");
} catch (\Exception $e) {
throw new \Exception("Error updating record {$record['id']}: " . $e->getMessage());
}
}
}
}