Skip to content

Commit

Permalink
Add product image sync plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
davidwindell committed Dec 8, 2021
1 parent 8e7d429 commit afdb58c
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
66 changes: 66 additions & 0 deletions Plugin/Catalog/Product/Image.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace AuroraExtensions\GoogleCloudStorage\Plugin\Catalog\Product;

use AuroraExtensions\GoogleCloudStorage\Model\File\Storage;
use Magento\Catalog\Model\Product\Image as ProductImage;
use Magento\Catalog\Model\Product\Media\Config;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\WriteInterface;
use Magento\Framework\App\Filesystem\DirectoryList;

class Image
{
/**
* @var Storage\BucketFactory
*/
protected $storageFactory;

/**
* @var WriteInterface
*/
protected $mediaDirectory;

/**
* @var Config
*/
protected $mediaConfig;

public function __construct(
Filesystem $filesystem,
Config $mediaConfig,
Storage\BucketFactory $storageFactory
) {
$this->mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->mediaConfig = $mediaConfig;
$this->storageFactory = $storageFactory;
}

public function beforeSetBaseFile(ProductImage $image, $file)
{
$relativeFileName = $this->mediaConfig->getBaseMediaPath() . $file;

if ($this->mediaDirectory->isFile($relativeFileName)) {
return;
}

/** @var $storage Storage\Bucket */
$storage = $this->storageFactory->create();
try {
$storage->loadByFilename($relativeFileName);
} catch (\Exception $e) {
}
if ($storage->getId()) {
/** @var WriteInterface $file */
$file = $this->mediaDirectory->openFile($relativeFileName, 'w');
try {
$file->lock();
$file->write($storage->getContent());
$file->unlock();
$file->close();
} catch (FileSystemException $e) {
$file->close();
}
}
}
}
5 changes: 5 additions & 0 deletions etc/di.xml
Original file line number Diff line number Diff line change
Expand Up @@ -110,4 +110,9 @@
type="AuroraExtensions\GoogleCloudStorage\Plugin\MediaStorage\Config\SynchronizeStorageParams"
sortOrder="10"/>
</type>
<type name="Magento\Catalog\Model\Product\Image">
<plugin name="googlecloudstorage_catalog_product_image"
type="AuroraExtensions\GoogleCloudStorage\Plugin\Catalog\Product\Image"
sortOrder="10"/>
</type>
</config>

0 comments on commit afdb58c

Please sign in to comment.