IpFilter   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
wmc 13
eloc 16
c 3
b 1
f 0
dl 0
loc 51
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isAllowed() 0 11 6
A checkIp() 0 4 4
A init() 0 9 3
1
<?php
2
3
namespace dominus77\maintenance\filters;
4
5
use Yii;
6
use yii\web\Application;
7
use yii\web\Request;
8
use dominus77\maintenance\Filter;
9
10
/**
11
 * IP addresses checker with mask supported.
12
 * @package dominus77\maintenance\filters
13
 */
14
class IpFilter extends Filter
15
{
16
    /**
17
     * @var array|string
18
     */
19
    public $ips;
20
    /**
21
     * @var Request|null
22
     */
23
    protected $request;
24
25
    /**
26
     * @inheritdoc
27
     */
28
    public function init()
29
    {
30
        if (Yii::$app instanceof Application) {
31
            $this->request = Yii::$app->request;
32
        }
33
        if (is_string($this->ips)) {
34
            $this->ips = [$this->ips];
35
        }
36
        parent::init();
37
    }
38
39
    /**
40
     * @return bool
41
     */
42
    public function isAllowed()
43
    {
44
        if ($this->request && is_array($this->ips) && !empty($this->ips)) {
45
            $ip = $this->request->userIP;
46
            foreach ($this->ips as $filter) {
47
                if ($this->checkIp($filter, $ip)) {
48
                    return true;
49
                }
50
            }
51
        }
52
        return false;
53
    }
54
55
    /**
56
     * Check IP (mask supported).
57
     * @param string $filter
58
     * @param string $ip
59
     * @return bool
60
     */
61
    protected function checkIp($filter, $ip)
62
    {
63
        return $filter === '*' || $filter === $ip
64
            || (($pos = strpos($filter, '*')) !== false && !strncmp($ip, $filter, $pos));
65
    }
66
}
67