Completed
Pull Request — master (#157)
by Thomas
06:34 queued 50s
created

BrowscapUpdater::setClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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