LogoUploadServices.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. <?php
  2. namespace App\Services;
  3. use Illuminate\Support\Facades\Storage;
  4. use Illuminate\Support\Facades\Log;
  5. use Illuminate\Http\UploadedFile;
  6. use Exception;
  7. class LogoUploadServices
  8. {
  9. /**
  10. * The storage disk to use for file operations
  11. */
  12. private $disk;
  13. /**
  14. * Allowed file extensions for logos
  15. */
  16. private const ALLOWED_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
  17. /**
  18. * Maximum file size in KB
  19. */
  20. private const MAX_FILE_SIZE = 2048;
  21. /**
  22. * Constructor
  23. */
  24. public function __construct()
  25. {
  26. $this->disk = Storage::disk('s3');
  27. }
  28. /**
  29. * Upload logo and manage client sub-folder
  30. *
  31. * @param UploadedFile $logoFile
  32. * @param mixed $azienda
  33. * @return string
  34. * @throws Exception
  35. */
  36. public function uploadLogo(UploadedFile $logoFile, $azienda): string
  37. {
  38. try {
  39. $currentClient = session('currentClient', 'default');
  40. if (!$currentClient) {
  41. throw new Exception('No current client found in session');
  42. }
  43. $this->validateLogoFile($logoFile);
  44. $this->ensureClientFolderExists($currentClient);
  45. $this->deleteExistingLogo($currentClient);
  46. $logoPath = $this->uploadNewLogo($logoFile, $currentClient);
  47. $azienda->logo = $logoPath;
  48. $azienda->save();
  49. Log::info("Logo uploaded successfully", [
  50. 'client' => $currentClient,
  51. 'path' => $logoPath,
  52. 'azienda_id' => $azienda->id ?? null
  53. ]);
  54. return $logoPath;
  55. } catch (Exception $e) {
  56. Log::error('Error uploading logo', [
  57. 'message' => $e->getMessage(),
  58. 'client' => session('currentClient'),
  59. 'azienda_id' => $azienda->id ?? null
  60. ]);
  61. throw $e;
  62. }
  63. }
  64. /**
  65. * Validate the uploaded logo file
  66. *
  67. * @param UploadedFile $logoFile
  68. * @throws Exception
  69. */
  70. private function validateLogoFile(UploadedFile $logoFile): void
  71. {
  72. // Check if file is valid
  73. if (!$logoFile->isValid()) {
  74. throw new Exception('Invalid file upload');
  75. }
  76. // Check file size
  77. if ($logoFile->getSize() > (self::MAX_FILE_SIZE * 1024)) {
  78. throw new Exception('File size exceeds maximum allowed size of ' . self::MAX_FILE_SIZE . 'KB');
  79. }
  80. // Check file extension
  81. $extension = strtolower($logoFile->getClientOriginalExtension());
  82. if (!in_array($extension, self::ALLOWED_EXTENSIONS)) {
  83. throw new Exception('File type not allowed. Allowed types: ' . implode(', ', self::ALLOWED_EXTENSIONS));
  84. }
  85. // Check mime type
  86. $mimeType = $logoFile->getMimeType();
  87. $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  88. if (!in_array($mimeType, $allowedMimeTypes)) {
  89. throw new Exception('Invalid file type');
  90. }
  91. }
  92. /**
  93. * Ensure client folder exists in the bucket
  94. *
  95. * @param string $clientName
  96. * @throws Exception
  97. */
  98. private function ensureClientFolderExists(string $clientName): void
  99. {
  100. try {
  101. $files = $this->disk->files($clientName);
  102. if (empty($files)) {
  103. $placeholderPath = $clientName . '/.gitkeep';
  104. $this->disk->put($placeholderPath, '');
  105. Log::info("Created client folder", ['client' => $clientName]);
  106. }
  107. } catch (Exception $e) {
  108. Log::error("Error creating client folder", [
  109. 'client' => $clientName,
  110. 'error' => $e->getMessage()
  111. ]);
  112. throw new Exception("Failed to create client folder: " . $e->getMessage());
  113. }
  114. }
  115. /**
  116. * Delete all existing logo files for the client
  117. *
  118. * @param string $clientName
  119. */
  120. private function deleteExistingLogo(string $clientName): void
  121. {
  122. try {
  123. foreach (self::ALLOWED_EXTENSIONS as $extension) {
  124. $logoPath = $clientName . '/logo.' . $extension;
  125. if ($this->disk->exists($logoPath)) {
  126. $this->disk->delete($logoPath);
  127. Log::info("Deleted existing logo", [
  128. 'client' => $clientName,
  129. 'file' => "logo.{$extension}"
  130. ]);
  131. }
  132. }
  133. } catch (Exception $e) {
  134. Log::warning("Error deleting existing logo", [
  135. 'client' => $clientName,
  136. 'error' => $e->getMessage()
  137. ]);
  138. }
  139. }
  140. /**
  141. * Upload the new logo file
  142. *
  143. * @param UploadedFile $logoFile
  144. * @param string $clientName
  145. * @return string
  146. * @throws Exception
  147. */
  148. private function uploadNewLogo(UploadedFile $logoFile, string $clientName): string
  149. {
  150. try {
  151. $extension = strtolower($logoFile->getClientOriginalExtension());
  152. $fileName = 'logo.' . $extension;
  153. $logoPath = $this->disk->putFileAs(
  154. $clientName,
  155. $logoFile,
  156. $fileName,
  157. 'private'
  158. );
  159. if (!$logoPath) {
  160. throw new Exception('Failed to upload file to storage');
  161. }
  162. Log::info("Logo file uploaded", [
  163. 'client' => $clientName,
  164. 'path' => $logoPath,
  165. 'size' => $logoFile->getSize()
  166. ]);
  167. return $logoPath;
  168. } catch (Exception $e) {
  169. Log::error("Error uploading logo file", [
  170. 'client' => $clientName,
  171. 'error' => $e->getMessage()
  172. ]);
  173. throw new Exception("Failed to upload logo: " . $e->getMessage());
  174. }
  175. }
  176. /**
  177. * Get a temporary URL for the logo
  178. *
  179. * @param mixed $azienda
  180. * @param string $expiresIn
  181. * @return string|null
  182. */
  183. public function getLogoUrl($azienda, string $expiresIn = '+1 hour'): ?string
  184. {
  185. if (!$azienda->logo) {
  186. return null;
  187. }
  188. try {
  189. if (!$this->disk->exists($azienda->logo)) {
  190. Log::warning("Logo file not found", ['path' => $azienda->logo]);
  191. return null;
  192. }
  193. return $this->disk->temporaryUrl($azienda->logo, now()->add($expiresIn));
  194. } catch (Exception $e) {
  195. Log::error("Error generating logo URL", [
  196. 'path' => $azienda->logo,
  197. 'error' => $e->getMessage()
  198. ]);
  199. return null;
  200. }
  201. }
  202. /**
  203. * Check if logo file exists
  204. *
  205. * @param mixed $azienda
  206. * @return bool
  207. */
  208. public function logoExists($azienda): bool
  209. {
  210. if (!$azienda->logo) {
  211. return false;
  212. }
  213. return $this->disk->exists($azienda->logo);
  214. }
  215. /**
  216. * Delete logo file and update database
  217. *
  218. * @param mixed $azienda
  219. * @return bool
  220. */
  221. public function deleteLogo($azienda): bool
  222. {
  223. try {
  224. if ($azienda->logo && $this->disk->exists($azienda->logo)) {
  225. $this->disk->delete($azienda->logo);
  226. Log::info("Logo deleted", [
  227. 'path' => $azienda->logo,
  228. 'azienda_id' => $azienda->id ?? null
  229. ]);
  230. $azienda->logo = null;
  231. $azienda->save();
  232. return true;
  233. }
  234. return false;
  235. } catch (Exception $e) {
  236. Log::error("Error deleting logo", [
  237. 'path' => $azienda->logo ?? 'unknown',
  238. 'error' => $e->getMessage()
  239. ]);
  240. return false;
  241. }
  242. }
  243. /**
  244. * Get logo file information
  245. *
  246. * @param mixed $azienda
  247. * @return array|null
  248. */
  249. public function getLogoInfo($azienda): ?array
  250. {
  251. if (!$azienda->logo || !$this->disk->exists($azienda->logo)) {
  252. return null;
  253. }
  254. try {
  255. return [
  256. 'path' => $azienda->logo,
  257. 'size' => $this->disk->size($azienda->logo),
  258. 'last_modified' => $this->disk->lastModified($azienda->logo),
  259. 'url' => $this->getLogoUrl($azienda),
  260. 'exists' => true
  261. ];
  262. } catch (Exception $e) {
  263. Log::error("Error getting logo info", [
  264. 'path' => $azienda->logo,
  265. 'error' => $e->getMessage()
  266. ]);
  267. return null;
  268. }
  269. }
  270. /**
  271. * List all logos for a client
  272. *
  273. * @param string|null $clientName
  274. * @return array
  275. */
  276. public function listClientLogos(?string $clientName = null): array
  277. {
  278. $clientName = $clientName ?? session('currentClient');
  279. if (!$clientName) {
  280. return [];
  281. }
  282. try {
  283. $files = $this->disk->files($clientName);
  284. return array_filter($files, function($file) {
  285. $filename = basename($file);
  286. return strpos($filename, 'logo.') === 0;
  287. });
  288. } catch (Exception $e) {
  289. Log::error("Error listing client logos", [
  290. 'client' => $clientName,
  291. 'error' => $e->getMessage()
  292. ]);
  293. return [];
  294. }
  295. }
  296. }