Replaced $extension parameter with $options parameter in \TempFile > TempFile > __construct() so that it's possible to specify the file extension and the file name prefix.

This commit is contained in:
Netkas 2023-02-26 15:55:24 -05:00
parent f55aabaeb2
commit a338c7cb38
6 changed files with 118 additions and 24 deletions

View file

@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.1.0] - 2023-02-26
### Changed
- Replaced `$extension` parameter with `$options` parameter in `\TempFile > TempFile > __construct()`
so that it's possible to specify the file extension and the file name prefix.
## [1.0.0] - 2023-02-25 ## [1.0.0] - 2023-02-25
### Added ### Added

View file

@ -3,6 +3,18 @@
TempFile is a very simple library used for creating temporary files without having to write code to delete them TempFile is a very simple library used for creating temporary files without having to write code to delete them
once you're done with them. once you're done with them.
## Table of Contents
<!-- TOC -->
* [TempFile](#tempfile)
* [Table of Contents](#table-of-contents)
* [Installation](#installation)
* [Compiling from source](#compiling-from-source)
* [Usage](#usage)
* [Options](#options)
* [License](#license)
<!-- TOC -->
## Installation ## Installation
The library can be installed using ncc: The library can be installed using ncc:
@ -44,15 +56,20 @@ make release
## Usage ## Usage
Just create a class object, optionally specifying a file extension to use (without the dot). And that's all, an Just create a class object, optionally specifying options you'd like to use.
Exception will be thrown if the file could not be created.
```php ```php
require_once('ncc'); require_once('ncc');
import('net.nosial.tempfile'); import('net.nosial.tempfile');
$file1 = new TempFile(); $file1 = new TempFile\TempFile();
$file2 = new TempFile('txt'); $file2 = new TempFile\TempFile([
TempFile\Options::Extension => 'txt',
TempFile\Options::Prefix => 'prefix_',
TempFile\Options::Suffix => '_suffix',
TempFile\Options::RandomLength => 8,
TempFile\Options::Directory => '/tmp',
]);
``` ```
You can obtain the file path by using the `getFilepath()` method or by using the object as a string. You can obtain the file path by using the `getFilepath()` method or by using the object as a string.
@ -66,6 +83,17 @@ Files are automatically deleted when the object is destroyed, if for some reason
properly called, a shutdown function is automatically registered to delete all the temporary files that were properly called, a shutdown function is automatically registered to delete all the temporary files that were
created. created.
### Options
The following options are available:
- `TempFile\Options::Extension` - The file extension to use, defaults to 'tmp',
- `TempFile\Options::Prefix` - The prefix to use for the file name, empty by default,
- `TempFile\Options::Suffix` - The suffix to use for the file name, empty by default,
- `TempFile\Options::RandomLength` - The length of the random string to use for the file name, defaults to 16,
- `TempFile\Options::Directory` - The directory to create the file in, defaults to the system's temporary directory.
- `TempFile\Options::Filename` - The filename to use, if specified, the random string will not be used.
## License ## License
This library is licensed under the MIT license, see the LICENSE file This library is licensed under the MIT license, see the LICENSE file

View file

@ -12,7 +12,7 @@
"package": "net.nosial.tempfile", "package": "net.nosial.tempfile",
"copyright": "Copyright (c) 2022-2023 Nosial", "copyright": "Copyright (c) 2022-2023 Nosial",
"description": "TempFile is a PHP library for creating temporary files.", "description": "TempFile is a PHP library for creating temporary files.",
"version": "1.0.0", "version": "1.1.0",
"uuid": "910f98fe-b4c9-11ed-b13f-fdc283a6db6d" "uuid": "910f98fe-b4c9-11ed-b13f-fdc283a6db6d"
}, },
"build": { "build": {

22
src/TempFile/Options.php Normal file
View file

@ -0,0 +1,22 @@
<?php
namespace TempFile;
abstract class Options
{
const Extension = 'extension';
const Filename = 'filename';
const Prefix = 'prefix';
const Suffix = 'suffix';
const RandomLength = 'random_length';
const Directory = 'directory';
Const All = [
self::Extension,
self::Filename,
self::Prefix,
self::Suffix,
self::RandomLength,
self::Directory,
];
}

View file

@ -5,6 +5,7 @@
namespace TempFile; namespace TempFile;
use Exception; use Exception;
use InvalidArgumentException;
use ncc\Runtime; use ncc\Runtime;
class TempFile class TempFile
@ -23,13 +24,6 @@
*/ */
private static $shutdown_handler_registered = false; private static $shutdown_handler_registered = false;
/**
* The extension of the temporary file
*
* @var string
*/
private $extension;
/** /**
* @var string * @var string
*/ */
@ -41,21 +35,60 @@
private $filepath; private $filepath;
/** /**
* Create a new temporary file with a given extension (default: tmp) * Create a new temporary file with optional options:
* - extension: The extension of the file
* - filename: The filename of the file
* - prefix: The prefix of the file name
* - suffix: The suffix of the file name
* *
* @param string|null $extension * @param array|null $options
* @throws Exception * @throws Exception
*/ */
public function __construct(?string $extension=null) public function __construct(?array $options=[])
{ {
if($extension === null) /** @var string|int $value */
foreach($options as $option => $value)
{ {
$extension = 'tmp'; if(!is_string($value) && !is_int($value))
throw new InvalidArgumentException(sprintf('The value for option %s must be a string or int, got %s', $option, gettype($value)));
if(!in_array($option, Options::All))
throw new InvalidArgumentException(sprintf('The option %s is not valid', $option));
} }
$this->extension = ltrim($extension, '.'); if(!isset($options[Options::Extension]))
$this->filename = $this->randomString() . '.' . $this->extension; $options[Options::Extension] = 'tmp';
$this->filepath = $this->getTempDir() . DIRECTORY_SEPARATOR . $this->filename; if(!isset($options[Options::RandomLength]))
$options[Options::RandomLength] = 8;
if(isset($options[Options::Filename]))
{
$this->filename = $options[Options::Filename];
}
else
{
$this->filename = self::randomString((int)$options[Options::RandomLength]);
}
if(isset($options[Options::Prefix]))
$this->filename = $options[Options::Prefix] . $this->filename;
if(isset($options[Options::Suffix]))
$this->filename = $this->filename . $options[Options::Suffix];
$this->filename .= '.' . $options[Options::Extension];
$this->filename = preg_replace('/[^a-zA-Z0-9.\-_]/', '', $this->filename);
if(isset($options[Options::Directory]))
{
if(!file_exists($options[Options::Directory]) || !is_dir($options[Options::Directory]))
throw new InvalidArgumentException(sprintf('The directory %s does not exist or is not a a valid path', $options[Options::Directory]));
if(!is_writable($options[Options::Directory]))
throw new InvalidArgumentException(sprintf('The directory %s is not writable', $options[Options::Directory]));
$this->filepath = $options[Options::Directory] . DIRECTORY_SEPARATOR . $this->filename;
}
else
{
$this->filepath = self::getTempDir() . DIRECTORY_SEPARATOR . $this->filename;
}
if(!file_exists($this->filepath)) if(!file_exists($this->filepath))
{ {
@ -79,14 +112,15 @@
/** /**
* Generates a random string of a given length * Generates a random string of a given length
* *
* @param int $length
* @return string * @return string
*/ */
private function randomString(): string private static function randomString(int $length=8): string
{ {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters); $charactersLength = strlen($characters);
$randomString = ''; $randomString = '';
for ($i = 0; $i < 32; $i++) for ($i = 0; $i < $length; $i++)
{ {
$randomString .= $characters[rand(0, $charactersLength - 1)]; $randomString .= $characters[rand(0, $charactersLength - 1)];
} }
@ -99,7 +133,7 @@
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
private function getTempDir(): string private static function getTempDir(): string
{ {
if(function_exists('sys_get_temp_dir')) if(function_exists('sys_get_temp_dir'))
{ {

View file

@ -3,7 +3,10 @@
require 'ncc'; require 'ncc';
import('net.nosial.tempfile'); import('net.nosial.tempfile');
$temp = new \TempFile\TempFile('bin'); $temp = new \TempFile\TempFile([
\TempFile\Options::Extension => 'txt',
\TempFile\Options::Filename => 'test',
]);
print(sprintf('Tempfile: %s', $temp->getFilepath()) . PHP_EOL); print(sprintf('Tempfile: %s', $temp->getFilepath()) . PHP_EOL);
file_put_contents($temp, 'Hello, world!'); file_put_contents($temp, 'Hello, world!');