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.

104 lines
2.9 KiB

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