Completed
Pull Request — master (#175)
by Thomas
12:41
created

BrowscapUpdater::setConnectTimeout()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
/**
3
 * Copyright (c) 1998-2015 Browser Capabilities Project
4
 *
5
 * Permission is hereby granted, free of charge, to any person obtaining a
6
 * copy of this software and associated documentation files (the "Software"),
7
 * to deal in the Software without restriction, including without limitation
8
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9
 * and/or sell copies of the Software, and to permit persons to whom the
10
 * Software is furnished to do so, subject to the following conditions:
11
 *
12
 * The above copyright notice and this permission notice shall be included
13
 * in all copies or substantial portions of the Software.
14
 *
15
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
16
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
 * THE SOFTWARE.
22
 *
23
 * @category   Browscap-PHP
24
 * @copyright  1998-2015 Browser Capabilities Project
25
 * @license    http://www.opensource.org/licenses/MIT MIT License
26
 * @link       https://github.com/browscap/browscap-php/
27
 */
28
29
namespace BrowscapPHP;
30
31
use BrowscapPHP\Cache\BrowscapCache;
32
use BrowscapPHP\Cache\BrowscapCacheInterface;
33
use BrowscapPHP\Exception\FetcherException;
34
use BrowscapPHP\Helper\Converter;
35
use BrowscapPHP\Helper\Filesystem;
36
use BrowscapPHP\Helper\IniLoader;
37
use GuzzleHttp\Client;
38
use Psr\Log\LoggerInterface;
39
use Psr\Log\NullLogger;
40
use WurflCache\Adapter\AdapterInterface;
41
use WurflCache\Adapter\File;
42
43
/**
44
 * Browscap.ini parsing class with caching and update capabilities
45
 *
46
 * @category   Browscap-PHP
47
 * @author     Jonathan Stoppani <[email protected]>
48
 * @author     Vítor Brandão <[email protected]>
49
 * @author     Mikołaj Misiurewicz <[email protected]>
50
 * @author     Christoph Ziegenberg <[email protected]>
51
 * @author     Thomas Müller <[email protected]>
52
 * @copyright  Copyright (c) 1998-2015 Browser Capabilities Project
53
 * @version    3.0
54
 * @license    http://www.opensource.org/licenses/MIT MIT License
55
 * @link       https://github.com/browscap/browscap-php/
56
 */
57
class BrowscapUpdater
58
{
59
    /**
60
     * The cache instance
61
     *
62
     * @var \BrowscapPHP\Cache\BrowscapCacheInterface
63
     */
64
    private $cache = null;
65
66
    /**
67
     * @var @var \Psr\Log\LoggerInterface
68
     */
69
    private $logger = null;
70
71
    /**
72
     * @var \GuzzleHttp\Client
73
     */
74
    private $client = null;
75
76
    /**
77
     * Curl connect timeout in seconds
78
     *
79
     * @var int
80
     */
81
    private $connectTimeout = 5;
82
83
    /**
84
     * Gets a cache instance
85
     *
86
     * @return \BrowscapPHP\Cache\BrowscapCacheInterface
87
     */
88 15 View Code Duplication
    public function getCache()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
89
    {
90 15
        if (null === $this->cache) {
91 2
            $cacheDirectory = __DIR__ . '/../resources/';
92
93 1
            $cacheAdapter = new File(
94 1
                [File::DIR => $cacheDirectory]
95 1
            );
96
97 1
            $this->cache = new BrowscapCache($cacheAdapter);
98
        }
99
100 15
        return $this->cache;
101
    }
102
103
    /**
104
     * Sets a cache instance
105
     *
106
     * @param \BrowscapPHP\Cache\BrowscapCacheInterface|\WurflCache\Adapter\AdapterInterface $cache
107
     *
108
     * @throws \BrowscapPHP\Exception
109
     *
110
     * @return self
111
     */
112 15 View Code Duplication
    public function setCache($cache)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
113
    {
114 15
        if ($cache instanceof BrowscapCacheInterface) {
115 11
            $this->cache = $cache;
116 15
        } elseif ($cache instanceof AdapterInterface) {
117 3
            $this->cache = new BrowscapCache($cache);
118 3
        } else {
119 1
            throw new Exception(
120
                'the cache has to be an instance of \BrowscapPHP\Cache\BrowscapCacheInterface or '
121 1
                . 'an instanceof of \WurflCache\Adapter\AdapterInterface',
122
                Exception::CACHE_INCOMPATIBLE
123 1
            );
124
        }
125
126 14
        return $this;
127
    }
128
129
    /**
130
     * Sets a logger instance
131
     *
132
     * @param \Psr\Log\LoggerInterface $logger
133
     *
134
     * @return self
135
     */
136 11
    public function setLogger(LoggerInterface $logger)
137
    {
138 11
        $this->logger = $logger;
139
140 11
        return $this;
141
    }
142
143
    /**
144
     * returns a logger instance
145
     *
146
     * @return \Psr\Log\LoggerInterface
147
     */
148 12
    public function getLogger()
149
    {
150 12
        if (null === $this->logger) {
151 3
            $this->logger = new NullLogger();
152
        }
153
154 12
        return $this->logger;
155
    }
156
157
    /**
158
     * Sets the Connection Timeout
159
     *
160
     * @param int $connectTimeout
161
     */
162 1
    public function setConnectTimeout($connectTimeout)
163
    {
164 1
        $this->connectTimeout = (int) $connectTimeout;
165 1
    }
166
167
    /**
168
     * @return \GuzzleHttp\Client
169
     */
170 11
    public function getClient()
171
    {
172 10
        if (null === $this->client) {
173 1
            $this->client = new Client();
174
        }
175
176 11
        return $this->client;
177
    }
178
179
    /**
180
     * @param \GuzzleHttp\Client $client
181
     */
182 10
    public function setClient(Client $client)
183
    {
184 10
        $this->client = $client;
185 10
    }
186
187
    /**
188
     * reads and parses an ini file and writes the results into the cache
189
     *
190
     * @param string $iniFile
191
     *
192
     * @throws \BrowscapPHP\Exception
193
     */
194 4
    public function convertFile($iniFile)
195
    {
196 4
        if (empty($iniFile)) {
197 1
            throw new Exception('the file name can not be empty');
198
        }
199
200 3
        if (!is_readable($iniFile)) {
201 1
            throw new Exception('it was not possible to read the local file ' . $iniFile);
202
        }
203
204
        try {
205 2
            $iniString = file_get_contents($iniFile);
206 2
        } catch (Helper\Exception $e) {
207
            throw new Exception('an error occured while converting the local file into the cache', 0, $e);
208
        }
209
210 2
        $this->convertString($iniString);
211 2
    }
212
213
    /**
214
     * reads and parses an ini string and writes the results into the cache
215
     *
216
     * @param string $iniString
217
     */
218 3
    public function convertString($iniString)
219
    {
220 3
        $cachedVersion = $this->getCache()->getItem('browscap.version', false, $success);
221 3
        $converter     = new Converter($this->getLogger(), $this->getCache());
222
223 3
        $this->storeContent($converter, $iniString, $cachedVersion);
224 3
    }
225
226
    /**
227
     * fetches a remote file and stores it into a local folder
228
     *
229
     * @param string $file       The name of the file where to store the remote content
230
     * @param string $remoteFile The code for the remote file to load
231
     *
232
     * @throws \BrowscapPHP\Exception\FetcherException
233
     * @throws \BrowscapPHP\Helper\Exception
234
     */
235 3
    public function fetch($file, $remoteFile = IniLoader::PHP_INI)
236
    {
237 3
        if (null === ($cachedVersion = $this->checkUpdate())) {
238
            // no newer version available
239
            return;
240
        }
241
242 2
        $this->getLogger()->debug('started fetching remote file');
243
244 2
        $uri = (new IniLoader())->setRemoteFilename($remoteFile)->getRemoteIniUrl();
245
246
        /** @var \Psr\Http\Message\ResponseInterface $response */
247 2
        $response = $this->getClient()->get($uri, ['connect_timeout' => $this->connectTimeout]);
248
249 2 View Code Duplication
        if ($response->getStatusCode() !== 200) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
250
            throw new FetcherException(
251
                'an error occured while fetching remote data from URI ' . $uri . ': StatusCode was '
252
                . $response->getStatusCode()
253
            );
254
        }
255
256
        try {
257 2
            $content = $response->getBody()->getContents();
258 2
        } catch (\Exception $e) {
259
            throw new FetcherException('an error occured while fetching remote data', 0, $e);
260
        }
261
262 2
        if (empty($content)) {
263
            $error = error_get_last();
264
            throw FetcherException::httpError($uri, $error['message']);
265
        }
266
267 2
        $this->getLogger()->debug('finished fetching remote file');
268 2
        $this->getLogger()->debug('started storing remote file into local file');
269
270 2
        $content = $this->sanitizeContent($content);
271
272 2
        $converter  = new Converter($this->getLogger(), $this->getCache());
273 2
        $iniVersion = $converter->getIniVersion($content);
274
275 2
        if ($iniVersion > $cachedVersion) {
276 2
            $fs = new Filesystem();
277 2
            $fs->dumpFile($file, $content);
278
        }
279
280 2
        $this->getLogger()->debug('finished storing remote file into local file');
281 2
    }
282
283
    /**
284
     * fetches a remote file, parses it and writes the result into the cache
285
     *
286
     * if the local stored information are in the same version as the remote data no actions are
287
     * taken
288
     *
289
     * @param string $remoteFile The code for the remote file to load
290
     *
291
     * @throws \BrowscapPHP\Exception\FileNotFoundException
292
     * @throws \BrowscapPHP\Helper\Exception
293
     * @throws \BrowscapPHP\Exception\FetcherException
294
     */
295 2
    public function update($remoteFile = IniLoader::PHP_INI)
296
    {
297 2
        $this->getLogger()->debug('started fetching remote file');
298
299 2
        if (null === ($cachedVersion = $this->checkUpdate())) {
300
            // no newer version available
301
            return;
302
        }
303
304 2
        $uri = (new IniLoader())->setRemoteFilename($remoteFile)->getRemoteIniUrl();
305
306
        /** @var \Psr\Http\Message\ResponseInterface $response */
307 2
        $response = $this->getClient()->get($uri, ['connect_timeout' => $this->connectTimeout]);
308
309 2 View Code Duplication
        if ($response->getStatusCode() !== 200) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
310
            throw new FetcherException(
311
                'an error occured while fetching remote data from URI ' . $uri . ': StatusCode was '
312
                . $response->getStatusCode()
313
            );
314
        }
315
316
        try {
317 2
            $content = $response->getBody()->getContents();
318 2
        } catch (\Exception $e) {
319
            throw new FetcherException('an error occured while fetching remote data', 0, $e);
320
        }
321
322 2
        if (empty($content)) {
323 1
            $error = error_get_last();
324
325 1
            throw FetcherException::httpError($uri, $error['message']);
326
        }
327
328 1
        $this->getLogger()->debug('finished fetching remote file');
329
330 1
        $converter = new Converter($this->getLogger(), $this->getCache());
331
332 1
        $this->storeContent($converter, $content, $cachedVersion);
333 1
    }
334
335
    /**
336
     * checks if an update on a remote location for the local file or the cache
337
     *
338
     * @throws \BrowscapPHP\Helper\Exception
339
     * @throws \BrowscapPHP\Exception\FetcherException
340
     * @return int|null                                The actual cached version if a newer version is available, null otherwise
341
     * @return int|null                                The actual cached version if a newer version is available, null otherwise
342
     */
343 9
    public function checkUpdate()
344
    {
345 9
        $success       = null;
346 9
        $cachedVersion = $this->getCache()->getItem('browscap.version', false, $success);
347
348 9
        if (!$cachedVersion) {
349
            // could not load version from cache
350 5
            $this->getLogger()->info('there is no cached version available, please update from remote');
351
352 5
            return 0;
353
        }
354
355 4
        $uri = (new IniLoader())->getRemoteVersionUrl();
356
357
        /** @var \Psr\Http\Message\ResponseInterface $response */
358 4
        $response = $this->getClient()->get($uri, ['connect_timeout' => $this->connectTimeout]);
359
360 4 View Code Duplication
        if ($response->getStatusCode() !== 200) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
361 1
            throw new FetcherException(
362 1
                'an error occured while fetching version data from URI ' . $uri . ': StatusCode was '
363 1
                . $response->getStatusCode()
364 1
            );
365
        }
366
367
        try {
368 3
            $remoteVersion = $response->getBody()->getContents();
369 3
        } catch (\Exception $e) {
370 1
            throw new FetcherException(
371 1
                'an error occured while fetching version data from URI ' . $uri . ': StatusCode was '
372 1
                . $response->getStatusCode(),
373 1
                0,
374
                $e
375 1
            );
376
        }
377
378 2
        if (!$remoteVersion) {
379
            // could not load remote version
380
            $this->getLogger()->info('could not load version from remote location');
381
382
            return 0;
383
        }
384
385 2
        if ($cachedVersion && $remoteVersion && $remoteVersion <= $cachedVersion) {
386
            // no newer version available
387 1
            $this->getLogger()->info('there is no newer version available');
388
389 1
            return null;
390
        }
391
392 1
        $this->getLogger()->info(
393 1
            'a newer version is available, local version: ' . $cachedVersion . ', remote version: ' . $remoteVersion
394 1
        );
395
396 1
        return (int) $cachedVersion;
397
    }
398
399
    /**
400
     * @param string $content
401
     *
402
     * @return mixed
403
     */
404 6
    private function sanitizeContent($content)
405
    {
406
        // replace everything between opening and closing php and asp tags
407 6
        $content = preg_replace('/<[?%].*[?%]>/', '', $content);
408
409
        // replace opening and closing php and asp tags
410 6
        return str_replace(['<?', '<%', '?>', '%>'], '', $content);
411
    }
412
413
    /**
414
     * reads and parses an ini string and writes the results into the cache
415
     *
416
     * @param \BrowscapPHP\Helper\Converter $converter
417
     * @param string                        $content
418
     * @param int|null                      $cachedVersion
419
     */
420 4
    private function storeContent(Converter $converter, $content, $cachedVersion)
421
    {
422 4
        $iniString  = $this->sanitizeContent($content);
423 4
        $iniVersion = $converter->getIniVersion($iniString);
424
425 4
        if (!$cachedVersion || $iniVersion > $cachedVersion) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $cachedVersion of type integer|null is loosely compared to false; this is ambiguous if the integer can be zero. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
426
            $converter
427 4
                ->storeVersion()
428 4
                ->convertString($iniString);
429
        }
430 4
    }
431
}
432