ImageProvider.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\ProductAlert\Block\Product;
  7. use Magento\Store\Model\App\Emulation;
  8. use Magento\Catalog\Block\Product\ImageBuilder;
  9. use Magento\Catalog\Model\Product;
  10. use Magento\Store\Model\StoreManagerInterface;
  11. use Magento\Framework\App\Area;
  12. use Magento\Catalog\Block\Product\Image;
  13. /**
  14. * Provides product image to be used in the Product Alert Email.
  15. */
  16. class ImageProvider
  17. {
  18. /**
  19. * @var ImageBuilder
  20. */
  21. private $imageBuilder;
  22. /**
  23. * @var StoreManagerInterface
  24. */
  25. private $storeManager;
  26. /**
  27. * @var Emulation
  28. */
  29. private $appEmulation;
  30. /**
  31. * @param ImageBuilder $imageBuilder
  32. * @param StoreManagerInterface $storeManager
  33. * @param Emulation $appEmulation
  34. */
  35. public function __construct(
  36. ImageBuilder $imageBuilder,
  37. StoreManagerInterface $storeManager,
  38. Emulation $appEmulation
  39. ) {
  40. $this->imageBuilder = $imageBuilder;
  41. $this->storeManager = $storeManager;
  42. $this->appEmulation = $appEmulation;
  43. }
  44. /**
  45. * @param Product $product
  46. * @param string $imageId
  47. * @param array $attributes
  48. * @return Image
  49. * @throws \Exception
  50. */
  51. public function getImage(Product $product, $imageId, $attributes = [])
  52. {
  53. $storeId = $this->storeManager->getStore()->getId();
  54. $this->appEmulation->startEnvironmentEmulation($storeId, Area::AREA_FRONTEND, true);
  55. try {
  56. $image = $this->imageBuilder->create($product, $imageId, $attributes);
  57. } catch (\Exception $exception) {
  58. $this->appEmulation->stopEnvironmentEmulation();
  59. throw $exception;
  60. }
  61. $this->appEmulation->stopEnvironmentEmulation();
  62. return $image;
  63. }
  64. }