Resource::prepareUri()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 0
cts 16
cp 0
rs 9.6666
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 6
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://github.com/flipbox/relay-hubspot/blob/master/LICENSE
6
 * @link       https://github.com/flipbox/relay-hubspot
7
 */
8
9
namespace Flipbox\Relay\HubSpot\Middleware;
10
11
use Flipbox\Relay\Middleware\AbstractMiddleware;
12
use Psr\Http\Message\RequestInterface;
13
use Psr\Http\Message\ResponseInterface;
14
15
/**
16
 * @author Flipbox Factory <[email protected]>
17
 * @since 1.0.0
18
 *
19
 * The anatomy of an API Resource Uri is constructed with this class.  This is the breakdown:
20
 * {scheme}://{host}/{node}/{version}/{path}
21
 */
22
class Resource extends AbstractMiddleware
23
{
24
    /**
25
     * The request method
26
     */
27
    public $method = 'GET';
28
29
    /**
30
     * The API Scheme
31
     */
32
    const SCHEME = 'https';
33
34
    /**
35
     * The API Host
36
     */
37
    const HOST = 'api.hubapi.com';
38
39
    /**
40
     * The resource path
41
     */
42
    public $resource;
43
44
    /**
45
     * Optional Query params
46
     *
47
     * @var array
48
     */
49
    public $params = [];
50
51
    /**
52
     * @inheritdoc
53
     */
54
    public function __invoke(
55
        RequestInterface $request,
56
        ResponseInterface $response,
57
        callable $next = null
58
    ) {
59
        parent::__invoke($request, $response, $next);
60
61
        $request = $this->prepareUri(
62
            $request->withMethod($this->method)
63
        );
64
65
        return $next($request, $response);
66
    }
67
68
    /**
69
     * @param RequestInterface $request
70
     * @return RequestInterface
71
     */
72
    protected function prepareUri(RequestInterface $request)
73
    {
74
        $uri = $request->getUri()
75
            ->withHost(static::HOST)
76
            ->withScheme(static::SCHEME);
77
78
        if (!empty($this->params)) {
79
            $uri = $uri->withQuery(
80
                http_build_query($this->params, null, '&', PHP_QUERY_RFC3986)
81
            );
82
        }
83
84
        return $request->withUri(
85
            $uri->withPath(
86
                $this->getPath()
87
            )
88
        );
89
    }
90
91
    /**
92
     * @return string
93
     */
94
    protected function getPath(): string
95
    {
96
        return "{$this->resource}";
97
    }
98
}
99