misuzu/src/IO/File.php

94 lines
2.2 KiB
PHP

<?php
namespace Misuzu\IO;
use Exception;
/**
* Static file meta functions.
* @package Misuzu\IO
* @author flashwave <me@flash.moe>
*/
class File
{
/**
* @param string $filename
* @return FileStream
* @throws FileDoesNotExistException
* @throws IOException
*/
public static function open(string $filename): FileStream
{
return new FileStream($filename, FileStream::MODE_READ_WRITE, true);
}
/**
* @param string $filename
* @param bool $lock
* @return string
*/
public static function readToEnd(string $filename, bool $lock = false): string
{
$output = '';
try {
$file = new FileStream($filename, FileStream::MODE_READ, $lock);
$output = $file->read($file->getLength());
$file->close();
} catch (Exception $ex) {
}
return $output;
}
/**
* @param string $filename
* @param string $data
* @throws FileDoesNotExistException
* @throws IOException
*/
public static function writeAll(string $filename, string $data): void
{
$file = new FileStream($filename, FileStream::MODE_TRUNCATE, true);
$file->write($data);
$file->close();
}
/**
* Creates an instance of a temporary file.
* @param string $prefix
* @return FileStream
* @throws FileDoesNotExistException
* @throws IOException
*/
public static function temp(string $prefix = 'Misuzu'): FileStream
{
return static::open(tempnam(sys_get_temp_dir(), $prefix));
}
/**
* Checks if a file exists.
* @param string $path
* @return bool
*/
public static function exists(string $path): bool
{
$path = realpath(Directory::fixSlashes($path));
return file_exists($path) && is_file($path);
}
/**
* Deletes a file permanently, use with care!
* @param string $path
* @throws FileDoesNotExistException
*/
public static function delete(string $path): void
{
$path = realpath(Directory::fixSlashes($path));
if (!is_string($path) || !static::exists($path)) {
throw new FileDoesNotExistException;
}
unlink($path);
}
}