<?php
/**
 * YANA library
 *
 * @package yana
 * @licence http://creativecommons.org/licenses/by-nc-sa/2.5/
 */

/**
 * This class is an alternative to csv files.
 *
 * @access      public
 * @package     yana
 * @subpackage  io
 *
 */
class DatFile extends SecureFileStream
{

    /**
    * retrieve a line of data from the file
    *
    * @uses $datfile->get(0)
    * @param integer $line_nr line to retrieve
    * @access public
    * @return array
    */
    function get($line_nr)
    {
        settype($line_nr, 'integer');
        $data      = $this->content[$line_nr];
        $REF       = array();
        while (preg_match("/<(.*)>(.*)<\/.*>/Ui", $data, $matches))
        {
            $matches[2]       = preg_replace("/(\S{80})(\S*)/i", "\\1<wbr>\\2", $matches[2]);
            $REF[strtoupper($matches[1])] = $matches[2];
            $data             = preg_replace("/<".$matches[1].">.*<\/.*>/U", "", $data);
            $matches          = array();
        }
        return $REF;
    }

    /**
    * insert (append) an entry to the file
    *
    * @uses $datfile->insert($new_entry)
    * @param array $new_entry associative array containing the new entry
    * @access public
    * @return boolean
    */
    function insert($REF)
    {
        if (!is_array($REF)) {
            return false;
        }
        $txt       = "";
        foreach ($REF as $key => $element)
        {
            $key     = strtoupper($key);
            $element = strip_tags($element);
            $txt    .= "<$key>$element</$key>";
        }
        $txt       = nl2br($txt);
        $txt       = preg_replace("/\s/"," ",$txt);
        $txt      .= "\n";
        if (!$this->isEmpty()) {
            array_unshift($this->content,$txt);
        } else {
            $this->content[0] = $txt;
        }
        return true;
    }

    /**
    * remove an entry from the file
    *
    * @uses $datfile->insert($new_entry)
    * @param array $line_nr line to retrieve
    * @access public
    * @return boolean
    */
    function remove($line_nr)
    {
        settype($line_nr, 'integer');
        if (isset($this->content[$line_nr])) {
            unset($this->content[$line_nr]);
            return true;
        } else {
            return false;
        }
    }

    /**
    * return file content as string (if available)
    *
    * @uses $datfile->toString()
    * @access public
    * @return string
    */
     function toString()
     {
        if (!$this->exists()) {
            return "Dat-file ".$this->filename." does not exist";
        } else if ($this->isEmpty()) {
            return "Dat-file ".$this->filename." is wether empty or not opened";
        } else {
            return implode("\n", $this->content);
        }
     }


    /**
    * return the number of rows in the file
    *
    * @uses $datfile->length()
    * @access public
    * @return integer
    */
    function length()
    {
        return count($this->content);
    }

}

?>