rosavox/lib/alveolata/file/functions.php

82 lines
1.3 KiB
PHP
Raw Normal View History

2025-05-23 07:33:29 +00:00
<?php
namespace alveolata\file;
// require_once(DIR_ALVEOLATA . '/definitions.php');
/**
* @param string $path
* @return bool
* @author Christian Fraß <frass@greenscale.de>
*/
function exists(
string $path
) : bool
{
return file_exists($path);
}
/**
* @param string $path
* @return string
* @author Christian Fraß <frass@greenscale.de>
*/
function read(
string $path
) : string
{
if (! exists($path)) {
throw (new \Exception(sprintf('file not found: "%s"', $path)));
}
else {
$content = file_get_contents($path);
if ($content === false) {
throw (new \Exception('could not read file'));
}
else {
return $content;
}
}
}
/**
* @param string $path
* @param string $content
* @author Christian Fraß <frass@greenscale.de>
*/
function write(
string $path,
string $content,
bool $create_directory_if_missing = false
)
{
if ($create_directory_if_missing) {
$directory = implode('/', array_slice(explode('/', $path), 0, -1));
if (! file_exists($directory)) {
mkdir($directory);
}
}
file_put_contents($path, $content);
}
/**
* @param string $path
* @author Christian Fraß <frass@greenscale.de>
*/
function remove(
string $path
)
{
if (! exists($path)) {
throw (new \Exception(sprintf('file not found: "%s"', $path)));
}
else {
unlink($path);
}
}