documentContent = $documentContent; $this->info = $info; $this->searchOnly = $searchOnly; } public function execute() { $searchResult = $this->search(); if ($this->searchOnly) { return $searchResult; } 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; } $searchers = []; foreach ($searchResult as $searcher => $searcherResults) { $replacementIndexes[$searcher] = []; foreach ($searcherResults as $searcherResult) { $searchers[$searcherResult['start']] = array_merge($searcherResult, [ 'searcher' => $searcher ]); } } ksort($searchers); $updatedDocumentContent = ''; $currentIndex = 0; foreach ($searchers as $s => $searcherItem) { $partialContent = substr($this->documentContent, $currentIndex, $searcherItem['start'] - $currentIndex); $updatedDocumentContent = $updatedDocumentContent . $partialContent; $start = mb_strlen($updatedDocumentContent); $replacementValue = $replacements[$searcherItem['searcher']]['type'] === 'replace' ? $replacements[$searcherItem['searcher']]['value'] : $this->getDisplaceValue($replacements[$searcherItem['searcher']]['value'], $searcherItem['content']); $updatedDocumentContent = $updatedDocumentContent . $replacementValue; $end = mb_strlen($updatedDocumentContent) - 1; if ($start <= $end) { $replacementIndexes[$searcherItem['searcher']][] = [ 'start' => $start, 'end' => $end, ]; } $currentIndex = $searcherItem['end'] + 1; } if ($currentIndex < strlen($this->documentContent) - 1) { $updatedDocumentContent = $updatedDocumentContent . substr($this->documentContent, $currentIndex); } return [ 'content' => $updatedDocumentContent, 'indexes' => $replacementIndexes, ]; } protected function getDisplaceValue($displaceValue, $content) { // return "<$displaceValue>$content"; return "{{$displaceValue}}{$content}{/{$displaceValue}}"; } }