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

/**
 * SecureInputStream
 *
 * @access      public
 * @package     yana
 * @subpackage  io
 */
class SecureInputStream extends InputStream
{

    /**#@+
     * @ignore
     * @access  protected
     * @var     array
     */

    var $source  = null;
    var $content = null;
    var $options = array();
    
    /**#@-*/

    /**
     * read
     *
     * @access public
     * @return boolean
     */
    function read()
    {
        if (!$this->exists()) {
            return false;
        } else {
            $this->content = $this->source = file($this->filename);
            $this->options = $this->attributes;
            return true;
        }
    }

    /**
     * failSafeRead
     *
     * @access public
     * @return boolean
     */
    function failSafeRead()
    {
        for ($i=0; $i<3; $i++) 
        {
            if ($this->read()) {
              return true;
              break;
            } else {
              sleep(0.5);
            }
        }
        return false;
    }

    /**
     * get
     *
     * @access public
     * @return string
     */
    function get()
    {
        if (!$this->isEmpty()) {
            return implode("", $this->content);
        } else {
            return "";
        }
    }

    /**
     * toString
     *
     * @access public
     * @return string
     */
    function toString()
    {
        if (!$this->exists()) {
            return "File ".$this->filename." does not exist\n";
        } elseif ($this->isEmpty()) {
            return "File ".$this->filename." is wether empty or not loaded\n";
        } else {
            return $this->get();
        }
    }

    /**
     * isEmpty
     *
     * @access public
     * @return boolean
     */
    function isEmpty()
    {
        if (is_null($this->source)) {
            return true;
        } elseif (is_array($this->source)) {
            return count($this->source) == 0;
        } elseif (is_scalar($this->source)) {
            return empty($this->source);
        } else {
            /* the source is invalid */
            return true;
        }
    }

    /**
     * checksum
     *
     * @access public
     * @return int
     */
    function checksum()
    {
        if (is_null($this->source)) {
            return 0;
        } elseif (is_array($this->source)) {
            return crc32(print_r($this->source,true));
        } elseif (is_string($this->source)) {
            return crc32($this->source);
        } else {
            /* the source is invalid */
            return 0;
        }
    }

    /**
     * reset
     *
     * @access public
     */
    function reset()
    {
        $this->content = $this->source;
        $this->options = $this->attributes;
    }

}

?>