Completed
Pull Request — master (#185)
by
unknown
12:19
created

BrowscapUpdater::fetch()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 47
Code Lines 26

Duplication

Lines 6
Ratio 12.77 %

Code Coverage

Tests 19
CRAP Score 6.9364

Importance

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