CreateOperation::create()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 10
rs 10
cc 4
nc 4
nop 1
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\Model\Operation;
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
    /**
28
     * @var string[]
29
     */
30
    private array $arguments;
31
32
    public function __construct(
33
        RequestBuilder $requestBuilder,
34
        DataObjectFactory $dataObjectFactory,
35
        string $entityType,
36
        array $arguments = []
37
    ) {
38
        $this->requestBuilder = $requestBuilder;
39
        $this->dataObjectFactory = $dataObjectFactory;
40
        $this->entityType = $entityType;
41
        $this->arguments = $arguments;
42
    }
43
44
    public function create(DataObjectInterface $dataObject): DataObjectInterface
45
    {
46
        try {
47
            return $this->dataObjectFactory->create($this->entityType, $this->saveEntity($dataObject)->getResult());
48
        } catch (InvalidArgumentException $e) {
49
            throw new CouldNotSaveException($e->getMessage(), $e->getCode(), $e);
50
        } catch (InvalidRequestException $e) {
51
            throw new CouldNotSaveException($e->getMessage(), $e->getCode(), $e);
52
        } catch (Exception $e) {
53
            throw new CouldNotSaveException('Could not create the entity.', $e->getCode(), $e);
54
        }
55
    }
56
57
    /**
58
     * @param DataObjectInterface $dataObject
59
     * @return ResponseInterface
60
     * @throws Exception
61
     * @throws InvalidArgumentException
62
     * @throws InvalidRequestException
63
     */
64
    private function saveEntity(DataObjectInterface $dataObject): ResponseInterface
65
    {
66
        return $this->requestBuilder
67
            ->setEntityType($this->entityType)
68
            ->setMethod(RequestBuilder::HTTP_POST)
69
            ->setArguments($this->arguments)
70
            ->setFields($dataObject->toArray())
71
            ->create()
72
            ->execute();
73
    }
74
}
75