/app/model/Service/FileManager.php
https://gitlab.com/Spilky/diplomova_prace · PHP · 120 lines · 71 code · 18 blank · 31 comment · 12 complexity · fb717ff162bdef76b16785caef7ccc9b MD5 · raw file
- <?php
- namespace App\Model\Service;
- use Exception;
- use Nette\Http\FileUpload;
- use Nette\Utils\Random;
- class FileManager
- {
- /** @var string */
- private $directory;
- /** @var string|null */
- private $subDirectory;
- /** @var string|null */
- private $watermark;
- /**
- * ImageManager constructor.
- * @param string $directory
- * @param string|null $watermark
- */
- public function __construct($directory, $watermark = null)
- {
- $this->directory = $directory;
- $this->watermark = $watermark;
- if (substr($this->directory, -1) != '/') {
- $this->directory .= '/';
- }
- }
- /**
- * @return string
- */
- public function getDirectory()
- {
- return $this->directory;
- }
- /**
- * @param mixed $subDirectory
- */
- public function setSubDirectory($subDirectory)
- {
- $this->subDirectory = $subDirectory;
- if (substr($this->subDirectory, 0, 1) == '/') {
- $this->subDirectory = substr($this->subDirectory, 1);
- }
- if (substr($this->subDirectory, -1) != '/') {
- $this->subDirectory .= '/';
- }
- }
- private function getPath()
- {
- return $this->directory . $this->subDirectory;
- }
- /**
- * @param FileUpload $file
- * @param null $name
- * @return null|string
- * @throws Exception
- */
- public function saveFile(FileUpload $file, $name = null)
- {
- if (!$file->isOk()) {
- throw new Exception('Upload error: ' . $file->getError());
- }
- if (is_null($name)) {
- $name = $this->generateName($file);
- } else {
- $this->checkName($name);
- }
- $file->move($this->getPath() . $name);
- return $name;
- }
- /**
- * @param $name
- * @throws Exception
- */
- private function checkName($name)
- {
- if (is_file($this->getPath() . $name)) {
- throw new Exception('File exists already.');
- }
- }
- /**
- * @param FileUpload $file
- * @return string
- */
- private function generateName(FileUpload $file)
- {
- $fileExt = strtolower(mb_substr($file->getSanitizedName(), strrpos($file->getSanitizedName(), ".")));
- do {
- $name = Random::generate() . $fileExt;
- } while (is_file($this->getPath() . $name));
- return $name;
- }
- /**
- * @param string $name
- */
- public function delete($name)
- {
- $file = $this->getPath() . $name;
- if (is_file($file)) {
- unlink($file);
- }
- }
- }