Completed
Pull Request — master (#131)
by Thomas
11:20
created

Browscap::getFormatter()   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
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4286
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
 * @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
48
/**
49
 * Browscap.ini parsing class with caching and update capabilities
50
 *
51
 * @category   Browscap-PHP
52
 * @package    Browscap
53
 * @author     Jonathan Stoppani <[email protected]>
54
 * @author     Vítor Brandão <[email protected]>
55
 * @author     Mikołaj Misiurewicz <[email protected]>
56
 * @author     Christoph Ziegenberg <[email protected]>
57
 * @author     Thomas Müller <[email protected]>
58
 * @copyright  Copyright (c) 1998-2015 Browser Capabilities Project
59
 * @version    3.0
60
 * @license    http://www.opensource.org/licenses/MIT MIT License
61
 * @link       https://github.com/browscap/browscap-php/
62
 */
63
class Browscap
64
{
65
    /**
66
     * Parser to use
67
     *
68
     * @var \BrowscapPHP\Parser\ParserInterface
69
     */
70
    private $parser = null;
71
72
    /**
73
     * Formatter to use
74
     *
75
     * @var \BrowscapPHP\Formatter\FormatterInterface
76
     */
77
    private $formatter = null;
78
79
    /**
80
     * The cache instance
81
     *
82
     * @var \BrowscapPHP\Cache\BrowscapCacheInterface
83
     */
84
    private $cache = null;
85
86
    /**
87
     * @var @var \Psr\Log\LoggerInterface
88
     */
89
    private $logger = null;
90
91
    /**
92
     * Options for the updater. The array should be overwritten,
93
     * containing all options as keys, set to the default value.
94
     *
95
     * @var array
96
     */
97
    private $options = array();
98
99
    /**
100
     * @var \BrowscapPHP\Helper\IniLoader
101
     */
102
    private $loader = null;
103
104
    /**
105
     * Set theformatter instance to use for the getBrowser() result
106
     *
107
     * @param \BrowscapPHP\Formatter\FormatterInterface $formatter
108
     *
109
     * @return \BrowscapPHP\Browscap
110
     */
111 6
    public function setFormatter(Formatter\FormatterInterface $formatter)
112
    {
113 6
        $this->formatter = $formatter;
114
115 6
        return $this;
116
    }
117
118
    /**
119
     * @return \BrowscapPHP\Formatter\FormatterInterface
120
     */
121 4
    public function getFormatter()
122
    {
123 4
        if (null === $this->formatter) {
124 2
            $this->setFormatter(new Formatter\PhpGetBrowser());
125
        }
126
127 4
        return $this->formatter;
128
    }
129
130
    /**
131
     * Gets a cache instance
132
     *
133
     * @return \BrowscapPHP\Cache\BrowscapCacheInterface
134
     */
135 17
    public function getCache()
136
    {
137 17
        if (null === $this->cache) {
138 2
            $resourceDirectory = __DIR__.'/../resources/';
139
140 2
            $cacheAdapter = new File(
141 2
                array(File::DIR => $resourceDirectory)
142 2
            );
143
144 2
            $this->cache = new BrowscapCache($cacheAdapter);
145
        }
146
147 17
        return $this->cache;
148
    }
149
150
    /**
151
     * Sets a cache instance
152
     *
153
     * @param \BrowscapPHP\Cache\BrowscapCacheInterface|\WurflCache\Adapter\AdapterInterface $cache
154
     *
155
     * @throws \BrowscapPHP\Exception
156
     * @return \BrowscapPHP\Browscap
157
     */
158 16
    public function setCache($cache)
159
    {
160 16
        if ($cache instanceof BrowscapCacheInterface) {
161 12
            $this->cache = $cache;
162 16
        } elseif ($cache instanceof AdapterInterface) {
163 3
            $this->cache = new BrowscapCache($cache);
164 3
        } else {
165 1
            throw new Exception(
166
                'the cache has to be an instance of \BrowscapPHP\Cache\BrowscapCacheInterface or '
167 1
                .'an instanceof of \WurflCache\Adapter\AdapterInterface',
168
                Exception::CACHE_INCOMPATIBLE
169 1
            );
170
        }
171
172 16
        return $this;
173
    }
174
175
    /**
176
     * Sets the parser instance to use
177
     *
178
     * @param \BrowscapPHP\Parser\ParserInterface $parser
179
     *
180
     * @return \BrowscapPHP\Browscap
181
     */
182 4
    public function setParser(ParserInterface $parser)
183
    {
184 4
        $this->parser = $parser;
185
186 4
        return $this;
187
    }
188
189
    /**
190
     * returns an instance of the used parser class
191
     *
192
     * @return \BrowscapPHP\Parser\ParserInterface
193
     */
194 6
    public function getParser()
195
    {
196 6
        if (null === $this->parser) {
197 2
            $cache  = $this->getCache();
198 2
            $logger = $this->getLogger();
199 2
            $quoter = new Quoter();
200
201 2
            $patternHelper = new Parser\Helper\GetPattern($cache, $logger);
202 2
            $dataHelper    = new Parser\Helper\GetData($cache, $logger, $quoter);
203
204 2
            $this->parser = new Parser\Ini($patternHelper, $dataHelper, $this->getFormatter());
205
        }
206
207 6
        return $this->parser;
208
    }
209
210
    /**
211
     * Sets a logger instance
212
     *
213
     * @param \Psr\Log\LoggerInterface $logger
214
     *
215
     * @return \BrowscapPHP\Browscap
216
     */
217 12
    public function setLogger(LoggerInterface $logger)
218
    {
219 12
        $this->logger = $logger;
220
221 12
        return $this;
222
    }
223
224
    /**
225
     * returns a logger instance
226
     *
227
     * @return \Psr\Log\LoggerInterface
228
     */
229 16
    public function getLogger()
230
    {
231 16
        if (null === $this->logger) {
232 4
            $this->logger = new NullLogger();
233 1
        }
234
235 16
        return $this->logger;
236
    }
237
238
    /**
239
     * Sets multiple loader options at once
240
     *
241
     * @param array $options
242
     *
243
     * @return \BrowscapPHP\Browscap
244
     */
245 1
    public function setOptions(array $options)
246 1
    {
247 1
        $this->options = $options;
248
249 1
        return $this;
250
    }
251
252
    /**
253
     * @return \BrowscapPHP\Helper\IniLoader
254
     */
255 10
    public function getLoader()
256
    {
257 10
        if (null === $this->loader) {
258 1
            $this->loader = new IniLoader();
259
        }
260
261 10
        return $this->loader;
262
    }
263
264
    /**
265
     * @param \BrowscapPHP\Helper\IniLoader $loader
266
     */
267 10
    public function setLoader(IniLoader $loader)
268
    {
269 10
        $this->loader = $loader;
270 10
    }
271
272
    /**
273
     * parses the given user agent to get the information about the browser
274
     *
275
     * if no user agent is given, it uses {@see \BrowscapPHP\Helper\Support} to get it
276
     *
277
     * @param string $userAgent the user agent string
278
     *
279
     * @throws \BrowscapPHP\Exception
280
     * @return \stdClass              the object containing the browsers details. Array if
281
     *                                $return_array is set to true.
282
     */
283 4
    public function getBrowser($userAgent = null)
284
    {
285
        // Automatically detect the useragent
286 4
        if (!isset($userAgent)) {
287 2
            $support   = new Helper\Support($_SERVER);
288 2
            $userAgent = $support->getUserAgent();
289
        }
290
291
        // try to get browser data
292 4
        $formatter = $this->getParser()->getBrowser($userAgent);
293
294
        // if return is still NULL, updates are disabled... in this
295
        // case we return an empty formatter instance
296 4
        if ($formatter === null) {
297 2
            return $this->getFormatter()->getData();
298
        }
299
300 2
        return $formatter->getData();
301
    }
302
303
    /**
304
     * reads and parses an ini file and writes the results into the cache
305
     *
306
     * @param  string $iniFile
307
     *
308
     * @throws \BrowscapPHP\Exception
309
     */
310 4
    public function convertFile($iniFile)
311
    {
312 4
        $loader = new IniLoader();
313
314
        try {
315 4
            $loader->setLocalFile($iniFile);
316 4
        } catch (Helper\Exception $e) {
317 1
            throw new Exception('an error occured while setting the local file', 0, $e);
318
        }
319
320
        try {
321 3
            $iniString = $loader->load();
322 3
        } catch (Helper\Exception $e) {
323 1
            throw new Exception('an error occured while converting the local file into the cache', 0, $e);
324
        }
325
326 2
        $this->convertString($iniString);
327 2
    }
328
329
    /**
330
     * reads and parses an ini string and writes the results into the cache
331
     *
332
     * @param string $iniString
333
     */
334 3
    public function convertString($iniString)
335
    {
336 3
        $cachedVersion = $this->getCache()->getItem('browscap.version', false, $success);
337 3
        $converter     = new Converter($this->getLogger(), $this->getCache());
338
339 3
        $this->storeContent($converter, $iniString, $cachedVersion);
340 3
    }
341
342
    /**
343
     * fetches a remote file and stores it into a local folder
344
     *
345
     * @param string $file       The name of the file where to store the remote content
346
     * @param string $remoteFile The code for the remote file to load
347
     *
348
     * @throws \BrowscapPHP\Exception\FetcherException
349
     * @throws \BrowscapPHP\Helper\Exception
350
     */
351 3
    public function fetch($file, $remoteFile = IniLoader::PHP_INI)
352
    {
353 3
        if (null === ($cachedVersion = $this->checkUpdate($remoteFile))) {
354
            // no newer version available
355
            return;
356
        }
357
358 3
        $this->getLoader()
359 3
            ->setRemoteFilename($remoteFile)
360 3
            ->setOptions($this->options)
361 3
            ->setLogger($this->getLogger())
362
        ;
363
364 3
        $this->getLogger()->debug('started fetching remote file');
365
366
        try {
367 3
            $content = $this->getLoader()->load();
368 3
        } catch (Helper\Exception $e) {
369
            throw new FetcherException('an error occured while fetching remote data', 0, $e);
370
        }
371
372 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...
373 1
            $error = error_get_last();
374 1
            throw FetcherException::httpError($this->getLoader()->getRemoteIniUrl(), $error['message']);
375
        }
376
377 2
        $this->getLogger()->debug('finished fetching remote file');
378 2
        $this->getLogger()->debug('started storing remote file into local file');
379
380 2
        $content = $this->sanitizeContent($content);
381
382 2
        $converter  = new Converter($this->getLogger(), $this->getCache());
383 2
        $iniVersion = $converter->getIniVersion($content);
384
385 2
        if ($iniVersion > $cachedVersion) {
386 2
            $fs = new Filesystem();
387 2
            $fs->dumpFile($file, $content);
388
        }
389
390 2
        $this->getLogger()->debug('finished storing remote file into local file');
391 2
    }
392
393
    /**
394
     * fetches a remote file, parses it and writes the result into the cache
395
     *
396
     * if the local stored information are in the same version as the remote data no actions are
397
     * taken
398
     *
399
     * @param string      $remoteFile The code for the remote file to load
400
     * @param string|null $buildFolder
401
     * @param int|null    $buildNumber
402
     *
403
     * @throws \BrowscapPHP\Exception\FileNotFoundException
404
     * @throws \BrowscapPHP\Helper\Exception
405
     * @throws \BrowscapPHP\Exception\FetcherException
406
     */
407 2
    public function update($remoteFile = IniLoader::PHP_INI, $buildFolder = null, $buildNumber = null)
408
    {
409 2
        $this->getLogger()->debug('started fetching remote file');
410
411 2
        $converter = new Converter($this->getLogger(), $this->getCache());
412
413 2
        if (class_exists('\Browscap\Browscap')) {
414
            $resourceFolder = 'vendor/browscap/browscap/resources/';
415
416
            if (null === $buildNumber) {
417
                $buildNumber = (int)file_get_contents('vendor/browscap/browscap/BUILD_NUMBER');
418
            }
419
420
            if (null === $buildFolder) {
421
                $buildFolder = 'resources';
422
            }
423
424
            $buildFolder .= '/browscap-ua-test-'.$buildNumber;
425
            $iniFile     = $buildFolder.'/full_php_browscap.ini';
426
427
            mkdir($buildFolder, 0777, true);
428
429
            $writerCollectionFactory = new PhpWriterFactory();
430
            $writerCollection        = $writerCollectionFactory->createCollection($this->getLogger(), $buildFolder);
431
432
            $buildGenerator = new BuildGenerator($resourceFolder, $buildFolder);
433
            $buildGenerator
434
                ->setLogger($this->getLogger())
435
                ->setCollectionCreator(new CollectionCreator())
436
                ->setWriterCollection($writerCollection)
437
                ->run($buildNumber, false)
438
            ;
439
440
            $converter
441
                ->setVersion($buildNumber)
442
                ->storeVersion()
443
                ->convertFile($iniFile)
444
            ;
445
446
            $filesystem = new Filesystem();
447
            $filesystem->remove($buildFolder);
448
        } else {
449 2
            if (null === ($cachedVersion = $this->checkUpdate($remoteFile))) {
450
                // no newer version available
451
                return;
452
            }
453
454 2
            $this->getLoader()
455 2
                ->setRemoteFilename($remoteFile)
456 2
                ->setOptions($this->options)
457 2
                ->setLogger($this->getLogger())
458
            ;
459
460
            try {
461 2
                $content = $this->getLoader()->load();
462 2
            } catch (Helper\Exception $e) {
463
                throw new FetcherException('an error occured while loading remote data', 0, $e);
464
            }
465
466 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...
467 1
                $internalLoader = $this->getLoader()->getLoader();
468 1
                $error          = error_get_last();
469
470 1
                throw FetcherException::httpError($internalLoader->getUri(), $error['message']);
471
            }
472
473 1
            $this->getLogger()->debug('finished fetching remote file');
474
475 1
            $this->storeContent($converter, $content, $cachedVersion);
476
        }
477 1
    }
478
479
    /**
480
     * checks if an update on a remote location for the local file or the cache
481
     *
482
     * @param string $remoteFile
483
     *
484
     * @return int|null The actual cached version if a newer version is available, null otherwise
485
     * @throws \BrowscapPHP\Helper\Exception
486
     * @throws \BrowscapPHP\Exception\FetcherException
487
     */
488 9
    public function checkUpdate($remoteFile = IniLoader::PHP_INI)
489
    {
490 9
        $success       = null;
491 9
        $cachedVersion = $this->getCache()->getItem('browscap.version', false, $success);
492
493 9
        if (!$cachedVersion) {
494
            // could not load version from cache
495 5
            $this->getLogger()->info('there is no cached version available, please update from remote');
496
497 5
            return 0;
498
        }
499
500 4
        $this->getLoader()
501 4
            ->setRemoteFilename($remoteFile)
502 4
            ->setOptions($this->options)
503 4
            ->setLogger($this->getLogger())
504
        ;
505
506
        try {
507 4
            $remoteVersion = $this->getLoader()->getRemoteVersion();
508 4
        } catch (Helper\Exception $e) {
509 1
            throw new FetcherException('an error occured while checking remote version', 0, $e);
510
        }
511
512 3
        if (!$remoteVersion) {
513
            // could not load remote version
514 1
            $this->getLogger()->info('could not load version from remote location');
515
516 1
            return 0;
517
        }
518
519 2
        if ($cachedVersion && $remoteVersion && $remoteVersion <= $cachedVersion) {
520
            // no newer version available
521 1
            $this->getLogger()->info('there is no newer version available');
522
523 1
            return null;
524
        }
525
526 1
        $this->getLogger()->info(
527 1
            'a newer version is available, local version: ' . $cachedVersion . ', remote version: ' . $remoteVersion
528 1
        );
529
530 1
        return (int) $cachedVersion;
531
    }
532
533
    /**
534
     * @param string $content
535
     *
536
     * @return mixed
537
     */
538 6
    private function sanitizeContent($content)
539
    {
540
        // replace everything between opening and closing php and asp tags
541 6
        $content = preg_replace('/<[?%].*[?%]>/', '', $content);
542
543
        // replace opening and closing php and asp tags
544 6
        return str_replace(array('<?', '<%', '?>', '%>'), '', $content);
545
    }
546
547
    /**
548
     * reads and parses an ini string and writes the results into the cache
549
     *
550
     * @param \BrowscapPHP\Helper\Converter $converter
551
     * @param string                        $content
552
     * @param int|null                      $cachedVersion
553
     */
554 4
    private function storeContent(Converter $converter, $content, $cachedVersion)
555
    {
556 4
        $iniString  = $this->sanitizeContent($content);
557 4
        $iniVersion = $converter->getIniVersion($iniString);
558
559 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...
560
            $converter
561 4
                ->storeVersion()
562 4
                ->convertString($iniString)
563
            ;
564
        }
565 4
    }
566
}
567