Skip to content
This repository has been archived by the owner on Dec 19, 2019. It is now read-only.

Fixed #176 - Show only active CMS Blocks #221

Merged
merged 8 commits into from
Nov 23, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions app/code/Magento/CmsGraphQl/Model/Resolver/Blocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ public function resolve(
}

/**
* Get block identifiers
*
* @param array $args
* @return string[]
* @throws GraphQlInputException
Expand All @@ -69,19 +71,21 @@ private function getBlockIdentifiers(array $args): array
}

/**
* Get blocks data
*
* @param array $blockIdentifiers
* @return array
* @throws GraphQlNoSuchEntityException
*/
private function getBlocksData(array $blockIdentifiers): array
{
$blocksData = [];
try {
foreach ($blockIdentifiers as $blockIdentifier) {
foreach ($blockIdentifiers as $blockIdentifier) {
try {
$blocksData[$blockIdentifier] = $this->blockDataProvider->getData($blockIdentifier);
} catch (NoSuchEntityException $e) {
$blocksData[$blockIdentifier] = new GraphQlNoSuchEntityException(__($e->getMessage()), $e);
}
} catch (NoSuchEntityException $e) {
throw new GraphQlNoSuchEntityException(__($e->getMessage()), $e);
}
return $blocksData;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ public function __construct(
}

/**
* Get block data
*
* @param string $blockIdentifier
* @return array
* @throws NoSuchEntityException
Expand All @@ -49,7 +51,9 @@ public function getData(string $blockIdentifier): array
$block = $this->blockRepository->getById($blockIdentifier);

if (false === $block->isActive()) {
throw new NoSuchEntityException();
throw new NoSuchEntityException(
__('The CMS block with the "%1" ID doesn\'t exist.', $blockIdentifier)
);
}

$renderedContent = $this->widgetFilter->filter($block->getContent());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@ class Client
private $json;

/**
* CurlClient constructor.
*
* @param CurlClient|null $curlClient
* @param JsonSerializer|null $json
*/
Expand Down Expand Up @@ -81,6 +79,8 @@ public function postQuery(string $query, array $variables = [], string $operatio
}

/**
* Process errors
*
* @param array $responseBodyArray
* @throws \Exception
*/
Expand All @@ -102,13 +102,18 @@ private function processErrors($responseBodyArray)
}
}

throw new \Exception('GraphQL response contains errors: ' . $errorMessage);
throw new ResponseContainsErrorsException(
'GraphQL response contains errors: ' . $errorMessage,
$responseBodyArray
);
}
throw new \Exception('GraphQL responded with an unknown error: ' . json_encode($responseBodyArray));
}
}

/**
* Get endpoint url
*
* @return string resource URL
* @throws \Exception
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);

namespace Magento\TestFramework\TestCase\GraphQl;

/**
* Response contains errors exception
*/
class ResponseContainsErrorsException extends \Exception
{
/**
* @var array
*/
private $responseData;

/**
* @param string $message
* @param array $responseData
* @param \Exception|null $cause
* @param int $code
*/
public function __construct(string $message, array $responseData, \Exception $cause = null, int $code = 0)
Copy link
Contributor

Choose a reason for hiding this comment

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

We should not swap the original arguments order to comply with Liskov substitution principle.

{
parent::__construct($message, $code, $cause);
$this->responseData = $responseData;
}

/**
* Get response data
*
* @return array
*/
public function getResponseData(): array
{
return $this->responseData;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,43 +7,45 @@

namespace Magento\GraphQl\Cms;

use Magento\Cms\Model\Block;
use Magento\Cms\Model\GetBlockByIdentifier;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Cms\Api\BlockRepositoryInterface;
use Magento\TestFramework\Helper\Bootstrap;
use Magento\TestFramework\TestCase\GraphQl\ResponseContainsErrorsException;
use Magento\TestFramework\TestCase\GraphQlAbstract;
use Magento\Widget\Model\Template\FilterEmulate;

class CmsBlockTest extends GraphQlAbstract
{
/**
* @var \Magento\TestFramework\ObjectManager
* @var BlockRepositoryInterface
*/
private $objectManager;
private $blockRepository;

/**
* @var FilterEmulate
*/
private $filterEmulate;

protected function setUp()
{
$this->objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
$this->blockRepository = Bootstrap::getObjectManager()->get(BlockRepositoryInterface::class);
$this->filterEmulate = Bootstrap::getObjectManager()->get(FilterEmulate::class);
}

/**
* Verify the fields of CMS Block selected by identifiers
*
* @magentoApiDataFixture Magento/Cms/_files/block.php
* @magentoApiDataFixture Magento/Cms/_files/blocks.php
*/
public function testGetCmsBlocksByIdentifiers()
public function testGetCmsBlock()
{
/** @var StoreManagerInterface $storeManager */
$storeManager = $this->objectManager->get(StoreManagerInterface::class);
$storeId = (int)$storeManager->getStore()->getId();
$cmsBlock = $this->objectManager->get(GetBlockByIdentifier::class)->execute("fixture_block", $storeId);
$cmsBlock = $this->blockRepository->getById('enabled_block');
$cmsBlockData = $cmsBlock->getData();
/** @var FilterEmulate $widgetFilter */
$widgetFilter = $this->objectManager->get(FilterEmulate::class);
$renderedContent = $widgetFilter->setUseSessionInUrl(false)->filter($cmsBlock->getContent());
$renderedContent = $this->filterEmulate->setUseSessionInUrl(false)->filter($cmsBlock->getContent());

$query =
<<<QUERY
{
cmsBlocks(identifiers: "fixture_block") {
cmsBlocks(identifiers: "enabled_block") {
items {
identifier
title
Expand All @@ -52,34 +54,30 @@ public function testGetCmsBlocksByIdentifiers()
}
}
QUERY;

$response = $this->graphQlQuery($query);
$this->assertArrayHasKey('cmsBlocks', $response);
$this->assertArrayHasKey('items', $response['cmsBlocks']);
$this->assertArrayHasKey('content', $response['cmsBlocks']['items'][0]);
$this->assertEquals($cmsBlockData['identifier'], $response['cmsBlocks']['items'][0]['identifier']);
$this->assertEquals($cmsBlockData['title'], $response['cmsBlocks']['items'][0]['title']);
$this->assertEquals($renderedContent, $response['cmsBlocks']['items'][0]['content']);

self::assertArrayHasKey('cmsBlocks', $response);
self::assertArrayHasKey('items', $response['cmsBlocks']);

self::assertEquals($cmsBlockData['identifier'], $response['cmsBlocks']['items'][0]['identifier']);
self::assertEquals($cmsBlockData['title'], $response['cmsBlocks']['items'][0]['title']);
self::assertEquals($renderedContent, $response['cmsBlocks']['items'][0]['content']);
}

/**
* Verify the message when CMS Block is disabled
*
* @magentoApiDataFixture Magento/Cms/_files/block.php
* @expectedException \Exception
* @expectedExceptionMessage The CMS block with the "disabled_block" ID doesn't exist
*
* @magentoApiDataFixture Magento/Cms/_files/blocks.php
*/
public function testGetDisabledCmsBlockByIdentifiers()
public function testGetDisabledCmsBlock()
{
/** @var StoreManagerInterface $storeManager */
$storeManager = $this->objectManager->get(StoreManagerInterface::class);
$storeId = (int)$storeManager->getStore()->getId();
$cmsBlockId = $this->objectManager->get(GetBlockByIdentifier::class)
->execute("fixture_block", $storeId)
->getId();
$this->objectManager->get(Block::class)->load($cmsBlockId)->setIsActive(0)->save();
$query =
<<<QUERY
{
cmsBlocks(identifiers: "fixture_block") {
cmsBlocks(identifiers: "disabled_block") {
items {
identifier
title
Expand All @@ -88,16 +86,16 @@ public function testGetDisabledCmsBlockByIdentifiers()
}
}
QUERY;

$this->expectException(\Exception::class);
$this->expectExceptionMessage('No such entity.');
$this->graphQlQuery($query);
}

/**
* Verify the message when identifiers were not specified
*
* @expectedException \Exception
* @expectedExceptionMessage "identifiers" of CMS blocks should be specified
*/
public function testGetCmsBlockBypassingIdentifiers()
public function testGetCmsBlocksWithoutIdentifiers()
{
$query =
<<<QUERY
Expand All @@ -111,21 +109,21 @@ public function testGetCmsBlockBypassingIdentifiers()
}
}
QUERY;

$this->expectException(\Exception::class);
$this->expectExceptionMessage('"identifiers" of CMS blocks should be specified');
$this->graphQlQuery($query);
}

/**
* Verify the message when CMS Block with such identifiers does not exist
*
* @expectedException \Exception
* @expectedExceptionMessage The CMS block with the "nonexistent_id" ID doesn't exist.
*/
public function testGetCmsBlockByNonExistentIdentifier()
{
$query =
<<<QUERY
{
cmsBlocks(identifiers: "0") {
cmsBlocks(identifiers: "nonexistent_id") {
items {
identifier
title
Expand All @@ -134,9 +132,39 @@ public function testGetCmsBlockByNonExistentIdentifier()
}
}
QUERY;

$this->expectException(\Exception::class);
$this->expectExceptionMessage('The CMS block with the "0" ID doesn\'t exist.');
$this->graphQlQuery($query);
}

/**
* Verify the fields of CMS Block selected by identifiers
*
* @magentoApiDataFixture Magento/Cms/_files/blocks.php
*/
public function testGetEnabledAndDisabledCmsBlockInOneRequest()
{
$query =
<<<QUERY
{
cmsBlocks(identifiers: ["enabled_block", "disabled_block"]) {
items {
identifier
}
}
}
QUERY;

try {
$this->graphQlQuery($query);
self::fail('Response should contains errors.');
} catch (ResponseContainsErrorsException $e) {
$responseData = $e->getResponseData();
}

self::assertNotEmpty($responseData);
self::assertEquals('enabled_block', $responseData['data']['cmsBlocks']['items'][0]['identifier']);
self::assertEquals(
'The CMS block with the "disabled_block" ID doesn\'t exist.',
$responseData['errors'][0]['message']
);
}
}
52 changes: 52 additions & 0 deletions dev/tests/integration/testsuite/Magento/Cms/_files/blocks.php
Original file line number Diff line number Diff line change
@@ -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);
Loading