GetPattern::getPatterns()   C
last analyzed

Complexity

Conditions 12
Paths 12

Size

Total Lines 66

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 156

Importance

Changes 0
Metric Value
dl 0
loc 66
ccs 0
cts 34
cp 0
rs 6.3151
c 0
b 0
f 0
cc 12
nc 12
nop 1
crap 156

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
                if (! $this->cache->hasItem('browscap.patterns.' . $tmpSubkey, true)) {
67
                    $this->logger->debug('cache key "browscap.patterns.' . $tmpSubkey . '" not found');
68
69
                    continue;
70
                }
71
            } catch (InvalidArgumentException $e) {
0 ignored issues
show
Bug introduced by
The class Psr\SimpleCache\InvalidArgumentException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
72
                $this->logger->error(new \InvalidArgumentException('an error occured while checking a pattern in the cache', 0, $e));
73
74
                continue;
75
            }
76
77
            $success = null;
78
79
            try {
80
                $file = $this->cache->getItem('browscap.patterns.' . $tmpSubkey, true, $success);
81
            } catch (InvalidArgumentException $e) {
0 ignored issues
show
Bug introduced by
The class Psr\SimpleCache\InvalidArgumentException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
82
                $this->logger->error(new \InvalidArgumentException('an error occured while reading the pattern data data from the cache', 0, $e));
83
84
                continue;
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
                [$tmpBuffer, $len, $patterns] = explode("\t", $buffer, 3);
0 ignored issues
show
Bug introduced by
The variable $tmpBuffer does not exist. Did you mean $buffer?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
Bug introduced by
The variable $len does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $patterns does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
103
104
                if ($tmpBuffer === $tmpStart) {
0 ignored issues
show
Bug introduced by
The variable $tmpBuffer does not exist. Did you mean $buffer?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
105
                    if ($len <= $length) {
106
                        yield trim($patterns);
107
                    }
108
109
                    $found = true;
110
                } elseif (true === $found) {
111
                    break;
112
                }
113
            }
114
        }
115
116
        yield '';
117
    }
118
}
119