Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
ProductUrlPathGenerator.php
Go to the documentation of this file.
1 <?php
7 
9 {
10  const XML_PATH_PRODUCT_URL_SUFFIX = 'catalog/seo/product_url_suffix';
11 
17  protected $productUrlSuffix = [];
18 
22  protected $storeManager;
23 
27  protected $scopeConfig;
28 
33 
37  protected $productRepository;
38 
45  public function __construct(
50  ) {
51  $this->storeManager = $storeManager;
52  $this->scopeConfig = $scopeConfig;
53  $this->categoryUrlPathGenerator = $categoryUrlPathGenerator;
54  $this->productRepository = $productRepository;
55  }
56 
65  public function getUrlPath($product, $category = null)
66  {
67  $path = $product->getData('url_path');
68  if ($path === null) {
69  $path = $product->getUrlKey()
72  }
73  return $category === null
74  ? $path
75  : $this->categoryUrlPathGenerator->getUrlPath($category) . '/' . $path;
76  }
77 
84  protected function prepareProductDefaultUrlKey(\Magento\Catalog\Model\Product $product)
85  {
86  $storedProduct = $this->productRepository->getById($product->getId());
87  $storedUrlKey = $storedProduct->getUrlKey();
88  return $storedUrlKey ?: $product->formatUrlKey($storedProduct->getName());
89  }
90 
99  public function getUrlPathWithSuffix($product, $storeId, $category = null)
100  {
101  return $this->getUrlPath($product, $category) . $this->getProductUrlSuffix($storeId);
102  }
103 
111  public function getCanonicalUrlPath($product, $category = null)
112  {
113  $path = 'catalog/product/view/id/' . $product->getId();
114  return $category ? $path . '/category/' . $category->getId() : $path;
115  }
116 
123  public function getUrlKey($product)
124  {
125  $generatedProductUrlKey = $this->prepareProductUrlKey($product);
126  return ($product->getUrlKey() === false || empty($generatedProductUrlKey)) ? null : $generatedProductUrlKey;
127  }
128 
135  protected function prepareProductUrlKey(\Magento\Catalog\Model\Product $product)
136  {
137  $urlKey = $product->getUrlKey();
138  return $product->formatUrlKey($urlKey === '' || $urlKey === null ? $product->getName() : $urlKey);
139  }
140 
147  protected function getProductUrlSuffix($storeId = null)
148  {
149  if ($storeId === null) {
150  $storeId = $this->storeManager->getStore()->getId();
151  }
152 
153  if (!isset($this->productUrlSuffix[$storeId])) {
154  $this->productUrlSuffix[$storeId] = $this->scopeConfig->getValue(
155  self::XML_PATH_PRODUCT_URL_SUFFIX,
157  $storeId
158  );
159  }
160  return $this->productUrlSuffix[$storeId];
161  }
162 }
prepareProductDefaultUrlKey(\Magento\Catalog\Model\Product $product)
__construct(\Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\CatalogUrlRewrite\Model\CategoryUrlPathGenerator $categoryUrlPathGenerator, \Magento\Catalog\Api\ProductRepositoryInterface $productRepository)
prepareProductUrlKey(\Magento\Catalog\Model\Product $product)