Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Public Member Functions | Protected Member Functions | Protected Attributes
Category Class Reference
Inheritance diagram for Category:
AbstractResource AbstractEntity AbstractResource EntityInterface ProviderInterface

Public Member Functions

 __construct (\Magento\Eav\Model\Entity\Context $context, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Catalog\Model\Factory $modelFactory, \Magento\Framework\Event\ManagerInterface $eventManager, \Magento\Catalog\Model\ResourceModel\Category\TreeFactory $categoryTreeFactory, \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory, Processor $indexerProcessor, $data=[], \Magento\Framework\Serialize\Serializer\Json $serializer=null)
 
 getEntityType ()
 
 getCategoryProductTable ()
 
 setStoreId ($storeId)
 
 getStoreId ()
 
 deleteChildren (\Magento\Framework\DataObject $object)
 
 getProductsPosition ($category)
 
 getChildrenCount ($categoryId)
 
 checkId ($entityId)
 
 verifyIds (array $ids)
 
 getChildrenAmount ($category, $isActiveFlag=true)
 
 getIsActiveAttributeId ()
 
 findWhereAttributeIs ($entityIdsFilter, $attribute, $expectedValue)
 
 getProductCount ($category)
 
 getCategories ($parent, $recursionLevel=0, $sorted=false, $asCollection=false, $toLoad=true)
 
 getParentDesignCategory ($category)
 
 getChildrenCategories ($category)
 
 getChildren ($category, $recursive=true)
 
 getAllChildren ($category)
 
 isInRootCategoryList ($category)
 
 isForbiddenToDelete ($categoryId)
 
 getCategoryPathById ($categoryId)
 
 changeParent (\Magento\Catalog\Model\Category $category, \Magento\Catalog\Model\Category $newParent, $afterCategoryId=null)
 
 countVisible ()
 
 load ($object, $entityId, $attributes=[])
 
 delete ($object)
 
 save (\Magento\Framework\Model\AbstractModel $object)
 
- Public Member Functions inherited from AbstractResource
 __construct (\Magento\Eav\Model\Entity\Context $context, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Catalog\Model\Factory $modelFactory, $data=[])
 
 getDefaultStoreId ()
 
 getAttributeRawValue ($entityId, $attribute, $store)
 
- Public Member Functions inherited from AbstractEntity
 __construct (Context $context, $data=[])
 
 setConnection ($connection)
 
 getConnection ()
 
 getIdFieldName ()
 
 getTable ($alias)
 
 setType ($type)
 
 getEntityType ()
 
 getType ()
 
 getTypeId ()
 
 unsetAttributes ($attributes=null)
 
 addAttribute (AbstractAttribute $attribute, $object=null)
 
 isPartialLoad ($flag=null)
 
 isPartialSave ($flag=null)
 
 loadAllAttributes ($object=null)
 
 getSortedAttributes ($setId=null)
 
 attributesCompare ($firstAttribute, $secondAttribute)
 
 getAttributesByCode ()
 
 getAttributesByTable ()
 
 getEntityTable ()
 
 getLinkField ()
 
 getEntityIdField ()
 
 getValueEntityIdField ()
 
 getValueTablePrefix ()
 
 getEntityTablePrefix ()
 
 isAttributeStatic ($attribute)
 
 validate ($object)
 
 setNewIncrementId (DataObject $object)
 
 checkAttributeUniqueValue (AbstractAttribute $attribute, $object)
 
 getDefaultAttributeSourceModel ()
 
 load ($object, $entityId, $attributes=[])
 
 save (\Magento\Framework\Model\AbstractModel $object)
 
 saveAttribute (DataObject $object, $attributeCode)
 
 delete ($object)
 
 getDefaultAttributes ()
 
 afterLoad (DataObject $object)
 
 beforeSave (DataObject $object)
 
 afterSave (DataObject $object)
 
 beforeDelete (DataObject $object)
 
 afterDelete (DataObject $object)
 
- Public Member Functions inherited from AbstractResource
 __construct ()
 
 getConnection ()
 
 beginTransaction ()
 
 addCommitCallback ($callback)
 
 commit ()
 
 rollBack ()
 
 getValidationRulesBeforeSave ()
 

Protected Member Functions

 _getTree ()
 
 _beforeDelete (\Magento\Framework\DataObject $object)
 
 _afterDelete (DataObject $object)
 
 _beforeSave (\Magento\Framework\DataObject $object)
 
 _afterSave (\Magento\Framework\DataObject $object)
 
 _savePath ($object)
 
 _getMaxPosition ($path)
 
 _saveCategoryProducts ($category)
 
 _processPositions ($category, $newParent, $afterCategoryId)
 
- Protected Member Functions inherited from AbstractResource
 _getDefaultAttributeModel ()
 
 _isApplicableAttribute ($object, $attribute)
 
 _isCallableAttributeInstance ($instance, $method, $args)
 
 _getLoadAttributesSelect ($object, $table)
 
 _prepareLoadSelect (array $selects)
 
 _saveAttributeValue ($object, $attribute, $value)
 
 _insertAttribute ($object, $attribute, $value)
 
 _updateAttribute ($object, $attribute, $valueId, $value)
 
 _updateAttributeForStore ($object, $attribute, $value, $storeId)
 
 _deleteAttributes ($object, $table, $info)
 
 _getOrigObject ($object)
 
 _canUpdateAttribute (AbstractAttribute $attribute, $value, array &$origData)
 
- Protected Member Functions inherited from AbstractEntity
 _construct ()
 
 _getConfig ()
 
 _isApplicableAttribute ($object, $attribute)
 
 _isCallableAttributeInstance ($instance, $method, $args)
 
 loadAttributesMetadata ($attributes)
 
 _loadModelAttributes ($object)
 
 _prepareLoadSelect (array $selects)
 
 _getLoadRowSelect ($object, $rowId)
 
 _getLoadAttributesSelect ($object, $table)
 
 _setAttributeValue ($object, $valueRow)
 
 processSave ($object)
 
 _getOrigObject ($object)
 
 _collectSaveData ($newObject)
 
 _canUpdateAttribute (AbstractAttribute $attribute, $v, array &$origData)
 
 _getStaticFieldProperties ($field)
 
 _prepareStaticValue ($key, $value)
 
 _insertAttribute ($object, $attribute, $value)
 
 _updateAttribute ($object, $attribute, $valueId, $value)
 
 _saveAttribute ($object, $attribute, $value)
 
 _processAttributeValues ()
 
 _prepareValueForSave ($value, AbstractAttribute $attribute)
 
 _deleteAttributes ($object, $table, $info)
 
 getAttributeRow ($entity, $object, $attribute)
 
 evaluateDelete ($object, $id, $connection)
 
 _afterLoad (DataObject $object)
 
 _beforeSave (DataObject $object)
 
 _afterSave (DataObject $object)
 
 _beforeDelete (DataObject $object)
 
 _afterDelete (DataObject $object)
 
 _getDefaultAttributeModel ()
 
 _getDefaultAttributes ()
 
 _isAttributeValueEmpty (AbstractAttribute $attribute, $value)
 
 getAttributeLoader ()
 
 loadAttributesForObject ($attributes, $object=null)
 
- Protected Member Functions inherited from AbstractResource
 _construct ()
 
 _serializeField (DataObject $object, $field, $defaultValue=null, $unsetEmpty=false)
 
 _unserializeField (DataObject $object, $field, $defaultValue=null)
 
 _prepareDataForTable (DataObject $object, $table)
 
 _prepareTableValueForSave ($value, $type)
 
 _getColumnsForEntityLoad (\Magento\Framework\Model\AbstractModel $object, $tableName)
 
 getSerializer ()
 

Protected Attributes

 $_tree
 
 $_categoryProductTable
 
 $_isActiveAttributeId = null
 
 $_storeId = null
 
 $_eventManager = null
 
 $_categoryCollectionFactory
 
 $_categoryTreeFactory
 
 $entityManager
 
 $aggregateCount
 
- Protected Attributes inherited from AbstractResource
 $_storeManager
 
 $_modelFactory
 
- Protected Attributes inherited from AbstractEntity
 $attributeLoader
 
 $connectionName
 
 $_type
 
 $_attributesByCode = []
 
 $_attributesByTable = []
 
 $_staticAttributes = []
 
 $_entityTable
 
 $_describeTable = []
 
 $_entityIdField
 
 $linkIdField
 
 $_valueEntityIdField
 
 $_valueTablePrefix
 
 $_entityTablePrefix
 
 $_isPartialLoad = false
 
 $_isPartialSave = false
 
 $_sortingSetId = null
 
 $_attributeValuesToDelete = []
 
 $_attributeValuesToSave = []
 
 $_resource
 
 $_eavConfig
 
 $_attrSetEntity
 
 $_localeFormat
 
 $_resourceHelper
 
 $_universalFactory
 
 $transactionManager
 
 $objectRelationProcessor
 
- Protected Attributes inherited from AbstractResource
 $serializer
 
 $_logger
 

Additional Inherited Members

- Static Protected Attributes inherited from AbstractEntity
static $_attributeBackendTables = []
 

Detailed Description

@SuppressWarnings(PHPMD.CouplingBetweenObjects)

Definition at line 21 of file Category.php.

Constructor & Destructor Documentation

◆ __construct()

__construct ( \Magento\Eav\Model\Entity\Context  $context,
\Magento\Store\Model\StoreManagerInterface  $storeManager,
\Magento\Catalog\Model\Factory  $modelFactory,
\Magento\Framework\Event\ManagerInterface  $eventManager,
\Magento\Catalog\Model\ResourceModel\Category\TreeFactory  $categoryTreeFactory,
\Magento\Catalog\Model\ResourceModel\Category\CollectionFactory  $categoryCollectionFactory,
Processor  $indexerProcessor,
  $data = [],
\Magento\Framework\Serialize\Serializer\Json  $serializer = null 
)

Category constructor.

Parameters
\Magento\Eav\Model\Entity\Context$context
\Magento\Store\Model\StoreManagerInterface$storeManager
\Magento\Catalog\Model\Factory$modelFactory
\Magento\Framework\Event\ManagerInterface$eventManager
Category\TreeFactory$categoryTreeFactory
Category\CollectionFactory$categoryCollectionFactory
Processor$indexerProcessor
array$data
\Magento\Framework\Serialize\Serializer\Json | null$serializer

Definition at line 104 of file Category.php.

114  {
115  parent::__construct(
116  $context,
118  $modelFactory,
119  $data
120  );
121  $this->_categoryTreeFactory = $categoryTreeFactory;
122  $this->_categoryCollectionFactory = $categoryCollectionFactory;
123  $this->_eventManager = $eventManager;
124  $this->connectionName = 'catalog';
125  $this->indexerProcessor = $indexerProcessor;
127  ->get(\Magento\Framework\Serialize\Serializer\Json::class);
128  }
$storeManager

Member Function Documentation

◆ _afterDelete()

_afterDelete ( DataObject  $object)
protected

Mark Category indexer as invalid to be picked up by cron.

Parameters
DataObject$object
Returns
$this

Definition at line 216 of file Category.php.

217  {
218  $this->indexerProcessor->markIndexerAsInvalid();
219  return parent::_afterDelete($object);
220  }

◆ _afterSave()

_afterSave ( \Magento\Framework\DataObject  $object)
protected

Process category data after save category object save related products ids and update path value

Parameters
\Magento\Framework\DataObject$object
Returns
$this

Add identifier for new category

Definition at line 306 of file Category.php.

307  {
311  if (substr($object->getPath(), -1) == '/') {
312  $object->setPath($object->getPath() . $object->getId());
313  $this->_savePath($object);
314  }
315 
316  $this->_saveCategoryProducts($object);
317  return parent::_afterSave($object);
318  }

◆ _beforeDelete()

_beforeDelete ( \Magento\Framework\DataObject  $object)
protected

Process category data before delete update children count for parent category delete child categories

Parameters
\Magento\Framework\DataObject$object
Returns
$this

Definition at line 203 of file Category.php.

204  {
205  parent::_beforeDelete($object);
206  $this->getAggregateCount()->processDelete($object);
207  $this->deleteChildren($object);
208  }
deleteChildren(\Magento\Framework\DataObject $object)
Definition: Category.php:228

◆ _beforeSave()

_beforeSave ( \Magento\Framework\DataObject  $object)
protected

Process category data before saving prepare path and increment children count for parent categories

Parameters
\Magento\Framework\DataObject$object
Returns
$this @SuppressWarnings(PHPMD.NPathComplexity) @SuppressWarnings(PHPMD.CyclomaticComplexity)

Definition at line 259 of file Category.php.

260  {
261  parent::_beforeSave($object);
262 
263  if (!$object->getChildrenCount()) {
264  $object->setChildrenCount(0);
265  }
266  $object->setAttributeSetId(
267  $object->getAttributeSetId() ?: $this->getEntityType()->getDefaultAttributeSetId()
268  );
269  if ($object->isObjectNew()) {
270  if ($object->getPosition() === null) {
271  $object->setPosition($this->_getMaxPosition($object->getPath()) + 1);
272  }
273  $path = explode('/', $object->getPath());
274  $level = count($path) - ($object->getId() ? 1 : 0);
275  $toUpdateChild = array_diff($path, [$object->getId()]);
276 
277  if (!$object->hasPosition()) {
278  $object->setPosition($this->_getMaxPosition(implode('/', $toUpdateChild)) + 1);
279  }
280  if (!$object->hasLevel()) {
281  $object->setLevel($level);
282  }
283  if (!$object->hasParentId() && $level) {
284  $object->setParentId($path[$level - 1]);
285  }
286  if (!$object->getId()) {
287  $object->setPath($object->getPath() . '/');
288  }
289 
290  $this->getConnection()->update(
291  $this->getEntityTable(),
292  ['children_count' => new \Zend_Db_Expr('children_count+1')],
293  ['entity_id IN(?)' => $toUpdateChild]
294  );
295  }
296  return $this;
297  }

◆ _getMaxPosition()

_getMaxPosition (   $path)
protected

Get maximum position of child categories by specific tree path

Parameters
string$path
Returns
int

Definition at line 345 of file Category.php.

346  {
347  $connection = $this->getConnection();
348  $positionField = $connection->quoteIdentifier('position');
349  $level = count(explode('/', $path));
350  $bind = ['c_level' => $level, 'c_path' => $path . '/%'];
351  $select = $connection->select()->from(
352  $this->getTable('catalog_category_entity'),
353  'MAX(' . $positionField . ')'
354  )->where(
355  $connection->quoteIdentifier('path') . ' LIKE :c_path'
356  )->where(
357  $connection->quoteIdentifier('level') . ' = :c_level'
358  );
359 
360  $position = $connection->fetchOne($select, $bind);
361  if (!$position) {
362  $position = 0;
363  }
364  return $position;
365  }
$connection
Definition: bulk.php:13

◆ _getTree()

_getTree ( )
protected

Retrieve category tree object

Returns
\Magento\Framework\Data\Tree\Db

Definition at line 187 of file Category.php.

188  {
189  if (!$this->_tree) {
190  $this->_tree = $this->_categoryTreeFactory->create()->load();
191  }
192  return $this->_tree;
193  }

◆ _processPositions()

_processPositions (   $category,
  $newParent,
  $afterCategoryId 
)
protected

Process positions of old parent category children and new parent category children. Get position for moved category

Parameters
\Magento\Catalog\Model\Category$category
\Magento\Catalog\Model\Category$newParent
null | int$afterCategoryId
Returns
int

Prepare position value

Definition at line 992 of file Category.php.

993  {
994  $table = $this->getEntityTable();
995  $connection = $this->getConnection();
996  $positionField = $connection->quoteIdentifier('position');
997 
998  $bind = ['position' => new \Zend_Db_Expr($positionField . ' - 1')];
999  $where = [
1000  'parent_id = ?' => $category->getParentId(),
1001  $positionField . ' > ?' => $category->getPosition(),
1002  ];
1003  $connection->update($table, $bind, $where);
1004 
1008  if ($afterCategoryId) {
1009  $select = $connection->select()->from($table, 'position')->where('entity_id = :entity_id');
1010  $position = $connection->fetchOne($select, ['entity_id' => $afterCategoryId]);
1011  $position += 1;
1012  } else {
1013  $position = 1;
1014  }
1015 
1016  $bind = ['position' => new \Zend_Db_Expr($positionField . ' + 1')];
1017  $where = ['parent_id = ?' => $newParent->getId(), $positionField . ' >= ?' => $position];
1018  $connection->update($table, $bind, $where);
1019 
1020  return $position;
1021  }
$connection
Definition: bulk.php:13
$table
Definition: trigger.php:14

◆ _saveCategoryProducts()

_saveCategoryProducts (   $category)
protected

Save category products relation

Parameters
\Magento\Catalog\Model\Category$category
Returns
$this @SuppressWarnings(PHPMD.CyclomaticComplexity) @SuppressWarnings(PHPMD.NPathComplexity)

new category-product relationships

Example re-save category

old category-product relationships

Find product ids which are presented in both arrays and saved before (check $oldProducts array)

Delete products from category

Add products to category

Update product positions in category

Setting affected products to category for third party engine index refresh

Definition at line 375 of file Category.php.

376  {
377  $category->setIsChangedProductList(false);
378  $id = $category->getId();
382  $products = $category->getPostedProducts();
383 
387  if ($products === null) {
388  return $this;
389  }
390 
394  $oldProducts = $category->getProductsPosition();
395 
396  $insert = array_diff_key($products, $oldProducts);
397  $delete = array_diff_key($oldProducts, $products);
398 
403  $update = array_intersect_key($products, $oldProducts);
404  $update = array_diff_assoc($update, $oldProducts);
405 
406  $connection = $this->getConnection();
407 
411  if (!empty($delete)) {
412  $cond = ['product_id IN(?)' => array_keys($delete), 'category_id=?' => $id];
413  $connection->delete($this->getCategoryProductTable(), $cond);
414  }
415 
419  if (!empty($insert)) {
420  $data = [];
421  foreach ($insert as $productId => $position) {
422  $data[] = [
423  'category_id' => (int)$id,
424  'product_id' => (int)$productId,
425  'position' => (int)$position,
426  ];
427  }
428  $connection->insertMultiple($this->getCategoryProductTable(), $data);
429  }
430 
434  if (!empty($update)) {
435  $newPositions = [];
436  foreach ($update as $productId => $position) {
437  $delta = $position - $oldProducts[$productId];
438  if (!isset($newPositions[$delta])) {
439  $newPositions[$delta] = [];
440  }
441  $newPositions[$delta][] = $productId;
442  }
443 
444  foreach ($newPositions as $delta => $productIds) {
445  $bind = ['position' => new \Zend_Db_Expr("position + ({$delta})")];
446  $where = ['category_id = ?' => (int)$id, 'product_id IN (?)' => $productIds];
447  $connection->update($this->getCategoryProductTable(), $bind, $where);
448  }
449  }
450 
451  if (!empty($insert) || !empty($delete)) {
452  $productIds = array_unique(array_merge(array_keys($insert), array_keys($delete)));
453  $this->_eventManager->dispatch(
454  'catalog_category_change_products',
455  ['category' => $category, 'product_ids' => $productIds]
456  );
457 
458  $category->setChangedProductIds($productIds);
459  }
460 
461  if (!empty($insert) || !empty($update) || !empty($delete)) {
462  $category->setIsChangedProductList(true);
463 
467  $productIds = array_keys($insert + $delete + $update);
468  $category->setAffectedProductIds($productIds);
469  }
470  return $this;
471  }
$id
Definition: fieldset.phtml:14
$connection
Definition: bulk.php:13

◆ _savePath()

_savePath (   $object)
protected

Update path field

Parameters
\Magento\Catalog\Model\Category$object
Returns
$this

Definition at line 326 of file Category.php.

327  {
328  if ($object->getId()) {
329  $this->getConnection()->update(
330  $this->getEntityTable(),
331  ['path' => $object->getPath()],
332  ['entity_id = ?' => $object->getId()]
333  );
334  $object->unsetData('path_ids');
335  }
336  return $this;
337  }

◆ changeParent()

changeParent ( \Magento\Catalog\Model\Category  $category,
\Magento\Catalog\Model\Category  $newParent,
  $afterCategoryId = null 
)

Move category to another parent node

Parameters
\Magento\Catalog\Model\Category$category
\Magento\Catalog\Model\Category$newParent
null | int$afterCategoryId
Returns
$this

Decrease children count for all old category parent categories

Increase children count for new category parents

Update children nodes path

Update moved category data

Definition at line 913 of file Category.php.

917  {
918  $childrenCount = $this->getChildrenCount($category->getId()) + 1;
919  $table = $this->getEntityTable();
920  $connection = $this->getConnection();
921  $levelFiled = $connection->quoteIdentifier('level');
922  $pathField = $connection->quoteIdentifier('path');
923 
927  $connection->update(
928  $table,
929  ['children_count' => new \Zend_Db_Expr('children_count - ' . $childrenCount)],
930  ['entity_id IN(?)' => $category->getParentIds()]
931  );
932 
936  $connection->update(
937  $table,
938  ['children_count' => new \Zend_Db_Expr('children_count + ' . $childrenCount)],
939  ['entity_id IN(?)' => $newParent->getPathIds()]
940  );
941 
942  $position = $this->_processPositions($category, $newParent, $afterCategoryId);
943 
944  $newPath = sprintf('%s/%s', $newParent->getPath(), $category->getId());
945  $newLevel = $newParent->getLevel() + 1;
946  $levelDisposition = $newLevel - $category->getLevel();
947 
951  $connection->update(
952  $table,
953  [
954  'path' => new \Zend_Db_Expr(
955  'REPLACE(' . $pathField . ',' . $connection->quote(
956  $category->getPath() . '/'
957  ) . ', ' . $connection->quote(
958  $newPath . '/'
959  ) . ')'
960  ),
961  'level' => new \Zend_Db_Expr($levelFiled . ' + ' . $levelDisposition)
962  ],
963  [$pathField . ' LIKE ?' => $category->getPath() . '/%']
964  );
968  $data = [
969  'path' => $newPath,
970  'level' => $newLevel,
971  'position' => $position,
972  'parent_id' => $newParent->getId(),
973  ];
974  $connection->update($table, $data, ['entity_id = ?' => $category->getId()]);
975 
976  // Update category object to new data
977  $category->addData($data);
978  $category->unsetData('path_ids');
979 
980  return $this;
981  }
$connection
Definition: bulk.php:13
$table
Definition: trigger.php:14
_processPositions($category, $newParent, $afterCategoryId)
Definition: Category.php:992

◆ checkId()

checkId (   $entityId)

Check if category id exist

Parameters
int$entityId
Returns
bool

Definition at line 517 of file Category.php.

518  {
519  $select = $this->getConnection()->select()->from(
520  $this->getEntityTable(),
521  'entity_id'
522  )->where(
523  'entity_id = :entity_id'
524  );
525  $bind = ['entity_id' => $entityId];
526 
527  return $this->getConnection()->fetchOne($select, $bind);
528  }

◆ countVisible()

countVisible ( )

Get total number of persistent categories in the system, excluding the default category

Returns
int

Definition at line 1028 of file Category.php.

1029  {
1030  $connection = $this->getConnection();
1031  $select = $connection->select();
1032  $select->from($this->getEntityTable(), 'COUNT(*)')->where('parent_id != ?', 0);
1033  return (int)$connection->fetchOne($select);
1034  }
$connection
Definition: bulk.php:13

◆ delete()

delete (   $object)

{}

Definition at line 1067 of file Category.php.

1068  {
1069  $this->getEntityManager()->delete($object);
1070  $this->_eventManager->dispatch(
1071  'catalog_category_delete_after_done',
1072  ['product' => $object, 'category' => $object]
1073  );
1074  return $this;
1075  }

◆ deleteChildren()

deleteChildren ( \Magento\Framework\DataObject  $object)

Delete children categories of specific category

Parameters
\Magento\Framework\DataObject$object
Returns
$this

Add deleted children ids to object This data can be used in after delete event

Definition at line 228 of file Category.php.

229  {
230  if ($object->getSkipDeleteChildren()) {
231  return $this;
232  }
233 
234  $categories = $this->_categoryCollectionFactory->create();
235  $categories->addAttributeToFilter('path', ['like' => $object->getPath() . '/%']);
236  $childrenIds = $categories->getAllIds();
237  foreach ($categories as $category) {
238  $category->setSkipDeleteChildren(true);
239  $category->delete();
240  }
241 
246  $object->setDeletedChildrenIds($childrenIds);
247  return $this;
248  }
$categories

◆ findWhereAttributeIs()

findWhereAttributeIs (   $entityIdsFilter,
  $attribute,
  $expectedValue 
)

Return entities where attribute value is

Parameters
array | int$entityIdsFilter
\Magento\Eav\Model\Entity\Attribute$attribute
mixed$expectedValue
Returns
array

Definition at line 617 of file Category.php.

618  {
619  // @codingStandardsIgnoreStart
620  $serializeData = $this->serializer->serialize($entityIdsFilter);
621  $entityIdsFilterHash = md5($serializeData);
622  // @codingStandardsIgnoreEnd
623 
624  if (!isset($this->entitiesWhereAttributesIs[$entityIdsFilterHash][$attribute->getId()][$expectedValue])) {
625  $linkField = $this->getLinkField();
626  $bind = ['attribute_id' => $attribute->getId(), 'value' => $expectedValue];
627  $selectEntities = $this->getConnection()->select()->from(
628  ['ce' => $this->getTable('catalog_category_entity')],
629  ['entity_id']
630  )->joinLeft(
631  ['ci' => $attribute->getBackend()->getTable()],
632  "ci.{$linkField} = ce.{$linkField} AND attribute_id = :attribute_id",
633  ['value']
634  )->where(
635  'ci.value = :value'
636  )->where(
637  'ce.entity_id IN (?)',
638  $entityIdsFilter
639  );
640  $this->entitiesWhereAttributesIs[$entityIdsFilterHash][$attribute->getId()][$expectedValue] =
641  $this->getConnection()->fetchCol($selectEntities, $bind);
642  }
643 
644  return $this->entitiesWhereAttributesIs[$entityIdsFilterHash][$attribute->getId()][$expectedValue];
645  }

◆ getAllChildren()

getAllChildren (   $category)

Return all children ids of category (with category id)

Parameters
\Magento\Catalog\Model\Category$category
Returns
array

Definition at line 841 of file Category.php.

842  {
843  $children = $this->getChildren($category);
844  $myId = [$category->getId()];
845  $children = array_merge($myId, $children);
846 
847  return $children;
848  }
getChildren($category, $recursive=true)
Definition: Category.php:798
$children
Definition: actions.phtml:11

◆ getCategories()

getCategories (   $parent,
  $recursionLevel = 0,
  $sorted = false,
  $asCollection = false,
  $toLoad = true 
)

Retrieve categories

Parameters
integer$parent
integer$recursionLevel
boolean | string$sorted
boolean$asCollection
boolean$toLoad
Returns
\Magento\Framework\Data\Tree\Node\Collection|\Magento\Catalog\Model\ResourceModel\Category\Collection

Definition at line 680 of file Category.php.

681  {
682  $tree = $this->_categoryTreeFactory->create();
683  /* @var $tree \Magento\Catalog\Model\ResourceModel\Category\Tree */
684  $nodes = $tree->loadNode($parent)->loadChildren($recursionLevel)->getChildren();
685 
686  $tree->addCollectionData(null, $sorted, $parent, $toLoad, true);
687 
688  if ($asCollection) {
689  return $tree->getCollection();
690  }
691  return $nodes;
692  }

◆ getCategoryPathById()

getCategoryPathById (   $categoryId)

Get category path value by its id

Parameters
int$categoryId
Returns
string

Definition at line 892 of file Category.php.

893  {
894  $select = $this->getConnection()->select()->from(
895  $this->getEntityTable(),
896  ['path']
897  )->where(
898  'entity_id = :entity_id'
899  );
900  $bind = ['entity_id' => (int)$categoryId];
901 
902  return $this->getConnection()->fetchOne($select, $bind);
903  }

◆ getCategoryProductTable()

getCategoryProductTable ( )

Category product table name getter

Returns
string

Definition at line 149 of file Category.php.

150  {
151  if (!$this->_categoryProductTable) {
152  $this->_categoryProductTable = $this->getTable('catalog_category_product');
153  }
155  }

◆ getChildren()

getChildren (   $category,
  $recursive = true 
)

Return children ids of category

Parameters
\Magento\Catalog\Model\Category$category
boolean$recursive
Returns
array

Definition at line 798 of file Category.php.

799  {
800  $linkField = $this->getLinkField();
801  $attributeId = $this->getIsActiveAttributeId();
802  $backendTable = $this->getTable([$this->getEntityTablePrefix(), 'int']);
803  $connection = $this->getConnection();
804  $checkSql = $connection->getCheckSql('c.value_id > 0', 'c.value', 'd.value');
805  $bind = [
806  'attribute_id' => $attributeId,
807  'store_id' => $category->getStoreId(),
808  'scope' => 1,
809  'c_path' => $category->getPath() . '/%',
810  ];
811  $select = $this->getConnection()->select()->from(
812  ['m' => $this->getEntityTable()],
813  'entity_id'
814  )->joinLeft(
815  ['d' => $backendTable],
816  "d.attribute_id = :attribute_id AND d.store_id = 0 AND d.{$linkField} = m.{$linkField}",
817  []
818  )->joinLeft(
819  ['c' => $backendTable],
820  "c.attribute_id = :attribute_id AND c.store_id = :store_id AND c.{$linkField} = m.{$linkField}",
821  []
822  )->where(
823  $checkSql . ' = :scope'
824  )->where(
825  $connection->quoteIdentifier('path') . ' LIKE :c_path'
826  );
827  if (!$recursive) {
828  $select->where($connection->quoteIdentifier('level') . ' <= :c_level');
829  $bind['c_level'] = $category->getLevel() + 1;
830  }
831 
832  return $connection->fetchCol($select, $bind);
833  }
$connection
Definition: bulk.php:13

◆ getChildrenAmount()

getChildrenAmount (   $category,
  $isActiveFlag = true 
)

Get count of active/not active children categories

Parameters
\Magento\Catalog\Model\Category$category
bool$isActiveFlag
Returns
int

Definition at line 560 of file Category.php.

561  {
562  $storeId = $this->_storeManager->getStore()->getId();
563  $attributeId = $this->getIsActiveAttributeId();
564  $table = $this->getTable([$this->getEntityTablePrefix(), 'int']);
565  $connection = $this->getConnection();
566  $checkSql = $connection->getCheckSql('c.value_id > 0', 'c.value', 'd.value');
567  $linkField = $this->getLinkField();
568  $bind = [
569  'attribute_id' => $attributeId,
570  'store_id' => $storeId,
571  'active_flag' => $isActiveFlag,
572  'c_path' => $category->getPath() . '/%',
573  ];
574  $select = $connection->select()->from(
575  ['m' => $this->getEntityTable()],
576  ['COUNT(m.entity_id)']
577  )->joinLeft(
578  ['d' => $table],
579  "d.attribute_id = :attribute_id AND d.store_id = 0 AND d.{$linkField} = m.{$linkField}",
580  []
581  )->joinLeft(
582  ['c' => $table],
583  "c.attribute_id = :attribute_id AND c.store_id = :store_id AND c.{$linkField} = m.{$linkField}",
584  []
585  )->where(
586  'm.path LIKE :c_path'
587  )->where(
588  $checkSql . ' = :active_flag'
589  );
590 
591  return $this->getConnection()->fetchOne($select, $bind);
592  }
$connection
Definition: bulk.php:13
$table
Definition: trigger.php:14

◆ getChildrenCategories()

getChildrenCategories (   $category)

Return child categories

Parameters
\Magento\Catalog\Model\Category$category
Returns
\Magento\Catalog\Model\ResourceModel\Category\Collection

Definition at line 766 of file Category.php.

767  {
768  $collection = $category->getCollection();
769  /* @var $collection \Magento\Catalog\Model\ResourceModel\Category\Collection */
770  $collection->addAttributeToSelect(
771  'url_key'
772  )->addAttributeToSelect(
773  'name'
774  )->addAttributeToSelect(
775  'all_children'
776  )->addAttributeToSelect(
777  'is_anchor'
778  )->addAttributeToFilter(
779  'is_active',
780  1
781  )->addIdFilter(
782  $category->getChildren()
783  )->setOrder(
784  'position',
785  \Magento\Framework\DB\Select::SQL_ASC
786  )->joinUrlRewrite();
787 
788  return $collection;
789  }
const SQL_ASC
Definition: Select.php:81

◆ getChildrenCount()

getChildrenCount (   $categoryId)

Get children categories count

Parameters
int$categoryId
Returns
int

Definition at line 498 of file Category.php.

499  {
500  $select = $this->getConnection()->select()->from(
501  $this->getEntityTable(),
502  'children_count'
503  )->where(
504  'entity_id = :entity_id'
505  );
506  $bind = ['entity_id' => $categoryId];
507 
508  return $this->getConnection()->fetchOne($select, $bind);
509  }

◆ getEntityType()

getEntityType ( )

Entity type getter and lazy loader

Returns
\Magento\Eav\Model\Entity\Type
Exceptions

Definition at line 136 of file Category.php.

137  {
138  if (empty($this->_type)) {
139  $this->setType(\Magento\Catalog\Model\Category::ENTITY);
140  }
141  return parent::getEntityType();
142  }

◆ getIsActiveAttributeId()

getIsActiveAttributeId ( )

Get "is_active" attribute identifier

Returns
int

Definition at line 599 of file Category.php.

600  {
601  if ($this->_isActiveAttributeId === null) {
602  $this->_isActiveAttributeId = (int)$this->_eavConfig
603  ->getAttribute($this->getEntityType(), 'is_active')
604  ->getAttributeId();
605  }
607  }

◆ getParentDesignCategory()

getParentDesignCategory (   $category)

Return parent category of current category with own custom design settings

Parameters
\Magento\Catalog\Model\Category$category
Returns
\Magento\Catalog\Model\Category

Definition at line 726 of file Category.php.

727  {
728  $pathIds = array_reverse($category->getPathIds());
729  $collection = $category->getCollection()->setStore(
730  $this->_storeManager->getStore()
731  )->addAttributeToSelect(
732  'custom_design'
733  )->addAttributeToSelect(
734  'custom_design_from'
735  )->addAttributeToSelect(
736  'custom_design_to'
737  )->addAttributeToSelect(
738  'page_layout'
739  )->addAttributeToSelect(
740  'custom_layout_update'
741  )->addAttributeToSelect(
742  'custom_apply_to_products'
743  )->addFieldToFilter(
744  'entity_id',
745  ['in' => $pathIds]
746  )->addAttributeToFilter(
747  'custom_use_parent_settings',
748  [['eq' => 0], ['null' => 0]],
749  'left'
750  )->addFieldToFilter(
751  'level',
752  ['neq' => 0]
753  )->setOrder(
754  'level',
755  'DESC'
756  )->load();
757  return $collection->getFirstItem();
758  }

◆ getProductCount()

getProductCount (   $category)

Get products count in category

Parameters
\Magento\Catalog\Model\Category$category
Returns
int

Definition at line 653 of file Category.php.

654  {
655  $productTable = $this->_resource->getTableName('catalog_category_product');
656 
657  $select = $this->getConnection()->select()->from(
658  ['main_table' => $productTable],
659  [new \Zend_Db_Expr('COUNT(main_table.product_id)')]
660  )->where(
661  'main_table.category_id = :category_id'
662  );
663 
664  $bind = ['category_id' => (int)$category->getId()];
665  $counts = $this->getConnection()->fetchOne($select, $bind);
666 
667  return intval($counts);
668  }

◆ getProductsPosition()

getProductsPosition (   $category)

Get positions of associated to category products

Parameters
\Magento\Catalog\Model\Category$category
Returns
array

Definition at line 479 of file Category.php.

480  {
481  $select = $this->getConnection()->select()->from(
482  $this->getCategoryProductTable(),
483  ['product_id', 'position']
484  )->where(
485  'category_id = :category_id'
486  );
487  $bind = ['category_id' => (int)$category->getId()];
488 
489  return $this->getConnection()->fetchPairs($select, $bind);
490  }

◆ getStoreId()

getStoreId ( )

Return store id

Returns
integer

Definition at line 174 of file Category.php.

175  {
176  if ($this->_storeId === null) {
177  return $this->_storeManager->getStore()->getId();
178  }
179  return $this->_storeId;
180  }

◆ isForbiddenToDelete()

isForbiddenToDelete (   $categoryId)

Check category is forbidden to delete. If category is root and assigned to store group return false

Parameters
integer$categoryId
Returns
boolean

Definition at line 870 of file Category.php.

871  {
872  $select = $this->getConnection()->select()->from(
873  $this->getTable('store_group'),
874  ['group_id']
875  )->where(
876  'root_category_id = :root_category_id'
877  );
878  $result = $this->getConnection()->fetchOne($select, ['root_category_id' => $categoryId]);
879 
880  if ($result) {
881  return true;
882  }
883  return false;
884  }

◆ isInRootCategoryList()

isInRootCategoryList (   $category)

Check is category in list of store categories

Parameters
\Magento\Catalog\Model\Category$category
Returns
boolean

Definition at line 856 of file Category.php.

857  {
858  $rootCategoryId = $this->_storeManager->getStore()->getRootCategoryId();
859 
860  return in_array($rootCategoryId, $category->getParentIds());
861  }

◆ load()

load (   $object,
  $entityId,
  $attributes = [] 
)

Reset firstly loaded attributes

Parameters
\Magento\Framework\DataObject$object
integer$entityId
array | null$attributes
Returns
$this

Definition at line 1044 of file Category.php.

1045  {
1046  $this->_attributes = [];
1047  $select = $this->_getLoadRowSelect($object, $entityId);
1048  $row = $this->getConnection()->fetchRow($select);
1049 
1050  if (is_array($row)) {
1051  $object->addData($row);
1052  } else {
1053  $object->isObjectNew(true);
1054  }
1055 
1056  $this->loadAttributesForObject($attributes, $object);
1057  $object = $this->getEntityManager()->load($object, $entityId);
1058  if (!$this->getEntityManager()->has($object)) {
1059  $object->isObjectNew(true);
1060  }
1061  return $this;
1062  }
$attributes
Definition: matrix.phtml:13
loadAttributesForObject($attributes, $object=null)

◆ save()

Save entity's attributes into the object's resource

Parameters
\Magento\Framework\Model\AbstractModel$object
Returns
$this
Exceptions

Definition at line 1084 of file Category.php.

1085  {
1086  $this->getEntityManager()->save($object);
1087  return $this;
1088  }

◆ setStoreId()

setStoreId (   $storeId)

Set store Id

Parameters
integer$storeId
Returns
$this

Definition at line 163 of file Category.php.

164  {
165  $this->_storeId = $storeId;
166  return $this;
167  }

◆ verifyIds()

verifyIds ( array  $ids)

Check array of category identifiers

Parameters
array$ids
Returns
array

Definition at line 536 of file Category.php.

537  {
538  if (empty($ids)) {
539  return [];
540  }
541 
542  $select = $this->getConnection()->select()->from(
543  $this->getEntityTable(),
544  'entity_id'
545  )->where(
546  'entity_id IN(?)',
547  $ids
548  );
549 
550  return $this->getConnection()->fetchCol($select);
551  }

Field Documentation

◆ $_categoryCollectionFactory

$_categoryCollectionFactory
protected

Definition at line 68 of file Category.php.

◆ $_categoryProductTable

$_categoryProductTable
protected

Definition at line 35 of file Category.php.

◆ $_categoryTreeFactory

$_categoryTreeFactory
protected

Definition at line 75 of file Category.php.

◆ $_eventManager

$_eventManager = null
protected

Definition at line 61 of file Category.php.

◆ $_isActiveAttributeId

$_isActiveAttributeId = null
protected

Definition at line 47 of file Category.php.

◆ $_storeId

$_storeId = null
protected

Definition at line 54 of file Category.php.

◆ $_tree

$_tree
protected

Definition at line 28 of file Category.php.

◆ $aggregateCount

$aggregateCount
protected

Definition at line 85 of file Category.php.

◆ $entityManager

$entityManager
protected

Definition at line 80 of file Category.php.


The documentation for this class was generated from the following file: