ltsecurityinc安防产品在线商城代码

This commit is contained in:
2026-09-14 17:47:10 +08:00
parent 57d8444c15
commit 6a3c9c5bd8
14539 changed files with 1775310 additions and 0 deletions
@@ -0,0 +1,35 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Cms\Block;
class BlockTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoAppArea frontend
* @magentoDataFixture Magento/Cms/_files/block.php
* @magentoDataFixture Magento/Variable/_files/variable.php
* @magentoConfigFixture current_store web/unsecure/base_url http://example.com/
* @magentoConfigFixture current_store web/unsecure/base_link_url http://example.com/
*/
public function testToHtml()
{
$cmsBlock = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Cms\Model\Block::class
);
$cmsBlock->load('fixture_block', 'identifier');
/** @var $block \Magento\Cms\Block\Block */
$block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Cms\Block\Block::class
);
$block->setBlockId($cmsBlock->getId());
$result = $block->toHtml();
$this->assertStringContainsString('<a href="http://example.com/', $result);
$this->assertStringContainsString('<p>Config value: "http://example.com/".</p>', $result);
$this->assertStringContainsString('<p>Custom variable: "HTML Value".</p>', $result);
}
}
@@ -0,0 +1,26 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Cms\Block;
class PageTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Cms/_files/pages.php
*/
public function testGetPage()
{
$page = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Cms\Model\Page::class);
$page->load('page100', 'identifier');
$layout = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
);
$pageBlock = $layout->createBlock(\Magento\Cms\Block\Page::class);
$pageBlock->setData('page', $page);
$pageBlock->toHtml();
$this->assertEquals($page, $pageBlock->getPage());
}
}
@@ -0,0 +1,36 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Cms\Block\Widget;
class BlockTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoDataFixture Magento/Cms/_files/block.php
* @magentoDataFixture Magento/Variable/_files/variable.php
* @magentoConfigFixture current_store web/unsecure/base_url http://example.com/
* @magentoConfigFixture current_store web/unsecure/base_link_url http://example.com/
*/
public function testToHtml()
{
$cmsBlock = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Cms\Model\Block::class
);
$cmsBlock->load('fixture_block', 'identifier');
/** @var $block \Magento\Cms\Block\Widget\Block */
$block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\LayoutInterface::class
)->createBlock(
\Magento\Cms\Block\Widget\Block::class
);
$block->setBlockId($cmsBlock->getId());
$block->toHtml();
$result = $block->getText();
$this->assertStringContainsString('<a href="http://example.com/', $result);
$this->assertStringContainsString('<p>Config value: "http://example.com/".</p>', $result);
$this->assertStringContainsString('<p>Custom variable: "HTML Value".</p>', $result);
$this->assertSame($cmsBlock->getIdentities(), $block->getIdentities());
}
}
@@ -0,0 +1,78 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Command;
use Magento\Cms\Model\Wysiwyg\Validator;
use Magento\Framework\App\Config\ReinitableConfigInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Tester\CommandTester;
/**
* Test the command.
*
* @magentoAppIsolation enabled
* @magentoDbIsolation enabled
*/
class WysiwygRestrictCommandTest extends TestCase
{
/**
* @var ReinitableConfigInterface
*/
private $config;
/**
* @var WysiwygRestrictCommandFactory
*/
private $factory;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->config = $objectManager->get(ReinitableConfigInterface::class);
$this->factory = $objectManager->get(WysiwygRestrictCommandFactory::class);
}
/**
* "Execute" method cases.
*
* @return array
*/
public function getExecuteCases(): array
{
return [
'yes' => ['y', true],
'no' => ['n', false],
'no-but-different' => ['what', false]
];
}
/**
* Test the command.
*
* @param string $argument
* @param bool $expectedFlag
* @return void
* @dataProvider getExecuteCases
* @magentoConfigFixture default_store cms/wysiwyg/force_valid 0
*/
public function testExecute(string $argument, bool $expectedFlag): void
{
/** @var WysiwygRestrictCommand $model */
$model = $this->factory->create();
$tester = new CommandTester($model);
$tester->execute(['restrict' => $argument]);
$this->config->reinit();
$this->assertEquals($expectedFlag, $this->config->isSetFlag(Validator::CONFIG_PATH_THROW_EXCEPTION));
}
}
@@ -0,0 +1,48 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Controller\Adminhtml\Block;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* @magentoAppArea adminhtml
*/
class CreateTest extends AbstractBackendController
{
/**
* Test create CMS block with invalid URL
*
* @return void
*/
public function testCreateBlockWithInvalidUrl(): void
{
$identifier = 'admin';
$reservedWords = 'admin, soap, rest, graphql, standard';
$sessionMessages = [sprintf(
'URL key &quot;%s&quot; matches a reserved endpoint name (%s). Use another URL key.',
$identifier,
$reservedWords
)];
$requestData = [
'title' => 'block title',
'identifier' => $identifier,
'content' => '',
'is_active' => 1,
];
$this->getRequest()->setMethod(Http::METHOD_POST);
$this->getRequest()->setPostValue($requestData);
$this->dispatch('backend/cms/block/save');
$this->assertSessionMessages(
self::equalTo($sessionMessages),
MessageInterface::TYPE_ERROR
);
}
}
@@ -0,0 +1,67 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Controller\Adminhtml\Block;
use Magento\Cms\Api\Data\BlockInterface;
use Magento\Cms\Api\GetBlockByIdentifierInterface;
use Magento\Framework\App\Request\Http;
use Magento\Framework\Message\MessageInterface;
use Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Checks that cms block can be successfully deleted
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class DeleteTest extends AbstractBackendController
{
/** @var GetBlockByIdentifierInterface */
private $getBlockByIdentifier;
/** @var StoreManagerInterface */
private $storeManager;
/** @var CollectionFactory */
private $collectionFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->getBlockByIdentifier = $this->_objectManager->get(GetBlockByIdentifierInterface::class);
$this->storeManager = $this->_objectManager->get(StoreManagerInterface::class);
$this->collectionFactory = $this->_objectManager->get(CollectionFactory::class);
}
/**
* @magentoDataFixture Magento/Cms/_files/block_default_store.php
*
* @return void
*/
public function testDeleteBlock(): void
{
$defaultStoreId = (int)$this->storeManager->getStore('default')->getId();
$blockId = $this->getBlockByIdentifier->execute('default_store_block', $defaultStoreId)->getId();
$this->getRequest()->setMethod(Http::METHOD_POST)
->setParams(['block_id' => $blockId]);
$this->dispatch('backend/cms/block/delete');
$this->assertSessionMessages(
$this->containsEqual((string)__('You deleted the block.')),
MessageInterface::TYPE_SUCCESS
);
$this->assertRedirect($this->stringContains('cms/block/index'));
$collection = $this->collectionFactory->getReport('cms_block_listing_data_source');
$this->assertNull($collection->getItemByColumnValue(BlockInterface::IDENTIFIER, 'default_store_block'));
}
}
@@ -0,0 +1,69 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Controller\Adminhtml;
use Magento\TestFramework\TestCase\AbstractBackendController;
/**
* Testing seach in grid.
*
* @magentoAppArea adminhtml
* @magentoDataFixture Magento/Cms/Fixtures/page_list.php
*/
class FulltextGridSearchTest extends AbstractBackendController
{
/**
* Checks a fulltext grid search by CMS page title.
*
* @param string $query
* @param int $expectedRows
* @param array $expectedTitles
* @dataProvider queryDataProvider
*/
public function testSearchByTitle(string $query, int $expectedRows, array $expectedTitles)
{
$url = 'backend/mui/index/render/?namespace=cms_page_listing&search=' . $query;
$this->getRequest()
->getHeaders()
->addHeaderLine('Accept', 'application/json');
$this->dispatch($url);
$response = $this->getResponse();
$data = json_decode($response->getBody(), true);
self::assertEquals($expectedRows, $data['totalRecords']);
$titleList = array_column($data['items'], 'title');
self::assertEquals($expectedTitles, $titleList);
}
/**
* Gets list of variations with different search queries.
*
* @return array
*/
public function queryDataProvider(): array
{
return [
[
'query' => 'simple',
'expectedRows' => 3,
'expectedTitles' => ['simplePage', 'simplePage01', '01simplePage']
],
[
'query' => 'page01',
'expectedRows' => 1,
'expectedTitles' => ['simplePage01']
],
[
'query' => '01simple',
'expectedRows' => 1,
'expectedTitles' => ['01simplePage']
],
];
}
}
@@ -0,0 +1,336 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Controller\Adminhtml;
use Magento\Cms\Api\Data\PageInterface;
use Magento\Cms\Api\GetPageByIdentifierInterface;
use Magento\Cms\Controller\Adminhtml\Page\PostDataProcessor;
use Magento\Cms\Model\Page;
use Magento\Cms\Model\Page\CustomLayout\CustomLayoutManager;
use Magento\Cms\Model\Page\CustomLayoutManagerInterface;
use Magento\Framework\Acl\Builder;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\Message\MessageInterface;
use Magento\TestFramework\Bootstrap;
use Magento\TestFramework\Helper\Bootstrap as BootstrapHelper;
use Magento\TestFramework\TestCase\AbstractBackendController;
use Magento\UrlRewrite\Model\ResourceModel\UrlRewriteCollection;
use Magento\UrlRewrite\Model\ResourceModel\UrlRewriteCollectionFactory;
use Magento\UrlRewrite\Model\UrlRewrite;
/**
* Test the saving CMS pages design via admin area interface.
*
* @magentoAppArea adminhtml
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class PageDesignTest extends AbstractBackendController
{
/**
* @var string
*/
protected $resource = 'Magento_Cms::save';
/**
* @var string
*/
protected $uri = 'backend/cms/page/save';
/**
* @var string
*/
protected $httpMethod = HttpRequest::METHOD_POST;
/**
* @var Builder
*/
private $aclBuilder;
/**
* @var GetPageByIdentifierInterface
*/
private $pageRetriever;
/**
* @var ScopeConfigInterface
*/
private $scopeConfig;
/**
* @var string[]
*/
private $pagesToDelete = [];
/**
* @var PostDataProcessor
*/
private $postDataProcessor;
/**
* @inheritDoc
*/
protected function setUp(): void
{
BootstrapHelper::getObjectManager()->configure([
'preferences' => [
CustomLayoutManagerInterface::class => CustomLayoutManager::class
]
]);
parent::setUp();
$this->aclBuilder = BootstrapHelper::getObjectManager()->get(Builder::class);
$this->pageRetriever = BootstrapHelper::getObjectManager()->get(GetPageByIdentifierInterface::class);
$this->scopeConfig = BootstrapHelper::getObjectManager()->get(ScopeConfigInterface::class);
$this->pagesToDelete = [];
$this->postDataProcessor = BootstrapHelper::getObjectManager()->get(PostDataProcessor::class);
}
/**
* @inheritDoc
*/
protected function tearDown(): void
{
parent::tearDown();
$pageIds = [];
foreach ($this->pagesToDelete as $identifier) {
$pageIds[] = $identifier;
$page = $this->pageRetriever->execute($identifier, 0);
$page->delete();
}
$this->removeUrlRewrites();
}
/**
* Removes url rewrites created during test execution.
*
* @return void
*/
private function removeUrlRewrites(): void
{
if (!empty($this->pagesToDelete)) {
$urlRewriteCollectionFactory = BootstrapHelper::getObjectManager()->get(
UrlRewriteCollectionFactory::class
);
/** @var UrlRewriteCollection $urlRewriteCollection */
$urlRewriteCollection = $urlRewriteCollectionFactory->create();
$urlRewriteCollection->addFieldToFilter('request_path', ['in' => $this->pagesToDelete]);
$urlRewrites = $urlRewriteCollection->getItems();
/** @var UrlRewrite $urlRewrite */
foreach ($urlRewrites as $urlRewrite) {
try {
$urlRewrite->delete();
} catch (\Exception $exception) {
// already removed
}
}
}
}
/**
* Check whether additional authorization is required for the design fields.
*
* @magentoDbIsolation disabled
* @return void
*/
public function testSaveDesign(): void
{
//Expected list of sessions messages collected throughout the controller calls.
$sessionMessages = ['You are not allowed to change CMS pages design settings'];
//Test page data.
$id = 'test-page' .rand(1111, 9999);
$requestData = [
PageInterface::IDENTIFIER => $id,
PageInterface::TITLE => 'Page title',
PageInterface::CUSTOM_THEME => '1',
PageInterface::PAGE_LAYOUT => 'empty'
];
//Creating a new page with design properties without the required permissions.
$this->aclBuilder->getAcl()->deny(
Bootstrap::ADMIN_ROLE_ID,
'Magento_Cms::save_design'
);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($requestData);
$this->dispatch($this->uri);
$this->assertSessionMessages(
self::equalTo($sessionMessages),
MessageInterface::TYPE_ERROR
);
//Trying again with the permissions.
$this->aclBuilder->getAcl()->allow(
Bootstrap::ADMIN_ROLE_ID,
['Magento_Cms::save', 'Magento_Cms::save_design']
);
$this->getRequest()->setDispatched(false);
$this->dispatch($this->uri);
/** @var Page $page */
$page = BootstrapHelper::getObjectManager()->create(PageInterface::class);
$page->load($id, PageInterface::IDENTIFIER);
$this->assertNotEmpty($page->getId());
$this->assertEquals(1, $page->getCustomTheme());
$requestData['page_id'] = $page->getId();
$this->getRequest()->setPostValue($requestData);
//Updating the page without the permissions but not touching design settings.
$this->aclBuilder->getAcl()->deny(
Bootstrap::ADMIN_ROLE_ID,
'Magento_Cms::save_design'
);
$this->getRequest()->setDispatched(false);
$this->dispatch($this->uri);
$this->assertSessionMessages(self::equalTo($sessionMessages), MessageInterface::TYPE_ERROR);
//Updating design settings without the permissions.
$requestData[PageInterface::CUSTOM_THEME] = '2';
$this->getRequest()->setPostValue($requestData);
$this->getRequest()->setDispatched(false);
$this->dispatch($this->uri);
$sessionMessages[] = $sessionMessages[0];
$this->assertSessionMessages(
self::equalTo($sessionMessages),
MessageInterface::TYPE_ERROR
);
$this->pagesToDelete = [$id];
}
/**
* Check that default design values are accepted without the permissions.
*
* @magentoDbIsolation disabled
* @return void
*/
public function testSaveDesignWithDefaults(): void
{
//Test page data.
$id = 'test-page' .rand(1111, 9999);
$defaultLayout = $this->scopeConfig->getValue('web/default_layouts/default_cms_layout');
$requestData = [
PageInterface::IDENTIFIER => $id,
PageInterface::TITLE => 'Page title',
PageInterface::PAGE_LAYOUT => $defaultLayout
];
//Creating a new page with design properties without the required permissions but with default values.
$this->aclBuilder->getAcl()->deny(
Bootstrap::ADMIN_ROLE_ID,
'Magento_Cms::save_design'
);
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($requestData);
$this->dispatch($this->uri);
//Validating saved page
/** @var Page $page */
$page = BootstrapHelper::getObjectManager()->create(PageInterface::class);
$page->load($id, PageInterface::IDENTIFIER);
$this->assertNotEmpty($page->getId());
$this->assertNotNull($page->getPageLayout());
$this->assertEquals($defaultLayout, $page->getPageLayout());
$this->pagesToDelete = [$id];
}
/**
* Test that custom layout update fields are dealt with properly.
*
* @magentoDataFixture Magento/Cms/_files/pages_with_layout_xml.php
* @throws \Throwable
* @return void
*/
public function testSaveLayoutXml(): void
{
$page = $this->pageRetriever->execute('test_custom_layout_page_1', 0);
$requestData = [
Page::PAGE_ID => $page->getId(),
PageInterface::IDENTIFIER => 'test_custom_layout_page_1',
PageInterface::TITLE => 'Page title',
PageInterface::CUSTOM_LAYOUT_UPDATE_XML => $page->getCustomLayoutUpdateXml(),
PageInterface::LAYOUT_UPDATE_XML => $page->getLayoutUpdateXml(),
'layout_update_selected' => '_existing_'
];
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($requestData);
$this->dispatch($this->uri);
$this->getRequest()->setDispatched(false);
$updated = $this->pageRetriever->execute('test_custom_layout_page_1', 0);
$this->assertEquals($updated->getCustomLayoutUpdateXml(), $page->getCustomLayoutUpdateXml());
$this->assertEquals($updated->getLayoutUpdateXml(), $page->getLayoutUpdateXml());
$requestData = [
Page::PAGE_ID => $page->getId(),
PageInterface::IDENTIFIER => 'test_custom_layout_page_1',
PageInterface::TITLE => 'Page title',
PageInterface::CUSTOM_LAYOUT_UPDATE_XML => $page->getCustomLayoutUpdateXml(),
PageInterface::LAYOUT_UPDATE_XML => $page->getLayoutUpdateXml(),
'layout_update_selected' => '_no_update_'
];
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($requestData);
$this->dispatch($this->uri);
$this->getRequest()->setDispatched(false);
$updated = $this->pageRetriever->execute('test_custom_layout_page_1', 0);
$this->assertEmpty($updated->getCustomLayoutUpdateXml());
$this->assertEmpty($updated->getLayoutUpdateXml());
$this->pagesToDelete = ['test_custom_layout_page_1'];
}
/**
* Test create CMS page with invalid URL
*
* @return void
*/
public function testSaveWithInlavidIdentifier(): void
{
$identifier = 'admin';
$reservedWords = 'admin, soap, rest, graphql, standard';
//Expected list of sessions messages collected throughout the controller calls.
$sessionMessages = [sprintf(
'URL key "%s" matches a reserved endpoint name (%s). Use another URL key.',
$identifier,
$reservedWords
)];
$requestData = [
PageInterface::IDENTIFIER => $identifier,
PageInterface::TITLE => 'page title',
PageInterface::CUSTOM_THEME => '1',
PageInterface::PAGE_LAYOUT => 'empty',
];
$this->getRequest()->setMethod(HttpRequest::METHOD_POST);
$this->getRequest()->setPostValue($requestData);
$this->dispatch($this->uri);
$this->assertSessionMessages(
self::equalTo($sessionMessages),
MessageInterface::TYPE_ERROR
);
}
/**
* Test create CMS page with invalid layout update
*
* @return void
*/
public function testSaveWithCustomLayoutUpdate(): void
{
$requestData = [
PageInterface::IDENTIFIER => 'randomidentified',
PageInterface::TITLE => 'page title',
PageInterface::CUSTOM_THEME => '1',
PageInterface::PAGE_LAYOUT => 'empty',
PageInterface::CUSTOM_LAYOUT_UPDATE_XML => '<container />',
PageInterface::LAYOUT_UPDATE_XML => '<container />',
];
$this->assertFalse($this->postDataProcessor->validate($requestData));
}
}
@@ -0,0 +1,286 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Controller\Adminhtml\Wysiwyg\Images;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Filesystem\Directory\DenyListPathValidator;
use Magento\Framework\Filesystem\Directory\WriteInterface;
use Magento\Framework\Filesystem\Driver\File;
use Magento\RemoteStorage\Driver\DriverPool;
use Magento\RemoteStorage\Model\Filesystem\Directory\WriteFactory;
/**
* Test for \Magento\Cms\Controller\Adminhtml\Wysiwyg\Images\DeleteFiles class.
*
* @magentoAppArea adminhtml
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class DeleteFilesTest extends \PHPUnit\Framework\TestCase
{
private const MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH
= 'system/media_storage_configuration/allowed_resources/media_gallery_image_folders';
/**
* @var array
*/
private $origConfigValue;
/**
* @var \Magento\Cms\Controller\Adminhtml\Wysiwyg\Images\DeleteFiles
*/
private $model;
/**
* @var \Magento\Cms\Helper\Wysiwyg\Images
*/
private $imagesHelper;
/**
* @var WriteInterface
*/
private $mediaDirectory;
/**
* @var string
*/
private $fullDirectoryPath;
/**
* @var string
*/
private $fileName = 'magento_small_image.jpg';
/**
* @var \Magento\Framework\Filesystem
*/
private $filesystem;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var DirectoryList
*/
private $directoryList;
/**
* @var WriteInterface
*/
private $bypassDenyListWrite;
/**
* @inheritdoc
* @throws FileSystemException
*/
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$directoryName = 'testDir';
$this->directoryList = $this->objectManager->get(DirectoryList::class);
$this->filesystem = $this->objectManager->get(\Magento\Framework\Filesystem::class);
/** @var \Magento\Cms\Helper\Wysiwyg\Images $imagesHelper */
$this->imagesHelper = $this->objectManager->get(\Magento\Cms\Helper\Wysiwyg\Images::class);
$this->mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->fullDirectoryPath = $this->imagesHelper->getStorageRoot() . $directoryName;
$this->mediaDirectory->create($this->mediaDirectory->getRelativePath($this->fullDirectoryPath));
$filePath = $this->fullDirectoryPath . DIRECTORY_SEPARATOR . $this->fileName;
$fixtureDir = realpath(__DIR__ . '/../../../../../Catalog/_files');
$this->copyFile($fixtureDir . '/' . $this->fileName, $filePath);
$this->model = $this->objectManager->get(\Magento\Cms\Controller\Adminhtml\Wysiwyg\Images\DeleteFiles::class);
$config = $this->objectManager->get(ScopeConfigInterface::class);
$this->origConfigValue = $config->getValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
'default'
);
$scopeConfig = $this->objectManager->get(\Magento\Framework\App\Config\MutableScopeConfigInterface::class);
$scopeConfig->setValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
array_merge($this->origConfigValue, ['testDir']),
);
}
protected function tearDown(): void
{
$this->mediaDirectory->delete($this->mediaDirectory->getRelativePath($this->fullDirectoryPath));
$this->mediaDirectory->delete('secondDir');
$scopeConfig = $this->objectManager->get(\Magento\Framework\App\Config\MutableScopeConfigInterface::class);
$scopeConfig->setValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
$this->origConfigValue
);
}
/**
* Execute method with correct directory path and file name to check that files under WYSIWYG media directory
* can be removed.
*
* @param string $filename
* @return void
* @dataProvider executeDataProvider
*/
public function testExecute(string $filename)
{
$filePath = $this->fullDirectoryPath . DIRECTORY_SEPARATOR . $filename;
$fixtureDir = realpath(__DIR__ . '/../../../../../Catalog/_files');
$this->copyFile($fixtureDir . '/' . $this->fileName, $filePath);
$this->model->getRequest()->setMethod('POST')
->setPostValue('files', [$this->imagesHelper->idEncode($filename)]);
$this->model->getStorage()->getSession()->setCurrentPath($this->fullDirectoryPath);
$this->model->execute();
$this->assertFalse(
$this->mediaDirectory->isExist(
$this->mediaDirectory->getRelativePath($this->fullDirectoryPath . '/' . $filename)
)
);
}
/**
* DataProvider for testExecute
*
* @return array
*/
public function executeDataProvider(): array
{
return [
['name with spaces.jpg'],
['name with, comma.jpg'],
['name with* asterisk.jpg'],
['name with[ bracket.jpg'],
['magento_small_image.jpg'],
['_.jpg'],
[' - .jpg'],
['-.jpg'],
];
}
/**
* Check that htaccess file couldn't be removed via
* \Magento\Cms\Controller\Adminhtml\Wysiwyg\Images\DeleteFiles::execute method
*
* @return void
*/
public function testDeleteHtaccess()
{
$testDir = $this->imagesHelper->getStorageRoot() . "directory1";
$this->mediaDirectory->create($this->mediaDirectory->getRelativePath($testDir));
$path = $testDir . '/.htaccess';
$denyListPathValidator = $this->objectManager
->create(DenyListPathValidator::class, ['driver' => $this->mediaDirectory->getDriver()]);
$denyListPathValidator->addException($path);
$bypassDenyListWriteFactory = $this->objectManager->create(WriteFactory::class, [
'denyListPathValidator' => $denyListPathValidator
]);
$this->bypassDenyListWrite = $bypassDenyListWriteFactory->create(
$this->mediaDirectory->getAbsolutePath(),
$this->mediaDirectory->getDriver() instanceof File ? DriverPool::FILE : DriverPool::REMOTE,
null,
DirectoryList::MEDIA
);
if (!$this->bypassDenyListWrite->isFile($path)) {
$this->bypassDenyListWrite->writeFile($path, "Order deny,allow\nDeny from all");
}
$this->model->getRequest()->setMethod('POST')
->setPostValue('files', [$this->imagesHelper->idEncode('.htaccess')]);
$this->model->getStorage()->getSession()->setCurrentPath($testDir);
$this->model->execute();
$this->assertTrue(
$this->bypassDenyListWrite->isExist(
$this->bypassDenyListWrite->getRelativePath($testDir . '/' . '.htaccess')
)
);
$this->bypassDenyListWrite->delete($testDir);
}
/**
* Execute method with traversal file path to check that there is no ability to remove file which is not
* under media directory.
*
* @return void
*/
public function testExecuteWithWrongFileName()
{
$fixtureDir = realpath(__DIR__ . '/../../../../../Catalog/_files');
$this->mediaDirectory->create('secondDir');
$driver = $this->mediaDirectory->getDriver();
$driver->filePutContents(
$this->mediaDirectory->getAbsolutePath('secondDir' . DIRECTORY_SEPARATOR . $this->fileName),
file_get_contents($fixtureDir . '/' . $this->fileName)
);
$fileName = '/../secondDir/' . $this->fileName;
$this->model->getRequest()->setMethod('POST')
->setPostValue('files', [$this->imagesHelper->idEncode($fileName)]);
$this->model->getStorage()->getSession()->setCurrentPath($this->fullDirectoryPath);
$this->model->execute();
$this->assertTrue($this->mediaDirectory->isExist($this->fullDirectoryPath . $fileName));
}
/**
* Execute method with correct directory path and file name to check that files under linked media directory
* can be removed.
*
* @return void
* @magentoDataFixture Magento/Cms/_files/linked_media.php
*/
public function testExecuteWithLinkedMedia()
{
if (!$this->mediaDirectory->getDriver() instanceof File) {
self::markTestSkipped('Remote storages like AWS S3 doesn\'t support symlinks');
}
$directoryName = 'linked_media';
$fullDirectoryPath = $this->filesystem->getDirectoryRead(DirectoryList::PUB)
->getAbsolutePath() . DIRECTORY_SEPARATOR . $directoryName;
$filePath = $fullDirectoryPath . DIRECTORY_SEPARATOR . $this->fileName;
$fixtureDir = realpath(__DIR__ . '/../../../../../Catalog/_files');
$this->copyFile($fixtureDir . '/' . $this->fileName, $filePath);
$wysiwygDir = $this->mediaDirectory->getAbsolutePath() . '/wysiwyg';
$this->model->getRequest()->setMethod('POST')
->setPostValue('files', [$this->imagesHelper->idEncode($this->fileName)]);
$this->model->getStorage()->getSession()->setCurrentPath($wysiwygDir);
$this->model->execute();
$this->assertFalse(is_file($fullDirectoryPath . DIRECTORY_SEPARATOR . $this->fileName));
}
/**
* @inheritdoc
*/
public static function tearDownAfterClass(): void
{
$filesystem = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->get(\Magento\Framework\Filesystem::class);
/** @var WriteInterface $directory */
$directory = $filesystem->getDirectoryWrite(DirectoryList::MEDIA);
if ($directory->isExist('wysiwyg')) {
$directory->delete('wysiwyg');
}
}
/**
* @param string $source
* @param string $destination
* @throws FileSystemException
*/
private function copyFile(string $source, string $destination)
{
$driver = $this->mediaDirectory->getDriver();
$driver->createDirectory(dirname($destination));
$driver->filePutContents($destination, file_get_contents($source));
}
}
@@ -0,0 +1,213 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Cms\Controller\Adminhtml\Wysiwyg\Images;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Response\HttpFactory as ResponseFactory;
use Magento\Framework\Filesystem\Driver\File;
/**
* Test for \Magento\Cms\Controller\Adminhtml\Wysiwyg\Images\DeleteFolder class.
*
* @magentoAppArea adminhtml
*/
class DeleteFolderTest extends \PHPUnit\Framework\TestCase
{
private const MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH
= 'system/media_storage_configuration/allowed_resources/media_gallery_image_folders';
/**
* @var array
*/
private $origConfigValue;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var \Magento\Cms\Controller\Adminhtml\Wysiwyg\Images\DeleteFolder
*/
private $model;
/**
* @var \Magento\Cms\Helper\Wysiwyg\Images
*/
private $imagesHelper;
/**
* @var \Magento\Framework\Filesystem\Directory\WriteInterface
*/
private $mediaDirectory;
/**
* @var string
*/
private $fullDirectoryPath;
/**
* @var \Magento\Framework\Filesystem
*/
private $filesystem;
/**
* @var HttpFactory
*/
private $responseFactory;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->filesystem = $this->objectManager->get(\Magento\Framework\Filesystem::class);
$this->mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
/** @var \Magento\Cms\Helper\Wysiwyg\Images $imagesHelper */
$this->imagesHelper = $this->objectManager->get(\Magento\Cms\Helper\Wysiwyg\Images::class);
$this->fullDirectoryPath = $this->imagesHelper->getStorageRoot();
$this->mediaDirectory->create($this->mediaDirectory->getRelativePath($this->fullDirectoryPath));
$this->responseFactory = $this->objectManager->get(ResponseFactory::class);
$this->model = $this->objectManager->get(\Magento\Cms\Controller\Adminhtml\Wysiwyg\Images\DeleteFolder::class);
$config = $this->objectManager->get(ScopeConfigInterface::class);
$this->origConfigValue = $config->getValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
'default'
);
$scopeConfig = $this->objectManager->get(\Magento\Framework\App\Config\MutableScopeConfigInterface::class);
$scopeConfig->setValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
array_merge($this->origConfigValue, ['testDir']),
);
}
protected function tearDown(): void
{
$directoryName = 'testDir';
$this->mediaDirectory->delete(
$this->mediaDirectory->getRelativePath($this->imagesHelper->getStorageRoot() . '/' . $directoryName)
);
$this->mediaDirectory->delete('secondDir');
$scopeConfig = $this->objectManager->get(\Magento\Framework\App\Config\MutableScopeConfigInterface::class);
$scopeConfig->setValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
$this->origConfigValue
);
}
/**
* Execute method with correct directory path to check that directories under WYSIWYG media directory
* can be removed.
*
* @return void
* @magentoAppIsolation enabled
*/
public function testExecute()
{
$directoryName = 'testDir/NewDirectory';
$path = $this->mediaDirectory->getRelativePath($this->fullDirectoryPath . $directoryName);
$this->mediaDirectory->create($path);
$this->model->getRequest()->setParams(['node' => $this->imagesHelper->idEncode($path)]);
$this->model->getRequest()->setMethod('POST');
$this->model->execute();
$this->assertFalse($this->mediaDirectory->isExist($path));
}
/**
* Execute method with correct directory path to check that directories under linked media directory
* can be removed.
*
* @magentoDataFixture Magento/Cms/_files/linked_media.php
* @magentoAppIsolation enabled
*/
public function testExecuteWithLinkedMedia()
{
if (!$this->mediaDirectory->getDriver() instanceof File) {
self::markTestSkipped('Remote storages like AWS S3 doesn\'t support symlinks');
}
$linkedDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::PUB);
$linkedDirectoryPath = $this->filesystem->getDirectoryRead(DirectoryList::PUB)
->getAbsolutePath() . 'linked_media';
$directoryName = 'NewDirectory';
$linkedDirectory->create(
$linkedDirectory->getRelativePath($linkedDirectoryPath . DIRECTORY_SEPARATOR . $directoryName)
);
$this->model->getRequest()->setParams(
['node' => $this->imagesHelper->idEncode('wysiwyg' . DIRECTORY_SEPARATOR . $directoryName)]
);
$this->model->execute();
$this->assertFalse(is_dir($linkedDirectoryPath . DIRECTORY_SEPARATOR . $directoryName));
}
/**
* Execute method with traversal directory path to check that there is no ability to remove folder which is not
* under media directory.
*
* @return void
* @magentoAppIsolation enabled
*/
public function testExecuteWithWrongDirectoryName()
{
$secondDir = $this->mediaDirectory->getRelativePath($this->fullDirectoryPath . 'secondDir');
$this->mediaDirectory->create($secondDir);
$testDir = $this->mediaDirectory->getRelativePath($this->fullDirectoryPath . 'testDir');
$this->mediaDirectory->create($testDir);
$directoryName = 'testDir/../secondDir/';
$this->assertTrue($this->mediaDirectory->isExist($this->fullDirectoryPath . $directoryName));
$this->model->getRequest()->setParams(['node' => $this->imagesHelper->idEncode($directoryName)]);
$this->model->execute();
$this->assertTrue($this->mediaDirectory->isExist($this->fullDirectoryPath . $directoryName));
}
/**
* Execute method to check that there is no ability to remove folder which is in excluded directories list.
*
* @return void
* @magentoAppIsolation enabled
*/
public function testExecuteWithExcludedDirectoryName()
{
$directoryName = 'downloadable';
$expectedResponseMessage = 'We cannot delete the selected directory.';
$mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$mediaDirectory->create($directoryName);
$this->assertTrue($this->mediaDirectory->isExist($this->fullDirectoryPath . $directoryName));
$this->model->getRequest()->setParams(['node' => $this->imagesHelper->idEncode($directoryName)]);
$this->model->getRequest()->setMethod('POST');
$jsonResponse = $this->model->execute();
$jsonResponse->renderResult($response = $this->responseFactory->create());
$data = json_decode($response->getBody(), true);
$this->assertTrue($data['error']);
$this->assertEquals($expectedResponseMessage, $data['message']);
$this->assertTrue($this->mediaDirectory->isExist($this->fullDirectoryPath . $directoryName));
}
/**
* @inheritdoc
*/
public static function tearDownAfterClass(): void
{
$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('wysiwyg')) {
$directory->delete('wysiwyg');
}
if ($directory->isExist('downloadable')) {
$directory->delete('downloadable');
}
}
}
@@ -0,0 +1,19 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Cms\Controller\Adminhtml\Wysiwyg\Images;
class IndexTest extends \Magento\TestFramework\TestCase\AbstractBackendController
{
public function testViewAction()
{
$this->dispatch('backend/cms/wysiwyg_images/index/target_element_id/page_content/store/undefined/type/image/');
$content = $this->getResponse()->getBody();
$this->assertStringNotContainsString('<html', $content);
$this->assertStringNotContainsString('<head', $content);
$this->assertStringNotContainsString('<body', $content);
}
}
@@ -0,0 +1,174 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Cms\Controller\Adminhtml\Wysiwyg\Images;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Filesystem\Driver\File;
/**
* Test for \Magento\Cms\Controller\Adminhtml\Wysiwyg\Images\NewFolder class.
*
* @magentoAppArea adminhtml
*/
class NewFolderTest extends \PHPUnit\Framework\TestCase
{
private const MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH
= 'system/media_storage_configuration/allowed_resources/media_gallery_image_folders';
/**
* @var array
*/
private $origConfigValue;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var \Magento\Cms\Controller\Adminhtml\Wysiwyg\Images\NewFolder
*/
private $model;
/**
* @var \Magento\Framework\Filesystem\Directory\WriteInterface
*/
private $mediaDirectory;
/**
* @var string
*/
private $fullDirectoryPath;
/**
* @var string
*/
private $dirName= 'NewDirectory';
/**
* @var \Magento\Framework\Filesystem
*/
private $filesystem;
/**
* @var \Magento\Cms\Helper\Wysiwyg\Images
*/
private $imagesHelper;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->filesystem = $this->objectManager->get(\Magento\Framework\Filesystem::class);
/** @var \Magento\Cms\Helper\Wysiwyg\Images $imagesHelper */
$this->imagesHelper = $this->objectManager->get(\Magento\Cms\Helper\Wysiwyg\Images::class);
$this->mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->fullDirectoryPath = $this->imagesHelper->getStorageRoot() . '/testDir';
$this->mediaDirectory->create($this->mediaDirectory->getRelativePath($this->fullDirectoryPath));
$this->model = $this->objectManager->get(\Magento\Cms\Controller\Adminhtml\Wysiwyg\Images\NewFolder::class);
$config = $this->objectManager->get(ScopeConfigInterface::class);
$this->origConfigValue = $config->getValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
'default'
);
$scopeConfig = $this->objectManager->get(\Magento\Framework\App\Config\MutableScopeConfigInterface::class);
$scopeConfig->setValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
array_merge($this->origConfigValue, ['testDir']),
);
}
protected function tearDown(): void
{
$this->mediaDirectory->delete($this->mediaDirectory->getRelativePath($this->fullDirectoryPath));
$scopeConfig = $this->objectManager->get(\Magento\Framework\App\Config\MutableScopeConfigInterface::class);
$scopeConfig->setValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
$this->origConfigValue
);
}
/**
* Execute method with correct directory path to check that new folder can be created under WYSIWYG media directory.
*
* @return void
*/
public function testExecute()
{
$this->model->getRequest()->setMethod('POST')
->setPostValue('name', $this->dirName);
$this->model->getStorage()->getSession()->setCurrentPath($this->fullDirectoryPath);
$this->model->execute();
$this->assertTrue(
$this->mediaDirectory->isExist(
$this->mediaDirectory->getRelativePath(
$this->fullDirectoryPath . DIRECTORY_SEPARATOR . $this->dirName
)
)
);
}
/**
* Execute method with correct directory path to check that new folder can be created under WYSIWYG media directory.
*
* @magentoDataFixture Magento/Cms/_files/linked_media.php
*/
public function testExecuteWithLinkedMedia()
{
if (!$this->mediaDirectory->getDriver() instanceof File) {
self::markTestSkipped('Remote storages like AWS S3 doesn\'t support symlinks');
}
$linkedDirectoryPath = $this->filesystem->getDirectoryRead(DirectoryList::PUB)
->getAbsolutePath() . 'linked_media';
$this->model->getRequest()->setMethod('POST')
->setPostValue('name', $this->dirName);
$this->model->getStorage()
->getSession()
->setCurrentPath($this->imagesHelper->getStorageRoot() . DIRECTORY_SEPARATOR . 'wysiwyg');
$this->model->execute();
$this->assertTrue(is_dir($linkedDirectoryPath . DIRECTORY_SEPARATOR . $this->dirName));
}
/**
* Execute method with traversal directory path to check that there is no ability to create new folder not
* under media directory.
*
* @return void
*/
public function testExecuteWithWrongPath()
{
$dirPath = '/../../../';
$this->model->getRequest()->setMethod('POST')
->setPostValue('name', $this->dirName);
$this->model->getStorage()->getSession()->setCurrentPath($this->fullDirectoryPath . $dirPath);
$this->model->execute();
$this->assertFileDoesNotExist(
$this->fullDirectoryPath . $dirPath . $this->dirName
);
}
/**
* @inheritdoc
*/
public static function tearDownAfterClass(): void
{
$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('wysiwyg')) {
$directory->delete('wysiwyg');
}
}
}
@@ -0,0 +1,267 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Controller\Adminhtml\Wysiwyg\Images;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Controller\Result\Json as JsonResponse;
use Magento\Framework\App\Response\HttpFactory as ResponseFactory;
use Magento\Framework\App\Response\Http as Response;
use Magento\Framework\Filesystem\Driver\File;
/**
* Test for \Magento\Cms\Controller\Adminhtml\Wysiwyg\Images\Upload class.
*
* @magentoAppArea adminhtml
*/
class UploadTest extends \PHPUnit\Framework\TestCase
{
private const MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH
= 'system/media_storage_configuration/allowed_resources/media_gallery_image_folders';
/**
* @var array
*/
private $origConfigValue;
/**
* @var \Magento\Cms\Controller\Adminhtml\Wysiwyg\Images\Upload
*/
private $model;
/**
* @var \Magento\Framework\Filesystem\Directory\WriteInterface
*/
private $mediaDirectory;
/**
* @var string
*/
private $fullDirectoryPath;
/**
* @var string
*/
private $fullExcludedDirectoryPath;
/**
* @var string
*/
private $fileName = 'magento_small_image.jpg';
/**
* @var \Magento\Framework\Filesystem
*/
private $filesystem;
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var HttpFactory
*/
private $responseFactory;
/**
* @var \Magento\Cms\Helper\Wysiwyg\Images
*/
private $imagesHelper;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$directoryName = 'testDir';
$excludedDirName = 'downloadable';
$this->filesystem = $this->objectManager->get(\Magento\Framework\Filesystem::class);
/** @var \Magento\Cms\Helper\Wysiwyg\Images $imagesHelper */
$this->imagesHelper = $this->objectManager->get(\Magento\Cms\Helper\Wysiwyg\Images::class);
$this->mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->fullDirectoryPath = rtrim($this->imagesHelper->getStorageRoot(), '/')
. DIRECTORY_SEPARATOR . $directoryName;
$this->fullExcludedDirectoryPath = $this->imagesHelper->getStorageRoot()
. DIRECTORY_SEPARATOR . $excludedDirName;
$this->mediaDirectory->create($this->mediaDirectory->getRelativePath($this->fullDirectoryPath));
$this->responseFactory = $this->objectManager->get(ResponseFactory::class);
$this->model = $this->objectManager->get(\Magento\Cms\Controller\Adminhtml\Wysiwyg\Images\Upload::class);
$fixtureDir = realpath(__DIR__ . '/../../../../../Catalog/_files');
$tmpFile = $this->filesystem->getDirectoryRead(DirectoryList::PUB)->getAbsolutePath() . $this->fileName;
copy($fixtureDir . DIRECTORY_SEPARATOR . $this->fileName, $tmpFile);
$_FILES = [
'image' => [
'name' => $this->fileName,
'type' => 'image/png',
'tmp_name' => $tmpFile,
'error' => 0,
'size' => filesize($fixtureDir),
],
];
$config = $this->objectManager->get(ScopeConfigInterface::class);
$this->origConfigValue = $config->getValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
'default'
);
$scopeConfig = $this->objectManager->get(\Magento\Framework\App\Config\MutableScopeConfigInterface::class);
$scopeConfig->setValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
array_merge($this->origConfigValue, ['testDir']),
);
}
protected function tearDown(): void
{
$directoryName = 'testDir';
$this->mediaDirectory->delete(
$this->mediaDirectory->getRelativePath($this->imagesHelper->getStorageRoot() . '/' . $directoryName)
);
$scopeConfig = $this->objectManager->get(\Magento\Framework\App\Config\MutableScopeConfigInterface::class);
$scopeConfig->setValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
$this->origConfigValue
);
}
/**
* Execute method with correct directory path and file name to check that file can be uploaded to the directory
* located under WYSIWYG media.
*
* @return void
* @magentoAppIsolation enabled
*/
public function testExecute()
{
$this->model->getRequest()->setParams(['type' => 'image/png']);
$this->model->getRequest()->setMethod('POST');
$this->model->getStorage()->getSession()->setCurrentPath($this->fullDirectoryPath);
/** @var JsonResponse $jsonResponse */
$jsonResponse = $this->model->execute();
/** @var Response $response */
$jsonResponse->renderResult($response = $this->responseFactory->create());
$data = json_decode($response->getBody(), true);
$this->assertTrue(
$this->mediaDirectory->isExist(
$this->mediaDirectory->getRelativePath(
$this->fullDirectoryPath . DIRECTORY_SEPARATOR . $this->fileName
)
)
);
//Asserting that response contains only data needed by clients.
$keys = ['name', 'type', 'error', 'size', 'file'];
sort($keys);
$dataKeys = array_keys($data);
sort($dataKeys);
$this->assertEquals($keys, $dataKeys);
}
/**
* Execute method with excluded directory path and file name to check that file can't be uploaded.
*
* @return void
* @magentoAppIsolation enabled
*/
public function testExecuteWithExcludedDirectory()
{
$expectedError = 'We can\'t upload the file to the current folder right now. Please try another folder.';
$this->model->getRequest()->setParams(['type' => 'image/png']);
$this->model->getRequest()->setMethod('POST');
$this->model->getStorage()->getSession()->setCurrentPath($this->fullExcludedDirectoryPath);
/** @var JsonResponse $jsonResponse */
$jsonResponse = $this->model->execute();
/** @var Response $response */
$jsonResponse->renderResult($response = $this->responseFactory->create());
$data = json_decode($response->getBody(), true);
$this->assertEquals($expectedError, $data['error']);
$this->assertFalse(
$this->mediaDirectory->isExist(
$this->mediaDirectory->getRelativePath(
$this->fullExcludedDirectoryPath . DIRECTORY_SEPARATOR . $this->fileName
)
)
);
}
/**
* Execute method with correct directory path and file name to check that file can be uploaded to the directory
* located under linked folder.
*
* @return void
* @magentoDataFixture Magento/Cms/_files/linked_media.php
*/
public function testExecuteWithLinkedMedia()
{
if (!$this->mediaDirectory->getDriver() instanceof File) {
self::markTestSkipped('Remote storages like AWS S3 doesn\'t support symlinks');
}
$directoryName = 'linked_media';
$fullDirectoryPath = $this->filesystem->getDirectoryRead(DirectoryList::PUB)
->getAbsolutePath() . $directoryName;
$wysiwygDir = $this->mediaDirectory->getAbsolutePath() . '/wysiwyg';
$this->model->getRequest()->setParams(['type' => 'image/png']);
$this->model->getStorage()->getSession()->setCurrentPath($wysiwygDir);
$this->model->execute();
$this->assertTrue(is_file($fullDirectoryPath . DIRECTORY_SEPARATOR . $this->fileName));
}
/**
* Execute method with traversal directory path to check that there is no ability to create file not
* under media directory.
*
* @return void
*/
public function testExecuteWithWrongPath()
{
$dirPath = '/../../../etc/';
$this->model->getRequest()->setParams(['type' => 'image/png']);
$this->model->getStorage()->getSession()->setCurrentPath($dirPath);
$this->model->execute();
$this->assertFileDoesNotExist(
$this->fullDirectoryPath . $dirPath . $this->fileName
);
}
/**
* Execute method with traversal file path to check that there is no ability to create file not
* under media directory.
*
* @return void
*/
public function testExecuteWithWrongFileName()
{
$newFilename = '/../../../../etc/new_file.png';
$_FILES['image']['name'] = $newFilename;
$_FILES['image']['tmp_name'] = __DIR__ . DIRECTORY_SEPARATOR . $this->fileName;
$this->model->getRequest()->setParams(['type' => 'image/png']);
$this->model->getStorage()->getSession()->setCurrentPath($this->fullDirectoryPath);
$this->model->execute();
$this->assertFileDoesNotExist($this->fullDirectoryPath . $newFilename);
}
/**
* @inheritdoc
*/
public static function tearDownAfterClass(): void
{
$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('wysiwyg')) {
$directory->delete('wysiwyg');
}
}
}
@@ -0,0 +1,27 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
/**
* Test class for \Magento\Cms\Controller\Page.
*/
namespace Magento\Cms\Controller\Noroute;
class IndexTest extends \Magento\TestFramework\TestCase\AbstractController
{
/**
* @magentoDbIsolation enabled
* @magentoDataFixture Magento/Cms/_files/noroute.php
*/
public function testDisabledNoRoutePage()
{
$this->dispatch('/test123');
$this->assertStringContainsString(
'There was no 404 CMS page configured or found.',
$this->getResponse()->getBody()
);
}
}
@@ -0,0 +1,150 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Cms\Controller;
use Magento\Cms\Api\GetPageByIdentifierInterface;
use Magento\Cms\Model\Page\CustomLayoutManagerInterface;
use Magento\Framework\View\LayoutInterface;
use Magento\TestFramework\Cms\Model\CustomLayoutManager;
use Magento\TestFramework\TestCase\AbstractController;
/**
* Test for \Magento\Cms\Controller\Page\View class.
*/
class PageTest extends AbstractController
{
/**
* @var GetPageByIdentifierInterface
*/
private $pageRetriever;
/**
* @inheritDoc
*/
protected function setUp(): void
{
parent::setUp();
$this->_objectManager->configure([
'preferences' => [
CustomLayoutManagerInterface::class => CustomLayoutManager::class,
]
]);
$this->pageRetriever = $this->_objectManager->get(GetPageByIdentifierInterface::class);
}
public function testViewAction()
{
$this->dispatch('/enable-cookies');
$this->assertStringContainsString('What are Cookies?', $this->getResponse()->getBody());
}
public function testViewRedirectWithTrailingSlash()
{
$this->dispatch('/enable-cookies/');
$code = $this->getResponse()->getStatusCode();
$location = $this->getResponse()->getHeader('Location')->getFieldValue();
$this->assertEquals(301, $code, 'Invalid response code');
$this->assertStringEndsWith('/enable-cookies', $location, 'Invalid location header');
}
/**
* Test \Magento\Cms\Block\Page::_addBreadcrumbs
*/
public function testAddBreadcrumbs()
{
$this->dispatch('/enable-cookies');
$layout = $this->_objectManager->get(LayoutInterface::class);
$breadcrumbsBlock = $layout->getBlock('breadcrumbs');
$this->assertStringContainsString($breadcrumbsBlock->toHtml(), $this->getResponse()->getBody());
}
/**
* @magentoDataFixture cmsPageWithSystemRouteFixture
*/
public function testCreatePageWithSameModuleName()
{
$this->dispatch('/shipping');
$content = $this->getResponse()->getBody();
$this->assertStringContainsString('Shipping Test Page', $content);
}
public static function cmsPageWithSystemRouteFixture()
{
/** @var $page \Magento\Cms\Model\Page */
$page = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(\Magento\Cms\Model\Page::class);
$page->setTitle('Test title')
->setIdentifier('shipping')
->setStores([0])
->setIsActive(1)
->setContent('<h1>Shipping Test Page</h1>')
->setPageLayout('1column')
->save();
}
/**
* Check that custom handles are applied when rendering a page.
*
* @return void
* @throws \Throwable
* @magentoDataFixture Magento/Cms/_files/pages_with_layout_xml.php
*/
public function testCustomHandles(): void
{
$page = $this->pageRetriever->execute('test_custom_layout_page_3', 0);
$this->dispatch('/cms/page/view/page_id/' . $page->getId());
/** @var LayoutInterface $layout */
$layout = $this->_objectManager->get(LayoutInterface::class);
$handles = $layout->getUpdate()->getHandles();
$this->assertContains('cms_page_view_selectable_test_custom_layout_page_3_test_selected', $handles);
}
/**
* Check home page custom handle is applied when rendering a page.
*
* @return void
* @throws \Throwable
* @magentoDataFixture Magento/Cms/_files/home_with_custom_handle.php
*/
public function testHomePageCustomHandles(): void
{
$this->dispatch('/');
/** @var LayoutInterface $layout */
$layout = $this->_objectManager->get(LayoutInterface::class);
$handles = $layout->getUpdate()->getHandles();
$this->assertContains('cms_page_view_selectable_home_page_custom_layout', $handles);
}
/**
* Tests page renders even with unavailable custom page layout.
*
* @magentoDataFixture Magento/Cms/Fixtures/page_list.php
* @dataProvider pageLayoutDataProvider
* @param string $pageIdentifier
* @return void
*/
public function testPageWithCustomLayout(string $pageIdentifier): void
{
$page = $this->pageRetriever->execute($pageIdentifier, 0);
$this->dispatch('/cms/page/view/page_id/' . $page->getId());
$this->assertStringContainsString(
'<main id="maincontent" class="page-main">',
$this->getResponse()->getBody()
);
}
/**
* @return array
*/
public function pageLayoutDataProvider(): array
{
return [
'Page with 1column layout' => ['page-with-1column-layout'],
'Page with unavailable layout' => ['page-with-unavailable-layout']
];
}
}
@@ -0,0 +1,82 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Cms\Controller;
/**
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class RouterTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Cms\Controller\Router
*/
protected $_model;
protected function setUp(): void
{
$this->markTestSkipped('MAGETWO-3393');
$this->_model = new \Magento\Cms\Controller\Router(
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\App\ActionFactory::class
),
new \Magento\Framework\Event\ManagerInterfaceStub(
$this->getMockForAbstractClass(\Magento\Framework\Event\InvokerInterface::class),
$this->createMock(\Magento\Framework\Event\Config::class),
$this->createMock(\Magento\Framework\EventFactory::class),
$this->createMock(\Magento\Framework\Event\ObserverFactory::class)
),
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Framework\UrlInterface::class),
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Cms\Model\PageFactory::class),
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Store\Model\StoreManagerInterface::class
),
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Store\Model\StoreManagerInterface::class
)
);
}
/**
* @magentoAppIsolation enabled
*/
public function testMatch()
{
$this->markTestSkipped('MAGETWO-3393');
$request = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()
->create(\Magento\Framework\App\RequestInterface::class);
//Open Node
$request->setPathInfo('parent_node');
$controller = $this->_model->match($request);
$this->assertInstanceOf(\Magento\Framework\App\Action\Redirect::class, $controller);
}
}
/**
* Event manager stub
* @codingStandardsIgnoreStart
*/
namespace Magento\Framework\Event;
class ManagerStub extends Manager
{
/**
* Stub dispatch event
*
* @param string $eventName
* @param array $params
* @return null
*/
public function dispatch($eventName, array $params = [])
{
switch ($eventName) {
case 'cms_controller_router_match_before':
$params['condition']->setRedirectUrl('http://www.example.com/');
break;
}
return null;
}
}
@@ -0,0 +1,46 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Api\Data\PageInterface;
use Magento\Cms\Api\PageRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
$data = [
[
'title' => 'simplePage',
'is_active' => 1,
],
[
'title' => 'simplePage01',
'is_active' => 1,
],
[
'title' => '01simplePage',
'is_active' => 1,
],
[
'title' => 'Page with 1column layout',
'is_active' => 1,
'content' => '<h1>Test Page Content</h1>',
'page_layout' => '1column',
],
[
'title' => 'Page with unavailable layout',
'content' => '<h1>Test Page Content</h1>',
'is_active' => 1,
'page_layout' => 'unavailable-layout',
],
];
/** @var PageRepositoryInterface $pageRepository */
$pageRepository = $objectManager->get(PageRepositoryInterface::class);
foreach ($data as $item) {
$page = $objectManager->create(PageInterface::class, ['data' => $item]);
$pageRepository->save($page);
}
@@ -0,0 +1,36 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Api\PageRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var PageRepositoryInterface $pageRepository */
$pageRepository = $objectManager->get(PageRepositoryInterface::class);
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder
->addFilter(
'title',
[
'simplePage',
'simplePage01',
'01simplePage',
'Page with 1column layout',
'Page with unavailable layout',
],
'in'
)
->create();
$result = $pageRepository->getList($searchCriteria);
foreach ($result->getItems() as $item) {
$pageRepository->delete($item);
}
@@ -0,0 +1,52 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Cms\Helper;
use Magento\Customer\Model\Context;
/**
* @magentoAppArea frontend
*/
class PageTest extends \PHPUnit\Framework\TestCase
{
/**
* @magentoAppIsolation enabled
* @magentoDataFixture Magento/Cms/_files/pages.php
*/
public function testRenderPage()
{
/** @var $objectManager \Magento\TestFramework\ObjectManager */
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$httpContext = $objectManager->get(\Magento\Framework\App\Http\Context::class);
$httpContext->setValue(Context::CONTEXT_AUTH, false, false);
$objectManager->get(\Magento\Framework\App\State::class)->setAreaCode('frontend');
$arguments = [
'request' => $objectManager->get(\Magento\TestFramework\Request::class),
'response' => $objectManager->get(\Magento\TestFramework\Response::class),
];
$context = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Framework\App\Action\Context::class,
$arguments
);
$page = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Cms\Model\Page::class);
$page->load('page_design_blank', 'identifier');
// fixture
/** @var $pageHelper \Magento\Cms\Helper\Page */
$pageHelper = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(\Magento\Cms\Helper\Page::class);
$result = $pageHelper->prepareResultPage(
\Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Framework\App\Test\Unit\Action\Stub\ActionStub::class,
['context' => $context]
),
$page->getId()
);
$design = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Framework\View\DesignInterface::class
);
$this->assertEquals('Magento/blank', $design->getDesignTheme()->getThemePath());
$this->assertInstanceOf(\Magento\Framework\View\Result\Page::class, $result);
}
}
@@ -0,0 +1,158 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Helper\Wysiwyg;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\Event\ManagerInterface;
use Magento\Framework\Filesystem;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\ObjectManager;
use PHPUnit\Framework\TestCase;
use stdClass;
class ImagesTest extends TestCase
{
/**
* @var ObjectManager
*/
private $objectManager;
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
}
public function testGetStorageRoot()
{
/** @var Filesystem $filesystem */
$filesystem = Bootstrap::getObjectManager()->get(Filesystem::class);
$mediaPath = $filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath();
/** @var Images $helper */
$helper = $this->objectManager->create(
Images::class
);
$this->assertStringStartsWith($mediaPath, $helper->getStorageRoot());
}
/**
* @magentoConfigFixture current_store web/unsecure/base_url http://example.com/
*/
public function testGetCurrentUrl()
{
/** @var Images $helper */
$helper = $this->objectManager->create(Images::class);
$this->assertStringStartsWith('http://example.com/', $helper->getCurrentUrl());
}
/**
* @param bool $isStaticUrlsAllowed
* @param string $filename
* @param bool $renderAsTag
* @param string|callable $expectedResult - string or callable to make unique assertions on $expectedResult
* @magentoConfigFixture current_store web/unsecure/base_url http://example.com/
* @dataProvider providerGetImageHtmlDeclaration
*/
public function testGetImageHtmlDeclaration(
$isStaticUrlsAllowed,
$filename,
$renderAsTag,
$expectedResult
) {
$helper = $this->generateHelper($isStaticUrlsAllowed);
$actualResult = $helper->getImageHtmlDeclaration($filename, $renderAsTag);
if (is_callable($expectedResult)) {
$expectedResult($actualResult);
} else {
$this->assertEquals(
$expectedResult,
$actualResult
);
}
}
/**
* Verify image html declaration renders correctly with custom admin url.
*
* @magentoConfigFixture default/admin/url/use_custom 1
* @magentoConfigFixture admin_store web/unsecure/base_url http://example-admin.com/
*/
public function testGetImageHtmlDeclarationCustomBackendUrl()
{
$helper = $this->generateHelper(false, 0);
$actualResult = $helper->getImageHtmlDeclaration('wysiwyg/hello.png', true);
$this->assertEquals('<img src="{{media url=&quot;wysiwyg/hello.png&quot;}}" alt="" />', $actualResult);
}
/**
* Data provider for testGetImageHtmlDeclaration
*
* @return array
*/
public function providerGetImageHtmlDeclaration()
{
return [
[true, 'wysiwyg/hello.png', true, '<img src="http://example.com/media/wysiwyg/hello.png" alt="" />'],
[
false,
'wysiwyg/hello.png',
false,
function ($actualResult) {
$expectedResult = (
'/backend/cms/wysiwyg/directive/___directive/' .
'e3ttZWRpYSB1cmw9Ind5c2l3eWcvaGVsbG8ucG5nIn19/'
);
$this->assertStringContainsString($expectedResult, parse_url($actualResult, PHP_URL_PATH));
},
],
[true, 'wysiwyg/hello.png', false, 'http://example.com/media/wysiwyg/hello.png'],
[false, 'wysiwyg/hello.png', true, '<img src="{{media url=&quot;wysiwyg/hello.png&quot;}}" alt="" />'],
];
}
/**
* Generate instance of Images Helper
*
* @param bool $isStaticUrlsAllowed - mock is created to override value of isUsingStaticUrlsAllowed method in class
* @param int $storeId
* @return Images
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
private function generateHelper($isStaticUrlsAllowed = false, int $storeId = 1)
{
$eventManagerMock = $this->createMock(ManagerInterface::class);
$contextMock = $this->objectManager->create(Context::class, [
'eventManager' => $eventManagerMock,
]);
$helper = $this->objectManager->create(Images::class, [
'context' => $contextMock,
]);
$checkResult = new stdClass();
$checkResult->isAllowed = false;
$eventManagerMock->expects($this->any())
->method('dispatch')
->with('cms_wysiwyg_images_static_urls_allowed', ['result' => $checkResult, 'store_id' => $storeId])
->willReturnCallback(function ($_, $arr) use ($isStaticUrlsAllowed) {
$arr['result']->isAllowed = $isStaticUrlsAllowed;
});
$helper->setStoreId($storeId);
return $helper;
}
}
@@ -0,0 +1,129 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Cms\Model;
use Magento\Cms\Model\ResourceModel\Block;
use Magento\Cms\Model\BlockFactory;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Framework\Stdlib\DateTime\Timezone;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* @magentoAppArea adminhtml
*/
class BlockTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @var Block
*/
private $blockResource;
/**
* @var BlockFactory
*/
private $blockFactory;
/**
* @var GetBlockByIdentifier
*/
private $blockIdentifier;
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
/** @var BlockFactory $blockFactory */
/** @var Block $blockResource */
/** @var GetBlockByIdentifier $getBlockByIdentifierCommand */
$this->blockResource = $this->objectManager->create(Block::class);
$this->blockFactory = $this->objectManager->create(BlockFactory::class);
$this->blockIdentifier = $this->objectManager->create(GetBlockByIdentifier::class);
}
/**
* Tests the get by identifier command
* @param array $blockData
* @throws \Exception
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @magentoDbIsolation enabled
* @dataProvider testGetByIdentifierDataProvider
*/
public function testGetByIdentifier(array $blockData)
{
# Prepare and save the temporary block
$tempBlock = $this->blockFactory->create();
$tempBlock->setData($blockData);
$this->blockResource->save($tempBlock);
# Load previously created block and compare identifiers
$storeId = reset($blockData['stores']);
$block = $this->blockIdentifier->execute($blockData['identifier'], $storeId);
$this->assertEquals($blockData['identifier'], $block->getIdentifier());
}
/**
* Tests the get by identifier command
* @param array $blockData
* @throws \Exception
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @magentoDbIsolation enabled
* @dataProvider testGetByIdentifierDataProvider
*/
public function testUpdateTime(array $blockData)
{
/**
* @var $db \Magento\Framework\DB\Adapter\AdapterInterface
*/
$db = $this->objectManager->get(\Magento\Framework\App\ResourceConnection::class)
->getConnection(ResourceConnection::DEFAULT_CONNECTION);
# Prepare and save the temporary block
$tempBlock = $this->blockFactory->create();
$tempBlock->setData($blockData);
$beforeTimestamp = $db->fetchCol('SELECT UNIX_TIMESTAMP()')[0];
$this->blockResource->save($tempBlock);
$afterTimestamp = $db->fetchCol('SELECT UNIX_TIMESTAMP()')[0];
# Load previously created block and compare identifiers
$storeId = reset($blockData['stores']);
$block = $this->blockIdentifier->execute($blockData['identifier'], $storeId);
$blockTimestamp = strtotime($block->getUpdateTime());
/*
* These checks prevent a race condition MAGETWO-87353
*/
$this->assertGreaterThanOrEqual($beforeTimestamp, $blockTimestamp);
$this->assertLessThanOrEqual($afterTimestamp, $blockTimestamp);
}
/**
* Data provider for "testGetByIdentifier" and "testUpdateTime" method
* @return array
*/
public function testGetByIdentifierDataProvider(): array
{
return [
[
'data' => [
'title' => 'Test title',
'stores' => [0],
'identifier' => 'test-identifier',
'content' => 'Test content',
'is_active' => 1
]
]
];
}
}
@@ -0,0 +1,105 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Model\Page;
use Magento\Cms\Model\Page;
use Magento\Cms\Model\PageFactory;
use Magento\Cms\Model\Page\CustomLayout\Data\CustomLayoutSelected;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
use Magento\Framework\View\Result\PageFactory as PageResultFactory;
use Magento\Framework\View\Model\Layout\MergeFactory;
use Magento\Framework\View\Model\Layout\Merge;
/**
* Test the manager.
*/
class CustomLayoutManagerTest extends TestCase
{
/**
* @var CustomLayoutRepositoryInterface
*/
private $repo;
/**
* @var CustomLayoutManagerInterface
*/
private $manager;
/**
* @var PageFactory
*/
private $pageFactory;
/**
* @var PageResultFactory
*/
private $resultFactory;
/**
* @var IdentityMap
*/
private $identityMap;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->resultFactory = $objectManager->get(PageResultFactory::class);
//Mocking available list of files for the page.
$handles = [
'cms_page_view_selectable_page100_select1',
'cms_page_view_selectable_page100_select2'
];
$processor = $this->getMockBuilder(Merge::class)->disableOriginalConstructor()->getMock();
$processor->method('getAvailableHandles')->willReturn($handles);
$processorFactory = $this->getMockBuilder(MergeFactory::class)->disableOriginalConstructor()->getMock();
$processorFactory->method('create')->willReturn($processor);
$this->manager = $objectManager->create(
CustomLayoutManagerInterface::class,
['layoutProcessorFactory' => $processorFactory]
);
$this->repo = $objectManager->create(
CustomLayoutRepositoryInterface::class,
['manager' => $this->manager]
);
$this->pageFactory = $objectManager->get(PageFactory::class);
$this->identityMap = $objectManager->get(IdentityMap::class);
}
/**
* Test updating a page's custom layout.
*
* @magentoDataFixture Magento/Cms/_files/pages.php
* @throws \Throwable
* @return void
*/
public function testCustomLayoutUpdate(): void
{
/** @var Page $page */
$page = $this->pageFactory->create(['customLayoutRepository' => $this->repo]);
$page->load('page100', 'identifier');
$pageId = (int)$page->getId();
$this->identityMap->add($page);
//Set file ID
$this->repo->save(new CustomLayoutSelected($pageId, 'select2'));
//Test handles
$result = $this->resultFactory->create();
$this->manager->applyUpdate($result, $this->repo->getFor($pageId));
$this->identityMap->remove((int)$page->getId());
$this->assertContains(
'cms_page_view_selectable_page100_select2',
$result->getLayout()->getUpdate()->getHandles()
);
}
}
@@ -0,0 +1,160 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Model\Page;
use Magento\Cms\Model\Page;
use Magento\Cms\Model\PageFactory;
use Magento\Cms\Model\Page\CustomLayout\Data\CustomLayoutSelected;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\View\Model\Layout\Merge;
use Magento\Framework\View\Model\Layout\MergeFactory;
use Magento\TestFramework\Cms\Model\CustomLayoutManager;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Test the repository.
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class CustomLayoutRepositoryTest extends TestCase
{
/**
* @var CustomLayoutRepositoryInterface
*/
private $repo;
/**
* @var PageFactory
*/
private $pageFactory;
/**
* @var CustomLayoutManager
*/
private $fakeManager;
/**
* @var IdentityMap
*/
private $identityMap;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$objectManager->configure([
'preferences' => [
\Magento\Cms\Model\Page\CustomLayoutManagerInterface::class =>
\Magento\TestFramework\Cms\Model\CustomLayoutManager::class
]
]);
$this->fakeManager = $objectManager->get(CustomLayoutManager::class);
$this->repo = $objectManager->create(CustomLayoutRepositoryInterface::class, ['manager' => $this->fakeManager]);
$this->pageFactory = $objectManager->get(PageFactory::class);
$this->identityMap = $objectManager->get(IdentityMap::class);
}
/**
* Create page instance.
*
* @param string $id
* @return Page
*/
private function createPage(string $id): Page
{
$page = $this->pageFactory->create(['customLayoutRepository' => $this->repo]);
$page->load($id, 'identifier');
$this->identityMap->add($page);
return $page;
}
/**
* Test updating a page's custom layout.
*
* @magentoDataFixture Magento/Cms/_files/pages.php
* @return void
*/
public function testCustomLayout(): void
{
$page = $this->createPage('page100');
$pageId = (int)$page->getId();
$this->fakeManager->fakeAvailableFiles($pageId, ['select1', 'select2']);
//Invalid file ID
$exceptionRaised = null;
try {
$this->repo->save(new CustomLayoutSelected($pageId, 'some_file'));
} catch (\Throwable $exception) {
$exceptionRaised = $exception;
}
$this->assertNotEmpty($exceptionRaised);
$this->assertInstanceOf(\InvalidArgumentException::class, $exceptionRaised);
//Set file ID
$this->repo->save(new CustomLayoutSelected($pageId, 'select2'));
//Test saved
$saved = $this->repo->getFor($pageId);
$this->assertEquals('select2', $saved->getLayoutFileId());
//Removing custom file
$this->repo->deleteFor($pageId);
//Test saved
$notFound = false;
try {
$this->repo->getFor($pageId);
} catch (NoSuchEntityException $exception) {
$notFound = true;
}
$this->assertTrue($notFound);
}
/**
* Test that layout updates are saved with save method.
*
* @magentoDataFixture Magento/Cms/_files/pages.php
* @return void
*/
public function testSaved(): void
{
$page = $this->createPage('page100');
$this->fakeManager->fakeAvailableFiles((int)$page->getId(), ['select1', 'select2']);
//Special no-update instruction
$page->setData('layout_update_selected', '_no_update_');
$page->save();
$this->assertNull($page->getData('layout_update_selected'));
//Existing file update
$page->setData('layout_update_selected', 'select1');
$page->save();
/** @var Page $page */
$page = $this->pageFactory->create();
$page->load('page100', 'identifier');
$this->assertEquals('select1', $page->getData('layout_update_selected'));
$this->assertEquals('select1', $this->repo->getFor((int)$page->getId())->getLayoutFileId());
//Invalid file
$caught = null;
$page->setData('layout_update_selected', 'nonExisting');
try {
$page->save();
} catch (\Throwable $exception) {
$caught = $exception;
}
$this->assertInstanceOf(LocalizedException::class, $caught);
$this->assertEquals($caught->getMessage(), 'Invalid Custom Layout Update selected');
}
}
@@ -0,0 +1,176 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Model\Page;
use Magento\Cms\Api\GetPageByIdentifierInterface;
use Magento\Framework\App\Request\Http as HttpRequest;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\TestFramework\Cms\Model\CustomLayoutManager;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Test pages data provider.
*
* @magentoAppArea adminhtml
*/
class DataProviderTest extends TestCase
{
private $providerData = [
'name' => 'test',
'primaryFieldName' => 'page_id',
'requestFieldName' => 'page_id',
];
/**
* @var DataProvider
*/
private $provider;
/**
* @var GetPageByIdentifierInterface
*/
private $repo;
/**
* @var CustomLayoutManager
*/
private $filesFaker;
/**
* @var HttpRequest
*/
private $request;
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->objectManager->configure([
'preferences' => [CustomLayoutManagerInterface::class => CustomLayoutManager::class]
]);
$this->repo = $this->objectManager->get(GetPageByIdentifierInterface::class);
$this->filesFaker = $this->objectManager->get(CustomLayoutManager::class);
$this->request = $this->objectManager->get(HttpRequest::class);
$this->provider = $this->objectManager->create(
DataProvider::class,
array_merge($this->providerData, ['customLayoutManager' => $this->filesFaker])
);
}
/**
* Check that custom layout date is handled properly.
*
* @magentoDataFixture Magento/Cms/_files/pages_with_layout_xml.php
* @dataProvider customLayoutDataProvider
*
* @param string $identifier
* @param string|null $layoutUpdateSelected
* @return void
*/
public function testCustomLayoutData(string $identifier, ?string $layoutUpdateSelected): void
{
$page = $this->repo->execute($identifier, 0);
$request = $this->objectManager->create(RequestInterface::class);
$request->setParam('page_id', $page->getId());
$provider = $this->objectManager->create(
DataProvider::class,
array_merge($this->providerData, ['request' => $request])
);
$data = $provider->getData();
$pageData = $data[$page->getId()];
$this->assertEquals($layoutUpdateSelected, $pageData['layout_update_selected']);
}
/**
* DataProvider for testCustomLayoutData
*
* @return array
*/
public function customLayoutDataProvider(): array
{
return [
['test_custom_layout_page_1', '_existing_'],
['test_custom_layout_page_2', null],
['test_custom_layout_page_3', 'test_selected'],
];
}
/**
* Check that proper meta for custom layout field is returned.
*
* @return void
* @throws \Throwable
* @magentoDataFixture Magento/Cms/_files/pages_with_layout_xml.php
*/
public function testCustomLayoutMeta(): void
{
//Testing a page without layout xml
$page = $this->repo->execute('test_custom_layout_page_3', 0);
$this->filesFaker->fakeAvailableFiles((int)$page->getId(), ['test1', 'test2']);
$this->request->setParam('page_id', $page->getId());
$meta = $this->provider->getMeta();
$this->assertArrayHasKey('design', $meta);
$this->assertArrayHasKey('children', $meta['design']);
$this->assertArrayHasKey('custom_layout_update_select', $meta['design']['children']);
$this->assertArrayHasKey('arguments', $meta['design']['children']['custom_layout_update_select']);
$this->assertArrayHasKey('data', $meta['design']['children']['custom_layout_update_select']['arguments']);
$this->assertArrayHasKey(
'options',
$meta['design']['children']['custom_layout_update_select']['arguments']['data']
);
$expectedList = [
['label' => 'No update', 'value' => '_no_update_'],
['label' => 'test1', 'value' => 'test1'],
['label' => 'test2', 'value' => 'test2']
];
$metaList = $meta['design']['children']['custom_layout_update_select']['arguments']['data']['options'];
sort($expectedList);
sort($metaList);
$this->assertEquals($expectedList, $metaList);
//Page with old layout xml
$page = $this->repo->execute('test_custom_layout_page_1', 0);
$this->filesFaker->fakeAvailableFiles((int)$page->getId(), ['test3']);
$this->request->setParam('page_id', $page->getId());
$meta = $this->provider->getMeta();
$this->assertArrayHasKey('design', $meta);
$this->assertArrayHasKey('children', $meta['design']);
$this->assertArrayHasKey('custom_layout_update_select', $meta['design']['children']);
$this->assertArrayHasKey('arguments', $meta['design']['children']['custom_layout_update_select']);
$this->assertArrayHasKey('data', $meta['design']['children']['custom_layout_update_select']['arguments']);
$this->assertArrayHasKey(
'options',
$meta['design']['children']['custom_layout_update_select']['arguments']['data']
);
$expectedList = [
['label' => 'No update', 'value' => '_no_update_'],
['label' => 'Use existing layout update XML', 'value' => '_existing_'],
['label' => 'test3', 'value' => 'test3'],
];
$metaList = $meta['design']['children']['custom_layout_update_select']['arguments']['data']['options'];
sort($expectedList);
sort($metaList);
$this->assertEquals($expectedList, $metaList);
}
}
@@ -0,0 +1,105 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Model;
use Magento\Cms\Api\GetPageByIdentifierInterface;
use Magento\Cms\Api\PageRepositoryInterface;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Test page repo.
*/
class PageRepositoryTest extends TestCase
{
/**
* @var PageRepositoryInterface
*/
private $repo;
/**
* @var GetPageByIdentifierInterface
*/
private $retriever;
/**
* @inheritDoc
*/
protected function setUp(): void
{
Bootstrap::getObjectManager()->configure([
'preferences' => [
\Magento\Cms\Model\Page\CustomLayoutManagerInterface::class =>
\Magento\TestFramework\Cms\Model\CustomLayoutManager::class
]
]);
$objectManager = Bootstrap::getObjectManager();
$this->repo = $objectManager->get(PageRepositoryInterface::class);
$this->retriever = $objectManager->get(GetPageByIdentifierInterface::class);
}
/**
* Test that the field is deprecated.
*
* @throws \Throwable
* @magentoDataFixture Magento/Cms/_files/pages_with_layout_xml.php
* @return void
*/
public function testSaveUpdateXml(): void
{
$page = $this->retriever->execute('test_custom_layout_page_1', 0);
$page->setTitle($page->getTitle() . 'TEST');
//Is successfully saved without changes to the custom layout xml.
$page = $this->repo->save($page);
//New value is not accepted.
$page->setCustomLayoutUpdateXml('<container name="new_container_for_save_update_xml" />');
$forbidden = false;
try {
$page = $this->repo->save($page);
} catch (CouldNotSaveException $exception) {
$forbidden = true;
}
$this->assertTrue($forbidden);
//New value is not accepted.
$page->setLayoutUpdateXml('<container name="new_container_for_save_update_xml2" />');
$forbidden = false;
try {
$page = $this->repo->save($page);
} catch (CouldNotSaveException $exception) {
$forbidden = true;
}
$this->assertTrue($forbidden);
//Can be removed
$page->setCustomLayoutUpdateXml(null);
$page->setLayoutUpdateXml(null);
$page = $this->repo->save($page);
$this->assertEmpty($page->getCustomLayoutUpdateXml());
$this->assertEmpty($page->getLayoutUpdateXml());
}
/**
* Verifies that cms page with identifier which duplicates existed route shouldn't be saved
*
* @return void
* @throws \Throwable
* @magentoDataFixture Magento/Cms/_files/pages.php
*/
public function testSaveWithRouteDuplicate(): void
{
$page = $this->retriever->execute('page100', 0);
$page->setIdentifier('customer');
$this->expectException(CouldNotSaveException::class);
$this->repo->save($page);
}
}
@@ -0,0 +1,138 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Cms\Model;
use Magento\Cms\Api\PageRepositoryInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Stdlib\DateTime\DateTime;
/**
* @magentoAppArea adminhtml
*/
class PageTest extends \PHPUnit\Framework\TestCase
{
protected function setUp(): void
{
$user = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\User\Model\User::class
)->loadByUsername(
\Magento\TestFramework\Bootstrap::ADMIN_NAME
);
/** @var $session \Magento\Backend\Model\Auth\Session */
$session = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get(
\Magento\Backend\Model\Auth\Session::class
);
$session->setUser($user);
}
/**
* Tests the get by identifier command
* @param array $pageData
* @throws \Magento\Framework\Exception\NoSuchEntityException
* @magentoDbIsolation enabled
* @dataProvider testGetByIdentifierDataProvider
*/
public function testGetByIdentifier(array $pageData)
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Cms\Model\GetPageByIdentifier $getPageByIdentifierCommand */
/** @var \Magento\Cms\Model\ResourceModel\Page $pageResource */
/** @var \Magento\Cms\Model\PageFactory $pageFactory */
$pageFactory = $objectManager->create(\Magento\Cms\Model\PageFactory::class);
$pageResource = $objectManager->create(\Magento\Cms\Model\ResourceModel\Page::class);
$getPageByIdentifierCommand = $objectManager->create(\Magento\Cms\Model\GetPageByIdentifier::class);
# Prepare and save the temporary page
$tempPage = $pageFactory->create();
$tempPage->setData($pageData);
$pageResource->save($tempPage);
# Load previously created block and compare identifiers
$storeId = reset($pageData['stores']);
$page = $getPageByIdentifierCommand->execute($pageData['identifier'], $storeId);
$this->assertEquals($pageData['identifier'], $page->getIdentifier());
}
/**
* @param array $data
* @param string $expectedIdentifier
* @magentoDbIsolation enabled
* @dataProvider generateIdentifierFromTitleDataProvider
*/
public function testGenerateIdentifierFromTitle($data, $expectedIdentifier)
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Cms\Model\Page $page */
$page = $objectManager->create(\Magento\Cms\Model\Page::class);
$page->setData($data);
$page->save();
$this->assertEquals($expectedIdentifier, $page->getIdentifier());
}
/**
* @magentoDbIsolation enabled
*/
public function testUpdateTime()
{
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/**
* @var $db \Magento\Framework\DB\Adapter\AdapterInterface
*/
$db = $objectManager->get(\Magento\Framework\App\ResourceConnection::class)
->getConnection(ResourceConnection::DEFAULT_CONNECTION);
/** @var \Magento\Cms\Model\Page $page */
$page = $objectManager->create(\Magento\Cms\Model\Page::class);
$page->setData(['title' => 'Test', 'stores' => [1]]);
$beforeTimestamp = $db->fetchCol('SELECT UNIX_TIMESTAMP()')[0];
$page->save();
$afterTimestamp = $db->fetchCol('SELECT UNIX_TIMESTAMP()')[0];
$page = $objectManager->get(PageRepositoryInterface::class)->getById($page->getId());
$pageTimestamp = strtotime($page->getUpdateTime());
/*
* These checks prevent a race condition MAGETWO-95534
*/
$this->assertGreaterThanOrEqual($beforeTimestamp, $pageTimestamp);
$this->assertLessThanOrEqual($afterTimestamp, $pageTimestamp);
}
public function generateIdentifierFromTitleDataProvider() : array
{
return [
['data' => ['title' => 'Test title', 'stores' => [1]], 'expectedIdentifier' => 'test-title'],
[
'data' => ['title' => 'Кирилический заголовок', 'stores' => [1]],
'expectedIdentifier' => 'kirilicheskij-zagolovok'
],
[
'data' => ['title' => 'Test title', 'identifier' => 'custom-identifier', 'stores' => [1]],
'expectedIdentifier' => 'custom-identifier'
]
];
}
/**
* Data provider for "testGetByIdentifier" method
* @return array
*/
public function testGetByIdentifierDataProvider() : array
{
return [
['data' => [
'title' => 'Test title',
'identifier' => 'test-identifier',
'page_layout' => '1column',
'stores' => [1],
'content' => 'Test content',
'is_active' => 1
]]
];
}
}
@@ -0,0 +1,72 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Model\ResourceModel\Block\Grid;
use Magento\Cms\Model\ResourceModel\Page;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
class CollectionTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
}
/**
* Verifies that filter condition date is being converted to config timezone before select sql query
*
* @dataProvider getCollectionFiltersDataProvider
* @return void
*/
public function testAddFieldToFilter($field): void
{
$filterDate = "2021-12-05 00:00:00";
/** @var TimezoneInterface $timeZone */
$timeZone = $this->objectManager->get(TimezoneInterface::class);
/** @var Collection $gridCollection */
$gridCollection = $this->objectManager->create(
Collection::class,
[
'mainTable' => 'cms_block',
'resourceModel' => Page::class
]
);
$convertedDate = $timeZone->convertConfigTimeToUtc($filterDate);
$collection = $gridCollection->addFieldToFilter($field, ['qteq' => $filterDate]);
$expectedSelectCondition = "`{$field}` = '{$convertedDate}'";
$this->assertStringContainsString($expectedSelectCondition, $collection->getSelectSql(true));
}
/**
* @return array
*/
public function getCollectionFiltersDataProvider(): array
{
return [
'cms_page_collection_for_creation_time' => [
'field' => 'creation_time',
],
'cms_page_collection_for_order_update_time' => [
'field' => 'update_time',
],
];
}
}
@@ -0,0 +1,72 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Model\ResourceModel\Page\Grid;
use Magento\Cms\Model\ResourceModel\Page;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
class CollectionTest extends TestCase
{
/**
* @var ObjectManagerInterface
*/
private $objectManager;
/**
* @inheritDoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
}
/**
* Verifies that filter condition date is being converted to config timezone before select sql query
*
* @dataProvider getCollectionFiltersDataProvider
* @return void
*/
public function testAddFieldToFilter($field): void
{
$filterDate = "2021-12-06 00:00:00";
/** @var TimezoneInterface $timeZone */
$timeZone = $this->objectManager->get(TimezoneInterface::class);
/** @var Collection $gridCollection */
$gridCollection = $this->objectManager->create(
Collection::class,
[
'mainTable' => 'cms_page',
'resourceModel' => Page::class
]
);
$convertedDate = $timeZone->convertConfigTimeToUtc($filterDate);
$collection = $gridCollection->addFieldToFilter($field, ['qteq' => $filterDate]);
$expectedSelectCondition = "`{$field}` = '{$convertedDate}'";
$this->assertStringContainsString($expectedSelectCondition, $collection->getSelectSql(true));
}
/**
* @return array
*/
public function getCollectionFiltersDataProvider(): array
{
return [
'cms_page_collection_for_creation_time' => [
'field' => 'creation_time',
],
'cms_page_collection_for_order_update_time' => [
'field' => 'update_time',
],
];
}
}
@@ -0,0 +1,97 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Cms\Model\Wysiwyg;
use Magento\Framework\View\DesignInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestModuleWysiwygConfig\Model\Config as TestModuleWysiwygConfig;
/**
* @magentoAppArea adminhtml
*/
class ConfigTest extends \PHPUnit\Framework\TestCase
{
/**
* @var \Magento\Cms\Model\Wysiwyg\Config
*/
private $model;
/**
* @var DesignInterface
*/
private $design;
/**
* {@inheritdoc}
*/
protected function setUp(): void
{
$objectManager = Bootstrap::getObjectManager();
$this->model = $objectManager->create(\Magento\Cms\Model\Wysiwyg\Config::class);
$this->design = $objectManager->get(DesignInterface::class);
}
/**
* Tests that config returns valid config array in it
*
* @return void
*/
public function testGetConfig()
{
$config = $this->model->getConfig();
$this->assertInstanceOf(\Magento\Framework\DataObject::class, $config);
}
/**
* Tests that config returns right urls going to the published library path
*
* @return void
*/
public function testGetConfigCssUrls()
{
$config = $this->model->getConfig();
$designTheme = $this->design->getConfigurationDesignTheme('adminhtml');
$publicPathPattern = "http://localhost/static/%s/adminhtml/{$designTheme}/en_US/%s";
$tinyMceConfig = $config->getData('tinymce');
$contentCss = $tinyMceConfig['content_css'];
if (is_array($contentCss)) {
foreach ($contentCss as $url) {
$this->assertStringMatchesFormat($publicPathPattern, $url);
}
} else {
$this->assertStringMatchesFormat($publicPathPattern, $contentCss);
}
}
/**
* Test enabled module is able to modify WYSIWYG config
*
* @return void
*
* @magentoConfigFixture default/cms/wysiwyg/editor Magento_TestModuleWysiwygConfig/wysiwyg/tinymceTestAdapter
*/
public function testTestModuleEnabledModuleIsAbleToModifyConfig()
{
$objectManager = Bootstrap::getObjectManager();
$compositeConfigProvider = $objectManager->create(\Magento\Cms\Model\Wysiwyg\CompositeConfigProvider::class);
$model = $objectManager->create(
\Magento\Cms\Model\Wysiwyg\Config::class,
['configProvider' => $compositeConfigProvider]
);
$config = $model->getConfig();
// @phpstan-ignore-next-line
$this->assertEquals(TestModuleWysiwygConfig::CONFIG_HEIGHT, $config['height']);
// @phpstan-ignore-next-line
$this->assertEquals(TestModuleWysiwygConfig::CONFIG_CONTENT_CSS, $config['content_css']);
$this->assertArrayHasKey('tinymce', $config);
$this->assertArrayHasKey('toolbar', $config['tinymce']);
$this->assertStringNotContainsString(
'charmap',
$config['tinymce']['toolbar'],
'Failed to address that the custom test module removes "charmap" button from the toolbar'
);
}
}
@@ -0,0 +1,137 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Model\Wysiwyg\Images;
use Magento\Backend\Model\UrlInterface;
use Magento\Cms\Helper\Wysiwyg\Images as ImagesHelper;
use Magento\Framework\Url\EncoderInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
class GetInsertImageContentTest extends TestCase
{
/**
* @var GetInsertImageContent
*/
private $getInsertImageContent;
/**
* @var ImagesHelper
*/
private $imagesHelper;
/**
* @var EncoderInterface
*/
private $urlEncoder;
/**
* @var UrlInterface
*/
protected $url;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->getInsertImageContent = Bootstrap::getObjectManager()->get(GetInsertImageContent::class);
$this->imagesHelper = Bootstrap::getObjectManager()->get(ImagesHelper::class);
$this->urlEncoder = Bootstrap::getObjectManager()->get(EncoderInterface::class);
$this->url = Bootstrap::getObjectManager()->get(UrlInterface::class);
}
/**
* Test for GetInsertImageContent::execute
*
* @dataProvider imageDataProvider
* @magentoDataFixture Magento/Store/_files/core_fixturestore.php
* @param string $filename
* @param bool $forceStaticPath
* @param bool $renderAsTag
* @param string|null $storeCode
* @param string $expectedResult
*/
public function testExecute(
string $filename,
bool $forceStaticPath,
bool $renderAsTag,
?string $storeCode,
string $expectedResult
): void {
$storeManager = Bootstrap::getObjectManager()->get(StoreManagerInterface::class);
$storeId = $storeCode ? (int)$storeManager->getStore($storeCode)->getId() : null;
if (!$forceStaticPath && !$renderAsTag && !$this->imagesHelper->isUsingStaticUrlsAllowed()) {
$expectedResult = $this->url->getUrl(
'cms/wysiwyg/directive',
[
'___directive' => $this->urlEncoder->encode($expectedResult),
'_escape_params' => false,
]
);
}
$this->assertEquals(
$expectedResult,
$this->getInsertImageContent->execute(
$this->imagesHelper->idEncode($filename),
$forceStaticPath,
$renderAsTag,
$storeId
)
);
}
/**
* Data provider for testExecute
*
* @return array[]
*/
public function imageDataProvider(): array
{
return [
[
'test-image.jpg',
false,
true,
'default',
'<img src="{{media url=&quot;test-image.jpg&quot;}}" alt="" />',
],
[
'catalog/category/test-image.jpg',
true,
false,
'default',
'/media/catalog/category/test-image.jpg',
],
[
'test-image.jpg',
false,
false,
'default',
'{{media url="test-image.jpg"}}',
],
[
'/test-image.jpg',
false,
true,
'fixturestore',
'<img src="{{media url=&quot;/test-image.jpg&quot;}}" alt="" />',
],
[
'test-image.jpg',
false,
true,
null,
'<img src="{{media url=&quot;test-image.jpg&quot;}}" alt="" />',
],
];
}
}
@@ -0,0 +1,185 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*
*/
namespace Magento\Cms\Model\Wysiwyg\Images;
use Magento\Cms\Model\Wysiwyg\Images\Storage\Collection;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\DataObject;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\Filesystem\DriverInterface;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test methods of class Storage
*
* @SuppressWarnings(PHPMD.LongVariable)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class GetThumbnailUrlsTest extends \PHPUnit\Framework\TestCase
{
private const MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH
= 'system/media_storage_configuration/allowed_resources/media_gallery_image_folders';
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var Storage
*/
private $storage;
/**
* @var DriverInterface
*/
private $driver;
/**
* @var array
*/
private $origConfigValue;
/**
* @var \Magento\Framework\Filesystem\Directory\WriteInterface
*/
private $mediaDirectory;
/**
* @var string
*/
private $fullDirectoryPath;
/**
* @var \Magento\Cms\Helper\Wysiwyg\Images
*/
private $imagesHelper;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->filesystem = $this->objectManager->get(Filesystem::class);
$this->imagesHelper = $this->objectManager->get(\Magento\Cms\Helper\Wysiwyg\Images::class);
$this->mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->fullDirectoryPath = rtrim($this->imagesHelper->getStorageRoot(), '/')
. '/MagentoCmsModelWysiwygImagesStorageTest';
$this->mediaDirectory->create($this->mediaDirectory->getRelativePath($this->fullDirectoryPath));
$config = $this->objectManager->get(ScopeConfigInterface::class);
$this->origConfigValue = $config->getValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
'default'
);
$scopeConfig = $this->objectManager->get(\Magento\Framework\App\Config\MutableScopeConfigInterface::class);
$scopeConfig->setValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
array_merge($this->origConfigValue, ['MagentoCmsModelWysiwygImagesStorageTest']),
);
$this->storage = $this->objectManager->create(Storage::class);
$this->driver = $this->mediaDirectory->getDriver();
}
protected function tearDown(): void
{
$this->mediaDirectory->delete($this->mediaDirectory->getRelativePath($this->fullDirectoryPath));
$scopeConfig = $this->objectManager->get(\Magento\Framework\App\Config\MutableScopeConfigInterface::class);
$scopeConfig->setValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
$this->origConfigValue
);
}
/**
* Test that getThumbnailUrl() returns correct URL for root folder or sub-folders images
*
* @param string $directory
* @param string $filename
* @param array $expectedUrls
* @return void
* @magentoAppIsolation enabled
* @magentoAppArea adminhtml
* @dataProvider getThumbnailUrlDataProvider
*/
public function testGetThumbnailUrl(string $directory, string $filename, array $expectedUrls): void
{
$root = $this->storage->getCmsWysiwygImages()->getStorageRoot();
$directory = implode('/', array_filter([rtrim($root, '/'), trim($directory, '/')]));
$path = $directory . '/' . $filename;
$this->generateImage($path);
$this->storage->resizeFile($path);
$collection = $this->storage->getFilesCollection($directory, 'image');
$paths = [];
foreach ($collection as $item) {
$paths[] = parse_url($item->getThumbUrl(), PHP_URL_PATH);
}
$this->assertEquals($expectedUrls, $paths);
$this->driver->deleteFile($path);
}
/**
* Provide scenarios for testing getThumbnailUrl()
*
* @return array
*/
public function getThumbnailUrlDataProvider(): array
{
return [
[
'/',
'image1.png',
[]
],
[
'/cms',
'image2.png',
[]
],
[
'/cms/pages',
'image3.png',
[]
],
[
'/MagentoCmsModelWysiwygImagesStorageTest',
'image2.png',
['/media/.thumbsMagentoCmsModelWysiwygImagesStorageTest/image2.png']
],
[
'/MagentoCmsModelWysiwygImagesStorageTest/pages',
'image3.png',
['/media/.thumbsMagentoCmsModelWysiwygImagesStorageTest/pages/image3.png']
]
];
}
/**
* Generate a dummy image of the given width and height.
*
* @param string $path
* @return string
*/
private function generateImage(string $path)
{
$this->mediaDirectory->create(dirname($this->mediaDirectory->getRelativePath($path)));
ob_start();
$image = imagecreatetruecolor(1024, 768);
imagepng($image);
$this->driver->filePutContents($path, ob_get_clean());
return $path;
}
}
@@ -0,0 +1,394 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*
*/
namespace Magento\Cms\Model\Wysiwyg\Images;
use Magento\Cms\Model\Wysiwyg\Images\Storage\Collection;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\DataObject;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\Filesystem\DriverInterface;
use Magento\TestFramework\Helper\Bootstrap;
/**
* Test methods of class Storage
*
* @SuppressWarnings(PHPMD.LongVariable)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class StorageTest extends \PHPUnit\Framework\TestCase
{
private const MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH
= 'system/media_storage_configuration/allowed_resources/media_gallery_image_folders';
/**
* @var \Magento\Framework\ObjectManagerInterface
*/
private $objectManager;
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var Storage
*/
private $storage;
/**
* @var DriverInterface
*/
private $driver;
/**
* @var array
*/
private $origConfigValue;
/**
* @var \Magento\Framework\Filesystem\Directory\WriteInterface
*/
private $mediaDirectory;
/**
* @var string
*/
private $fullDirectoryPath;
/**
* @var \Magento\Cms\Helper\Wysiwyg\Images
*/
private $imagesHelper;
/**
* @inheritdoc
*/
protected function setUp(): void
{
$this->objectManager = Bootstrap::getObjectManager();
$this->filesystem = $this->objectManager->get(Filesystem::class);
$this->imagesHelper = $this->objectManager->get(\Magento\Cms\Helper\Wysiwyg\Images::class);
$this->mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->fullDirectoryPath = rtrim($this->imagesHelper->getStorageRoot(), '/')
. '/MagentoCmsModelWysiwygImagesStorageTest';
$this->mediaDirectory->create($this->mediaDirectory->getRelativePath($this->fullDirectoryPath));
$config = $this->objectManager->get(ScopeConfigInterface::class);
$this->origConfigValue = $config->getValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
'default'
);
$scopeConfig = $this->objectManager->get(\Magento\Framework\App\Config\MutableScopeConfigInterface::class);
$scopeConfig->setValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
array_merge($this->origConfigValue, ['MagentoCmsModelWysiwygImagesStorageTest']),
);
$this->storage = $this->objectManager->create(Storage::class);
$this->driver = $this->mediaDirectory->getDriver();
}
protected function tearDown(): void
{
$this->mediaDirectory->delete($this->mediaDirectory->getRelativePath($this->fullDirectoryPath));
$scopeConfig = $this->objectManager->get(\Magento\Framework\App\Config\MutableScopeConfigInterface::class);
$scopeConfig->setValue(
self::MEDIA_GALLERY_IMAGE_FOLDERS_CONFIG_PATH,
$this->origConfigValue
);
}
/**
* @magentoAppIsolation enabled
* @return void
*/
public function testGetFilesCollection(): void
{
Bootstrap::getInstance()
->loadArea(\Magento\Backend\App\Area\FrontNameResolver::AREA_CODE);
$fileName = 'magento_image.jpg';
$imagePath = realpath(__DIR__ . '/../../../../Catalog/_files/' . $fileName);
$mediaDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::MEDIA);
$modifiableFilePath = $mediaDirectory->getAbsolutePath('MagentoCmsModelWysiwygImagesStorageTest/' . $fileName);
$this->driver->copy(
$imagePath,
$modifiableFilePath
);
$this->storage->resizeFile($modifiableFilePath);
$collection = $this->storage->getFilesCollection($this->fullDirectoryPath, '/image');
$this->assertInstanceOf(Collection::class, $collection);
foreach ($collection as $item) {
$thumbUrl = parse_url($item->getThumbUrl(), PHP_URL_PATH);
$this->assertInstanceOf(DataObject::class, $item);
$this->assertStringEndsWith('/' . $fileName, $item->getUrl());
$this->assertEquals(
'/media/.thumbsMagentoCmsModelWysiwygImagesStorageTest/magento_image.jpg',
$thumbUrl,
"Check if Thumbnail URL is equal to the generated URL"
);
$this->assertEquals(
'image/jpeg',
$item->getMimeType(),
"Check if Mime Type is equal to the image in the file system"
);
return;
}
}
/**
* @magentoAppArea adminhtml
* @return void
*/
public function testGetThumbsPath(): void
{
$this->assertStringStartsWith(
$this->filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath(),
$this->storage->getThumbsPath()
);
}
/**
* @return void
*/
public function testDeleteDirectory(): void
{
$path = $this->objectManager->get(\Magento\Cms\Helper\Wysiwyg\Images::class)->getCurrentPath();
$dir = 'MagentoCmsModelWysiwygImagesStorageTest/testDeleteDirectory';
$fullPath = $path . $dir;
$this->storage->createDirectory('testDeleteDirectory', $path . '/MagentoCmsModelWysiwygImagesStorageTest');
$this->assertTrue($this->mediaDirectory->isExist($fullPath));
$this->storage->deleteDirectory($fullPath);
$this->assertFileDoesNotExist($fullPath);
}
/**
* @return void
*/
public function testDeleteDirectoryWithExcludedDirPath(): void
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage('We cannot delete the selected directory.');
$dir = $this->objectManager->get(\Magento\Cms\Helper\Wysiwyg\Images::class)->getCurrentPath() . 'downloadable';
$this->storage->deleteDirectory($dir);
}
/**
* @return void
*/
public function testUploadFile(): void
{
$fileName = 'magento_small_image.jpg';
$tmpDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::SYS_TMP);
$filePath = $tmpDirectory->getAbsolutePath($fileName);
// phpcs:disable
$fixtureDir = realpath(__DIR__ . '/../../../../Catalog/_files');
copy($fixtureDir . DIRECTORY_SEPARATOR . $fileName, $filePath);
$_FILES['image'] = [
'name' => $fileName,
'type' => 'image/jpeg',
'tmp_name' => $filePath,
'error' => 0,
'size' => 12500,
];
$this->storage->uploadFile($this->fullDirectoryPath);
$this->assertTrue($this->mediaDirectory->isExist($this->fullDirectoryPath . DIRECTORY_SEPARATOR . $fileName));
// phpcs:enable
}
/**
* @return void
*/
public function testUploadFileWithExcludedDirPath(): void
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage(
'We can\'t upload the file to the current folder right now. Please try another folder.'
);
$fileName = 'magento_small_image.jpg';
$tmpDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::SYS_TMP);
$filePath = $tmpDirectory->getAbsolutePath($fileName);
// phpcs:disable
$fixtureDir = realpath(__DIR__ . '/../../../../Catalog/_files');
copy($fixtureDir . DIRECTORY_SEPARATOR . $fileName, $filePath);
$_FILES['image'] = [
'name' => $fileName,
'type' => 'image/jpeg',
'tmp_name' => $filePath,
'error' => 0,
'size' => 12500,
];
$dir = $this->objectManager->get(\Magento\Cms\Helper\Wysiwyg\Images::class)->getCurrentPath() . 'downloadable';
$this->storage->uploadFile($dir);
// phpcs:enable
}
/**
* @param string $fileName
* @param string $fileType
* @param string|null $storageType
*
* @return void
* @dataProvider testUploadFileWithWrongExtensionDataProvider
*/
public function testUploadFileWithWrongExtension(string $fileName, string $fileType, ?string $storageType): void
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage('File validation failed.');
$tmpDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::SYS_TMP);
$filePath = $tmpDirectory->getAbsolutePath($fileName);
// phpcs:disable
$fixtureDir = realpath(__DIR__ . '/../../../_files');
copy($fixtureDir . DIRECTORY_SEPARATOR . $fileName, $filePath);
$_FILES['image'] = [
'name' => $fileName,
'type' => $fileType,
'tmp_name' => $filePath,
'error' => 0,
'size' => 12500,
];
$this->storage->uploadFile($this->fullDirectoryPath, $storageType);
$this->assertFalse(is_file($this->fullDirectoryPath . DIRECTORY_SEPARATOR . $fileName));
// phpcs:enable
}
/**
* @return array
*/
public function testUploadFileWithWrongExtensionDataProvider(): array
{
return [
[
'fileName' => 'text.txt',
'fileType' => 'text/plain',
'storageType' => null,
],
[
'fileName' => 'test.swf',
'fileType' => 'application/x-shockwave-flash',
'storageType' => 'media',
],
];
}
/**
* @return void
*/
public function testUploadFileWithWrongFile(): void
{
$this->expectException(\Magento\Framework\Exception\LocalizedException::class);
$this->expectExceptionMessage('File validation failed.');
$fileName = 'file.gif';
$tmpDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::SYS_TMP);
$filePath = $tmpDirectory->getAbsolutePath($fileName);
// phpcs:disable
$file = fopen($filePath, "wb");
fwrite($file, 'just a text');
$_FILES['image'] = [
'name' => $fileName,
'type' => 'image/gif',
'tmp_name' => $filePath,
'error' => 0,
'size' => 12500,
];
$this->storage->uploadFile($this->fullDirectoryPath);
$this->assertFalse(is_file($this->fullDirectoryPath . DIRECTORY_SEPARATOR . $fileName));
// phpcs:enable
}
/**
* Verify thumbnail generation for diferent sizes
*
* @param array $sizes
* @param bool $resized
* @dataProvider getThumbnailsSizes
*/
public function testResizeFile(array $sizes, bool $resized): void
{
$root = $this->storage->getCmsWysiwygImages()->getStorageRoot();
$path = rtrim($root, '/') . '/testfile.png';
$this->generateImage($path, $sizes['width'], $sizes['height']);
$this->storage->resizeFile($path);
$thumbPath = $this->storage->getThumbnailPath($path);
list($imageWidth, $imageHeight) = getimagesizefromstring($this->driver->fileGetContents($thumbPath));
$this->assertEquals(
$resized ? $this->storage->getResizeWidth() : $sizes['width'],
$imageWidth
);
$this->assertLessThanOrEqual(
$resized ? $this->storage->getResizeHeight() : $sizes['height'],
$imageHeight
);
$this->driver->deleteFile($path);
}
/**
* Provide sizes for resizeFile test
*/
public function getThumbnailsSizes(): array
{
return [
[
[
'width' => 1024,
'height' => 768,
],
true
],
[
[
'width' => 20,
'height' => 20,
],
false
]
];
}
/**
* Generate a dummy image of the given width and height.
*
* @param string $path
* @param int $width
* @param int $height
* @return string
*/
private function generateImage(string $path, int $width = 1024, int $height = 768)
{
$this->mediaDirectory->create(dirname($this->mediaDirectory->getRelativePath($path)));
$extension = pathinfo($path, PATHINFO_EXTENSION);
ob_start();
$image = imagecreatetruecolor($width, $height);
switch ($extension) {
case 'jpeg':
imagejpeg($image);
break;
case 'png':
imagepng($image);
break;
}
$this->driver->filePutContents($path, ob_get_clean());
return $path;
}
}
@@ -0,0 +1,75 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Cms\Setup;
class ContentConverterTest extends \Magento\TestFramework\TestCase\AbstractController
{
/** @var \Magento\Cms\Setup\ContentConverter */
private $converter;
protected function setUp(): void
{
$this->converter = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create(
\Magento\Cms\Setup\ContentConverter::class
);
}
/**
* @param string $value
* @param string $expected
* @dataProvider convertDataProvider
*/
public function testConvert($value, $expected)
{
$this->assertEquals($expected, $this->converter->convert($value));
}
public function convertDataProvider()
{
// @codingStandardsIgnoreStart
$someContent = '<div class="content-heading">
<h2 class="title">Hot Sellers</h2>
<p class="info">Here is what`s trending on Luma right now</p>
</div>';
$serializedWidgetContent = '{{widget type="Magento\\CatalogWidget\\Block\\Product\\ProductsList" products_per_page="8" products_count="8" template="Magento_CatalogWidget::product/widget/content/grid.phtml" conditions_encoded="a:2:[i:1;a:4:[s:4:`type`;s:50:`Magento|CatalogWidget|Model|Rule|Condition|Combine`;s:10:`aggregator`;s:3:`all`;s:5:`value`;s:1:`1`;s:9:`new_child`;s:0:``;]s:4:`1--1`;a:4:[s:4:`type`;s:50:`Magento|CatalogWidget|Model|Rule|Condition|Product`;s:9:`attribute`;s:3:`sku`;s:8:`operator`;s:2:`()`;s:5:`value`;a:8:[i:0;s:4:`WS12`;i:1;s:4:`WT09`;i:2;s:4:`MT07`;i:3;s:4:`MH07`;i:4;s:7:`24-MB02`;i:5;s:7:`24-WB04`;i:6;s:8:`241-MB08`;i:7;s:8:`240-LV05`;]]]"}}';
$jsonEncodedWidgetContent = '{{widget type="Magento\\CatalogWidget\\Block\\Product\\ProductsList" products_per_page="8" products_count="8" template="Magento_CatalogWidget::product/widget/content/grid.phtml" conditions_encoded="^[`1`:^[`type`:`Magento||CatalogWidget||Model||Rule||Condition||Combine`,`aggregator`:`all`,`value`:`1`,`new_child`:``^],`1--1`:^[`type`:`Magento||CatalogWidget||Model||Rule||Condition||Product`,`attribute`:`sku`,`operator`:`()`,`value`:[`WS12`,`WT09`,`MT07`,`MH07`,`24-MB02`,`24-WB04`,`241-MB08`,`240-LV05`]^]^]"}}';
// @codingStandardsIgnoreEnd
return [
'no widget' => [
$someContent,
$someContent,
],
'one serialized widget, end with widget' => [
$someContent . $serializedWidgetContent,
$someContent . $jsonEncodedWidgetContent,
],
'two serialized widgets, end with widget' => [
$someContent . $serializedWidgetContent . $someContent . $serializedWidgetContent,
$someContent . $jsonEncodedWidgetContent . $someContent . $jsonEncodedWidgetContent,
],
'one serialized widget, end with content other than widget' => [
$someContent . $serializedWidgetContent . $someContent,
$someContent . $jsonEncodedWidgetContent . $someContent,
],
'one json encoded widget, end with widget' => [
$someContent . $jsonEncodedWidgetContent,
$someContent . $jsonEncodedWidgetContent,
],
'two json encoded widgets, end with widget' => [
$someContent . $jsonEncodedWidgetContent . $someContent . $jsonEncodedWidgetContent,
$someContent . $jsonEncodedWidgetContent . $someContent . $jsonEncodedWidgetContent,
],
'one json encoded widget, one serialized widget, end with widget' => [
$someContent . $jsonEncodedWidgetContent . $someContent . $serializedWidgetContent,
$someContent . $jsonEncodedWidgetContent . $someContent . $jsonEncodedWidgetContent,
],
'one json encoded widget, end with content other than widget' => [
$someContent . $jsonEncodedWidgetContent . $someContent,
$someContent . $jsonEncodedWidgetContent . $someContent,
],
];
}
}
@@ -0,0 +1,104 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Magento\Cms\Ui\Component;
use Magento\Cms\Api\Data\BlockInterface;
use Magento\Cms\Api\Data\PageInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\ObjectManagerInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Framework\View\Element\UiComponentInterface;
use Magento\TestFramework\Helper\Bootstrap;
use PHPUnit\Framework\TestCase;
/**
* Checks Cms UI component data provider behaviour
*
* @magentoAppArea adminhtml
* @magentoDbIsolation enabled
*/
class DataProviderTest extends TestCase
{
/** @var ObjectManagerInterface */
private $objectManager;
/** @var UiComponentFactory */
private $componentFactory;
/** @var RequestInterface */
private $request;
/**
* @inheritdoc
*/
protected function setUp(): void
{
parent::setUp();
$this->objectManager = Bootstrap::getObjectManager();
$this->request = $this->objectManager->get(RequestInterface::class);
$this->componentFactory = $this->objectManager->get(UiComponentFactory::class);
}
/**
* @magentoDataFixture Magento/Cms/_files/pages.php
*
* @return void
*/
public function testPageFilteringByTitlePart(): void
{
$this->request->setParams(['search' => 'Cms Page 1']);
$data = $this->getComponentProvidedData('cms_page_listing');
$items = $data['items'];
$this->assertCount(1, $items);
$this->assertEquals('page100', reset($items)[PageInterface::IDENTIFIER]);
}
/**
* @magentoDataFixture Magento/Cms/_files/blocks.php
*
* @return void
*/
public function testBlockFilteringByTitlePart(): void
{
$this->request->setParams(['search' => 'Enabled CMS Block']);
$data = $this->getComponentProvidedData('cms_block_listing');
$items = $data['items'];
$this->assertCount(1, $items);
$this->assertEquals('enabled_block', reset($items)[BlockInterface::IDENTIFIER]);
}
/**
* Call prepare method in the child components
*
* @param UiComponentInterface $component
* @return void
*/
private function prepareChildComponents(UiComponentInterface $component): void
{
foreach ($component->getChildComponents() as $child) {
$this->prepareChildComponents($child);
}
$component->prepare();
}
/**
* Get component provided data
*
* @param string $namespace
* @return array
*/
private function getComponentProvidedData(string $namespace): array
{
$component = $this->componentFactory->create($namespace);
$this->prepareChildComponents($component);
return $component->getContext()->getDataProvider()->getData();
}
}
@@ -0,0 +1,42 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Cms\Model\Block;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/**
* @var $block Block
* @var $blockRepository BlockRepositoryInterface
*/
$block = $objectManager->create(Block::class);
$blockRepository = $objectManager->create(BlockRepositoryInterface::class);
$block->setTitle(
'CMS Block Title'
)->setIdentifier(
'fixture_block'
)->setContent(
'<h1>Fixture Block Title</h1>
<a href="{{store url=""}}">store url</a>
<p>Config value: "{{config path="web/unsecure/base_url"}}".</p>
<p>Custom variable: "{{customvar code="variable_code"}}".</p>
'
)->setIsActive(
1
)->setStores(
[
Bootstrap::getObjectManager()->get(
StoreManagerInterface::class
)->getStore()->getId()
]
);
$blockRepository->save($block);
@@ -0,0 +1,37 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Cms\Model\Block;
use Magento\Store\Model\Store;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/**
* @var $block Block
* @var $blockRepository BlockRepositoryInterface
*/
$block = $objectManager->create(Block::class);
$blockRepository = $objectManager->create(BlockRepositoryInterface::class);
$block->setTitle(
'CMS Block Title'
)->setIdentifier(
'default_store_block'
)->setContent(
'<h1>Fixture Block Title</h1>
<a href="{{store url=""}}">store url</a>
<p>Config value: "{{config path="web/unsecure/base_url"}}".</p>
<p>Custom variable: "{{customvar code="variable_code"}}".</p>'
)->setIsActive(
1
)->setStores(
[Store::DEFAULT_STORE_ID]
);
$blockRepository->save($block);
@@ -0,0 +1,30 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Cms\Api\Data\BlockInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var BlockRepositoryInterface $blockRepository */
$blockRepository = $objectManager->get(BlockRepositoryInterface::class);
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter(BlockInterface::IDENTIFIER, 'default_store_block')
->create();
$result = $blockRepository->getList($searchCriteria);
/**
* Tests which are wrapped with MySQL transaction clear all data by transaction rollback.
* In that case there is "if" which checks that "fixture_block" still exists in database.
*/
foreach ($result->getItems() as $item) {
$blockRepository->delete($item);
}
@@ -0,0 +1,30 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Cms\Api\Data\BlockInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var BlockRepositoryInterface $blockRepository */
$blockRepository = $objectManager->get(BlockRepositoryInterface::class);
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter(BlockInterface::IDENTIFIER, 'fixture_block')
->create();
$result = $blockRepository->getList($searchCriteria);
/**
* Tests which are wrapped with MySQL transaction clear all data by transaction rollback.
* In that case there is "if" which checks that "fixture_block" still exists in database.
*/
foreach ($result->getItems() as $item) {
$blockRepository->delete($item);
}
@@ -0,0 +1,52 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Cms\Api\Data\BlockInterface;
use Magento\Cms\Api\Data\BlockInterfaceFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
/** @var BlockRepositoryInterface $blockRepository */
$blockRepository = Bootstrap::getObjectManager()->get(BlockRepositoryInterface::class);
/** @var BlockInterfaceFactory $blockFactory */
$blockFactory = Bootstrap::getObjectManager()->get(BlockInterfaceFactory::class);
$storeId = Bootstrap::getObjectManager()->get(StoreManagerInterface::class)->getStore()->getId();
/** @var BlockInterface $block */
$block = $blockFactory->create([
'data' => [
BlockInterface::IDENTIFIER => 'enabled_block',
BlockInterface::TITLE => 'Enabled CMS Block Title',
BlockInterface::CONTENT => '
<h1>Enabled Block</h1>
<a href="{{store url=""}}">store url</a>
<p>Config value: "{{config path="web/unsecure/base_url"}}".</p>
<p>Custom variable: "{{customvar code="variable_code"}}".</p>
',
BlockInterface::IS_ACTIVE => 1,
'store_id' => [$storeId],
]
]);
$blockRepository->save($block);
/** @var BlockInterface $block */
$block = $blockFactory->create([
'data' => [
BlockInterface::IDENTIFIER => 'disabled_block',
BlockInterface::TITLE => 'Disabled CMS Block Title',
BlockInterface::CONTENT => '
<h1>Disabled Block</h1>
<a href="{{store url=""}}">store url</a>
<p>Config value: "{{config path="web/unsecure/base_url"}}".</p>
<p>Custom variable: "{{customvar code="variable_code"}}".</p>
',
BlockInterface::IS_ACTIVE => 0,
'store_id' => [$storeId],
]
]);
$blockRepository->save($block);
@@ -0,0 +1,71 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Cms\Api\Data\BlockInterface;
use Magento\Cms\Api\Data\BlockInterfaceFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\TestFramework\Helper\Bootstrap;
/** @var BlockRepositoryInterface $blockRepository */
$blockRepository = Bootstrap::getObjectManager()->get(BlockRepositoryInterface::class);
/** @var BlockInterfaceFactory $blockFactory */
$blockFactory = Bootstrap::getObjectManager()->get(BlockInterfaceFactory::class);
/** @var StoreManagerInterface $stores */
$stores = Bootstrap::getObjectManager()->get(StoreManagerInterface::class)->getStores();
array_shift($stores);
/** @var BlockInterface $block */
$block = $blockFactory->create([
'data' => [
BlockInterface::IDENTIFIER => 'test-block',
BlockInterface::TITLE => 'Second store block',
BlockInterface::CONTENT => '
<h1>Test Block 1 for Second Store</h1>
<a href="{{store url=""}}">store url</a>
<p>Config value: "{{config path="trans_email/ident_general/name"}}".</p>
<p>Custom path: "{{config path="trans_email/ident_general/email"}}".</p>
',
BlockInterface::IS_ACTIVE => 1,
'store_id' => [$stores[0]->getId()],
]
]);
$blockRepository->save($block);
/** @var BlockInterface $block */
$block = $blockFactory->create([
'data' => [
BlockInterface::IDENTIFIER => 'test-block-2',
BlockInterface::TITLE => 'Second store block 2',
BlockInterface::CONTENT => '
<h1>Test Block 2 for Second Store</h1>
<a href="{{store url=""}}">store url</a>
<p>Config value: "{{config path="trans_email/ident_general/name"}}".</p>
<p>Custom path: "{{config path="trans_email/ident_general/email"}}".</p>
',
BlockInterface::IS_ACTIVE => 1,
'store_id' => [$stores[0]->getId()],
]
]);
$blockRepository->save($block);
/** @var BlockInterface $block */
$block = $blockFactory->create([
'data' => [
BlockInterface::IDENTIFIER => 'test-block',
BlockInterface::TITLE => 'Third store block',
BlockInterface::CONTENT => '
<h1>Test Block for Third Store</h1>
<a href="{{store url=""}}">store url</a>
<p>Config value: "{{config path="trans_email/ident_general/name"}}".</p>
<p>Custom path: "{{config path="trans_email/ident_general/email"}}".</p>
',
BlockInterface::IS_ACTIVE => 1,
'store_id' => [$stores[1]->getId()],
]
]);
$blockRepository->save($block);
@@ -0,0 +1,26 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Cms\Api\Data\BlockInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var BlockRepositoryInterface $blockRepository */
$blockRepository = $objectManager->get(BlockRepositoryInterface::class);
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter(BlockInterface::IDENTIFIER, '%test-block%', 'like')
->create();
$result = $blockRepository->getList($searchCriteria);
foreach ($result->getItems() as $item) {
$blockRepository->delete($item);
}
@@ -0,0 +1,23 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\TestFramework\Helper\Bootstrap;
/** @var BlockRepositoryInterface $blockRepository */
$blockRepository = Bootstrap::getObjectManager()->get(BlockRepositoryInterface::class);
foreach (['enabled_block', 'disabled_block'] as $blockId) {
try {
$blockRepository->deleteById($blockId);
} catch (NoSuchEntityException $e) {
/**
* Tests which are wrapped with MySQL transaction clear all data by transaction rollback.
*/
}
}
@@ -0,0 +1,36 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Model\ResourceModel\Page as PageResource;
use Magento\Cms\Model\Page as PageModel;
use Magento\Cms\Model\PageFactory as PageModelFactory;
use Magento\TestFramework\Cms\Model\CustomLayoutManager;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var PageModelFactory $pageFactory */
$pageFactory = $objectManager->get(PageModelFactory::class);
/** @var CustomLayoutManager $fakeManager */
$fakeManager = $objectManager->get(CustomLayoutManager::class);
$layoutRepo = $objectManager->create(PageModel\CustomLayoutRepositoryInterface::class, ['manager' => $fakeManager]);
$customLayoutName = 'page_custom_layout';
/**
* @var PageModel $page
* @var PageResource $pageResource
*/
$page = $pageFactory->create(['customLayoutRepository' => $layoutRepo]);
$pageResource = $objectManager->create(PageResource::class);
$pageResource->load($page, 'home');
$cmsPageId = (int)$page->getId();
$fakeManager->fakeAvailableFiles($cmsPageId, [$customLayoutName]);
$page->setData('layout_update_selected', $customLayoutName);
$pageResource->save($page);
@@ -0,0 +1,21 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Api\PageRepositoryInterface;
use Magento\Cms\Model\Page\CustomLayout\CustomLayoutRepository;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var PageRepositoryInterface $pageRepository */
$pageRepository = $objectManager->get(PageRepositoryInterface::class);
$cmsPage = $pageRepository->getById('home');
$cmsPageId = (int)$cmsPage->getId();
/** @var CustomLayoutRepository $customLayoutRepository */
$customLayoutRepository = $objectManager->get(CustomLayoutRepository::class);
$customLayoutRepository->deleteFor($cmsPageId);
@@ -0,0 +1,27 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Framework\Filesystem\Driver\File;
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$directoryName = 'linked_media';
/** @var \Magento\Framework\Filesystem $filesystem */
$filesystem = $objectManager->get(\Magento\Framework\Filesystem::class);
$fullDirectoryPath = $filesystem->getDirectoryRead(Magento\Framework\App\Filesystem\DirectoryList::PUB)
->getAbsolutePath() . $directoryName;
$mediaDirectory = $filesystem->getDirectoryWrite(Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
if (!$mediaDirectory->getDriver() instanceof File) {
return;
}
$wysiwygDir = $mediaDirectory->getAbsolutePath() . 'wysiwyg';
$mediaDirectory->delete($wysiwygDir);
if (!is_dir($fullDirectoryPath)) {
mkdir($fullDirectoryPath);
}
if (is_dir($fullDirectoryPath) && !is_dir($wysiwygDir)) {
symlink($fullDirectoryPath, $wysiwygDir);
}
@@ -0,0 +1,21 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$directoryName = 'linked_media';
/** @var \Magento\Framework\Filesystem $filesystem */
$filesystem = $objectManager->get(\Magento\Framework\Filesystem::class);
$pubDir = $filesystem->getDirectoryWrite(Magento\Framework\App\Filesystem\DirectoryList::PUB);
$fullDirectoryPath = $pubDir->getAbsolutePath() . DIRECTORY_SEPARATOR . $directoryName;
$mediaDirectory = $filesystem->getDirectoryWrite(Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
$wysiwygDir = $mediaDirectory->getAbsolutePath() . 'wysiwyg';
if (is_link($wysiwygDir)) {
unlink($wysiwygDir);
}
if (is_dir($fullDirectoryPath)) {
$pubDir->delete($directoryName);
}
@@ -0,0 +1,24 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Model\Page;
use Magento\Cms\Model\ResourceModel\Page as PageResource;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/**
* @var Page $page
* @var PageResource $pageResource
*/
$page = $objectManager->create(Page::class);
$pageResource = $objectManager->create(PageResource::class);
$pageResource->load($page, 'no-route', 'identifier');
$page->setIsActive(0);
$pageResource->save($page);
@@ -0,0 +1,46 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Api\PageRepositoryInterface;
use Magento\Cms\Model\Page;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/**
* @var $page Page
* @var $pageRepository PageRepositoryInterface
*/
$page = $objectManager->create(Page::class);
$pageRepository = $objectManager->create(PageRepositoryInterface::class);
$page->setTitle('Cms Page 100')
->setIdentifier('page100')
->setStores([0])
->setIsActive(1)
->setContent('<h1>Cms Page 100 Title</h1>')
->setContentHeading('<h2>Cms Page 100 Title</h2>')
->setMetaTitle('Cms Meta title for page100')
->setMetaKeywords('Cms Meta Keywords for page100')
->setMetaDescription('Cms Meta Description for page100')
->setPageLayout('1column');
$pageRepository->save($page);
$page = $objectManager->create(Page::class);
$page->setTitle('Cms Page Design Blank')
->setIdentifier('page_design_blank')
->setStores([0])
->setIsActive(1)
->setContent('<h1>Cms Page Design Blank Title</h1>')
->setContentHeading('<h2>Cms Page Blank Title</h2>')
->setMetaTitle('Cms Meta title for Blank page')
->setMetaKeywords('Cms Meta Keywords for Blank page')
->setMetaDescription('Cms Meta Description for Blank page')
->setPageLayout('1column')
->setCustomTheme('Magento/blank');
$pageRepository->save($page);
@@ -0,0 +1,30 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Api\Data\PageInterface;
use Magento\Cms\Api\PageRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
/** @var PageRepositoryInterface $pageRepository */
$pageRepository = $objectManager->get(PageRepositoryInterface::class);
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter(PageInterface::IDENTIFIER, ['page100', 'page_design_blank'], 'in')
->create();
$result = $pageRepository->getList($searchCriteria);
/**
* Tests which are wrapped with MySQL transaction clear all data by transaction rollback.
* In that case there is "if" which checks that "page100" and "page_design_blank" still exists in database.
*/
foreach ($result->getItems() as $item) {
$pageRepository->delete($item);
}
@@ -0,0 +1,60 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Model\Page as PageModel;
use Magento\Cms\Model\ResourceModel\Page as PageResource;
use Magento\Cms\Model\PageFactory as PageModelFactory;
use Magento\TestFramework\Cms\Model\CustomLayoutManager;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
$objectManager->configure([
'preferences' => [
\Magento\Cms\Model\Page\CustomLayoutManagerInterface::class =>
\Magento\TestFramework\Cms\Model\CustomLayoutManager::class
]
]);
$pageFactory = $objectManager->get(PageModelFactory::class);
/** @var CustomLayoutManager $fakeManager */
$fakeManager = $objectManager->get(CustomLayoutManager::class);
$layoutRepo = $objectManager->create(PageModel\CustomLayoutRepositoryInterface::class, ['manager' => $fakeManager]);
/** @var PageResource $pageRepository */
$pageResource = $objectManager->create(PageResource::class);
/** @var PageModel $page */
$page = $pageFactory->create(['customLayoutRepository' => $layoutRepo]);
$page->setIdentifier('test_custom_layout_page_1');
$page->setTitle('Test Page');
$page->setCustomLayoutUpdateXml('<container />');
$page->setLayoutUpdateXml('<container />');
$page->setIsActive(true);
$page->setStoreId(0);
$pageResource->save($page);
/** @var PageModel $page2 */
$page2 = $pageFactory->create(['customLayoutRepository' => $layoutRepo]);
$page2->setIdentifier('test_custom_layout_page_2');
$page2->setTitle('Test Page 2');
$page->setIsActive(true);
$page->setStoreId(0);
$pageResource->save($page2);
/** @var PageModel $page3 */
$page3 = $pageFactory->create(['customLayoutRepository' => $layoutRepo]);
$page3->setIdentifier('test_custom_layout_page_3');
$page3->setTitle('Test Page 3');
$page3->setStores([0]);
$page3->setIsActive(1);
$page3->setContent('<h1>Test Page</h1>');
$page3->setPageLayout('1column');
$pageResource->save($page3);
$fakeManager->fakeAvailableFiles((int)$page3->getId(), ['test_selected']);
$page3->setData('layout_update_selected', 'test_selected');
$pageResource->save($page3);
@@ -0,0 +1,40 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Model\Page as PageModel;
use Magento\Cms\Model\PageFactory as PageModelFactory;
use Magento\Cms\Model\ResourceModel\Page as PageResource;
use Magento\TestFramework\Helper\Bootstrap;
$objectManager = Bootstrap::getObjectManager();
$pageFactory = $objectManager->get(PageModelFactory::class);
/**
* @var PageModel $page
* @var PageResource $pageResource
*/
$page = $pageFactory->create();
$pageResource = $objectManager->create(PageResource::class);
$pageResource->load($page, 'test_custom_layout_page_1', PageModel::IDENTIFIER);
if ($page->getId()) {
$pageResource->delete($page);
}
/** @var PageModel $page2 */
$page2 = $pageFactory->create();
$pageResource->load($page2, 'test_custom_layout_page_2', PageModel::IDENTIFIER);
if ($page2->getId()) {
$pageResource->delete($page2);
}
/** @var PageModel $page3 */
$page3 = $pageFactory->create();
$pageResource->load($page3, 'test_custom_layout_page_3', PageModel::IDENTIFIER);
if ($page3->getId()) {
$pageResource->delete($page3);
}
@@ -0,0 +1 @@
just a text
@@ -0,0 +1,41 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Api\PageRepositoryInterface;
use Magento\Cms\Model\Page;
use Magento\Store\Api\StoreRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
Resolver::getInstance()->requireDataFixture('Magento/Store/_files/second_store.php');
$objectManager = Bootstrap::getObjectManager();
/** @var StoreRepositoryInterface $storeRepository */
$storeRepository = $objectManager->get(StoreRepositoryInterface::class);
$store = $storeRepository->get('fixture_second_store');
/** @var PageRepositoryInterface $pageRepository */
$pageRepository = $objectManager->create(PageRepositoryInterface::class);
/** @var $page Page */
$page = $objectManager->create(Page::class);
$page->setTitle('First test page')
->setIdentifier('page1')
->setStores([1])
->setIsActive(1)
->setPageLayout('1column');
$pageRepository->save($page);
/** @var $page Page */
$page = $objectManager->create(Page::class);
$page->setTitle('Second test page')
->setIdentifier('page1')
->setStores([$store->getId()])
->setIsActive(1)
->setPageLayout('1column');
$pageRepository->save($page);
@@ -0,0 +1,29 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
use Magento\Cms\Api\Data\PageInterface;
use Magento\Cms\Api\PageRepositoryInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\Workaround\Override\Fixture\Resolver;
$objectManager = Bootstrap::getObjectManager();
/** @var PageRepositoryInterface $pageRepository */
$pageRepository = $objectManager->get(PageRepositoryInterface::class);
/** @var SearchCriteriaBuilder $searchCriteriaBuilder */
$searchCriteriaBuilder = $objectManager->get(SearchCriteriaBuilder::class);
$searchCriteria = $searchCriteriaBuilder->addFilter(PageInterface::IDENTIFIER, 'page1')
->create();
$result = $pageRepository->getList($searchCriteria);
foreach ($result->getItems() as $item) {
$pageRepository->delete($item);
}
Resolver::getInstance()->requireDataFixture('Magento/Store/_files/second_store_rollback.php');