Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
25 / 25 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
RebuildIpAddressService | |
100.00% |
25 / 25 |
|
100.00% |
3 / 3 |
7 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
rebuild | |
100.00% |
15 / 15 |
|
100.00% |
1 / 1 |
5 | |||
getIpAddresses | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
1 |
1 | <?php |
2 | |
3 | namespace Drupal\visitors\Service; |
4 | |
5 | use Drupal\Core\Database\Connection; |
6 | use Drupal\Core\Utility\Error; |
7 | use Drupal\visitors\VisitorsRebuildIpAddressInterface; |
8 | use Psr\Log\LoggerInterface; |
9 | |
10 | /** |
11 | * Convert legacy IP address to new format. |
12 | */ |
13 | class RebuildIpAddressService implements VisitorsRebuildIpAddressInterface { |
14 | |
15 | const ERROR = -1; |
16 | |
17 | /** |
18 | * The database connection. |
19 | * |
20 | * @var \Drupal\Core\Database\Connection |
21 | */ |
22 | protected $database; |
23 | |
24 | /** |
25 | * The logger. |
26 | * |
27 | * @var \Psr\Log\LoggerInterface |
28 | */ |
29 | protected $logger; |
30 | |
31 | /** |
32 | * Constructs a new Rebuild Route Service. |
33 | * |
34 | * @param \Drupal\Core\Database\Connection $connection |
35 | * The database connection. |
36 | * @param \Psr\Log\LoggerInterface $logger |
37 | * The logger. |
38 | */ |
39 | public function __construct(Connection $connection, LoggerInterface $logger) { |
40 | $this->database = $connection; |
41 | $this->logger = $logger; |
42 | } |
43 | |
44 | /** |
45 | * {@inheritdoc} |
46 | */ |
47 | public function rebuild(string $ip_address): int { |
48 | if (inet_pton($ip_address) !== FALSE) { |
49 | return 0; |
50 | } |
51 | $new_address = NULL; |
52 | if (inet_ntop($ip_address) !== FALSE) { |
53 | $new_address = inet_ntop($ip_address); |
54 | } |
55 | elseif (long2ip((int) $ip_address) !== FALSE) { |
56 | $new_address = long2ip((int) $ip_address); |
57 | } |
58 | |
59 | $count = self::ERROR; |
60 | try { |
61 | $count = $this->database->update('visitors') |
62 | ->fields(['visitors_ip' => $new_address]) |
63 | ->condition('visitors_ip', $ip_address) |
64 | ->execute(); |
65 | } |
66 | catch (\Exception $e) { |
67 | Error::logException($this->logger, $e); |
68 | } |
69 | |
70 | return $count; |
71 | } |
72 | |
73 | /** |
74 | * {@inheritdoc} |
75 | */ |
76 | public function getIpAddresses(): array { |
77 | $ip_addresses = $this->database->select('visitors', 'v') |
78 | ->fields('v', [ |
79 | 'visitors_ip', |
80 | ]) |
81 | ->distinct() |
82 | ->orderBy('visitors_ip', 'ASC') |
83 | ->execute()->fetchAll(); |
84 | |
85 | return $ip_addresses; |
86 | } |
87 | |
88 | } |