82 lines
2.0 KiB
PHP
82 lines
2.0 KiB
PHP
|
<?php
|
||
|
/**
|
||
|
* Buffer class for a string.
|
||
|
* Will fix issues with sockets that don't care about linebreaks.
|
||
|
* Can also be used for all kinds of purpose.
|
||
|
* @author jpt
|
||
|
* @package Misc
|
||
|
*/
|
||
|
class Misc_Buffer {
|
||
|
|
||
|
/**
|
||
|
* Bufferstring - contains all the data.
|
||
|
* @var string
|
||
|
*/
|
||
|
protected $buffer;
|
||
|
|
||
|
/**
|
||
|
* Linebreak to use for pulling lines out of the buffer.
|
||
|
* @var string
|
||
|
*/
|
||
|
protected $linebreak;
|
||
|
|
||
|
/**
|
||
|
* Default constructor. Sets a default linebreak and initializes the buffer.
|
||
|
* @param $linebreak
|
||
|
* @return void
|
||
|
*/
|
||
|
function __construct($linebreak = "\r\n") {
|
||
|
$this->buffer = "";
|
||
|
$this->linebreak = $linebreak;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Prunes empty lines out of the buffer.
|
||
|
* @return void
|
||
|
*/
|
||
|
protected function pruneEmptyLines() {
|
||
|
if(strpos($this->buffer, $this->linebreak) === FALSE) return;
|
||
|
$has_linebreak_at_end = (substr($this->buffer, (-1) * strlen($this->linebreak)) === $this->linebreak) ? TRUE : FALSE;
|
||
|
$lines = explode($this->linebreak, $this->buffer);
|
||
|
foreach($lines AS $key=>$line) {
|
||
|
$line = str_replace($this->linebreak, "", $line);
|
||
|
$line = trim($line);
|
||
|
if($line === "") unset($lines[$key]);
|
||
|
}
|
||
|
$this->buffer = implode($this->linebreak, $lines);
|
||
|
if($has_linebreak_at_end) $this->buffer .= $this->linebreak;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Appends data to the buffer.
|
||
|
* @param string $data
|
||
|
* @return void
|
||
|
*/
|
||
|
public function addData($data) {
|
||
|
$this->buffer .= $data;
|
||
|
$this->pruneEmptyLines();
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Returns the next line in the buffer and removes it from the buffer.
|
||
|
* @return string
|
||
|
*/
|
||
|
public function getNextLine() {
|
||
|
if(!$this->hasLines()) return "";
|
||
|
list($line) = explode($this->linebreak, $this->buffer);
|
||
|
$this->buffer = str_replace($line.$this->linebreak, "", $this->buffer);
|
||
|
$line = trim($line);
|
||
|
$result = ($line !== "") ? $line.$this->linebreak : "";
|
||
|
return $result;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Checks whether the buffer contains more lines to process.
|
||
|
* @return boolean
|
||
|
*/
|
||
|
public function hasLines() {
|
||
|
return (trim(strstr($this->buffer, $this->linebreak, TRUE)) !== "") ? TRUE : FALSE;
|
||
|
}
|
||
|
|
||
|
}
|
||
|
?>
|