-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRetrofit.php
75 lines (68 loc) · 2.04 KB
/
Retrofit.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
declare(strict_types=1);
namespace Retrofit\Core;
use InvalidArgumentException;
use Psr\Http\Message\UriInterface;
use ReflectionClass;
use Retrofit\Core\Internal\ConverterProvider;
use Retrofit\Core\Internal\Proxy\ProxyFactory;
/**
* Retrofit adapts a PHP interface to HTTP calls by using attributes on the declared methods to define how request are
* made. Create instances using {@link RetrofitBuilder the builder} and pass your interface to
* {@link Retrofit::create() create} method to generate an implementation.
*
* For example:
* <pre>
* $retrofit = Retrofit::Builder()
* ->client(...) // Implementation of the HttpClient interface
* ->baseUrl('https://api.example.com')
* ->addConverterFactory(...)
* ->build();
*
* $api = $retrofit->create(MyApi::class);
* $users = $api->getUsers()->execute();
* </pre>
*
* @api
*/
readonly class Retrofit
{
public function __construct(
public HttpClient $httpClient,
public UriInterface $baseUrl,
public ConverterProvider $converterProvider,
private ProxyFactory $proxyFactory,
)
{
}
/**
* Creates an implementation of the API endpoints defined by the <code>service</code> interface.
*
* @template T of object
* @param class-string<T> $service
* @return T
*/
public function create(string $service): object
{
$reflectionClass = new ReflectionClass($service);
$this->validateServiceInterface($reflectionClass);
return $this->proxyFactory->create($this, $reflectionClass);
}
/**
* Build a new {@link Retrofit}.
*/
public static function Builder(): RetrofitBuilder
{
return new RetrofitBuilder();
}
/**
* @template T of object
* @param ReflectionClass<T> $service
*/
private function validateServiceInterface(ReflectionClass $service): void
{
if (!$service->isInterface()) {
throw new InvalidArgumentException("Service '{$service->getShortName()}' API declarations must be interface.");
}
}
}