|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Copyright © Thomas Klein, All rights reserved. |
| 4 | + * See LICENSE bundled with this library for license details. |
| 5 | + */ |
| 6 | +declare(strict_types=1); |
| 7 | + |
| 8 | +namespace Zoho\Desk\Service; |
| 9 | + |
| 10 | +use Zoho\Desk\Client\RequestBuilder; |
| 11 | +use Zoho\Desk\Client\ResponseInterface; |
| 12 | +use Zoho\Desk\Exception\CouldNotSaveException; |
| 13 | +use Zoho\Desk\Exception\Exception; |
| 14 | +use Zoho\Desk\Exception\InvalidArgumentException; |
| 15 | +use Zoho\Desk\Exception\InvalidRequestException; |
| 16 | +use Zoho\Desk\Model\DataObjectFactory; |
| 17 | +use Zoho\Desk\Model\DataObjectInterface; |
| 18 | + |
| 19 | +final class CreateOperation implements CreateOperationInterface |
| 20 | +{ |
| 21 | + private RequestBuilder $requestBuilder; |
| 22 | + |
| 23 | + private DataObjectFactory $dataObjectFactory; |
| 24 | + |
| 25 | + private string $entityType; |
| 26 | + |
| 27 | + private ?string $path; |
| 28 | + |
| 29 | + /** |
| 30 | + * @var string[] |
| 31 | + */ |
| 32 | + private array $arguments; |
| 33 | + |
| 34 | + public function __construct( |
| 35 | + RequestBuilder $requestBuilder, |
| 36 | + DataObjectFactory $dataObjectFactory, |
| 37 | + string $entityType, |
| 38 | + ?string $path = null, |
| 39 | + array $arguments = [] |
| 40 | + ) { |
| 41 | + $this->requestBuilder = $requestBuilder; |
| 42 | + $this->dataObjectFactory = $dataObjectFactory; |
| 43 | + $this->entityType = $entityType; |
| 44 | + $this->path = $path; |
| 45 | + $this->arguments = $arguments; |
| 46 | + } |
| 47 | + |
| 48 | + public function create(DataObjectInterface $dataObject, array $bind = []): DataObjectInterface |
| 49 | + { |
| 50 | + try { |
| 51 | + return $this->dataObjectFactory->create($this->entityType, $this->saveEntity($dataObject)->getResult()); |
| 52 | + } catch (InvalidArgumentException $e) { |
| 53 | + throw new CouldNotSaveException($e->getMessage(), $e->getCode(), $e); |
| 54 | + } catch (InvalidRequestException $e) { |
| 55 | + throw new CouldNotSaveException($e->getMessage(), $e->getCode(), $e); |
| 56 | + } catch (Exception $e) { |
| 57 | + throw new CouldNotSaveException('Could not create the entity.', $e->getCode(), $e); |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * @throws Exception |
| 63 | + * @throws InvalidArgumentException |
| 64 | + * @throws InvalidRequestException |
| 65 | + */ |
| 66 | + private function saveEntity(DataObjectInterface $dataObject, array $bind = []): ResponseInterface |
| 67 | + { |
| 68 | + return $this->requestBuilder |
| 69 | + ->setPath($this->path ?? $this->entityType, $bind) |
| 70 | + ->setMethod(RequestBuilder::HTTP_POST) |
| 71 | + ->setArguments($this->arguments) |
| 72 | + ->setFields($dataObject->toArray()) |
| 73 | + ->create() |
| 74 | + ->execute(); |
| 75 | + } |
| 76 | +} |
0 commit comments