<?php
namespace App\Utils\BaseParser\Utils\Extractor;

/**
 * A speed-optimized version of the extractor. It will use more memory instead, because it uses a caching mechanism
 * @author Lucian Sirbu
 */
class SingleOptimized extends Single
{
	protected $cache = [];


	protected function safeFind($regexp, $content)
	{
		$cacheKey = $regexp;
		if (isset($this->cache[$cacheKey])) {
			list($regexp, $renamedPatternNames) = $this->cache[$cacheKey];
		}
		else {
			list($regexp, $renamedPatternNames) = $this->safeFind_renamePatterns($regexp, []);

			$this->cache[$cacheKey] = [$regexp, $renamedPatternNames];
		}

		// main pattern match
		$matches = [];
		$matchCount = preg_match($regexp, (string)$content, $matches, PREG_OFFSET_CAPTURE);
		if ($matchCount===false) {
			throw new \Exception\Regexp\Base(sprintf("[%s] Invalid regexp specified in \$this->extractRegexp : '%s'", __METHOD__, htmlentities($regexp)));
		}

		$matches = $this->renameRegexpPatternsInMatches($matches, $renamedPatternNames);

		$ret = new SingleFindResponse($matchCount, $matches);
		return $ret;
	}
}
