<?php namespace Newsletter\Builder;

use Newsletter\Builder\RequiredVar\RequiredVar;

class Parser {

	/**
	 * Get the required variables specification from the template tile.
	 *
	 * @param string $file The path to the file to extract the specification from.
	 *
	 * @return mixed The found specification.
	 */
	public static function getSpecification($file) {
		/** @var mixed $requiredVars */

		ob_start();
		require $file;
		ob_get_clean();

		return $requiredVars;
	}

	/**
	 * Get the list of all variables.
	 *
	 * @param array $requiredVars The variables specification.
	 *
	 * @return RequiredVar[] The list of all required variables.
	 */
	public static function getVariables($requiredVars) {
		$vars = [];
		foreach ($requiredVars as $name => $params) {

			// Set the defaults
			$defaults = [
				'title'   => $name,
				'type'    => 'string',
				'options' => []
			];

			// Initialize
			$params = array_merge($defaults, $params);
			$vars[$name] = RequiredVar::create($name, $params['title'], $params['type'], $params['options']);
		};

		return $vars;
	}

	/**
	 * Parse the required variables.
	 *
	 * @param array $requiredVars The variables specification.
	 * @param array $data         The data for the variables;
	 *
	 * @return array The resulting variables.
	 */
	public static function parse($requiredVars, $data = []) {
		$export = [];

		$vars = static::getVariables($requiredVars);
		foreach ($vars as $var) {
			$name = $var->getName();

			$export[$name] = $data && key_exists($name, $data)
				? $data[$name]
				: null;
		}

		return $export;
	}

}