BaseApi::url()   A
last analyzed

Complexity

Conditions 6
Paths 8

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 6
eloc 6
c 3
b 0
f 0
nc 8
nop 1
dl 0
loc 14
ccs 0
cts 9
cp 0
crap 42
rs 9.2222
1
<?php
2
3
namespace Distilleries\Contentful\Api;
4
5
use GuzzleHttp\ClientInterface;
6
use Psr\Http\Message\ResponseInterface;
7
8
abstract class BaseApi
9
{
10
    /**
11
     * HTTP client implementation.
12
     *
13
     * @var \GuzzleHttp\ClientInterface
14
     */
15
    protected $client;
16
17
    /**
18
     * Contentful configuration.
19
     *
20
     * @var array
21
     */
22
    protected $config;
23
24
    /**
25
     * API base URL.
26
     *
27
     * @var string
28
     */
29
    protected $baseUrl;
30
31
    /**
32
     * API preview Base URL.
33
     *
34
     * @var string
35
     */
36
    protected $previewBaseUrl;
37
38
    /**
39
     * BaseApi constructor.
40
     *
41
     * @param  \GuzzleHttp\ClientInterface  $client
42
     * @return void
43
     */
44
    public function __construct(ClientInterface $client)
45
    {
46
        $this->client = $client;
47
48
        $this->config = config('contentful', []);
49
        $this->config = ! is_array($this->config) ? (array)$this->config : $this->config;
50
    }
51
52
    /**
53
     * Return endpoint URL.
54
     *
55
     * @param  string  $endpoint
56
     * @return string
57
     */
58
    protected function url($endpoint): string
59
    {
60
        $baseUrl = rtrim($this->baseUrl, '/');
61
62
        // Mandatory to make sure we have the last version modified by the scripts
63
        $this->config['use_preview'] = config('contentful.use_preview');
64
65
        if ((isset($this->config['use_preview']) && $this->config['use_preview'] == true) && ! empty($this->previewBaseUrl)) {
66
            $baseUrl = rtrim($this->previewBaseUrl, '/');
67
        }
68
69
        $environment = (isset($this->config['use_environment']) && $this->config['use_environment'] == true) ? '/environments/' . $this->config['environment'] . '/' : '/';
70
71
        return $baseUrl . '/spaces/' . $this->config['space_id'] . $environment . trim($endpoint, '/');
72
    }
73
74
    /**
75
     * Decode given response.
76
     *
77
     * @param  \Psr\Http\Message\ResponseInterface  $response
78
     * @return array
79
     */
80
    protected function decodeResponse(ResponseInterface $response): array
81
    {
82
        return json_decode($response->getBody()->getContents(), true);
83
    }
84
}
85