Skip to content

Commit

Permalink
Merge pull request #4969 from magento-qwerty/MC-18684
Browse files Browse the repository at this point in the history
[Qwerty] MC-18684: [2.2.x] Remove custom layout updates from admin
  • Loading branch information
dvoskoboinikov authored Nov 4, 2019
2 parents b60d290 + e5525c4 commit 38de4ec
Show file tree
Hide file tree
Showing 104 changed files with 5,564 additions and 964 deletions.
26 changes: 17 additions & 9 deletions app/code/Magento/Catalog/Controller/Adminhtml/Category.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ public function __construct(Context $context, Date $dateFilter = null)

/**
* Initialize requested category and put it into registry.
*
* Root category can be returned, if inappropriate store/category is specified
*
* @param bool $getRootInstead
Expand Down Expand Up @@ -80,8 +81,12 @@ protected function _initCategory(bool $getRootInstead = false)
}
}

$this->_objectManager->get(Registry::class)->register('category', $category);
$this->_objectManager->get(Registry::class)->register('current_category', $category);
/** @var \Magento\Framework\Registry $registry */
$registry = $this->_objectManager->get(\Magento\Framework\Registry::class);
$registry->unregister('category');
$registry->unregister('current_category');
$registry->register('category', $category);
$registry->register('current_category', $category);
$this->_objectManager->get(Config::class)
->setStoreId($this->getRequest()->getParam('store'));
return $category;
Expand All @@ -103,6 +108,7 @@ private function resolveCategoryId(): int
* Resolve store id
*
* Tries to take store id from store HTTP parameter
*
* @see Store
*
* @return int
Expand Down Expand Up @@ -147,13 +153,15 @@ protected function ajaxRequestResponse(CategoryModel $category, Page $resultPage
}
}

$eventResponse = new DataObject([
'content' => $resultPage->getLayout()->getUiComponent('category_form')->getFormHtml()
. $resultPage->getLayout()->getBlock('category.tree')
->getBreadcrumbsJavascript($breadcrumbsPath, 'editingCategoryBreadcrumbs'),
'messages' => $resultPage->getLayout()->getMessagesBlock()->getGroupedHtml(),
'toolbar' => $resultPage->getLayout()->getBlock('page.actions.toolbar')->toHtml()
]);
$eventResponse = new DataObject(
[
'content' => $resultPage->getLayout()->getUiComponent('category_form')->getFormHtml()
. $resultPage->getLayout()->getBlock('category.tree')
->getBreadcrumbsJavascript($breadcrumbsPath, 'editingCategoryBreadcrumbs'),
'messages' => $resultPage->getLayout()->getMessagesBlock()->getGroupedHtml(),
'toolbar' => $resultPage->getLayout()->getBlock('page.actions.toolbar')->toHtml()
]
);
$this->_eventManager->dispatch(
'category_prepare_ajax_response',
['response' => $eventResponse, 'controller' => $this]
Expand Down
40 changes: 21 additions & 19 deletions app/code/Magento/Catalog/Controller/Adminhtml/Category/Save.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,29 +170,29 @@ public function execute()
$products = json_decode($categoryPostData['category_products'], true);
$category->setPostedProducts($products);
}
$this->_eventManager->dispatch(
'catalog_category_prepare_save',
['category' => $category, 'request' => $this->getRequest()]
);

/**
* Check "Use Default Value" checkboxes values
*/
if (isset($categoryPostData['use_default']) && !empty($categoryPostData['use_default'])) {
foreach ($categoryPostData['use_default'] as $attributeCode => $attributeValue) {
if ($attributeValue) {
$category->setData($attributeCode, null);
try {
$this->_eventManager->dispatch(
'catalog_category_prepare_save',
['category' => $category, 'request' => $this->getRequest()]
);
/**
* Check "Use Default Value" checkboxes values
*/
if (isset($categoryPostData['use_default']) && !empty($categoryPostData['use_default'])) {
foreach ($categoryPostData['use_default'] as $attributeCode => $attributeValue) {
if ($attributeValue) {
$category->setData($attributeCode, null);
}
}
}
}

/**
* Proceed with $_POST['use_config']
* set into category model for processing through validation
*/
$category->setData('use_post_data_config', $useConfig);
/**
* Proceed with $_POST['use_config']
* set into category model for processing through validation
*/
$category->setData('use_post_data_config', $useConfig);

try {
$categoryResource = $category->getResource();
if ($category->hasCustomDesignTo()) {
$categoryResource->getAttribute('custom_design_from')->setMaxValue($category->getCustomDesignTo());
Expand All @@ -207,7 +207,7 @@ public function execute()
__('Attribute "%1" is required.', $attribute)
);
} else {
throw new \Exception($error);
throw new \RuntimeException($error);
}
}
}
Expand All @@ -216,10 +216,12 @@ public function execute()

$category->save();
$this->messageManager->addSuccessMessage(__('You saved the category.'));
// phpcs:disable Magento2.Exceptions.ThrowCatch
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addExceptionMessage($e);
$this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
$this->_getSession()->setCategoryData($categoryPostData);
// phpcs:disable Magento2.Exceptions.ThrowCatch
} catch (\Exception $e) {
$this->messageManager->addErrorMessage(__('Something went wrong while saving the category.'));
$this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ public function build(RequestInterface $request)
$store = $this->storeFactory->create();
$store->load($storeId);

$this->registry->unregister('product');
$this->registry->unregister('current_product');
$this->registry->unregister('current_store');
$this->registry->register('product', $product);
$this->registry->register('current_product', $product);
$this->registry->register('current_store', $store);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use Magento\Catalog\Model\Product\LinkTypeProvider;
use Magento\Framework\App\ObjectManager;
use Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper\AttributeFilter;
use Magento\Catalog\Model\Product\Authorization as ProductAuthorization;

/**
* Product helper
Expand Down Expand Up @@ -96,6 +97,11 @@ class Helper
*/
private $attributeFilter;

/**
* @var ProductAuthorization
*/
private $productAuthorization;

/**
* Constructor
*
Expand All @@ -110,6 +116,7 @@ class Helper
* @param ProductRepositoryInterface|null $productRepository
* @param LinkTypeProvider|null $linkTypeProvider
* @param AttributeFilter|null $attributeFilter
* @param ProductAuthorization|null $productAuthorization
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
Expand All @@ -123,7 +130,8 @@ public function __construct(
ProductLinkFactory $productLinkFactory = null,
ProductRepositoryInterface $productRepository = null,
LinkTypeProvider $linkTypeProvider = null,
AttributeFilter $attributeFilter = null
AttributeFilter $attributeFilter = null,
ProductAuthorization $productAuthorization = null
) {
$this->request = $request;
$this->storeManager = $storeManager;
Expand All @@ -138,6 +146,7 @@ public function __construct(
$this->productRepository = $productRepository ?: $objectManager->get(ProductRepositoryInterface::class);
$this->linkTypeProvider = $linkTypeProvider ?: $objectManager->get(LinkTypeProvider::class);
$this->attributeFilter = $attributeFilter ?: $objectManager->get(AttributeFilter::class);
$this->productAuthorization = $productAuthorization ?? $objectManager->get(ProductAuthorization::class);
}

/**
Expand Down Expand Up @@ -228,7 +237,10 @@ public function initializeFromData(\Magento\Catalog\Model\Product $product, arra
public function initialize(\Magento\Catalog\Model\Product $product)
{
$productData = $this->request->getPost('product', []);
return $this->initializeFromData($product, $productData);
$product = $this->initializeFromData($product, $productData);
$this->productAuthorization->authorizeSavingOf($product);

return $product;
}

/**
Expand Down Expand Up @@ -448,9 +460,12 @@ private function fillProductOptions(Product $product, array $productOptions)
}

if (isset($customOptionData['values'])) {
$customOptionData['values'] = array_filter($customOptionData['values'], function ($valueData) {
return empty($valueData['is_delete']);
});
$customOptionData['values'] = array_filter(
$customOptionData['values'],
function ($valueData) {
return empty($valueData['is_delete']);
}
);
}

$customOption = $this->customOptionFactory->create(['data' => $customOptionData]);
Expand Down
4 changes: 4 additions & 0 deletions app/code/Magento/Catalog/Controller/Category/View.php
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,10 @@ public function execute()
if ($settings->getPageLayout()) {
$page->getConfig()->setPageLayout($settings->getPageLayout());
}
//Apply custom handles
if ($settings->getPageLayoutHandles()) {
$page->addPageLayoutHandles($settings->getPageLayoutHandles());
}

$hasChildren = $category->hasChildren();
if ($category->getIsAnchor()) {
Expand Down
8 changes: 6 additions & 2 deletions app/code/Magento/Catalog/Helper/Product/View.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

namespace Magento\Catalog\Helper\Product;

use Magento\Framework\App\ObjectManager;
use Magento\Framework\View\Result\Page as ResultPage;

/**
Expand Down Expand Up @@ -76,6 +77,7 @@ class View extends \Magento\Framework\App\Helper\AbstractHelper
* @param \Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator $categoryUrlPathGenerator
* @param array $messageGroups
* @param \Magento\Framework\Stdlib\StringUtils|null $string
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
*/
public function __construct(
\Magento\Framework\App\Helper\Context $context,
Expand All @@ -95,8 +97,7 @@ public function __construct(
$this->messageGroups = $messageGroups;
$this->messageManager = $messageManager;
$this->categoryUrlPathGenerator = $categoryUrlPathGenerator;
$this->string = $string ?: \Magento\Framework\App\ObjectManager::getInstance()
->get(\Magento\Framework\Stdlib\StringUtils::class);
$this->string = $string ?: ObjectManager::getInstance()->get(\Magento\Framework\Stdlib\StringUtils::class);
parent::__construct($context);
}

Expand Down Expand Up @@ -200,6 +201,9 @@ public function initProductLayout(ResultPage $resultPage, $product, $params = nu
}
}
}
if ($settings->getPageLayoutHandles()) {
$resultPage->addPageLayoutHandles($settings->getPageLayoutHandles());
}

$currentCategory = $this->_coreRegistry->registry('current_category');
$controllerClass = $this->_request->getFullActionName();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/

declare(strict_types=1);

namespace Magento\Catalog\Model\Attribute\Backend;

use Magento\Eav\Model\Entity\Attribute\Backend\AbstractBackend;
use Magento\Framework\Exception\LocalizedException;
use Magento\Catalog\Model\AbstractModel;

/**
* Custom layout file attribute.
*/
abstract class AbstractLayoutUpdate extends AbstractBackend
{
const VALUE_USE_UPDATE_XML = '__existing__';

const VALUE_NO_UPDATE = '__no_update__';

/**
* Extract attribute value.
*
* @param AbstractModel $model
* @return mixed
*/
private function extractAttributeValue(AbstractModel $model)
{
$code = $this->getAttribute()->getAttributeCode();

return $model->getData($code);
}

/**
* Compose list of available files (layout handles) for given entity.
*
* @param AbstractModel $forModel
* @return string[]
*/
abstract protected function listAvailableValues(AbstractModel $forModel): array;

/**
* Extracts prepare attribute value to be saved.
*
* @throws LocalizedException
* @param AbstractModel $model
* @return string|null
*/
private function prepareValue(AbstractModel $model)
{
$value = $this->extractAttributeValue($model);
if (!is_string($value)) {
$value = null;
}
if ($value
&& $value !== self::VALUE_USE_UPDATE_XML
&& $value !== self::VALUE_NO_UPDATE
&& !in_array($value, $this->listAvailableValues($model), true)
) {
throw new LocalizedException(__('Selected layout update is not available'));
}

return $value;
}

/**
* Set value for the object.
*
* @param string|null $value
* @param AbstractModel $forObject
* @param string|null $attrCode
* @return void
*/
private function setAttributeValue($value, AbstractModel $forObject, $attrCode = null)
{
$attrCode = $attrCode ?? $this->getAttribute()->getAttributeCode();
if ($forObject->hasData(AbstractModel::CUSTOM_ATTRIBUTES)) {
$forObject->setCustomAttribute($attrCode, $value);
}
$forObject->setData($attrCode, $value);
}

/**
* @inheritDoc
*
* @param AbstractModel $object
*/
public function validate($object)
{
$valid = parent::validate($object);
if ($valid) {
$this->prepareValue($object);
}

return $valid;
}

/**
* @inheritDoc
* @param AbstractModel $object
* @throws LocalizedException
*/
public function beforeSave($object)
{
$value = $this->prepareValue($object);
if ($value && ($value === self::VALUE_NO_UPDATE || $value !== self::VALUE_USE_UPDATE_XML)) {
$this->setAttributeValue(null, $object, 'custom_layout_update');
}
if (!$value || $value === self::VALUE_USE_UPDATE_XML || $value === self::VALUE_NO_UPDATE) {
$value = null;
}
$this->setAttributeValue($value, $object);

return $this;
}
}
Loading

0 comments on commit 38de4ec

Please sign in to comment.