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