-
Notifications
You must be signed in to change notification settings - Fork 184
/
Copy pathHttpDriver.php
59 lines (51 loc) · 1.39 KB
/
HttpDriver.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
namespace Stevebauman\Location\Drivers;
use Closure;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Fluent;
use Stevebauman\Location\Request;
abstract class HttpDriver extends Driver
{
/**
* The HTTP resolver callback.
*/
protected static ?Closure $httpResolver = null;
/**
* Get the URL for the HTTP request.
*/
abstract public function url(string $ip): string;
/**
* Set the callback used to resolve a pending HTTP request.
*/
public static function resolveHttpBy(Closure $callback): void
{
static::$httpResolver = $callback;
}
/**
* Attempt to fetch and process the location data from the driver.
*/
public function process(Request $request): Fluent|false
{
return rescue(fn () => new Fluent(
$this->http()
->throw()
->acceptJson()
->get($this->url($request->getIp()))
->json()
), false, false);
}
/**
* Create a new HTTP request.
*/
protected function http(): PendingRequest
{
$callback = static::$httpResolver ?: fn ($http) => $http;
return value($callback, Http::withOptions(
config('location.http', [
'timeout' => 3,
'connect_timeout' => 3,
])
));
}
}