Completed
Push — master ( f3bfa6...b4eba1 )
by Daryl
02:03
created

Geocoder::_get_state_from_results()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Clubdeuce\WPLib\Components\GoogleMaps;
4
5
/**
6
 * Class Geocoder
7
 * @package Clubdeuce\WPLib\Components\GoogleMaps
8
 */
9
class Geocoder {
10
11
    /**
12
     * @var string
13
     */
14
    protected $_api_key;
15
16
    /**
17
     * KSA_Geocoder constructor.
18
     *
19
     * @param array $args
20
     */
21
    function __construct( $args = array() ) {
22
23
        $args = wp_parse_args( $args, array(
24
            'api_key' => '',
25
        ) );
26
27
        $this->_api_key = $args['api_key'];
28
29
    }
30
31
    /**
32
     * @return string
33
     */
34
    function api_key() {
35
36
        return $this->_api_key;
37
38
    }
39
40
    /**
41
     * @param  string $address
42
     * @return Location|\WP_Error
43
     */
44
    function geocode( $address ) {
45
46
        $location = new \WP_Error(100, 'No results found', array( 'address' => $address ) );
47
        $url = $this->_make_url( $address );
48
49
        $response = $this->_make_request( $url );
50
51
        if ( ! is_wp_error( $response ) && count( $response['results'] ) > 0 ) {
52
            $location = $this->_make_location( $response['results'][0] );
53
        }
54
55
        return $location;
56
57
    }
58
59
    /**
60
     * @param  string $address
61
     * @return string
62
     */
63
    private function _make_url( $address ) {
64
65
        return sprintf(
66
            'https://maps.googleapis.com/maps/api/geocode/json?address=%1$s&key=%2$s',
67
            urlencode( filter_var( $address, FILTER_SANITIZE_STRING ) ),
68
            self::api_key()
69
        );
70
71
    }
72
73
    /**
74
     * Convert the response body into an a Location object
75
     *
76
     * @param  array $results
77
     * @return Location
78
     */
79
    private function _make_location( $results ) {
80
81
        $response = new Location( array(
82
            'address'           => $results['formatted_address'],
83
            'formatted_address' => $results['formatted_address'],
84
            'state'             => self::_get_state_from_results( $results ),
85
            'zip_code'          => self::_get_zip_from_results( $results ),
86
            'latitude'          => $results['geometry']['location']['lat'],
87
            'longitude'         => $results['geometry']['location']['lng'],
88
            'place_id'          => $results['place_id'],
89
            'types'             => $results['types'],
90
            'viewport'          => $results['geometry']['viewport'],
91
        ) );
92
93
        return $response;
94
95
    }
96
97
    /**
98
     * @param  array  $results
99
     * @return string
100
     */
101
    private function _get_state_from_results( $results ) {
102
103
        return self::_get_value_from_results( 'administrative_area_level_1', $results );
104
105
    }
106
107
    /**
108
     * @param  array $results
109
     * @return string
110
     */
111
    private function _get_zip_from_results( $results ) {
112
113
        return self::_get_value_from_results( 'postal_code', $results );
114
115
    }
116
117
    /**
118
     * @param  string $value
119
     * @param  array  $results
120
     * @return string
121
     */
122
    private function _get_value_from_results( $value, $results ) {
123
124
        $result_value = '';
125
126
        if ( isset( $results['address_components'] ) ) {
127
            foreach ( $results['address_components'] as $component ) {
128
                if ( $component['types'][0] === $value ) {
129
                    $result_value = $component['short_name'];
130
                    break;
131
                }
132
            }
133
        }
134
135
        return $result_value;
136
137
    }
138
139
    /**
140
     * @param  string $url
141
     * @return array|\WP_Error
142
     */
143
    private function _make_request( $url ) {
144
145
        $return = new \WP_Error( 1, 'Invalid URL', $url );
146
147
        if ( wp_http_validate_url( $url ) ) {
148
            $request = $this->_get_data( $url );
149
150
            $return = new \WP_Error( $request['response']['code'], $request['response']['message'] );
151
152
            if ( 200 == $request['response']['code'] ) {
153
                $return = json_decode( $request['body'], true );
154
            }
155
156
        }
157
158
        return $return;
159
160
    }
161
162
    /**
163
     * @param $url
164
     * @return array|\WP_Error
165
     */
166
    private function _get_data( $url ) {
167
168
        $cache_key = md5( serialize( $url ) );
169
170
        if ( ! $data = wp_cache_get( $cache_key ) ) {
171
            $data = wp_remote_get( $url );
172
            wp_cache_add( $cache_key, $data, 300 );
173
        }
174
175
        return $data;
176
177
    }
178
179
}
180