Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
15.00% covered (danger)
15.00%
3 / 20
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
HttpGeoLocation
15.00% covered (danger)
15.00%
3 / 20
0.00% covered (danger)
0.00%
0 / 2
71.41
0.00% covered (danger)
0.00%
0 / 1
 __construct
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
 locate
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
56
1<?php
2
3namespace CookieWarning;
4
5use InvalidArgumentException;
6use MediaWiki\Http\HttpRequestFactory;
7use Wikimedia\IPUtils;
8
9/**
10 * Implements the GeoLocation class, which allows to locate the user based on the IP address.
11 */
12class HttpGeoLocation implements GeoLocation {
13    private $geoIPServiceURL;
14    private $locatedIPs = [];
15
16    /** @var HttpRequestFactory */
17    private $httpRequestFactory;
18
19    /**
20     * @param string $geoIPServiceURL
21     * @param HttpRequestFactory $httpRequestFactory
22     */
23    public function __construct( $geoIPServiceURL, HttpRequestFactory $httpRequestFactory ) {
24        if ( !is_string( $geoIPServiceURL ) || !$geoIPServiceURL ) {
25            throw new InvalidArgumentException( 'The geoIPServiceUL is invalid' );
26        }
27        $this->geoIPServiceURL = $geoIPServiceURL;
28        $this->httpRequestFactory = $httpRequestFactory;
29    }
30
31    /**
32     * {@inheritdoc}
33     * @param string $ip The IP address to lookup
34     * @return string|null
35     */
36    public function locate( $ip ) {
37        if ( isset( $this->locatedIPs[$ip] ) ) {
38            return $this->locatedIPs[$ip];
39        }
40        if ( !IPUtils::isValid( $ip ) ) {
41            throw new InvalidArgumentException( "$ip is not a valid IP address." );
42        }
43        if ( substr( $this->geoIPServiceURL, -1 ) !== '/' ) {
44            $this->geoIPServiceURL .= '/';
45        }
46        $json = $this->httpRequestFactory->get( $this->geoIPServiceURL . $ip, [
47            'timeout' => '2',
48        ] );
49        if ( !$json ) {
50            return null;
51        }
52        $returnObject = json_decode( $json );
53        if ( $returnObject === null || !property_exists( $returnObject, 'country_code' ) ) {
54            return null;
55        }
56        $this->locatedIPs[$ip] = $returnObject->country_code;
57
58        return $this->locatedIPs[$ip];
59    }
60}