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

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

/**
 * Parses the JSON data.
 */
class Json 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 = @json_decode($raw, true);
		if ($data === null) {
			throw new ContentCannotBeParsedException('JSON', $raw);
		}

		return $data;
	}

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

		// Handle empty data;
		if (empty($data)) {
			return is_array($data) ? '[]' : '{}';
		}

		return json_encode($data);
	}

}
