Switch Message::respond() to use Http::class instead of curl directly

This commit is contained in:
Deon George 2022-09-05 22:26:08 +10:00
parent 2c791ccead
commit a1be3ccd09

View File

@ -7,6 +7,7 @@ use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Slack\Blockkit\Blocks;
@ -188,30 +189,20 @@ final class Message extends BlockKit
* @note This URL can only be used 5 times in 30 minutes
* @param string $url
* @param Carbon|null $delete
* @return string
* @return object
* @throws SlackException
*/
public function respond(string $url,Carbon $delete=NULL)
public function respond(string $url,Carbon $delete=NULL): object
{
// @todo change this to use Http::class or the API?
if (! $delete && $this->selfdestruct)
$delete = $this->selfdestruct;
$request = curl_init();
curl_setopt($request,CURLOPT_URL,$url);
curl_setopt($request,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($request,CURLINFO_HEADER_OUT,TRUE);
curl_setopt($request,CURLOPT_HTTPHEADER,['Content-Type: application/json; charset=utf-8']);
curl_setopt($request,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($request,CURLOPT_POSTFIELDS,json_encode($this));
$http = Http::acceptJson();
$http->withBody(json_encode($this),'application/json');
try {
$result = curl_exec($request);
if (! $result)
throw new \Exception('CURL exec returned an empty response: '.serialize(curl_getinfo($request)));
$result = json_decode($result);
$request = $http->post($url)->throw();
$response = $request->object();
} catch (\Exception $e) {
Log::error(sprintf('%s:Got an error while posting to [%s] (%s)',static::LOGKEY,$url,$e->getMessage()),['m'=>__METHOD__]);
@ -219,12 +210,9 @@ final class Message extends BlockKit
throw new \Exception($e->getMessage());
}
if (! $result->ok) {
switch ($result) {
default:
Log::critical(sprintf('%s:Generic Error',static::LOGKEY),['m'=>__METHOD__,'r'=>$result]);
throw new SlackException($result,curl_getinfo($request,CURLINFO_HTTP_CODE));
}
if (! $response->ok) {
Log::critical(sprintf('%s:Generic Error',static::LOGKEY),['m'=>__METHOD__,'r'=>$response]);
throw new SlackException(serialize($response),$request->status());
}
if ($delete) {
@ -234,8 +222,7 @@ final class Message extends BlockKit
dispatch((new DeleteResponse($url))->onQueue('slack')->delay($delete));
}
curl_close($request);
return $result;
return $response;
}
/**