Controller.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace App\Controllers;
  3. use League\Flysystem\Adapter\Local;
  4. use League\Flysystem\FileNotFoundException;
  5. use League\Flysystem\Filesystem;
  6. use Slim\Container;
  7. use Slim\Http\Request;
  8. use Slim\Http\Response;
  9. abstract class Controller
  10. {
  11. /** @var Container */
  12. protected $container;
  13. public function __construct(Container $container)
  14. {
  15. $this->container = $container;
  16. }
  17. /**
  18. * @param $name
  19. * @return mixed|null
  20. * @throws \Interop\Container\Exception\ContainerException
  21. */
  22. public function __get($name)
  23. {
  24. if ($this->container->has($name)) {
  25. return $this->container->get($name);
  26. }
  27. return null;
  28. }
  29. /**
  30. * Generate a human readable file size
  31. * @param $size
  32. * @param int $precision
  33. * @return string
  34. */
  35. protected function humanFilesize($size, $precision = 2): string
  36. {
  37. for ($i = 0; ($size / 1024) > 0.9; $i++, $size /= 1024) {
  38. }
  39. return round($size, $precision) . ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'][$i];
  40. }
  41. /**
  42. * Get a filesystem instance
  43. * @return Filesystem
  44. */
  45. protected function getStorage(): Filesystem
  46. {
  47. return new Filesystem(new Local($this->settings['storage_dir']));
  48. }
  49. /**
  50. * @param $path
  51. */
  52. protected function removeDirectory($path)
  53. {
  54. $files = glob($path . '/*');
  55. foreach ($files as $file) {
  56. is_dir($file) ? $this->removeDirectory($file) : unlink($file);
  57. }
  58. rmdir($path);
  59. return;
  60. }
  61. /**
  62. * @param $id
  63. * @return int
  64. */
  65. protected function getUsedSpaceByUser($id): int
  66. {
  67. $medias = $this->database->query('SELECT `uploads`.`storage_path` FROM `uploads` WHERE `user_id` = ?', $id)->fetchAll();
  68. $totalSize = 0;
  69. $filesystem = $this->getStorage();
  70. foreach ($medias as $media) {
  71. try {
  72. $totalSize += $filesystem->getSize($media->storage_path);
  73. } catch (FileNotFoundException $e) {
  74. }
  75. }
  76. return $totalSize;
  77. }
  78. }