1 | <?php |
||
2 | |||
3 | namespace Bjos\Validate; |
||
4 | |||
5 | use Anax\Commons\ContainerInjectableInterface; |
||
6 | use Anax\Commons\ContainerInjectableTrait; |
||
7 | |||
8 | // use Anax\Route\Exception\ForbiddenException; |
||
9 | // use Anax\Route\Exception\NotFoundException; |
||
10 | // use Anax\Route\Exception\InternalErrorException; |
||
11 | |||
12 | /** |
||
13 | * Validates IP address and return a json response. |
||
14 | */ |
||
15 | class IpJsonController implements ContainerInjectableInterface |
||
16 | { |
||
17 | use ContainerInjectableTrait; |
||
18 | |||
19 | /** |
||
20 | * Shows basic instruction how to use api. |
||
21 | * |
||
22 | * @return array |
||
23 | */ |
||
24 | 1 | public function indexActionGet() : array |
|
25 | { |
||
26 | $json = [ |
||
27 | "data" => [ |
||
28 | 1 | "message" => "Use POST with IP-address in body to validate", |
|
29 | "example" => "POST /ip-json/ {'ip': '8.8.8.8'}", |
||
30 | ], |
||
31 | ]; |
||
32 | 1 | return [$json]; |
|
33 | } |
||
34 | |||
35 | /** |
||
36 | * Validates IP address in post method. |
||
37 | * |
||
38 | * @return array |
||
39 | */ |
||
40 | 4 | public function indexActionPost() : array |
|
41 | { |
||
42 | 4 | $valid = null; |
|
43 | 4 | $type = null; |
|
44 | 4 | $host = null; |
|
45 | // $page = $this->di->get("page"); |
||
46 | 4 | $ipAdr = $this->di->request->getPost("ip"); |
|
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
47 | |||
48 | 4 | if ($ipAdr) { |
|
49 | 3 | if (filter_var($ipAdr, FILTER_VALIDATE_IP)) { |
|
50 | 2 | $valid = true; |
|
51 | 2 | $host = gethostbyaddr($ipAdr); |
|
52 | } else { |
||
53 | 1 | $valid = false; |
|
54 | } |
||
55 | |||
56 | 3 | if ($valid) { |
|
57 | 2 | if (filter_var($ipAdr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { |
|
58 | 1 | $type = "IPV4"; |
|
59 | 1 | } elseif (filter_var($ipAdr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { |
|
60 | 1 | $type = "IPV6"; |
|
61 | } |
||
62 | } |
||
63 | $json = [ |
||
64 | 3 | "ip" => $ipAdr, |
|
65 | 3 | "valid" => $valid, |
|
66 | 3 | "type" => $type, |
|
67 | 3 | "host" => $host |
|
68 | ]; |
||
69 | } else { |
||
70 | 1 | http_response_code(400); |
|
71 | $json = [ |
||
72 | "error" => [ |
||
73 | 1 | "status" => http_response_code(), |
|
74 | 1 | "error" => "Bad Request", |
|
75 | 1 | "message" => "ip missing in body", |
|
76 | ] |
||
77 | ]; |
||
78 | } |
||
79 | |||
80 | 4 | return [$json]; |
|
81 | } |
||
82 | } |
||
83 |