<?php
namespace App\Utils\BaseParser\TextParser\Types;

/**
 * Conditional parsing. Allow specifying isValid & extract functions as inline texts
 * @author Lucian Sirbu
 *
 */
class ContainerConditionalParse extends \App\Utils\BaseParser\TextParser\BlockRegexpAbstract
{
	protected $matcher = null;

	public function  __construct($options = [], $parent = null)
	{
		parent::__construct($options, $parent);

		if(!$this->options['isValid']) {
			throw new \Exception("isValid is not defined");
		}
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Utils\BaseParser\TextParser\BlockRegexpAbstract::isValid()
	 */
	public function isValid()
	{
		\Engine\Debug\ParserCallTrace\ParserCallTrace::getInstance()->logCallStart($this, __METHOD__, func_get_args());
		\Engine\Debug\ParserCallTrace\ParserCallTrace::getInstance()->logInput([
			'key' => $this->options['key'],
			'rawData' => $this->rawData,
		]);
		\Engine\Debug\ParserCallTrace\ParserCallTrace::getInstance()->logInput([
			'extractRegexp' => $this->extractRegexp,
		], 'regexp');

		if (is_string($this->options['isValid'])) {
			$condition = $this->options['isValid'];
			$ret = eval($condition);
		}
		else {
			// assume isValid is a callback
			$condition = $this->options['isValid'];
			$ret = $condition();
		}

		\Engine\Debug\ParserCallTrace\ParserCallTrace::getInstance()->logOutput([
			'return' => $ret,
		]);

		\Engine\Debug\ParserCallTrace\ParserCallTrace::getInstance()->logCallEnd();
		return $ret;
	}

	/**
	 * (non-PHPdoc)
	 * @see \App\Utils\BaseParser\TextParser\BlockRegexpAbstract::_extract()
	 */
	protected function _extract(\App\Utils\BaseParser\TextParser\ExtractedBlock $ret, $originalRawData)
	{
		if (is_string($this->options['isValid'])) {
			$extract = $this->options['extract'];
			$ret = eval($extract);
		}
		else {
			// assume extract is a callback
			$condition = $this->options['extract'];
			$ret = $condition($ret, $originalRawData);
		}
		return $ret;
	}
}
