Issues (42)

src/Controller/KrisWeatherApiController.php (6 issues)

1
<?php
2
3
namespace Kris3XIQ\Controller;
4
5
use Anax\Commons\ContainerInjectableInterface;
6
use Anax\Commons\ContainerInjectableTrait;
7
use Kris3XIQ\Service\APIService;
0 ignored issues
show
The type Kris3XIQ\Service\APIService was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Kris3XIQ\Weather\Weather;
9
10
// use Anax\Route\Exception\ForbiddenException;
11
// use Anax\Route\Exception\NotFoundException;
12
// use Anax\Route\Exception\InternalErrorException;
13
14
/**
15
 * A sample controller to show how a controller class can be implemented.
16
 * The controller will be injected with $di if implementing the interface
17
 * ContainerInjectableInterface, like this sample class does.
18
 * The controller is mounted on a particular route and can then handle all
19
 * requests for that mount point.
20
 *
21
 * @SuppressWarnings(PHPMD.TooManyPublicMethods)
22
 */
23
class KrisWeatherApiController implements ContainerInjectableInterface
24
{
25
    use ContainerInjectableTrait;
26
27
    /**
28
     * This is the index method action, it handles:
29
     * ANY METHOD mountpoint
30
     * ANY METHOD mountpoint/
31
     * ANY METHOD mountpoint/index
32
     *
33
     * @SuppressWarnings(PHPMD.UnusedLocalVariable)
34
     *
35
     * @return object
36
     */
37
    public function indexAction() : object
38
    {
39
        // Setting up variables.
40
        $title = "Weather service";
41
        $page = $this->di->get("page");
42
43
        // Get services to load and their API-keys.
44
        $service = $this->di->get("api-service");
45
        $service->setServiceToLoad("openweathermap");
46
        $owmApiKey = $service->getKeyToService();
47
        $service->setServiceToLoad("ipstack");
48
        $ipsApiKey = $service->getKeyToService("ipstack");
49
50
        // Setting up Weather
51
        $weather = new Weather();
52
        $weather->setKeyChain(array("openweathermap" => $owmApiKey, "ipstack" => $ipsApiKey));
53
        
54
        // Session variables
55
        $statusCode = $_SESSION["statusCode"] ?? null;
56
57
        // Add data to the view
58
        $data = [
59
            "statusCode" => $statusCode ?? null,
60
        ];
61
62
        // Grab a view
63
        $page->add("weather/weather-service-api", $data);
64
            
65
        return $page->render([
66
            "title" => $title,
67
        ]);
68
    }
69
70
    /**
71
     * This handles POST request
72
     *
73
     * @SuppressWarnings(PHPMD.UnusedLocalVariable)
74
     */
75
    public function indexActionPost()
76
    {
77
        // Set variables
78
        $response = $this->di->get("response");
0 ignored issues
show
The assignment to $response is dead and can be removed.
Loading history...
79
        $request = $this->di->get("request");
80
        $service = $this->di->get("api-service");
81
82
        // Grab post variables
83
        $external = false;
0 ignored issues
show
The assignment to $external is dead and can be removed.
Loading history...
84
        $input = $request->getPost("input");
85
        if (!$input) {
86
            $external = true;
87
            try {
88
                $body = $this->di->get("request")->getBodyAsJson();
89
            } catch (\Exception $e) {
90
                $data = [
91
                    "status_code" => 404,
92
                    "message" => "Something went wrong, read the API-documentation",
93
                    "details" => "Looks like your input was empty"
94
                ];
95
                return [$data];
96
            }
97
            if (is_array($body)) {
98
                if (!array_key_exists("input", $body)) {
99
                    $data = [
100
                        "status_code" => 404,
101
                        "message" => "Something went wrong, read the API-documentation",
102
                        "details" => "Make sure to use the key 'input', read documentation for examples",
103
                    ];
104
                    return [$data];
105
                }
106
            }
107
            $input = $body["input"];
108
        }
109
110
        // If user didnt input anything
111
        if ($input == "") {
112
            $data = [
113
                "status_code" => 404,
114
                "message" => "Something went wrong, read the API-documentation",
115
                "details" => "Looks like your input was empty"
116
            ];
117
            return [$data];
118
        }
119
120
        // Setting up Weather
121
        $weather = new Weather();
122
        $service->setServiceToLoad("openweathermap");
123
        $owmApiKey = $service->getKeyToService();
124
        $service->setServiceToLoad("ipstack");
125
        $ipsApiKey = $service->getKeyToService("ipstack");
126
        $weather->setKeyChain(array("openweathermap" => $owmApiKey, "ipstack" => $ipsApiKey));
127
        
128
        $filter = $weather->isIpAddress($input);
129
        if ($filter) {
130
            $loc = $weather->ipTrackWithGeolocation($input);
131
            $location = $loc["city"] . ", " . $loc["country_code"];
132
            $weatherCurrentJSON = $weather->getWeatherCurrentFromAPI($location);
133
            $weatherHistoryJSON = $weather->getWeatherHistoryFromAPI($loc["latitude"], $loc["longitude"]);
134
        } else {
135
            $weather->setApiKey($owmApiKey);
136
            $isVerified = $weather->verifyLocation($input);
137
            if ($isVerified != "404") {
138
                $weatherCurrentJSON = $weather->getWeatherCurrentFromAPI($input);
139
                $lon = $weatherCurrentJSON["coord"]["lon"];
140
                $lat = $weatherCurrentJSON["coord"]["lat"];
141
                $weatherHistoryJSON = $weather->getWeatherHistoryFromAPI($lat, $lon);
142
            } else {
143
                $data = [
144
                    "status_code" => 404,
145
                    "message" => "Something went wrong, read the API-documentation",
146
                    "details" => "Looks like your search for '$input' didnt match anything"
147
                ];
148
                return [$data];
149
            }
150
        }
151
152
        if ($weatherHistoryJSON) {
0 ignored issues
show
$weatherHistoryJSON is a non-empty array, thus is always true.
Loading history...
Bug Best Practice introduced by
The expression $weatherHistoryJSON of type array<string,array<string,string>|integer> is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
153
            $dataJSON = $weather->convertToJSON($weatherCurrentJSON, $weatherHistoryJSON);
154
            $_SESSION["statusCode"] = null;
155
        }
156
157
        return [$dataJSON];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $dataJSON does not seem to be defined for all execution paths leading up to this point.
Loading history...
158
    }
159
}
160