GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#844)
by
unknown
02:38
created

Here::executeQuery()   C

Complexity

Conditions 11
Paths 17

Size

Total Lines 54
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 54
rs 6.6153
c 0
b 0
f 0
cc 11
eloc 37
nc 17
nop 2

How to fix   Long Method    Complexity   

Long Method

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:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Geocoder package.
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * @license    MIT License
11
 */
12
13
namespace Geocoder\Provider\Here;
14
15
use Geocoder\Collection;
16
use Geocoder\Exception\InvalidCredentials;
17
use Geocoder\Exception\UnsupportedOperation;
18
use Geocoder\Model\AddressBuilder;
19
use Geocoder\Model\AddressCollection;
20
use Geocoder\Query\GeocodeQuery;
21
use Geocoder\Query\ReverseQuery;
22
use Geocoder\Http\Provider\AbstractHttpProvider;
23
use Geocoder\Provider\Provider;
24
use Geocoder\Provider\Here\Model\HereAddress;
25
use Http\Client\HttpClient;
26
27
/**
28
 * @author Sébastien Barré <[email protected]>
29
 */
30
final class Here extends AbstractHttpProvider implements Provider
31
{
32
    /**
33
     * @var string
34
     */
35
    const GEOCODE_ENDPOINT_URL = 'https://geocoder.api.here.com/6.2/geocode.json?app_id=%s&app_code=%s&searchtext=%s&gen=8';
36
37
    /**
38
     * @var string
39
     */
40
    const REVERSE_ENDPOINT_URL = 'https://reverse.geocoder.api.here.com/6.2/reversegeocode.json?prox=%F,%F&250&app_id=%s&app_code=%s&mode=retrieveAddresses&gen=8&maxresults=%d';
41
42
    /**
43
     * @var string
44
     */
45
    private $appId = null;
46
47
    /**
48
     * @var string
49
     */
50
    private $appCode = null;
51
52
    /**
53
     * @param HttpClient $adapter An HTTP adapter.
0 ignored issues
show
Bug introduced by
There is no parameter named $adapter. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
54
     * @param string     $appId   An App ID.
55
     * @param string     $apoCode An App code.
0 ignored issues
show
Bug introduced by
There is no parameter named $apoCode. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
56
     */
57
    public function __construct(HttpClient $client, string $appId, string $appCode)
58
    {
59
        if (empty($appId) || empty($appCode)) {
60
            throw new InvalidCredentials('Invalid or missing api key.');
61
        }
62
        $this->appId = $appId;
63
        $this->appCode = $appCode;
64
65
        parent::__construct($client);
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    public function geocodeQuery(GeocodeQuery $query): Collection
72
    {
73
        // This API doesn't handle IPs
74
        if (filter_var($query->getText(), FILTER_VALIDATE_IP)) {
75
            throw new UnsupportedOperation('The Here provider does not support IP addresses, only street addresses.');
76
        }
77
78
        $url = sprintf(self::GEOCODE_ENDPOINT_URL, $this->appId, $this->appCode, rawurlencode($query->getText()));
79
80
        if (null !== $query->getLocale()) {
81
            $url = sprintf('%s&language=%s', $url, $query->getLocale());
82
        }
83
84
        return $this->executeQuery($url, $query->getLimit());
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    public function reverseQuery(ReverseQuery $query): Collection
91
    {
92
        $coordinates = $query->getCoordinates();
93
        $url = sprintf(self::REVERSE_ENDPOINT_URL, $coordinates->getLatitude(), $coordinates->getLongitude(), $this->appId, $this->appCode, $query->getLimit());
94
95
        return $this->executeQuery($url, $query->getLimit());
96
    }
97
98
    /**
99
     * @param string $url
100
     * @param string $locale
0 ignored issues
show
Bug introduced by
There is no parameter named $locale. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
101
     * @param int    $limit
102
     *
103
     * @return \Geocoder\Collection
104
     */
105
    private function executeQuery(string $url, int $limit): Collection
106
    {
107
        $content = $this->getUrlContents($url);
108
        $json = json_decode($content, true);
109
110
        if (isset($json['type'])) {
111
            switch ($json['type']['subtype']) {
112
                case 'InvalidInputData':
113
                    throw new InvalidArgument('Input parameter validation failed.');
114
                case 'QuotaExceeded':
115
                    throw new QuotaExceeded('Valid request but quota exceeded.');
116
                case 'InvalidCredentials':
117
                    throw new InvalidCredentials('Invalid or missing api key.');
118
            }
119
        }
120
121
        if (!isset($json['Response']) || empty($json['Response'])) {
122
            return new AddressCollection([]);
123
        }
124
125
        if (!isset($json['Response']['View'][0])) {
126
            return new AddressCollection([]);
127
        }
128
129
        $locations = $json['Response']['View'][0]['Result'];
130
131
        foreach ($locations as $loc) {
132
            $location = $loc['Location'];
133
            $builder = new AddressBuilder($this->getName());
134
            $coordinates = isset($location['NavigationPosition'][0]) ? $location['NavigationPosition'][0] : $location['DisplayPosition'];
135
            $builder->setCoordinates($coordinates['Latitude'], $coordinates['Longitude']);
136
            $bounds = $location['MapView'];
137
138
            $builder->setBounds($bounds['BottomRight']['Latitude'], $bounds['TopLeft']['Longitude'], $bounds['TopLeft']['Latitude'], $bounds['BottomRight']['Longitude']);
139
            $builder->setStreetNumber($location['Address']['HouseNumber'] ?? null);
140
            $builder->setStreetName($location['Address']['Street'] ?? null);
141
            $builder->setPostalCode($location['Address']['PostalCode'] ?? null);
142
            $builder->setLocality($location['Address']['City'] ?? null);
143
            $builder->setSubLocality($location['Address']['District'] ?? null);
144
            $builder->setCountry($location['Address']['AdditionalData'][0]['value'] ?? null);
145
            $builder->setCountryCode($location['Address']['Country'] ?? null);
146
147
            $address = $builder->build(HereAddress::class);
148
            $address = $address->withLocationId($location['LocationId']);
149
            $address = $address->withLocationType($location['LocationType']);
150
            $results[] = $address;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$results was never initialized. Although not strictly required by PHP, it is generally a good practice to add $results = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
151
152
            if (count($results) >= $limit) {
153
                break;
154
            }
155
        }
156
157
        return new AddressCollection($results);
0 ignored issues
show
Bug introduced by
The variable $results does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
158
    }
159
160
    /**
161
     * {@inheritdoc}
162
     */
163
    public function getName(): string
164
    {
165
        return 'Here';
166
    }
167
}
168