本文整理汇总了PHP中Magento\Catalog\Api\CategoryRepositoryInterface::get方法的典型用法代码示例。如果您正苦于以下问题:PHP CategoryRepositoryInterface::get方法的具体用法?PHP CategoryRepositoryInterface::get怎么用?PHP CategoryRepositoryInterface::get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Magento\Catalog\Api\CategoryRepositoryInterface
的用法示例。
在下文中一共展示了CategoryRepositoryInterface::get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: getRssData
/**
* {@inheritdoc}
*/
public function getRssData()
{
try {
$category = $this->categoryRepository->get($this->getRequest()->getParam('cid'));
} catch (NoSuchEntityException $e) {
return ['title' => 'Category Not Found', 'description' => 'Category Not Found', 'link' => $this->getUrl(''), 'charset' => 'UTF-8'];
}
$category->setIsAnchor(true);
$newUrl = $category->getUrl();
$title = $category->getName();
$data = ['title' => $title, 'description' => $title, 'link' => $newUrl, 'charset' => 'UTF-8'];
/** @var $product \Magento\Catalog\Model\Product */
foreach ($this->rssModel->getProductCollection($category, $this->getStoreId()) as $product) {
$product->setAllowedInRss(true);
$product->setAllowedPriceInRss(true);
$this->_eventManager->dispatch('rss_catalog_category_xml_callback', ['product' => $product]);
if (!$product->getAllowedInRss()) {
continue;
}
$description = '
<table><tr>
<td><a href="%s"><img src="%s" border="0" align="left" height="75" width="75"></a></td>
<td style="text-decoration:none;">%s %s</td>
</tr></table>
';
$description = sprintf($description, $product->getProductUrl(), $this->imageHelper->init($product, 'rss_thumbnail')->getUrl(), $product->getDescription(), $product->getAllowedPriceInRss() ? $this->renderPriceHtml($product) : '');
$data['entries'][] = ['title' => $product->getName(), 'link' => $product->getProductUrl(), 'description' => $description];
}
return $data;
}
示例2: execute
/**
* Send Email Post Action
*
* @return \Magento\Framework\Controller\ResultInterface
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function execute()
{
/** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
if (!$this->_formKeyValidator->validate($this->getRequest())) {
$resultRedirect->setPath('sendfriend/product/send', ['_current' => true]);
return $resultRedirect;
}
$product = $this->_initProduct();
$data = $this->getRequest()->getPostValue();
if (!$product || !$data) {
/** @var \Magento\Framework\Controller\Result\Forward $resultForward */
$resultForward = $this->resultFactory->create(ResultFactory::TYPE_FORWARD);
$resultForward->forward('noroute');
return $resultForward;
}
$categoryId = $this->getRequest()->getParam('cat_id', null);
if ($categoryId) {
try {
$category = $this->categoryRepository->get($categoryId);
} catch (NoSuchEntityException $noEntityException) {
$category = null;
}
if ($category) {
$product->setCategory($category);
$this->_coreRegistry->register('current_category', $category);
}
}
$this->sendFriend->setSender($this->getRequest()->getPost('sender'));
$this->sendFriend->setRecipients($this->getRequest()->getPost('recipients'));
$this->sendFriend->setProduct($product);
try {
$validate = $this->sendFriend->validate();
if ($validate === true) {
$this->sendFriend->send();
$this->messageManager->addSuccess(__('The link to a friend was sent.'));
$url = $product->getProductUrl();
$resultRedirect->setUrl($this->_redirect->success($url));
return $resultRedirect;
} else {
if (is_array($validate)) {
foreach ($validate as $errorMessage) {
$this->messageManager->addError($errorMessage);
}
} else {
$this->messageManager->addError(__('We found some problems with the data.'));
}
}
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addError($e->getMessage());
} catch (\Exception $e) {
$this->messageManager->addException($e, __('Some emails were not sent.'));
}
// save form data
$this->catalogSession->setSendfriendFormData($data);
$url = $this->_url->getUrl('sendfriend/product/send', ['_current' => true]);
$resultRedirect->setUrl($this->_redirect->error($url));
return $resultRedirect;
}
示例3: generate
/**
* Generate list based on categories
*
* @param int $storeId
* @param Product $product
* @param ObjectRegistry $productCategories
* @return UrlRewrite[]
*/
public function generate($storeId, Product $product, ObjectRegistry $productCategories)
{
$urls = [];
foreach ($productCategories->getList() as $category) {
$anchorCategoryIds = $category->getAnchorsAbove();
if ($anchorCategoryIds) {
foreach ($anchorCategoryIds as $anchorCategoryId) {
$anchorCategory = $this->categoryRepository->get($anchorCategoryId);
$urls[] = $this->urlRewriteFactory->create()->setEntityType(ProductUrlRewriteGenerator::ENTITY_TYPE)->setEntityId($product->getId())->setRequestPath($this->urlPathGenerator->getUrlPathWithSuffix($product, $storeId, $anchorCategory))->setTargetPath($this->urlPathGenerator->getCanonicalUrlPath($product, $anchorCategory))->setStoreId($storeId)->setMetadata(['category_id' => $anchorCategory->getId()]);
}
}
}
return $urls;
}
示例4: getTreeArray
/**
* Get categories tree as recursive array
*
* @param int $parentId
* @param bool $asJson
* @param int $recursionLevel
* @return array
*/
public function getTreeArray($parentId = null, $asJson = false, $recursionLevel = 3)
{
$productId = $this->_request->getParam('product');
if ($productId) {
$product = $this->_productFactory->create()->setId($productId);
$this->_allowedCategoryIds = $product->getCategoryIds();
unset($product);
}
$result = [];
if ($parentId) {
try {
$category = $this->categoryRepository->get($parentId);
} catch (NoSuchEntityException $e) {
$category = null;
}
if ($category) {
$tree = $this->_getNodesArray($this->getNode($category, $recursionLevel));
if (!empty($tree) && !empty($tree['children'])) {
$result = $tree['children'];
}
}
} else {
$result = $this->_getNodesArray($this->getRoot(null, $recursionLevel));
}
if ($asJson) {
return $this->_jsonEncoder->encode($result);
}
$this->_allowedCategoryIds = [];
return $result;
}
示例5: initProduct
/**
* Initialize and check product
*
* @return \Magento\Catalog\Model\Product|bool
*/
protected function initProduct()
{
$this->_eventManager->dispatch('review_controller_product_init_before', ['controller_action' => $this]);
$categoryId = (int)$this->getRequest()->getParam('category', false);
$productId = (int)$this->getRequest()->getParam('id');
$product = $this->loadProduct($productId);
if (!$product) {
return false;
}
if ($categoryId) {
$category = $this->categoryRepository->get($categoryId);
$this->coreRegistry->register('current_category', $category);
}
try {
$this->_eventManager->dispatch('review_controller_product_init', ['product' => $product]);
$this->_eventManager->dispatch(
'review_controller_product_init_after',
['product' => $product, 'controller_action' => $this]
);
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->logger->critical($e);
return false;
}
return $product;
}
示例6: convertAttribute
/**
* Set current attribute to entry (for specified product)
*
* @param \Magento\Catalog\Model\Product $product
* @param \Magento\Framework\Gdata\Gshopping\Entry $entry
* @return \Magento\Framework\Gdata\Gshopping\Entry
*/
public function convertAttribute($product, $entry)
{
$productCategories = $product->getCategoryIds();
// TODO: set Default value for product_type attribute if product isn't assigned for any category
$value = 'Shop';
if (!empty($productCategories)) {
$category = $this->categoryRepository->get(array_shift($productCategories));
$breadcrumbs = [];
foreach ($category->getParentCategories() as $cat) {
$breadcrumbs[] = $cat->getName();
}
$value = implode(' > ', $breadcrumbs);
}
$this->_setAttribute($entry, 'product_type', self::ATTRIBUTE_TYPE_TEXT, $value);
return $entry;
}
示例7: getAssignedProducts
/**
* {@inheritdoc}
*/
public function getAssignedProducts($categoryId)
{
$category = $this->categoryRepository->get($categoryId);
$productsPosition = $category->getProductsPosition();
/** @var \Magento\Framework\Data\Collection\Db $products */
$products = $category->getProductCollection();
/** @var \Magento\Catalog\Api\Data\CategoryProductLinkInterface[] $links */
$links = [];
/** @var \Magento\Catalog\Model\Product $product */
foreach ($products->getItems() as $productId => $product) {
/** @var \Magento\Catalog\Api\Data\CategoryProductLinkInterface $link */
$link = $this->productLinkFactory->create();
$link->setSku($product->getSku())->setPosition($productsPosition[$productId])->setCategoryId($category->getId());
$links[] = $link;
}
return $links;
}
示例8: getAssignedProducts
/**
* {@inheritdoc}
*/
public function getAssignedProducts($categoryId)
{
$category = $this->categoryRepository->get($categoryId);
/** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $products */
$products = $category->getProductCollection();
$products->addFieldToSelect('position');
/** @var \Magento\Catalog\Api\Data\CategoryProductLinkInterface[] $links */
$links = [];
/** @var \Magento\Catalog\Model\Product $product */
foreach ($products->getItems() as $product) {
/** @var \Magento\Catalog\Api\Data\CategoryProductLinkInterface $link */
$link = $this->productLinkFactory->create();
$link->setSku($product->getSku())->setPosition($product->getData('cat_index_position'))->setCategoryId($category->getId());
$links[] = $link;
}
return $links;
}
示例9: setCategoryLandingPage
/**
* @param string $blockId
* @param string $categoryId
* @return void
*/
protected function setCategoryLandingPage($blockId, $categoryId)
{
$categoryCms = ['landing_page' => $blockId, 'display_mode' => 'PRODUCTS_AND_PAGE'];
if (!empty($categoryId)) {
$category = $this->categoryRepository->get($categoryId);
$category->setData($categoryCms);
$this->categoryRepository->save($categoryId);
}
}
示例10: getUrlPath
/**
* Build category URL path
*
* @param \Magento\Catalog\Api\Data\CategoryInterface|\Magento\Framework\Model\AbstractModel $category
* @return string
*/
public function getUrlPath($category)
{
if ($category->getParentId() == Category::TREE_ROOT_ID) {
return '';
}
$path = $category->getUrlPath();
if ($path !== null && !$category->dataHasChangedFor('url_key') && !$category->dataHasChangedFor('parent_id')) {
return $path;
}
$path = $category->getUrlKey();
if ($path === false) {
return $category->getUrlPath();
}
if ($this->isNeedToGenerateUrlPathForParent($category)) {
$parentPath = $this->getUrlPath($this->categoryRepository->get($category->getParentId()));
$path = $parentPath === '' ? $path : $parentPath . '/' . $path;
}
return $path;
}
示例11: initProduct
/**
* Inits product to be used for product controller actions and layouts
* $params can have following data:
* 'category_id' - id of category to check and append to product as current.
* If empty (except FALSE) - will be guessed (e.g. from last visited) to load as current.
*
* @param int $productId
* @param \Magento\Framework\App\Action\Action $controller
* @param \Magento\Framework\DataObject $params
*
* @return false|ModelProduct
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function initProduct($productId, $controller, $params = null)
{
// Prepare data for routine
if (!$params) {
$params = new \Magento\Framework\DataObject();
}
// Init and load product
$this->_eventManager->dispatch('catalog_controller_product_init_before', ['controller_action' => $controller, 'params' => $params]);
if (!$productId) {
return false;
}
try {
$product = $this->productRepository->getById($productId, false, $this->_storeManager->getStore()->getId());
} catch (NoSuchEntityException $e) {
return false;
}
if (!$this->canShow($product)) {
return false;
}
if (!in_array($this->_storeManager->getStore()->getWebsiteId(), $product->getWebsiteIds())) {
return false;
}
// Load product current category
$categoryId = $params->getCategoryId();
if (!$categoryId && $categoryId !== false) {
$lastId = $this->_catalogSession->getLastVisitedCategoryId();
if ($product->canBeShowInCategory($lastId)) {
$categoryId = $lastId;
}
} elseif (!$product->canBeShowInCategory($categoryId)) {
$categoryId = null;
}
if ($categoryId) {
try {
$category = $this->categoryRepository->get($categoryId);
} catch (NoSuchEntityException $e) {
$category = null;
}
if ($category) {
$product->setCategory($category);
$this->_coreRegistry->register('current_category', $category);
}
}
// Register current data and dispatch final events
$this->_coreRegistry->register('current_product', $product);
$this->_coreRegistry->register('product', $product);
try {
$this->_eventManager->dispatch('catalog_controller_product_init_after', ['product' => $product, 'controller_action' => $controller]);
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->_logger->critical($e);
return false;
}
return $product;
}
示例12: reindex
/**
* Refresh entities index
*
* @param int[] $entityIds
* @param bool $useTempTable
* @return Rows
*/
public function reindex(array $entityIds = [], $useTempTable = false)
{
$stores = $this->storeManager->getStores();
/* @var $store \Magento\Store\Model\Store */
foreach ($stores as $store) {
$tableName = $this->getTableNameByStore($store, $useTempTable);
if (!$this->getWriteAdapter()->isTableExists($tableName)) {
continue;
}
/** @TODO Do something with chunks */
$categoriesIdsChunks = array_chunk($entityIds, 500);
foreach ($categoriesIdsChunks as $categoriesIdsChunk) {
$categoriesIdsChunk = $this->filterIdsByStore($categoriesIdsChunk, $store);
$attributesData = $this->getAttributeValues($categoriesIdsChunk, $store->getId());
$data = [];
foreach ($categoriesIdsChunk as $categoryId) {
if (!isset($attributesData[$categoryId])) {
continue;
}
try {
$category = $this->categoryRepository->get($categoryId);
} catch (NoSuchEntityException $e) {
continue;
}
$data[] = $this->prepareValuesToInsert(array_merge($category->getData(), $attributesData[$categoryId], ['store_id' => $store->getId()]));
}
foreach ($data as $row) {
$updateFields = [];
foreach (array_keys($row) as $key) {
$updateFields[$key] = $key;
}
$this->getWriteAdapter()->insertOnDuplicate($tableName, $row, $updateFields);
}
}
$this->deleteNonStoreCategories($store, $useTempTable);
}
return $this;
}
示例13: execute
/**
* Delete category action
*
* @return \Magento\Backend\Model\View\Result\Redirect
*/
public function execute()
{
/** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
$categoryId = (int) $this->getRequest()->getParam('id');
$parentId = null;
if ($categoryId) {
try {
$category = $this->categoryRepository->get($categoryId);
$parentId = $category->getParentId();
$this->_eventManager->dispatch('catalog_controller_category_delete', ['category' => $category]);
$this->_auth->getAuthStorage()->setDeletedPath($category->getPath());
$this->categoryRepository->delete($category);
$this->messageManager->addSuccess(__('You deleted the category.'));
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addError($e->getMessage());
return $resultRedirect->setPath('catalog/*/edit', ['_current' => true]);
} catch (\Exception $e) {
$this->messageManager->addError(__('Something went wrong while trying to delete the category.'));
return $resultRedirect->setPath('catalog/*/edit', ['_current' => true]);
}
}
return $resultRedirect->setPath('catalog/*/', ['_current' => true, 'id' => $parentId]);
}
示例14: setCurrentCategory
/**
* Change current category object
*
* @param mixed $category
* @return \Magento\Catalog\Model\Layer
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function setCurrentCategory($category)
{
if (is_numeric($category)) {
try {
$category = $this->categoryRepository->get($category);
} catch (NoSuchEntityException $e) {
throw new \Magento\Framework\Exception\LocalizedException(__('Please correct the category.'), $e);
}
} elseif ($category instanceof \Magento\Catalog\Model\Category) {
if (!$category->getId()) {
throw new \Magento\Framework\Exception\LocalizedException(__('Please correct the category.'));
}
} else {
throw new \Magento\Framework\Exception\LocalizedException(__('Must be category model instance or its id.'));
}
if ($category->getId() != $this->getCurrentCategory()->getId()) {
$this->setData('current_category', $category);
}
return $this;
}
示例15: canShow
/**
* Check if a category can be shown
*
* @param ModelCategory|int $category
* @return bool
*/
public function canShow($category)
{
if (is_int($category)) {
try {
$category = $this->categoryRepository->get($category);
} catch (NoSuchEntityException $e) {
return false;
}
} else {
if (!$category->getId()) {
return false;
}
}
if (!$category->getIsActive()) {
return false;
}
if (!$category->isInRootCategoryList()) {
return false;
}
return true;
}