Passed
Pull Request — master (#8)
by Thomas
01:35
created

ReadOperation   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 24
c 1
b 0
f 0
dl 0
loc 55
rs 10

3 Methods

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