Completed
Push — master ( 5c5133...4bc4b0 )
by Marcin
02:40
created

Client::curlRequest()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 4.0218

Importance

Changes 0
Metric Value
dl 0
loc 26
ccs 16
cts 18
cp 0.8889
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 18
nc 4
nop 1
crap 4.0218
1
<?php
2
/**
3
 * MOJEPANSTWO-API
4
 *
5
 * Copyright © 2017 pudelek.org.pl
6
 *
7
 * @license MIT License (MIT)
8
 *
9
 * For the full copyright and license information, please view source file
10
 * that is bundled with this package in the file LICENSE
11
 *
12
 * @author  Marcin Pudełek <[email protected]>
13
 */
14
declare (strict_types=1);
15
16
namespace mrcnpdlk\MojePanstwo;
17
18
19
use mrcnpdlk\Psr16Cache\Adapter;
20
use Psr\Log\LoggerInterface;
21
use Psr\Log\NullLogger;
22
use Psr\SimpleCache\CacheInterface;
23
24
class Client
25
{
26
    /**
27
     * @var string
28
     */
29
    private $sApiUrl;
30
    /**
31
     * Cache handler
32
     *
33
     * @var CacheInterface
34
     */
35
    private $oCache;
36
    /**
37
     * @var Adapter
38
     */
39
    private $oCacheAdapter;
40
    /**
41
     * Logger handler
42
     *
43
     * @var \Psr\Log\LoggerInterface
44
     */
45
    private $oLogger;
46
47
    /**
48
     * Client constructor.
49
     *
50
     * @param string $apiUrl
51
     */
52 13
    public function __construct(string $apiUrl = 'https://api-v3.mojepanstwo.pl/')
53
    {
54 13
        $this->sApiUrl = $apiUrl;
55 13
        $this->setLoggerInstance();
56 13
        $this->setCacheInstance();
57 13
    }
58
59
    /**
60
     * @param string $url
61
     *
62
     * @return mixed
63
     * @throws \mrcnpdlk\MojePanstwo\Exception
64
     */
65 8
    private function curlRequest(string $url)
66
    {
67 8
        $ch = curl_init();
68
69 8
        curl_setopt($ch, CURLOPT_URL, $url);
70 8
        curl_setopt($ch, CURLOPT_HEADER, 0);
71 8
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
72 8
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
73 8
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
74 8
        $output = curl_exec($ch);
75 8
        if (curl_errno($ch)) {
76
            throw new Exception('Request Error: ' . curl_error($ch));
77
        }
78 8
        $respCode = curl_getinfo($ch, \CURLINFO_HTTP_CODE);
79 8
        if ($respCode !== 200) {
80 1
            throw new Exception('Request Error: ' . $respCode);
81
        }
82 7
        curl_close($ch);
83
84 7
        $resObj = json_decode($output);
85 7
        if (\JSON_ERROR_NONE !== json_last_error()) {
86
            throw new Exception('Unable to parse response body into JSON: ' . json_last_error());
87
        }
88
89 7
        return $resObj;
90
    }
91
92
    /**
93
     * Get logger instance
94
     *
95
     * @return \Psr\Log\LoggerInterface
96
     */
97 10
    public function getLogger()
98
    {
99 10
        return $this->oLogger;
100
    }
101
102
    /**
103
     * @param string                                  $sPrefixedContext
104
     * @param string|null                             $id
105
     * @param \mrcnpdlk\MojePanstwo\QueryBuilder|null $oParams
106
     *
107
     * @return \stdClass
108
     * @internal param string $context
109
     */
110 8
    public function request(string $sPrefixedContext, string $id = null, QueryBuilder $oParams = null)
111
    {
112
        $tPath = [
113 8
            rtrim($this->sApiUrl, '/'),
114 8
            trim($sPrefixedContext, '/'),
115
        ];
116 8
        if (!is_null($id)) {
117 3
            $tPath[] = $id;
118
        }
119 8
        if (!is_null($oParams)) {
120 7
            $tPath[] = '?' . $oParams->getQuery();
121
        }
122 8
        $url = implode('/', $tPath);
123
124 8
        $this->getLogger()->debug(sprintf('REQ: %s', $url));
125
126 8
        return $this->oCacheAdapter->useCache(
127 8
            function () use ($url) {
128 8
                return $this->curlRequest($url);
129 8
            },
130 8
            [$url],
131 8
            60 * 60 * 24
132
        );
133
    }
134
135
    /**
136
     * Setting Cache Adapter
137
     *
138
     * @return $this
139
     */
140 13
    private function setCacheAdapter()
141
    {
142 13
        $this->oCacheAdapter = new Adapter($this->oCache, $this->oLogger);
143
144 13
        return $this;
145
    }
146
147
    /**
148
     * Set Cache handler (PSR-16)
149
     *
150
     * @param \Psr\SimpleCache\CacheInterface|null $oCache
151
     *
152
     * @return \mrcnpdlk\MojePanstwo\Client
153
     * @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-16-simple-cache.md PSR-16
154
     */
155 13
    public function setCacheInstance(CacheInterface $oCache = null)
156
    {
157 13
        $this->oCache = $oCache;
158 13
        $this->setCacheAdapter();
159
160 13
        return $this;
161
    }
162
163
    /**
164
     * Set Logger handler (PSR-3)
165
     *
166
     * @param \Psr\Log\LoggerInterface|null $oLogger
167
     *
168
     * @return $this
169
     */
170 13
    public function setLoggerInstance(LoggerInterface $oLogger = null)
171
    {
172 13
        $this->oLogger = $oLogger ?: new NullLogger();
173 13
        $this->setCacheAdapter();
174
175 13
        return $this;
176
    }
177
178
}
179