| Conditions | 13 |
| Paths | 25 |
| Total Lines | 45 |
| Code Lines | 28 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
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:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 19 | function smarty_modifier_cidr(string $ipAddress, ?int $cidr): string { |
||
| 20 | if (filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { |
||
| 21 | if ($cidr === null) { |
||
| 22 | $cidr = 32; |
||
| 23 | } |
||
| 24 | |||
| 25 | if ($cidr < 0 || $cidr > 32) { |
||
| 26 | throw new InvalidArgumentException("Invalid CIDR prefix for IPv4: $cidr"); |
||
| 27 | } |
||
| 28 | |||
| 29 | $ipLong = ip2long($ipAddress); |
||
| 30 | $mask = -1 << (32 - $cidr); |
||
| 31 | $network = $ipLong & $mask; |
||
| 32 | |||
| 33 | return long2ip($network); |
||
| 34 | } |
||
| 35 | elseif (filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { |
||
| 36 | if ($cidr === null) { |
||
| 37 | $cidr = 64; |
||
| 38 | } |
||
| 39 | |||
| 40 | if ($cidr < 0 || $cidr > 128) { |
||
| 41 | throw new InvalidArgumentException("Invalid CIDR prefix for IPv6: $cidr"); |
||
| 42 | } |
||
| 43 | |||
| 44 | $ipBin = inet_pton($ipAddress); |
||
| 45 | $prefix = $cidr; |
||
| 46 | $bin = ''; |
||
| 47 | for ($i = 0; $i < strlen($ipBin); $i++) { |
||
| 48 | $bits = 8; |
||
| 49 | if ($prefix < 8) { |
||
| 50 | $bits = $prefix; |
||
| 51 | } |
||
| 52 | $mask = $bits === 0 ? 0 : (0xFF << (8 - $bits)) & 0xFF; |
||
| 53 | $bin .= chr(ord($ipBin[$i]) & $mask); |
||
| 54 | $prefix -= $bits; |
||
| 55 | if ($prefix <= 0) { |
||
| 56 | $prefix = 0; |
||
| 57 | } |
||
| 58 | } |
||
| 59 | |||
| 60 | return inet_ntop($bin); |
||
| 61 | } |
||
| 62 | |||
| 63 | throw new InvalidArgumentException("Invalid IP address: $ipAddress"); |
||
| 64 | } |