Completed
Pull Request — master (#157)
by Thomas
13:25
created

BrowscapUpdater::checkUpdate()   B

Complexity

Conditions 8
Paths 6

Size

Total Lines 55
Code Lines 29

Duplication

Lines 6
Ratio 10.91 %

Code Coverage

Tests 28
CRAP Score 8.0189

Importance

Changes 4
Bugs 1 Features 0
Metric Value
c 4
b 1
f 0
dl 6
loc 55
ccs 28
cts 30
cp 0.9333
rs 7.4033
cc 8
eloc 29
nc 6
nop 0
crap 8.0189

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
 * @package    Browscap
25
 * @copyright  1998-2015 Browser Capabilities Project
26
 * @license    http://www.opensource.org/licenses/MIT MIT License
27
 * @link       https://github.com/browscap/browscap-php/
28
 */
29
30
namespace BrowscapPHP;
31
32
use Browscap\Generator\BuildGenerator;
33
use Browscap\Helper\CollectionCreator;
34
use Browscap\Writer\Factory\PhpWriterFactory;
35
use BrowscapPHP\Cache\BrowscapCache;
36
use BrowscapPHP\Cache\BrowscapCacheInterface;
37
use BrowscapPHP\Exception\FetcherException;
38
use BrowscapPHP\Helper\Converter;
39
use BrowscapPHP\Helper\Filesystem;
40
use BrowscapPHP\Helper\IniLoader;
41
use BrowscapPHP\Helper\Quoter;
42
use BrowscapPHP\Parser\ParserInterface;
43
use Psr\Log\LoggerInterface;
44
use Psr\Log\NullLogger;
45
use WurflCache\Adapter\AdapterInterface;
46
use WurflCache\Adapter\File;
47
use GuzzleHttp\Client;
48
49
/**
50
 * Browscap.ini parsing class with caching and update capabilities
51
 *
52
 * @category   Browscap-PHP
53
 * @package    Browscap
54
 * @author     Jonathan Stoppani <[email protected]>
55
 * @author     Vítor Brandão <[email protected]>
56
 * @author     Mikołaj Misiurewicz <[email protected]>
57
 * @author     Christoph Ziegenberg <[email protected]>
58
 * @author     Thomas Müller <[email protected]>
59
 * @copyright  Copyright (c) 1998-2015 Browser Capabilities Project
60
 * @version    3.0
61
 * @license    http://www.opensource.org/licenses/MIT MIT License
62
 * @link       https://github.com/browscap/browscap-php/
63
 */
64
class BrowscapUpdater
65
{
66
    /**
67
     * The cache instance
68
     *
69
     * @var \BrowscapPHP\Cache\BrowscapCacheInterface
70
     */
71
    private $cache = null;
72
73
    /**
74
     * @var @var \Psr\Log\LoggerInterface
75
     */
76
    private $logger = null;
77
78
    /**
79
     * @var \GuzzleHttp\Client
80
     */
81
    private $client = null;
82
83
    /**
84
     * Gets a cache instance
85
     *
86
     * @return \BrowscapPHP\Cache\BrowscapCacheInterface
87
     */
88 14 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 14
        if (null === $this->cache) {
91 1
            $cacheDirectory = __DIR__.'/../resources/';
92
93 2
            $cacheAdapter = new File(
94 1
                array(File::DIR => $cacheDirectory)
95 1
            );
96
97 1
            $this->cache = new BrowscapCache($cacheAdapter);
98
        }
99
100 14
        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
     * @return \BrowscapPHP\BrowscapUpdater
110
     */
111 14 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 14
        if ($cache instanceof BrowscapCacheInterface) {
114 10
            $this->cache = $cache;
115 14
        } elseif ($cache instanceof AdapterInterface) {
116 3
            $this->cache = new BrowscapCache($cache);
117 3
        } else {
118 1
            throw new Exception(
119
                'the cache has to be an instance of \BrowscapPHP\Cache\BrowscapCacheInterface or '
120 1
                .'an instanceof of \WurflCache\Adapter\AdapterInterface',
121
                Exception::CACHE_INCOMPATIBLE
122 1
            );
123
        }
124
125 13
        return $this;
126
    }
127
128
    /**
129
     * Sets a logger instance
130
     *
131
     * @param \Psr\Log\LoggerInterface $logger
132
     *
133
     * @return \BrowscapPHP\BrowscapUpdater
134
     */
135 10
    public function setLogger(LoggerInterface $logger)
136
    {
137 10
        $this->logger = $logger;
138
139 10
        return $this;
140
    }
141
142
    /**
143
     * returns a logger instance
144
     *
145
     * @return \Psr\Log\LoggerInterface
146
     */
147 11
    public function getLogger()
148
    {
149 11
        if (null === $this->logger) {
150 3
            $this->logger = new NullLogger();
151
        }
152
153 11
        return $this->logger;
154
    }
155
156
    /**
157
     * @return \GuzzleHttp\Client
158
     */
159 9
    public function getClient()
160 4
    {
161 9
        if (null === $this->client) {
162 1
            $this->client = new Client();
163
        }
164
165 9
        return $this->client;
166
    }
167
168
    /**
169
     * @param \GuzzleHttp\Client $client
170
     */
171 9
    public function setClient(Client $client)
172 4
    {
173 9
        $this->client = $client;
174 9
    }
175
176
    /**
177
     * reads and parses an ini file and writes the results into the cache
178
     *
179
     * @param  string $iniFile
180
     *
181
     * @throws \BrowscapPHP\Exception
182
     */
183 4
    public function convertFile($iniFile)
184
    {
185 4
        if (empty($iniFile)) {
186 1
            throw new Exception('the file name can not be empty');
187
        }
188
189 3
        if (!is_readable($iniFile)) {
190 1
            throw new Exception('it was not possible to read the local file ' . $iniFile);
191
        }
192
193
        try {
194 2
            $iniString = file_get_contents($iniFile);
195 2
        } catch (Helper\Exception $e) {
196
            throw new Exception('an error occured while converting the local file into the cache', 0, $e);
197
        }
198
199 2
        $this->convertString($iniString);
200 2
    }
201
202
    /**
203
     * reads and parses an ini string and writes the results into the cache
204
     *
205
     * @param string $iniString
206
     */
207 3
    public function convertString($iniString)
208
    {
209 3
        $cachedVersion = $this->getCache()->getItem('browscap.version', false, $success);
210 3
        $converter     = new Converter($this->getLogger(), $this->getCache());
211
212 3
        $this->storeContent($converter, $iniString, $cachedVersion);
213 3
    }
214
215
    /**
216
     * fetches a remote file and stores it into a local folder
217
     *
218
     * @param string $file       The name of the file where to store the remote content
219
     * @param string $remoteFile The code for the remote file to load
220
     *
221
     * @throws \BrowscapPHP\Exception\FetcherException
222
     * @throws \BrowscapPHP\Helper\Exception
223
     */
224 3
    public function fetch($file, $remoteFile = IniLoader::PHP_INI)
225
    {
226 3
        if (null === ($cachedVersion = $this->checkUpdate())) {
227
            // no newer version available
228
            return;
229
        }
230
231 2
        $this->getLogger()->debug('started fetching remote file');
232
233 3
        $uri = (new IniLoader())->setRemoteFilename($remoteFile)->getRemoteIniUrl();
234
235
        /** @var \Psr\Http\Message\ResponseInterface $response */
236 2
        $response = $this->getClient()->get($uri, ['timeout' => 5]);
237
238 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...
239
            throw new FetcherException(
240
                'an error occured while fetching remote data from URI ' . $uri . ': StatusCode was '
241
                . $response->getStatusCode()
242
            );
243
        }
244
245
        try {
246 2
            $content = $response->getBody()->getContents();
247 2
        } catch (\Exception $e) {
248
            throw new FetcherException('an error occured while fetching remote data', 0, $e);
249
        }
250
251 2
        if (empty($content)) {
252
            $error = error_get_last();
253
            throw FetcherException::httpError($uri, $error['message']);
254
        }
255
256 2
        $this->getLogger()->debug('finished fetching remote file');
257 2
        $this->getLogger()->debug('started storing remote file into local file');
258
259 2
        $content = $this->sanitizeContent($content);
260
261 2
        $converter  = new Converter($this->getLogger(), $this->getCache());
262 2
        $iniVersion = $converter->getIniVersion($content);
263
264 2
        if ($iniVersion > $cachedVersion) {
265 2
            $fs = new Filesystem();
266 2
            $fs->dumpFile($file, $content);
267
        }
268
269 2
        $this->getLogger()->debug('finished storing remote file into local file');
270 2
    }
271
272
    /**
273
     * fetches a remote file, parses it and writes the result into the cache
274
     *
275
     * if the local stored information are in the same version as the remote data no actions are
276
     * taken
277
     *
278
     * @param string $remoteFile The code for the remote file to load
279
     *
280
     * @throws \BrowscapPHP\Exception\FileNotFoundException
281
     * @throws \BrowscapPHP\Helper\Exception
282
     * @throws \BrowscapPHP\Exception\FetcherException
283
     */
284 2
    public function update($remoteFile = IniLoader::PHP_INI)
285
    {
286 2
        $this->getLogger()->debug('started fetching remote file');
287
288 2
        if (null === ($cachedVersion = $this->checkUpdate())) {
289
            // no newer version available
290
            return;
291
        }
292
293 2
        $uri = (new IniLoader())->setRemoteFilename($remoteFile)->getRemoteIniUrl();
294
295
        /** @var \Psr\Http\Message\ResponseInterface $response */
296 2
        $response = $this->getClient()->get($uri, ['timeout' => 5]);
297
298 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...
299
            throw new FetcherException(
300
                'an error occured while fetching remote data from URI ' . $uri . ': StatusCode was '
301
                . $response->getStatusCode()
302
            );
303
        }
304
305
        try {
306 2
            $content = $response->getBody()->getContents();
307 2
        } catch (\Exception $e) {
308
            throw new FetcherException('an error occured while fetching remote data', 0, $e);
309
        }
310
311 2
        if (empty($content)) {
312 1
            $error = error_get_last();
313
314 1
            throw FetcherException::httpError($uri, $error['message']);
315
        }
316
317 1
        $this->getLogger()->debug('finished fetching remote file');
318
319 1
        $converter = new Converter($this->getLogger(), $this->getCache());
320
321 1
        $this->storeContent($converter, $content, $cachedVersion);
322 1
    }
323
324
    /**
325
     * checks if an update on a remote location for the local file or the cache
326
     *
327
     * @return int|null The actual cached version if a newer version is available, null otherwise
328
     * @throws \BrowscapPHP\Helper\Exception
329
     * @throws \BrowscapPHP\Exception\FetcherException
330
     */
331 9
    public function checkUpdate()
332
    {
333 9
        $success       = null;
334 9
        $cachedVersion = $this->getCache()->getItem('browscap.version', false, $success);
335
336 9
        if (!$cachedVersion) {
337
            // could not load version from cache
338 5
            $this->getLogger()->info('there is no cached version available, please update from remote');
339
340 5
            return 0;
341
        }
342
343 4
        $uri = (new IniLoader())->getRemoteVersionUrl();
344
345
        /** @var \Psr\Http\Message\ResponseInterface $response */
346 4
        $response = $this->getClient()->get($uri, ['timeout' => 5]);
347
348 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...
349 1
            throw new FetcherException(
350 1
                'an error occured while fetching version data from URI ' . $uri . ': StatusCode was '
351 1
                . $response->getStatusCode()
352 1
            );
353
        }
354
355
        try {
356 3
            $remoteVersion = $response->getBody()->getContents();
357 3
        } catch (\Exception $e) {
358 1
            throw new FetcherException(
359 1
                'an error occured while fetching version data from URI ' . $uri . ': StatusCode was '
360 1
                . $response->getStatusCode(),
361 1
                0,
362
                $e
363 1
            );
364
        }
365
366 2
        if (!$remoteVersion) {
367
            // could not load remote version
368
            $this->getLogger()->info('could not load version from remote location');
369
370
            return 0;
371
        }
372
373 2
        if ($cachedVersion && $remoteVersion && $remoteVersion <= $cachedVersion) {
374
            // no newer version available
375 1
            $this->getLogger()->info('there is no newer version available');
376
377 1
            return null;
378
        }
379
380 1
        $this->getLogger()->info(
381 1
            'a newer version is available, local version: ' . $cachedVersion . ', remote version: ' . $remoteVersion
382 1
        );
383
384 1
        return (int) $cachedVersion;
385
    }
386
387
    /**
388
     * @param string $content
389
     *
390
     * @return mixed
391
     */
392 6
    private function sanitizeContent($content)
393
    {
394
        // replace everything between opening and closing php and asp tags
395 6
        $content = preg_replace('/<[?%].*[?%]>/', '', $content);
396
397
        // replace opening and closing php and asp tags
398 6
        return str_replace(array('<?', '<%', '?>', '%>'), '', $content);
399
    }
400
401
    /**
402
     * reads and parses an ini string and writes the results into the cache
403
     *
404
     * @param \BrowscapPHP\Helper\Converter $converter
405
     * @param string                        $content
406
     * @param int|null                      $cachedVersion
407
     */
408 4
    private function storeContent(Converter $converter, $content, $cachedVersion)
409
    {
410 4
        $iniString  = $this->sanitizeContent($content);
411 4
        $iniVersion = $converter->getIniVersion($iniString);
412
413 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...
414
            $converter
415 4
                ->storeVersion()
416 4
                ->convertString($iniString)
417
            ;
418
        }
419 4
    }
420
}
421