1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Coco\SourceWatcher\Core\Api; |
4
|
|
|
|
5
|
|
|
use Coco\SourceWatcher\Core\SourceWatcherException; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Class ApiReader |
9
|
|
|
* @package Coco\SourceWatcher\Core\Api |
10
|
|
|
*/ |
11
|
|
|
class ApiReader implements Reader |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var string |
15
|
|
|
*/ |
16
|
|
|
protected string $endpoint; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var int |
20
|
|
|
*/ |
21
|
|
|
protected int $timeout = 5; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var int |
25
|
|
|
*/ |
26
|
|
|
protected int $currentAttempt; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @var int |
30
|
|
|
*/ |
31
|
|
|
protected int $attempts = 3; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* ApiReader constructor. |
35
|
|
|
*/ |
36
|
|
|
public function __construct () |
37
|
|
|
{ |
38
|
|
|
$this->currentAttempt = 1; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @return string |
43
|
|
|
*/ |
44
|
|
|
public function getEndpoint () : string |
45
|
|
|
{ |
46
|
|
|
return $this->endpoint; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param string $endpoint |
51
|
|
|
*/ |
52
|
|
|
public function setEndpoint ( string $endpoint ) : void |
53
|
|
|
{ |
54
|
|
|
$this->endpoint = $endpoint; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @return int |
59
|
|
|
*/ |
60
|
|
|
public function getTimeout () : int |
61
|
|
|
{ |
62
|
|
|
return $this->timeout; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param int $timeout |
67
|
|
|
*/ |
68
|
|
|
public function setTimeout ( int $timeout ) : void |
69
|
|
|
{ |
70
|
|
|
$this->timeout = $timeout; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* @return bool|string |
75
|
|
|
* @throws SourceWatcherException |
76
|
|
|
*/ |
77
|
|
|
public function read () |
78
|
|
|
{ |
79
|
|
|
if ( $this->endpoint == null || $this->endpoint == "" ) { |
80
|
|
|
throw new SourceWatcherException( "No endpoint found." ); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
$curl = curl_init(); |
84
|
|
|
|
85
|
|
|
curl_setopt( $curl, CURLOPT_URL, $this->endpoint ); |
|
|
|
|
86
|
|
|
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 ); |
87
|
|
|
curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, $this->timeout ); |
88
|
|
|
|
89
|
|
|
/** |
90
|
|
|
* https://www.php.net/manual/en/function.curl-exec.php |
91
|
|
|
* |
92
|
|
|
* Returns TRUE on success or FALSE on failure. |
93
|
|
|
* However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure. |
94
|
|
|
*/ |
95
|
|
|
|
96
|
|
|
$response = curl_exec( $curl ); |
|
|
|
|
97
|
|
|
|
98
|
|
|
curl_close( $curl ); |
|
|
|
|
99
|
|
|
|
100
|
|
|
if ( $response == false ) { |
|
|
|
|
101
|
|
|
if ( $this->currentAttempt < $this->attempts ) { |
102
|
|
|
$this->currentAttempt++; |
103
|
|
|
$this->read(); |
104
|
|
|
} |
105
|
|
|
} |
106
|
|
|
|
107
|
|
|
return $response; |
108
|
|
|
} |
109
|
|
|
} |
110
|
|
|
|