Completed
Pull Request — master (#171)
by
unknown
35:23
created

BrowscapUpdater::setConnectTimeout()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
c 1
b 0
f 0
cc 1
eloc 3
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 15
    private $connectTimeout = 5;
82
83 15
    /**
84 1
     * Gets a cache instance
85
     *
86 1
     * @return \BrowscapPHP\Cache\BrowscapCacheInterface
87 1
     */
88 1 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 1
        if (null === $this->cache) {
91 1
            $cacheDirectory = __DIR__ . '/../resources/';
92
93 15
            $cacheAdapter = new File(
94
                [File::DIR => $cacheDirectory]
95
            );
96
97
            $this->cache = new BrowscapCache($cacheAdapter);
98
        }
99
100
        return $this->cache;
101
    }
102
103
    /**
104 15
     * Sets a cache instance
105
     *
106 15
     * @param \BrowscapPHP\Cache\BrowscapCacheInterface|\WurflCache\Adapter\AdapterInterface $cache
107 11
     *
108 15
     * @throws \BrowscapPHP\Exception
109 3
     * @return \BrowscapPHP\BrowscapUpdater
110 3
     */
111 1 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...
112
    {
113 1
        if ($cache instanceof BrowscapCacheInterface) {
114
            $this->cache = $cache;
115 1
        } elseif ($cache instanceof AdapterInterface) {
116
            $this->cache = new BrowscapCache($cache);
117
        } else {
118 14
            throw new Exception(
119
                'the cache has to be an instance of \BrowscapPHP\Cache\BrowscapCacheInterface or '
120
                . 'an instanceof of \WurflCache\Adapter\AdapterInterface',
121
                Exception::CACHE_INCOMPATIBLE
122
            );
123
        }
124
125
        return $this;
126
    }
127
128 11
    /**
129
     * Sets a logger instance
130 11
     *
131
     * @param \Psr\Log\LoggerInterface $logger
132 11
     *
133
     * @return \BrowscapPHP\BrowscapUpdater
134
     */
135
    public function setLogger(LoggerInterface $logger)
136
    {
137
        $this->logger = $logger;
138
139
        return $this;
140 12
    }
141
    
142 12
    /**
143 3
     * returns a logger instance
144
     *
145
     * @return \Psr\Log\LoggerInterface
146 12
     */
147
    public function getLogger()
148
    {
149
        if (null === $this->logger) {
150
            $this->logger = new NullLogger();
151
        }
152 13
153
        return $this->logger;
154 11
    }
155 1
156
    /**
157
     * Sets the Connection Timeout
158 13
     *
159
     * @param $connectTimeout
160
     *
161
     * @return \BrowscapPHP\BrowscapUpdater
162
     */
163
    public function setConnectTimeout($connectTimeout)
164 10
    {        
165
        $this->connectTimeout = (int)$connectTimeout;
166 10
        
167 10
        return $this;
168
    }
169
170
    /**
171
     * @return \GuzzleHttp\Client
172
     */
173
    public function getClient()
174
    {
175
        if (null === $this->client) {
176 4
            $this->client = new Client();
177
        }
178 4
179 1
        return $this->client;
180
    }
181
182 3
    /**
183 1
     * @param \GuzzleHttp\Client $client
184
     */
185
    public function setClient(Client $client)
186
    {
187 2
        $this->client = $client;
188 2
    }
189
190
    /**
191
     * reads and parses an ini file and writes the results into the cache
192 2
     *
193 2
     * @param string $iniFile
194
     *
195
     * @throws \BrowscapPHP\Exception
196
     */
197
    public function convertFile($iniFile)
198
    {
199
        if (empty($iniFile)) {
200 3
            throw new Exception('the file name can not be empty');
201
        }
202 3
203 3
        if (!is_readable($iniFile)) {
204
            throw new Exception('it was not possible to read the local file ' . $iniFile);
205 3
        }
206 3
207
        try {
208
            $iniString = file_get_contents($iniFile);
209
        } catch (Helper\Exception $e) {
210
            throw new Exception('an error occured while converting the local file into the cache', 0, $e);
211
        }
212
213
        $this->convertString($iniString);
214
    }
215
216
    /**
217 3
     * reads and parses an ini string and writes the results into the cache
218
     *
219 3
     * @param string $iniString
220
     */
221
    public function convertString($iniString)
222
    {
223
        $cachedVersion = $this->getCache()->getItem('browscap.version', false, $success);
224 2
        $converter     = new Converter($this->getLogger(), $this->getCache());
225
226 2
        $this->storeContent($converter, $iniString, $cachedVersion);
227
    }
228
229 2
    /**
230
     * fetches a remote file and stores it into a local folder
231 2
     *
232 1
     * @param string $file       The name of the file where to store the remote content
233
     * @param string $remoteFile The code for the remote file to load
234
     *
235
     * @throws \BrowscapPHP\Exception\FetcherException
236
     * @throws \BrowscapPHP\Helper\Exception
237
     */
238
    public function fetch($file, $remoteFile = IniLoader::PHP_INI)
239 2
    {
240 2
        if (null === ($cachedVersion = $this->checkUpdate())) {
241
            // no newer version available
242
            return;
243
        }
244 2
245
        $this->getLogger()->debug('started fetching remote file');
246
247
        $uri = (new IniLoader())->setRemoteFilename($remoteFile)->getRemoteIniUrl();
248
249 2
        /** @var \Psr\Http\Message\ResponseInterface $response */
250 2
        $response = $this->getClient()->get($uri, ['connect_timeout' => $this->connectTimeout]);
251
252 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...
253
            throw new FetcherException(
254 2
                'an error occured while fetching remote data from URI ' . $uri . ': StatusCode was '
255 2
                . $response->getStatusCode()
256
            );
257 2
        }
258 2
259 2
        try {
260
            $content = $response->getBody()->getContents();
261
        } catch (\Exception $e) {
262 2
            throw new FetcherException('an error occured while fetching remote data', 0, $e);
263 2
        }
264
265
        if (empty($content)) {
266
            $error = error_get_last();
267
            throw FetcherException::httpError($uri, $error['message']);
268
        }
269
270
        $this->getLogger()->debug('finished fetching remote file');
271
        $this->getLogger()->debug('started storing remote file into local file');
272
273
        $content = $this->sanitizeContent($content);
274
275
        $converter  = new Converter($this->getLogger(), $this->getCache());
276
        $iniVersion = $converter->getIniVersion($content);
277 2
278
        if ($iniVersion > $cachedVersion) {
279 2
            $fs = new Filesystem();
280
            $fs->dumpFile($file, $content);
281 2
        }
282
283
        $this->getLogger()->debug('finished storing remote file into local file');
284
    }
285
286 2
    /**
287
     * fetches a remote file, parses it and writes the result into the cache
288
     *
289 2
     * if the local stored information are in the same version as the remote data no actions are
290
     * taken
291 2
     *
292
     * @param string $remoteFile The code for the remote file to load
293
     *
294
     * @throws \BrowscapPHP\Exception\FileNotFoundException
295
     * @throws \BrowscapPHP\Helper\Exception
296
     * @throws \BrowscapPHP\Exception\FetcherException
297
     */
298
    public function update($remoteFile = IniLoader::PHP_INI)
299 2
    {
300 2
        $this->getLogger()->debug('started fetching remote file');
301
302
        if (null === ($cachedVersion = $this->checkUpdate())) {
303
            // no newer version available
304 2
            return;
305 1
        }
306
307 1
        $uri = (new IniLoader())->setRemoteFilename($remoteFile)->getRemoteIniUrl();
308
309
        /** @var \Psr\Http\Message\ResponseInterface $response */
310 1
        $response = $this->getClient()->get($uri, ['connect_timeout' => $this->connectTimeout]);
311
312 1 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...
313
            throw new FetcherException(
314 1
                'an error occured while fetching remote data from URI ' . $uri . ': StatusCode was '
315 1
                . $response->getStatusCode()
316
            );
317
        }
318
319
        try {
320
            $content = $response->getBody()->getContents();
321
        } catch (\Exception $e) {
322
            throw new FetcherException('an error occured while fetching remote data', 0, $e);
323
        }
324
325 9
        if (empty($content)) {
326
            $error = error_get_last();
327 9
328 9
            throw FetcherException::httpError($uri, $error['message']);
329
        }
330 9
331
        $this->getLogger()->debug('finished fetching remote file');
332 5
333
        $converter = new Converter($this->getLogger(), $this->getCache());
334 5
335
        $this->storeContent($converter, $content, $cachedVersion);
336
    }
337 4
338
    /**
339
     * checks if an update on a remote location for the local file or the cache
340 4
     *
341
     * @throws \BrowscapPHP\Helper\Exception
342 4
     * @throws \BrowscapPHP\Exception\FetcherException
343 1
     * @return int|null                                The actual cached version if a newer version is available, null otherwise
344 1
     * @return int|null                                The actual cached version if a newer version is available, null otherwise
345 1
     */
346 1
    public function checkUpdate()
347
    {
348
        $success       = null;
349
        $cachedVersion = $this->getCache()->getItem('browscap.version', false, $success);
350 3
351 3
        if (!$cachedVersion) {
352 1
            // could not load version from cache
353 1
            $this->getLogger()->info('there is no cached version available, please update from remote');
354 1
355 1
            return 0;
356
        }
357 1
358
        $uri = (new IniLoader())->getRemoteVersionUrl();
359
360 2
        /** @var \Psr\Http\Message\ResponseInterface $response */
361
        $response = $this->getClient()->get($uri, ['connect_timeout' => $this->connectTimeout]);
362
363 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...
364
            throw new FetcherException(
365
                'an error occured while fetching version data from URI ' . $uri . ': StatusCode was '
366
                . $response->getStatusCode()
367 2
            );
368
        }
369 1
370
        try {
371 1
            $remoteVersion = $response->getBody()->getContents();
372
        } catch (\Exception $e) {
373
            throw new FetcherException(
374 1
                'an error occured while fetching version data from URI ' . $uri . ': StatusCode was '
375 1
                . $response->getStatusCode(),
376 1
                0,
377
                $e
378 1
            );
379
        }
380
381
        if (!$remoteVersion) {
382
            // could not load remote version
383
            $this->getLogger()->info('could not load version from remote location');
384
385
            return 0;
386 6
        }
387
388
        if ($cachedVersion && $remoteVersion && $remoteVersion <= $cachedVersion) {
389 6
            // no newer version available
390
            $this->getLogger()->info('there is no newer version available');
391
392 6
            return null;
393
        }
394
395
        $this->getLogger()->info(
396
            'a newer version is available, local version: ' . $cachedVersion . ', remote version: ' . $remoteVersion
397
        );
398
399
        return (int) $cachedVersion;
400
    }
401
402 4
    /**
403
     * @param string $content
404 4
     *
405 4
     * @return mixed
406
     */
407 4
    private function sanitizeContent($content)
408
    {
409 4
        // replace everything between opening and closing php and asp tags
410 4
        $content = preg_replace('/<[?%].*[?%]>/', '', $content);
411
412 4
        // replace opening and closing php and asp tags
413
        return str_replace(['<?', '<%', '?>', '%>'], '', $content);
414
    }
415
416
    /**
417
     * reads and parses an ini string and writes the results into the cache
418
     *
419
     * @param \BrowscapPHP\Helper\Converter $converter
420
     * @param string                        $content
421
     * @param int|null                      $cachedVersion
422
     */
423
    private function storeContent(Converter $converter, $content, $cachedVersion)
424
    {
425
        $iniString  = $this->sanitizeContent($content);
426
        $iniVersion = $converter->getIniVersion($iniString);
427
428
        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...
429
            $converter
430
                ->storeVersion()
431
                ->convertString($iniString);
432
        }
433
    }
434
}
435