Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
CategoryUrlPathAutogeneratorObserver.php
Go to the documentation of this file.
1 <?php
7 
15 
17 {
22 
27 
31  protected $storeViewService;
32 
38  public function __construct(
42  ) {
43  $this->categoryUrlPathGenerator = $categoryUrlPathGenerator;
44  $this->childrenCategoriesProvider = $childrenCategoriesProvider;
45  $this->storeViewService = $storeViewService;
46  }
47 
53  public function execute(\Magento\Framework\Event\Observer $observer)
54  {
56  $category = $observer->getEvent()->getCategory();
57  $useDefaultAttribute = !$category->isObjectNew() && !empty($category->getData('use_default')['url_key']);
58  if ($category->getUrlKey() !== false && !$useDefaultAttribute) {
59  $resultUrlKey = $this->categoryUrlPathGenerator->getUrlKey($category);
60  if (empty($resultUrlKey)) {
61  throw new \Magento\Framework\Exception\LocalizedException(__('Invalid URL key'));
62  }
63  $category->setUrlKey($resultUrlKey)
64  ->setUrlPath($this->categoryUrlPathGenerator->getUrlPath($category));
65  if (!$category->isObjectNew()) {
66  $category->getResource()->saveAttribute($category, 'url_path');
67  if ($category->dataHasChangedFor('url_path')) {
69  }
70  }
71  }
72  }
73 
79  {
80  $children = $this->childrenCategoriesProvider->getChildren($category, true);
81 
82  if ($this->isGlobalScope($category->getStoreId())) {
83  foreach ($children as $child) {
84  foreach ($category->getStoreIds() as $storeId) {
85  if ($this->storeViewService->doesEntityHaveOverriddenUrlPathForStore(
86  $storeId,
87  $child->getId(),
89  )) {
90  $child->setStoreId($storeId);
91  $this->updateUrlPathForCategory($child);
92  }
93  }
94  }
95  } else {
96  foreach ($children as $child) {
97  $child->setStoreId($category->getStoreId());
98  $this->updateUrlPathForCategory($child);
99  }
100  }
101  }
102 
109  protected function isGlobalScope($storeId)
110  {
111  return null === $storeId || $storeId == Store::DEFAULT_STORE_ID;
112  }
113 
119  {
120  $category->unsUrlPath();
121  $category->setUrlPath($this->categoryUrlPathGenerator->getUrlPath($category));
122  $category->getResource()->saveAttribute($category, 'url_path');
123  }
124 }
__construct(CategoryUrlPathGenerator $categoryUrlPathGenerator, ChildrenCategoriesProvider $childrenCategoriesProvider, StoreViewService $storeViewService)
__()
Definition: __.php:13
$children
Definition: actions.phtml:11