Test Failed
Push — trunk ( 132e87...b3f953 )
by SuperNova.WS
11:54
created

BanHammer   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 13
dl 0
loc 40
rs 10
c 1
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getByIpV4() 0 12 4
A checkIpV4() 0 2 1
1
<?php
2
3
/** Created by Gorlum 25.02.2025 13:16 */
4
5
/**
6
 *
7
 * MySQL: INET_ATON() -> string to int, INET_NTOA() -> int to string
8
 * PHP: ip2long -> string to int, long2ip() -> int to string
9
 */
10
class BanHammer {
11
  /** Ban record can be of any expirations */
12
  const EXPIRED_ANY = null;
13
  /** Ban record should NOT be active */
14
  const EXPIRED_NOT = false;
15
  /** Ban record should ALREADY be expired */
16
  const EXPIRED_ALREADY = true;
17
18
  /**
19
   * Get ban records for specified IPv4 address from ban table with appropriate status
20
   *
21
   * @param int|string $ipV4 IPv4 address to check. Can be ether string like `192.168.1.1` or integer like 3232235777 (int unsigned)
22
   * @param ?bool      $isExpired
23
   *
24
   * @return array[]|object[]
25
   */
26
  public static function getByIpV4($ipV4, $isExpired = self::EXPIRED_NOT) {
27
    $ipV4 = !is_numeric($ipV4) ? ip2long($ipV4) : (integer)$ipV4;
28
29
    $sqlArray = [
30
      "SELECT *, INET_NTOA(`ipv4_from`) as ipv4_from_string, INET_NTOA(`ipv4_to`) as ipv4_to_string
31
       FROM {{ban_ip}}
32
       WHERE ipv4_from <= $ipV4 AND ipv4_to >= $ipV4",
33
      $isExpired === self::EXPIRED_ANY ? ''
34
        : ('AND `expired_at` ' . ($isExpired === self::EXPIRED_NOT ? '>=' : '<') . ' NOW()'),
35
    ];
36
37
    return SN::$db->dbGetAll(implode(' ', $sqlArray));
38
  }
39
40
  /**
41
   * Check if specified IPv4 address is currently fit specified status
42
   *
43
   * @param int|string $ipV4      IPv4 address to check. Can be ether string like `192.168.1.1` or integer like 3232235777 (int unsigned)
44
   * @param ?bool      $isExpired @see BanHammer::EXPIRED_ANY EXPIRED_XXX class constants
45
   *
46
   * @return bool
47
   */
48
  public static function checkIpV4($ipV4, $isExpired = self::EXPIRED_NOT) {
49
    return !empty(static::getByIpV4($ipV4, $isExpired));
50
  }
51
52
}
53