IPTrait::attachInitIPEvent()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
3
/**
4
 *   _   __ __ _____ _____ ___  ____  _____
5
 *  | | / // // ___//_  _//   ||  __||_   _|
6
 *  | |/ // /(__  )  / / / /| || |     | |
7
 *  |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link https://vistart.me/
9
 * @copyright Copyright (c) 2016 - 2017 vistart
10
 * @license https://vistart.me/license/
11
 */
12
13
namespace rhosocial\base\models\traits;
14
15
use rhosocial\base\helpers\IP;
16
use Yii;
17
use yii\base\ModelEvent;
18
use yii\web\Request;
19
20
/**
21
 * The IP address features.
22
 * @property string|null $ipAddress
23
 * @property integer $ipType
24
 * @proeperty array $ipRules
25
 * @version 1.0
26
 * @author vistart <[email protected]>
27
 */
28
trait IPTrait
29
{
30
    /**
31
     * @var integer REQUIRED. Determine whether the IP attributes if enabled.
32
     * All the parameters accepted are listed below.
33
     */
34
    public $enableIP = 0x3;
35
    public static $noIP = 0x0;
36
    public static $ipv4 = 0x1;
37
    public static $ipv6 = 0x2;
38
    public static $ipAll = 0x3;
39
    
40
    public $ipAttribute = 'ip';
41
    public $ipTypeAttribute = 'ip_type';
42
    public $requestId = 'request';
43
    
44 392
    protected function getWebRequest()
45
    {
46 392
        $requestId = $this->requestId;
47 392
        if (!empty($requestId) && is_string($requestId)) {
48 392
            $request = Yii::$app->$requestId;
49
        } else {
50 1
            $request = Yii::$app->request;
51
        }
52 392
        if ($request instanceof Request) {
53 392
            return $request;
54
        }
55 1
        return null;
56
    }
57
    
58 392
    protected function attachInitIPEvent($eventName)
59
    {
60 392
        $this->on($eventName, [$this, 'onInitIPAddress']);
0 ignored issues
show
Bug introduced by
It seems like on() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
61 392
    }
62
    
63
    /**
64
     * Initialize IP Attributes.
65
     * This method is ONLY used for being triggered by event. DO NOT call,
66
     * override or modify it directly, unless you know the consequences.
67
     * @param ModelEvent $event
68
     */
69 392
    public function onInitIPAddress($event)
70
    {
71 392
        $sender = $event->sender;
72 392
        $request = $sender->getWebRequest();
73 392
        if ($sender->enableIP && $request && empty($sender->ipAddress)) {
74 392
            $sender->ipAddress = $request->userIP;
75
        }
76 392
    }
77
    
78
    /**
79
     * Get the IPv4 address.
80
     * @return string
81
     */
82 11
    protected function getIPv4Address()
83
    {
84 11
        return $this->{$this->ipTypeAttribute} == IP::IPv4 ? inet_ntop($this->{$this->ipAttribute}) : null;
85
    }
86
    
87
    /**
88
     * Get the IPv6 address.
89
     * @return string
90
     */
91 7
    protected function getIPv6Address()
92
    {
93 7
        return $this->{$this->ipTypeAttribute} == IP::IPv6 ? inet_ntop($this->{$this->ipAttribute}) : null;
94
    }
95
    
96
    /**
97
     *
98
     * @param string $ipAddress IPv4 address.
99
     * @return string
100
     */
101 7
    protected function setIPv4Address($ipAddress)
102
    {
103 7
        return $this->{$this->ipAttribute} = inet_pton($ipAddress);
104
    }
105
    
106
    /**
107
     *
108
     * @param string $ipAddress IPv6 address.
109
     * @return string
110
     */
111 3
    protected function setIPv6Address($ipAddress)
112
    {
113 3
        return $this->{$this->ipAttribute} = inet_pton($ipAddress);
114
    }
115
    
116
    /**
117
     *
118
     * @return string
119
     */
120 392
    public function getIPAddress()
121
    {
122 392
        if (!$this->enableIP) {
123 6
            return null;
124
        }
125
        try {
126 392
            if ($this->enableIP == static::$ipv4) {
127 7
                return $this->getIPv4Address();
128 392
            } elseif ($this->enableIP == static::$ipv6) {
129 7
                return $this->getIPv6Address();
130 392
            } elseif ($this->enableIP == static::$ipAll) {
131 392
                if ($this->{$this->ipTypeAttribute} == IP::IPv4) {
132 10
                    return $this->getIPv4Address();
133
                }
134 392
                if ($this->{$this->ipTypeAttribute} == IP::IPv6) {
135 6
                    return $this->getIPv6Address();
136
                }
137
            }
138
        } catch (\Exception $ex) {
139
            Yii::error($ex->getMessage(), __METHOD__);
140
        }
141 392
        return null;
142
    }
143
    
144
    /**
145
     * Convert the IP address to integer, and store it(them) to ipAttribute*.
146
     * If you disable($this->enableIP = false) the IP feature, this method will
147
     * be skipped(return null).
148
     * @param string $ipAddress the significantly IP address.
149
     * @return string|integer|null Integer when succeeded to convert.
150
     */
151 392
    public function setIPAddress($ipAddress)
152
    {
153 392
        if (!$ipAddress || !$this->enableIP) {
154 392
            return null;
155
        }
156 16
        $ipType = IP::judgeIPtype($ipAddress);
157 16
        if ($ipType == IP::IPv4 && $this->enableIP & static::$ipv4) {
158 10
            $this->setIPv4Address($ipAddress);
159 9
        } elseif ($ipType == Ip::IPv6 && $this->enableIP & static::$ipv6) {
160 6
            $this->setIPv6Address($ipAddress);
161
        } else {
162 6
            return 0;
163
        }
164 16
        if ($this->enableIP & static::$ipAll) {
165 16
            $this->{$this->ipTypeAttribute} = $ipType;
166
        }
167 16
        return $ipType;
168
    }
169
    
170
    /**
171
     * Get the rules associated with ip attributes.
172
     * @return array
173
     */
174 346
    public function getIPRules()
175
    {
176 346
        $rules = [];
177 346
        if ($this->enableIP & static::$ipv4) {
178
            $rules = [
179 346
                [[$this->ipAttribute],
180 346
                    'string', 'max' => 4
181
                ],
182
            ];
183
        }
184 346
        if ($this->enableIP & static::$ipv6) {
185
            $rules = [
186 346
                [[$this->ipAttribute],
187 346
                    'string', 'max' => 16
188
                ],
189
            ];
190
        }
191 346
        if ($this->enableIP & static::$ipAll) {
192 346
            $rules[] = [
193 346
                [$this->ipTypeAttribute], 'in', 'range' => [IP::IPv4, IP::IPv6],
194
            ];
195
        }
196 346
        return $rules;
197
    }
198
    
199
    /**
200
     * @inheritdoc
201
     */
202 136
    public function enabledIPFields()
203
    {
204 136
        $fields = [];
205 136
        switch ($this->enableIP) {
206 136
            case static::$ipAll:
207 135
                $fields[] = $this->ipTypeAttribute;
208 2
            case static::$ipv6:
209 2
            case static::$ipv4:
210 135
                $fields[] = $this->ipAttribute;
211 2
            case static::$noIP:
212
            default:
213 136
                break;
214
        }
215 136
        return $fields;
216
    }
217
}
218