Repo for the search and displace core module including the interface to select files and search and displace operations to run on them. https://searchanddisplace.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.4 KiB

3 years ago
3 years ago
3 years ago
3 years ago
  1. <?php
  2. namespace App\SearchDisplace\Ingest;
  3. use GuzzleHttp\Client;
  4. use GuzzleHttp\Exception\ClientException;
  5. class SendDocument
  6. {
  7. protected $url;
  8. public function __construct()
  9. {
  10. $this->url = env('SD_INGEST_URL') . '/ingest';
  11. }
  12. public function execute($id, $document, $fileResultType = 'md')
  13. {
  14. try {
  15. $response = $this->sendRequest($id, $document, $fileResultType);
  16. if ($response['status'] === 'fail') {
  17. $message = array_key_exists('message', $response)
  18. ? $response['message']
  19. : 'Something went wrong.';
  20. throw new \Exception($message);
  21. }
  22. // The file in Ingest si in Processing state.
  23. } catch (\Exception $exception) {
  24. throw new \Exception($exception->getMessage());
  25. }
  26. }
  27. /**
  28. * Send request to Ingest.
  29. *
  30. * @param $id
  31. * @param $document
  32. * @return mixed
  33. * @throws \GuzzleHttp\Exception\GuzzleException
  34. */
  35. public function sendRequest($id, $document, $fileResultType)
  36. {
  37. $client = new Client();
  38. try {
  39. $response = $client->request('post', $this->url, [
  40. 'headers' => [
  41. 'Accept' => 'application/json',
  42. ],
  43. 'multipart' => [
  44. [
  45. 'name' => 'id',
  46. 'contents' => $id,
  47. ],
  48. [
  49. 'name' => 'file_result_type',
  50. 'contents' => $fileResultType,
  51. ],
  52. [
  53. 'name' => 'mime_type',
  54. 'contents' => $document['type'],
  55. ],
  56. [
  57. 'name' => 'document',
  58. 'contents' => fopen($document['path'], 'r'),
  59. 'filename' => $document['name'],
  60. 'Content-type' => $document['type'],
  61. ]
  62. ],
  63. ]);
  64. return json_decode($response->getBody()->getContents(), true);
  65. } catch (ClientException $clientException) {
  66. $error = json_decode($clientException->getResponse()->getBody()->getContents(), true);
  67. throw new \Exception($error['message']);
  68. } catch (\Exception $exception) {
  69. throw $exception;
  70. }
  71. }
  72. }