Completed
Push — master ( a53fa0...b35614 )
by Marcin
03:36
created

Client::setCacheAdapter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * TERYT-API
4
 *
5
 * Copyright (c) 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
 */
15
16
declare (strict_types=1);
17
18
namespace mrcnpdlk\Teryt;
19
20
use mrcnpdlk\Psr16Cache\Adapter;
21
use mrcnpdlk\Teryt\Exception\Connection;
22
use mrcnpdlk\Teryt\Exception\Response;
23
use Psr\Log\LoggerInterface;
24
use Psr\Log\NullLogger;
25
use Psr\SimpleCache\CacheInterface;
26
27
/**
28
 * Class Client
29
 *
30
 * @package mrcnpdlk\Teryt
31
 */
32
class Client
33
{
34
    const SERVICE_URL_TEST      = 'https://uslugaterytws1test.stat.gov.pl/wsdl/terytws1.wsdl';
35
    const SERVICE_URL           = 'https://uslugaterytws1.stat.gov.pl/wsdl/terytws1.wsdl';
36
    const SERVICE_USER_TEST     = 'TestPubliczny';
37
    const SERVICE_PASSWORD_TEST = '1234abcd';
38
    /**
39
     * SoapClient handler
40
     *
41
     * @var \mrcnpdlk\Teryt\TerytSoapClient
42
     */
43
    private $soapClient;
44
    /**
45
     * Cache handler
46
     *
47
     * @var CacheInterface
48
     */
49
    private $oCache;
50
    /**
51
     * @var Adapter
52
     */
53
    private $oCacheAdapter;
54
    /**
55
     * Logger handler
56
     *
57
     * @var LoggerInterface
58
     */
59
    private $oLogger;
60
    /**
61
     * @var string
62
     */
63
    private $sServiceUrl;
64
    /**
65
     * @var string
66
     */
67
    private $sServiceUsername;
68
    /**
69
     * @var string
70
     */
71
    private $sServicePassword;
72
73
    /**
74
     * Client constructor.
75
     */
76 13
    public function __construct()
77
    {
78 13
        $this->setConfig();
79 13
        $this->setLoggerInstance();
80 13
        $this->setCacheInstance();
81 13
    }
82
83
    /**
84
     * @return array
85
     *
86
     */
87
    public function __debugInfo()
88
    {
89
        return ['Top secret'];
90
    }
91
92
    /**
93
     * Get logger instance
94
     *
95
     * @return LoggerInterface
96
     */
97 2
    public function getLogger()
98
    {
99 2
        return $this->oLogger;
100
    }
101
102
    /**
103
     * Get SoapClient
104
     *
105
     * @return \mrcnpdlk\Teryt\TerytSoapClient
106
     */
107 11
    private function getSoap()
108
    {
109
        try {
110 11
            if (!$this->soapClient) {
111 11
                $this->reinitSoap();
112
            }
113
114
        } catch (\Exception $e) {
115
            Helper::handleException($e);
116
        }
117
118 11
        return $this->soapClient;
119
    }
120
121
    /**
122
     * Reinit Soap Client
123
     *
124
     * @return $this
125
     * @throws Connection
126
     * @throws Exception
127
     */
128 13
    private function reinitSoap()
129
    {
130
        try {
131 13
            $this->soapClient = new TerytSoapClient($this->sServiceUrl, [
132 13
                'soap_version' => SOAP_1_1,
133
                'exceptions'   => true,
134 13
                'cache_wsdl'   => WSDL_CACHE_BOTH,
135
            ]);
136 13
            $this->soapClient->addUserToken($this->sServiceUsername, $this->sServicePassword);
137
        } catch (\Exception $e) {
138
            throw Helper::handleException($e);
139
        }
140
141 13
        return $this;
142
    }
143
144
    /**
145
     * Making request to Teryt WS1 API
146
     *
147
     * @param string  $method  Method name
148
     * @param array   $args    Parameters
149
     * @param boolean $addDate Add DataStanu to request
150
     *
151
     * @return mixed
152
     * @throws \mrcnpdlk\Teryt\Exception
153
     * @throws \mrcnpdlk\Teryt\Exception\Connection
154
     */
155 11
    public function request(string $method, array $args = [], bool $addDate = true)
156
    {
157
        try {
158 11
            if (!array_key_exists('DataStanu', $args) && $addDate) {
159 10
                $args['DataStanu'] = (new \DateTime())->format('Y-m-d');
160
            }
161 11
            $self    = $this;
162 11
            $this->oLogger->debug(sprintf('REQ: %s', $method), $args);
163
164
165 11
            $resp = $this->oCacheAdapter->useCache(
166 11
                function () use ($self, $method, $args) {
167 11
                    $res       = $self->getSoap()->__soapCall($method, [$args]);
168 10
                    $resultKey = $method . 'Result';
169 10
                    if (!property_exists($res, $resultKey)) {
170
                        throw new Response(sprintf('%s doesnt exist in response', $resultKey));
171
                    }
172
173 10
                    return $res->{$resultKey};
174 11
                },
175 11
                [__METHOD__, $method, $args]
176
            );
177
178 10
            $this->oLogger->debug(sprintf('RESP: %s, type is %s', $method, gettype($resp)));
179
180 10
            return $resp;
181
182 1
        } catch (\Exception $e) {
183 1
            throw Helper::handleException($e);
184
        }
185
    }
186
187
    /**
188
     * Setting Cache Adapter
189
     *
190
     * @return $this
191
     */
192 13
    private function setCacheAdapter()
193
    {
194 13
        $this->oCacheAdapter = new Adapter($this->oCache, $this->oLogger);
195
196 13
        return $this;
197
    }
198
199
    /**
200
     * Set Cache handler (PSR-16)
201
     *
202
     * @param CacheInterface|null $oCache
203
     *
204
     * @return \mrcnpdlk\Teryt\Client
205
     * @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-16-simple-cache.md PSR-16
206
     */
207 13
    public function setCacheInstance(CacheInterface $oCache = null)
208
    {
209 13
        $this->oCache = $oCache;
210 13
        $this->setCacheAdapter();
211
212 13
        return $this;
213
    }
214
215
    /**
216
     * Set Teryt configuration parameters
217
     *
218
     * @param string|null $username     Service username
219
     * @param string|null $password     Service password
220
     * @param bool        $isProduction Default FALSE
221
     *
222
     * @return $this
223
     *
224
     */
225 13
    public function setConfig(string $username = null, string $password = null, bool $isProduction = false)
226
    {
227 13
        $this->sServiceUrl      = $isProduction ? Client::SERVICE_URL : Client::SERVICE_URL_TEST;
228 13
        $this->sServiceUsername = $username ?? Client::SERVICE_USER_TEST;
229 13
        $this->sServicePassword = $password ?? Client::SERVICE_PASSWORD_TEST;
230
231 13
        $this->reinitSoap();
232
233 13
        return $this;
234
    }
235
236
    /**
237
     * Set Logger handler (PSR-3)
238
     *
239
     * @param LoggerInterface|null $oLogger
240
     *
241
     * @return $this
242
     */
243 13
    public function setLoggerInstance(LoggerInterface $oLogger = null)
244
    {
245 13
        $this->oLogger = $oLogger ?: new NullLogger();
246 13
        $this->setCacheAdapter();
247
248 13
        return $this;
249
    }
250
251
}
252