<?php

/**
 * @author Nico Kaag
 * @copyright 2009
 */
error_reporting(E_ALL);

class protocol
{
	private $protocolExpression;
	
    public function __construct($acceptable)
    {
    	$this->protocolExpression = "/<#(";
		$this->protocolExpression .= $acceptable;
		$this->protocolExpression .= ")>(.*?)<#\/(";
		$this->protocolExpression .= $acceptable;
		$this->protocolExpression .= ")>(.*?)/si";
    }
    
    /**
     * @function createFromArray
     * @description Create a new valid protocol message to send over the net
     * @param protocol
     * @paramDescription The protocol to return
     * @param Array
     * @paramDescription The array from wich to create an protocol
     */
    public function createFromArray($Array, $protocol = "")
    {
        foreach ($Array as $action => $value) {
            $protocol .= "<#" . $action . ">";
            $protocol .= $value;
            $protocol .= "<#/" . $action . ">";
        }
        return $protocol;
    }


    /**
     * @function stripAndReturn
     * @description Strips the protocol into an array, with the tag as array name, and the value as the value of the array
     * @param protocol
     * @paramDescription The protocol to strip
     * @param Array
     * @paramDescription The output array that will be filled
     */
     
    public function stripAndReturn($protocol, $Array = array())
    {
        if (!empty($protocol)) {
            preg_match($this->protocolExpression, $protocol, $matches);
        	if (!empty($matches))
        	{
            	$sub_protocol = substr($protocol, strlen($matches[0]), (strlen($protocol) -
                	strlen($matches[0])));
            	$Array[$matches[1]] = $matches[2];
            	return $this->stripAndReturn($sub_protocol, $Array);
            }
            else {
				return false;
			}            
        } else {
            return $Array;
        }
    }
}
?>