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.
79 lines
2.1 KiB
79 lines
2.1 KiB
<?php
|
|
|
|
namespace App\SearchDisplace;
|
|
|
|
use App\SearchDisplace\Searchers\Searcher;
|
|
|
|
class SearchAndDisplace
|
|
{
|
|
protected $documentContent;
|
|
protected $info;
|
|
|
|
public function __construct($documentContent, $info)
|
|
{
|
|
$this->documentContent = $documentContent;
|
|
$this->info = $info;
|
|
}
|
|
|
|
public function execute()
|
|
{
|
|
$searchResult = $this->search();
|
|
|
|
return $this->displace($searchResult);
|
|
}
|
|
|
|
/**
|
|
*
|
|
* @return mixed
|
|
* @throws \Exception
|
|
*/
|
|
protected function search()
|
|
{
|
|
$searcher = new Searcher($this->info['searchers'], $this->documentContent);
|
|
|
|
return $searcher->execute();
|
|
}
|
|
|
|
protected function displace($searchResult)
|
|
{
|
|
$replacementIndexes = [];
|
|
$replacements = [];
|
|
|
|
foreach ($this->info['searchers'] as $searcher) {
|
|
$replacements[$searcher['key']] = $searcher['replace_with'];
|
|
}
|
|
|
|
$updatedDocumentContent = '';
|
|
$currentIndex = 0;
|
|
|
|
foreach ($searchResult as $searcher => $searcherResults) {
|
|
$replacementIndexes[$searcher] = [];
|
|
|
|
foreach ($searcherResults as $searcherResult) {
|
|
$partialContent = substr($this->documentContent, $currentIndex, $searcherResult['start'] - $currentIndex);
|
|
|
|
$updatedDocumentContent = $updatedDocumentContent . $partialContent;
|
|
|
|
$start = strlen($updatedDocumentContent);
|
|
|
|
$updatedDocumentContent = $updatedDocumentContent . $replacements[$searcher];
|
|
|
|
$replacementIndexes[$searcher][] = [
|
|
'start' => $start,
|
|
'end' => strlen($updatedDocumentContent) - 1,
|
|
];
|
|
|
|
$currentIndex = $searcherResult['end'] + 1;
|
|
}
|
|
}
|
|
|
|
if ($currentIndex < strlen($this->documentContent) - 1) {
|
|
$updatedDocumentContent = $updatedDocumentContent . substr($this->documentContent, $currentIndex);
|
|
}
|
|
|
|
return [
|
|
'content' => $updatedDocumentContent,
|
|
'indexes' => $replacementIndexes,
|
|
];
|
|
}
|
|
}
|