Skip to content

Refactor moveFileFromTmp to not use a static method call #27581

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 44 additions & 51 deletions app/code/Magento/Catalog/Model/ImageUploader.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,114 +5,116 @@
*/
namespace Magento\Catalog\Model;

use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\File\Uploader;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\File\Name;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\WriteInterface;
use Magento\MediaStorage\Helper\File\Storage\Database;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Magento\Store\Model\StoreManagerInterface;
use Psr\Log\LoggerInterface;

/**
* Catalog image uploader
*/
class ImageUploader
{
/**
* Core file storage database
*
* @var \Magento\MediaStorage\Helper\File\Storage\Database
* @var Database
*/
protected $coreFileStorageDatabase;

/**
* Media directory object (writable).
*
* @var \Magento\Framework\Filesystem\Directory\WriteInterface
* @var WriteInterface
*/
protected $mediaDirectory;

/**
* Uploader factory
*
* @var \Magento\MediaStorage\Model\File\UploaderFactory
* @var UploaderFactory
*/
private $uploaderFactory;

/**
* Store manager
*
* @var \Magento\Store\Model\StoreManagerInterface
* @var StoreManagerInterface
*/
protected $storeManager;

/**
* @var \Psr\Log\LoggerInterface
* @var LoggerInterface
*/
protected $logger;

/**
* Base tmp path
*
* @var string
*/
protected $baseTmpPath;

/**
* Base path
*
* @var string
*/
protected $basePath;

/**
* Allowed extensions
*
* @var string
*/
protected $allowedExtensions;

/**
* List of allowed image mime types
*
* @var string[]
*/
private $allowedMimeTypes;

/**
* ImageUploader constructor
* @var Name
*/
private $fileNameLookup;

/**
* ImageUploader constructor.
*
* @param \Magento\MediaStorage\Helper\File\Storage\Database $coreFileStorageDatabase
* @param \Magento\Framework\Filesystem $filesystem
* @param \Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Psr\Log\LoggerInterface $logger
* @param Database $coreFileStorageDatabase
* @param Filesystem $filesystem
* @param UploaderFactory $uploaderFactory
* @param StoreManagerInterface $storeManager
* @param LoggerInterface $logger
* @param string $baseTmpPath
* @param string $basePath
* @param string[] $allowedExtensions
* @param string[] $allowedMimeTypes
* @param Name|null $fileNameLookup
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
\Magento\MediaStorage\Helper\File\Storage\Database $coreFileStorageDatabase,
\Magento\Framework\Filesystem $filesystem,
\Magento\MediaStorage\Model\File\UploaderFactory $uploaderFactory,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Psr\Log\LoggerInterface $logger,
Database $coreFileStorageDatabase,
Filesystem $filesystem,
UploaderFactory $uploaderFactory,
StoreManagerInterface $storeManager,
LoggerInterface $logger,
$baseTmpPath,
$basePath,
$allowedExtensions,
$allowedMimeTypes = []
$allowedMimeTypes = [],
Name $fileNameLookup = null
) {
$this->coreFileStorageDatabase = $coreFileStorageDatabase;
$this->mediaDirectory = $filesystem->getDirectoryWrite(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
$this->mediaDirectory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->uploaderFactory = $uploaderFactory;
$this->storeManager = $storeManager;
$this->logger = $logger;
$this->baseTmpPath = $baseTmpPath;
$this->basePath = $basePath;
$this->allowedExtensions = $allowedExtensions;
$this->allowedMimeTypes = $allowedMimeTypes;
$this->fileNameLookup = $fileNameLookup ?? ObjectManager::getInstance()->get(Name::class);
}

/**
* Set base tmp path
*
* @param string $baseTmpPath
*
* @return void
*/
public function setBaseTmpPath($baseTmpPath)
Expand All @@ -124,7 +126,6 @@ public function setBaseTmpPath($baseTmpPath)
* Set base path
*
* @param string $basePath
*
* @return void
*/
public function setBasePath($basePath)
Expand All @@ -136,7 +137,6 @@ public function setBasePath($basePath)
* Set allowed extensions
*
* @param string[] $allowedExtensions
*
* @return void
*/
public function setAllowedExtensions($allowedExtensions)
Expand Down Expand Up @@ -179,7 +179,6 @@ public function getAllowedExtensions()
*
* @param string $path
* @param string $imageName
*
* @return string
*/
public function getFilePath($path, $imageName)
Expand All @@ -194,7 +193,7 @@ public function getFilePath($path, $imageName)
* @param bool $returnRelativePath
* @return string
*
* @throws \Magento\Framework\Exception\LocalizedException
* @throws LocalizedException
*/
public function moveFileFromTmp($imageName, $returnRelativePath = false)
{
Expand All @@ -203,7 +202,7 @@ public function moveFileFromTmp($imageName, $returnRelativePath = false)

$baseImagePath = $this->getFilePath(
$basePath,
Uploader::getNewFileName(
$this->fileNameLookup->getNewFileName(
$this->mediaDirectory->getAbsolutePath(
$this->getFilePath($basePath, $imageName)
)
Expand All @@ -222,10 +221,7 @@ public function moveFileFromTmp($imageName, $returnRelativePath = false)
);
} catch (\Exception $e) {
$this->logger->critical($e);
throw new \Magento\Framework\Exception\LocalizedException(
__('Something went wrong while saving the file(s).'),
$e
);
throw new LocalizedException(__('Something went wrong while saving the file(s).'), $e);
}

return $returnRelativePath ? $baseImagePath : $imageName;
Expand All @@ -235,10 +231,9 @@ public function moveFileFromTmp($imageName, $returnRelativePath = false)
* Checking file for save and save it to tmp dir
*
* @param string $fileId
*
* @return string[]
*
* @throws \Magento\Framework\Exception\LocalizedException
* @throws LocalizedException
*/
public function saveFileToTmpDir($fileId)
{
Expand All @@ -249,15 +244,13 @@ public function saveFileToTmpDir($fileId)
$uploader->setAllowedExtensions($this->getAllowedExtensions());
$uploader->setAllowRenameFiles(true);
if (!$uploader->checkMimeType($this->allowedMimeTypes)) {
throw new \Magento\Framework\Exception\LocalizedException(__('File validation failed.'));
throw new LocalizedException(__('File validation failed.'));
}
$result = $uploader->save($this->mediaDirectory->getAbsolutePath($baseTmpPath));
unset($result['path']);

if (!$result) {
throw new \Magento\Framework\Exception\LocalizedException(
__('File can not be saved to the destination folder.')
);
throw new LocalizedException(__('File can not be saved to the destination folder.'));
}

/**
Expand All @@ -277,7 +270,7 @@ public function saveFileToTmpDir($fileId)
$this->coreFileStorageDatabase->saveFile($relativePath);
} catch (\Exception $e) {
$this->logger->critical($e);
throw new \Magento\Framework\Exception\LocalizedException(
throw new LocalizedException(
__('Something went wrong while saving the file(s).'),
$e
);
Expand Down
64 changes: 64 additions & 0 deletions lib/internal/Magento/Framework/File/Name.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);

namespace Magento\Framework\File;

use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Validation\ValidationException;

/**
* Utility for generating a unique file name
*/
class Name
{
/**
* Get new file name if the given name is in use
*
* @param string $destinationFile
* @return string
*/
public function getNewFileName(string $destinationFile)
{
$fileInfo = $this->getPathInfo($destinationFile);
if ($this->fileExist($destinationFile)) {
$index = 1;
$baseName = $fileInfo['filename'] . '.' . $fileInfo['extension'];
while ($this->fileExist($fileInfo['dirname'] . '/' . $baseName)) {
$baseName = $fileInfo['filename'] . '_' . $index . '.' . $fileInfo['extension'];
$index++;
}
$destFileName = $baseName;
} else {
return $fileInfo['basename'];
}

return $destFileName;
}

/**
* Get the path information from a given file
*
* @param string $destinationFile
* @return string|string[]
*/
private function getPathInfo(string $destinationFile)
{
return pathinfo($destinationFile);
}

/**
* Check to see if a given file exists
*
* @param string $destinationFile
* @return bool
*/
private function fileExist(string $destinationFile)
{
return file_exists($destinationFile);
}
}
67 changes: 67 additions & 0 deletions lib/internal/Magento/Framework/Test/Unit/File/NameTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

namespace Magento\Framework\Test\Unit\File;

use Magento\Framework\File\Name;

class NameTest extends \PHPUnit\Framework\TestCase
{
/**
* @var string
*/
private $existingFilePath;

/**
* @var string
*/
private $nonExistingFilePath;

/**
* @var string
*/
private $multipleExistingFilePath;

/**
* @var Name
*/
private $name;

/**
* @inheritDoc
*/
protected function setUp(): void
{
$this->name = new Name();
$this->existingFilePath = __DIR__ . '/../_files/source.txt';
$this->multipleExistingFilePath = __DIR__ . '/../_files/name.txt';
$this->nonExistingFilePath = __DIR__ . '/../_files/file.txt';
}

/**
* @test
*/
public function testGetNewFileNameWhenOneFileExists()
{
$this->assertEquals('source_1.txt', $this->name->getNewFileName($this->existingFilePath));
}

/**
* @test
*/
public function testGetNewFileNameWhenTwoFileExists()
{
$this->assertEquals('name_2.txt', $this->name->getNewFileName($this->multipleExistingFilePath));
}

/**
* @test
*/
public function testGetNewFileNameWhenFileDoesNotExist()
{
$this->assertEquals('file.txt', $this->name->getNewFileName($this->nonExistingFilePath));
}
}
1 change: 1 addition & 0 deletions lib/internal/Magento/Framework/Test/Unit/_files/name.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
name
1 change: 1 addition & 0 deletions lib/internal/Magento/Framework/Test/Unit/_files/name_1.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
name_1