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.

64 lines
1.6 KiB

  1. <?php
  2. namespace App\SearchDisplace;
  3. use App\SearchDisplace\Searchers\Searcher;
  4. class SearchAndDisplace
  5. {
  6. protected $documentContent;
  7. protected $info;
  8. public function __construct($documentContent, $info)
  9. {
  10. $this->documentContent = $documentContent;
  11. $this->info = $info;
  12. }
  13. public function execute()
  14. {
  15. $searchResult = $this->search();
  16. return $this->displace($searchResult);
  17. }
  18. /**
  19. *
  20. * @return mixed
  21. * @throws \Exception
  22. */
  23. protected function search()
  24. {
  25. $searcher = new Searcher($this->info['searchers'], $this->documentContent);
  26. return $searcher->execute();
  27. }
  28. protected function displace($searchResult)
  29. {
  30. $replacements = [];
  31. foreach ($this->info['searchers'] as $searcher) {
  32. $replacements[$searcher['key']] = $searcher['replace_with'];
  33. }
  34. $updatedDocumentContent = '';
  35. $currentIndex = 0;
  36. foreach ($searchResult as $item) {
  37. $partialContent = substr($this->documentContent, $currentIndex, $item['start'] - $currentIndex);
  38. $updatedDocumentContent = $updatedDocumentContent . $partialContent;
  39. $updatedDocumentContent = $updatedDocumentContent . $replacements[$item['dim']];
  40. $currentIndex = $item['end'];
  41. }
  42. if ($currentIndex < strlen($this->documentContent) - 1) {
  43. $updatedDocumentContent = $updatedDocumentContent . substr($this->documentContent, $currentIndex);
  44. }
  45. return $updatedDocumentContent;
  46. }
  47. }