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.

78 lines
2.1 KiB

  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)
  13. {
  14. try {
  15. $response = $this->sendRequest($id, $document);
  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)
  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' => 'document',
  50. 'contents' => fopen($document['path'], 'r'),
  51. 'filename' => $document['name'],
  52. 'Content-type' => $document['type'],
  53. ]
  54. ],
  55. ]);
  56. return json_decode($response->getBody()->getContents(), true);
  57. } catch (ClientException $clientException) {
  58. $error = json_decode($clientException->getResponse()->getBody()->getContents(), true);
  59. throw new \Exception($error['message']);
  60. } catch (\Exception $exception) {
  61. throw $exception;
  62. }
  63. }
  64. }