Return null of trying to get nonexisting object

This commit is contained in:
Tim 2021-10-12 23:38:02 +02:00
parent 136681b675
commit 653744b751

View File

@ -9,6 +9,7 @@ use Ardent\GrocyApi\Objects\ObjectTransformer;
use Ardent\GrocyApi\Objects\ProductsObject;
use Ardent\GrocyApi\Objects\QuantityUnitsObject;
use Ardent\GrocyApi\Objects\ShoppingListObject;
use GuzzleHttp\Exception\ClientException;
class GrocyClient
{
@ -55,7 +56,7 @@ class GrocyClient
return $this->getObjects('shopping_list');
}
public function getProduct(int $id): ProductsObject
public function getProduct(int $id): ?ProductsObject
{
return $this->getObject('products', $id);
}
@ -80,13 +81,6 @@ class GrocyClient
$this->client->put(sprintf('userfields/%s/%s', $object::getEntity(), $object->getId()), $userfields);
}
public function setProductPicnicId(int $productId, int $picnicId)
{
$this->setUserFieldsForObject((new ProductsObject())->setId($productId), [
'picnic' => $picnicId,
]);
}
public function uploadPicture(string $fileName, string $image, string $group = 'productpictures')
{
$this->client->putFile(sprintf('files/%s/%s', $group, base64_encode($fileName)), $image);
@ -111,9 +105,13 @@ class GrocyClient
return $objects;
}
private function getObject(string $entity, int $id): AbstractApiObject
private function getObject(string $entity, int $id): ?AbstractApiObject
{
$rawObject = $this->client->get(sprintf('objects/%s/%s', $entity, $id));
try {
$rawObject = $this->client->get(sprintf('objects/%s/%s', $entity, $id));
} catch (ClientException) {
return null;
}
return ObjectTransformer::denormalize($rawObject, $entity);
}