<?php
/**
* File Buffer for Scheduled Runs
*
* Buffers file inputs for scheduled execution based on a configuration file.
*/
class FileBuffer
{
private $config;
private $buffer = [];
public function __construct(array $config)
{
$this->config = $config;
}
/**
* Adds a file path to the buffer.
*
* @param string $filePath The path to the file.
* @return bool True on success, false on failure.
*/
public function addFile(string $filePath): bool
{
if (file_exists($filePath) && is_readable($filePath)) {
$this->buffer[] = $filePath;
return true;
}
return false;
}
/**
* Clears the buffer.
*/
public function clearBuffer(): void
{
$this->buffer = [];
}
/**
* Gets the buffered file paths.
*
* @return array An array of file paths.
*/
public function getBuffer(): array
{
return $this->buffer;
}
/**
* Processes the buffered files.
*
* @return array An array of processed file paths. Returns empty array on error.
*/
public function processFiles(): array
{
$processedFiles = [];
if (empty($this->buffer)) {
return $processedFiles; // Return empty array if buffer is empty
}
foreach ($this->buffer as $filePath) {
try {
// Simulate file processing - replace with actual logic
$processedFiles[] = $filePath . " - Processed";
//Example: file_get_contents($filePath);
} catch (Exception $e) {
error_log("Error processing file " . $filePath . ": " . $e->getMessage());
// Optionally, remove the failed file from the buffer.
//unset($this->buffer[array_search($filePath, $this->buffer)]);
}
}
$this->clearBuffer(); // Clear the buffer after processing
return $processedFiles;
}
}
/**
* Configuration File Handling
*
* Reads configuration from a JSON file.
*
* @param string $configFile Path to the configuration file.
* @return array|null An array of configuration settings, or null on error.
*/
function getConfig(string $configFile): ?array
{
if (file_exists($configFile)) {
$json = file_get_contents($configFile);
$config = json_decode($json, true);
if (json_last_error() === JSON_ERROR_NONE) {
return $config;
} else {
error_log("Error decoding JSON from " . $configFile . ": " . json_last_error_msg());
return null;
}
} else {
error_log("Configuration file not found: " . $configFile);
return null;
}
}
// Example Usage (assuming config.json exists)
$config = getConfig('config.json');
if ($config) {
$buffer = new FileBuffer($config);
// Simulate adding files
$buffer->addFile('/path/to/file1.txt');
$buffer->addFile('/path/to/file2.csv');
$buffer->addFile('/path/to/nonexistent_file.txt'); //Test error handling
$processedFiles = $buffer->processFiles();
print_r($processedFiles); //Output the processed file paths.
} else {
echo "Failed to load configuration. Exiting.\n";
}
?>
Add your comment