Passed
Branch master (66fada)
by Marcin
04:18 queued 16s
created

Client::useCache()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 12
nc 3
nop 3
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\Teryt\Exception\Connection;
21
use mrcnpdlk\Teryt\Exception\Response;
22
use Psr\Log\LoggerInterface;
23
use Psr\Log\NullLogger;
24
use Psr\SimpleCache\CacheInterface;
25
26
/**
27
 * Class Client
28
 *
29
 * @package mrcnpdlk\Teryt
30
 */
31
class Client
32
{
33
    /**
34
     * Client instance
35
     *
36
     * @var \mrcnpdlk\Teryt\Client
37
     */
38
    protected static $classInstance;
39
    /**
40
     * SoapClient handler
41
     *
42
     * @var \mrcnpdlk\Teryt\TerytSoapClient
43
     */
44
    private $soapClient;
45
    /**
46
     * Cache handler
47
     *
48
     * @var CacheInterface
49
     */
50
    private $oCache;
51
    /**
52
     * Logger handler
53
     *
54
     * @var LoggerInterface
55
     */
56
    private $oLogger;
57
    /**
58
     * Teryt auth configuration
59
     *
60
     * @var array
61
     */
62
    private $tTerytConfig = [];
63
    /**
64
     * Default Teryt auth configuration
65
     *
66
     * @var array
67
     */
68
    private $tDefTerytConfig
69
        = [
70
            'url'      => 'https://uslugaterytws1test.stat.gov.pl/wsdl/terytws1.wsdl',
71
            'username' => 'TestPubliczny',
72
            'password' => '1234abcd',
73
        ];
74
75
    /**
76
     * Client constructor.
77
     */
78
    protected function __construct()
79
    {
80
        $this->setTerytConfig();
81
        $this->setLoggerInstance();
82
        $this->setCacheInstance();
83
    }
84
85
    /**
86
     * Set Teryt configuration parameters
87
     *
88
     * @param array $tConfig
89
     *
90
     * @return $this
91
     * @throws \mrcnpdlk\Teryt\Exception\Connection
92
     */
93
    public function setTerytConfig(array $tConfig = [])
94
    {
95
        if (empty($tConfig)) {
96
            $tConfig = $this->tDefTerytConfig;
97
        }
98
        $this->tTerytConfig['url']      = $tConfig['url'] ?? 'https://uslugaterytws1.stat.gov.pl/wsdl/terytws1.wsdl';
99
        $this->tTerytConfig['username'] = $tConfig['username'] ?? null;
100
        $this->tTerytConfig['password'] = $tConfig['password'] ?? null;
101
102
        if (!$this->tTerytConfig['username'] || !$this->tTerytConfig['password']) {
103
            throw new Connection(sprintf('Username and password for TERYT WS1 is required'));
104
        }
105
        $this->reinitSoap();
106
107
        return $this;
108
    }
109
110
    /**
111
     * Reinit Soap Client
112
     *
113
     * @return $this
114
     * @throws Connection
115
     * @throws Exception
116
     */
117
    private function reinitSoap()
118
    {
119
        try {
120
            $this->soapClient = new TerytSoapClient($this->tTerytConfig['url'], [
121
                'soap_version' => SOAP_1_1,
122
                'exceptions'   => true,
123
                'cache_wsdl'   => WSDL_CACHE_BOTH,
124
            ]);
125
            $this->soapClient->addUserToken($this->tTerytConfig['username'], $this->tTerytConfig['password']);
126
        } catch (\Exception $e) {
127
            throw Helper::handleException($e);
128
        }
129
130
        return $this;
131
    }
132
133
    /**
134
     * Set Logger handler (PSR-3)
135
     *
136
     * @param LoggerInterface|null $oLogger
137
     *
138
     * @return $this
139
     */
140
    public function setLoggerInstance(LoggerInterface $oLogger = null)
141
    {
142
        $this->oLogger = $oLogger ?: new NullLogger();
143
144
        return $this;
145
    }
146
147
    /**
148
     * Set Cache handler (PSR-16)
149
     *
150
     * @param CacheInterface|null $oCache
151
     *
152
     * @return \mrcnpdlk\Teryt\Client
153
     * @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-16-simple-cache.md PSR-16
154
     */
155
    public function setCacheInstance(CacheInterface $oCache = null)
156
    {
157
        $this->oCache = $oCache;
158
159
        return $this;
160
    }
161
162
    /**
163
     * Get Client class instance
164
     *
165
     * @return \mrcnpdlk\Teryt\Client Instancja klasy
166
     * @throws \mrcnpdlk\Teryt\Exception
167
     */
168
    public static function getInstance()
169
    {
170
        if (!static::$classInstance) {
171
            static::$classInstance = new static;
172
        }
173
174
        return static::$classInstance;
175
    }
176
177
    /**
178
     * Making request to Teryt WS1 API
179
     *
180
     * @param string  $method  Methid name
181
     * @param array   $args    Parameters
182
     * @param boolean $addDate Add DataSTanu to request
183
     *
184
     * @return mixed
185
     * @throws \mrcnpdlk\Teryt\Exception
186
     * @throws \mrcnpdlk\Teryt\Exception\Connection
187
     */
188
    public function request(string $method, array $args = [], bool $addDate = true)
189
    {
190
        try {
191
            if (!array_key_exists('DataStanu', $args) && $addDate) {
192
                $args['DataStanu'] = (new \DateTime())->format('Y-m-d');
193
            }
194
            $hashKey = md5(json_encode([__METHOD__, $method, $args]));
195
            $self    = $this;
196
            $this->oLogger->debug(sprintf('REQ: %s, hash: %s', $method, $hashKey), $args);
197
198
            $resp = $this->useCache(
199
                function () use ($self, $method, $args) {
200
                    $res       = $self->getSoap()->__soapCall($method, [$args]);
201
                    $resultKey = $method . 'Result';
202
                    if (!property_exists($res, $resultKey)) {
203
                        throw new Response(sprintf('%s doesnt exist in response', $resultKey));
204
                    }
205
206
                    return $res->{$resultKey};
207
                },
208
                $hashKey);
209
210
            $this->oLogger->debug(sprintf('RESP: %s, type is %s', $method, gettype($resp)));
211
212
            return $resp;
213
214
        } catch (\Exception $e) {
215
            throw Helper::handleException($e);
216
        }
217
    }
218
219
    /**
220
     * Caching things
221
     *
222
     * @param \Closure $closure Function calling wheen cache is empty or not valid
223
     * @param mixed    $hashKey Cache key of item
224
     * @param int|null $ttl     Time to live for item
225
     *
226
     * @return mixed
227
     */
228
    private function useCache(\Closure $closure, string $hashKey, int $ttl = null)
229
    {
230
        if ($this->oCache) {
231
            if ($this->oCache->has($hashKey)) {
232
                $answer = $this->oCache->get($hashKey);
233
                $this->oLogger->debug(sprintf('CACHE [%s]: geting from cache', $hashKey));
234
            } else {
235
                $answer = $closure();
236
                $this->oCache->set($hashKey, $answer, $ttl);
237
                $this->oLogger->debug(sprintf('CACHE [%s]: old, reset', $hashKey));
238
            }
239
        } else {
240
            $this->oLogger->debug(sprintf('CACHE [%s]: no implemented', $hashKey));
241
            $answer = $closure();
242
        }
243
244
        return $answer;
245
    }
246
247
    /**
248
     * Get SoapClient
249
     *
250
     * @return \mrcnpdlk\Teryt\TerytSoapClient
251
     */
252
    private function getSoap()
253
    {
254
        try {
255
            if (!$this->soapClient) {
256
                $this->reinitSoap();
257
            }
258
259
        } catch (\Exception $e) {
260
            Helper::handleException($e);
261
        }
262
263
        return $this->soapClient;
264
    }
265
266
    /**
267
     * Get logger instance
268
     *
269
     * @return LoggerInterface
270
     */
271
    public function getLogger()
272
    {
273
        return $this->oLogger;
274
    }
275
276
    public function __debugInfo()
277
    {
278
        return ['Top secret'];
279
    }
280
}
281