Completed
Pull Request — master (#164)
by Thomas
12:16
created

BrowscapUpdater   B

Complexity

Total Complexity 39

Size/Duplication

Total Lines 392
Duplicated Lines 10.2 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 81.88%

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 39
c 2
b 1
f 0
lcom 1
cbo 10
dl 40
loc 392
ccs 122
cts 149
cp 0.8188
rs 8.2857

14 Methods

Rating   Name   Duplication   Size   Complexity  
A getCache() 14 14 2
A setCache() 16 16 3
A setLogger() 0 6 1
A getLogger() 0 8 2
A setOptions() 0 6 1
A getLoader() 0 8 2
A setLoader() 0 4 1
A convertFile() 0 18 3
A convertString() 0 7 1
B fetch() 4 40 5
C update() 6 68 7
C checkUpdate() 0 43 7
A sanitizeContent() 0 8 1
A storeContent() 0 11 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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