1

app/code/Test/Shipping/etc/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">
    <type name="Magento\Shipping\Model\Shipping">
        <plugin name="shipping_test" type="Test\Shipping\Plugin\Shipping" sortOrder="1"/>
    </type>

</config>

app/code/Test/Shipping/Plugin/Shipping.php

<?php

namespace Test\Shipping\Plugin;

use Magento\Quote\Model\Quote\Address\RateRequest;
use Test\Shipping\Model\Source\Allshippingmethods;
use Test\Shipping\Helper\Data;
use Magento\Quote\Model\Quote\Address\RateCollectorInterface;

/**
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Shipping
{
    /**
     * Code of the carrier
     * @var string
     */
    protected $_code='Shipping';

    /**
     * @var \Magento\Shipping\Model\Rate\ResultFactory
     */
    protected $_rateResultFactory;

    /**
     * @var \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory
     */
    protected $_rateMethodFactory;

    /**
     * Rate result data
     *
     * @var Result
     */
    protected $_result;

    /**
     *
     * @var \Magento\Quote\Model\Quote\Address\RateCollectorInterface
     */
    protected $_rateCollector;

    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Quote\Model\Quote\Address\RateResult\ErrorFactory $rateErrorFactory,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Shipping\Model\Rate\ResultFactory $rateResultFactory,
        \Magento\Quote\Model\Quote\Address\RateResult\MethodFactory $rateMethodFactory,
        \Magento\Checkout\Model\Cart $cart,
        \Magento\Framework\App\Filesystem\DirectoryList $directory_list,
        \Magento\Framework\App\ResourceConnection $resourceConnection,
        RateCollectorInterface $rateCollector,
        \Test\Shipping\Helper\Data $helper,
        array $data = []
    ) { 
        $this->_rateResultFactory = $rateResultFactory;
        $this->_rateMethodFactory = $rateMethodFactory;
        $this->directory_list = $directory_list;
        $this->cart = $cart;
        $this->resourceConnection = $resourceConnection;
        $this->_rateCollector = $rateCollector;
        $this->helper = $helper;
    }

    /**
     * Returns array of key-value pairs of all available methods
     * @return array
     */
    public function getAllowedMethods()
    {
        $group_info=$this->helper->getAllMethods();
        $carriers=array();
        foreach ($group_info as &$carrier) {
            $carriers[$group_info['label']]=$group_info['label'];
        }
        return $carriers;
    }

    public function getResult()
    {
        if (empty($this->_result)) {
            $this->_result = $this->_rateResultFactory->create();
        }
        return $this->_result;
    }

    public function aroundCollectCarrierRates($proceed, $carrierCode, $request)
    {
        $result = $proceed();

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $customerSession = $objectManager->create('Magento\Customer\Model\Session');

        if ($customerSession->isLoggedIn()) {
            $gid = $customerSession->getCustomerGroupId();
            $group_info = $this->helper->getGroupData($gid);
            //var_dump($group_info);exit;
        }

        $result->getResult()->append($group_info);

        return $result;
    }
}
?>

Here I want var_dump($group_info) in return. Because I got all methods set in checkout/cart page.

app/code/Test/Shipping/Helper/Data.php

<?php

namespace Test\Shipping\Helper;

use Magento\Store\Model\StoreManagerInterface;
use Test\Shipping\Model\Source\Allshippingmethods;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    protected $urlInterface;

    protected $scopeConfig;

    protected $_storeManager;

    protected $_asm;

    protected $resourceConnection;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Framework\UrlInterface $urlInterface,
        StoreManagerInterface $storeManager,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfigObject,
        Allshippingmethods $Allshippingmethods,
        \Magento\Framework\App\ResourceConnection $resourceConnection
    ) {
        parent::__construct($context);
        $this->scopeConfig = $scopeConfigObject;
        $this->urlInterface = $urlInterface;
        $this->_storeManager = $storeManager;
        $this->_asm = $Allshippingmethods;
        $this->resourceConnection = $resourceConnection;
    }

    public function getGroupData($id)
    {
        $db = $this->resourceConnection->getConnection();
        $result = $db->query('SELECT * FROM test_shipping WHERE customer_group=' . $id);
        $row = $result->fetch();
        $values=$row['carriers'];//print_r($values);exit;
        $split=explode(",",$values);
        $count = count($split);

        $methods=$this->_asm->toOptionArray();

        foreach ($methods as $j => $inner) {
            if(!empty($inner['value'])){
                foreach ($inner['value'] as $key => $value) {
                    if (in_array($value['value'], $split)) {      
                       unset($methods[$j]['value'][$key]);
                    }
                }
            }
        }

        return $methods;
    }

    public function getAllMethods()
    {
        $methods=$this->_asm->toOptionArray();

        return $methods;
    }
}

?>

app/code/Test/Shipping/Model/Source/Allshippingmethods.php

<?php

namespace Test\Shipping\Model\Source;

/**
 * Class Allshippingmethods
 */
class Allshippingmethods implements \Magento\Framework\Option\ArrayInterface
{
   /**
     * Core store config
     *
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $_scopeConfig;

    /**
     * @var \Magento\Shipping\Model\Config
     */
    protected $_shippingConfig;

    /**
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
     * @param \Magento\Shipping\Model\Config $shippingConfig
     */
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Shipping\Model\Config $shippingConfig
    ) {
        $this->_scopeConfig = $scopeConfig;
        $this->_shippingConfig = $shippingConfig;
    }

    /**
     * Return array of carriers.
     * If $isActiveOnlyFlag is set to true, will return only active carriers
     *
     * @param bool $isActiveOnlyFlag
     * @return array
     */
    public function toOptionArray($isActiveOnlyFlag = false)
    {
        $methods = [['value' => '', 'label' => '']];
        $carriers = $this->_shippingConfig->getAllCarriers();

        foreach ($carriers as $carrierCode => $carrierModel) {
            if (!$carrierModel->isActive() && (bool)$isActiveOnlyFlag === true) {
                continue;
            }
            $carrierMethods = $carrierModel->getAllowedMethods();
            if (!$carrierMethods) {
                continue;
            }
            $carrierTitle = $this->_scopeConfig->getValue(
                'carriers/' . $carrierCode . '/title',
                \Magento\Store\Model\ScopeInterface::SCOPE_STORE
            );

            $methods[$carrierCode] = ['label' => $carrierTitle, 'value' => []];
            foreach ($carrierMethods as $methodCode => $methodTitle) {
                $methods[$carrierCode]['value'][] = [
                    'value' => $carrierCode . '_' . $methodCode,
                    'label' => '[' . $carrierCode . '] ' . $methodTitle,
                ];
            }
        }
        return $methods;
    }
}

?>

Below i got the error:

<b>Fatal error</b>:  Uncaught Error: Function name must be a string in /mage2/shipping
/app/code/Test/Shipping/Plugin/Shipping.php:90
Stack trace:
#0 /mage2/shipping/vendor/magento/framework/Interception/Interceptor.php(142
): Test\Shipping\Plugin\Shipping-&gt;aroundCollectCarrierRates(Object(Magento\Shipping\Model
\Shipping\Interceptor), Object(Closure), 'dhl', Object(Magento\Quote\Model\Quote\Address\RateRequest
))
#1 /mage2/shipping/var/generation/Magento/Shipping/Model/Shipping/Interceptor
.php(91): Magento\Shipping\Model\Shipping\Interceptor-&gt;___callPlugins('collectCarrierR...', Array
, Array)
#2 /mage2/shipping/vendor/magento/module-shipping/Model/Shipping.php(209):
 Magento\Shipping\Model\Shipping\Interceptor-&gt;collectCarrierRates('dhl', Object(Magento\Quote\Model
\Quote\Address\RateRequest))
#3 /mage2/shipping/var/generation/Magento/Shipping/Model/Shipping/Interceptor
.php(76): Mage in <b>/mage2/shipping/app/code/Test/Shipping/Plugin
/Shipping.php</b> on line <b>90</b><br />
{"messages":{"error":[{"code":500,"message":"Server internal error. See details in report api\/1070442461519"
}]}}

What do I do now ?

  • Line 90: $result = $proceed(); It should be $result = $proceed; right? – Ankit Shah Sep 21 '16 at 7:26
  • @AnkitShah Yes, i also try for that.. And error removed but i got in response only blank array like this [ ] – Payal Patel Sep 21 '16 at 7:41
1

your aroundCollectCarrierRates is declared wrongly.
The first parameter should be the instance of the class you are pluginizing.
See this for more details.

Your method should look like this:

public function aroundCollectCarrierRates(
    \Magento\Shipping\Model\Shipping $subject,
    $proceed, 
    $carrierCode, 
    $request
) {
   //your code here
}
  • You are right @Marius, But When i use this aroundCollectCarrierRates(\Magento\Shipping\Model\Shipping $subject, \callable $proceed, $carrierCode, $request) I got this error:- <b>Parse error</b>: syntax error, unexpected 'callable' (T_CALLABLE), expecting identifier (T_STRING ) in <b>/mage2/shipping/app/code/Test/Shipping/Plugin/Shipping .php</b> on line <b>88</b><br /> {"messages":{"error":[{"code":500,"message":"Server internal error. See details in report api\/1322575338538" }]}} – Payal Patel Sep 21 '16 at 7:32
  • see my edit. Remove \callable from the method definition. – Marius Sep 21 '16 at 7:34
  • I also remove \callable.. Now new error create like this:- [2016-09-21 07:36:09] main.CRITICAL: Exception: Warning: Missing argument 1 for Magento\Shipping\Model\Shipping::collectCarrierRates() – Payal Patel Sep 21 '16 at 7:37
  • remove just the word \callable, not the variable. See my edit. – Marius Sep 21 '16 at 7:46
  • 1
    @PayalPatel: It should be \Closure not \callable – Toan Nguyen Sep 22 '16 at 8:19

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.