Completed
Push — master ( 7633c5...295faf )
by Andreas
02:54 queued 19s
created

TimezoneService::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
/**
3
 * Copyright (c) Andreas Heigl<[email protected]>
4
 * Permission is hereby granted, free of charge, to any person obtaining a copy
5
 * of this software and associated documentation files (the "Software"), to deal
6
 * in the Software without restriction, including without limitation the rights
7
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
 * copies of the Software, and to permit persons to whom the Software is
9
 * furnished to do so, subject to the following conditions:
10
 * The above copyright notice and this permission notice shall be included in
11
 * all copies or substantial portions of the Software.
12
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
18
 * THE SOFTWARE.
19
 *
20
 * @author    Andreas Heigl<[email protected]>
21
 * @copyright Andreas Heigl
22
 * @license   http://www.opensource.org/licenses/mit-license.php MIT-License
23
 * @since     25.07.2016
24
 * @link      http://github.com/heiglandreas/callingallpapers
25
 */
26
27
namespace Callingallpapers\Service;
28
29
use GuzzleHttp\ClientInterface;
30
31
class TimezoneService
32
{
33
    public static $lastAccess;
34
35
    protected $uri = 'http://api.timezonedb.com/v2/get-time-zone?key=%1$s&format=json&by=position&lat=%2$s&lng=%3$s';
36
37
    protected $key;
38
39
    protected $client;
40
41
    public function __construct(ClientInterface $client, $key)
42
    {
43
        $this->client = $client;
44
        $this->key = $key;
45
    }
46
47
    public function getTimezoneForLocation($lat, $lng)
48
    {
49
        if (self::$lastAccess === time()) {
50
            sleep(1);
51
        }
52
        self::$lastAccess = time();
53
        try {
54
            $result = $this->client->get(sprintf(
55
                $this->uri,
56
                $this->key,
57
                $lat,
58
                $lng
59
            ));
60
        } catch (\Exception $e) {
61
            return 'UTC';
62
        }
63
64
        $values = json_decode($result->getBody()->getContents(), true);
65
66
        if (! isset($values['status']) || $values['status'] !== 'OK') {
67
            return 'UTC';
68
        }
69
70
        return $values['zoneName'];
71
    }
72
}