Completed
Pull Request — master (#164)
by Thomas
14:19
created

BrowscapUpdater::getClient()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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