Scripts
Protocol Class
Nu nog een kleine klasse om simpel een protocol te strippen en te bouwen. Kan handig zijn als je dingen via Sockets o.i.d. verstuurt. Je kan er array ingooien, en dan krijg je het protocol terug. Of je gooit er een protocol in, en dan rolt een array eruit, waarvan de actie de naam is, en het resultaat ervan dus de waarde. Voorbeeld: Als je er nog een functie bij wilt, hoor ik dat graag. Overigens hoor ik ook graag alle op en aanmerkingen.
protocol-class
<?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;
}
}
}
?>
Reacties
0