<?php
namespace ModulesAbstract\ElectronicInvoice; class TemporaryFilePicker { protected $basePath = null; protected $baseName = null; protected $baseExtension = null; protected $basePathAndName = null; protected $maxAllowedAge = 3600; public function __construct($basePath, $baseName, $maxAllowedAge=3600) { $this->basePath = $basePath; $this->baseName = \Engine\File::getName(preg_replace("/[^a-z0-9-_\.]/i", "", $baseName)); $this->baseExtension = (\Engine\File::getExtension(preg_replace("/[^a-z0-9-_\.]/i", "", $baseName))?:'tmp'); $this->basePathAndName = sprintf("%s/%s/", $this->basePath, $this->baseName); $this->maxAllowedAge = $maxAllowedAge; } public function initialize() { if (!\Engine\Dir::check($this->basePathAndName)) { \Engine\Dir::create($this->basePathAndName); } if (\Engine\RandomGenerator::randomInt(0, 100) < 33) { $this->cleanup(); } return $this; } public function cleanup() { $currentTime = time(); $dirContents = \Engine\Dir::getContents($this->basePathAndName); $existingFiles = (array)$dirContents['files']; $oldFiles = array_filter($existingFiles, function($f) use ($currentTime) { return ($currentTime - filemtime($this->basePathAndName . $f)) > $this->maxAllowedAge; }); foreach ($oldFiles as $f) { \Engine\File::delete($this->basePathAndName . $f); } $existingFolders = (array)$dirContents['dirs']; $oldFolders = array_filter($existingFolders, function($f) use ($currentTime) { return ($currentTime - filemtime($this->basePathAndName . $f)) > $this->maxAllowedAge; }); foreach ($oldFolders as $f) { \Engine\Dir::delete($this->basePathAndName . $f); } return $this; } public function getAvailableFile() { $f = sprintf("%s/%s-%s.%s", $this->basePathAndName, uniqid(), \Engine\RandomGenerator::randomString(\Engine\RandomGenerator::randomInt(2, 9)), $this->baseExtension); \Engine\File::create($f, ""); return $f; } } 