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.

100 lines
2.7 KiB

2 years ago
2 years ago
2 years ago
  1. <?php namespace WpsMcloud\Actions\Convert;
  2. use WpsMcloud\Support\Http;
  3. use WpsMcloud\Support\Counters;
  4. use WpsMcloud\Actions\Convert;
  5. use WpsMcloud\Models\PostAttachment;
  6. class ReplacerService
  7. {
  8. const S3_ACL = 'public-read';
  9. private string $uploadsDirBaseUrl;
  10. private string $mcloudEndPoint;
  11. private string $bucket;
  12. private string $mcloudBaseUrl;
  13. public function __construct()
  14. {
  15. $this->uploadsDirBaseUrl = trailingslashit(wp_get_upload_dir()['baseurl']);
  16. $this->mcloudEndPoint = trailingslashit(get_option('mcloud-storage-s3-endpoint'));
  17. $this->bucket = get_option('mcloud-storage-s3-bucket');
  18. $this->mcloudBaseUrl = trailingslashit( $this->getMcloudEndPoint() . $this->bucket);
  19. }
  20. public function processImage(PostAttachment $post): void
  21. {
  22. if (!Http::fileExists($post->getUrl())) {
  23. $post->setFlaggedAs404();
  24. echo sprintf('Not found image %d: %s', $post->getId(), $post->getUrl());
  25. Counters::$imagesNotFound++;
  26. return;
  27. }
  28. $postAttachmentReplacer = new Convert\Replacer\PostAttachmentReplacer($post, $this);
  29. $meta = $post->getMeta();
  30. $meta['file'] = $postAttachmentReplacer->getKey();
  31. $meta['s3'] = $postAttachmentReplacer->getGeneralS3Info();
  32. if (array_key_exists('sizes', $meta) && is_array($meta['sizes'])) {
  33. $newSizes = [];
  34. foreach ($meta['sizes'] as $size => $sizeData) {
  35. $sizeFilename = $sizeData['file'];
  36. $localSizeUrl = $postAttachmentReplacer->getLocalPostBaseUrl() . $sizeFilename;
  37. if (!Http::fileExists($localSizeUrl)) {
  38. echo sprintf(
  39. 'Not found size "%s" image %d: %s',
  40. $sizeFilename,
  41. $post->getId(),
  42. $localSizeUrl
  43. ) . PHP_EOL;
  44. Counters::$imagesNotFound++;
  45. continue;
  46. }
  47. $sizeData['s3'] = $postAttachmentReplacer->getSizeS3Info($sizeFilename);
  48. $newSizes[$size] = $sizeData;
  49. }
  50. $meta['sizes'] = $newSizes;
  51. }
  52. $post->setAttachmentMetaData($meta);
  53. Counters::$processedImages++;
  54. }
  55. public function getUploadsDirBaseUrl(): string
  56. {
  57. return $this->uploadsDirBaseUrl;
  58. }
  59. public function getMcloudEndPoint(): string
  60. {
  61. return $this->mcloudEndPoint;
  62. }
  63. public function getBucket(): string
  64. {
  65. return $this->bucket;
  66. }
  67. public function getMcloudBaseUrl(): string
  68. {
  69. return $this->mcloudBaseUrl;
  70. }
  71. }