Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Category.php
Go to the documentation of this file.
1 <?php
7 
9 use Magento\Catalog\Model\CategoryFactory as CategoryModelFactory;
12 
13 class Category
14 {
18  private $coreRegistry;
19 
23  private $category;
24 
28  private $categoryId;
29 
33  private $isApplied = false;
34 
38  private $layer;
39 
43  private $categoryFactory;
44 
51  public function __construct(
52  Registry $coreRegistry,
53  CategoryModelFactory $categoryFactory,
54  Layer $layer
55  ) {
56  $this->coreRegistry = $coreRegistry;
57  $this->layer = $layer;
58  $this->categoryFactory = $categoryFactory;
59  }
60 
66  public function isValid()
67  {
68  $category = $this->getCategory();
69  if ($category->getId()) {
70  while ($category->getLevel() != 0) {
71  if (!$category->getIsActive()) {
72  return false;
73  }
74  $category = $category->getParentCategory();
75  }
76 
77  return true;
78  }
79 
80  return false;
81  }
82 
87  public function setCategoryId($categoryId)
88  {
89  $this->isApplied = true;
90  $this->category = null;
91  $this->categoryId = $categoryId;
92 
93  return $this;
94  }
95 
99  private function isApplied()
100  {
101  return $this->isApplied;
102  }
103 
109  public function getCategory()
110  {
111  if ($this->category === null) {
113  $category = null;
114  if ($this->categoryId !== null) {
115  $category = $this->categoryFactory->create()
116  ->setStoreId(
117  $this->getLayer()
118  ->getCurrentStore()
119  ->getId()
120  )
121  ->load($this->categoryId);
122  }
123 
124  if ($category === null || !$category->getId()) {
125  $category = $this->getLayer()
126  ->getCurrentCategory();
127  }
128 
129  $this->coreRegistry->register('current_category_filter', $category, true);
130  $this->category = $category;
131  }
132 
133  return $this->category;
134  }
135 
141  public function getResetValue()
142  {
143  if ($this->isApplied()) {
147  $category = $this->getCategory();
148  $pathIds = array_reverse($category->getPathIds());
149  $curCategoryId = $this->getLayer()
150  ->getCurrentCategory()
151  ->getId();
152  if (isset($pathIds[1]) && $pathIds[1] != $curCategoryId) {
153  return $pathIds[1];
154  }
155  }
156 
157  return null;
158  }
159 
163  private function getLayer()
164  {
165  return $this->layer;
166  }
167 }
__construct(Registry $coreRegistry, CategoryModelFactory $categoryFactory, Layer $layer)
Definition: Category.php:51