Skip to content
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

Remove media gallery assets metadata when a directory removed #26015

Merged
Merged
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);

namespace Magento\MediaGallery\Model\Asset\Command;

use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\Exception\CouldNotDeleteException;
use Magento\Framework\Exception\LocalizedException;
use Magento\MediaGalleryApi\Model\Asset\Command\DeleteByDirectoryPathInterface;
use Psr\Log\LoggerInterface;

/**
* Class DeleteByDirectoryPath
*
* Remove asset(s) that correspond the provided directory path
*/
class DeleteByDirectoryPath implements DeleteByDirectoryPathInterface
{
private const TABLE_MEDIA_GALLERY_ASSET = 'media_gallery_asset';

private const MEDIA_GALLERY_ASSET_PATH = 'path';

/**
* @var ResourceConnection
*/
private $resourceConnection;

/**
* @var LoggerInterface
*/
private $logger;

/**
* DeleteById constructor.
*
* @param ResourceConnection $resourceConnection
* @param LoggerInterface $logger
*/
public function __construct(
ResourceConnection $resourceConnection,
LoggerInterface $logger
) {
$this->resourceConnection = $resourceConnection;
$this->logger = $logger;
}

/**
* Delete media asset(s) by path
*
* @param string $directoryPath
*
* @return void
* @throws CouldNotDeleteException
*/
public function execute(string $directoryPath): void
{
try {
$this->validateDirectoryPath($directoryPath);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

validateDirectoryPath throws a LocalizedException. I don't think it's necessary to recapture that exception, I propose to move the call out of try-catch block (also it may be good to change the LocalizedException to more specific CouldNotDeleteException in validateDirectoryPath)


// Make sure that the path has a trailing slash
$directoryPath = rtrim($directoryPath, '/') . '/';

/** @var AdapterInterface $connection */
$connection = $this->resourceConnection->getConnection();
$tableName = $this->resourceConnection->getTableName(self::TABLE_MEDIA_GALLERY_ASSET);
$connection->delete($tableName, [self::MEDIA_GALLERY_ASSET_PATH . ' LIKE ?' => $directoryPath . '%']);
} catch (\Exception $exception) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Import? :-)

$this->logger->critical($exception);
$message = __(
'Could not delete media assets by path %path: %error',
['path' => $directoryPath, 'error' => $exception->getMessage()]
);
throw new CouldNotDeleteException($message, $exception);
}
}

/**
* Validate the directory path
*
* @param string $directoryPath
* @throws LocalizedException
*/
private function validateDirectoryPath(string $directoryPath): void
{
if (!$directoryPath || trim($directoryPath) === '') {
throw new LocalizedException(__('Cannot remove assets, the directory path does not exist'));
}
}
}
34 changes: 32 additions & 2 deletions app/code/Magento/MediaGallery/Plugin/Wysiwyg/Images/Storage.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@

namespace Magento\MediaGallery\Plugin\Wysiwyg\Images;

use Magento\MediaGalleryApi\Model\Asset\Command\DeleteByDirectoryPathInterface;
use Magento\MediaGalleryApi\Model\Asset\Command\GetByPathInterface;
use Magento\MediaGalleryApi\Model\Asset\Command\DeleteByPathInterface;
use Magento\Cms\Model\Wysiwyg\Images\Storage as StorageSubject;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem;
use Magento\Framework\Exception\ValidatorException;
use Psr\Log\LoggerInterface;

/**
Expand All @@ -31,6 +31,11 @@ class Storage
*/
private $deleteMediaAssetByPath;

/**
* @var DeleteByDirectoryPathInterface
*/
private $deleteMediAssetByDirectoryPath;

/**
* @var Filesystem
*/
Expand All @@ -46,17 +51,20 @@ class Storage
*
* @param GetByPathInterface $getMediaAssetByPath
* @param DeleteByPathInterface $deleteMediaAssetByPath
* @param DeleteByDirectoryPathInterface $deleteByDirectoryPath
* @param Filesystem $filesystem
* @param LoggerInterface $logger
*/
public function __construct(
GetByPathInterface $getMediaAssetByPath,
DeleteByPathInterface $deleteMediaAssetByPath,
DeleteByDirectoryPathInterface $deleteByDirectoryPath,
Filesystem $filesystem,
LoggerInterface $logger
) {
$this->getMediaAssetByPath = $getMediaAssetByPath;
$this->deleteMediaAssetByPath = $deleteMediaAssetByPath;
$this->deleteMediAssetByDirectoryPath = $deleteByDirectoryPath;
$this->filesystem = $filesystem;
$this->logger = $logger;
}
Expand All @@ -69,7 +77,6 @@ public function __construct(
* @param string $target
*
* @return StorageSubject
* @throws ValidatorException
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
Expand All @@ -92,4 +99,27 @@ public function afterDeleteFile(StorageSubject $subject, StorageSubject $result,

return $result;
}

/**
* Delete media data after the folder delete action from Wysiwyg
*
* @param StorageSubject $subject
* @param mixed $result
* @param string $path
*
* @return null
*
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterDeleteDirectory(StorageSubject $subject, $result, $path)
{
if (!is_string($path)) {
return $result;
}

$relativePath = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA)->getRelativePath($path);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getRelativePath throws ValidatorException. I think it should be logged without interrupting the code execution.

Also, it looks like getRelativePath will return the original passed path if an incorrect path was provided, so I'd check if the path exists in media directory not to remove assets if the StorageSubject provided an incorrect path for some reason

$this->deleteMediAssetByDirectoryPath->execute($relativePath);

return $result;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);

namespace Magento\MediaGallery\Test\Unit\Model\Asset\Command;

use Magento\MediaGallery\Model\Asset\Command\DeleteByDirectoryPath;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\Exception\CouldNotDeleteException;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Magento\Framework\TestFramework\Unit\Helper\ObjectManager;
use Psr\Log\LoggerInterface;

/**
* Test the DeleteByDirectoryPath command model
*/
class DeleteByDirectoryPathTest extends TestCase
{
private const TABLE_NAME = 'media_gallery_asset';
private const DIRECTORY_PATH = 'test-directory-path/';

/**
* @var ResourceConnection|MockObject
*/
private $resourceConnection;

/**
* @var DeleteByDirectoryPath
*/
private $deleteMediaAssetByDirectoryPath;

/**
* @var AdapterInterface|MockObject
*/
private $adapter;

/**
* @var LoggerInterface|MockObject
*/
private $logger;

/**
* Initialize basic test class mocks
*/
protected function setUp(): void
{
$this->logger = $this->createMock(LoggerInterface::class);
$this->resourceConnection = $this->createMock(ResourceConnection::class);

$this->deleteMediaAssetByDirectoryPath = (new ObjectManager($this))->getObject(
DeleteByDirectoryPath::class,
[
'resourceConnection' => $this->resourceConnection,
'logger' => $this->logger,
]
);

$this->adapter = $this->createMock(AdapterInterface::class);
}

/**
* Test delete media asset by path command
*
* @param string $directoryPath
* @throws CouldNotDeleteException
* @dataProvider directoryPathDataProvider
*/
public function testDeleteByDirectoryPath(string $directoryPath): void
{
if (!empty($directoryPath)) {
$this->resourceConnection->expects($this->once())
->method('getConnection')
->willReturn($this->adapter);
$this->resourceConnection->expects($this->once())
->method('getTableName')
->with(self::TABLE_NAME)
->willReturn('prefix_' . self::TABLE_NAME);
$this->adapter->expects($this->once())
->method('delete')
->with('prefix_' . self::TABLE_NAME, ['path LIKE ?' => self::DIRECTORY_PATH . '%']);
} else {
self::expectException('\Magento\Framework\Exception\CouldNotDeleteException');
}

$this->deleteMediaAssetByDirectoryPath->execute($directoryPath);
}

/**
* Data provider for directory path
*
* @return array
*/
public function directoryPathDataProvider(): array
{
return [
'Existing path' => [self::DIRECTORY_PATH],
'Empty path' => ['']
];
}
}
1 change: 1 addition & 0 deletions app/code/Magento/MediaGallery/etc/di.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<preference for="Magento\MediaGalleryApi\Model\Asset\Command\SaveInterface" type="Magento\MediaGallery\Model\Asset\Command\Save"/>
<preference for="Magento\MediaGalleryApi\Model\Asset\Command\GetByPathInterface" type="Magento\MediaGallery\Model\Asset\Command\GetByPath"/>
<preference for="Magento\MediaGalleryApi\Model\Asset\Command\DeleteByPathInterface" type="Magento\MediaGallery\Model\Asset\Command\DeleteByPath"/>
<preference for="Magento\MediaGalleryApi\Model\Asset\Command\DeleteByDirectoryPathInterface" type="Magento\MediaGallery\Model\Asset\Command\DeleteByDirectoryPath"/>

<preference for="Magento\MediaGalleryApi\Model\Keyword\Command\GetAssetKeywordsInterface" type="Magento\MediaGallery\Model\Keyword\Command\GetAssetKeywords"/>
<preference for="Magento\MediaGalleryApi\Model\Keyword\Command\SaveAssetKeywordsInterface" type="Magento\MediaGallery\Model\Keyword\Command\SaveAssetKeywords"/>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

declare(strict_types=1);

namespace Magento\MediaGalleryApi\Model\Asset\Command;

/**
* A command represents the media gallery assets delete action. A media gallery asset is filtered by directory
* path value.
*/
interface DeleteByDirectoryPathInterface
{
/**
* Delete media assets by directory path
*
* @param string $directoryPath
*
* @return void
*/
public function execute(string $directoryPath): void;
}