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.

108 lines
2.7 KiB

  1. <?php
  2. namespace App\Console\Commands;
  3. use App\SearchDisplace\Ingest\SendDocument;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Facades\Storage;
  6. class RunSearchDisplace extends Command
  7. {
  8. /**
  9. * The name and signature of the console command.
  10. *
  11. * @var string
  12. */
  13. protected $signature = 'sd:run
  14. {path : The document path}
  15. {filters* : The filters which will be applied to the search}';
  16. /**
  17. * The console command description.
  18. *
  19. * @var string
  20. */
  21. protected $description = 'Run search and displace on document with filters.';
  22. /**
  23. * Create a new command instance.
  24. *
  25. * @return void
  26. */
  27. public function __construct()
  28. {
  29. parent::__construct();
  30. }
  31. /**
  32. * Execute the console command.
  33. *
  34. */
  35. public function handle()
  36. {
  37. $documentPath = $this->argument('path');
  38. $searchers = $this->argument('filters');
  39. $id = md5(uniqid(rand(), true));
  40. $this->storeSearchers($id, $searchers, $documentPath);
  41. try {
  42. $sendToIngest = new SendDocument();
  43. $sendToIngest->execute($documentPath, $id);
  44. $this->info('Processing document..');
  45. $this->info('After the processing will be done the result will show up at the same path as the input.');
  46. } catch (\Exception $exception) {
  47. $this->error('Something went wrong. (' . $exception->getMessage() . ')');
  48. }
  49. }
  50. protected function storeSearchers($id, $searchers, $documentPath)
  51. {
  52. $data = [
  53. 'searchers' => $this->getSearchers($searchers),
  54. 'document_path' => $documentPath,
  55. ];
  56. $storage = Storage::disk('local');
  57. $storage->put("searchers/$id.json", json_encode($data));
  58. }
  59. protected function getSearchers($searchers)
  60. {
  61. if (count($searchers) === 1 && str_contains($searchers[0], '.json')) {
  62. return $this->getSearchersFromFile($searchers[0]);
  63. }
  64. return $this->getSearchersFromList($searchers);
  65. }
  66. protected function getSearchersFromList($searchers)
  67. {
  68. $list = [];
  69. foreach ($searchers as $searcher) {
  70. $result = explode(':', $searcher);
  71. $list[] = [
  72. 'key' => $result[0],
  73. 'replace_with' => $result[1],
  74. ];
  75. }
  76. return $list;
  77. }
  78. protected function getSearchersFromFile($path)
  79. {
  80. $contents = file_get_contents($path);
  81. if ( ! $contents) {
  82. throw new \Exception('Something went wrong when tried reading from file.');
  83. }
  84. return json_decode($contents);
  85. }
  86. }