Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
AnchorUrlRewriteGenerator.php
Go to the documentation of this file.
1 <?php
7 
15 use Magento\UrlRewrite\Service\V1\Data\UrlRewriteFactory;
16 
18 {
22  protected $urlPathGenerator;
23 
27  protected $urlRewriteFactory;
28 
32  private $categoryRepository;
33 
39  public function __construct(
41  UrlRewriteFactory $urlRewriteFactory,
42  CategoryRepositoryInterface $categoryRepository
43  ) {
44  $this->urlPathGenerator = $urlPathGenerator;
45  $this->urlRewriteFactory = $urlRewriteFactory;
46  $this->categoryRepository = $categoryRepository;
47  }
48 
57  public function generate($storeId, Product $product, ObjectRegistry $productCategories)
58  {
59  $urls = [];
60  foreach ($productCategories->getList() as $category) {
61  $anchorCategoryIds = $category->getAnchorsAbove();
62  if ($anchorCategoryIds) {
63  foreach ($anchorCategoryIds as $anchorCategoryId) {
64  $anchorCategory = $this->categoryRepository->get($anchorCategoryId);
65  $urls[] = $this->urlRewriteFactory->create()
67  ->setEntityId($product->getId())
68  ->setRequestPath(
69  $this->urlPathGenerator->getUrlPathWithSuffix(
70  $product,
71  $storeId,
72  $anchorCategory
73  )
74  )
75  ->setTargetPath(
76  $this->urlPathGenerator->getCanonicalUrlPath(
77  $product,
78  $anchorCategory
79  )
80  )
82  ->setMetadata(['category_id' => $anchorCategory->getId()]);
83  }
84  }
85  }
86 
87  return $urls;
88  }
89 }
__construct(ProductUrlPathGenerator $urlPathGenerator, UrlRewriteFactory $urlRewriteFactory, CategoryRepositoryInterface $categoryRepository)
generate($storeId, Product $product, ObjectRegistry $productCategories)