0
<?php
namespace Magento\FetchProductsFromCategory\Model;

use \Magento\FetchProductsFromCategory\Api\ProductInterface;
use \Magento\Framework\Exception\NoSuchEntityException;

class Product implements ProductInterface
{
    protected $_categoryFactory;
    protected $_category;
    protected $_categoryRepository;
    protected $_storeManager;
    protected $jsonHelper;

    public function __construct(
        \Magento\Catalog\Model\CategoryFactory $categoryFactory,
        \Magento\Catalog\Helper\Category $category,
        \Magento\Catalog\Model\CategoryRepository $categoryRepository,
        \Magento\Framework\Json\Helper\Data $jsonHelper,
        \Magento\Store\Model\StoreManagerInterface $storeManager
    ){
        $this->_categoryFactory = $categoryFactory;
        $this->_category = $category;
        $this->_categoryRepository = $categoryRepository;
        $this->jsonHelper = $jsonHelper;
        $this->_storeManager = $storeManager;
    }
    /**
     * POST for test api
     * @param string $slug
     * @param string $sort_by
     * @param string $sort_order
     * @param int $page_size
     * @param int $current_page
     * @param string $in_stock
     * @return string
     */
    public function getProducts($slug,$sort_by='created_at',$sort_order='desc',$page_size=12,$current_page=1,$in_stock=1)
    {
        $json = $this->getJsonArrayProductFromCategory($slug,$sort_by,$sort_order,$page_size,$current_page,$in_stock);
        header('Content-Type: application/json');
        header("Access-Control-Allow-Origin: *");
        echo $json;
        exit(0);
    }
    public function sort_ascending($item1,$item2)//sort items in ascending order
    {
        return($item1['extension_attributes']['final_price']<=$item2['extension_attributes']['final_price'])?-1:1;
    }
    public function sort_descending($item1,$item2)//sort items in descending order
    {
        return($item1['extension_attributes']['final_price']>=$item2['extension_attributes']['final_price'])?-1:1;
    }

    public function getJsonArrayProductFromCategory($slug,$sort_by='created_at',$sort_order='desc',$page_size=12,$current_page=1,$in_stock=1){
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
        $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
        $connection = $resource->getConnection();
        $categoryFactory = $objectManager->create('Magento\Catalog\Model\CategoryFactory');
        $productFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');


        $slugList = explode(",", $slug);

        $json= array();
        $i=0;
        $totals = 0;

        $categoryList = [];

        foreach ($slugList as $slug) {
            $category =  $categoryFactory->create()->loadByAttribute('url_key',$slug);
            if ($category == FALSE){
                throw new NoSuchEntityException(__("No category with slug '".$slug."' found"));
                return;
            }else{
                $categoryId = $category->getId();
            }

            $child_category_list = [];

            array_push($categoryList, $categoryId);
            $subcategories = $category->getChildrenCategories();
            foreach ($subcategories as $subcategory) {
                array_push($categoryList, $subcategory->getId());
                $child_category["category_name"] = $subcategory->getName();
                $subcategory_slug = (preg_replace("/[^a-zA-Z0-9]+/", " ", $child_category["category_name"]));
                $subcategory_slug = strtolower(trim($subcategory_slug));
                $subcategory_slug = str_replace(' ', '-', $subcategory_slug);
                $child_category["category_slug"] = $subcategory_slug;
                array_push($child_category_list, $child_category);
                }
        }

        if($sort_by=='price')
        {
            $categoryProducts = $productFactory->create()
                            ->addAttributeToSelect('*')
                            ->addCategoriesFilter(array('in' => $categoryList))
                            ->addAttributeToFilter('status',1)
                            ->addAttributeToFilter('visibility',4)
                            ->joinField(
                                'is_in_stock', 'cataloginventory_stock_item', 'is_in_stock', 'product_id=entity_id', '{{table}}.stock_id=1', 'left'
                                )
                            ->addAttributeToFilter('is_in_stock', $in_stock)
                            ->setPageSize($page_size)
                            ->setCurPage($current_page)
                            ->load();


        }
        else
        {
            $categoryProducts = $productFactory->create()
                            ->addAttributeToSelect('*')
                            ->addCategoriesFilter(array('in' => $categoryList))
                            ->addAttributeToFilter('status',1)
                            ->addAttributeToFilter('visibility',4)
                            ->joinField('is_in_stock', 'cataloginventory_stock_item', 'is_in_stock', 'product_id=entity_id', 'is_in_stock='.$in_stock)
                            ->addAttributeToSort($sort_by, $sort_order)
                            ->setPageSize($page_size)
                            ->setCurPage($current_page)
                            ->load();
        }   

        foreach ($categoryProducts as $product)
        {   
            $productCategories = $product->getCategoryIds();
            $category_names = array();

            foreach($productCategories as $productCategoryId){
                $productCategory = $objectManager->create('Magento\Catalog\Model\Category')->load($productCategoryId);
                $parentCategory = $productCategory->getParentCategory();
                array_push($category_names, $productCategory->getName());
                if ($parentCategory->getData('show_on_megamenu') == '1'){
                        if($parentCategory->getName() == "Collections" || $parentCategory->getName() == "Gifting" || $parentCategory->getName() == "Sales" || $parentCategory->getName() == "Sale" || $parentCategory->getName() == "Diwali" || $parentCategory->getName() == "Combo" || $parentCategory->getName() == "Combos"){
                            continue;
                    }
                    else{
                        $productData['category_id'] = $parentCategory->getId();
                        $productData['category_name'] = $parentCategory->getName();
                        break;
                    }
                }elseif ($productCategory->getData('show_on_megamenu') == '1') {
                    $productData['category_id'] = $parentCategory->getId();
                    $productData['category_name'] = $productCategory->getName();
                    break;
                }else{
                    $productData['category_id'] = $parentCategory->getId();
                    $productData['category_name'] = $productCategory->getName();
                }
            }
            $productData['name'] = $product->getName();
            $productData['id'] = $product->getId();
            $productData['sku'] = $product->getSku();
            $productData['image'] = $product->getImage();
            if($product->getTypeId()=="configurable"){
                $children = $product->getTypeInstance()->getUsedProducts($product);
                foreach ($children as $child){
                    $extensionAttributes['price'] = (int)$child->getPrice();
                    $extensionAttributes['final_price'] = (int)$child->getFinalPrice();
                    break;
                }
            } 
            else {
                $extensionAttributes['price'] = (int)$product->getPrice();
                $extensionAttributes['final_price'] = (int)$product->getFinalPrice();
            }

            if($product->getPreOrder()== 0){
                $extensionAttributes['pre_order'] = "No";
            } 
            else {
                $extensionAttributes['pre_order'] = "Yes";
            }


            if ($extensionAttributes['price'] == $extensionAttributes['final_price']){
                $extensionAttributes['on_sale'] = "No";
            }else{
                $extensionAttributes['on_sale'] = "Yes";
            }
            $product_slug = (preg_replace("/[^a-zA-Z0-9]+/", " ", $product->getName()));
            $product_slug = strtolower(trim($product_slug));
            $product_slug = str_replace(' ', '-', $product_slug);
            $productData['slug'] = $product_slug;
            if ($product->getTypeId()=='simple'){
                $StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
                $productQtyBySku = $StockState->getStockQty($product->getId());
                if ($productQtyBySku == 0){
                    $qty = "Out of Stock";                   
                    $almost_gone = false;
                }
                elseif($productQtyBySku > 15){
                    $qty = "In-Stock";
                    $almost_gone = false;
                }else{
                    $qty = "In-Stock";
                    $almost_gone = true;
                }
            }
            else{
                if (!$product->isSaleable()){
                    $qty = "Out of Stock";
                    $almost_gone = false;
                }
                else{
                    $qty = "In-Stock";
                    $almost_gone = false;                    
                }
            }
            if (round((time() - strtotime($product->getCreatedAt())) / (60 * 60 * 24)) > 15){
                $new_launch = false;
            }else{
                $new_launch = true;
            }

            if ($product->getSpecialOffer() == 1){
                $extensionAttributes["custom_tag_text"] ="Special Offer";
                $extensionAttributes["custom_tag_color"] = "#e3b627";
            }elseif(($product->getSpecialOffer() == 0) && $new_launch){
                $extensionAttributes["custom_tag_text"] = "New Launch";
                $extensionAttributes["custom_tag_color"] = "#00bfa5";
            }elseif(($product->getSpecialOffer() == 0) && (!$new_launch) && ($almost_gone)){
                $extensionAttributes["custom_tag_text"] = "Almost Gone";
                $extensionAttributes["custom_tag_color"] = "#e3b627";
            }elseif(($product->getSpecialOffer() == 0) && (!$new_launch) && (!$almost_gone) && ($product->getBestSeller() == 1)){
                $extensionAttributes["custom_tag_text"] = "Bestseller";
                $extensionAttributes["custom_tag_color"] = "#d23762";
            }elseif(($product->getSpecialOffer() == 0) && (!$new_launch) && (!$almost_gone) && ($product->getBestSeller() == 0) && ($product->getBackInStock() == 1)){
                $extensionAttributes["custom_tag_text"] = "Back in Stock";
                $extensionAttributes["custom_tag_color"] = "#00bfa5";
            }else{
                $extensionAttributes["custom_tag_text"] = "";
                $extensionAttributes["custom_tag_color"] = "";
            }
            $extensionAttributes['qty'] = $qty;
            $productData['extension_attributes'] = $extensionAttributes;
            $json[$i]=$productData;



            $i++;

        }
        //using usort to sort array by final_price
        if($sort_by=='price'&&$sort_order=='asc')
            usort($json,array($this, "sort_ascending"));
        else if($sort_by=='price'&&$sort_order=='desc')
            usort($json,array($this, "sort_descending"));

        $totals = $totals + sizeof($productFactory->create()
                            ->addAttributeToSelect('*')
                            ->addCategoriesFilter(array('in' => $categoryList))
                            ->addAttributeToFilter('status',1)
                            ->addAttributeToFilter('visibility',4)
                            );

        $category_image = $category->getImageUrl();
        $category_description = $category->getDescription();

        $items['items'] = $json;
        $items['category_image'] = $category_image;
        $items['category_name'] =  $category->getName();
        $items['category_description'] = $category_description;
        $items['child_categories'] = $child_category_list;
        $items['in_stock_count'] = sizeof($productFactory->create()
                                                        ->addAttributeToSelect('*')
                                                        ->addCategoriesFilter(array('in' => $categoryList))
                                                        ->addAttributeToFilter('status',1)
                                                        ->addAttributeToFilter('visibility',4)
                                                        ->joinField('is_in_stock', 'cataloginventory_stock_item', 'is_in_stock', 'product_id=entity_id', 'is_in_stock=1'));
        $items['total_count'] = $totals;

        return json_encode($items); 
    }

}

This is the API I am using to fetch products from category.I want to convert it to elasticsearch. Please help me someone with the code.

Your Answer

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

Browse other questions tagged or ask your own question.