|
|
<?php
namespace App\SearchDisplace\Ingest;
use GuzzleHttp\Client; use GuzzleHttp\Exception\ClientException; use GuzzleHttp\Exception\GuzzleException;
class SendDocument { protected $url;
public function __construct() { $this->url = env('SD_INGEST_URL') . '/ingest'; }
/** * * * @param $id * @param $document * @param string $fileResultType * @throws \Exception */ public function execute($id, $document, string $fileResultType = 'md') { try { if ( ! in_array($fileResultType, ['md', 'original'])) { throw new \Exception('Invalid file result type provided.'); }
$response = $this->sendRequest($id, $document, $fileResultType);
if ($response['status'] === 'fail') { $message = array_key_exists('message', $response) ? $response['message'] : 'Something went wrong.';
throw new \Exception($message); }
// The file in Ingest si in Processing state.
} catch (\Exception $exception) { throw new \Exception($exception->getMessage()); } catch (GuzzleException $exception) { throw new \Exception($exception->getMessage()); } }
/** * Send request to Ingest. * * @param $id * @param $document * @param $fileResultType * @return mixed * @throws GuzzleException */ public function sendRequest($id, $document, $fileResultType) { $client = new Client();
try { $response = $client->request('post', $this->url, [ 'headers' => [ 'Accept' => 'application/json', ],
'multipart' => [ [ 'name' => 'id', 'contents' => $id, ],
[ 'name' => 'file_result_type', 'contents' => $fileResultType, ],
[ 'name' => 'mime_type', 'contents' => $document['type'], ],
[ 'name' => 'document', 'contents' => fopen($document['path'], 'r'), 'filename' => $document['name'], 'Content-type' => $document['type'], ] ], ]);
return json_decode($response->getBody()->getContents(), true); } catch (ClientException $clientException) { $error = json_decode($clientException->getResponse()->getBody()->getContents(), true);
throw new \Exception($error['message']); } catch (\Exception $exception) { throw $exception; } } }
|