You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
2.2KB

  1. <?php
  2. namespace common\helpers;
  3. class Image
  4. {
  5. const DIR_UPLOADS = 'uploads';
  6. const THUMBNAIL_SMALL = 'small';
  7. const THUMBNAIL_MEDIUM = 'medium';
  8. const THUMBNAIL_BIG = 'big';
  9. public static function getThumbnailSmall(string $filenameOriginal, bool $absoluteUrl = false)
  10. {
  11. return self::getThumbnail($filenameOriginal, self::THUMBNAIL_SMALL, $absoluteUrl);
  12. }
  13. public static function getThumbnailMedium(string $filenameOriginal, bool $absoluteUrl = false)
  14. {
  15. return self::getThumbnail($filenameOriginal, self::THUMBNAIL_MEDIUM, $absoluteUrl);
  16. }
  17. public static function getThumbnailBig(string $filenameOriginal, bool $absoluteUrl = false)
  18. {
  19. return self::getThumbnail($filenameOriginal, self::THUMBNAIL_BIG, $absoluteUrl);
  20. }
  21. public static function getThumbnail(string $filenameOriginal, string $thumbnail = self::THUMBNAIL_MEDIUM, bool $absoluteUrl = false)
  22. {
  23. $basePath = self::getBasePath($absoluteUrl);
  24. $thumbnailFilename = self::getThumbnailFilename($filenameOriginal, $thumbnail);
  25. $thumbnailPath = $basePath . $thumbnailFilename;
  26. $originalPath = $basePath . $filenameOriginal;
  27. $defaultImagePath = $basePath . 'default.jpg';
  28. if(self::isPhotoExist($thumbnailFilename)) {
  29. return $thumbnailPath;
  30. }
  31. if(self::isPhotoExist($filenameOriginal)) {
  32. return $originalPath;
  33. }
  34. return $defaultImagePath;
  35. }
  36. public static function getBasePath(bool $absoluteUrl = false): string
  37. {
  38. $absoluteUrlPrepend = '';
  39. if($absoluteUrl) {
  40. $absoluteUrlPrepend = \Yii::$app->urlManagerProducer->getHostInfo();
  41. }
  42. return $absoluteUrlPrepend . \Yii::$app->urlManagerProducer->baseUrl.'/'.self::DIR_UPLOADS.'/';
  43. }
  44. public static function getThumbnailFilename(string $filename, string $thumbnail = self::THUMBNAIL_MEDIUM)
  45. {
  46. $filenameArray = explode('.', $filename);
  47. return $filenameArray[0].'-'.$thumbnail.'.'.$filenameArray[1];
  48. }
  49. public static function isPhotoExist(string $filename): bool
  50. {
  51. return file_exists(\Yii::getAlias('@producer').'/web/'.self::DIR_UPLOADS.'/'.$filename);
  52. }
  53. }