Completed
Pull Request — master (#164)
by Thomas
13:11
created

BrowscapUpdater::convertString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

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