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.

66 lines
2.1 KiB

  1. <?php
  2. namespace App\SearchDisplace;
  3. use App\Events\SDAppliedOnMarkdownDocument;
  4. use Illuminate\Support\Facades\Storage;
  5. class SearchAndDisplaceFromFiles
  6. {
  7. protected $id;
  8. protected $storage;
  9. protected $directoryPath;
  10. protected $infoFilePath;
  11. public function __construct($id)
  12. {
  13. $this->id = $id;
  14. $this->storage = Storage::disk('local');
  15. $this->directoryPath = "contracts/$this->id";
  16. $this->infoFilePath = "searchers/$this->id.json";
  17. }
  18. public function execute()
  19. {
  20. // The files don't exist, so we don't have to apply S&D.
  21. if ( ! $this->storage->exists($this->directoryPath) || ! $this->storage->exists($this->infoFilePath)) {
  22. return;
  23. }
  24. try {
  25. $documentContent = $this->storage->get("$this->directoryPath/document.md");
  26. $searchersContent = json_decode($this->storage->get($this->infoFilePath), true);
  27. $documentPath = $searchersContent['document_path'];
  28. $searchers = $searchersContent['searchers'];
  29. $this->storage->put($this->infoFilePath, json_encode($searchers[0]['content']));
  30. $searchAndDisplace = new SearchAndDisplace($documentContent, [
  31. 'searchers' => [
  32. [
  33. 'key' => $this->id,
  34. 'type' => $searchers[0]['type'],
  35. 'value' => $searchers[0]['value'],
  36. ]
  37. ],
  38. ]);
  39. $result = $searchAndDisplace->execute();
  40. file_put_contents($documentPath, $result['content']);
  41. SDAppliedOnMarkdownDocument::dispatch($this->id);
  42. } catch (\Exception $exception) {
  43. \Illuminate\Support\Facades\Log::info('EXCEPTION: ' . $exception->getMessage());
  44. \Illuminate\Support\Facades\Log::info('EXCEPTION: ' . $exception->getTraceAsString());
  45. return;
  46. } finally {
  47. $this->storage->deleteDirectory($this->directoryPath);
  48. $this->storage->delete($this->infoFilePath);
  49. }
  50. }
  51. }