1

i want to override CategoryProcessor.php namespace Magento\CatalogImportExport\Model\Import\Product;

I have created my custom module but not override.

my registration file

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magenticians_Showcategory',
    __DIR__
);

composer.json

{
    "name": "Magenticians/Showcategory",
    "description": "remove category on menu when import the product csv",
    "require": {
        "php": "~5.5.0|~5.6.0|~7.0.0"
    },
    "type": "magento2-module",
    "version": "1.0.0",
    "license": [
        "Commercial"
    ],
    "autoload": {
        "files": [ "registration.php" ],
        "psr-4": {
            "Magenticians\\Showcategory\\": ""
        }
    }
}

module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Magenticians_Showcategory" setup_version="1.0.0">
    </module>
</config>

di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\CatalogImportExport\Model\Import\Product\CategoryProcessor" type="Magenticians\Showcategory\Model\Import\Product\CategoryProcessor" />
</config>

CategoryProcessor.php overrided . "just change true to false in include in menue"

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
 namespace Magenticians\Showcategory\Model\Import\Product;

/**
 * Class CategoryProcessor
 *
 * @api
 * @since 100.0.2
 */
class CategoryProcessor
{
    /**
     * Delimiter in category path.
     */
    const DELIMITER_CATEGORY = '/';

    /**
     * @var \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory
     */
    protected $categoryColFactory;

    /**
     * Categories text-path to ID hash.
     *
     * @var array
     */
    protected $categories = [];

    /**
     * Categories id to object cache.
     *
     * @var array
     */
    protected $categoriesCache = [];

    /**
     * Instance of catalog category factory.
     *
     * @var \Magento\Catalog\Model\CategoryFactory
     */
    protected $categoryFactory;

    /**
     * Failed categories during creation
     *
     * @var array
     * @since 100.1.0
     */
    protected $failedCategories = [];

    /**
     * @param \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryColFactory
     * @param \Magento\Catalog\Model\CategoryFactory $categoryFactory
     */
    public function __construct(
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryColFactory,
        \Magento\Catalog\Model\CategoryFactory $categoryFactory
    ) {
        $this->categoryColFactory = $categoryColFactory;
        $this->categoryFactory = $categoryFactory;
        $this->initCategories();
    }

    /**
     * @return $this
     */
    protected function initCategories()
    {
        if (empty($this->categories)) {
            $collection = $this->categoryColFactory->create();
            $collection->addAttributeToSelect('name')
                ->addAttributeToSelect('url_key')
                ->addAttributeToSelect('url_path');
            /* @var $collection \Magento\Catalog\Model\ResourceModel\Category\Collection */
            foreach ($collection as $category) {
                $structure = explode(self::DELIMITER_CATEGORY, $category->getPath());
                $pathSize = count($structure);

                $this->categoriesCache[$category->getId()] = $category;
                if ($pathSize > 1) {
                    $path = [];
                    for ($i = 1; $i < $pathSize; $i++) {
                        $path[] = $collection->getItemById((int)$structure[$i])->getName();
                    }
                    /** @var string $index */
                    $index = $this->standardizeString(
                        implode(self::DELIMITER_CATEGORY, $path)
                    );
                    $this->categories[$index] = $category->getId();
                }
            }
        }
        return $this;
    }

    /**
     * Creates a category.
     *
     * @param string $name
     * @param int $parentId
     *
     * @return int
     */
    protected function createCategory($name, $parentId)
    {
        /** @var \Magento\Catalog\Model\Category $category */
        $category = $this->categoryFactory->create();
        if (!($parentCategory = $this->getCategoryById($parentId))) {
            $parentCategory = $this->categoryFactory->create()->load($parentId);
        }
        $category->setPath($parentCategory->getPath());
        $category->setParentId($parentId);
        $category->setName($name);
        $category->setIsActive(true);
        $category->setIncludeInMenu(false);
        $category->setAttributeSetId($category->getDefaultAttributeSetId());
        try {
            $category->save();
            $this->categoriesCache[$category->getId()] = $category;
        } catch (\Exception $e) {
            $this->addFailedCategory($category, $e);
        }

        return $category->getId();
    }

    /**
     * Returns ID of category by string path creating nonexistent ones.
     *
     * @param string $categoryPath
     *
     * @return int
     */
    protected function upsertCategory($categoryPath)
    {
        /** @var string $index */
        $index = $this->standardizeString($categoryPath);

        if (!isset($this->categories[$index])) {
            $pathParts = explode(self::DELIMITER_CATEGORY, $categoryPath);
            $parentId = \Magento\Catalog\Model\Category::TREE_ROOT_ID;
            $path = '';

            foreach ($pathParts as $pathPart) {
                $path .= $this->standardizeString($pathPart);
                if (!isset($this->categories[$path])) {
                    $this->categories[$path] = $this->createCategory($pathPart, $parentId);
                }
                $parentId = $this->categories[$path];
                $path .= self::DELIMITER_CATEGORY;
            }
        }

        return $this->categories[$index];
    }

    /**
     * Returns IDs of categories by string path creating nonexistent ones.
     *
     * @param string $categoriesString
     * @param string $categoriesSeparator
     *
     * @return array
     */
    public function upsertCategories($categoriesString, $categoriesSeparator)
    {
        $categoriesIds = [];
        $categories = explode($categoriesSeparator, $categoriesString);

        foreach ($categories as $category) {
            try {
                $categoriesIds[] = $this->upsertCategory($category);
            } catch (\Magento\Framework\Exception\AlreadyExistsException $e) {
                $this->addFailedCategory($category, $e);
            }
        }

        return $categoriesIds;
    }

    /**
     * Add failed category
     *
     * @param string $category
     * @param \Magento\Framework\Exception\AlreadyExistsException $exception
     *
     * @return $this
     */
    private function addFailedCategory($category, $exception)
    {
        $this->failedCategories[] =
            [
                'category' => $category,
                'exception' => $exception,
            ];
        return $this;
    }

    /**
     * Return failed categories
     *
     * @return array
     * @since 100.1.0
     */
    public function getFailedCategories()
    {
        return $this->failedCategories;
    }

    /**
     * Resets failed categories' array
     *
     * @return $this
     * @since 100.2.0
     */
    public function clearFailedCategories()
    {
        $this->failedCategories = [];
        return $this;
    }

    /**
     * Get category by Id
     *
     * @param int $categoryId
     *
     * @return \Magento\Catalog\Model\Category|null
     */
    public function getCategoryById($categoryId)
    {
        return isset($this->categoriesCache[$categoryId]) ? $this->categoriesCache[$categoryId] : null;
    }

    /**
     * Standardize a string.
     * For now it performs only a lowercase action, this method is here to include more complex checks in the future
     * if needed.
     *
     * @param string $string
     * @return string
     */
    private function standardizeString($string)
    {
        return mb_strtolower($string);
    }
}

but can't override the model. correct me where I am wrong?

  • Please share the code of Magenticians\Showcategory\Model\Import\Product\CategoryProcessor – Amit Bera Jan 4 at 13:38
  • i have update my question ,, you can see Magenticians\Showcategory\Model\Import\Product\CategoryProcessor code also. – Hafiz Arslan Jan 4 at 13:50
  • You may need to use extends Magento\CatalogImportExport\Model\Import\Product\CategoryProcessor in your class definition. It is also good to change only the required function in your override class. – Pritam Info 24 Jan 4 at 14:55
  • when i extend ,,class CategoryProcessor extends Magento\CatalogImportExport\Model\Import\Product\CategoryProcessor,,it give me an error :Fatal error: Class 'Magenticians\Showcategory\Model\Import\Product\Magento\CatalogImportExport\Model\Import\Product\CategoryProcessor' not found in /var/www/html/olympic-supply-company/app/code/Magenticians/Showcategory/Model/Import/Product/CategoryProcessor.php on line 14 – Hafiz Arslan Jan 4 at 15:09
1

we can override protected function in magento2 like this:

Extend CategoryProcessor class with \Magento\CatalogImportExport\Model\Import\Product\CategoryProcessor

like this :

class CategoryProcessor extends \Magento\CatalogImportExport\Model\Import\Product\CategoryProcessor

m just missing the \ before Magento.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.