1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace WyriHaximus\Travis\Transport; |
5
|
|
|
|
6
|
|
|
use GeneratedHydrator\Configuration; |
7
|
|
|
use GuzzleHttp\Psr7\Request; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
use React\EventLoop\LoopInterface; |
10
|
|
|
use React\Promise\Deferred; |
11
|
|
|
|
12
|
|
|
class Client |
13
|
|
|
{ |
14
|
|
|
const VERSION = '0.0.1-alpha1'; |
15
|
|
|
const USER_AGENT = 'wyrihaximus/travis-client/' . self::VERSION; |
16
|
|
|
const API_VERSION = 'application/vnd.travis-ci.2+json'; |
17
|
|
|
const API_HOST_OPEN_SOURCE = 'api.travis-ci.org'; |
18
|
|
|
const API_HOST_PRO = 'api.travis-ci.com'; |
19
|
|
|
const API_HOST = self::API_HOST_OPEN_SOURCE; |
20
|
|
|
const API_SCHEMA = 'https'; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var callable |
24
|
|
|
*/ |
25
|
|
|
protected $handler; |
26
|
|
|
protected $loop; |
27
|
|
|
|
28
|
|
|
protected $hydrators = []; |
29
|
|
|
|
30
|
|
|
public function __construct(LoopInterface $loop, callable $handler = null) |
31
|
|
|
{ |
32
|
|
|
$this->loop = $loop; |
33
|
|
|
if ($handler === null) { |
34
|
|
|
$handler = \Aws\default_http_handler(); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
$this->handler = $handler; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function request($path) |
41
|
|
|
{ |
42
|
|
|
$deferred = new Deferred(); |
43
|
|
|
$handler = $this->handler; |
44
|
|
|
$handler($this->createRequest('GET', $path))->then(function (ResponseInterface $response) use ($deferred) { |
45
|
|
|
$deferred->resolve($response); |
46
|
|
|
}, function ($error) use ($deferred) { |
47
|
|
|
$deferred->reject($error); |
48
|
|
|
}); |
49
|
|
|
return $deferred->promise(); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function hydrate($class, $response) |
53
|
|
|
{ |
54
|
|
|
$json = json_decode($response->getBody()->getContents(), true); |
55
|
|
|
return $this->getHydrator($class)->hydrate($json['repo'], new $class); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
protected function getHydrator($class) |
59
|
|
|
{ |
60
|
|
|
if (isset($this->hydrators[$class])) { |
61
|
|
|
return $this->hydrators[$class]; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$hydrator = (new Configuration($class))->createFactory()->getHydratorClass(); |
65
|
|
|
$this->hydrators[$class] = new $hydrator; |
66
|
|
|
return $this->hydrators[$class]; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
protected function createRequest(string $method, string $path) |
70
|
|
|
{ |
71
|
|
|
$url = self::API_SCHEMA . '://' . self::API_HOST . '/' . $path; |
72
|
|
|
return new Request($method, $url, [ |
73
|
|
|
'User-Agent' => self::USER_AGENT, |
74
|
|
|
'Accept' => self::API_VERSION, |
75
|
|
|
]); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* @return LoopInterface |
80
|
|
|
*/ |
81
|
|
|
public function getLoop() |
82
|
|
|
{ |
83
|
|
|
return $this->loop; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|