|
1 | | -<?php |
| 1 | +<?php declare(strict_types=1); |
2 | 2 |
|
3 | 3 | namespace App\Models; |
4 | 4 |
|
| 5 | +use App\Enum\HttpMethod; |
| 6 | +use App\Exceptions\RemotesiteCommunicationException; |
| 7 | +use GuzzleHttp\Client; |
| 8 | +use GuzzleHttp\Exception\RequestException; |
| 9 | +use GuzzleHttp\Psr7\Request; |
| 10 | +use GuzzleHttp\Psr7\Response; |
5 | 11 | use Illuminate\Database\Eloquent\Factories\HasFactory; |
6 | 12 | use Illuminate\Foundation\Auth\User as Authenticatable; |
7 | 13 | use Illuminate\Notifications\Notifiable; |
| 14 | +use Illuminate\Support\Facades\App; |
| 15 | +use Psr\Http\Message\RequestInterface; |
| 16 | +use Psr\Http\Message\ResponseInterface; |
8 | 17 |
|
9 | 18 | class Site extends Authenticatable |
10 | 19 | { |
@@ -34,4 +43,77 @@ protected function casts(): array |
34 | 43 | 'update_major' => 'bool' |
35 | 44 | ]; |
36 | 45 | } |
| 46 | + |
| 47 | + public function getUrlAttribute(string $value): string |
| 48 | + { |
| 49 | + return rtrim($value, "/") . "/"; |
| 50 | + } |
| 51 | + |
| 52 | + |
| 53 | + protected function performRequest( |
| 54 | + RequestInterface $request, |
| 55 | + array $options = [] |
| 56 | + ): array { |
| 57 | + /** @var Client $httpClient */ |
| 58 | + $httpClient = App::make(Client::class); |
| 59 | + |
| 60 | + /** @var Response $response */ |
| 61 | + $response = $httpClient->send( |
| 62 | + $request, |
| 63 | + $options |
| 64 | + ); |
| 65 | + |
| 66 | + // Validate response |
| 67 | + if (!json_validate((string) $response->getBody())) { |
| 68 | + throw new RequestException( |
| 69 | + "Invalid JSON body", |
| 70 | + $request, |
| 71 | + $response |
| 72 | + ); |
| 73 | + } |
| 74 | + |
| 75 | + // Return decoded body |
| 76 | + return json_decode( |
| 77 | + (string) $response->getBody(), |
| 78 | + true, |
| 79 | + 512, |
| 80 | + JSON_THROW_ON_ERROR |
| 81 | + ); |
| 82 | + } |
| 83 | + |
| 84 | + public function performExtractionRequest(array $data, string $password): array |
| 85 | + { |
| 86 | + $request = new Request( |
| 87 | + 'POST', |
| 88 | + $this->url . 'extract.php' |
| 89 | + ); |
| 90 | + |
| 91 | + $data['password'] = $password; |
| 92 | + |
| 93 | + return $this->performRequest( |
| 94 | + $request, |
| 95 | + [ |
| 96 | + 'form_params' => $data, |
| 97 | + 'timeout' => 300.0 |
| 98 | + ] |
| 99 | + ); |
| 100 | + } |
| 101 | + |
| 102 | + public function performWebserviceRequest(HttpMethod $method, string $endpoint, array $data = []): array |
| 103 | + { |
| 104 | + $request = new Request( |
| 105 | + $method->name, |
| 106 | + $this->url . $endpoint, |
| 107 | + [ |
| 108 | + 'Authorization' => 'JUpdate-Token ' . $this->key |
| 109 | + ] |
| 110 | + ); |
| 111 | + |
| 112 | + return $this->performRequest( |
| 113 | + $request, |
| 114 | + [ |
| 115 | + "json" => $data |
| 116 | + ] |
| 117 | + ); |
| 118 | + } |
37 | 119 | } |
0 commit comments