Completed
Push — master ( 7014bb...a38bcf )
by James
15s
created

GetPattern   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 106
Duplicated Lines 4.72 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 10.53%

Importance

Changes 0
Metric Value
wmc 13
c 0
b 0
f 0
lcom 1
cbo 4
dl 5
loc 106
ccs 4
cts 38
cp 0.1053
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
C getPatterns() 5 66 12

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
declare(strict_types = 1);
3
4
namespace BrowscapPHP\Parser\Helper;
5
6
use BrowscapPHP\Cache\BrowscapCacheInterface;
7
use Psr\Log\LoggerInterface;
8
use Psr\SimpleCache\InvalidArgumentException;
9
10
/**
11
 * extracts the pattern and the data for theses pattern from the ini content, optimized for PHP 5.5+
12
 */
13
class GetPattern implements GetPatternInterface
14
{
15
    /**
16
     * The cache instance
17
     *
18
     * @var \BrowscapPHP\Cache\BrowscapCacheInterface
19
     */
20
    private $cache;
21
22
    /**
23
     * a logger instance
24
     *
25
     * @var \Psr\Log\LoggerInterface
26
     */
27
    private $logger;
28
29
    /**
30
     * class contructor
31
     *
32
     * @param \BrowscapPHP\Cache\BrowscapCacheInterface $cache
33
     * @param \Psr\Log\LoggerInterface                  $logger
34
     */
35 1
    public function __construct(BrowscapCacheInterface $cache, LoggerInterface $logger)
36
    {
37 1
        $this->cache = $cache;
38 1
        $this->logger = $logger;
39 1
    }
40
41
    /**
42
     * Gets some possible patterns that have to be matched against the user agent. With the given
43
     * user agent string, we can optimize the search for potential patterns:
44
     * - We check the first characters of the user agent (or better: a hash, generated from it)
45
     * - We compare the length of the pattern with the length of the user agent
46
     *   (the pattern cannot be longer than the user agent!)
47
     *
48
     * @param string $userAgent
49
     *
50
     * @return \Generator
51
     */
52
    public function getPatterns(string $userAgent) : \Generator
53
    {
54
        $starts = Pattern::getHashForPattern($userAgent, true);
55
        $length = strlen($userAgent);
56
57
        // add special key to fall back to the default browser
58
        $starts[] = str_repeat('z', 32);
59
60
        // get patterns, first for the given browser and if that is not found,
61
        // for the default browser (with a special key)
62
        foreach ($starts as $tmpStart) {
63
            $tmpSubkey = SubKey::getPatternCacheSubkey($tmpStart);
64
65
            try {
66 View Code Duplication
                if (! $this->cache->hasItem('browscap.patterns.' . $tmpSubkey, true)) {
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...
67
                    $this->logger->debug('cache key "browscap.patterns.' . $tmpSubkey . '" not found');
68
69
                    continue;
70
                }
71
            } catch (InvalidArgumentException $e) {
72
                $this->logger->error(new \InvalidArgumentException('an error occured while checking a pattern in the cache', 0, $e));
73
                continue;
74
            }
75
76
            $success = null;
77
78
            try {
79
                $file = $this->cache->getItem('browscap.patterns.' . $tmpSubkey, true, $success);
80
            } catch (InvalidArgumentException $e) {
81
                $this->logger->error(new \InvalidArgumentException('an error occured while reading the pattern data data from the cache', 0, $e));
82
83
                continue;
84
            }
85
86
87
            if (! $success) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $success of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
88
                $this->logger->debug('cache key "browscap.patterns.' . $tmpSubkey . '" not found');
89
90
                continue;
91
            }
92
93
            if (! is_array($file) || ! count($file)) {
94
                $this->logger->debug('cache key "browscap.patterns.' . $tmpSubkey . '" was empty');
95
96
                continue;
97
            }
98
99
            $found = false;
100
101
            foreach ($file as $buffer) {
102
                list($tmpBuffer, $len, $patterns) = explode("\t", $buffer, 3);
103
104
                if ($tmpBuffer === $tmpStart) {
105
                    if ($len <= $length) {
106
                        yield trim($patterns);
107
                    }
108
109
                    $found = true;
110
                } elseif ($found === true) {
111
                    break;
112
                }
113
            }
114
        }
115
116
        yield '';
117
    }
118
}
119