/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

  1. <?php
  2. namespace App\Model\Service;
  3. use Exception;
  4. use Nette\Http\FileUpload;
  5. use Nette\Utils\Random;
  6. class FileManager
  7. {
  8. /** @var string */
  9. private $directory;
  10. /** @var string|null */
  11. private $subDirectory;
  12. /** @var string|null */
  13. private $watermark;
  14. /**
  15. * ImageManager constructor.
  16. * @param string $directory
  17. * @param string|null $watermark
  18. */
  19. public function __construct($directory, $watermark = null)
  20. {
  21. $this->directory = $directory;
  22. $this->watermark = $watermark;
  23. if (substr($this->directory, -1) != '/') {
  24. $this->directory .= '/';
  25. }
  26. }
  27. /**
  28. * @return string
  29. */
  30. public function getDirectory()
  31. {
  32. return $this->directory;
  33. }
  34. /**
  35. * @param mixed $subDirectory
  36. */
  37. public function setSubDirectory($subDirectory)
  38. {
  39. $this->subDirectory = $subDirectory;
  40. if (substr($this->subDirectory, 0, 1) == '/') {
  41. $this->subDirectory = substr($this->subDirectory, 1);
  42. }
  43. if (substr($this->subDirectory, -1) != '/') {
  44. $this->subDirectory .= '/';
  45. }
  46. }
  47. private function getPath()
  48. {
  49. return $this->directory . $this->subDirectory;
  50. }
  51. /**
  52. * @param FileUpload $file
  53. * @param null $name
  54. * @return null|string
  55. * @throws Exception
  56. */
  57. public function saveFile(FileUpload $file, $name = null)
  58. {
  59. if (!$file->isOk()) {
  60. throw new Exception('Upload error: ' . $file->getError());
  61. }
  62. if (is_null($name)) {
  63. $name = $this->generateName($file);
  64. } else {
  65. $this->checkName($name);
  66. }
  67. $file->move($this->getPath() . $name);
  68. return $name;
  69. }
  70. /**
  71. * @param $name
  72. * @throws Exception
  73. */
  74. private function checkName($name)
  75. {
  76. if (is_file($this->getPath() . $name)) {
  77. throw new Exception('File exists already.');
  78. }
  79. }
  80. /**
  81. * @param FileUpload $file
  82. * @return string
  83. */
  84. private function generateName(FileUpload $file)
  85. {
  86. $fileExt = strtolower(mb_substr($file->getSanitizedName(), strrpos($file->getSanitizedName(), ".")));
  87. do {
  88. $name = Random::generate() . $fileExt;
  89. } while (is_file($this->getPath() . $name));
  90. return $name;
  91. }
  92. /**
  93. * @param string $name
  94. */
  95. public function delete($name)
  96. {
  97. $file = $this->getPath() . $name;
  98. if (is_file($file)) {
  99. unlink($file);
  100. }
  101. }
  102. }