0

Fatal error: Uncaught Error: Function name must be a string in /Applications/MAMP/htdocs/magentoshop/app/code/Magestore/couponoverride/Model/CouponManagement.php:74

Stack trace:

#0 [internal function]: Magestore\couponoverride\Model\CouponManagement->set(53694, 'special')
#1 /Applications/MAMP/htdocs/magentoshop/vendor/magento/module-webapi/Controller/Rest.php(330):
call_user_func_array(Array, Array)
#2 /Applications/MAMP/htdocs/magentoshop/vendor/magento/module-webapi/Controller/Rest.php(239):
Magento\Webapi\Controller\Rest->processApiRequest()
#3 /Applications/MAMP/htdocs/magentoshop/vendor/magento/framework/Interception/Interceptor.php(58):
Magento\Webapi\Controller\Rest->dispatch(Object(Magento\Framework\App\Request\Http))
#4 /Applications/MAMP/htdocs/magentoshop/vendor/magento/framework/Interception/Interceptor.php(138):
Magento\Webapi\Controller\Rest\Interceptor->___callParent('dispatch', Array)
#5 /Applications/MAMP/htdocs/magentoshop/vendor/magento/framework/Interception/Interceptor.php(153):
Magento\Webapi\Contro in
<b>/Applications/MAMP/htdocs/magentoshop/app/code/Magestore/couponoverride/Model/CouponManagement.php</b> on line
<b>74</b><br />
{"messages":{"error":[{"code":500,"message":"Fatal Error: 'Uncaught Error: Function name must be a string in \/Applications\/MAMP\/htdocs\/magentoshop\/app\/code\/Magestore\/couponoverride\/Model\/CouponManagement.php:74\nStack trace:\n#0 [internal function]: Magestore\\couponoverride\\Model\\CouponManagement->set(53694, 'special')\n#1 \/Applications\/MAMP\/htdocs\/magentoshop\/vendor\/magento\/module-webapi\/Controller\/Rest.php(330): call_user_func_array(Array, Array)\n#2 \/Applications\/MAMP\/htdocs\/magentoshop\/vendor\/magento\/module-webapi\/Controller\/Rest.php(239): Magento\\Webapi\\Controller\\Rest->processApiRequest()\n#3 \/Applications\/MAMP\/htdocs\/magentoshop\/vendor\/magento\/framework\/Interception\/Interceptor.php(58): Magento\\Webapi\\Controller\\Rest->dispatch(Object(Magento\\Framework\\App\\Request\\Http))\n#4 \/Applications\/MAMP\/htdocs\/magentoshop\/vendor\/magento\/framework\/Interception\/Interceptor.php(138): Magento\\Webapi\\Controller\\Rest\\Interceptor->___callParent('dispatch', Array)\n#5 \/Applications\/MAMP\/htdocs\/magentoshop\/vendor\/magento\/framework\/Interception\/Interceptor.php(153): Magento\\Webapi\\Contro' in '\/Applications\/MAMP\/htdocs\/magentoshop\/app\/code\/Magestore\/couponoverride\/Model\/CouponManagement.php' on line 74","trace":"Trace is not available."}]}}

My app/code/Magestore/couponoverride/Model/CouponManagement.php:

<?php
/**
 *
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Magestore\couponoverride\Model;

use Magento\Framework\Exception\LocalizedException;
use Magestore\couponoverride\Api\CouponManagementInterface;
use Magento\Framework\Exception\CouldNotDeleteException;
use Magento\Framework\Exception\CouldNotSaveException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\SalesRule\Model\Rule\Action\Discount\AbstractDiscount;
/**
 * Coupon management object.
 */
class CouponManagement implements CouponManagementInterface
{
    /**
     * Quote repository.
     *
     * @var \Magento\Quote\Api\CartRepositoryInterface //\Magento\SalesRule\Model\Coupon
     */
    protected $quoteRepository;
    protected $coupon;
    protected $saleRule; 

    /**
     * Constructs a coupon read service object.
     *
     * @param \Magento\Quote\Api\CartRepositoryInterface $quoteRepository Quote repository.
     */
    public function __construct(
        \Magento\Quote\Api\CartRepositoryInterface $quoteRepository,
        \Magento\SalesRule\Model\Coupon $coupon,

        \Magento\SalesRule\Model\Rule $saleRule,
        \Magento\Quote\Model\Quote\Address\Total $total
    ) {
        $this->quoteRepository = $quoteRepository;
        $this->coupon=$coupon;
        $this->saleRule = $saleRule;

      }

    // /**
    //  * @inheritDoc
    //  */
    // public function get($cartId)
    // {
    //     /** @var  \Magento\Quote\Model\Quote $quote */
    //     $quote = $this->quoteRepository->getActive($cartId);
    //    // echo "tmkoc";
    //     return $quote->getCouponCode();
    // }

   /**
     * Adds a coupon by code to a specified cart.
     *
     * @param int $cartId The cart ID.
     * @param string $couponCode The coupon code data.
     * @return bool
     * @throws \Magento\Framework\Exception\NoSuchEntityException The specified cart does not exist.
     * @throws \Magento\Framework\Exception\CouldNotSaveException The specified coupon could not be added.
     */
    public function set( $cartId, $couponCode)
    {
        /** @var  \Magento\Quote\Model\Quote $quote */
        $couponCode=trim($couponCode);
        $quote = $this->quoteRepository->getActive($cartId);

    $items = $quote()->getAllItems();

         if (!$quote->getItemsCount()) {
            throw new NoSuchEntityException(__('The "%1" Cart doesn\'t contain products.', $cartId));
        }
        if (!$quote->getStoreId()) {
            throw new NoSuchEntityException(__('Cart isn\'t assigned to correct store'));
        }
      //  $quote->getShippingAddress()->setCollectShippingRates(true);

        $subtotalInclTax = 0;

        try {

              foreach($items as $item) {

                    $subtotalInclTax += $item->getRowTotalInclTax();

                      $qty=$item->getQty();
                       $price=$item->getPrice();
                          $total+=$price*$qty;
                $item->getShippingAddress()->setCollectShippingRates(true);
                      if($item->getPrice()==$item->getFinalPrice())
                      {
                        //$item->setcouponamount($couponCode);


                        $discount+=setcouponamount($couponCode,$item,$qty);
                        if($discount== -1)
                        {
                           $quote->setCouponCode($couponCode);
                           $this->quoteRepository->save($quote->collectTotals());
                          break;
                        }
                      }  

            }
            if($amount!=-1)
            {
              $total2=$total-$discount;
              $quote->setSubtotal($total);
              $quote->setBaseSubtotal($total);
              $quote->setDiscountAmount($discount);
              $quote->setBaseDiscountAmount($discount);
              $quote->setSubtotalWithDiscount($total2);
              $quote->setBaseSubtotalWithDiscount($total2);
              $quote->setSubtotalInclTax($subtotalInclTax);
              $quote->setGrandTotal($subtotalInclTax-$discount);
              $quote->setBaseGrandTotal($subtotalInclTax-$discount);
            //  $quote->setcoupon
              $quote->save();



          }
          echo $total;
          echo $amount;
          echo $total2;

         //   $quote->setCouponCode($couponCode);
           // $this->quoteRepository->save($quote->collectTotals());
        } catch (LocalizedException $e) {
            throw new CouldNotSaveException(__('The coupon code couldn\'t be applied: ' .$e->getMessage()), $e);
        } catch (\Exception $e) {
            throw new CouldNotSaveException(
                __("The coupon code couldn't be applied. Verify the coupon code and try again."),
                $e
            );
        }
        //if ($quote->getCouponCode() != $couponCode) {
          //  throw new NoSuchEntityException(__("The coupon code isn't valid. Verify the code and try again."));
        //}
        exit(0);
        return true;
    }
    // *
    // *inhertdoc
    // *
     public function setcouponamount($couponCode,$item,$qty)
     {
        $ruleId =   $this->coupon->loadByCode($couponCode)->getRuleId();
        $rule = $this->saleRule->load($ruleId);
        //return $rule->getDiscountAmount();
      //  $amount=$rule->(int)getDiscountAmount();
       // return $amount;
        if($rule->getSimpleAction()=="by_percent")
        {
          //$amount=$rule->getDiscountAmount();
            $rulePercent = min(100, $rule->getDiscountAmount());
               $discountData = $this->discountFactory->create();

        $itemPrice = $this->validator->getItemPrice($item);
        $baseItemPrice = $this->validator->getItemBasePrice($item);
        $itemOriginalPrice = $this->validator->getItemOriginalPrice($item);
        $baseItemOriginalPrice = $this->validator->getItemBaseOriginalPrice($item);

        $_rulePct = $rulePercent / 100;

        $taxAmount = $itemPrice - ($itemPrice / ((100 + $item->getTaxPercent())/100));
        $perItemTaxAmount = $taxAmount;
        $itemPriceBeforeTax = $itemPrice - $perItemTaxAmount;
        $discountData->setAmount(($qty * $itemPriceBeforeTax - $item->getDiscountAmount()) * $_rulePct);
        $discountData->setBaseAmount(($qty * ($baseItemPrice - $perItemTaxAmount) - $item->getBaseDiscountAmount()) * $_rulePct);
        $discountData->setOriginalAmount(($qty * ($itemOriginalPrice - $perItemTaxAmount) - $item->getDiscountAmount()) * $_rulePct);
        $discountData->setBaseOriginalAmount(
            ($qty * $baseItemOriginalPrice - $item->getBaseDiscountAmount()) * $_rulePct
        );

        if (!$rule->getDiscountQty() || $rule->getDiscountQty() > $qty) {
            $discountPercent = min(100, $item->getDiscountPercent() + $rulePercent);
            $item->setDiscountPercent($discountPercent);
        }

        return $discountData;

        }
        elseif($rule->getSimpleAction()=="by_fixed")
        {
             $discountData = $this->discountFactory->create();

        $quoteAmount = $this->priceCurrency->convert($rule->getDiscountAmount(), $item->getQuote()->getStore());
        $discountData->setAmount($qty * $quoteAmount);
        $discountData->setBaseAmount($qty * $rule->getDiscountAmount());

        return $discountData;
        }
        elseif($rule->getSimpleAction()=="cart_fixed")
        {
          return -1;
        }
     }


    /**
     * @inheritDoc
     */
    // public function remove($cartId)
    // {
    //     /** @var  \Magento\Quote\Model\Quote $quote */
    //     $quote = $this->quoteRepository->getActive($cartId);
    //     if (!$quote->getItemsCount()) {
    //         throw new NoSuchEntityException(__('The "%1" Cart doesn\'t contain products.', $cartId));
    //     }
    //     $quote->getShippingAddress()->setCollectShippingRates(true);
    //     try {
    //         $quote->setCouponCode('');
    //         $this->quoteRepository->save($quote->collectTotals());
    //     } catch (\Exception $e) {
    //         throw new CouldNotDeleteException(
    //             __("The coupon code couldn't be deleted. Verify the coupon code and try again.")
    //         );
    //     }
    //     if ($quote->getCouponCode() != '') {
    //         throw new CouldNotDeleteException(
    //             __("The coupon code couldn't be deleted. Verify the coupon code and try again.")
    //         );
    //     }
    //     return true;
    // }
}


***My interface is:***
<?php
/**
 *
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Magestore\couponoverride\Api;

/**
 * Coupon Management service interface.
 * @api
 * @since 100.0.2
 */
interface CouponManagementInterface
{
   /**
     * Adds a coupon by code to a specified cart.
     *
     * @param int $cartId The cart ID.
     * @param string $couponCode The coupon code data.
     * @return bool
     * @throws \Magento\Framework\Exception\NoSuchEntityException The specified cart does not exist.
     * @throws \Magento\Framework\Exception\CouldNotSaveException The specified coupon could not be added.
     */
    public function set($cartId, $couponCode);
}
1

Check this code in line 74:

$items = $quote()->getAllItems();

Change it to

$items = $quote->getAllItems();

Basically if you write $quote() it means you call a method, where the method name is saved in $quote variable. Because the $quote variable store an object, not a string, then the error comes.

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.