Skip to content

Commit

Permalink
Simple cache implementation for image hashes
Browse files Browse the repository at this point in the history
  • Loading branch information
elevinskii committed Mar 4, 2024
1 parent 6707c1c commit 7ea3d6a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 2 deletions.
12 changes: 10 additions & 2 deletions Model/Gallery/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

namespace Elevinskii\MediaStorage\Model\Gallery;

use Elevinskii\MediaStorage\Model\Gallery\Image\HashCache;
use Elevinskii\MediaStorage\Model\Gallery\Image\PathInfo;
use Elevinskii\MediaStorage\Model\Gallery\Image\PathInfoFactory;
use Magento\Catalog\Model\Product\Media\ConfigInterface as MediaConfig;
Expand All @@ -28,13 +29,15 @@ class Image implements ImageInterface
* @param PathInfoFactory $pathInfoFactory
* @param DirectoryList $directoryList
* @param MediaConfig $mediaConfig
* @param HashCache $hashCache
* @param string $catalogPath
*/
public function __construct(
private readonly DirectoryReaderFactory $directoryReaderFactory,
private readonly PathInfoFactory $pathInfoFactory,
private readonly DirectoryList $directoryList,
private readonly MediaConfig $mediaConfig,
private readonly HashCache $hashCache,
private readonly string $catalogPath
) {
}
Expand Down Expand Up @@ -72,9 +75,14 @@ public function getPathInfo(): PathInfo
public function getHash(): string
{
$absolutePath = $this->getAbsolutePath();
$hash = @hash_file(self::HASH_ALGORITHM, $absolutePath);

if ($hash === false) {
$hash = $this->hashCache->get($absolutePath);
if (!$hash) {
$hash = @hash_file(self::HASH_ALGORITHM, $absolutePath) ?: null;
$this->hashCache->set($absolutePath, $hash);
}

if (!$hash) {
throw new FileSystemException(
__('Cannot calculate hash for the image by path %1', [$absolutePath])
);
Expand Down
35 changes: 35 additions & 0 deletions Model/Gallery/Image/HashCache.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);

namespace Elevinskii\MediaStorage\Model\Gallery\Image;

class HashCache
{
/**
* @var array
*/
private array $cache = [];

/**
* Retrieve file hash by path
*
* @param string $path
* @return string|null
*/
public function get(string $path): ?string
{
return $this->cache[$path] ?? null;
}

/**
* Set file hash by path
*
* @return $this
*/
public function set(string $path, ?string $hash): self
{
$this->cache[$path] = $hash;

return $this;
}
}

0 comments on commit 7ea3d6a

Please sign in to comment.