<?php namespace Intellex\Curly\Content\TypeHandlers;

use Intellex\Curly\Content\Exception\ContentCannotBeParsedException;
use Intellex\Curly\Content\TypeHandlerInterface;

/**
 * Parses the XML data.
 */
class XML implements TypeHandlerInterface {

	/**
	 * Extract the values;
	 *
	 * @param string $raw The raw content.
	 *
	 * @return array The extracted data, as array.
	 * @throws ContentCannotBeParsedException
	 */
	public function parse($raw) {
		$data = @simplexml_load_string($raw);
		if (!$data || !is_object($data)) {
			throw new ContentCannotBeParsedException('XML', $raw);
		}

		//

		return $data;
	}

	/**
	 * Format the data based on the type.
	 *
	 * @param mixed $data The data to format.
	 *
	 * @return string The JSON representation.
	 */
	public function format($data) {
		// TODO
	}

	/**
	 * Convert SimpleXMLElement to an array, ignoring the attributes.
	 *
	 * @param \SimpleXMLElement $xml The input XML.
	 *
	 * @return array The resulting array.
	 */
	public static function toArray($xml) {
		$array = [];

		foreach ((array) $xml as $tag => $node) {
			$array[$tag] = (is_object($node)) ? static::toArray($node) : $node;
		}

		return $array;
	}

}
