Completed
Push — master ( 85d367...f929c4 )
by Mark
02:03
created

CrawlerDetect::getExclusions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of Crawler Detect - the web crawler detection library.
5
 *
6
 * (c) Mark Beech <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Jaybizzle\CrawlerDetect;
13
14
use Jaybizzle\CrawlerDetect\Fixtures\Crawlers;
15
use Jaybizzle\CrawlerDetect\Fixtures\Exclusions;
16
17
class CrawlerDetect
18
{
19
    /**
20
     * The user agent.
21
     *
22
     * @var null
23
     */
24
    protected $userAgent = null;
25
26
    /**
27
     * Headers that contain a user agent.
28
     *
29
     * @var array
30
     */
31
    protected $httpHeaders = array();
32
33
    /**
34
     * Store regex matches.
35
     *
36
     * @var array
37
     */
38
    protected $matches = array();
39
40
    /**
41
     * Crawlers object.
42
     *
43
     * @var \Jaybizzle\CrawlerDetect\Fixtures\Crawlers
44
     */
45
    protected $crawlers;
46
47
    /**
48
     * Exclusions object.
49
     *
50
     * @var \Jaybizzle\CrawlerDetect\Fixtures\Exclusions
51
     */
52
    protected $exclusions;
53
54
    /**
55
     * All possible HTTP headers that represent the
56
     * User-Agent string.
57
     *
58
     * @var array
59
     */
60
    protected static $uaHttpHeaders = array(
61
        // The default User-Agent string.
62
        'HTTP_USER_AGENT',
63
        // Header can occur on devices using Opera Mini.
64
        'HTTP_X_OPERAMINI_PHONE_UA',
65
        // Vodafone specific header: http://www.seoprinciple.com/mobile-web-community-still-angry-at-vodafone/24/
66
        'HTTP_X_DEVICE_USER_AGENT',
67
        'HTTP_X_ORIGINAL_USER_AGENT',
68
        'HTTP_X_SKYFIRE_PHONE',
69
        'HTTP_X_BOLT_PHONE_UA',
70
        'HTTP_DEVICE_STOCK_UA',
71
        'HTTP_X_UCBROWSER_DEVICE_UA',
72
    );
73
74
    /**
75
     * Class constructor.
76
     */
77
    public function __construct(array $headers = null, $userAgent = null)
78
    {
79
        $this->setHttpHeaders($headers);
80
        $this->setUserAgent($userAgent);
81
        $this->crawlers = new Crawlers();
82
        $this->exclusions = new Exclusions();
83
    }
84
85
    /**
86
     * Set HTTP headers.
87
     *
88
     * @param array $httpHeaders
89
     */
90
    public function setHttpHeaders($httpHeaders = null)
0 ignored issues
show
Coding Style introduced by
setHttpHeaders uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
91
    {
92
        // use global _SERVER if $httpHeaders aren't defined
93
        if (!is_array($httpHeaders) || !count($httpHeaders)) {
94
            $httpHeaders = $_SERVER;
95
        }
96
        // clear existing headers
97
        $this->httpHeaders = array();
98
        // Only save HTTP headers. In PHP land, that means only _SERVER vars that
99
        // start with HTTP_.
100
        foreach ($httpHeaders as $key => $value) {
101
            if (substr($key, 0, 5) === 'HTTP_') {
102
                $this->httpHeaders[$key] = $value;
103
            }
104
        }
105
    }
106
107
    /**
108
     * Return user agent headers.
109
     *
110
     * @return array
111
     */
112
    public function getUaHttpHeaders()
113
    {
114
        return self::$uaHttpHeaders;
115
    }
116
117
    /**
118
     * Set the user agent.
119
     *
120
     * @param string $userAgent
121
     */
122
    public function setUserAgent($userAgent = null)
123
    {
124
        if (false === empty($userAgent)) {
125
            return $this->userAgent = $userAgent;
0 ignored issues
show
Documentation Bug introduced by
It seems like $userAgent of type string is incompatible with the declared type null of property $userAgent.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
126
        } else {
127
            $this->userAgent = null;
128
            foreach ($this->getUaHttpHeaders() as $altHeader) {
129
                if (false === empty($this->httpHeaders[$altHeader])) { // @todo: should use getHttpHeader(), but it would be slow.
130
                    $this->userAgent .= $this->httpHeaders[$altHeader].' ';
131
                }
132
            }
133
134
            return $this->userAgent = (!empty($this->userAgent) ? trim($this->userAgent) : null);
0 ignored issues
show
Documentation Bug introduced by
It seems like !empty($this->userAgent)...this->userAgent) : null can also be of type string. However, the property $userAgent is declared as type null. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
135
        }
136
    }
137
138
    /**
139
     * Build the user agent regex.
140
     *
141
     * @return string
142
     */
143
    public function getRegex()
144
    {
145
        return '('.implode('|', $this->crawlers->getAll()).')';
146
    }
147
148
    /**
149
     * Build the replacement regex.
150
     *
151
     * @return string
152
     */
153
    public function getExclusions()
154
    {
155
        return '('.implode('|', $this->exclusions->getAll()).')';
156
    }
157
158
    /**
159
     * Check user agent string against the regex.
160
     *
161
     * @param string $userAgent
162
     *
163
     * @return bool
164
     */
165
    public function isCrawler($userAgent = null)
166
    {
167
        $agent = is_null($userAgent) ? $this->userAgent : $userAgent;
168
169
        $agent = preg_replace('/'.$this->getExclusions().'/i', '', $agent);
170
171
        if (trim($agent) === false) {
172
            return false;
173
        } else {
174
            $result = preg_match('/'.$this->getRegex().'/i', trim($agent), $matches);
175
        }
176
177
        if ($matches) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $matches of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
178
            $this->matches = $matches;
179
        }
180
181
        return (bool) $result;
182
    }
183
184
    /**
185
     * Return the matches.
186
     *
187
     * @return string
188
     */
189
    public function getMatches()
190
    {
191
        return $this->matches[0];
192
    }
193
}
194