<?php
/**
 * Link         :   http://www.phpcorner.net
 * User         :   qingbing<780042175@qq.com>
 * Date         :   2018-10-27
 * Version      :   1.0
 */

namespace Helper;

use Abstracts\Factory;

/**
 * 文件实例
 * Class File
 * @package Helper
 */
class File extends Factory
{
    private $_filePath;
    private $_stringBuffer = "";

    /**
     * 设置操作的文件路径
     * @param string $filePath
     * @return $this
     */
    public function setFilePath($filePath)
    {
        $this->_filePath = $filePath;
        return $this;
    }

    /**
     * 删除一个存在的文件
     * @return bool
     */
    public function unlink()
    {
        if (file_exists($this->_filePath)) {
            return @unlink($this->_filePath);
        }
        return true;
    }

    /**
     * 获取文件的相应属性，文件不一定存在
     * @param null|int $option
     *      PATHINFO_DIRNAME
     *      PATHINFO_BASENAME
     *      PATHINFO_EXTENSION
     *      PATHINFO_FILENAME
     * @return mixed
     */
    public function pathinfo($option = null)
    {
        if (null === $option) {
            return pathinfo($this->_filePath);
        }
        return pathinfo($this->_filePath, $option);
    }

    /**
     * 获取文件中的内容
     * @return bool|string
     */
    public function get()
    {
        if (file_exists($this->_filePath)) {
            return file_get_contents($this->_filePath);
        }
        return null;
    }

    /**
     * 将字符串写入文件中
     * @param $content
     * @param int $mode 写入方式：LOCK_EX、 FILE_APPEND
     * @return bool|int
     */
    public function put($content, $mode = LOCK_EX)
    {
        return file_put_contents($this->_filePath, $content, $mode);
    }

    /**
     * 清空文件（删除文件，并返回本实例）
     * @return $this
     * @throws Exception
     */
    public function setEmpty()
    {
        if ($this->unlink()) {
            return $this;
        }
        throw new Exception("清空文件失败", 100100301);
    }

    /**
     * 将字符串追加到缓冲字符串中
     * @param string $content
     * @param bool $needLine
     * @return $this
     */
    public function append($content, $needLine = false)
    {
        if ($needLine) {
            $this->_stringBuffer .= "\r\n";
        }
        $this->_stringBuffer .= $content;
        return $this;
    }

    /**
     * 将缓冲内容追加到文件中
     * @return bool|int
     * @throws Exception
     */
    public function flush()
    {
        if (false !== $many = $this->put($this->_stringBuffer, FILE_APPEND)) {
            $this->_stringBuffer = "";
            return $many;
        }
        throw new Exception("文件写入失败+", 100100302);
    }
}