UserStorageService.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. namespace App\Services;
  3. use App\Media;
  4. use App\User;
  5. class UserStorageService
  6. {
  7. const CACHE_KEY = 'pf:services:user-storage:byId:';
  8. public static function get($id)
  9. {
  10. $user = User::find($id);
  11. if (! $user || $user->status) {
  12. return -1;
  13. }
  14. if ($user->storage_used_updated_at) {
  15. return (int) $user->storage_used;
  16. }
  17. $updatedVal = self::calculateStorageUsed($id);
  18. $user->storage_used = $updatedVal;
  19. $user->storage_used_updated_at = now();
  20. $user->save();
  21. return $user->storage_used;
  22. }
  23. public static function calculateStorageUsed($id)
  24. {
  25. return (int) floor(Media::whereUserId($id)->sum('size') / 1000);
  26. }
  27. public static function recalculateUpdateStorageUsed($id)
  28. {
  29. $user = User::find($id);
  30. if (! $user || $user->status) {
  31. return;
  32. }
  33. $updatedVal = (int) floor(Media::whereUserId($id)->sum('size') / 1000);
  34. $user->storage_used = $updatedVal;
  35. $user->storage_used_updated_at = now();
  36. $user->save();
  37. return $updatedVal;
  38. }
  39. }