Passed
Push — master ( 653599...c050da )
by Stephen
47s queued 12s
created

Extract::cityState()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 7
nc 3
nop 1
dl 0
loc 16
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Sfneal\GooglePlaces\Services;
4
5
use Sfneal\GooglePlaces\Actions\Traits\States;
6
7
class Extract
8
{
9
    use States;
10
11
    /**
12
     * Extract a (city, state) string from a google places API return that may contain a zip code.
13
     *
14
     * @param string $description
15
     * @return array
16
     */
17
    public static function cityState(string $description): array
18
    {
19
        // Check that the place description contains a comma string
20
        if (strpos($description, ', ') !== false) {
21
            // Separate city and state strings
22
            [$city, $state] = explode(', ', $description);
23
24
            // Check if the state string contains more than a state code
25
            if (strlen(trim($state)) > 2 && strpos($state, ' ') !== false) {
26
                // Extract the zip code
27
                [$state, $zip] = explode(' ', $state);
28
            }
29
30
            return [$city, $state];
31
        } else {
32
            return ['', self::stateAbbreviation($description)];
33
        }
34
    }
35
36
    /**
37
     * Extract a zip code string from a google places API return that may contain a zip code.
38
     *
39
     * @param string $description
40
     * @return string
41
     */
42
    public static function zip(string $description): ?string
43
    {
44
        // Check that the place description contains a comma string
45
        if (strpos($description, ', ') !== false) {
46
            // Separate city and state strings
47
            [$city, $state] = explode(', ', $description);
48
49
            // Check if the state string contains more than a state code
50
            if (strlen(trim($state)) > 2 && strpos($state, ' ') !== false) {
51
                // Extract the zip code
52
                [$state, $zip] = explode(' ', $state);
53
54
                return $zip;
55
            }
56
        }
57
58
        return null;
59
    }
60
61
    /**
62
     * Extract a city from a google places API return.
63
     *
64
     * @param string $description
65
     * @return string|null
66
     */
67
    public static function city(string $description): ?string
68
    {
69
        return self::cityState($description)[0];
70
    }
71
72
    /**
73
     * Extract a state from a google places API return.
74
     *
75
     * @param string $description
76
     * @return string|null
77
     */
78
    public static function state(string $description): ?string
79
    {
80
        return self::cityState($description)[1];
81
    }
82
}
83