Passed
Pull Request — master (#4)
by Stephen
02:30
created

Extract::zip()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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