ReadOperation::get()   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\CouldNotReadException;
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
use function array_merge;
19
20
final class ReadOperation implements ReadOperationInterface
21
{
22
    private RequestBuilder $requestBuilder;
23
24
    private DataObjectFactory $dataObjectFactory;
25
26
    private string $entityType;
27
28
    /**
29
     * @var string[]
30
     */
31
    private array $arguments;
32
33
    public function __construct(
34
        RequestBuilder $requestBuilder,
35
        DataObjectFactory $dataObjectFactory,
36
        string $entityType,
37
        array $arguments = []
38
    ) {
39
        $this->requestBuilder = $requestBuilder;
40
        $this->dataObjectFactory = $dataObjectFactory;
41
        $this->entityType = $entityType;
42
        $this->arguments = $arguments;
43
    }
44
45
    public function get(int $entityId): DataObjectInterface
46
    {
47
        try {
48
            return $this->dataObjectFactory->create($this->entityType, $this->fetchEntity($entityId)->getResult());
49
        } catch (InvalidArgumentException $e) {
50
            throw new CouldNotReadException($e->getMessage(), $e->getCode(), $e);
51
        } catch (InvalidRequestException $e) {
52
            throw new CouldNotReadException($e->getMessage(), $e->getCode(), $e);
53
        } catch (Exception $e) {
54
            throw new CouldNotReadException('Could not fetch the entity.', $e->getCode(), $e);
55
        }
56
    }
57
58
    /**
59
     * @param int $entityId
60
     * @return ResponseInterface
61
     * @throws Exception
62
     * @throws InvalidArgumentException
63
     * @throws InvalidRequestException
64
     */
65
    private function fetchEntity(int $entityId): ResponseInterface
66
    {
67
        return $this->requestBuilder
68
            ->setEntityType($this->entityType)
69
            ->setMethod(RequestBuilder::HTTP_GET)
70
            ->setArguments(array_merge([$entityId], $this->arguments))
71
            ->create()
72
            ->execute();
73
    }
74
}
75