<?php

namespace Velis\Filesystem\Stream;

/**
 * @author Jan Małysiak <jan.malysiak@velis.pl>
 */
class LocalStream implements StreamInterface
{
    /**
     * @var string
     */
    private $filename;

    /**
     * @var resource
     */
    private $handle;

    public function __construct($filename)
    {
        $this->filename = $filename;
    }

    /**
     * {@inheritDoc}
     */
    public function open($mode = 'r')
    {
        if (!file_exists($this->filename)) {
            return false;
        }

        $this->handle = fopen($this->filename, $mode);

        return (bool) $this->handle;
    }

    /**
     * {@inheritDoc}
     */
    public function seek($offset, $whence = SEEK_SET)
    {
        if ($this->handle) {
            return 0 === fseek($this->handle, $offset, $whence);
        }

        return false;
    }

    /**
     * {@inheritDoc}
     */
    public function read($count)
    {
        if (!$this->handle) {
            return false;
        }

        return fread($this->handle, $count);
    }

    /**
     * {@inheritDoc}
     */
    public function close()
    {
        if (fclose($this->handle)) {
            $this->handle = null;
        }
    }
}
