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.

Yandex::executeQuery()   C
last analyzed

Complexity

Conditions 19
Paths 16

Size

Total Lines 71
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 71
rs 5.4997
cc 19
eloc 43
nc 16
nop 3

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\Yandex;
14
15
use Geocoder\Collection;
16
use Geocoder\Exception\UnsupportedOperation;
17
use Geocoder\Model\AddressCollection;
18
use Geocoder\Model\AddressBuilder;
19
use Geocoder\Provider\Yandex\Model\YandexAddress;
20
use Geocoder\Query\GeocodeQuery;
21
use Geocoder\Query\ReverseQuery;
22
use Geocoder\Http\Provider\AbstractHttpProvider;
23
use Geocoder\Provider\Provider;
24
use Http\Client\HttpClient;
25
26
/**
27
 * @author Antoine Corcy <[email protected]>
28
 */
29
final class Yandex extends AbstractHttpProvider implements Provider
30
{
31
    /**
32
     * @var string
33
     */
34
    const GEOCODE_ENDPOINT_URL = 'https://geocode-maps.yandex.ru/1.x/?format=json&geocode=%s';
35
36
    /**
37
     * @var string
38
     */
39
    const REVERSE_ENDPOINT_URL = 'https://geocode-maps.yandex.ru/1.x/?format=json&geocode=%F,%F';
40
41
    /**
42
     * @var string
43
     */
44
    private $toponym;
45
46
    /**
47
     * @param HttpClient $client  an HTTP adapter
48
     * @param string     $toponym toponym biasing only for reverse geocoding (optional)
0 ignored issues
show
Documentation introduced by
Should the type for parameter $toponym not be null|string?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
49
     */
50
    public function __construct(HttpClient $client, string $toponym = null)
51
    {
52
        parent::__construct($client);
53
54
        $this->toponym = $toponym;
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function geocodeQuery(GeocodeQuery $query): Collection
61
    {
62
        $address = $query->getText();
63
        // This API doesn't handle IPs
64
        if (filter_var($address, FILTER_VALIDATE_IP)) {
65
            throw new UnsupportedOperation('The Yandex provider does not support IP addresses, only street addresses.');
66
        }
67
68
        $url = sprintf(self::GEOCODE_ENDPOINT_URL, urlencode($address));
69
70
        return $this->executeQuery($url, $query->getLocale(), $query->getLimit());
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     */
76
    public function reverseQuery(ReverseQuery $query): Collection
77
    {
78
        $coordinates = $query->getCoordinates();
79
        $longitude = $coordinates->getLongitude();
80
        $latitude = $coordinates->getLatitude();
81
        $url = sprintf(self::REVERSE_ENDPOINT_URL, $longitude, $latitude);
82
83
        if (null !== $toponym = $query->getData('toponym', $this->toponym)) {
84
            $url = sprintf('%s&kind=%s', $url, $toponym);
85
        }
86
87
        return $this->executeQuery($url, $query->getLocale(), $query->getLimit());
88
    }
89
90
    /**
91
     * {@inheritdoc}
92
     */
93
    public function getName(): string
94
    {
95
        return 'yandex';
96
    }
97
98
    /**
99
     * @param string      $url
100
     * @param string|null $locale
101
     * @param int         $limit
102
     *
103
     * @return AddressCollection
104
     */
105
    private function executeQuery(string $url, string $locale = null, int $limit): AddressCollection
106
    {
107
        if (null !== $locale) {
108
            $url = sprintf('%s&lang=%s', $url, str_replace('_', '-', $locale));
109
        }
110
111
        $url = sprintf('%s&results=%d', $url, $limit);
112
        $content = $this->getUrlContents($url);
113
        $json = json_decode($content, true);
114
115
        if (empty($json) || isset($json['error']) ||
116
            (isset($json['response']) && '0' === $json['response']['GeoObjectCollection']['metaDataProperty']['GeocoderResponseMetaData']['found'])
117
        ) {
118
            return new AddressCollection([]);
119
        }
120
121
        $data = $json['response']['GeoObjectCollection']['featureMember'];
122
123
        $locations = [];
124
        foreach ($data as $item) {
125
            $builder = new AddressBuilder($this->getName());
126
            $bounds = null;
0 ignored issues
show
Unused Code introduced by
$bounds is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
127
            $flatArray = ['pos' => ' '];
128
129
            array_walk_recursive(
130
                $item['GeoObject'],
131
132
                /**
133
                 * @param string $value
134
                 */
135
                function ($value, $key) use (&$flatArray) {
136
                    $flatArray[$key] = $value;
137
                }
138
            );
139
140
            if (!empty($flatArray['lowerCorner']) && !empty($flatArray['upperCorner'])) {
141
                $lowerCorner = explode(' ', $flatArray['lowerCorner']);
142
                $upperCorner = explode(' ', $flatArray['upperCorner']);
143
                $builder->setBounds(
144
                    (float) $lowerCorner[1],
145
                    (float) $lowerCorner[0],
146
                    (float) $upperCorner[1],
147
                    (float) $upperCorner[0]
148
                );
149
            }
150
151
            $coordinates = explode(' ', $flatArray['pos']);
152
            $builder->setCoordinates((float) $coordinates[1], (float) $coordinates[0]);
153
154
            foreach (['AdministrativeAreaName', 'SubAdministrativeAreaName'] as $i => $name) {
155
                if (isset($flatArray[$name])) {
156
                    $builder->addAdminLevel($i + 1, $flatArray[$name], null);
157
                }
158
            }
159
160
            $builder->setStreetNumber(isset($flatArray['PremiseNumber']) ? $flatArray['PremiseNumber'] : null);
161
            $builder->setStreetName(isset($flatArray['ThoroughfareName']) ? $flatArray['ThoroughfareName'] : null);
162
            $builder->setSubLocality(isset($flatArray['DependentLocalityName']) ? $flatArray['DependentLocalityName'] : null);
163
            $builder->setLocality(isset($flatArray['LocalityName']) ? $flatArray['LocalityName'] : null);
164
            $builder->setCountry(isset($flatArray['CountryName']) ? $flatArray['CountryName'] : null);
165
            $builder->setCountryCode(isset($flatArray['CountryNameCode']) ? $flatArray['CountryNameCode'] : null);
166
167
            /** @var YandexAddress $location */
168
            $location = $builder->build(YandexAddress::class);
169
            $location = $location->withPrecision(isset($flatArray['precision']) ? $flatArray['precision'] : null);
170
            $location = $location->withName(isset($flatArray['name']) ? $flatArray['name'] : null);
171
            $locations[] = $location;
172
        }
173
174
        return new AddressCollection($locations);
175
    }
176
}
177