Fully working version of working with products

This commit is contained in:
Tim
2021-10-04 00:37:36 +02:00
parent 44bd43128b
commit 22c4101729
6 changed files with 305 additions and 51 deletions

View File

@ -4,6 +4,10 @@
namespace Ardent\GrocyApi;
use Ardent\GrocyApi\Objects\AbstractApiObject;
use Ardent\GrocyApi\Objects\ObjectTransformer;
use Ardent\GrocyApi\Objects\ProductsObject;
class GrocyClient
{
private Client $client;
@ -13,23 +17,67 @@ class GrocyClient
$this->client = new Client($host, $apikey);
}
private function getObjects(string $object, array $query = [], $order = null, $limit = null, $offset = null)
/**
* @return AbstractApiObject[]
*/
private function getObjects(string $entity, array $query = [], string $order = null, int $limit = null, int $offset = null)
{
return $this->client->get(sprintf('objects/%s', $object), compact('order', 'limit', 'offset'));
$array = $this->client->get(sprintf('objects/%s', $entity), compact('order', 'limit', 'offset'));
$objects = [];
foreach ($array as $rawObject) {
$objects[] = ObjectTransformer::denormalize($rawObject, $entity);
}
return $objects;
}
private function getObject(string $object, int $id)
private function getObject(string $entity, int $id): AbstractApiObject
{
return $this->client->get(sprintf('%s/%s', $object, $id));
$rawObject = $this->client->get(sprintf('objects/%s/%s', $entity, $id));
return ObjectTransformer::denormalize($rawObject, $entity);
}
public function getAllProducts()
private function setObject(string $entity, AbstractApiObject $object, int $id = null): void
{
$this->client->put(
sprintf('objects/%s/%s', $entity, $id),
ObjectTransformer::normalize($object)
);
}
/**
* @return int the id of the created object
*/
private function addObject(string $entity, AbstractApiObject $object): int
{
$data = $this->client->post(
sprintf('objects/%s', $entity),
ObjectTransformer::normalize($object)
);
return $data['created_object_id'];
dd($data);
}
/**
* @return ProductsObject[]
*/
public function getProducts(): array
{
return $this->getObjects('products');
}
public function getProduct(int $id)
public function getProduct(int $id): ProductsObject
{
$this->getObject('products', $id);
return $this->getObject('products', $id);
}
public function setProduct(ProductsObject $product, int $id): void
{
$this->setObject('products', $product, $id);
}
public function addProduct(ProductsObject $product): int
{
return $this->addObject('products', $product);
}
}