From 5d0c97255f83c6aead003a420a8db803a7085b2d Mon Sep 17 00:00:00 2001 From: Lukasz Bajsarowicz Date: Mon, 16 Mar 2020 02:53:18 +0100 Subject: [PATCH 01/89] FIX #27299 AbstractController::resetRequest(), automatically setDispatched(false) before each AbstractController::dispatch() --- .../TestCase/AbstractController.php | 36 +++++++++++++------ .../Customer/Controller/AccountTest.php | 30 ++++++++-------- 2 files changed, 41 insertions(+), 25 deletions(-) diff --git a/dev/tests/integration/framework/Magento/TestFramework/TestCase/AbstractController.php b/dev/tests/integration/framework/Magento/TestFramework/TestCase/AbstractController.php index feb9eca0793a2..d2a6bb7da9abd 100644 --- a/dev/tests/integration/framework/Magento/TestFramework/TestCase/AbstractController.php +++ b/dev/tests/integration/framework/Magento/TestFramework/TestCase/AbstractController.php @@ -7,21 +7,25 @@ /** * Abstract class for the controller tests */ + namespace Magento\TestFramework\TestCase; +use Magento\Framework\App\RequestInterface; +use Magento\Framework\App\ResponseInterface; use Magento\Framework\Data\Form\FormKey; use Magento\Framework\Message\MessageInterface; use Magento\Framework\Stdlib\CookieManagerInterface; use Magento\Framework\View\Element\Message\InterpretationStrategyInterface; use Magento\Theme\Controller\Result\MessagePlugin; -use Magento\Framework\App\Request\Http as HttpRequest; -use Magento\Framework\App\Response\Http as HttpResponse; +use PHPUnit\Framework\TestCase; /** + * Set of methods useful for performing requests to Controllers. + * * @SuppressWarnings(PHPMD.NumberOfChildren) * @SuppressWarnings(PHPMD.CouplingBetweenObjects) */ -abstract class AbstractController extends \PHPUnit\Framework\TestCase +abstract class AbstractController extends TestCase { protected $_runCode = ''; @@ -30,12 +34,12 @@ abstract class AbstractController extends \PHPUnit\Framework\TestCase protected $_runOptions = []; /** - * @var \Magento\Framework\App\RequestInterface + * @var RequestInterface */ protected $_request; /** - * @var \Magento\Framework\App\ResponseInterface + * @var ResponseInterface */ protected $_response; @@ -103,8 +107,9 @@ protected function assertPostConditions() */ public function dispatch($uri) { - /** @var HttpRequest $request */ $request = $this->getRequest(); + + $request->setDispatched(false); $request->setRequestUri($uri); if ($request->isPost() && !array_key_exists('form_key', $request->getPost()) @@ -119,25 +124,36 @@ public function dispatch($uri) /** * Request getter * - * @return \Magento\Framework\App\RequestInterface|HttpRequest + * @return RequestInterface */ public function getRequest() { if (!$this->_request) { - $this->_request = $this->_objectManager->get(\Magento\Framework\App\RequestInterface::class); + $this->_request = $this->_objectManager->get(RequestInterface::class); } return $this->_request; } + /** + * Reset Request parameters + * + * @return void + */ + protected function resetRequest(): void + { + $this->_objectManager->removeSharedInstance(RequestInterface::class); + $this->_request = null; + } + /** * Response getter * - * @return \Magento\Framework\App\ResponseInterface|HttpResponse + * @return ResponseInterface */ public function getResponse() { if (!$this->_response) { - $this->_response = $this->_objectManager->get(\Magento\Framework\App\ResponseInterface::class); + $this->_response = $this->_objectManager->get(ResponseInterface::class); } return $this->_response; } diff --git a/dev/tests/integration/testsuite/Magento/Customer/Controller/AccountTest.php b/dev/tests/integration/testsuite/Magento/Customer/Controller/AccountTest.php index 9b0b53e11615f..a799c139545f4 100644 --- a/dev/tests/integration/testsuite/Magento/Customer/Controller/AccountTest.php +++ b/dev/tests/integration/testsuite/Magento/Customer/Controller/AccountTest.php @@ -188,14 +188,14 @@ public function testCreatepasswordActionInvalidToken() } /** - * @param int $customerId + * @param int $customerId * @param string|null $confirmation */ private function assertCustomerConfirmationEquals(int $customerId, string $confirmation = null) { /** @var \Magento\Customer\Model\Customer $customer */ $customer = Bootstrap::getObjectManager() - ->create(\Magento\Customer\Model\Customer::class)->load($customerId); + ->create(\Magento\Customer\Model\Customer::class)->load($customerId); $this->assertEquals($confirmation, $customer->getConfirmation()); } @@ -492,14 +492,14 @@ public function testChangePasswordEditPostAction() ->setMethod('POST') ->setPostValue( [ - 'form_key' => $this->_objectManager->get(FormKey::class)->getFormKey(), - 'firstname' => 'John', - 'lastname' => 'Doe', - 'email' => 'johndoe@email.com', - 'change_password' => 1, - 'change_email' => 1, + 'form_key' => $this->_objectManager->get(FormKey::class)->getFormKey(), + 'firstname' => 'John', + 'lastname' => 'Doe', + 'email' => 'johndoe@email.com', + 'change_password' => 1, + 'change_email' => 1, 'current_password' => 'password', - 'password' => 'new-Password1', + 'password' => 'new-Password1', 'password_confirmation' => 'new-Password1', ] ); @@ -645,6 +645,7 @@ public function testRegisterCustomerWithEmailConfirmation(): void /** @var CookieManagerInterface $cookieManager */ $cookieManager = $this->_objectManager->get(CookieManagerInterface::class); $cookieManager->deleteCookie(MessagePlugin::MESSAGES_COOKIES_NAME); + $this->_objectManager->removeSharedInstance(Http::class); $this->_objectManager->removeSharedInstance(Request::class); $this->_request = null; @@ -761,8 +762,9 @@ public function testResetPasswordWhenEmailChanged(): void $customer->setEmail($newEmail); $customerRepository->save($customer); - /* Goes through the link in a mail */ $this->resetRequest(); + + /* Goes through the link in a mail */ $this->getRequest() ->setParam('token', $token) ->setParam('id', $customerData->getId()); @@ -842,15 +844,13 @@ private function assertForgotPasswordEmailContent(string $token): void } /** - * Clear request object. - * - * @return void + * @inheritDoc */ - private function resetRequest(): void + protected function resetRequest(): void { $this->_objectManager->removeSharedInstance(Http::class); $this->_objectManager->removeSharedInstance(Request::class); - $this->_request = null; + parent::resetRequest(); } /** From ba8d3669a7b498759023dc9518e5339764e0170b Mon Sep 17 00:00:00 2001 From: Lukasz Bajsarowicz Date: Wed, 18 Mar 2020 12:31:42 +0100 Subject: [PATCH 02/89] Add Integration Test to cover consecutive calls. --- .../Adminhtml/ConsecutiveCallTest.php | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/ConsecutiveCallTest.php diff --git a/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/ConsecutiveCallTest.php b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/ConsecutiveCallTest.php new file mode 100644 index 0000000000000..aff706688dc9f --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/Backend/Controller/Adminhtml/ConsecutiveCallTest.php @@ -0,0 +1,25 @@ +dispatch('backend/admin/auth/login'); + $this->dispatch('backend/admin/auth/login'); + } +} From c12201ea7e461ec73f765b6db18d26988a83a9d8 Mon Sep 17 00:00:00 2001 From: Sergii Ivashchenko Date: Mon, 30 Mar 2020 12:31:22 +0100 Subject: [PATCH 03/89] Updated MediaGallery modules and marked as API --- .../Model/Asset/Command/GetById.php | 2 +- .../Model/Asset/Command/GetByPath.php | 6 +- .../Model/Directory/Command/CreateByPath.php | 59 ++++++++++ .../Model/Directory/Command/DeleteByPath.php | 58 ++++++++++ .../MediaGallery/Model/Directory/Excluded.php | 48 ++++++++ .../Model/File/Command/DeleteByAssetId.php | 74 +++++++++++++ .../Keyword/Command/GetAssetKeywords.php | 2 +- .../Unit/Model/Directory/ExcludedTest.php | 64 +++++++++++ .../File/Command/DeleteByAssetIdTest.php | 103 ++++++++++++++++++ app/code/Magento/MediaGallery/etc/di.xml | 14 +++ .../Api/Data/AssetInterface.php | 1 + .../Api/Data/KeywordInterface.php | 1 + .../DeleteByDirectoryPathInterface.php | 2 +- .../Asset/Command/DeleteByPathInterface.php | 2 +- .../Model/Asset/Command/GetByIdInterface.php | 2 +- .../Asset/Command/GetByPathInterface.php | 2 +- .../Model/Asset/Command/SaveInterface.php | 2 +- .../Model/DataExtractorInterface.php | 1 + .../Command/CreateByPathInterface.php | 24 ++++ .../Command/DeleteByPathInterface.php | 23 ++++ .../Model/Directory/ExcludedInterface.php | 23 ++++ .../File/Command/DeleteByAssetIdInterface.php | 24 ++++ .../Command/GetAssetKeywordsInterface.php | 2 +- .../Command/SaveAssetKeywordsInterface.php | 1 + 24 files changed, 528 insertions(+), 12 deletions(-) create mode 100644 app/code/Magento/MediaGallery/Model/Directory/Command/CreateByPath.php create mode 100644 app/code/Magento/MediaGallery/Model/Directory/Command/DeleteByPath.php create mode 100644 app/code/Magento/MediaGallery/Model/Directory/Excluded.php create mode 100644 app/code/Magento/MediaGallery/Model/File/Command/DeleteByAssetId.php create mode 100644 app/code/Magento/MediaGallery/Test/Unit/Model/Directory/ExcludedTest.php create mode 100644 app/code/Magento/MediaGallery/Test/Unit/Model/File/Command/DeleteByAssetIdTest.php create mode 100644 app/code/Magento/MediaGalleryApi/Model/Directory/Command/CreateByPathInterface.php create mode 100644 app/code/Magento/MediaGalleryApi/Model/Directory/Command/DeleteByPathInterface.php create mode 100644 app/code/Magento/MediaGalleryApi/Model/Directory/ExcludedInterface.php create mode 100644 app/code/Magento/MediaGalleryApi/Model/File/Command/DeleteByAssetIdInterface.php diff --git a/app/code/Magento/MediaGallery/Model/Asset/Command/GetById.php b/app/code/Magento/MediaGallery/Model/Asset/Command/GetById.php index 6be11610ac197..b6153c45dbf8c 100644 --- a/app/code/Magento/MediaGallery/Model/Asset/Command/GetById.php +++ b/app/code/Magento/MediaGallery/Model/Asset/Command/GetById.php @@ -28,7 +28,7 @@ class GetById implements GetByIdInterface private $resourceConnection; /** - * @var AssetInterface + * @var AssetInterfaceFactory */ private $assetFactory; diff --git a/app/code/Magento/MediaGallery/Model/Asset/Command/GetByPath.php b/app/code/Magento/MediaGallery/Model/Asset/Command/GetByPath.php index db8482d3399ba..fe5fcca6cb0de 100644 --- a/app/code/Magento/MediaGallery/Model/Asset/Command/GetByPath.php +++ b/app/code/Magento/MediaGallery/Model/Asset/Command/GetByPath.php @@ -30,7 +30,7 @@ class GetByPath implements GetByPathInterface private $resourceConnection; /** - * @var AssetInterface + * @var AssetInterfaceFactory */ private $mediaAssetFactory; @@ -78,9 +78,7 @@ public function execute(string $mediaFilePath): AssetInterface throw new NoSuchEntityException($message); } - $mediaAssets = $this->mediaAssetFactory->create(['data' => $data]); - - return $mediaAssets; + return $this->mediaAssetFactory->create(['data' => $data]); } catch (\Exception $exception) { $this->logger->critical($exception); $message = __('An error occurred during get media asset list: %1', $exception->getMessage()); diff --git a/app/code/Magento/MediaGallery/Model/Directory/Command/CreateByPath.php b/app/code/Magento/MediaGallery/Model/Directory/Command/CreateByPath.php new file mode 100644 index 0000000000000..6d0ea45aa02cd --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/Directory/Command/CreateByPath.php @@ -0,0 +1,59 @@ +logger = $logger; + $this->storage = $storage; + } + + /** + * Create new directory by provided path + * + * @param string $path + * @param string $name + * @throws CouldNotSaveException + */ + public function execute(string $path, string $name): void + { + try { + $this->storage->createDirectory($name, $this->storage->getCmsWysiwygImages()->getStorageRoot() . $path); + } catch (\Exception $exception) { + $this->logger->critical($exception); + $message = __('Failed to create the folder: %error', ['error' => $exception->getMessage()]); + throw new CouldNotSaveException($message, $exception); + } + } +} diff --git a/app/code/Magento/MediaGallery/Model/Directory/Command/DeleteByPath.php b/app/code/Magento/MediaGallery/Model/Directory/Command/DeleteByPath.php new file mode 100644 index 0000000000000..ee78216fafdaf --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/Directory/Command/DeleteByPath.php @@ -0,0 +1,58 @@ +logger = $logger; + $this->storage = $storage; + } + + /** + * Deletes the existing folder + * + * @param string $path + * @throws CouldNotDeleteException + */ + public function execute(string $path): void + { + try { + $this->storage->deleteDirectory($this->storage->getCmsWysiwygImages()->getStorageRoot() . $path); + } catch (\Exception $exception) { + $this->logger->critical($exception); + $message = __('Failed to delete the folder: %error', ['error' => $exception->getMessage()]); + throw new CouldNotDeleteException($message, $exception); + } + } +} diff --git a/app/code/Magento/MediaGallery/Model/Directory/Excluded.php b/app/code/Magento/MediaGallery/Model/Directory/Excluded.php new file mode 100644 index 0000000000000..ad8843da9e8c3 --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/Directory/Excluded.php @@ -0,0 +1,48 @@ +patterns = $patterns; + } + + /** + * Check if the path is excluded from displaying in the media gallery + * + * @param string $path + * @return bool + */ + public function isExcluded(string $path): bool + { + foreach ($this->patterns as $pattern) { + preg_match($pattern, $path, $result); + + if ($result) { + return true; + } + } + return false; + } +} diff --git a/app/code/Magento/MediaGallery/Model/File/Command/DeleteByAssetId.php b/app/code/Magento/MediaGallery/Model/File/Command/DeleteByAssetId.php new file mode 100644 index 0000000000000..177c67280580c --- /dev/null +++ b/app/code/Magento/MediaGallery/Model/File/Command/DeleteByAssetId.php @@ -0,0 +1,74 @@ +getAssetById = $getAssetById; + $this->imagesStorage = $imagesStorage; + $this->filesystem = $filesystem; + } + + /** + * Delete image by asset ID + * + * @param int $assetId + * + * @return void + * + * @throws LocalizedException + */ + public function execute(int $assetId): void + { + $mediaFilePath = $this->getAssetById->execute($assetId)->getPath(); + $mediaDirectory = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA); + + if (!$mediaDirectory->isFile($mediaFilePath)) { + throw new LocalizedException(__('File "%1" does not exist in media directory.', $mediaFilePath)); + } + + $this->imagesStorage->deleteFile($mediaDirectory->getAbsolutePath() . $mediaFilePath); + } +} diff --git a/app/code/Magento/MediaGallery/Model/Keyword/Command/GetAssetKeywords.php b/app/code/Magento/MediaGallery/Model/Keyword/Command/GetAssetKeywords.php index 5b826a26e937d..ae61867884c7a 100644 --- a/app/code/Magento/MediaGallery/Model/Keyword/Command/GetAssetKeywords.php +++ b/app/code/Magento/MediaGallery/Model/Keyword/Command/GetAssetKeywords.php @@ -59,7 +59,7 @@ public function __construct( * * @param int $assetId * - * @return KeywordInterface[]|[] + * @return KeywordInterface[] * @throws IntegrationException */ public function execute(int $assetId): array diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/Directory/ExcludedTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/Directory/ExcludedTest.php new file mode 100644 index 0000000000000..e468bee7cc5d7 --- /dev/null +++ b/app/code/Magento/MediaGallery/Test/Unit/Model/Directory/ExcludedTest.php @@ -0,0 +1,64 @@ +object = (new ObjectManager($this))->getObject( + Excluded::class, + [ + 'patterns' => [ + 'tmp' => '/pub\/media\/tmp/', + 'captcha' => '/pub\/media\/captcha/' + ] + ] + ); + } + + /** + * Test is directory path excluded + * + * @param string $path + * @param bool $isExcluded + * @dataProvider pathsProvider + */ + public function testIsExcluded(string $path, bool $isExcluded): void + { + $this->assertEquals($isExcluded, $this->object->isExcluded($path)); + } + + /** + * Data provider for testIsExcluded + * + * @return array + */ + public function pathsProvider() + { + return [ + ['/var/www/html/pub/media/tmp/somedir', true], + ['/var/www/html/pub/media/wysiwyg/somedir', false] + ]; + } +} diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/File/Command/DeleteByAssetIdTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/File/Command/DeleteByAssetIdTest.php new file mode 100644 index 0000000000000..de5b5d42c71e3 --- /dev/null +++ b/app/code/Magento/MediaGallery/Test/Unit/Model/File/Command/DeleteByAssetIdTest.php @@ -0,0 +1,103 @@ +filesystem = $this->createMock(Filesystem::class); + $this->storage = $this->createMock(Storage::class); + $this->getById = $this->createMock(GetByIdInterface::class); + + $this->object = (new ObjectManager($this))->getObject( + DeleteByAssetId::class, + [ + 'filesystem' => $this->filesystem, + 'imagesStorage' => $this->storage, + 'getAssetById' => $this->getById + ] + ); + } + + /** + * Test delete file by asset id + */ + public function testExecute(): void + { + $assetId = 42; + $path = '/file1.jpg'; + $absoluteMediaPath = '/var/www/html/pub/media'; + + $asset = $this->createMock(AssetInterface::class); + $asset->expects($this->once()) + ->method('getPath') + ->willReturn($path); + + $this->getById->expects($this->once()) + ->method('execute') + ->with($assetId) + ->willReturn($asset); + + $directory = $this->createMock(Read::class); + $directory->expects($this->once()) + ->method('isFile') + ->willReturn(true); + $directory->expects($this->once()) + ->method('getAbsolutePath') + ->willReturn($absoluteMediaPath); + + $this->filesystem->expects($this->once()) + ->method('getDirectoryRead') + ->with(DirectoryList::MEDIA) + ->willReturn($directory); + + $this->storage->expects($this->once()) + ->method('deleteFile') + ->with($absoluteMediaPath . $path); + + $this->object->execute($assetId); + } +} diff --git a/app/code/Magento/MediaGallery/etc/di.xml b/app/code/Magento/MediaGallery/etc/di.xml index 24ed42b2b06dd..ccc8ce28a733d 100644 --- a/app/code/Magento/MediaGallery/etc/di.xml +++ b/app/code/Magento/MediaGallery/etc/di.xml @@ -29,4 +29,18 @@ + + + + /pub\/media\/captcha/ + /pub\/media\/catalog\/product/ + /pub\/media\/customer/ + /pub\/media\/downloadable/ + /pub\/media\/import/ + /pub\/media\/theme/ + /pub\/media\/theme_customization/ + /pub\/media\/tmp/ + + + diff --git a/app/code/Magento/MediaGalleryApi/Api/Data/AssetInterface.php b/app/code/Magento/MediaGalleryApi/Api/Data/AssetInterface.php index 0f4b78a6dc603..7cd94f90a60a0 100644 --- a/app/code/Magento/MediaGalleryApi/Api/Data/AssetInterface.php +++ b/app/code/Magento/MediaGalleryApi/Api/Data/AssetInterface.php @@ -13,6 +13,7 @@ /** * Represents a media gallery asset which contains information about a media asset entity such * as path to the media storage, media asset title and its content type, etc. + * @api */ interface AssetInterface extends ExtensibleDataInterface { diff --git a/app/code/Magento/MediaGalleryApi/Api/Data/KeywordInterface.php b/app/code/Magento/MediaGalleryApi/Api/Data/KeywordInterface.php index ae3b7dbd76291..7f19e53d6e380 100644 --- a/app/code/Magento/MediaGalleryApi/Api/Data/KeywordInterface.php +++ b/app/code/Magento/MediaGalleryApi/Api/Data/KeywordInterface.php @@ -12,6 +12,7 @@ /** * Represents a media gallery keyword. This object contains information about a media asset keyword entity. + * @api */ interface KeywordInterface extends ExtensibleDataInterface { diff --git a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/DeleteByDirectoryPathInterface.php b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/DeleteByDirectoryPathInterface.php index e55f7cb714f77..ee012c068a697 100644 --- a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/DeleteByDirectoryPathInterface.php +++ b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/DeleteByDirectoryPathInterface.php @@ -11,6 +11,7 @@ /** * A command represents the media gallery assets delete action. A media gallery asset is filtered by directory * path value. + * @api */ interface DeleteByDirectoryPathInterface { @@ -18,7 +19,6 @@ interface DeleteByDirectoryPathInterface * Delete media assets by directory path * * @param string $directoryPath - * * @return void */ public function execute(string $directoryPath): void; diff --git a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/DeleteByPathInterface.php b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/DeleteByPathInterface.php index b3612a67ed536..0f04eaecf02ec 100644 --- a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/DeleteByPathInterface.php +++ b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/DeleteByPathInterface.php @@ -10,6 +10,7 @@ /** * A command represents the media gallery asset delete action. A media gallery asset is filtered by path value. + * @api */ interface DeleteByPathInterface { @@ -17,7 +18,6 @@ interface DeleteByPathInterface * Delete media asset by path * * @param string $mediaAssetPath - * * @return void */ public function execute(string $mediaAssetPath): void; diff --git a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByIdInterface.php b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByIdInterface.php index ef2ceb5ffbfe6..9d0b8863baf22 100644 --- a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByIdInterface.php +++ b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByIdInterface.php @@ -10,6 +10,7 @@ /** * A command represents the get media gallery asset by using media gallery asset id as a filter parameter. + * @api */ interface GetByIdInterface { @@ -17,7 +18,6 @@ interface GetByIdInterface * Get media asset by id * * @param int $mediaAssetId - * * @return \Magento\MediaGalleryApi\Api\Data\AssetInterface * @throws \Magento\Framework\Exception\NoSuchEntityException * @throws \Magento\Framework\Exception\IntegrationException diff --git a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByPathInterface.php b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByPathInterface.php index 547b0dc695dae..9d39b5cc692f3 100644 --- a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByPathInterface.php +++ b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByPathInterface.php @@ -10,6 +10,7 @@ /** * A command represents the get media gallery asset by using media gallery asset path as a filter parameter. + * @api */ interface GetByPathInterface { @@ -17,7 +18,6 @@ interface GetByPathInterface * Get media asset list * * @param string $mediaFilePath - * * @return \Magento\MediaGalleryApi\Api\Data\AssetInterface */ public function execute(string $mediaFilePath): \Magento\MediaGalleryApi\Api\Data\AssetInterface; diff --git a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/SaveInterface.php b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/SaveInterface.php index b3e3607e6e822..6d2aae21754b8 100644 --- a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/SaveInterface.php +++ b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/SaveInterface.php @@ -12,6 +12,7 @@ /** * A command which executes the media gallery asset save operation. + * @api */ interface SaveInterface { @@ -19,7 +20,6 @@ interface SaveInterface * Save media asset * * @param \Magento\MediaGalleryApi\Api\Data\AssetInterface $mediaAsset - * * @return int * @throws \Magento\Framework\Exception\CouldNotSaveException */ diff --git a/app/code/Magento/MediaGalleryApi/Model/DataExtractorInterface.php b/app/code/Magento/MediaGalleryApi/Model/DataExtractorInterface.php index 6570cd2235412..33fd2425edc6f 100644 --- a/app/code/Magento/MediaGalleryApi/Model/DataExtractorInterface.php +++ b/app/code/Magento/MediaGalleryApi/Model/DataExtractorInterface.php @@ -9,6 +9,7 @@ /** * Extract data from an object using available getters + * @api */ interface DataExtractorInterface { diff --git a/app/code/Magento/MediaGalleryApi/Model/Directory/Command/CreateByPathInterface.php b/app/code/Magento/MediaGalleryApi/Model/Directory/Command/CreateByPathInterface.php new file mode 100644 index 0000000000000..59a371cdb823f --- /dev/null +++ b/app/code/Magento/MediaGalleryApi/Model/Directory/Command/CreateByPathInterface.php @@ -0,0 +1,24 @@ + Date: Mon, 30 Mar 2020 19:36:21 +0100 Subject: [PATCH 04/89] Fixed static tests --- .../MediaGallery/Model/Asset/Command/GetById.php | 2 +- .../Model/File/Command/DeleteByAssetId.php | 2 -- .../Model/Keyword/Command/GetAssetKeywords.php | 2 +- .../Test/Unit/Model/Directory/ExcludedTest.php | 4 ++-- .../Unit/Model/File/Command/DeleteByAssetIdTest.php | 10 +++++----- 5 files changed, 9 insertions(+), 11 deletions(-) diff --git a/app/code/Magento/MediaGallery/Model/Asset/Command/GetById.php b/app/code/Magento/MediaGallery/Model/Asset/Command/GetById.php index b6153c45dbf8c..4475d5570c988 100644 --- a/app/code/Magento/MediaGallery/Model/Asset/Command/GetById.php +++ b/app/code/Magento/MediaGallery/Model/Asset/Command/GetById.php @@ -16,7 +16,7 @@ use Psr\Log\LoggerInterface; /** - * Class GetById + * Get media asset by id */ class GetById implements GetByIdInterface { diff --git a/app/code/Magento/MediaGallery/Model/File/Command/DeleteByAssetId.php b/app/code/Magento/MediaGallery/Model/File/Command/DeleteByAssetId.php index 177c67280580c..dff91e73c8c7a 100644 --- a/app/code/Magento/MediaGallery/Model/File/Command/DeleteByAssetId.php +++ b/app/code/Magento/MediaGallery/Model/File/Command/DeleteByAssetId.php @@ -55,9 +55,7 @@ public function __construct( * Delete image by asset ID * * @param int $assetId - * * @return void - * * @throws LocalizedException */ public function execute(int $assetId): void diff --git a/app/code/Magento/MediaGallery/Model/Keyword/Command/GetAssetKeywords.php b/app/code/Magento/MediaGallery/Model/Keyword/Command/GetAssetKeywords.php index ae61867884c7a..6cd8bd2463a2c 100644 --- a/app/code/Magento/MediaGallery/Model/Keyword/Command/GetAssetKeywords.php +++ b/app/code/Magento/MediaGallery/Model/Keyword/Command/GetAssetKeywords.php @@ -15,7 +15,7 @@ use Psr\Log\LoggerInterface; /** - * ClassGetAssetKeywords + * Retrieve keywords for the media asset */ class GetAssetKeywords implements GetAssetKeywordsInterface { diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/Directory/ExcludedTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/Directory/ExcludedTest.php index e468bee7cc5d7..ea9094b3ac1f4 100644 --- a/app/code/Magento/MediaGallery/Test/Unit/Model/Directory/ExcludedTest.php +++ b/app/code/Magento/MediaGallery/Test/Unit/Model/Directory/ExcludedTest.php @@ -5,14 +5,14 @@ */ declare(strict_types=1); -namespace Magento\MediaGallery\Test\Unit\Model\File\Command; +namespace Magento\MediaGallery\Test\Unit\Model\Directory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use PHPUnit\Framework\TestCase; use Magento\MediaGallery\Model\Directory\Excluded; /** - * Test the DeleteByAssetIdTest command model + * Test the Excluded model */ class ExcludedTest extends TestCase { diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/File/Command/DeleteByAssetIdTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/File/Command/DeleteByAssetIdTest.php index de5b5d42c71e3..903b366d0a9fd 100644 --- a/app/code/Magento/MediaGallery/Test/Unit/Model/File/Command/DeleteByAssetIdTest.php +++ b/app/code/Magento/MediaGallery/Test/Unit/Model/File/Command/DeleteByAssetIdTest.php @@ -7,16 +7,16 @@ namespace Magento\MediaGallery\Test\Unit\Model\File\Command; +use Magento\Cms\Model\Wysiwyg\Images\Storage; use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\MediaGalleryApi\Api\Data\AssetInterface; -use PHPUnit\Framework\MockObject\MockObject; -use PHPUnit\Framework\TestCase; -use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use Magento\Framework\Filesystem; use Magento\Framework\Filesystem\Directory\Read; -use Magento\Cms\Model\Wysiwyg\Images\Storage; +use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; +use Magento\MediaGalleryApi\Api\Data\AssetInterface; use Magento\MediaGalleryApi\Model\Asset\Command\GetByIdInterface; use Magento\MediaGallery\Model\File\Command\DeleteByAssetId; +use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\TestCase; /** * Test the DeleteByAssetIdTest command model From d88ed422fadb1cdb32ef56317d22fe53d1139299 Mon Sep 17 00:00:00 2001 From: Sergii Ivashchenko Date: Wed, 1 Apr 2020 16:33:38 +0100 Subject: [PATCH 05/89] Introduced MediaContent and MediaContentApi modules --- .../Observer/MediaContent/Category.php | 56 ++++++ .../Catalog/Observer/MediaContent/Product.php | 56 ++++++ app/code/Magento/Catalog/composer.json | 1 + app/code/Magento/Catalog/etc/di.xml | 23 +++ app/code/Magento/Catalog/etc/events.xml | 6 + .../Cms/Observer/MediaContent/Block.php | 56 ++++++ .../Cms/Observer/MediaContent/Page.php | 56 ++++++ app/code/Magento/Cms/composer.json | 1 + app/code/Magento/Cms/etc/di.xml | 21 +++ app/code/Magento/Cms/etc/events.xml | 6 + app/code/Magento/MediaContent/LICENSE.txt | 48 +++++ app/code/Magento/MediaContent/LICENSE_AFL.txt | 48 +++++ .../MediaContent/Model/AssignAsset.php | 69 +++++++ .../MediaContent/Model/ContentProcessor.php | 117 ++++++++++++ .../Model/ExtractAssetFromContent.php | 91 +++++++++ .../Model/GetAssetsUsedInContent.php | 76 ++++++++ .../Model/GetContentWithAsset.php | 63 +++++++ .../MediaContent/Model/ModelProcessor.php | 54 ++++++ .../MediaContent/Model/UnassignAsset.php | 71 +++++++ app/code/Magento/MediaContent/README.md | 13 ++ .../Test/Unit/Model/AssignAssetTest.php | 177 ++++++++++++++++++ .../Unit/Model/GetAssetsusedInContentTest.php | 148 +++++++++++++++ .../Unit/Model/GetContentWithAssetTest.php | 107 +++++++++++ .../Test/Unit/Model/UnassignAssetTest.php | 171 +++++++++++++++++ app/code/Magento/MediaContent/composer.json | 24 +++ .../Magento/MediaContent/etc/db_schema.xml | 21 +++ .../MediaContent/etc/db_schema_whitelist.json | 14 ++ app/code/Magento/MediaContent/etc/di.xml | 15 ++ app/code/Magento/MediaContent/etc/module.xml | 14 ++ .../Magento/MediaContent/registration.php | 10 + .../Api/AssignAssetInterface.php | 26 +++ .../Api/ExtractAssetFromContentInterface.php | 25 +++ .../Api/GetAssetsUsedInContentInterface.php | 28 +++ .../Api/GetContentWithAssetInterface.php | 24 +++ .../Api/ModelProcessorInterface.php | 26 +++ .../Api/UnassignAssetInterface.php | 26 +++ app/code/Magento/MediaContentApi/LICENSE.txt | 48 +++++ .../Magento/MediaContentApi/LICENSE_AFL.txt | 48 +++++ app/code/Magento/MediaContentApi/README.md | 13 ++ .../Magento/MediaContentApi/composer.json | 22 +++ .../Magento/MediaContentApi/etc/module.xml | 10 + .../Magento/MediaContentApi/registration.php | 10 + 42 files changed, 1939 insertions(+) create mode 100644 app/code/Magento/Catalog/Observer/MediaContent/Category.php create mode 100644 app/code/Magento/Catalog/Observer/MediaContent/Product.php create mode 100644 app/code/Magento/Cms/Observer/MediaContent/Block.php create mode 100644 app/code/Magento/Cms/Observer/MediaContent/Page.php create mode 100644 app/code/Magento/MediaContent/LICENSE.txt create mode 100644 app/code/Magento/MediaContent/LICENSE_AFL.txt create mode 100644 app/code/Magento/MediaContent/Model/AssignAsset.php create mode 100644 app/code/Magento/MediaContent/Model/ContentProcessor.php create mode 100644 app/code/Magento/MediaContent/Model/ExtractAssetFromContent.php create mode 100644 app/code/Magento/MediaContent/Model/GetAssetsUsedInContent.php create mode 100644 app/code/Magento/MediaContent/Model/GetContentWithAsset.php create mode 100644 app/code/Magento/MediaContent/Model/ModelProcessor.php create mode 100644 app/code/Magento/MediaContent/Model/UnassignAsset.php create mode 100644 app/code/Magento/MediaContent/README.md create mode 100644 app/code/Magento/MediaContent/Test/Unit/Model/AssignAssetTest.php create mode 100644 app/code/Magento/MediaContent/Test/Unit/Model/GetAssetsusedInContentTest.php create mode 100644 app/code/Magento/MediaContent/Test/Unit/Model/GetContentWithAssetTest.php create mode 100644 app/code/Magento/MediaContent/Test/Unit/Model/UnassignAssetTest.php create mode 100644 app/code/Magento/MediaContent/composer.json create mode 100644 app/code/Magento/MediaContent/etc/db_schema.xml create mode 100644 app/code/Magento/MediaContent/etc/db_schema_whitelist.json create mode 100644 app/code/Magento/MediaContent/etc/di.xml create mode 100644 app/code/Magento/MediaContent/etc/module.xml create mode 100644 app/code/Magento/MediaContent/registration.php create mode 100644 app/code/Magento/MediaContentApi/Api/AssignAssetInterface.php create mode 100644 app/code/Magento/MediaContentApi/Api/ExtractAssetFromContentInterface.php create mode 100644 app/code/Magento/MediaContentApi/Api/GetAssetsUsedInContentInterface.php create mode 100644 app/code/Magento/MediaContentApi/Api/GetContentWithAssetInterface.php create mode 100644 app/code/Magento/MediaContentApi/Api/ModelProcessorInterface.php create mode 100644 app/code/Magento/MediaContentApi/Api/UnassignAssetInterface.php create mode 100644 app/code/Magento/MediaContentApi/LICENSE.txt create mode 100644 app/code/Magento/MediaContentApi/LICENSE_AFL.txt create mode 100644 app/code/Magento/MediaContentApi/README.md create mode 100644 app/code/Magento/MediaContentApi/composer.json create mode 100644 app/code/Magento/MediaContentApi/etc/module.xml create mode 100644 app/code/Magento/MediaContentApi/registration.php diff --git a/app/code/Magento/Catalog/Observer/MediaContent/Category.php b/app/code/Magento/Catalog/Observer/MediaContent/Category.php new file mode 100644 index 0000000000000..0044a7301e67b --- /dev/null +++ b/app/code/Magento/Catalog/Observer/MediaContent/Category.php @@ -0,0 +1,56 @@ +processor = $processor; + $this->fields = $fields; + } + + /** + * Retrieve the saved category and pass it to the model processor to save content - asset relations + * + * @param Observer $observer + */ + public function execute(Observer $observer): void + { + /** @var CatalogCategory $model */ + $model = $observer->getEvent()->getData('category'); + if ($model instanceof AbstractModel) { + $this->processor->execute(self::CONTENT_TYPE, $model, $this->fields); + } + } +} diff --git a/app/code/Magento/Catalog/Observer/MediaContent/Product.php b/app/code/Magento/Catalog/Observer/MediaContent/Product.php new file mode 100644 index 0000000000000..bb043712a44f2 --- /dev/null +++ b/app/code/Magento/Catalog/Observer/MediaContent/Product.php @@ -0,0 +1,56 @@ +processor = $processor; + $this->fields = $fields; + } + + /** + * Retrieve the saved product and pass it to the model processor to save content - asset relations + * + * @param Observer $observer + */ + public function execute(Observer $observer): void + { + /** @var CatalogProduct $model */ + $model = $observer->getEvent()->getData('product'); + if ($model instanceof AbstractModel) { + $this->processor->execute(self::CONTENT_TYPE, $model, $this->fields); + } + } +} diff --git a/app/code/Magento/Catalog/composer.json b/app/code/Magento/Catalog/composer.json index 8023634fa074d..660c496b5a8f0 100644 --- a/app/code/Magento/Catalog/composer.json +++ b/app/code/Magento/Catalog/composer.json @@ -20,6 +20,7 @@ "magento/module-directory": "*", "magento/module-eav": "*", "magento/module-indexer": "*", + "magento/module-media-content-api": "*", "magento/module-media-storage": "*", "magento/module-msrp": "*", "magento/module-page-cache": "*", diff --git a/app/code/Magento/Catalog/etc/di.xml b/app/code/Magento/Catalog/etc/di.xml index ff67989d337bb..5f8710fef0ac9 100644 --- a/app/code/Magento/Catalog/etc/di.xml +++ b/app/code/Magento/Catalog/etc/di.xml @@ -1333,4 +1333,27 @@ + + + + image + description + + + + + + + description + short_description + + + + + + + /^\/?media\/(.*)/ + + + diff --git a/app/code/Magento/Catalog/etc/events.xml b/app/code/Magento/Catalog/etc/events.xml index 24186146c56f0..bb28dc00b50f2 100644 --- a/app/code/Magento/Catalog/etc/events.xml +++ b/app/code/Magento/Catalog/etc/events.xml @@ -67,4 +67,10 @@ + + + + + + diff --git a/app/code/Magento/Cms/Observer/MediaContent/Block.php b/app/code/Magento/Cms/Observer/MediaContent/Block.php new file mode 100644 index 0000000000000..80fe854531586 --- /dev/null +++ b/app/code/Magento/Cms/Observer/MediaContent/Block.php @@ -0,0 +1,56 @@ +processor = $processor; + $this->fields = $fields; + } + + /** + * Retrieve the saved block and pass it to the model processor to save content - asset relations + * + * @param Observer $observer + */ + public function execute(Observer $observer): void + { + /** @var CmsBlock $model */ + $model = $observer->getEvent()->getData('object'); + if ($model instanceof AbstractModel) { + $this->processor->execute(self::CONTENT_TYPE, $model, $this->fields); + } + } +} diff --git a/app/code/Magento/Cms/Observer/MediaContent/Page.php b/app/code/Magento/Cms/Observer/MediaContent/Page.php new file mode 100644 index 0000000000000..cc4fe14990a86 --- /dev/null +++ b/app/code/Magento/Cms/Observer/MediaContent/Page.php @@ -0,0 +1,56 @@ +processor = $processor; + $this->fields = $fields; + } + + /** + * Retrieve the saved page and pass it to the model processor to save content - asset relations + * + * @param Observer $observer + */ + public function execute(Observer $observer): void + { + /** @var CmsPage $model */ + $model = $observer->getEvent()->getData('object'); + if ($model instanceof AbstractModel) { + $this->processor->execute(self::CONTENT_TYPE, $model, $this->fields); + } + } +} diff --git a/app/code/Magento/Cms/composer.json b/app/code/Magento/Cms/composer.json index 91036d31fdc2b..c299ba63f9a96 100644 --- a/app/code/Magento/Cms/composer.json +++ b/app/code/Magento/Cms/composer.json @@ -10,6 +10,7 @@ "magento/module-backend": "*", "magento/module-catalog": "*", "magento/module-email": "*", + "magento/module-media-content-api": "*", "magento/module-media-storage": "*", "magento/module-store": "*", "magento/module-theme": "*", diff --git a/app/code/Magento/Cms/etc/di.xml b/app/code/Magento/Cms/etc/di.xml index 7fc8268eea5e0..0f573047d098f 100644 --- a/app/code/Magento/Cms/etc/di.xml +++ b/app/code/Magento/Cms/etc/di.xml @@ -243,4 +243,25 @@ + + + + content + + + + + + + content + + + + + + + /{{media url="?(.*?)"?}}/ + + + diff --git a/app/code/Magento/Cms/etc/events.xml b/app/code/Magento/Cms/etc/events.xml index 1ad847e215ccc..a49e1638f0ab2 100644 --- a/app/code/Magento/Cms/etc/events.xml +++ b/app/code/Magento/Cms/etc/events.xml @@ -39,4 +39,10 @@ + + + + + + diff --git a/app/code/Magento/MediaContent/LICENSE.txt b/app/code/Magento/MediaContent/LICENSE.txt new file mode 100644 index 0000000000000..49525fd99da9c --- /dev/null +++ b/app/code/Magento/MediaContent/LICENSE.txt @@ -0,0 +1,48 @@ + +Open Software License ("OSL") v. 3.0 + +This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Open Software License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including 'fair use' or 'fair dealing'). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright (C) 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. \ No newline at end of file diff --git a/app/code/Magento/MediaContent/LICENSE_AFL.txt b/app/code/Magento/MediaContent/LICENSE_AFL.txt new file mode 100644 index 0000000000000..f39d641b18a19 --- /dev/null +++ b/app/code/Magento/MediaContent/LICENSE_AFL.txt @@ -0,0 +1,48 @@ + +Academic Free License ("AFL") v. 3.0 + +This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Academic Free License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor's reserved rights and remedies, in this Academic Free License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. diff --git a/app/code/Magento/MediaContent/Model/AssignAsset.php b/app/code/Magento/MediaContent/Model/AssignAsset.php new file mode 100644 index 0000000000000..ada7e9adf20ef --- /dev/null +++ b/app/code/Magento/MediaContent/Model/AssignAsset.php @@ -0,0 +1,69 @@ +resourceConnection = $resourceConnection; + $this->logger = $logger; + } + + /** + * @inheritDoc + */ + public function execute(int $assetId, string $contentType, string $contentEntityId, string $contentField): void + { + try { + $connection = $this->resourceConnection->getConnection(); + $tableName = $this->resourceConnection->getTableName(self::MEDIA_CONTENT_ASSET_TABLE_NAME); + $saveData = [ + self::ASSET_ID => $assetId, + self::TYPE => $contentType, + self::ENTITY_ID => $contentEntityId, + self::FIELD => $contentField + ]; + $connection->insert($tableName, $saveData); + } catch (\Exception $exception) { + $this->logger->critical($exception); + $message = __('An error occurred while saving relation between media asset and media content.'); + throw new CouldNotSaveException($message); + } + } +} diff --git a/app/code/Magento/MediaContent/Model/ContentProcessor.php b/app/code/Magento/MediaContent/Model/ContentProcessor.php new file mode 100644 index 0000000000000..2d8fc45506e89 --- /dev/null +++ b/app/code/Magento/MediaContent/Model/ContentProcessor.php @@ -0,0 +1,117 @@ +extractAssetFromContent = $extractAssetFromContent; + $this->assignAsset = $assignAsset; + $this->getAssetsUsedInContent = $getAssetsUsedInContent; + $this->unassignAsset = $unassignAsset; + $this->logger = $logger; + } + + /** + * Create new relation between media asset and content or updated existing + * + * @param string $type + * @param string $field + * @param string $entityId + * @param string $data + */ + public function execute(string $type, string $field, string $entityId, string $data): void + { + try { + $this->updateRelation($type, $field, $entityId, $data); + } catch (\Exception $exception) { + $this->logger->critical($exception); + } + } + + /** + * Records a relation for the newly added asset + * + * @param string $type + * @param string $field + * @param string $entityId + * @param string $data + * @throws CouldNotDeleteException + * @throws CouldNotSaveException + * @throws IntegrationException + */ + private function updateRelation(string $type, string $field, string $entityId, string $data) + { + $relations = $this->getAssetsUsedInContent->execute($type, $entityId, $field); + $assetsInContent = $this->extractAssetFromContent->execute($data); + /** @var AssetInterface $asset */ + foreach ($assetsInContent as $asset) { + if (!isset($relations[$asset->getId()])) { + $this->assignAsset->execute($asset->getId(), $type, $entityId, $field); + } + } + + foreach (array_keys($relations) as $assetId) { + if (!isset($assetsInContent[$assetId])) { + $this->unassignAsset->execute($assetId, $type, $entityId, $field); + } + } + } +} diff --git a/app/code/Magento/MediaContent/Model/ExtractAssetFromContent.php b/app/code/Magento/MediaContent/Model/ExtractAssetFromContent.php new file mode 100644 index 0000000000000..5f379080bc0f1 --- /dev/null +++ b/app/code/Magento/MediaContent/Model/ExtractAssetFromContent.php @@ -0,0 +1,91 @@ +getMediaAssetByPath = $getMediaAssetByPath; + $this->logger = $logger; + $this->searchPatterns = $searchPatterns; + } + + /** + * Search for the media asset in content and extract it providing a list of media assets. + * + * @param string $content + * @return AssetInterface[] + */ + public function execute(string $content): array + { + $paths = []; + + foreach ($this->searchPatterns as $pattern) { + preg_match_all($pattern, $content, $matches, PREG_PATTERN_ORDER); + if (!empty($matches[1])) { + $paths += array_unique($matches[1]); + } + } + + return $this->getAssetsByPaths(array_unique($paths)); + } + + /** + * Get media assets by paths array + * + * @param array $paths + * @return AssetInterface[] + */ + private function getAssetsByPaths(array $paths): array + { + $assets = []; + + foreach ($paths as $path) { + try { + /** @var AssetInterface $asset */ + $asset = $this->getMediaAssetByPath->execute('/' . $path); + $assets[$asset->getId()] = $asset; + } catch (\Exception $exception) { + $this->logger->critical($exception); + } + } + + return $assets; + } +} diff --git a/app/code/Magento/MediaContent/Model/GetAssetsUsedInContent.php b/app/code/Magento/MediaContent/Model/GetAssetsUsedInContent.php new file mode 100644 index 0000000000000..2baa022713d8f --- /dev/null +++ b/app/code/Magento/MediaContent/Model/GetAssetsUsedInContent.php @@ -0,0 +1,76 @@ +resourceConnection = $resourceConnection; + $this->logger = $logger; + } + + /** + * @inheritDoc + */ + public function execute(string $contentType, string $contentEntityId = null, string $contentField = null): array + { + try { + $connection = $this->resourceConnection->getConnection(); + $select = $connection->select() + ->from( + $this->resourceConnection->getTableName(self::MEDIA_CONTENT_ASSET_TABLE_NAME), + self::ASSET_ID + )->where(self::TYPE . ' = ?', $contentType); + + if (null !== $contentEntityId) { + $select = $select->where(self::ENTITY_ID . '= ?', $contentEntityId); + } + + if (null !== $contentField) { + $select = $select->where(self::FIELD . '= ?', $contentField); + } + + return $connection->fetchAssoc($select); + } catch (\Exception $exception) { + $this->logger->critical($exception); + $message = __('An error occurred at getting asset used in content information.'); + throw new IntegrationException($message); + } + } +} diff --git a/app/code/Magento/MediaContent/Model/GetContentWithAsset.php b/app/code/Magento/MediaContent/Model/GetContentWithAsset.php new file mode 100644 index 0000000000000..796cc890b3845 --- /dev/null +++ b/app/code/Magento/MediaContent/Model/GetContentWithAsset.php @@ -0,0 +1,63 @@ +resourceConnection = $resourceConnection; + $this->logger = $logger; + } + + /** + * @inheritDoc + */ + public function execute(int $assetId): array + { + try { + $connection = $this->resourceConnection->getConnection(); + $select = $connection->select() + ->from($this->resourceConnection->getTableName(self::MEDIA_CONTENT_ASSET_TABLE_NAME)) + ->where(self::ASSET_ID . '= ?', $assetId); + + return $connection->fetchAssoc($select); + } catch (\Exception $exception) { + $this->logger->critical($exception); + $message = __('An error occurred at getting media asset to content relation by media asset id.'); + throw new IntegrationException($message); + } + } +} diff --git a/app/code/Magento/MediaContent/Model/ModelProcessor.php b/app/code/Magento/MediaContent/Model/ModelProcessor.php new file mode 100644 index 0000000000000..8e3a3ebf168d6 --- /dev/null +++ b/app/code/Magento/MediaContent/Model/ModelProcessor.php @@ -0,0 +1,54 @@ +contentProcessor = $contentProcessor; + } + + /** + * Save relations for content within an AbstractModel instance + * + * @param string $type + * @param AbstractModel $model + * @param array $fields + */ + public function execute(string $type, AbstractModel $model, array $fields): void + { + foreach ($fields as $field) { + if (!$model->dataHasChangedFor($field)) { + continue; + } + $this->contentProcessor->execute( + $type, + $field, + (string) $model->getId(), + (string) $model->getData($field) + ); + } + } +} diff --git a/app/code/Magento/MediaContent/Model/UnassignAsset.php b/app/code/Magento/MediaContent/Model/UnassignAsset.php new file mode 100644 index 0000000000000..ae5924f662403 --- /dev/null +++ b/app/code/Magento/MediaContent/Model/UnassignAsset.php @@ -0,0 +1,71 @@ +resourceConnection = $resourceConnection; + $this->logger = $logger; + } + + /** + * @inheritDoc + */ + public function execute(int $assetId, string $contentType, string $contentEntityId, string $contentField): void + { + try { + $connection = $this->resourceConnection->getConnection(); + $tableName = $this->resourceConnection->getTableName(self::MEDIA_CONTENT_ASSET_TABLE_NAME); + $connection->delete( + $tableName, + [ + self::ASSET_ID . ' = ?' => $assetId, + self::TYPE . ' = ?' => $contentType, + self::ENTITY_ID . ' = ?' => $contentEntityId, + self::FIELD . ' = ?' => $contentField + ] + ); + } catch (\Exception $exception) { + $this->logger->critical($exception); + $message = __('An error occurred at unassign relation between the media asset and media content.'); + throw new CouldNotDeleteException($message); + } + } +} diff --git a/app/code/Magento/MediaContent/README.md b/app/code/Magento/MediaContent/README.md new file mode 100644 index 0000000000000..b5813540acef7 --- /dev/null +++ b/app/code/Magento/MediaContent/README.md @@ -0,0 +1,13 @@ +# Magento_MediaContent module + +The Magento_MediaContent module provides implementations for managing relations between content and media files used in that content. + +## Extensibility + +Extension developers can interact with the Magento_MediaContent module. For more information about the Magento extension mechanism, see [Magento plug-ins](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/plugins.html). + +[The Magento dependency injection mechanism](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html) enables you to override the functionality of the Magento_MediaContent module. + +## Additional information + +For information about significant changes in patch releases, see [2.3.x Release information](https://devdocs.magento.com/guides/v2.3/release-notes/bk-release-notes.html). diff --git a/app/code/Magento/MediaContent/Test/Unit/Model/AssignAssetTest.php b/app/code/Magento/MediaContent/Test/Unit/Model/AssignAssetTest.php new file mode 100644 index 0000000000000..98e0e8fe2606e --- /dev/null +++ b/app/code/Magento/MediaContent/Test/Unit/Model/AssignAssetTest.php @@ -0,0 +1,177 @@ +adapterMock = $this->createMock(Mysql::class); + $this->loggerMock = $this->createMock(LoggerInterface::class); + $this->resourceConnectionMock = $this->createConfiguredMock( + ResourceConnection::class, + [ + 'getConnection' => $this->adapterMock, + 'getTableName' => self::PREFIXED_TABLE_MEDIA_CONTENT_ASSET + ] + ); + + $this->assignAsset = (new ObjectManager($this))->getObject( + AssignAsset::class, + [ + 'resourceConnection' => $this->resourceConnectionMock, + 'logger' => $this->loggerMock + ] + ); + } + + /** + * Tests successful scenario for saving relation between media asset and media content. + * + * @param int $assetId + * @param string $contentType + * @param string $contentEntityId + * @param string $contentField + * @dataProvider assignAssetDataProvider + * @return void + */ + public function testSuccessfulExecute( + int $assetId, + string $contentType, + string $contentEntityId, + string $contentField + ): void { + $saveData = [ + self::ASSET_ID => $assetId, + self::TYPE => $contentType, + self::ENTITY_ID => $contentEntityId, + self::FIELD => $contentField + ]; + $this->adapterMock + ->expects(self::once()) + ->method('insert') + ->with(self::PREFIXED_TABLE_MEDIA_CONTENT_ASSET, $saveData) + ->willReturn(self::AFFECTED_ROWS); + + $this->assignAsset->execute($assetId, $contentType, $contentEntityId, $contentField); + } + + /** + * Tests with exception scenario for saving relation between media asset and media content. + * + * @param int $assetId + * @param string $contentType + * @param string $contentEntityId + * @param string $contentField + * @dataProvider assignAssetDataProvider + */ + public function testExceptionExecute( + int $assetId, + string $contentType, + string $contentEntityId, + string $contentField + ): void { + $this->resourceConnectionMock->method('getConnection')->willThrowException((new \Exception())); + + $this->loggerMock + ->expects(self::once()) + ->method('critical') + ->willReturnSelf(); + + $this->expectException(CouldNotSaveException::class); + $this->assignAsset->execute($assetId, $contentType, $contentEntityId, $contentField); + } + + /** + * Media asset to media content relation data + * + * @return array + */ + public function assignAssetDataProvider(): array + { + return [ + [ + '18976345', + 'cms_page', + '1', + 'content' + ] + ]; + } +} diff --git a/app/code/Magento/MediaContent/Test/Unit/Model/GetAssetsusedInContentTest.php b/app/code/Magento/MediaContent/Test/Unit/Model/GetAssetsusedInContentTest.php new file mode 100644 index 0000000000000..911d9b6e6f375 --- /dev/null +++ b/app/code/Magento/MediaContent/Test/Unit/Model/GetAssetsusedInContentTest.php @@ -0,0 +1,148 @@ +resourceConnectionStub = $this->createMock(ResourceConnection::class); + $this->loggerMock = $this->createMock(LoggerInterface::class); + $this->getAssetsUsedInContent = new GetAssetsUsedInContent($this->resourceConnectionStub, $this->loggerMock); + } + + /** + * Test successful execution of the GetAssetsUsedInContent::execute. + * + * @param array $requestParameters + * @param array $expectedAssetIdList + * @dataProvider getAssetsListRelatedToContent + */ + public function testSuccessfulGetUsedAssets( + array $requestParameters, + array $expectedAssetIdList + ): void { + $this->configureResourceConnectionStub($expectedAssetIdList); + $assetList = $this->getAssetsUsedInContent->execute( + $requestParameters['type'], + $requestParameters['entity_id'], + $requestParameters['field'] + ); + + $this->assertEquals($expectedAssetIdList, $assetList); + } + + /** + * Test GetAssetsUsedInContent::execute with exception. + */ + public function testGetUsedAssetsWithException(): void + { + $this->resourceConnectionStub->method('getConnection')->willThrowException((new \Exception())); + $this->expectException(IntegrationException::class); + $this->loggerMock->expects($this->once()) + ->method('critical') + ->willReturnSelf(); + + $this->getAssetsUsedInContent->execute('cms_page', '1', 'content'); + } + + /** + * Configure resource connection for the command. Based on the current implementation. + * + * @param array $expectedAssetIdList + */ + private function configureResourceConnectionStub(array $expectedAssetIdList): void + { + $selectStub = $this->createMock(Select::class); + $selectStub->expects($this->any())->method('from')->willReturnSelf(); + $selectStub->expects($this->any())->method('where')->willReturnSelf(); + + $connectionMock = $this->getMockBuilder(AdapterInterface::class)->getMock(); + $connectionMock->expects($this->any())->method('select')->willReturn($selectStub); + $connectionMock->expects($this->any()) + ->method('fetchAssoc') + ->with($selectStub) + ->willReturn($expectedAssetIdList); + $this->resourceConnectionStub->expects($this->any()) + ->method('getConnection') + ->willReturn($connectionMock); + } + + /** + * Media asset to media content relation data + * + * @return array + */ + public function getAssetsListRelatedToContent(): array + { + return [ + [ + [ + 'type' => 'cms_page', + 'entity_id' => '1', + 'field' => 'content' + ], + [1234123] + ], + [ + [ + 'type' => 'cms_page', + 'entity_id' => null, + 'field' => 'content' + ], + [1234123, 2425168] + ], + [ + [ + 'type' => 'catalog_category', + 'entity_id' => '1', + 'field' => null + ], + [1234123] + ], + [ + [ + 'type' => 'cbm_block', + 'entity_id' => null, + 'field' => null + ], + [1234123, 2425168] + ] + ]; + } +} diff --git a/app/code/Magento/MediaContent/Test/Unit/Model/GetContentWithAssetTest.php b/app/code/Magento/MediaContent/Test/Unit/Model/GetContentWithAssetTest.php new file mode 100644 index 0000000000000..3ba98a400fcba --- /dev/null +++ b/app/code/Magento/MediaContent/Test/Unit/Model/GetContentWithAssetTest.php @@ -0,0 +1,107 @@ + [ + 1234123, + 'cms_page', + '1', + 'content', + ] + ]; + + /** + * @var ResourceConnection | MockObject + */ + private $resourceConnectionStub; + + /** + * @var LoggerInterface | MockObject + */ + private $loggerMock; + + /** + * @var GetContentWithAsset + */ + private $getContentWithAsset; + + /** + * @inheritdoc + */ + protected function setUp(): void + { + $this->resourceConnectionStub = $this->createMock(ResourceConnection::class); + $this->loggerMock = $this->createMock(LoggerInterface::class); + $this->getContentWithAsset = new GetContentWithAsset($this->resourceConnectionStub, $this->loggerMock); + } + + /** + * Test successful execution of the GetContentWithAsset::execute. + */ + public function testSuccessfulGetContentWithAsset(): void + { + $assetId = 1234123; + $this->configureResourceConnectionStub(); + $assetList = $this->getContentWithAsset->execute($assetId); + + $this->assertEquals(self::EXPECTED_LIST_OF_ASSETS, $assetList); + } + + /** + * Test GetContentWithAsset::execute with exception. + */ + public function testGetContentWithAssetWithException(): void + { + $this->resourceConnectionStub->method('getConnection')->willThrowException((new \Exception())); + $this->expectException(IntegrationException::class); + $this->loggerMock->expects($this->once()) + ->method('critical') + ->willReturnSelf(); + + $this->getContentWithAsset->execute(1); + } + + /** + * Configure resource connection for the command. Based on the current implementation. + */ + private function configureResourceConnectionStub(): void + { + $selectStub = $this->createMock(Select::class); + $selectStub->method('from')->willReturnSelf(); + $selectStub->method('where')->willReturnSelf(); + + $connectionMock = $this->getMockBuilder(AdapterInterface::class)->getMock(); + $connectionMock->expects($this->any())->method('select')->willReturn($selectStub); + $connectionMock->expects($this->any()) + ->method('fetchAssoc') + ->with($selectStub) + ->willReturn(self::EXPECTED_LIST_OF_ASSETS); + $this->resourceConnectionStub->expects($this->any()) + ->method('getConnection') + ->willReturn($connectionMock); + } +} diff --git a/app/code/Magento/MediaContent/Test/Unit/Model/UnassignAssetTest.php b/app/code/Magento/MediaContent/Test/Unit/Model/UnassignAssetTest.php new file mode 100644 index 0000000000000..ac35ef6e75dd2 --- /dev/null +++ b/app/code/Magento/MediaContent/Test/Unit/Model/UnassignAssetTest.php @@ -0,0 +1,171 @@ +adapterMock = $this->createMock(Mysql::class); + $this->loggerMock = $this->createMock(LoggerInterface::class); + $this->resourceConnectionMock = $this->createConfiguredMock( + ResourceConnection::class, + [ + 'getConnection' => $this->adapterMock, + 'getTableName' => self::PREFIXED_TABLE_MEDIA_CONTENT_ASSET + ] + ); + + $this->unassignAsset = (new ObjectManager($this))->getObject( + UnassignAsset::class, + [ + 'resourceConnection' => $this->resourceConnectionMock, + 'logger' => $this->loggerMock + ] + ); + } + + /** + * Test successful scenario for deleting relation between media asset and media content. + * + * @param int $assetId + * @param string $contentType + * @param string $contentEntityId + * @param string $contentField + * @dataProvider unassignAssetDataProvider + * @return void + */ + public function testSuccessfulUnassignAsset( + int $assetId, + string $contentType, + string $contentEntityId, + string $contentField + ): void { + $this->adapterMock->expects($this->once()) + ->method('delete') + ->with( + self::PREFIXED_TABLE_MEDIA_CONTENT_ASSET, + [ + self::ASSET_ID . ' = ?' => $assetId, + self::TYPE . ' = ?' => $contentType, + self::ENTITY_ID . ' = ?' => $contentEntityId, + self::FIELD . ' = ?' => $contentField + ] + ); + + $this->unassignAsset->execute($assetId, $contentType, $contentEntityId, $contentField); + } + + /** + * Test exception scenario for deleting relation between media asset and media content. + * + * @param int $assetId + * @param string $contentType + * @param string $contentEntityId + * @param string $contentField + * @dataProvider unassignAssetDataProvider + * @return void + */ + public function testUnassignAssetWithException( + int $assetId, + string $contentType, + string $contentEntityId, + string $contentField + ): void { + $this->resourceConnectionMock->method('getConnection')->willThrowException((new \Exception())); + + $this->expectException(CouldNotDeleteException::class); + $this->loggerMock->expects($this->once()) + ->method('critical') + ->willReturnSelf(); + $this->unassignAsset->execute($assetId, $contentType, $contentEntityId, $contentField); + } + + /** + * Media asset to media content relation data + * + * @return array + */ + public function unassignAssetDataProvider(): array + { + return [ + [ + 18976345, + 'cms_page', + '1', + 'content' + ] + ]; + } +} diff --git a/app/code/Magento/MediaContent/composer.json b/app/code/Magento/MediaContent/composer.json new file mode 100644 index 0000000000000..e14c0fc1aeadd --- /dev/null +++ b/app/code/Magento/MediaContent/composer.json @@ -0,0 +1,24 @@ +{ + "name": "magento/module-media-content", + "description": "Magento module provides the implementation for managing relations between content and media files used in that content", + "require": { + "php": "~7.1.3||~7.2.0||~7.3.0", + "magento/framework": "*", + "magento/module-media-content-api": "*", + "magento/module-media-gallery-api": "*", + "magento/module-media-gallery": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\MediaContent\\": "" + } + } +} diff --git a/app/code/Magento/MediaContent/etc/db_schema.xml b/app/code/Magento/MediaContent/etc/db_schema.xml new file mode 100644 index 0000000000000..25c4b50098085 --- /dev/null +++ b/app/code/Magento/MediaContent/etc/db_schema.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + +
+
diff --git a/app/code/Magento/MediaContent/etc/db_schema_whitelist.json b/app/code/Magento/MediaContent/etc/db_schema_whitelist.json new file mode 100644 index 0000000000000..9b55f29a3b039 --- /dev/null +++ b/app/code/Magento/MediaContent/etc/db_schema_whitelist.json @@ -0,0 +1,14 @@ +{ + "media_content_asset": { + "column": { + "asset_id": true, + "type": true, + "entity_id": true, + "field": true + }, + "constraint": { + "PRIMARY": true, + "MEDIA_CONTENT_ASSET_ASSET_ID_MEDIA_GALLERY_ASSET_ID": true + } + } +} diff --git a/app/code/Magento/MediaContent/etc/di.xml b/app/code/Magento/MediaContent/etc/di.xml new file mode 100644 index 0000000000000..3a8839c3ca741 --- /dev/null +++ b/app/code/Magento/MediaContent/etc/di.xml @@ -0,0 +1,15 @@ + + + + + + + + + + diff --git a/app/code/Magento/MediaContent/etc/module.xml b/app/code/Magento/MediaContent/etc/module.xml new file mode 100644 index 0000000000000..ebf2a2f0d9277 --- /dev/null +++ b/app/code/Magento/MediaContent/etc/module.xml @@ -0,0 +1,14 @@ + + + + + + + + + diff --git a/app/code/Magento/MediaContent/registration.php b/app/code/Magento/MediaContent/registration.php new file mode 100644 index 0000000000000..d6776f29f46df --- /dev/null +++ b/app/code/Magento/MediaContent/registration.php @@ -0,0 +1,10 @@ +" or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. \ No newline at end of file diff --git a/app/code/Magento/MediaContentApi/LICENSE_AFL.txt b/app/code/Magento/MediaContentApi/LICENSE_AFL.txt new file mode 100644 index 0000000000000..f39d641b18a19 --- /dev/null +++ b/app/code/Magento/MediaContentApi/LICENSE_AFL.txt @@ -0,0 +1,48 @@ + +Academic Free License ("AFL") v. 3.0 + +This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Academic Free License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor's reserved rights and remedies, in this Academic Free License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. diff --git a/app/code/Magento/MediaContentApi/README.md b/app/code/Magento/MediaContentApi/README.md new file mode 100644 index 0000000000000..87e0d7524f59b --- /dev/null +++ b/app/code/Magento/MediaContentApi/README.md @@ -0,0 +1,13 @@ +# Magento_MediaContentApi module + +The Magento_MediaContentApi module provides interfaces for managing relations between content and media files used in that content. + +## Extensibility + +Extension developers can interact with the Magento_MediaContent module. For more information about the Magento extension mechanism, see [Magento plug-ins](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/plugins.html). + +[The Magento dependency injection mechanism](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html) enables you to override the functionality of the Magento_MediaContent module. + +## Additional information + +For information about significant changes in patch releases, see [2.3.x Release information](https://devdocs.magento.com/guides/v2.3/release-notes/bk-release-notes.html). diff --git a/app/code/Magento/MediaContentApi/composer.json b/app/code/Magento/MediaContentApi/composer.json new file mode 100644 index 0000000000000..f8c27093280f6 --- /dev/null +++ b/app/code/Magento/MediaContentApi/composer.json @@ -0,0 +1,22 @@ +{ + "name": "magento/module-media-content-api", + "description": "Magento module provides the API interfaces for managing relations between content and media files used in that content", + "require": { + "php": "~7.1.3||~7.2.0||~7.3.0", + "magento/module-media-gallery-api": "*", + "magento/framework": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\MediaContentApi\\": "" + } + } +} diff --git a/app/code/Magento/MediaContentApi/etc/module.xml b/app/code/Magento/MediaContentApi/etc/module.xml new file mode 100644 index 0000000000000..3aa553170fe2a --- /dev/null +++ b/app/code/Magento/MediaContentApi/etc/module.xml @@ -0,0 +1,10 @@ + + + + + diff --git a/app/code/Magento/MediaContentApi/registration.php b/app/code/Magento/MediaContentApi/registration.php new file mode 100644 index 0000000000000..fb3faefa2734f --- /dev/null +++ b/app/code/Magento/MediaContentApi/registration.php @@ -0,0 +1,10 @@ + Date: Wed, 1 Apr 2020 17:54:48 +0100 Subject: [PATCH 06/89] magento/magento2#27536: Included MediaContent modules in root composer.json --- composer.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/composer.json b/composer.json index 769885ef305bf..4b0d4d18eac2a 100644 --- a/composer.json +++ b/composer.json @@ -197,6 +197,8 @@ "magento/module-instant-purchase": "*", "magento/module-integration": "*", "magento/module-layered-navigation": "*", + "magento/module-media-content": "*", + "magento/module-media-content-api": "*", "magento/module-media-gallery": "*", "magento/module-media-gallery-api": "*", "magento/module-media-storage": "*", From be2e6958f68593c30b8e21d39d467f5e5ddfcc53 Mon Sep 17 00:00:00 2001 From: Sergii Ivashchenko Date: Wed, 1 Apr 2020 20:57:00 +0100 Subject: [PATCH 07/89] magento/magento2#27499: Code review changes --- .../Model/Directory/Command/CreateByPath.php | 5 ++-- .../Model/Directory/Command/DeleteByPath.php | 7 +++--- app/code/Magento/MediaGallery/etc/di.xml | 16 ------------- .../Model/Directory/Blacklist.php} | 19 +++++++++------ ...edInterface.php => BlacklistInterface.php} | 8 +++---- .../File/Command/DeleteByAssetIdInterface.php | 4 ++-- .../Unit/Model/Directory/BlacklistTest.php} | 16 ++++++------- app/code/Magento/MediaGalleryApi/etc/di.xml | 24 +++++++++++++++++++ 8 files changed, 55 insertions(+), 44 deletions(-) rename app/code/Magento/{MediaGallery/Model/Directory/Excluded.php => MediaGalleryApi/Model/Directory/Blacklist.php} (55%) rename app/code/Magento/MediaGalleryApi/Model/Directory/{ExcludedInterface.php => BlacklistInterface.php} (51%) rename app/code/Magento/{MediaGallery/Test/Unit/Model/Directory/ExcludedTest.php => MediaGalleryApi/Test/Unit/Model/Directory/BlacklistTest.php} (72%) create mode 100644 app/code/Magento/MediaGalleryApi/etc/di.xml diff --git a/app/code/Magento/MediaGallery/Model/Directory/Command/CreateByPath.php b/app/code/Magento/MediaGallery/Model/Directory/Command/CreateByPath.php index 6d0ea45aa02cd..c70f71df02a39 100644 --- a/app/code/Magento/MediaGallery/Model/Directory/Command/CreateByPath.php +++ b/app/code/Magento/MediaGallery/Model/Directory/Command/CreateByPath.php @@ -40,7 +40,7 @@ public function __construct( } /** - * Create new directory by provided path + * Create new directory by the provided path in the media storage * * @param string $path * @param string $name @@ -52,8 +52,7 @@ public function execute(string $path, string $name): void $this->storage->createDirectory($name, $this->storage->getCmsWysiwygImages()->getStorageRoot() . $path); } catch (\Exception $exception) { $this->logger->critical($exception); - $message = __('Failed to create the folder: %error', ['error' => $exception->getMessage()]); - throw new CouldNotSaveException($message, $exception); + throw new CouldNotSaveException(__('Failed to create the folder'), $exception); } } } diff --git a/app/code/Magento/MediaGallery/Model/Directory/Command/DeleteByPath.php b/app/code/Magento/MediaGallery/Model/Directory/Command/DeleteByPath.php index ee78216fafdaf..73f0e08add751 100644 --- a/app/code/Magento/MediaGallery/Model/Directory/Command/DeleteByPath.php +++ b/app/code/Magento/MediaGallery/Model/Directory/Command/DeleteByPath.php @@ -13,7 +13,7 @@ use Psr\Log\LoggerInterface; /** - * Delete folder by provided path + * Delete directory from media storage by path */ class DeleteByPath implements DeleteByPathInterface { @@ -40,7 +40,7 @@ public function __construct( } /** - * Deletes the existing folder + * Removes directory and corresponding thumbnails directory from media storage if not in blacklist * * @param string $path * @throws CouldNotDeleteException @@ -51,8 +51,7 @@ public function execute(string $path): void $this->storage->deleteDirectory($this->storage->getCmsWysiwygImages()->getStorageRoot() . $path); } catch (\Exception $exception) { $this->logger->critical($exception); - $message = __('Failed to delete the folder: %error', ['error' => $exception->getMessage()]); - throw new CouldNotDeleteException($message, $exception); + throw new CouldNotDeleteException(__('Failed to delete the folder'), $exception); } } } diff --git a/app/code/Magento/MediaGallery/etc/di.xml b/app/code/Magento/MediaGallery/etc/di.xml index ccc8ce28a733d..2f402c30c5bc7 100644 --- a/app/code/Magento/MediaGallery/etc/di.xml +++ b/app/code/Magento/MediaGallery/etc/di.xml @@ -19,8 +19,6 @@ - - @@ -29,18 +27,4 @@ - - - - /pub\/media\/captcha/ - /pub\/media\/catalog\/product/ - /pub\/media\/customer/ - /pub\/media\/downloadable/ - /pub\/media\/import/ - /pub\/media\/theme/ - /pub\/media\/theme_customization/ - /pub\/media\/tmp/ - - - diff --git a/app/code/Magento/MediaGallery/Model/Directory/Excluded.php b/app/code/Magento/MediaGalleryApi/Model/Directory/Blacklist.php similarity index 55% rename from app/code/Magento/MediaGallery/Model/Directory/Excluded.php rename to app/code/Magento/MediaGalleryApi/Model/Directory/Blacklist.php index ad8843da9e8c3..fc6d73550f0fa 100644 --- a/app/code/Magento/MediaGallery/Model/Directory/Excluded.php +++ b/app/code/Magento/MediaGalleryApi/Model/Directory/Blacklist.php @@ -5,14 +5,16 @@ */ declare(strict_types=1); -namespace Magento\MediaGallery\Model\Directory; - -use Magento\MediaGalleryApi\Model\Directory\ExcludedInterface; +namespace Magento\MediaGalleryApi\Model\Directory; /** - * Directory paths that should not be included in the media gallery + * Directories blacklisted for media gallery. This class should be used for DI configuration. + * + * Please use the interface in the code (for constructor injection) instead of this implementation. + * + * @api */ -class Excluded implements ExcludedInterface +class Blacklist implements BlacklistInterface { /** * @var array @@ -29,14 +31,17 @@ public function __construct( } /** - * Check if the path is excluded from displaying in the media gallery + * Check if the directory path can be used in the media gallery operations * * @param string $path * @return bool */ - public function isExcluded(string $path): bool + public function isBlacklisted(string $path): bool { foreach ($this->patterns as $pattern) { + if (empty($pattern)) { + continue; + } preg_match($pattern, $path, $result); if ($result) { diff --git a/app/code/Magento/MediaGalleryApi/Model/Directory/ExcludedInterface.php b/app/code/Magento/MediaGalleryApi/Model/Directory/BlacklistInterface.php similarity index 51% rename from app/code/Magento/MediaGalleryApi/Model/Directory/ExcludedInterface.php rename to app/code/Magento/MediaGalleryApi/Model/Directory/BlacklistInterface.php index 159813a7094a3..f75af40fa72a7 100644 --- a/app/code/Magento/MediaGalleryApi/Model/Directory/ExcludedInterface.php +++ b/app/code/Magento/MediaGalleryApi/Model/Directory/BlacklistInterface.php @@ -8,16 +8,16 @@ namespace Magento\MediaGalleryApi\Model\Directory; /** - * Directory paths that should not be included in the media gallery + * Directory paths that are reserved by system and not be included in the media gallery * @api */ -interface ExcludedInterface +interface BlacklistInterface { /** - * Check if the path is excluded from displaying in the media gallery + * Check if the path is excluded from displaying and processing in the media gallery * * @param string $path * @return bool */ - public function isExcluded(string $path): bool; + public function isBlacklisted(string $path): bool; } diff --git a/app/code/Magento/MediaGalleryApi/Model/File/Command/DeleteByAssetIdInterface.php b/app/code/Magento/MediaGalleryApi/Model/File/Command/DeleteByAssetIdInterface.php index a73a29e8de1dd..5d973eb785abf 100644 --- a/app/code/Magento/MediaGalleryApi/Model/File/Command/DeleteByAssetIdInterface.php +++ b/app/code/Magento/MediaGalleryApi/Model/File/Command/DeleteByAssetIdInterface.php @@ -8,13 +8,13 @@ namespace Magento\MediaGalleryApi\Model\File\Command; /** - * Load Media Asset path from database by id and delete the file + * Remove the media asset file from the media storage * @api */ interface DeleteByAssetIdInterface { /** - * Delete the file by asset ID + * Remove the file of the media asset identified by the passed id from the media storage * * @param int $assetId * @return void diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/Directory/ExcludedTest.php b/app/code/Magento/MediaGalleryApi/Test/Unit/Model/Directory/BlacklistTest.php similarity index 72% rename from app/code/Magento/MediaGallery/Test/Unit/Model/Directory/ExcludedTest.php rename to app/code/Magento/MediaGalleryApi/Test/Unit/Model/Directory/BlacklistTest.php index ea9094b3ac1f4..3fe4ebd7cafcc 100644 --- a/app/code/Magento/MediaGallery/Test/Unit/Model/Directory/ExcludedTest.php +++ b/app/code/Magento/MediaGalleryApi/Test/Unit/Model/Directory/BlacklistTest.php @@ -5,19 +5,19 @@ */ declare(strict_types=1); -namespace Magento\MediaGallery\Test\Unit\Model\Directory; +namespace Magento\MediaGalleryApi\Test\Unit\Model\Directory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use PHPUnit\Framework\TestCase; -use Magento\MediaGallery\Model\Directory\Excluded; +use Magento\MediaGalleryApi\Model\Directory\Blacklist; /** * Test the Excluded model */ -class ExcludedTest extends TestCase +class BlacklistTest extends TestCase { /** - * @var Excluded + * @var Blacklist */ private $object; @@ -27,7 +27,7 @@ class ExcludedTest extends TestCase protected function setUp(): void { $this->object = (new ObjectManager($this))->getObject( - Excluded::class, + Blacklist::class, [ 'patterns' => [ 'tmp' => '/pub\/media\/tmp/', @@ -38,15 +38,15 @@ protected function setUp(): void } /** - * Test is directory path excluded + * Test if the directory path is blacklisted * * @param string $path * @param bool $isExcluded * @dataProvider pathsProvider */ - public function testIsExcluded(string $path, bool $isExcluded): void + public function testIsBlacklisted(string $path, bool $isExcluded): void { - $this->assertEquals($isExcluded, $this->object->isExcluded($path)); + $this->assertEquals($isExcluded, $this->object->isBlacklisted($path)); } /** diff --git a/app/code/Magento/MediaGalleryApi/etc/di.xml b/app/code/Magento/MediaGalleryApi/etc/di.xml new file mode 100644 index 0000000000000..7a00192cdd87b --- /dev/null +++ b/app/code/Magento/MediaGalleryApi/etc/di.xml @@ -0,0 +1,24 @@ + + + + + + + + /pub\/media\/captcha/ + /pub\/media\/catalog\/product/ + /pub\/media\/customer/ + /pub\/media\/downloadable/ + /pub\/media\/import/ + /pub\/media\/theme/ + /pub\/media\/theme_customization/ + /pub\/media\/tmp/ + + + + From e8eb3a9c474a38b129eace62e0af6a5f80d74b70 Mon Sep 17 00:00:00 2001 From: Sergii Ivashchenko Date: Wed, 1 Apr 2020 21:01:38 +0100 Subject: [PATCH 08/89] magento/magento2#27499: Corrected DI configuration --- app/code/Magento/MediaGallery/etc/di.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/code/Magento/MediaGallery/etc/di.xml b/app/code/Magento/MediaGallery/etc/di.xml index 2f402c30c5bc7..67ae43e667d17 100644 --- a/app/code/Magento/MediaGallery/etc/di.xml +++ b/app/code/Magento/MediaGallery/etc/di.xml @@ -19,6 +19,12 @@ + + + + + + From 6cd1dac700d2a2bc691c193a69f59aecbaf6cf08 Mon Sep 17 00:00:00 2001 From: Sergii Ivashchenko Date: Wed, 1 Apr 2020 21:43:19 +0100 Subject: [PATCH 09/89] magento/magento2#27536: Code review changes --- app/code/Magento/Catalog/composer.json | 1 - app/code/Magento/Catalog/etc/di.xml | 23 -- app/code/Magento/Catalog/etc/events.xml | 6 - app/code/Magento/Cms/composer.json | 1 - app/code/Magento/Cms/etc/di.xml | 21 -- app/code/Magento/Cms/etc/events.xml | 6 - ...ntentProcessor.php => UpdateRelations.php} | 12 +- app/code/Magento/MediaContent/etc/di.xml | 2 +- .../Api/ModelProcessorInterface.php | 26 -- .../Api/UpdateRelationsInterface.php | 34 ++ .../Model/ExtractAssetFromContent.php | 9 +- .../Magento/MediaContentCatalog/LICENSE.txt | 48 +++ .../MediaContentCatalog/LICENSE_AFL.txt | 48 +++ .../Observer}/Category.php | 32 +- .../Observer}/Product.php | 32 +- .../Magento/MediaContentCatalog/README.md | 13 + .../Magento/MediaContentCatalog/composer.json | 23 ++ .../Magento/MediaContentCatalog/etc/di.xml | 32 ++ .../MediaContentCatalog/etc/events.xml | 15 + .../MediaContentCatalog/etc/module.xml | 10 + .../MediaContentCatalog/registration.php | 10 + app/code/Magento/MediaContentCms/LICENSE.txt | 48 +++ .../Magento/MediaContentCms/LICENSE_AFL.txt | 48 +++ .../Observer}/Block.php | 32 +- .../Observer}/Page.php | 32 +- app/code/Magento/MediaContentCms/README.md | 13 + .../Magento/MediaContentCms/composer.json | 23 ++ app/code/Magento/MediaContentCms/etc/di.xml | 30 ++ .../Magento/MediaContentCms/etc/events.xml | 15 + .../Magento/MediaContentCms/etc/module.xml | 10 + .../Magento/MediaContentCms/registration.php | 10 + composer.json | 2 + composer.lock | 296 +++++++++--------- 33 files changed, 701 insertions(+), 262 deletions(-) rename app/code/Magento/MediaContent/Model/{ContentProcessor.php => UpdateRelations.php} (90%) delete mode 100644 app/code/Magento/MediaContentApi/Api/ModelProcessorInterface.php create mode 100644 app/code/Magento/MediaContentApi/Api/UpdateRelationsInterface.php rename app/code/Magento/{MediaContent => MediaContentApi}/Model/ExtractAssetFromContent.php (88%) create mode 100644 app/code/Magento/MediaContentCatalog/LICENSE.txt create mode 100644 app/code/Magento/MediaContentCatalog/LICENSE_AFL.txt rename app/code/Magento/{Catalog/Observer/MediaContent => MediaContentCatalog/Observer}/Category.php (57%) rename app/code/Magento/{Catalog/Observer/MediaContent => MediaContentCatalog/Observer}/Product.php (57%) create mode 100644 app/code/Magento/MediaContentCatalog/README.md create mode 100644 app/code/Magento/MediaContentCatalog/composer.json create mode 100644 app/code/Magento/MediaContentCatalog/etc/di.xml create mode 100644 app/code/Magento/MediaContentCatalog/etc/events.xml create mode 100644 app/code/Magento/MediaContentCatalog/etc/module.xml create mode 100644 app/code/Magento/MediaContentCatalog/registration.php create mode 100644 app/code/Magento/MediaContentCms/LICENSE.txt create mode 100644 app/code/Magento/MediaContentCms/LICENSE_AFL.txt rename app/code/Magento/{Cms/Observer/MediaContent => MediaContentCms/Observer}/Block.php (56%) rename app/code/Magento/{Cms/Observer/MediaContent => MediaContentCms/Observer}/Page.php (56%) create mode 100644 app/code/Magento/MediaContentCms/README.md create mode 100644 app/code/Magento/MediaContentCms/composer.json create mode 100644 app/code/Magento/MediaContentCms/etc/di.xml create mode 100644 app/code/Magento/MediaContentCms/etc/events.xml create mode 100644 app/code/Magento/MediaContentCms/etc/module.xml create mode 100644 app/code/Magento/MediaContentCms/registration.php diff --git a/app/code/Magento/Catalog/composer.json b/app/code/Magento/Catalog/composer.json index 660c496b5a8f0..8023634fa074d 100644 --- a/app/code/Magento/Catalog/composer.json +++ b/app/code/Magento/Catalog/composer.json @@ -20,7 +20,6 @@ "magento/module-directory": "*", "magento/module-eav": "*", "magento/module-indexer": "*", - "magento/module-media-content-api": "*", "magento/module-media-storage": "*", "magento/module-msrp": "*", "magento/module-page-cache": "*", diff --git a/app/code/Magento/Catalog/etc/di.xml b/app/code/Magento/Catalog/etc/di.xml index 5f8710fef0ac9..ff67989d337bb 100644 --- a/app/code/Magento/Catalog/etc/di.xml +++ b/app/code/Magento/Catalog/etc/di.xml @@ -1333,27 +1333,4 @@ - - - - image - description - - - - - - - description - short_description - - - - - - - /^\/?media\/(.*)/ - - - diff --git a/app/code/Magento/Catalog/etc/events.xml b/app/code/Magento/Catalog/etc/events.xml index bb28dc00b50f2..24186146c56f0 100644 --- a/app/code/Magento/Catalog/etc/events.xml +++ b/app/code/Magento/Catalog/etc/events.xml @@ -67,10 +67,4 @@ - - - - - - diff --git a/app/code/Magento/Cms/composer.json b/app/code/Magento/Cms/composer.json index c299ba63f9a96..91036d31fdc2b 100644 --- a/app/code/Magento/Cms/composer.json +++ b/app/code/Magento/Cms/composer.json @@ -10,7 +10,6 @@ "magento/module-backend": "*", "magento/module-catalog": "*", "magento/module-email": "*", - "magento/module-media-content-api": "*", "magento/module-media-storage": "*", "magento/module-store": "*", "magento/module-theme": "*", diff --git a/app/code/Magento/Cms/etc/di.xml b/app/code/Magento/Cms/etc/di.xml index 0f573047d098f..7fc8268eea5e0 100644 --- a/app/code/Magento/Cms/etc/di.xml +++ b/app/code/Magento/Cms/etc/di.xml @@ -243,25 +243,4 @@ - - - - content - - - - - - - content - - - - - - - /{{media url="?(.*?)"?}}/ - - - diff --git a/app/code/Magento/Cms/etc/events.xml b/app/code/Magento/Cms/etc/events.xml index a49e1638f0ab2..1ad847e215ccc 100644 --- a/app/code/Magento/Cms/etc/events.xml +++ b/app/code/Magento/Cms/etc/events.xml @@ -39,10 +39,4 @@ - - - - - - diff --git a/app/code/Magento/MediaContent/Model/ContentProcessor.php b/app/code/Magento/MediaContent/Model/UpdateRelations.php similarity index 90% rename from app/code/Magento/MediaContent/Model/ContentProcessor.php rename to app/code/Magento/MediaContent/Model/UpdateRelations.php index 2d8fc45506e89..1716739434591 100644 --- a/app/code/Magento/MediaContent/Model/ContentProcessor.php +++ b/app/code/Magento/MediaContent/Model/UpdateRelations.php @@ -11,18 +11,20 @@ use Magento\Framework\Exception\CouldNotSaveException; use Magento\Framework\Exception\IntegrationException; use Magento\MediaContentApi\Api\AssignAssetInterface; +use Magento\MediaContentApi\Api\ExtractAssetFromContentInterface; use Magento\MediaContentApi\Api\GetAssetsUsedInContentInterface; use Magento\MediaContentApi\Api\UnassignAssetInterface; +use Magento\MediaContentApi\Api\UpdateRelationsInterface; use Magento\MediaGalleryApi\Api\Data\AssetInterface; use Psr\Log\LoggerInterface; /** * Process relation managing between media asset and content: assign or unassign relation if exists. */ -class ContentProcessor +class UpdateRelations implements UpdateRelationsInterface { /** - * @var ExtractAssetFromContent + * @var ExtractAssetFromContentInterface */ private $extractAssetFromContent; @@ -47,16 +49,14 @@ class ContentProcessor private $logger; /** - * ContentProcessor constructor. - * - * @param ExtractAssetFromContent $extractAssetFromContent + * @param ExtractAssetFromContentInterface $extractAssetFromContent * @param AssignAssetInterface $assignAsset * @param GetAssetsUsedInContentInterface $getAssetsUsedInContent * @param UnassignAssetInterface $unassignAsset * @param LoggerInterface $logger */ public function __construct( - ExtractAssetFromContent $extractAssetFromContent, + ExtractAssetFromContentInterface $extractAssetFromContent, AssignAssetInterface $assignAsset, GetAssetsUsedInContentInterface $getAssetsUsedInContent, UnassignAssetInterface $unassignAsset, diff --git a/app/code/Magento/MediaContent/etc/di.xml b/app/code/Magento/MediaContent/etc/di.xml index 3a8839c3ca741..66be373535c6c 100644 --- a/app/code/Magento/MediaContent/etc/di.xml +++ b/app/code/Magento/MediaContent/etc/di.xml @@ -10,6 +10,6 @@ - + diff --git a/app/code/Magento/MediaContentApi/Api/ModelProcessorInterface.php b/app/code/Magento/MediaContentApi/Api/ModelProcessorInterface.php deleted file mode 100644 index be395656633db..0000000000000 --- a/app/code/Magento/MediaContentApi/Api/ModelProcessorInterface.php +++ /dev/null @@ -1,26 +0,0 @@ -" or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. \ No newline at end of file diff --git a/app/code/Magento/MediaContentCatalog/LICENSE_AFL.txt b/app/code/Magento/MediaContentCatalog/LICENSE_AFL.txt new file mode 100644 index 0000000000000..f39d641b18a19 --- /dev/null +++ b/app/code/Magento/MediaContentCatalog/LICENSE_AFL.txt @@ -0,0 +1,48 @@ + +Academic Free License ("AFL") v. 3.0 + +This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Academic Free License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor's reserved rights and remedies, in this Academic Free License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. diff --git a/app/code/Magento/Catalog/Observer/MediaContent/Category.php b/app/code/Magento/MediaContentCatalog/Observer/Category.php similarity index 57% rename from app/code/Magento/Catalog/Observer/MediaContent/Category.php rename to app/code/Magento/MediaContentCatalog/Observer/Category.php index 0044a7301e67b..83ad371426a47 100644 --- a/app/code/Magento/Catalog/Observer/MediaContent/Category.php +++ b/app/code/Magento/MediaContentCatalog/Observer/Category.php @@ -5,13 +5,13 @@ */ declare(strict_types=1); -namespace Magento\Catalog\Observer\MediaContent; +namespace Magento\MediaContentCatalog\Observer; use Magento\Catalog\Model\Category as CatalogCategory; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Model\AbstractModel; -use Magento\MediaContentApi\Api\ModelProcessorInterface; +use Magento\MediaContentApi\Api\UpdateRelationsInterface; /** * Observe the catalog_category_save_after event and run processing relation between category content and media asset. @@ -21,7 +21,7 @@ class Category implements ObserverInterface private const CONTENT_TYPE = 'catalog_category'; /** - * @var ModelProcessorInterface + * @var UpdateRelationsInterface */ private $processor; @@ -31,10 +31,10 @@ class Category implements ObserverInterface private $fields; /** - * @param ModelProcessorInterface $processor + * @param UpdateRelationsInterface $processor * @param array $fields */ - public function __construct(ModelProcessorInterface $processor, array $fields) + public function __construct(UpdateRelationsInterface $processor, array $fields) { $this->processor = $processor; $this->fields = $fields; @@ -50,7 +50,27 @@ public function execute(Observer $observer): void /** @var CatalogCategory $model */ $model = $observer->getEvent()->getData('category'); if ($model instanceof AbstractModel) { - $this->processor->execute(self::CONTENT_TYPE, $model, $this->fields); + $this->updateRelations($model); + } + } + + /** + * Update relations for the model + * + * @param AbstractModel $model + */ + private function updateRelations(AbstractModel $model): void + { + foreach ($this->fields as $field) { + if (!$model->dataHasChangedFor($field)) { + continue; + } + $this->processor->execute( + self::CONTENT_TYPE, + $field, + (string) $model->getId(), + (string) $model->getData($field) + ); } } } diff --git a/app/code/Magento/Catalog/Observer/MediaContent/Product.php b/app/code/Magento/MediaContentCatalog/Observer/Product.php similarity index 57% rename from app/code/Magento/Catalog/Observer/MediaContent/Product.php rename to app/code/Magento/MediaContentCatalog/Observer/Product.php index bb043712a44f2..2bbcd65cd790e 100644 --- a/app/code/Magento/Catalog/Observer/MediaContent/Product.php +++ b/app/code/Magento/MediaContentCatalog/Observer/Product.php @@ -5,13 +5,13 @@ */ declare(strict_types=1); -namespace Magento\Catalog\Observer\MediaContent; +namespace Magento\MediaContentCatalog\Observer; use Magento\Catalog\Model\Product as CatalogProduct; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Model\AbstractModel; -use Magento\MediaContentApi\Api\ModelProcessorInterface; +use Magento\MediaContentApi\Api\UpdateRelationsInterface; /** * Observe the catalog_product_save_after event and run processing relation between product content and media asset @@ -21,7 +21,7 @@ class Product implements ObserverInterface private const CONTENT_TYPE = 'catalog_product'; /** - * @var ModelProcessorInterface + * @var UpdateRelationsInterface */ private $processor; @@ -31,10 +31,10 @@ class Product implements ObserverInterface private $fields; /** - * @param ModelProcessorInterface $processor + * @param UpdateRelationsInterface $processor * @param array $fields */ - public function __construct(ModelProcessorInterface $processor, array $fields) + public function __construct(UpdateRelationsInterface $processor, array $fields) { $this->processor = $processor; $this->fields = $fields; @@ -50,7 +50,27 @@ public function execute(Observer $observer): void /** @var CatalogProduct $model */ $model = $observer->getEvent()->getData('product'); if ($model instanceof AbstractModel) { - $this->processor->execute(self::CONTENT_TYPE, $model, $this->fields); + $this->updateRelations($model); + } + } + + /** + * Update relations for the model + * + * @param AbstractModel $model + */ + private function updateRelations(AbstractModel $model): void + { + foreach ($this->fields as $field) { + if (!$model->dataHasChangedFor($field)) { + continue; + } + $this->processor->execute( + self::CONTENT_TYPE, + $field, + (string) $model->getId(), + (string) $model->getData($field) + ); } } } diff --git a/app/code/Magento/MediaContentCatalog/README.md b/app/code/Magento/MediaContentCatalog/README.md new file mode 100644 index 0000000000000..359126a8b7a13 --- /dev/null +++ b/app/code/Magento/MediaContentCatalog/README.md @@ -0,0 +1,13 @@ +# Magento_MediaContentCatalog module + +The Magento_MediaContentCatalog provides the implementation of MediaContent functionality for Magento_Catalog module + +## Extensibility + +Extension developers can interact with the Magento_MediaContent module. For more information about the Magento extension mechanism, see [Magento plug-ins](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/plugins.html). + +[The Magento dependency injection mechanism](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html) enables you to override the functionality of the Magento_MediaContent module. + +## Additional information + +For information about significant changes in patch releases, see [2.3.x Release information](https://devdocs.magento.com/guides/v2.3/release-notes/bk-release-notes.html). diff --git a/app/code/Magento/MediaContentCatalog/composer.json b/app/code/Magento/MediaContentCatalog/composer.json new file mode 100644 index 0000000000000..9efe7aadba041 --- /dev/null +++ b/app/code/Magento/MediaContentCatalog/composer.json @@ -0,0 +1,23 @@ +{ + "name": "magento/module-media-content-catalog", + "description": "Magento module provides the implementation of MediaContent functionality for Magento_Catalog module", + "require": { + "php": "~7.1.3||~7.2.0||~7.3.0", + "magento/module-media-content-api": "*", + "magento/module-catalog": "*", + "magento/framework": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\MediaContentCatalog\\": "" + } + } +} diff --git a/app/code/Magento/MediaContentCatalog/etc/di.xml b/app/code/Magento/MediaContentCatalog/etc/di.xml new file mode 100644 index 0000000000000..d39adaa725b5a --- /dev/null +++ b/app/code/Magento/MediaContentCatalog/etc/di.xml @@ -0,0 +1,32 @@ + + + + + + + image + description + + + + + + + description + short_description + + + + + + + /^\/?media\/(.*)/ + + + + diff --git a/app/code/Magento/MediaContentCatalog/etc/events.xml b/app/code/Magento/MediaContentCatalog/etc/events.xml new file mode 100644 index 0000000000000..f68d66eb3cc40 --- /dev/null +++ b/app/code/Magento/MediaContentCatalog/etc/events.xml @@ -0,0 +1,15 @@ + + + + + + + + + + diff --git a/app/code/Magento/MediaContentCatalog/etc/module.xml b/app/code/Magento/MediaContentCatalog/etc/module.xml new file mode 100644 index 0000000000000..9b863edd57e5e --- /dev/null +++ b/app/code/Magento/MediaContentCatalog/etc/module.xml @@ -0,0 +1,10 @@ + + + + + diff --git a/app/code/Magento/MediaContentCatalog/registration.php b/app/code/Magento/MediaContentCatalog/registration.php new file mode 100644 index 0000000000000..e954285921cba --- /dev/null +++ b/app/code/Magento/MediaContentCatalog/registration.php @@ -0,0 +1,10 @@ +" or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. \ No newline at end of file diff --git a/app/code/Magento/MediaContentCms/LICENSE_AFL.txt b/app/code/Magento/MediaContentCms/LICENSE_AFL.txt new file mode 100644 index 0000000000000..f39d641b18a19 --- /dev/null +++ b/app/code/Magento/MediaContentCms/LICENSE_AFL.txt @@ -0,0 +1,48 @@ + +Academic Free License ("AFL") v. 3.0 + +This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Academic Free License version 3.0 + + 1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + 1. to reproduce the Original Work in copies, either alone or as part of a collective work; + + 2. to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + 3. to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor's reserved rights and remedies, in this Academic Free License; + + 4. to perform the Original Work publicly; and + + 5. to display the Original Work publicly. + + 2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + + 3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + + 4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + + 5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + + 6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + + 7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + + 8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + + 9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + + 10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + + 11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + + 12. Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + + 13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + + 14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + + 15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + + 16. Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. diff --git a/app/code/Magento/Cms/Observer/MediaContent/Block.php b/app/code/Magento/MediaContentCms/Observer/Block.php similarity index 56% rename from app/code/Magento/Cms/Observer/MediaContent/Block.php rename to app/code/Magento/MediaContentCms/Observer/Block.php index 80fe854531586..106f42fcc0b7b 100644 --- a/app/code/Magento/Cms/Observer/MediaContent/Block.php +++ b/app/code/Magento/MediaContentCms/Observer/Block.php @@ -5,13 +5,13 @@ */ declare(strict_types=1); -namespace Magento\Cms\Observer\MediaContent; +namespace Magento\MediaContentCms\Observer; use Magento\Cms\Block\Block as CmsBlock; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Model\AbstractModel; -use Magento\MediaContentApi\Api\ModelProcessorInterface; +use Magento\MediaContentApi\Api\UpdateRelationsInterface; /** * Observe cms_block_save_after event and run processing relation between cms block content and media asset @@ -21,7 +21,7 @@ class Block implements ObserverInterface private const CONTENT_TYPE = 'cms_block'; /** - * @var ModelProcessorInterface + * @var UpdateRelationsInterface */ private $processor; @@ -31,10 +31,10 @@ class Block implements ObserverInterface private $fields; /** - * @param ModelProcessorInterface $processor + * @param UpdateRelationsInterface $processor * @param array $fields */ - public function __construct(ModelProcessorInterface $processor, array $fields) + public function __construct(UpdateRelationsInterface $processor, array $fields) { $this->processor = $processor; $this->fields = $fields; @@ -50,7 +50,27 @@ public function execute(Observer $observer): void /** @var CmsBlock $model */ $model = $observer->getEvent()->getData('object'); if ($model instanceof AbstractModel) { - $this->processor->execute(self::CONTENT_TYPE, $model, $this->fields); + $this->updateRelations($model); + } + } + + /** + * Update relations for the model + * + * @param AbstractModel $model + */ + private function updateRelations(AbstractModel $model): void + { + foreach ($this->fields as $field) { + if (!$model->dataHasChangedFor($field)) { + continue; + } + $this->processor->execute( + self::CONTENT_TYPE, + $field, + (string) $model->getId(), + (string) $model->getData($field) + ); } } } diff --git a/app/code/Magento/Cms/Observer/MediaContent/Page.php b/app/code/Magento/MediaContentCms/Observer/Page.php similarity index 56% rename from app/code/Magento/Cms/Observer/MediaContent/Page.php rename to app/code/Magento/MediaContentCms/Observer/Page.php index cc4fe14990a86..8dd80840508a8 100644 --- a/app/code/Magento/Cms/Observer/MediaContent/Page.php +++ b/app/code/Magento/MediaContentCms/Observer/Page.php @@ -5,13 +5,13 @@ */ declare(strict_types=1); -namespace Magento\Cms\Observer\MediaContent; +namespace Magento\MediaContentCms\Observer; use Magento\Cms\Model\Page as CmsPage; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; use Magento\Framework\Model\AbstractModel; -use Magento\MediaContentApi\Api\ModelProcessorInterface; +use Magento\MediaContentApi\Api\UpdateRelationsInterface; /** * Observe cms_page_save_after event and run processing relation between cms page content and media asset. @@ -21,7 +21,7 @@ class Page implements ObserverInterface private const CONTENT_TYPE = 'cms_page'; /** - * @var ModelProcessorInterface + * @var UpdateRelationsInterface */ private $processor; @@ -31,10 +31,10 @@ class Page implements ObserverInterface private $fields; /** - * @param ModelProcessorInterface $processor + * @param UpdateRelationsInterface $processor * @param array $fields */ - public function __construct(ModelProcessorInterface $processor, array $fields) + public function __construct(UpdateRelationsInterface $processor, array $fields) { $this->processor = $processor; $this->fields = $fields; @@ -50,7 +50,27 @@ public function execute(Observer $observer): void /** @var CmsPage $model */ $model = $observer->getEvent()->getData('object'); if ($model instanceof AbstractModel) { - $this->processor->execute(self::CONTENT_TYPE, $model, $this->fields); + $this->updateRelations($model); + } + } + + /** + * Update relations for the model + * + * @param AbstractModel $model + */ + private function updateRelations(AbstractModel $model): void + { + foreach ($this->fields as $field) { + if (!$model->dataHasChangedFor($field)) { + continue; + } + $this->processor->execute( + self::CONTENT_TYPE, + $field, + (string) $model->getId(), + (string) $model->getData($field) + ); } } } diff --git a/app/code/Magento/MediaContentCms/README.md b/app/code/Magento/MediaContentCms/README.md new file mode 100644 index 0000000000000..32b0fdc2bbd2f --- /dev/null +++ b/app/code/Magento/MediaContentCms/README.md @@ -0,0 +1,13 @@ +# Magento_MediaContentCms module + +The Magento_MediaContentCms provides the implementation of MediaContent functionality for Magento_Cms module + +## Extensibility + +Extension developers can interact with the Magento_MediaContent module. For more information about the Magento extension mechanism, see [Magento plug-ins](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/plugins.html). + +[The Magento dependency injection mechanism](https://devdocs.magento.com/guides/v2.3/extension-dev-guide/depend-inj.html) enables you to override the functionality of the Magento_MediaContent module. + +## Additional information + +For information about significant changes in patch releases, see [2.3.x Release information](https://devdocs.magento.com/guides/v2.3/release-notes/bk-release-notes.html). diff --git a/app/code/Magento/MediaContentCms/composer.json b/app/code/Magento/MediaContentCms/composer.json new file mode 100644 index 0000000000000..318027d87a44b --- /dev/null +++ b/app/code/Magento/MediaContentCms/composer.json @@ -0,0 +1,23 @@ +{ + "name": "magento/module-media-content-cms", + "description": "Magento module provides the implementation of MediaContent functionality for Magento_Cms module", + "require": { + "php": "~7.1.3||~7.2.0||~7.3.0", + "magento/module-media-content-api": "*", + "magento/module-cms": "*", + "magento/framework": "*" + }, + "type": "magento2-module", + "license": [ + "OSL-3.0", + "AFL-3.0" + ], + "autoload": { + "files": [ + "registration.php" + ], + "psr-4": { + "Magento\\MediaContentApi\\": "" + } + } +} diff --git a/app/code/Magento/MediaContentCms/etc/di.xml b/app/code/Magento/MediaContentCms/etc/di.xml new file mode 100644 index 0000000000000..bccb8084f5050 --- /dev/null +++ b/app/code/Magento/MediaContentCms/etc/di.xml @@ -0,0 +1,30 @@ + + + + + + + content + + + + + + + content + + + + + + + /{{media url="?(.*?)"?}}/ + + + + diff --git a/app/code/Magento/MediaContentCms/etc/events.xml b/app/code/Magento/MediaContentCms/etc/events.xml new file mode 100644 index 0000000000000..7e9abe3bf19c4 --- /dev/null +++ b/app/code/Magento/MediaContentCms/etc/events.xml @@ -0,0 +1,15 @@ + + + + + + + + + + diff --git a/app/code/Magento/MediaContentCms/etc/module.xml b/app/code/Magento/MediaContentCms/etc/module.xml new file mode 100644 index 0000000000000..7278f82890b42 --- /dev/null +++ b/app/code/Magento/MediaContentCms/etc/module.xml @@ -0,0 +1,10 @@ + + + + + diff --git a/app/code/Magento/MediaContentCms/registration.php b/app/code/Magento/MediaContentCms/registration.php new file mode 100644 index 0000000000000..b231ce3c6f3de --- /dev/null +++ b/app/code/Magento/MediaContentCms/registration.php @@ -0,0 +1,10 @@ + Date: Wed, 1 Apr 2020 21:48:25 +0100 Subject: [PATCH 10/89] magento/magento2#27536: Code review changes --- .../MediaContent/Model/ModelProcessor.php | 54 ------------------- .../Model/ExtractAssetFromContent.php | 5 ++ 2 files changed, 5 insertions(+), 54 deletions(-) delete mode 100644 app/code/Magento/MediaContent/Model/ModelProcessor.php diff --git a/app/code/Magento/MediaContent/Model/ModelProcessor.php b/app/code/Magento/MediaContent/Model/ModelProcessor.php deleted file mode 100644 index 8e3a3ebf168d6..0000000000000 --- a/app/code/Magento/MediaContent/Model/ModelProcessor.php +++ /dev/null @@ -1,54 +0,0 @@ -contentProcessor = $contentProcessor; - } - - /** - * Save relations for content within an AbstractModel instance - * - * @param string $type - * @param AbstractModel $model - * @param array $fields - */ - public function execute(string $type, AbstractModel $model, array $fields): void - { - foreach ($fields as $field) { - if (!$model->dataHasChangedFor($field)) { - continue; - } - $this->contentProcessor->execute( - $type, - $field, - (string) $model->getId(), - (string) $model->getData($field) - ); - } - } -} diff --git a/app/code/Magento/MediaContentApi/Model/ExtractAssetFromContent.php b/app/code/Magento/MediaContentApi/Model/ExtractAssetFromContent.php index c307fa88a2e5e..57cef519f1f2a 100644 --- a/app/code/Magento/MediaContentApi/Model/ExtractAssetFromContent.php +++ b/app/code/Magento/MediaContentApi/Model/ExtractAssetFromContent.php @@ -62,7 +62,12 @@ public function execute(string $content): array $paths = []; foreach ($this->searchPatterns as $pattern) { + if (empty($pattern)) { + continue; + } + preg_match_all($pattern, $content, $matches, PREG_PATTERN_ORDER); + if (!empty($matches[1])) { $paths += array_unique($matches[1]); } From 23fb9143030cce13af7e7302c529f806200c0464 Mon Sep 17 00:00:00 2001 From: Stanislav Idolov Date: Thu, 2 Apr 2020 16:18:15 -0500 Subject: [PATCH 11/89] magento/magento2#27536: Review fixes --- .../MediaContentCatalog/Observer/Category.php | 30 ++++++------------ .../MediaContentCatalog/Observer/Product.php | 31 +++++++------------ .../MediaContentCms/Observer/Block.php | 30 ++++++------------ .../Magento/MediaContentCms/Observer/Page.php | 30 ++++++------------ 4 files changed, 41 insertions(+), 80 deletions(-) diff --git a/app/code/Magento/MediaContentCatalog/Observer/Category.php b/app/code/Magento/MediaContentCatalog/Observer/Category.php index 83ad371426a47..58efd114f5782 100644 --- a/app/code/Magento/MediaContentCatalog/Observer/Category.php +++ b/app/code/Magento/MediaContentCatalog/Observer/Category.php @@ -50,27 +50,17 @@ public function execute(Observer $observer): void /** @var CatalogCategory $model */ $model = $observer->getEvent()->getData('category'); if ($model instanceof AbstractModel) { - $this->updateRelations($model); - } - } - - /** - * Update relations for the model - * - * @param AbstractModel $model - */ - private function updateRelations(AbstractModel $model): void - { - foreach ($this->fields as $field) { - if (!$model->dataHasChangedFor($field)) { - continue; + foreach ($this->fields as $field) { + if (!$model->dataHasChangedFor($field)) { + continue; + } + $this->processor->execute( + self::CONTENT_TYPE, + $field, + (string) $model->getId(), + (string) $model->getData($field) + ); } - $this->processor->execute( - self::CONTENT_TYPE, - $field, - (string) $model->getId(), - (string) $model->getData($field) - ); } } } diff --git a/app/code/Magento/MediaContentCatalog/Observer/Product.php b/app/code/Magento/MediaContentCatalog/Observer/Product.php index 2bbcd65cd790e..9349d5ff90be0 100644 --- a/app/code/Magento/MediaContentCatalog/Observer/Product.php +++ b/app/code/Magento/MediaContentCatalog/Observer/Product.php @@ -49,28 +49,19 @@ public function execute(Observer $observer): void { /** @var CatalogProduct $model */ $model = $observer->getEvent()->getData('product'); - if ($model instanceof AbstractModel) { - $this->updateRelations($model); - } - } - /** - * Update relations for the model - * - * @param AbstractModel $model - */ - private function updateRelations(AbstractModel $model): void - { - foreach ($this->fields as $field) { - if (!$model->dataHasChangedFor($field)) { - continue; + if ($model instanceof AbstractModel) { + foreach ($this->fields as $field) { + if (!$model->dataHasChangedFor($field)) { + continue; + } + $this->processor->execute( + self::CONTENT_TYPE, + $field, + (string) $model->getId(), + (string) $model->getData($field) + ); } - $this->processor->execute( - self::CONTENT_TYPE, - $field, - (string) $model->getId(), - (string) $model->getData($field) - ); } } } diff --git a/app/code/Magento/MediaContentCms/Observer/Block.php b/app/code/Magento/MediaContentCms/Observer/Block.php index 106f42fcc0b7b..9d5d24d422a78 100644 --- a/app/code/Magento/MediaContentCms/Observer/Block.php +++ b/app/code/Magento/MediaContentCms/Observer/Block.php @@ -50,27 +50,17 @@ public function execute(Observer $observer): void /** @var CmsBlock $model */ $model = $observer->getEvent()->getData('object'); if ($model instanceof AbstractModel) { - $this->updateRelations($model); - } - } - - /** - * Update relations for the model - * - * @param AbstractModel $model - */ - private function updateRelations(AbstractModel $model): void - { - foreach ($this->fields as $field) { - if (!$model->dataHasChangedFor($field)) { - continue; + foreach ($this->fields as $field) { + if (!$model->dataHasChangedFor($field)) { + continue; + } + $this->processor->execute( + self::CONTENT_TYPE, + $field, + (string) $model->getId(), + (string) $model->getData($field) + ); } - $this->processor->execute( - self::CONTENT_TYPE, - $field, - (string) $model->getId(), - (string) $model->getData($field) - ); } } } diff --git a/app/code/Magento/MediaContentCms/Observer/Page.php b/app/code/Magento/MediaContentCms/Observer/Page.php index 8dd80840508a8..111b4478a9888 100644 --- a/app/code/Magento/MediaContentCms/Observer/Page.php +++ b/app/code/Magento/MediaContentCms/Observer/Page.php @@ -50,27 +50,17 @@ public function execute(Observer $observer): void /** @var CmsPage $model */ $model = $observer->getEvent()->getData('object'); if ($model instanceof AbstractModel) { - $this->updateRelations($model); - } - } - - /** - * Update relations for the model - * - * @param AbstractModel $model - */ - private function updateRelations(AbstractModel $model): void - { - foreach ($this->fields as $field) { - if (!$model->dataHasChangedFor($field)) { - continue; + foreach ($this->fields as $field) { + if (!$model->dataHasChangedFor($field)) { + continue; + } + $this->processor->execute( + self::CONTENT_TYPE, + $field, + (string) $model->getId(), + (string) $model->getData($field) + ); } - $this->processor->execute( - self::CONTENT_TYPE, - $field, - (string) $model->getId(), - (string) $model->getData($field) - ); } } } From f250d88ed34b55382e56afcffd954384b8537051 Mon Sep 17 00:00:00 2001 From: Stanislav Idolov Date: Thu, 2 Apr 2020 21:17:18 -0500 Subject: [PATCH 12/89] magento/magento2#27536: Correct modules dependencies --- app/code/Magento/Cms/etc/module.xml | 1 + app/code/Magento/MediaContentCatalog/etc/di.xml | 2 +- app/code/Magento/MediaContentCms/etc/di.xml | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/app/code/Magento/Cms/etc/module.xml b/app/code/Magento/Cms/etc/module.xml index d3fc2846217d9..ff378a0312e56 100644 --- a/app/code/Magento/Cms/etc/module.xml +++ b/app/code/Magento/Cms/etc/module.xml @@ -11,6 +11,7 @@ + diff --git a/app/code/Magento/MediaContentCatalog/etc/di.xml b/app/code/Magento/MediaContentCatalog/etc/di.xml index d39adaa725b5a..a9cd9ac8bd796 100644 --- a/app/code/Magento/MediaContentCatalog/etc/di.xml +++ b/app/code/Magento/MediaContentCatalog/etc/di.xml @@ -22,7 +22,7 @@ - + /^\/?media\/(.*)/ diff --git a/app/code/Magento/MediaContentCms/etc/di.xml b/app/code/Magento/MediaContentCms/etc/di.xml index bccb8084f5050..165c295c28208 100644 --- a/app/code/Magento/MediaContentCms/etc/di.xml +++ b/app/code/Magento/MediaContentCms/etc/di.xml @@ -20,7 +20,7 @@ - + /{{media url="?(.*?)"?}}/ From ef94acbaf0010f6cc7c7a189730e9fc85d87aa99 Mon Sep 17 00:00:00 2001 From: Stanislav Idolov Date: Thu, 2 Apr 2020 21:18:29 -0500 Subject: [PATCH 13/89] magento/magento2#27536: Correct interface preference --- app/code/Magento/MediaContent/etc/di.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/Magento/MediaContent/etc/di.xml b/app/code/Magento/MediaContent/etc/di.xml index 66be373535c6c..98031f32211d4 100644 --- a/app/code/Magento/MediaContent/etc/di.xml +++ b/app/code/Magento/MediaContent/etc/di.xml @@ -10,6 +10,6 @@ - + From e671db30c6d593301b8817f34840d0c9e20672e2 Mon Sep 17 00:00:00 2001 From: Volodymyr Zaets Date: Thu, 2 Apr 2020 21:36:45 -0500 Subject: [PATCH 14/89] - Rename interface - Refactoring - Test coverage --- .../Model/Directory/IsBlacklisted.php} | 8 +- .../Model/Directory/IsBlacklistedTest.php} | 14 ++-- app/code/Magento/MediaGallery/etc/di.xml | 17 ++++ ...terface.php => IsBlacklistedInterface.php} | 4 +- app/code/Magento/MediaGalleryApi/etc/di.xml | 24 ------ .../Directory/Command/DeleteByPathTest.php | 83 +++++++++++++++++++ 6 files changed, 114 insertions(+), 36 deletions(-) rename app/code/Magento/{MediaGalleryApi/Model/Directory/Blacklist.php => MediaGallery/Model/Directory/IsBlacklisted.php} (82%) rename app/code/Magento/{MediaGalleryApi/Test/Unit/Model/Directory/BlacklistTest.php => MediaGallery/Test/Unit/Model/Directory/IsBlacklistedTest.php} (75%) rename app/code/Magento/MediaGalleryApi/Model/Directory/{BlacklistInterface.php => IsBlacklistedInterface.php} (84%) delete mode 100644 app/code/Magento/MediaGalleryApi/etc/di.xml create mode 100644 dev/tests/integration/testsuite/Magento/MediaGallery/Model/Directory/Command/DeleteByPathTest.php diff --git a/app/code/Magento/MediaGalleryApi/Model/Directory/Blacklist.php b/app/code/Magento/MediaGallery/Model/Directory/IsBlacklisted.php similarity index 82% rename from app/code/Magento/MediaGalleryApi/Model/Directory/Blacklist.php rename to app/code/Magento/MediaGallery/Model/Directory/IsBlacklisted.php index fc6d73550f0fa..312d5ab3dcf8a 100644 --- a/app/code/Magento/MediaGalleryApi/Model/Directory/Blacklist.php +++ b/app/code/Magento/MediaGallery/Model/Directory/IsBlacklisted.php @@ -5,7 +5,9 @@ */ declare(strict_types=1); -namespace Magento\MediaGalleryApi\Model\Directory; +namespace Magento\MediaGallery\Model\Directory; + +use Magento\MediaGalleryApi\Model\Directory\IsBlacklistedInterface; /** * Directories blacklisted for media gallery. This class should be used for DI configuration. @@ -14,7 +16,7 @@ * * @api */ -class Blacklist implements BlacklistInterface +class IsBlacklisted implements IsBlacklistedInterface { /** * @var array @@ -36,7 +38,7 @@ public function __construct( * @param string $path * @return bool */ - public function isBlacklisted(string $path): bool + public function execute(string $path): bool { foreach ($this->patterns as $pattern) { if (empty($pattern)) { diff --git a/app/code/Magento/MediaGalleryApi/Test/Unit/Model/Directory/BlacklistTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/Directory/IsBlacklistedTest.php similarity index 75% rename from app/code/Magento/MediaGalleryApi/Test/Unit/Model/Directory/BlacklistTest.php rename to app/code/Magento/MediaGallery/Test/Unit/Model/Directory/IsBlacklistedTest.php index 3fe4ebd7cafcc..4742db34cfcab 100644 --- a/app/code/Magento/MediaGalleryApi/Test/Unit/Model/Directory/BlacklistTest.php +++ b/app/code/Magento/MediaGallery/Test/Unit/Model/Directory/IsBlacklistedTest.php @@ -5,19 +5,19 @@ */ declare(strict_types=1); -namespace Magento\MediaGalleryApi\Test\Unit\Model\Directory; +namespace Magento\MediaGallery\Test\Unit\Model\Directory; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use PHPUnit\Framework\TestCase; -use Magento\MediaGalleryApi\Model\Directory\Blacklist; +use Magento\MediaGallery\Model\Directory\IsBlacklisted; /** * Test the Excluded model */ -class BlacklistTest extends TestCase +class IsBlacklistedTest extends TestCase { /** - * @var Blacklist + * @var */ private $object; @@ -27,7 +27,7 @@ class BlacklistTest extends TestCase protected function setUp(): void { $this->object = (new ObjectManager($this))->getObject( - Blacklist::class, + IsBlacklisted::class, [ 'patterns' => [ 'tmp' => '/pub\/media\/tmp/', @@ -44,9 +44,9 @@ protected function setUp(): void * @param bool $isExcluded * @dataProvider pathsProvider */ - public function testIsBlacklisted(string $path, bool $isExcluded): void + public function testExecute(string $path, bool $isExcluded): void { - $this->assertEquals($isExcluded, $this->object->isBlacklisted($path)); + $this->assertEquals($isExcluded, $this->object->execute($path)); } /** diff --git a/app/code/Magento/MediaGallery/etc/di.xml b/app/code/Magento/MediaGallery/etc/di.xml index 67ae43e667d17..ea05da9498607 100644 --- a/app/code/Magento/MediaGallery/etc/di.xml +++ b/app/code/Magento/MediaGallery/etc/di.xml @@ -23,8 +23,25 @@ + + + + + + + /pub\/media\/captcha/ + /pub\/media\/catalog\/product/ + /pub\/media\/customer/ + /pub\/media\/downloadable/ + /pub\/media\/import/ + /pub\/media\/theme/ + /pub\/media\/theme_customization/ + /pub\/media\/tmp/ + + + diff --git a/app/code/Magento/MediaGalleryApi/Model/Directory/BlacklistInterface.php b/app/code/Magento/MediaGalleryApi/Model/Directory/IsBlacklistedInterface.php similarity index 84% rename from app/code/Magento/MediaGalleryApi/Model/Directory/BlacklistInterface.php rename to app/code/Magento/MediaGalleryApi/Model/Directory/IsBlacklistedInterface.php index f75af40fa72a7..bc01bcdc77912 100644 --- a/app/code/Magento/MediaGalleryApi/Model/Directory/BlacklistInterface.php +++ b/app/code/Magento/MediaGalleryApi/Model/Directory/IsBlacklistedInterface.php @@ -11,7 +11,7 @@ * Directory paths that are reserved by system and not be included in the media gallery * @api */ -interface BlacklistInterface +interface IsBlacklistedInterface { /** * Check if the path is excluded from displaying and processing in the media gallery @@ -19,5 +19,5 @@ interface BlacklistInterface * @param string $path * @return bool */ - public function isBlacklisted(string $path): bool; + public function execute(string $path): bool; } diff --git a/app/code/Magento/MediaGalleryApi/etc/di.xml b/app/code/Magento/MediaGalleryApi/etc/di.xml deleted file mode 100644 index 7a00192cdd87b..0000000000000 --- a/app/code/Magento/MediaGalleryApi/etc/di.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - /pub\/media\/captcha/ - /pub\/media\/catalog\/product/ - /pub\/media\/customer/ - /pub\/media\/downloadable/ - /pub\/media\/import/ - /pub\/media\/theme/ - /pub\/media\/theme_customization/ - /pub\/media\/tmp/ - - - - diff --git a/dev/tests/integration/testsuite/Magento/MediaGallery/Model/Directory/Command/DeleteByPathTest.php b/dev/tests/integration/testsuite/Magento/MediaGallery/Model/Directory/Command/DeleteByPathTest.php new file mode 100644 index 0000000000000..27da09e38889d --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/MediaGallery/Model/Directory/Command/DeleteByPathTest.php @@ -0,0 +1,83 @@ +get(Filesystem::class) + ->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath(); + mkdir(self::$_mediaPath . self::TEST_DIRECTORY_NAME); + } + + /** + * @inheritdoc + */ + public function setUp() + { + $this->deleteByPath = Bootstrap::getObjectManager()->create(DeleteByPathInterface::class); + } + + /** + * @return void + * @throws \Magento\Framework\Exception\CouldNotDeleteException + */ + public function testDeleteDirectoryWithExistingDirectoryAndCorrectAbsolutePath(): void + { + $fullPath = self::$_mediaPath . self::TEST_DIRECTORY_NAME; + $this->assertFileExists($fullPath); + $this->deleteByPath->execute(self::TEST_DIRECTORY_NAME); + $this->assertFileNotExists($fullPath); + } + + /** + * @return void + * @throws \Magento\Framework\Exception\CouldNotDeleteException + * @expectedException \Magento\Framework\Exception\CouldNotDeleteException + */ + public function testDeleteDirectoryWithRelativePathUnderMediaFolder(): void + { + $this->deleteByPath->execute('../../pub/media'); + } + + /** + * @return void + * @throws \Magento\Framework\Exception\CouldNotDeleteException + * @expectedException \Magento\Framework\Exception\CouldNotDeleteException + */ + public function testDeleteDirectoryThatIsNotAllowed(): void + { + $this->deleteByPath->execute('theme'); + } +} From ad24d872b562871825db16bd1f545331f8f4f37d Mon Sep 17 00:00:00 2001 From: Slava Mankivski Date: Fri, 3 Apr 2020 00:29:11 -0500 Subject: [PATCH 15/89] Updated sequence for CMS --- app/code/Magento/Cms/etc/module.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/app/code/Magento/Cms/etc/module.xml b/app/code/Magento/Cms/etc/module.xml index ff378a0312e56..880ce5b7075e6 100644 --- a/app/code/Magento/Cms/etc/module.xml +++ b/app/code/Magento/Cms/etc/module.xml @@ -12,6 +12,7 @@ + From 83e7e37e2e2bef0bfffa67814adbb7bd3557805d Mon Sep 17 00:00:00 2001 From: Volodymyr Zaets Date: Fri, 3 Apr 2020 03:13:00 -0500 Subject: [PATCH 16/89] Test coverage --- .../Directory/Command/CreateByPathTest.php | 95 ++++++++++++++++++ .../Directory/Command/DeleteByPathTest.php | 21 +++- .../File/Command/DeleteByAssertIdTest.php | 99 +++++++++++++++++++ .../MediaGallery/_files/media_asset.php | 29 ++++++ 4 files changed, 241 insertions(+), 3 deletions(-) create mode 100644 dev/tests/integration/testsuite/Magento/MediaGallery/Model/Directory/Command/CreateByPathTest.php create mode 100644 dev/tests/integration/testsuite/Magento/MediaGallery/Model/File/Command/DeleteByAssertIdTest.php create mode 100644 dev/tests/integration/testsuite/Magento/MediaGallery/_files/media_asset.php diff --git a/dev/tests/integration/testsuite/Magento/MediaGallery/Model/Directory/Command/CreateByPathTest.php b/dev/tests/integration/testsuite/Magento/MediaGallery/Model/Directory/Command/CreateByPathTest.php new file mode 100644 index 0000000000000..84861a5375713 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/MediaGallery/Model/Directory/Command/CreateByPathTest.php @@ -0,0 +1,95 @@ +get(Filesystem::class) + ->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath(); + } + + /** + * @inheritdoc + */ + public function setUp() + { + $this->createByPath = Bootstrap::getObjectManager()->create(CreateByPathInterface::class); + } + + /** + * @return void + * @throws \Magento\Framework\Exception\CouldNotSaveException + */ + public function testCreateDirectory(): void + { + $fullPath = self::$_mediaPath . self::TEST_DIRECTORY_NAME; + $this->createByPath->execute('', self::TEST_DIRECTORY_NAME); + $this->assertFileExists($fullPath); + } + + /** + * @return void + * @throws \Magento\Framework\Exception\CouldNotSaveException + * @expectedException \Magento\Framework\Exception\CouldNotSaveException + */ + public function testCreateDirectoryThatAlreadyExist(): void + { + $this->createByPath->execute('', self::TEST_DIRECTORY_NAME); + } + + /** + * @return void + * @throws \Magento\Framework\Exception\CouldNotSaveException + * @expectedException \Magento\Framework\Exception\CouldNotSaveException + */ + public function testCreateDirectoryWithRelativePath(): void + { + $this->createByPath->execute('../../pub/', self::TEST_DIRECTORY_NAME); + } + + /** + * @throws \Magento\Framework\Exception\FileSystemException + */ + public static function tearDownAfterClass() + { + $filesystem = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() + ->get(\Magento\Framework\Filesystem::class); + /** @var \Magento\Framework\Filesystem\Directory\WriteInterface $directory */ + $directory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA); + if ($directory->isExist(self::TEST_DIRECTORY_NAME)) { + $directory->delete(self::TEST_DIRECTORY_NAME); + } + } +} diff --git a/dev/tests/integration/testsuite/Magento/MediaGallery/Model/Directory/Command/DeleteByPathTest.php b/dev/tests/integration/testsuite/Magento/MediaGallery/Model/Directory/Command/DeleteByPathTest.php index 27da09e38889d..282dbe2ed11d0 100644 --- a/dev/tests/integration/testsuite/Magento/MediaGallery/Model/Directory/Command/DeleteByPathTest.php +++ b/dev/tests/integration/testsuite/Magento/MediaGallery/Model/Directory/Command/DeleteByPathTest.php @@ -36,9 +36,10 @@ class DeleteByPathTest extends \PHPUnit\Framework\TestCase */ public static function setUpBeforeClass() { - self::$_mediaPath = Bootstrap::getObjectManager()->get(Filesystem::class) - ->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath(); - mkdir(self::$_mediaPath . self::TEST_DIRECTORY_NAME); + /** @var \Magento\Framework\Filesystem\Directory\WriteInterface $directory */ + $directory = Bootstrap::getObjectManager()->get(Filesystem::class)->getDirectoryWrite(DirectoryList::MEDIA); + self::$_mediaPath = $directory->getAbsolutePath(); + $directory->create(self::TEST_DIRECTORY_NAME); } /** @@ -80,4 +81,18 @@ public function testDeleteDirectoryThatIsNotAllowed(): void { $this->deleteByPath->execute('theme'); } + + /** + * @throws \Magento\Framework\Exception\FileSystemException + */ + public static function tearDownAfterClass() + { + $filesystem = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() + ->get(\Magento\Framework\Filesystem::class); + /** @var \Magento\Framework\Filesystem\Directory\WriteInterface $directory */ + $directory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA); + if ($directory->isExist(self::TEST_DIRECTORY_NAME)) { + $directory->delete(self::TEST_DIRECTORY_NAME); + } + } } diff --git a/dev/tests/integration/testsuite/Magento/MediaGallery/Model/File/Command/DeleteByAssertIdTest.php b/dev/tests/integration/testsuite/Magento/MediaGallery/Model/File/Command/DeleteByAssertIdTest.php new file mode 100644 index 0000000000000..7eb0d7a886e92 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/MediaGallery/Model/File/Command/DeleteByAssertIdTest.php @@ -0,0 +1,99 @@ +get(Filesystem::class)->getDirectoryWrite(DirectoryList::MEDIA); + self::$_mediaPath = $directory->getAbsolutePath(); + $directory->create(self::TEST_DIRECTORY_NAME); + $directory->touch(self::TEST_DIRECTORY_NAME . '/path.jpg'); + } + + /** + * @inheritdoc + */ + public function setUp() + { + $this->deleteByAssetId = Bootstrap::getObjectManager()->create(DeleteByAssetIdInterface::class); + } + + /** + * @magentoDataFixture Magento/MediaGallery/_files/media_asset.php + * @return void + * @throws \Magento\Framework\Exception\LocalizedException + */ + public function testDeleteByAssetIdWithExistingAsset(): void + { + $fullPath = self::$_mediaPath . self::TEST_DIRECTORY_NAME . '/path.jpg'; + $getById = Bootstrap::getObjectManager()->get(GetByIdInterface::class); + $this->assertFileExists($fullPath); + $this->assertEquals(1, $getById->execute(1)->getId()); + $this->deleteByAssetId->execute(1); + $this->assertFileNotExists($fullPath); + $this->expectException(\Magento\Framework\Exception\NoSuchEntityException::class); + $getById->execute(1); + } + + /** + * @magentoDataFixture Magento/MediaGallery/_files/media_asset.php + * @return void + * @throws \Magento\Framework\Exception\LocalizedException + * @expectedException \Magento\Framework\Exception\LocalizedException + */ + public function testDeleteByAssetIdWithoutAsset(): void + { + $fullPath = self::$_mediaPath . self::TEST_DIRECTORY_NAME . '/path.jpg'; + $this->assertFileNotExists($fullPath); + $this->deleteByAssetId->execute(1); + } + + /** + * @throws \Magento\Framework\Exception\FileSystemException + */ + public static function tearDownAfterClass() + { + $filesystem = \Magento\TestFramework\Helper\Bootstrap::getObjectManager() + ->get(\Magento\Framework\Filesystem::class); + /** @var \Magento\Framework\Filesystem\Directory\WriteInterface $directory */ + $directory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA); + if ($directory->isExist(self::TEST_DIRECTORY_NAME)) { + $directory->delete(self::TEST_DIRECTORY_NAME); + } + } +} diff --git a/dev/tests/integration/testsuite/Magento/MediaGallery/_files/media_asset.php b/dev/tests/integration/testsuite/Magento/MediaGallery/_files/media_asset.php new file mode 100644 index 0000000000000..c0a6691e54852 --- /dev/null +++ b/dev/tests/integration/testsuite/Magento/MediaGallery/_files/media_asset.php @@ -0,0 +1,29 @@ +get(AssetInterfaceFactory::class); +/** @var AssetInterface $mediaAsset */ +$mediaAsset = $mediaAssetFactory->create( + [ + 'data' => [ + 'id' => 1, + 'path' => 'testDirectory/path.jpg' + ] + ] +); +/** @var SaveInterface $mediaSave */ +$mediaSave = $objectManager->get(SaveInterface::class); +$mediaId = $mediaSave->execute($mediaAsset); + From 3784f92befdc78d8db72f3a9755948bf63f6f921 Mon Sep 17 00:00:00 2001 From: Sergii Ivashchenko Date: Fri, 3 Apr 2020 14:12:20 +0100 Subject: [PATCH 17/89] magento/magento2#27499: Removed DataExtractor in favour to DataObjectProcessor --- .../MediaGallery/Model/Asset/Command/Save.php | 17 +- .../MediaGallery/Model/DataExtractor.php | 48 ------ .../Unit/Model/Asset/Command/SaveTest.php | 21 +-- .../Test/Unit/Model/DataExtractorTest.php | 161 ------------------ app/code/Magento/MediaGallery/etc/di.xml | 2 - .../Model/DataExtractorInterface.php | 24 --- 6 files changed, 21 insertions(+), 252 deletions(-) delete mode 100644 app/code/Magento/MediaGallery/Model/DataExtractor.php delete mode 100644 app/code/Magento/MediaGallery/Test/Unit/Model/DataExtractorTest.php delete mode 100644 app/code/Magento/MediaGalleryApi/Model/DataExtractorInterface.php diff --git a/app/code/Magento/MediaGallery/Model/Asset/Command/Save.php b/app/code/Magento/MediaGallery/Model/Asset/Command/Save.php index 7cb2f73169642..e017c4c58eb63 100644 --- a/app/code/Magento/MediaGallery/Model/Asset/Command/Save.php +++ b/app/code/Magento/MediaGallery/Model/Asset/Command/Save.php @@ -7,11 +7,11 @@ namespace Magento\MediaGallery\Model\Asset\Command; -use Magento\MediaGalleryApi\Model\DataExtractorInterface; use Magento\MediaGalleryApi\Api\Data\AssetInterface; use Magento\MediaGalleryApi\Model\Asset\Command\SaveInterface; use Magento\Framework\App\ResourceConnection; use Magento\Framework\Exception\CouldNotSaveException; +use Magento\Framework\Reflection\DataObjectProcessor; use Psr\Log\LoggerInterface; /** @@ -27,9 +27,9 @@ class Save implements SaveInterface private $resourceConnection; /** - * @var DataExtractorInterface + * @var DataObjectProcessor */ - private $extractor; + private $objectProcessor; /** * @var LoggerInterface @@ -40,16 +40,16 @@ class Save implements SaveInterface * Save constructor. * * @param ResourceConnection $resourceConnection - * @param DataExtractorInterface $extractor + * @param DataObjectProcessor $objectProcessor * @param LoggerInterface $logger */ public function __construct( ResourceConnection $resourceConnection, - DataExtractorInterface $extractor, + DataObjectProcessor $objectProcessor, LoggerInterface $logger ) { $this->resourceConnection = $resourceConnection; - $this->extractor = $extractor; + $this->objectProcessor = $objectProcessor; $this->logger = $logger; } @@ -68,7 +68,10 @@ public function execute(AssetInterface $mediaAsset): int $connection = $this->resourceConnection->getConnection(); $tableName = $this->resourceConnection->getTableName(self::TABLE_MEDIA_GALLERY_ASSET); - $connection->insertOnDuplicate($tableName, $this->extractor->extract($mediaAsset, AssetInterface::class)); + $connection->insertOnDuplicate( + $tableName, + array_filter($this->objectProcessor->buildOutputDataArray($mediaAsset, AssetInterface::class)) + ); return (int) $connection->lastInsertId($tableName); } catch (\Exception $exception) { $this->logger->critical($exception); diff --git a/app/code/Magento/MediaGallery/Model/DataExtractor.php b/app/code/Magento/MediaGallery/Model/DataExtractor.php deleted file mode 100644 index 92cf237022c28..0000000000000 --- a/app/code/Magento/MediaGallery/Model/DataExtractor.php +++ /dev/null @@ -1,48 +0,0 @@ -getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { - $methodName = $method->getName(); - if (strpos($methodName, 'get') !== 0 - || !empty($method->getParameters()) - || strpos($methodName, 'getExtensionAttributes') !== false - ) { - continue; - } - $value = $object->$methodName(); - if (!empty($value)) { - $key = strtolower(preg_replace("/([a-z])([A-Z])/", "$1_$2", substr($methodName, 3))); - $data[$key] = $value; - } - } - return $data; - } -} diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/SaveTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/SaveTest.php index 2f736fb832eac..8af26f0c64b16 100644 --- a/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/SaveTest.php +++ b/app/code/Magento/MediaGallery/Test/Unit/Model/Asset/Command/SaveTest.php @@ -7,9 +7,9 @@ namespace Magento\MediaGallery\Test\Unit\Model\Asset\Command; +use Magento\Eav\Helper\Data; use Magento\MediaGallery\Model\Asset\Command\Save; use Magento\MediaGalleryApi\Api\Data\AssetInterface; -use Magento\MediaGalleryApi\Model\DataExtractorInterface; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Adapter\Pdo\Mysql; @@ -17,6 +17,7 @@ use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; +use Magento\Framework\Reflection\DataObjectProcessor; use Psr\Log\LoggerInterface; /** @@ -63,14 +64,14 @@ class SaveTest extends TestCase private $resourceConnectionMock; /** - * @var MockObject | DataExtractorInterface + * @var MockObject | LoggerInterface */ private $loggerMock; /** - * @var MockObject | LoggerInterface + * @var MockObject | DataObjectProcessor */ - private $extractorMock; + private $objectProcessor; /** * @var MockObject | AdapterInterface @@ -97,7 +98,7 @@ protected function setUp(): void $this->mediaAssetMock = $this->createMock(AssetInterface::class); /* Save constructor mocks */ - $this->extractorMock = $this->createMock(DataExtractorInterface::class); + $this->objectProcessor = $this->createMock(DataObjectProcessor::class); $this->loggerMock = $this->createMock(LoggerInterface::class); $this->resourceConnectionMock = $this->createConfiguredMock( ResourceConnection::class, @@ -112,7 +113,7 @@ protected function setUp(): void Save::class, [ 'resourceConnection' => $this->resourceConnectionMock, - 'extractor' => $this->extractorMock, + 'objectProcessor' => $this->objectProcessor, 'logger' => $this->loggerMock ] ); @@ -126,9 +127,9 @@ public function testSuccessfulExecute(): void $this->resourceConnectionMock->expects(self::once())->method('getConnection'); $this->resourceConnectionMock->expects(self::once())->method('getTableName'); - $this->extractorMock + $this->objectProcessor ->expects(self::once()) - ->method('extract') + ->method('buildOutputDataArray') ->with($this->mediaAssetMock, AssetInterface::class) ->willReturn(self::IMAGE_DATA); @@ -155,9 +156,9 @@ public function testExceptionExecute(): void $this->resourceConnectionMock->expects(self::once())->method('getConnection'); $this->resourceConnectionMock->expects(self::once())->method('getTableName'); - $this->extractorMock + $this->objectProcessor ->expects(self::once()) - ->method('extract') + ->method('buildOutputDataArray') ->with($this->mediaAssetMock, AssetInterface::class) ->willReturn(self::IMAGE_DATA); diff --git a/app/code/Magento/MediaGallery/Test/Unit/Model/DataExtractorTest.php b/app/code/Magento/MediaGallery/Test/Unit/Model/DataExtractorTest.php deleted file mode 100644 index f70e4ccdae22c..0000000000000 --- a/app/code/Magento/MediaGallery/Test/Unit/Model/DataExtractorTest.php +++ /dev/null @@ -1,161 +0,0 @@ -dataExtractor = new DataExtractor(); - } - - /** - * Test extract object data by interface - * - * @dataProvider assetProvider - * - * @param string $class - * @param string|null $interfaceClass - * @param array $expectedData - * - * @throws \ReflectionException - */ - public function testExtractData(string $class, $interfaceClass, array $expectedData): void - { - $data = []; - foreach ($expectedData as $expectedDataKey => $expectedDataItem) { - $data[$expectedDataKey] = $expectedDataItem['value']; - } - $model = (new ObjectManager($this))->getObject( - $class, - [ - 'data' => $data, - ] - ); - if ($interfaceClass) { - $receivedData = $this->dataExtractor->extract($model, $interfaceClass); - $this->checkAssetValues($expectedData, $receivedData, $model); - } else { - $receivedData = $this->dataExtractor->extract($model); - $this->checkKeyWordValues($expectedData, $receivedData, $model); - } - } - - /** - * @param array $expectedData - * @param array $data - * @param object $model - */ - private function checkAssetValues(array $expectedData, array $data, $model) - { - foreach ($expectedData as $expectedDataKey => $expectedDataItem) { - $this->assertEquals($data[$expectedDataKey] ?? null, $model->{$expectedDataItem['method']}()); - $this->assertEquals($data[$expectedDataKey] ?? null, $expectedDataItem['value']); - } - $this->assertEquals(array_keys($expectedData), array_keys($data)); - } - - /** - * @param array $expectedData - * @param array $data - * @param object $model - */ - private function checkKeyWordValues(array $expectedData, array $data, $model) - { - foreach ($expectedData as $expectedDataKey => $expectedDataItem) { - $this->assertEquals($data[$expectedDataKey] ?? null, $model->{$expectedDataItem['method']}()); - $this->assertEquals($data[$expectedDataKey] ?? null, $expectedDataItem['value']); - } - $this->assertEquals(array_keys($expectedData), array_keys(array_slice($data, 0, 2))); - } - - /** - * @return array - */ - public function assetProvider() - { - return [ - 'Asset conversion with interface' => [ - Asset::class, - AssetInterface::class, - [ - 'id' => [ - 'value' => 2, - 'method' => 'getId', - ], - 'path' => [ - 'value' => 'path', - 'method' => 'getPath', - ], - 'title' => [ - 'value' => 'title', - 'method' => 'getTitle', - ], - 'source' => [ - 'value' => 'source', - 'method' => 'getSource', - ], - 'content_type' => [ - 'value' => 'content_type', - 'method' => 'getContentType', - ], - 'height' => [ - 'value' => 4, - 'method' => 'getHeight', - ], - 'width' => [ - 'value' => 3, - 'method' => 'getWidth', - ], - 'size' => [ - 'value' => 300, - 'method' => 'getSize', - ], - 'created_at' => [ - 'value' => '2019-11-28 10:40:09', - 'method' => 'getCreatedAt', - ], - 'updated_at' => [ - 'value' => '2019-11-28 10:41:08', - 'method' => 'getUpdatedAt', - ], - ], - ], - 'Keyword conversion without interface' => [ - Keyword::class, - '', - [ - 'id' => [ - 'value' => 2, - 'method' => 'getId', - ], - 'keyword' => [ - 'value' => 'keyword', - 'method' => 'getKeyword', - ], - ], - ] - ]; - } -} diff --git a/app/code/Magento/MediaGallery/etc/di.xml b/app/code/Magento/MediaGallery/etc/di.xml index ea05da9498607..c993d82342326 100644 --- a/app/code/Magento/MediaGallery/etc/di.xml +++ b/app/code/Magento/MediaGallery/etc/di.xml @@ -19,8 +19,6 @@ - - diff --git a/app/code/Magento/MediaGalleryApi/Model/DataExtractorInterface.php b/app/code/Magento/MediaGalleryApi/Model/DataExtractorInterface.php deleted file mode 100644 index 33fd2425edc6f..0000000000000 --- a/app/code/Magento/MediaGalleryApi/Model/DataExtractorInterface.php +++ /dev/null @@ -1,24 +0,0 @@ - Date: Fri, 3 Apr 2020 14:23:27 +0100 Subject: [PATCH 18/89] magento/magento2#27499: Code review changes --- .../MediaGallery/Model/Asset/Command/GetByPath.php | 8 ++++---- .../Magento/MediaGalleryApi/Api/Data/AssetInterface.php | 2 +- .../Model/Asset/Command/GetByPathInterface.php | 4 ++-- .../MediaGalleryApi/Model/Asset/Command/SaveInterface.php | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/app/code/Magento/MediaGallery/Model/Asset/Command/GetByPath.php b/app/code/Magento/MediaGallery/Model/Asset/Command/GetByPath.php index fe5fcca6cb0de..32c7323c3a511 100644 --- a/app/code/Magento/MediaGallery/Model/Asset/Command/GetByPath.php +++ b/app/code/Magento/MediaGallery/Model/Asset/Command/GetByPath.php @@ -59,22 +59,22 @@ public function __construct( /** * Return media asset asset list * - * @param string $mediaFilePath + * @param string $path * * @return AssetInterface * @throws IntegrationException */ - public function execute(string $mediaFilePath): AssetInterface + public function execute(string $path): AssetInterface { try { $connection = $this->resourceConnection->getConnection(); $select = $connection->select() ->from($this->resourceConnection->getTableName(self::TABLE_MEDIA_GALLERY_ASSET)) - ->where(self::MEDIA_GALLERY_ASSET_PATH . ' = ?', $mediaFilePath); + ->where(self::MEDIA_GALLERY_ASSET_PATH . ' = ?', $path); $data = $connection->query($select)->fetch(); if (empty($data)) { - $message = __('There is no such media asset with path "%1"', $mediaFilePath); + $message = __('There is no such media asset with path "%1"', $path); throw new NoSuchEntityException($message); } diff --git a/app/code/Magento/MediaGalleryApi/Api/Data/AssetInterface.php b/app/code/Magento/MediaGalleryApi/Api/Data/AssetInterface.php index 7cd94f90a60a0..c3454400b2995 100644 --- a/app/code/Magento/MediaGalleryApi/Api/Data/AssetInterface.php +++ b/app/code/Magento/MediaGalleryApi/Api/Data/AssetInterface.php @@ -39,7 +39,7 @@ public function getPath(): string; public function getTitle(): ?string; /** - * Get source of the file + * Get the name of the channel/stock/integration file was retrieved from. null if not identified. * * @return string|null */ diff --git a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByPathInterface.php b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByPathInterface.php index 9d39b5cc692f3..aa3f76f721374 100644 --- a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByPathInterface.php +++ b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/GetByPathInterface.php @@ -17,8 +17,8 @@ interface GetByPathInterface /** * Get media asset list * - * @param string $mediaFilePath + * @param string $path * @return \Magento\MediaGalleryApi\Api\Data\AssetInterface */ - public function execute(string $mediaFilePath): \Magento\MediaGalleryApi\Api\Data\AssetInterface; + public function execute(string $path): \Magento\MediaGalleryApi\Api\Data\AssetInterface; } diff --git a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/SaveInterface.php b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/SaveInterface.php index 6d2aae21754b8..77f8fcf8b2c2e 100644 --- a/app/code/Magento/MediaGalleryApi/Model/Asset/Command/SaveInterface.php +++ b/app/code/Magento/MediaGalleryApi/Model/Asset/Command/SaveInterface.php @@ -17,7 +17,7 @@ interface SaveInterface { /** - * Save media asset + * Save media asset and return the media asset id * * @param \Magento\MediaGalleryApi\Api\Data\AssetInterface $mediaAsset * @return int From e66c9a906fa262f2e9a6c4de8c63ad603a7f8c86 Mon Sep 17 00:00:00 2001 From: Stanislav Idolov Date: Fri, 3 Apr 2020 10:54:38 -0500 Subject: [PATCH 19/89] magento/magento2#27536: Remove dependency to the MediaGallery module --- ...MediaGalleryAssetDeleteByDirectoryPath.php | 84 +++++++++++++++++++ .../Plugin/MediaGalleryAssetDeleteByPath.php | 84 +++++++++++++++++++ app/code/Magento/MediaContent/composer.json | 3 +- .../Magento/MediaContent/etc/db_schema.xml | 1 - app/code/Magento/MediaContent/etc/di.xml | 6 ++ .../Api/AssignAssetInterface.php | 2 + .../Api/GetContentWithAssetInterface.php | 2 + .../Api/UnassignAssetInterface.php | 2 + 8 files changed, 181 insertions(+), 3 deletions(-) create mode 100644 app/code/Magento/MediaContent/Model/Plugin/MediaGalleryAssetDeleteByDirectoryPath.php create mode 100644 app/code/Magento/MediaContent/Model/Plugin/MediaGalleryAssetDeleteByPath.php diff --git a/app/code/Magento/MediaContent/Model/Plugin/MediaGalleryAssetDeleteByDirectoryPath.php b/app/code/Magento/MediaContent/Model/Plugin/MediaGalleryAssetDeleteByDirectoryPath.php new file mode 100644 index 0000000000000..569798be356ca --- /dev/null +++ b/app/code/Magento/MediaContent/Model/Plugin/MediaGalleryAssetDeleteByDirectoryPath.php @@ -0,0 +1,84 @@ +resourceConnection = $resourceConnection; + $this->logger = $logger; + } + + /** + * @param DeleteByDirectoryPathInterface $subject + * @param \Closure $proceed + * @param string $directoryPath + * @throws CouldNotDeleteException + * @return void + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function aroundExecute( + DeleteByDirectoryPathInterface $subject, + \Closure $proceed, + string $directoryPath + ) : void { + /** @var AdapterInterface $connection */ + $connection = $this->resourceConnection->getConnection(); + $galleryAssetTableName = $this->resourceConnection->getTableName('media_gallery_asset'); + $mediaContentAssetTableName = $this->resourceConnection->getTableName('media_content_asset'); + + $select = $connection->select(); + $select->from($galleryAssetTableName, ['id']); + $select->where('path LIKE ?', $directoryPath); + $galleryAssetIds = $connection->fetchCol($select); + + $proceed(); + + try { + $connection->delete( + $mediaContentAssetTableName, + ['asset_id IN(?)' => implode(', ', $galleryAssetIds)] + ); + } catch (\Exception $exception) { + $this->logger->critical($exception); + $message = __( + 'Could not delete media content assets for media gallery asset with path %path: %error', + ['path' => $directoryPath, 'error' => $exception->getMessage()] + ); + throw new CouldNotDeleteException($message, $exception); + } + } +} diff --git a/app/code/Magento/MediaContent/Model/Plugin/MediaGalleryAssetDeleteByPath.php b/app/code/Magento/MediaContent/Model/Plugin/MediaGalleryAssetDeleteByPath.php new file mode 100644 index 0000000000000..b5bf39cb70b69 --- /dev/null +++ b/app/code/Magento/MediaContent/Model/Plugin/MediaGalleryAssetDeleteByPath.php @@ -0,0 +1,84 @@ +resourceConnection = $resourceConnection; + $this->logger = $logger; + } + + /** + * @param DeleteByPathInterface $subject + * @param \Closure $proceed + * @param string $mediaAssetPath + * @throws CouldNotDeleteException + * @return void + * + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + public function aroundExecute( + DeleteByPathInterface $subject, + \Closure $proceed, + string $mediaAssetPath + ) : void { + /** @var AdapterInterface $connection */ + $connection = $this->resourceConnection->getConnection(); + $galleryAssetTableName = $this->resourceConnection->getTableName('media_gallery_asset'); + $mediaContentAssetTableName = $this->resourceConnection->getTableName('media_content_asset'); + + $select = $connection->select(); + $select->from($galleryAssetTableName, ['id']); + $select->where('path = ?', $mediaAssetPath); + $galleryAssetIds = $connection->fetchCol($select); + + $proceed(); + + try { + $connection->delete( + $mediaContentAssetTableName, + ['asset_id IN(?)' => implode(', ', $galleryAssetIds)] + ); + } catch (\Exception $exception) { + $this->logger->critical($exception); + $message = __( + 'Could not delete media content assets for media gallery asset with path %path: %error', + ['path' => $mediaAssetPath, 'error' => $exception->getMessage()] + ); + throw new CouldNotDeleteException($message, $exception); + } + } +} diff --git a/app/code/Magento/MediaContent/composer.json b/app/code/Magento/MediaContent/composer.json index e14c0fc1aeadd..6734c1a300810 100644 --- a/app/code/Magento/MediaContent/composer.json +++ b/app/code/Magento/MediaContent/composer.json @@ -5,8 +5,7 @@ "php": "~7.1.3||~7.2.0||~7.3.0", "magento/framework": "*", "magento/module-media-content-api": "*", - "magento/module-media-gallery-api": "*", - "magento/module-media-gallery": "*" + "magento/module-media-gallery-api": "*" }, "type": "magento2-module", "license": [ diff --git a/app/code/Magento/MediaContent/etc/db_schema.xml b/app/code/Magento/MediaContent/etc/db_schema.xml index 25c4b50098085..2cd917070cf0b 100644 --- a/app/code/Magento/MediaContent/etc/db_schema.xml +++ b/app/code/Magento/MediaContent/etc/db_schema.xml @@ -16,6 +16,5 @@ - diff --git a/app/code/Magento/MediaContent/etc/di.xml b/app/code/Magento/MediaContent/etc/di.xml index 98031f32211d4..15fa68bce99a0 100644 --- a/app/code/Magento/MediaContent/etc/di.xml +++ b/app/code/Magento/MediaContent/etc/di.xml @@ -12,4 +12,10 @@ + + + + + + diff --git a/app/code/Magento/MediaContentApi/Api/AssignAssetInterface.php b/app/code/Magento/MediaContentApi/Api/AssignAssetInterface.php index ebe0968cc57f5..a0436b57e01af 100644 --- a/app/code/Magento/MediaContentApi/Api/AssignAssetInterface.php +++ b/app/code/Magento/MediaContentApi/Api/AssignAssetInterface.php @@ -15,6 +15,8 @@ interface AssignAssetInterface { /** + * Save relation between media asset and media content. + * * @param int $assetId * @param string $contentType * @param string $contentEntityId diff --git a/app/code/Magento/MediaContentApi/Api/GetContentWithAssetInterface.php b/app/code/Magento/MediaContentApi/Api/GetContentWithAssetInterface.php index a10cc4a476426..ab8347098da82 100644 --- a/app/code/Magento/MediaContentApi/Api/GetContentWithAssetInterface.php +++ b/app/code/Magento/MediaContentApi/Api/GetContentWithAssetInterface.php @@ -15,6 +15,8 @@ interface GetContentWithAssetInterface { /** + * Get media asset to content relation by media asset id. + * * @param int $assetId * * @return array diff --git a/app/code/Magento/MediaContentApi/Api/UnassignAssetInterface.php b/app/code/Magento/MediaContentApi/Api/UnassignAssetInterface.php index 502fb738c8d00..831275de8a78e 100644 --- a/app/code/Magento/MediaContentApi/Api/UnassignAssetInterface.php +++ b/app/code/Magento/MediaContentApi/Api/UnassignAssetInterface.php @@ -15,6 +15,8 @@ interface UnassignAssetInterface { /** + * Remove relation between the media asset and media content. + * * @param int $assetId * @param string $contentType * @param string $contentEntityId From d5cdd0b4da6c7b2cb06f6f7b7ca681ec277a3a38 Mon Sep 17 00:00:00 2001 From: Sergii Ivashchenko Date: Fri, 3 Apr 2020 21:53:49 +0100 Subject: [PATCH 20/89] magento/magento2#27536: Introduced ContentIdentity --- app/code/Magento/Cms/etc/module.xml | 2 - .../{AssignAsset.php => AssignAssets.php} | 28 ++++---- .../MediaContent/Model/ContentIdentity.php | 45 ++++++++++++ ...ntent.php => GetAssetIdsUsedInContent.php} | 28 ++++---- ...WithAsset.php => GetContentWithAssets.php} | 36 +++++++--- .../{UnassignAsset.php => UnassignAssets.php} | 22 +++--- .../MediaContent/Model/UpdateRelations.php | 63 ++++++++--------- ...signAssetTest.php => AssignAssetsTest.php} | 68 +++++++++++++------ .../Unit/Model/GetAssetsusedInContentTest.php | 68 ++++++++++--------- ...tTest.php => GetContentWithAssetsTest.php} | 57 +++++++++------- .../Test/Unit/Model/UnassignAssetTest.php | 68 +++++++++++++------ .../MediaContent/etc/db_schema_whitelist.json | 3 +- app/code/Magento/MediaContent/etc/di.xml | 13 ++-- app/code/Magento/MediaContent/etc/module.xml | 6 +- ...nterface.php => AssignAssetsInterface.php} | 13 ++-- .../Api/Data/ContentIdentityInterface.php | 37 ++++++++++ ... => ExtractAssetsFromContentInterface.php} | 2 +- ... => GetAssetIdsUsedInContentInterface.php} | 11 ++- ....php => GetContentWithAssetsInterface.php} | 13 ++-- ...erface.php => UnassignAssetsInterface.php} | 13 ++-- .../Api/UpdateRelationsInterface.php | 18 ++--- ...ntent.php => ExtractAssetsFromContent.php} | 4 +- .../MediaContentCatalog/Observer/Category.php | 35 +++++++--- .../MediaContentCatalog/Observer/Product.php | 34 +++++++--- .../Magento/MediaContentCatalog/etc/di.xml | 2 +- .../MediaContentCms/Observer/Block.php | 35 +++++++--- .../Magento/MediaContentCms/Observer/Page.php | 35 +++++++--- app/code/Magento/MediaContentCms/etc/di.xml | 2 +- 28 files changed, 494 insertions(+), 267 deletions(-) rename app/code/Magento/MediaContent/Model/{AssignAsset.php => AssignAssets.php} (68%) create mode 100644 app/code/Magento/MediaContent/Model/ContentIdentity.php rename app/code/Magento/MediaContent/Model/{GetAssetsUsedInContent.php => GetAssetIdsUsedInContent.php} (71%) rename app/code/Magento/MediaContent/Model/{GetContentWithAsset.php => GetContentWithAssets.php} (52%) rename app/code/Magento/MediaContent/Model/{UnassignAsset.php => UnassignAssets.php} (67%) rename app/code/Magento/MediaContent/Test/Unit/Model/{AssignAssetTest.php => AssignAssetsTest.php} (70%) rename app/code/Magento/MediaContent/Test/Unit/Model/{GetContentWithAssetTest.php => GetContentWithAssetsTest.php} (62%) rename app/code/Magento/MediaContentApi/Api/{AssignAssetInterface.php => AssignAssetsInterface.php} (59%) create mode 100644 app/code/Magento/MediaContentApi/Api/Data/ContentIdentityInterface.php rename app/code/Magento/MediaContentApi/Api/{ExtractAssetFromContentInterface.php => ExtractAssetsFromContentInterface.php} (92%) rename app/code/Magento/MediaContentApi/Api/{GetAssetsUsedInContentInterface.php => GetAssetIdsUsedInContentInterface.php} (57%) rename app/code/Magento/MediaContentApi/Api/{GetContentWithAssetInterface.php => GetContentWithAssetsInterface.php} (54%) rename app/code/Magento/MediaContentApi/Api/{UnassignAssetInterface.php => UnassignAssetsInterface.php} (60%) rename app/code/Magento/MediaContentApi/Model/{ExtractAssetFromContent.php => ExtractAssetsFromContent.php} (94%) diff --git a/app/code/Magento/Cms/etc/module.xml b/app/code/Magento/Cms/etc/module.xml index 880ce5b7075e6..d3fc2846217d9 100644 --- a/app/code/Magento/Cms/etc/module.xml +++ b/app/code/Magento/Cms/etc/module.xml @@ -11,8 +11,6 @@ - - diff --git a/app/code/Magento/MediaContent/Model/AssignAsset.php b/app/code/Magento/MediaContent/Model/AssignAssets.php similarity index 68% rename from app/code/Magento/MediaContent/Model/AssignAsset.php rename to app/code/Magento/MediaContent/Model/AssignAssets.php index ada7e9adf20ef..7184e8b9914fa 100644 --- a/app/code/Magento/MediaContent/Model/AssignAsset.php +++ b/app/code/Magento/MediaContent/Model/AssignAssets.php @@ -9,13 +9,14 @@ use Magento\Framework\App\ResourceConnection; use Magento\Framework\Exception\CouldNotSaveException; -use Magento\MediaContentApi\Api\AssignAssetInterface; +use Magento\MediaContentApi\Api\AssignAssetsInterface; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; use Psr\Log\LoggerInterface; /** * Used for saving relation between the media asset and media content where the media asset is used */ -class AssignAsset implements AssignAssetInterface +class AssignAssets implements AssignAssetsInterface { private const MEDIA_CONTENT_ASSET_TABLE_NAME = 'media_content_asset'; private const ASSET_ID = 'asset_id'; @@ -34,8 +35,6 @@ class AssignAsset implements AssignAssetInterface private $logger; /** - * AssignAsset constructor. - * * @param ResourceConnection $resourceConnection * @param LoggerInterface $logger */ @@ -46,20 +45,23 @@ public function __construct(ResourceConnection $resourceConnection, LoggerInterf } /** - * @inheritDoc + * @inheritdoc */ - public function execute(int $assetId, string $contentType, string $contentEntityId, string $contentField): void + public function execute(ContentIdentityInterface $contentIdentity, array $assetIds): void { try { $connection = $this->resourceConnection->getConnection(); $tableName = $this->resourceConnection->getTableName(self::MEDIA_CONTENT_ASSET_TABLE_NAME); - $saveData = [ - self::ASSET_ID => $assetId, - self::TYPE => $contentType, - self::ENTITY_ID => $contentEntityId, - self::FIELD => $contentField - ]; - $connection->insert($tableName, $saveData); + $data = []; + foreach ($assetIds as $assetId) { + $data[] = [ + self::ASSET_ID => $assetId, + self::TYPE => $contentIdentity->getEntityType(), + self::ENTITY_ID => $contentIdentity->getEntityId(), + self::FIELD => $contentIdentity->getField() + ]; + } + $connection->insertMultiple($tableName, $data); } catch (\Exception $exception) { $this->logger->critical($exception); $message = __('An error occurred while saving relation between media asset and media content.'); diff --git a/app/code/Magento/MediaContent/Model/ContentIdentity.php b/app/code/Magento/MediaContent/Model/ContentIdentity.php new file mode 100644 index 0000000000000..2af8dd043680d --- /dev/null +++ b/app/code/Magento/MediaContent/Model/ContentIdentity.php @@ -0,0 +1,45 @@ +getData(self::TYPE); + } + + /** + * @inheritdoc + */ + public function getEntityId(): string + { + return (string) $this->getData(self::ENTITY_ID); + } + + /** + * @inheritdoc + */ + public function getField(): string + { + return (string) $this->getData(self::FIELD); + } +} diff --git a/app/code/Magento/MediaContent/Model/GetAssetsUsedInContent.php b/app/code/Magento/MediaContent/Model/GetAssetIdsUsedInContent.php similarity index 71% rename from app/code/Magento/MediaContent/Model/GetAssetsUsedInContent.php rename to app/code/Magento/MediaContent/Model/GetAssetIdsUsedInContent.php index 2baa022713d8f..4da0898525887 100644 --- a/app/code/Magento/MediaContent/Model/GetAssetsUsedInContent.php +++ b/app/code/Magento/MediaContent/Model/GetAssetIdsUsedInContent.php @@ -9,13 +9,14 @@ use Magento\Framework\App\ResourceConnection; use Magento\Framework\Exception\IntegrationException; -use Magento\MediaContentApi\Api\GetAssetsUsedInContentInterface; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; +use Magento\MediaContentApi\Api\GetAssetIdsUsedInContentInterface; use Psr\Log\LoggerInterface; /** * Used to return media asset id list which is used in the specified media content */ -class GetAssetsUsedInContent implements GetAssetsUsedInContentInterface +class GetAssetIdsUsedInContent implements GetAssetIdsUsedInContentInterface { private const MEDIA_CONTENT_ASSET_TABLE_NAME = 'media_content_asset'; private const ASSET_ID = 'asset_id'; @@ -46,9 +47,9 @@ public function __construct(ResourceConnection $resourceConnection, LoggerInterf } /** - * @inheritDoc + * @inheritdoc */ - public function execute(string $contentType, string $contentEntityId = null, string $contentField = null): array + public function execute(ContentIdentityInterface $contentIdentity): array { try { $connection = $this->resourceConnection->getConnection(); @@ -56,15 +57,16 @@ public function execute(string $contentType, string $contentEntityId = null, str ->from( $this->resourceConnection->getTableName(self::MEDIA_CONTENT_ASSET_TABLE_NAME), self::ASSET_ID - )->where(self::TYPE . ' = ?', $contentType); - - if (null !== $contentEntityId) { - $select = $select->where(self::ENTITY_ID . '= ?', $contentEntityId); - } - - if (null !== $contentField) { - $select = $select->where(self::FIELD . '= ?', $contentField); - } + )->where( + self::TYPE . ' = ?', + $contentIdentity->getEntityType() + )->where( + self::ENTITY_ID . '= ?', + $contentIdentity->getEntityId() + )->where( + self::FIELD . '= ?', + $contentIdentity->getField() + ); return $connection->fetchAssoc($select); } catch (\Exception $exception) { diff --git a/app/code/Magento/MediaContent/Model/GetContentWithAsset.php b/app/code/Magento/MediaContent/Model/GetContentWithAssets.php similarity index 52% rename from app/code/Magento/MediaContent/Model/GetContentWithAsset.php rename to app/code/Magento/MediaContent/Model/GetContentWithAssets.php index 796cc890b3845..8f014ee77e680 100644 --- a/app/code/Magento/MediaContent/Model/GetContentWithAsset.php +++ b/app/code/Magento/MediaContent/Model/GetContentWithAssets.php @@ -9,13 +9,14 @@ use Magento\Framework\App\ResourceConnection; use Magento\Framework\Exception\IntegrationException; -use Magento\MediaContentApi\Api\GetContentWithAssetInterface; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterfaceFactory; +use Magento\MediaContentApi\Api\GetContentWithAssetsInterface; use Psr\Log\LoggerInterface; /** * Used to return media asset list for the specified asset. */ -class GetContentWithAsset implements GetContentWithAssetInterface +class GetContentWithAssets implements GetContentWithAssetsInterface { private const MEDIA_CONTENT_ASSET_TABLE_NAME = 'media_content_asset'; private const ASSET_ID = 'asset_id'; @@ -31,13 +32,21 @@ class GetContentWithAsset implements GetContentWithAssetInterface private $logger; /** - * GetAssetsUsedInContent constructor. - * + * @var ContentIdentityInterfaceFactory + */ + private $factory; + + /** + * @param ContentIdentityInterfaceFactory $factory * @param ResourceConnection $resourceConnection * @param LoggerInterface $logger */ - public function __construct(ResourceConnection $resourceConnection, LoggerInterface $logger) - { + public function __construct( + ContentIdentityInterfaceFactory $factory, + ResourceConnection $resourceConnection, + LoggerInterface $logger + ) { + $this->factory = $factory; $this->resourceConnection = $resourceConnection; $this->logger = $logger; } @@ -45,19 +54,24 @@ public function __construct(ResourceConnection $resourceConnection, LoggerInterf /** * @inheritDoc */ - public function execute(int $assetId): array + public function execute(array $assetIds): array { try { $connection = $this->resourceConnection->getConnection(); $select = $connection->select() ->from($this->resourceConnection->getTableName(self::MEDIA_CONTENT_ASSET_TABLE_NAME)) - ->where(self::ASSET_ID . '= ?', $assetId); + ->where(self::ASSET_ID . 'IN (?)', $assetIds); - return $connection->fetchAssoc($select); + $contentIdentities = []; + foreach ($connection->fetchAssoc($select) as $contentIdentityData) { + $contentIdentities[] = $this->factory->create(['data' => $contentIdentityData]); + } + return $contentIdentities; } catch (\Exception $exception) { $this->logger->critical($exception); - $message = __('An error occurred at getting media asset to content relation by media asset id.'); - throw new IntegrationException($message); + throw new IntegrationException( + __('An error occurred at getting media asset to content relation by media asset id.') + ); } } } diff --git a/app/code/Magento/MediaContent/Model/UnassignAsset.php b/app/code/Magento/MediaContent/Model/UnassignAssets.php similarity index 67% rename from app/code/Magento/MediaContent/Model/UnassignAsset.php rename to app/code/Magento/MediaContent/Model/UnassignAssets.php index ae5924f662403..3236538ff181c 100644 --- a/app/code/Magento/MediaContent/Model/UnassignAsset.php +++ b/app/code/Magento/MediaContent/Model/UnassignAssets.php @@ -9,13 +9,14 @@ use Magento\Framework\App\ResourceConnection; use Magento\Framework\Exception\CouldNotDeleteException; -use Magento\MediaContentApi\Api\UnassignAssetInterface; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; +use Magento\MediaContentApi\Api\UnassignAssetsInterface; use Psr\Log\LoggerInterface; /** * Used to unassign relation of the media asset to the media content where the media asset is used */ -class UnassignAsset implements UnassignAssetInterface +class UnassignAssets implements UnassignAssetsInterface { private const MEDIA_CONTENT_ASSET_TABLE_NAME = 'media_content_asset'; private const ASSET_ID = 'asset_id'; @@ -46,9 +47,9 @@ public function __construct(ResourceConnection $resourceConnection, LoggerInterf } /** - * @inheritDoc + * @inheritdoc */ - public function execute(int $assetId, string $contentType, string $contentEntityId, string $contentField): void + public function execute(ContentIdentityInterface $contentIdentity, array $assetIds): void { try { $connection = $this->resourceConnection->getConnection(); @@ -56,16 +57,17 @@ public function execute(int $assetId, string $contentType, string $contentEntity $connection->delete( $tableName, [ - self::ASSET_ID . ' = ?' => $assetId, - self::TYPE . ' = ?' => $contentType, - self::ENTITY_ID . ' = ?' => $contentEntityId, - self::FIELD . ' = ?' => $contentField + self::ASSET_ID . ' IN (?)' => $assetIds, + self::TYPE . ' = ?' => $contentIdentity->getEntityType(), + self::ENTITY_ID . ' = ?' => $contentIdentity->getEntityId(), + self::FIELD . ' = ?' => $contentIdentity->getField() ] ); } catch (\Exception $exception) { $this->logger->critical($exception); - $message = __('An error occurred at unassign relation between the media asset and media content.'); - throw new CouldNotDeleteException($message); + throw new CouldNotDeleteException( + __('An error occurred at unassign relation between the media asset and media content.') + ); } } } diff --git a/app/code/Magento/MediaContent/Model/UpdateRelations.php b/app/code/Magento/MediaContent/Model/UpdateRelations.php index 1716739434591..c3ae928ead364 100644 --- a/app/code/Magento/MediaContent/Model/UpdateRelations.php +++ b/app/code/Magento/MediaContent/Model/UpdateRelations.php @@ -10,10 +10,11 @@ use Magento\Framework\Exception\CouldNotDeleteException; use Magento\Framework\Exception\CouldNotSaveException; use Magento\Framework\Exception\IntegrationException; -use Magento\MediaContentApi\Api\AssignAssetInterface; -use Magento\MediaContentApi\Api\ExtractAssetFromContentInterface; -use Magento\MediaContentApi\Api\GetAssetsUsedInContentInterface; -use Magento\MediaContentApi\Api\UnassignAssetInterface; +use Magento\MediaContentApi\Api\AssignAssetsInterface; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; +use Magento\MediaContentApi\Api\ExtractAssetsFromContentInterface; +use Magento\MediaContentApi\Api\GetAssetIdsUsedInContentInterface; +use Magento\MediaContentApi\Api\UnassignAssetsInterface; use Magento\MediaContentApi\Api\UpdateRelationsInterface; use Magento\MediaGalleryApi\Api\Data\AssetInterface; use Psr\Log\LoggerInterface; @@ -24,22 +25,22 @@ class UpdateRelations implements UpdateRelationsInterface { /** - * @var ExtractAssetFromContentInterface + * @var ExtractAssetsFromContentInterface */ private $extractAssetFromContent; /** - * @var AssignAssetInterface + * @var AssignAssetsInterface */ private $assignAsset; /** - * @var GetAssetsUsedInContentInterface + * @var GetAssetIdsUsedInContentInterface */ private $getAssetsUsedInContent; /** - * @var UnassignAssetInterface + * @var UnassignAssetsInterface */ private $unassignAsset; @@ -49,17 +50,17 @@ class UpdateRelations implements UpdateRelationsInterface private $logger; /** - * @param ExtractAssetFromContentInterface $extractAssetFromContent - * @param AssignAssetInterface $assignAsset - * @param GetAssetsUsedInContentInterface $getAssetsUsedInContent - * @param UnassignAssetInterface $unassignAsset + * @param ExtractAssetsFromContentInterface $extractAssetFromContent + * @param AssignAssetsInterface $assignAsset + * @param GetAssetIdsUsedInContentInterface $getAssetsUsedInContent + * @param UnassignAssetsInterface $unassignAsset * @param LoggerInterface $logger */ public function __construct( - ExtractAssetFromContentInterface $extractAssetFromContent, - AssignAssetInterface $assignAsset, - GetAssetsUsedInContentInterface $getAssetsUsedInContent, - UnassignAssetInterface $unassignAsset, + ExtractAssetsFromContentInterface $extractAssetFromContent, + UnassignAssetsInterface $assignAsset, + GetAssetIdsUsedInContentInterface $getAssetsUsedInContent, + UnassignAssetsInterface $unassignAsset, LoggerInterface $logger ) { $this->extractAssetFromContent = $extractAssetFromContent; @@ -72,15 +73,13 @@ public function __construct( /** * Create new relation between media asset and content or updated existing * - * @param string $type - * @param string $field - * @param string $entityId + * @param ContentIdentityInterface $contentIdentity * @param string $data */ - public function execute(string $type, string $field, string $entityId, string $data): void + public function execute(ContentIdentityInterface $contentIdentity, string $data): void { try { - $this->updateRelation($type, $field, $entityId, $data); + $this->updateRelation($contentIdentity, $data); } catch (\Exception $exception) { $this->logger->critical($exception); } @@ -89,28 +88,26 @@ public function execute(string $type, string $field, string $entityId, string $d /** * Records a relation for the newly added asset * - * @param string $type - * @param string $field - * @param string $entityId + * @param ContentIdentityInterface $contentIdentity * @param string $data * @throws CouldNotDeleteException * @throws CouldNotSaveException * @throws IntegrationException */ - private function updateRelation(string $type, string $field, string $entityId, string $data) + private function updateRelation(ContentIdentityInterface $contentIdentity, string $data) { - $relations = $this->getAssetsUsedInContent->execute($type, $entityId, $field); - $assetsInContent = $this->extractAssetFromContent->execute($data); + $existingAssetIds = $this->getAssetsUsedInContent->execute($contentIdentity); + $currentAssets = $this->extractAssetFromContent->execute($data); /** @var AssetInterface $asset */ - foreach ($assetsInContent as $asset) { - if (!isset($relations[$asset->getId()])) { - $this->assignAsset->execute($asset->getId(), $type, $entityId, $field); + foreach ($currentAssets as $asset) { + if (!in_array($asset->getId(), $existingAssetIds)) { + $this->assignAsset->execute($contentIdentity, [$asset->getId()]); } } - foreach (array_keys($relations) as $assetId) { - if (!isset($assetsInContent[$assetId])) { - $this->unassignAsset->execute($assetId, $type, $entityId, $field); + foreach ($existingAssetIds as $assetId) { + if (!isset($currentAssets[$assetId])) { + $this->unassignAsset->execute($contentIdentity, [$assetId]); } } } diff --git a/app/code/Magento/MediaContent/Test/Unit/Model/AssignAssetTest.php b/app/code/Magento/MediaContent/Test/Unit/Model/AssignAssetsTest.php similarity index 70% rename from app/code/Magento/MediaContent/Test/Unit/Model/AssignAssetTest.php rename to app/code/Magento/MediaContent/Test/Unit/Model/AssignAssetsTest.php index 98e0e8fe2606e..d2bb1ca5c59b7 100644 --- a/app/code/Magento/MediaContent/Test/Unit/Model/AssignAssetTest.php +++ b/app/code/Magento/MediaContent/Test/Unit/Model/AssignAssetsTest.php @@ -12,7 +12,8 @@ use Magento\Framework\DB\Adapter\Pdo\Mysql; use Magento\Framework\Exception\CouldNotSaveException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\MediaContent\Model\AssignAsset; +use Magento\MediaContent\Model\AssignAssets; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; @@ -20,7 +21,7 @@ /** * Tests for the AssignAsset command. */ -class AssignAssetTest extends TestCase +class AssignAssetsTest extends TestCase { /** * Media content relation data storage table name @@ -73,7 +74,7 @@ class AssignAssetTest extends TestCase private $loggerMock; /** - * @var AssignAsset + * @var AssignAssets */ private $assignAsset; @@ -93,7 +94,7 @@ protected function setUp(): void ); $this->assignAsset = (new ObjectManager($this))->getObject( - AssignAsset::class, + AssignAssets::class, [ 'resourceConnection' => $this->resourceConnectionMock, 'logger' => $this->loggerMock @@ -125,29 +126,24 @@ public function testSuccessfulExecute( ]; $this->adapterMock ->expects(self::once()) - ->method('insert') - ->with(self::PREFIXED_TABLE_MEDIA_CONTENT_ASSET, $saveData) + ->method('insertMultiple') + ->with(self::PREFIXED_TABLE_MEDIA_CONTENT_ASSET, [$saveData]) ->willReturn(self::AFFECTED_ROWS); - $this->assignAsset->execute($assetId, $contentType, $contentEntityId, $contentField); + $this->assignAsset->execute( + $this->getContentIdentity($contentType, $contentField, $contentEntityId), + [ + $assetId + ] + ); } /** * Tests with exception scenario for saving relation between media asset and media content. - * - * @param int $assetId - * @param string $contentType - * @param string $contentEntityId - * @param string $contentField - * @dataProvider assignAssetDataProvider */ - public function testExceptionExecute( - int $assetId, - string $contentType, - string $contentEntityId, - string $contentField - ): void { - $this->resourceConnectionMock->method('getConnection')->willThrowException((new \Exception())); + public function testExceptionExecute(): void { + $this->resourceConnectionMock->method('getConnection') + ->willThrowException((new \Exception())); $this->loggerMock ->expects(self::once()) @@ -155,7 +151,36 @@ public function testExceptionExecute( ->willReturnSelf(); $this->expectException(CouldNotSaveException::class); - $this->assignAsset->execute($assetId, $contentType, $contentEntityId, $contentField); + $this->assignAsset->execute( + $this->createMock(ContentIdentityInterface::class), + [ + '42' + ] + ); + } + + /** + * Get content identity mock + * + * @param string $type + * @param string $field + * @param string $id + * @return MockObject|ContentIdentityInterface + */ + private function getContentIdentity(string $type, string $field, string $id): MockObject + { + $contentIdentity = $this->createMock(ContentIdentityInterface::class); + $contentIdentity->expects($this->once()) + ->method('getEntityId') + ->willReturn($id); + $contentIdentity->expects($this->once()) + ->method('getField') + ->willReturn($field); + $contentIdentity->expects($this->once()) + ->method('getEntityType') + ->willReturn($type); + + return $contentIdentity; } /** @@ -165,6 +190,7 @@ public function testExceptionExecute( */ public function assignAssetDataProvider(): array { + return [ [ '18976345', diff --git a/app/code/Magento/MediaContent/Test/Unit/Model/GetAssetsusedInContentTest.php b/app/code/Magento/MediaContent/Test/Unit/Model/GetAssetsusedInContentTest.php index 911d9b6e6f375..5b5cf2b277ee5 100644 --- a/app/code/Magento/MediaContent/Test/Unit/Model/GetAssetsusedInContentTest.php +++ b/app/code/Magento/MediaContent/Test/Unit/Model/GetAssetsusedInContentTest.php @@ -11,7 +11,8 @@ use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; use Magento\Framework\Exception\IntegrationException; -use Magento\MediaContent\Model\GetAssetsUsedInContent; +use Magento\MediaContent\Model\GetAssetIdsUsedInContent; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; @@ -32,7 +33,7 @@ class GetAssetsusedInContentTest extends TestCase private $loggerMock; /** - * @var GetAssetsUsedInContent + * @var GetAssetIdsUsedInContent */ private $getAssetsUsedInContent; @@ -43,7 +44,10 @@ protected function setUp(): void { $this->resourceConnectionStub = $this->createMock(ResourceConnection::class); $this->loggerMock = $this->createMock(LoggerInterface::class); - $this->getAssetsUsedInContent = new GetAssetsUsedInContent($this->resourceConnectionStub, $this->loggerMock); + $this->getAssetsUsedInContent = new GetAssetIdsUsedInContent( + $this->resourceConnectionStub, + $this->loggerMock + ); } /** @@ -59,9 +63,11 @@ public function testSuccessfulGetUsedAssets( ): void { $this->configureResourceConnectionStub($expectedAssetIdList); $assetList = $this->getAssetsUsedInContent->execute( - $requestParameters['type'], - $requestParameters['entity_id'], - $requestParameters['field'] + $this->getContentIdentity( + $requestParameters['type'], + $requestParameters['field'], + $requestParameters['entity_id'] + ) ); $this->assertEquals($expectedAssetIdList, $assetList); @@ -78,7 +84,7 @@ public function testGetUsedAssetsWithException(): void ->method('critical') ->willReturnSelf(); - $this->getAssetsUsedInContent->execute('cms_page', '1', 'content'); + $this->getAssetsUsedInContent->execute($this->createMock(ContentIdentityInterface::class)); } /** @@ -103,6 +109,30 @@ private function configureResourceConnectionStub(array $expectedAssetIdList): vo ->willReturn($connectionMock); } + /** + * Get content identity mock + * + * @param string $type + * @param string $field + * @param string $id + * @return MockObject|ContentIdentityInterface + */ + private function getContentIdentity(string $type, string $field, string $id): MockObject + { + $contentIdentity = $this->createMock(ContentIdentityInterface::class); + $contentIdentity->expects($this->once()) + ->method('getEntityId') + ->willReturn($id); + $contentIdentity->expects($this->once()) + ->method('getField') + ->willReturn($field); + $contentIdentity->expects($this->once()) + ->method('getEntityType') + ->willReturn($type); + + return $contentIdentity; + } + /** * Media asset to media content relation data * @@ -118,30 +148,6 @@ public function getAssetsListRelatedToContent(): array 'field' => 'content' ], [1234123] - ], - [ - [ - 'type' => 'cms_page', - 'entity_id' => null, - 'field' => 'content' - ], - [1234123, 2425168] - ], - [ - [ - 'type' => 'catalog_category', - 'entity_id' => '1', - 'field' => null - ], - [1234123] - ], - [ - [ - 'type' => 'cbm_block', - 'entity_id' => null, - 'field' => null - ], - [1234123, 2425168] ] ]; } diff --git a/app/code/Magento/MediaContent/Test/Unit/Model/GetContentWithAssetTest.php b/app/code/Magento/MediaContent/Test/Unit/Model/GetContentWithAssetsTest.php similarity index 62% rename from app/code/Magento/MediaContent/Test/Unit/Model/GetContentWithAssetTest.php rename to app/code/Magento/MediaContent/Test/Unit/Model/GetContentWithAssetsTest.php index 3ba98a400fcba..f2958d0a378ed 100644 --- a/app/code/Magento/MediaContent/Test/Unit/Model/GetContentWithAssetTest.php +++ b/app/code/Magento/MediaContent/Test/Unit/Model/GetContentWithAssetsTest.php @@ -11,7 +11,9 @@ use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\DB\Select; use Magento\Framework\Exception\IntegrationException; -use Magento\MediaContent\Model\GetContentWithAsset; +use Magento\MediaContent\Model\GetContentWithAssets; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterfaceFactory; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; @@ -19,21 +21,8 @@ /** * Test for the GetContentWithAsset command. */ -class GetContentWithAssetTest extends TestCase +class GetContentWithAssetsTest extends TestCase { - /** - * Expected list of assets for the return statement. - */ - private const EXPECTED_LIST_OF_ASSETS = - [ - 1234123 => [ - 1234123, - 'cms_page', - '1', - 'content', - ] - ]; - /** * @var ResourceConnection | MockObject */ @@ -45,10 +34,15 @@ class GetContentWithAssetTest extends TestCase private $loggerMock; /** - * @var GetContentWithAsset + * @var GetContentWithAssets */ private $getContentWithAsset; + /** + * @var ContentIdentityInterfaceFactory + */ + private $factory; + /** * @inheritdoc */ @@ -56,7 +50,12 @@ protected function setUp(): void { $this->resourceConnectionStub = $this->createMock(ResourceConnection::class); $this->loggerMock = $this->createMock(LoggerInterface::class); - $this->getContentWithAsset = new GetContentWithAsset($this->resourceConnectionStub, $this->loggerMock); + $this->factory = $this->createMock(ContentIdentityInterfaceFactory::class); + $this->getContentWithAsset = new GetContentWithAssets( + $this->factory, + $this->resourceConnectionStub, + $this->loggerMock + ); } /** @@ -65,10 +64,20 @@ protected function setUp(): void public function testSuccessfulGetContentWithAsset(): void { $assetId = 1234123; - $this->configureResourceConnectionStub(); - $assetList = $this->getContentWithAsset->execute($assetId); + $contentIdentityData = [ + 'entity_type' => 'catalog_product', + 'entity_id' => 42, + 'field' => 'desctiption' + ]; + $this->configureResourceConnectionStub($contentIdentityData); + + $contentIdentity = $this->createMock(ContentIdentityInterface::class); + $this->factory->expects($this->once()) + ->method('create') + ->with(['data' => $contentIdentityData]) + ->willReturn($contentIdentity); - $this->assertEquals(self::EXPECTED_LIST_OF_ASSETS, $assetList); + $this->assertEquals([$contentIdentity], $this->getContentWithAsset->execute([$assetId])); } /** @@ -82,13 +91,15 @@ public function testGetContentWithAssetWithException(): void ->method('critical') ->willReturnSelf(); - $this->getContentWithAsset->execute(1); + $this->getContentWithAsset->execute([1]); } /** * Configure resource connection for the command. Based on the current implementation. + * + * @param array $contentIdentityData */ - private function configureResourceConnectionStub(): void + private function configureResourceConnectionStub(array $contentIdentityData): void { $selectStub = $this->createMock(Select::class); $selectStub->method('from')->willReturnSelf(); @@ -99,7 +110,7 @@ private function configureResourceConnectionStub(): void $connectionMock->expects($this->any()) ->method('fetchAssoc') ->with($selectStub) - ->willReturn(self::EXPECTED_LIST_OF_ASSETS); + ->willReturn([$contentIdentityData]); $this->resourceConnectionStub->expects($this->any()) ->method('getConnection') ->willReturn($connectionMock); diff --git a/app/code/Magento/MediaContent/Test/Unit/Model/UnassignAssetTest.php b/app/code/Magento/MediaContent/Test/Unit/Model/UnassignAssetTest.php index ac35ef6e75dd2..5b5fc41cb29fa 100644 --- a/app/code/Magento/MediaContent/Test/Unit/Model/UnassignAssetTest.php +++ b/app/code/Magento/MediaContent/Test/Unit/Model/UnassignAssetTest.php @@ -12,7 +12,8 @@ use Magento\Framework\DB\Adapter\Pdo\Mysql; use Magento\Framework\Exception\CouldNotDeleteException; use Magento\Framework\TestFramework\Unit\Helper\ObjectManager; -use Magento\MediaContent\Model\UnassignAsset; +use Magento\MediaContent\Model\UnassignAssets; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Log\LoggerInterface; @@ -68,7 +69,7 @@ class UnassignAssetTest extends TestCase private $loggerMock; /** - * @var UnassignAsset + * @var UnassignAssets */ private $unassignAsset; @@ -88,7 +89,7 @@ protected function setUp(): void ); $this->unassignAsset = (new ObjectManager($this))->getObject( - UnassignAsset::class, + UnassignAssets::class, [ 'resourceConnection' => $this->resourceConnectionMock, 'logger' => $this->loggerMock @@ -117,39 +118,66 @@ public function testSuccessfulUnassignAsset( ->with( self::PREFIXED_TABLE_MEDIA_CONTENT_ASSET, [ - self::ASSET_ID . ' = ?' => $assetId, + self::ASSET_ID . ' IN (?)' => [$assetId], self::TYPE . ' = ?' => $contentType, self::ENTITY_ID . ' = ?' => $contentEntityId, self::FIELD . ' = ?' => $contentField ] ); - $this->unassignAsset->execute($assetId, $contentType, $contentEntityId, $contentField); + $this->unassignAsset->execute( + $this->getContentIdentity( + $contentType, + $contentField, + $contentEntityId + ), + [ + $assetId + ] + ); } /** * Test exception scenario for deleting relation between media asset and media content. - * - * @param int $assetId - * @param string $contentType - * @param string $contentEntityId - * @param string $contentField - * @dataProvider unassignAssetDataProvider - * @return void */ - public function testUnassignAssetWithException( - int $assetId, - string $contentType, - string $contentEntityId, - string $contentField - ): void { - $this->resourceConnectionMock->method('getConnection')->willThrowException((new \Exception())); + public function testUnassignAssetWithException(): void { + $this->resourceConnectionMock->method('getConnection') + ->willThrowException((new \Exception())); $this->expectException(CouldNotDeleteException::class); $this->loggerMock->expects($this->once()) ->method('critical') ->willReturnSelf(); - $this->unassignAsset->execute($assetId, $contentType, $contentEntityId, $contentField); + $this->unassignAsset->execute( + $this->createMock(ContentIdentityInterface::class), + [ + '42' + ] + ); + } + + /** + * Get content identity mock + * + * @param string $type + * @param string $field + * @param string $id + * @return MockObject|ContentIdentityInterface + */ + private function getContentIdentity(string $type, string $field, string $id): MockObject + { + $contentIdentity = $this->createMock(ContentIdentityInterface::class); + $contentIdentity->expects($this->once()) + ->method('getEntityId') + ->willReturn($id); + $contentIdentity->expects($this->once()) + ->method('getField') + ->willReturn($field); + $contentIdentity->expects($this->once()) + ->method('getEntityType') + ->willReturn($type); + + return $contentIdentity; } /** diff --git a/app/code/Magento/MediaContent/etc/db_schema_whitelist.json b/app/code/Magento/MediaContent/etc/db_schema_whitelist.json index 9b55f29a3b039..071dc72b3a467 100644 --- a/app/code/Magento/MediaContent/etc/db_schema_whitelist.json +++ b/app/code/Magento/MediaContent/etc/db_schema_whitelist.json @@ -7,8 +7,7 @@ "field": true }, "constraint": { - "PRIMARY": true, - "MEDIA_CONTENT_ASSET_ASSET_ID_MEDIA_GALLERY_ASSET_ID": true + "PRIMARY": true } } } diff --git a/app/code/Magento/MediaContent/etc/di.xml b/app/code/Magento/MediaContent/etc/di.xml index 15fa68bce99a0..ef3262ea09a79 100644 --- a/app/code/Magento/MediaContent/etc/di.xml +++ b/app/code/Magento/MediaContent/etc/di.xml @@ -6,16 +6,17 @@ */ --> - - - - - + + + + + + - + diff --git a/app/code/Magento/MediaContent/etc/module.xml b/app/code/Magento/MediaContent/etc/module.xml index ebf2a2f0d9277..58cff2aabf3a6 100644 --- a/app/code/Magento/MediaContent/etc/module.xml +++ b/app/code/Magento/MediaContent/etc/module.xml @@ -6,9 +6,5 @@ */ --> - - - - - + diff --git a/app/code/Magento/MediaContentApi/Api/AssignAssetInterface.php b/app/code/Magento/MediaContentApi/Api/AssignAssetsInterface.php similarity index 59% rename from app/code/Magento/MediaContentApi/Api/AssignAssetInterface.php rename to app/code/Magento/MediaContentApi/Api/AssignAssetsInterface.php index a0436b57e01af..21ab0b08e15c5 100644 --- a/app/code/Magento/MediaContentApi/Api/AssignAssetInterface.php +++ b/app/code/Magento/MediaContentApi/Api/AssignAssetsInterface.php @@ -8,21 +8,20 @@ namespace Magento\MediaContentApi\Api; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; + /** * Saving data represents relation between the media asset and media content * @api */ -interface AssignAssetInterface +interface AssignAssetsInterface { /** * Save relation between media asset and media content. * - * @param int $assetId - * @param string $contentType - * @param string $contentEntityId - * @param string $contentField - * + * @param ContentIdentityInterface $contentIdentity + * @param int[] $assetIds * @throws \Magento\Framework\Exception\CouldNotSaveException */ - public function execute(int $assetId, string $contentType, string $contentEntityId, string $contentField): void; + public function execute(ContentIdentityInterface $contentIdentity, array $assetIds): void; } diff --git a/app/code/Magento/MediaContentApi/Api/Data/ContentIdentityInterface.php b/app/code/Magento/MediaContentApi/Api/Data/ContentIdentityInterface.php new file mode 100644 index 0000000000000..c107a9cd124db --- /dev/null +++ b/app/code/Magento/MediaContentApi/Api/Data/ContentIdentityInterface.php @@ -0,0 +1,37 @@ +contentIdentityFactory = $contentIdentityFactory; $this->processor = $processor; $this->fields = $fields; } @@ -47,17 +60,23 @@ public function __construct(UpdateRelationsInterface $processor, array $fields) */ public function execute(Observer $observer): void { - /** @var CatalogCategory $model */ $model = $observer->getEvent()->getData('category'); - if ($model instanceof AbstractModel) { + + if ($model instanceof CatalogCategory) { foreach ($this->fields as $field) { if (!$model->dataHasChangedFor($field)) { continue; } $this->processor->execute( - self::CONTENT_TYPE, - $field, - (string) $model->getId(), + $this->contentIdentityFactory->create( + [ + 'data' => [ + self::TYPE => self::CONTENT_TYPE, + self::FIELD => $field, + self::ENTITY_ID => (string) $model->getId(), + ] + ] + ), (string) $model->getData($field) ); } diff --git a/app/code/Magento/MediaContentCatalog/Observer/Product.php b/app/code/Magento/MediaContentCatalog/Observer/Product.php index 9349d5ff90be0..d250a02498da5 100644 --- a/app/code/Magento/MediaContentCatalog/Observer/Product.php +++ b/app/code/Magento/MediaContentCatalog/Observer/Product.php @@ -10,8 +10,8 @@ use Magento\Catalog\Model\Product as CatalogProduct; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; -use Magento\Framework\Model\AbstractModel; use Magento\MediaContentApi\Api\UpdateRelationsInterface; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterfaceFactory; /** * Observe the catalog_product_save_after event and run processing relation between product content and media asset @@ -19,6 +19,9 @@ class Product implements ObserverInterface { private const CONTENT_TYPE = 'catalog_product'; + private const TYPE = 'entity_type'; + private const ENTITY_ID = 'entity_id'; + private const FIELD = 'field'; /** * @var UpdateRelationsInterface @@ -31,11 +34,21 @@ class Product implements ObserverInterface private $fields; /** + * @var ContentIdentityInterfaceFactory + */ + private $contentIdentityFactory; + + /** + * @param ContentIdentityInterfaceFactory $contentIdentityFactory * @param UpdateRelationsInterface $processor * @param array $fields */ - public function __construct(UpdateRelationsInterface $processor, array $fields) - { + public function __construct( + ContentIdentityInterfaceFactory $contentIdentityFactory, + UpdateRelationsInterface $processor, + array $fields + ) { + $this->contentIdentityFactory = $contentIdentityFactory; $this->processor = $processor; $this->fields = $fields; } @@ -47,18 +60,23 @@ public function __construct(UpdateRelationsInterface $processor, array $fields) */ public function execute(Observer $observer): void { - /** @var CatalogProduct $model */ $model = $observer->getEvent()->getData('product'); - if ($model instanceof AbstractModel) { + if ($model instanceof CatalogProduct) { foreach ($this->fields as $field) { if (!$model->dataHasChangedFor($field)) { continue; } $this->processor->execute( - self::CONTENT_TYPE, - $field, - (string) $model->getId(), + $this->contentIdentityFactory->create( + [ + 'data' => [ + self::TYPE => self::CONTENT_TYPE, + self::FIELD => $field, + self::ENTITY_ID => (string) $model->getId(), + ] + ] + ), (string) $model->getData($field) ); } diff --git a/app/code/Magento/MediaContentCatalog/etc/di.xml b/app/code/Magento/MediaContentCatalog/etc/di.xml index a9cd9ac8bd796..88c92f6028b02 100644 --- a/app/code/Magento/MediaContentCatalog/etc/di.xml +++ b/app/code/Magento/MediaContentCatalog/etc/di.xml @@ -22,7 +22,7 @@ - + /^\/?media\/(.*)/ diff --git a/app/code/Magento/MediaContentCms/Observer/Block.php b/app/code/Magento/MediaContentCms/Observer/Block.php index 9d5d24d422a78..17bf5bd88acac 100644 --- a/app/code/Magento/MediaContentCms/Observer/Block.php +++ b/app/code/Magento/MediaContentCms/Observer/Block.php @@ -10,8 +10,8 @@ use Magento\Cms\Block\Block as CmsBlock; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; -use Magento\Framework\Model\AbstractModel; use Magento\MediaContentApi\Api\UpdateRelationsInterface; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterfaceFactory; /** * Observe cms_block_save_after event and run processing relation between cms block content and media asset @@ -19,6 +19,9 @@ class Block implements ObserverInterface { private const CONTENT_TYPE = 'cms_block'; + private const TYPE = 'entity_type'; + private const ENTITY_ID = 'entity_id'; + private const FIELD = 'field'; /** * @var UpdateRelationsInterface @@ -31,11 +34,21 @@ class Block implements ObserverInterface private $fields; /** + * @var ContentIdentityInterfaceFactory + */ + private $contentIdentityFactory; + + /** + * @param ContentIdentityInterfaceFactory $contentIdentityFactory * @param UpdateRelationsInterface $processor * @param array $fields */ - public function __construct(UpdateRelationsInterface $processor, array $fields) - { + public function __construct( + ContentIdentityInterfaceFactory $contentIdentityFactory, + UpdateRelationsInterface $processor, + array $fields + ) { + $this->contentIdentityFactory = $contentIdentityFactory; $this->processor = $processor; $this->fields = $fields; } @@ -47,17 +60,23 @@ public function __construct(UpdateRelationsInterface $processor, array $fields) */ public function execute(Observer $observer): void { - /** @var CmsBlock $model */ $model = $observer->getEvent()->getData('object'); - if ($model instanceof AbstractModel) { + + if ($model instanceof CmsBlock) { foreach ($this->fields as $field) { if (!$model->dataHasChangedFor($field)) { continue; } $this->processor->execute( - self::CONTENT_TYPE, - $field, - (string) $model->getId(), + $this->contentIdentityFactory->create( + [ + 'data' => [ + self::TYPE => self::CONTENT_TYPE, + self::FIELD => $field, + self::ENTITY_ID => (string) $model->getId(), + ] + ] + ), (string) $model->getData($field) ); } diff --git a/app/code/Magento/MediaContentCms/Observer/Page.php b/app/code/Magento/MediaContentCms/Observer/Page.php index 111b4478a9888..727efe3dc2ef0 100644 --- a/app/code/Magento/MediaContentCms/Observer/Page.php +++ b/app/code/Magento/MediaContentCms/Observer/Page.php @@ -10,8 +10,8 @@ use Magento\Cms\Model\Page as CmsPage; use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; -use Magento\Framework\Model\AbstractModel; use Magento\MediaContentApi\Api\UpdateRelationsInterface; +use Magento\MediaContentApi\Api\Data\ContentIdentityInterfaceFactory; /** * Observe cms_page_save_after event and run processing relation between cms page content and media asset. @@ -19,6 +19,9 @@ class Page implements ObserverInterface { private const CONTENT_TYPE = 'cms_page'; + private const TYPE = 'entity_type'; + private const ENTITY_ID = 'entity_id'; + private const FIELD = 'field'; /** * @var UpdateRelationsInterface @@ -31,11 +34,21 @@ class Page implements ObserverInterface private $fields; /** + * @var ContentIdentityInterfaceFactory + */ + private $contentIdentityFactory; + + /** + * @param ContentIdentityInterfaceFactory $contentIdentityFactory * @param UpdateRelationsInterface $processor * @param array $fields */ - public function __construct(UpdateRelationsInterface $processor, array $fields) - { + public function __construct( + ContentIdentityInterfaceFactory $contentIdentityFactory, + UpdateRelationsInterface $processor, + array $fields + ) { + $this->contentIdentityFactory = $contentIdentityFactory; $this->processor = $processor; $this->fields = $fields; } @@ -47,17 +60,23 @@ public function __construct(UpdateRelationsInterface $processor, array $fields) */ public function execute(Observer $observer): void { - /** @var CmsPage $model */ $model = $observer->getEvent()->getData('object'); - if ($model instanceof AbstractModel) { + + if ($model instanceof CmsPage) { foreach ($this->fields as $field) { if (!$model->dataHasChangedFor($field)) { continue; } $this->processor->execute( - self::CONTENT_TYPE, - $field, - (string) $model->getId(), + $this->contentIdentityFactory->create( + [ + 'data' => [ + self::TYPE => self::CONTENT_TYPE, + self::FIELD => $field, + self::ENTITY_ID => (string) $model->getId(), + ] + ] + ), (string) $model->getData($field) ); } diff --git a/app/code/Magento/MediaContentCms/etc/di.xml b/app/code/Magento/MediaContentCms/etc/di.xml index 165c295c28208..e1f94ec753c7b 100644 --- a/app/code/Magento/MediaContentCms/etc/di.xml +++ b/app/code/Magento/MediaContentCms/etc/di.xml @@ -20,7 +20,7 @@ - + /{{media url="?(.*?)"?}}/ From 909ea3f184eaeeb3caff92178722ec02a48a813d Mon Sep 17 00:00:00 2001 From: Sergii Ivashchenko Date: Sat, 4 Apr 2020 17:28:17 +0100 Subject: [PATCH 21/89] agento/magento2#27499: Updated blacklist patterns --- app/code/Magento/MediaGallery/etc/di.xml | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/app/code/Magento/MediaGallery/etc/di.xml b/app/code/Magento/MediaGallery/etc/di.xml index c993d82342326..8910a2261005c 100644 --- a/app/code/Magento/MediaGallery/etc/di.xml +++ b/app/code/Magento/MediaGallery/etc/di.xml @@ -29,14 +29,15 @@ - /pub\/media\/captcha/ - /pub\/media\/catalog\/product/ - /pub\/media\/customer/ - /pub\/media\/downloadable/ - /pub\/media\/import/ - /pub\/media\/theme/ - /pub\/media\/theme_customization/ - /pub\/media\/tmp/ + /^captcha/ + /^catalog\/product/ + /^customer/ + /^downloadable/ + /^import/ + /^theme/ + /^theme_customization/ + /^tmp/ + /^\./ From 2b5975c83701fa1039c84b8034b19c719dd10c7a Mon Sep 17 00:00:00 2001 From: Sergii Ivashchenko Date: Mon, 6 Apr 2020 14:19:21 +0100 Subject: [PATCH 22/89] magento/magento2#27536: Improved interfaces comments and introduced MediaContentCms sequence --- app/code/Magento/Cms/etc/module.xml | 1 + .../Magento/MediaContentApi/Api/AssignAssetsInterface.php | 4 ++-- .../MediaContentApi/Api/ExtractAssetsFromContentInterface.php | 4 ++-- .../MediaContentApi/Api/GetAssetIdsUsedInContentInterface.php | 4 ++-- .../MediaContentApi/Api/GetContentWithAssetsInterface.php | 4 ++-- .../Magento/MediaContentApi/Api/UnassignAssetsInterface.php | 4 ++-- .../Magento/MediaContentApi/Api/UpdateRelationsInterface.php | 4 ++-- app/code/Magento/MediaContentCms/etc/module.xml | 4 +++- 8 files changed, 16 insertions(+), 13 deletions(-) diff --git a/app/code/Magento/Cms/etc/module.xml b/app/code/Magento/Cms/etc/module.xml index d3fc2846217d9..4c2e91ad5e172 100644 --- a/app/code/Magento/Cms/etc/module.xml +++ b/app/code/Magento/Cms/etc/module.xml @@ -11,6 +11,7 @@ + diff --git a/app/code/Magento/MediaContentApi/Api/AssignAssetsInterface.php b/app/code/Magento/MediaContentApi/Api/AssignAssetsInterface.php index 21ab0b08e15c5..6a7ba1abbff6e 100644 --- a/app/code/Magento/MediaContentApi/Api/AssignAssetsInterface.php +++ b/app/code/Magento/MediaContentApi/Api/AssignAssetsInterface.php @@ -11,13 +11,13 @@ use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; /** - * Saving data represents relation between the media asset and media content + * Assign a media asset to the piece of content. Should be executed when media assets is added to the content * @api */ interface AssignAssetsInterface { /** - * Save relation between media asset and media content. + * Assign a media asset to the piece of content. Should be executed when media assets is added to the content * * @param ContentIdentityInterface $contentIdentity * @param int[] $assetIds diff --git a/app/code/Magento/MediaContentApi/Api/ExtractAssetsFromContentInterface.php b/app/code/Magento/MediaContentApi/Api/ExtractAssetsFromContentInterface.php index 8f1b438361501..4f95571f30ffd 100644 --- a/app/code/Magento/MediaContentApi/Api/ExtractAssetsFromContentInterface.php +++ b/app/code/Magento/MediaContentApi/Api/ExtractAssetsFromContentInterface.php @@ -10,13 +10,13 @@ use Magento\MediaGalleryApi\Api\Data\AssetInterface; /** - * Used for extracting media asset list from a media content by the search pattern. + * Parse the content string for references to media assets and return the list of identified media assets * @api */ interface ExtractAssetsFromContentInterface { /** - * Search for the media asset in content and extract it providing a list of media assets. + * Parse the content string for references to media assets and return the list of identified media assets * * @param string $content * @return AssetInterface[] diff --git a/app/code/Magento/MediaContentApi/Api/GetAssetIdsUsedInContentInterface.php b/app/code/Magento/MediaContentApi/Api/GetAssetIdsUsedInContentInterface.php index ef6b98ba1505c..91faa6b7646fc 100644 --- a/app/code/Magento/MediaContentApi/Api/GetAssetIdsUsedInContentInterface.php +++ b/app/code/Magento/MediaContentApi/Api/GetAssetIdsUsedInContentInterface.php @@ -11,13 +11,13 @@ use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; /** - * Get media asset ids used in the content + * Get media asset ids that are used in the piece of content identified by the specified content identity * @api */ interface GetAssetIdsUsedInContentInterface { /** - * Get media asset ids used in the content + * Get media asset ids that are used in the piece of content identified by the specified content identity * * @param ContentIdentityInterface $contentIdentity * @return int[] diff --git a/app/code/Magento/MediaContentApi/Api/GetContentWithAssetsInterface.php b/app/code/Magento/MediaContentApi/Api/GetContentWithAssetsInterface.php index abfc3f94fa6b0..ec940829ce6fc 100644 --- a/app/code/Magento/MediaContentApi/Api/GetContentWithAssetsInterface.php +++ b/app/code/Magento/MediaContentApi/Api/GetContentWithAssetsInterface.php @@ -11,13 +11,13 @@ use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; /** - * Get media content list which is used with the specified media asset + * Get list of content identifiers for pieces of content that include the specified media asset * @api */ interface GetContentWithAssetsInterface { /** - * Get media asset to content relations by media asset id. + * Get list of content identifiers for pieces of content that include the specified media asset * * @param int[] $assetIds * @return ContentIdentityInterface[] diff --git a/app/code/Magento/MediaContentApi/Api/UnassignAssetsInterface.php b/app/code/Magento/MediaContentApi/Api/UnassignAssetsInterface.php index 348d213fd9074..462d1c188a168 100644 --- a/app/code/Magento/MediaContentApi/Api/UnassignAssetsInterface.php +++ b/app/code/Magento/MediaContentApi/Api/UnassignAssetsInterface.php @@ -11,13 +11,13 @@ use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; /** - * Unassign relation between the media asset and media content where the media asset is used + * Remove the relation between media asset and the piece of content. I.e media asset no longer part of the content * @api */ interface UnassignAssetsInterface { /** - * Remove relation between the media asset and media content. + * Remove relation between the media asset and the content. I.e media asset no longer part of the content * * @param int[] $assetIds * @param ContentIdentityInterface $contentIdentity diff --git a/app/code/Magento/MediaContentApi/Api/UpdateRelationsInterface.php b/app/code/Magento/MediaContentApi/Api/UpdateRelationsInterface.php index 7faab00846495..d9ccdb5759e6b 100644 --- a/app/code/Magento/MediaContentApi/Api/UpdateRelationsInterface.php +++ b/app/code/Magento/MediaContentApi/Api/UpdateRelationsInterface.php @@ -10,12 +10,12 @@ use Magento\MediaContentApi\Api\Data\ContentIdentityInterface; /** - * Process relation managing between media asset and content: assign or unassign relation if exists. + * Update the media assets to content relations. Assign new media assets and unassign media assets no longer used */ interface UpdateRelationsInterface { /** - * Create new relation between media asset and content or updated existing + * Update the media assets to content relations. Assign new media assets and unassign media assets no longer used * * @param ContentIdentityInterface $contentIdentity * @param string $content diff --git a/app/code/Magento/MediaContentCms/etc/module.xml b/app/code/Magento/MediaContentCms/etc/module.xml index 7278f82890b42..e273636359b5b 100644 --- a/app/code/Magento/MediaContentCms/etc/module.xml +++ b/app/code/Magento/MediaContentCms/etc/module.xml @@ -6,5 +6,7 @@ */ --> - + + + From c839ecc74d2cf74236e1df9818c3ff8b6df1d1ae Mon Sep 17 00:00:00 2001 From: Stanislav Idolov Date: Mon, 6 Apr 2020 16:20:32 -0500 Subject: [PATCH 23/89] magento/adobe-stock-integration#935 : Loader stays over the media gallery if it was opened second time from different control on the same page --- .../Framework/Data/Form/Element/Editor.php | 26 +++++++++++-------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/lib/internal/Magento/Framework/Data/Form/Element/Editor.php b/lib/internal/Magento/Framework/Data/Form/Element/Editor.php index 08a5edd09bf35..41e27b1d431b2 100644 --- a/lib/internal/Magento/Framework/Data/Form/Element/Editor.php +++ b/lib/internal/Magento/Framework/Data/Form/Element/Editor.php @@ -286,15 +286,19 @@ protected function _getPluginButtonsHtml($visible = true) // Button to media images insertion window if ($this->getConfig('add_images')) { + $htmlId = $this->getHtmlId(); + $url = $this->getConfig('files_browser_window_url') + . 'target_element_id/' + . $htmlId + . '/' + . (null !== $this->getConfig('store_id') + ? 'store/' . $this->getConfig('store_id') . '/"' + : ''); $buttonsHtml .= $this->_getButtonHtml( [ 'title' => $this->translate('Insert Image...'), - 'onclick' => "MediabrowserUtility.openDialog('" - . $this->getConfig('files_browser_window_url') - . "target_element_id/" . $this->getHtmlId() . "/" - . (null !== $this->getConfig('store_id') ? 'store/' - . $this->getConfig('store_id') . '/' : '') - . "')", + 'onclick' => 'MediabrowserUtility.openDialog(\'' . $url + . '\', null, null, null, { \'targetElementId\': \'' . $htmlId . '\' })', 'class' => 'action-add-image plugin', 'style' => $visible ? '' : 'display:none', ] @@ -496,13 +500,13 @@ protected function getInlineJs($jsSetupObject, $forceLoad) $jsString = '