0

I'm trying to override the round method in \vendor\magento\module-directory\Model\PriceCurrency.php. This is the method:

/**
 * @inheritdoc
 */
public function round($price)
{
    return round($price, 2);
}

And this is the code I have in a plugin to override the above method:

class PriceCurrency
{
    public function aroundRound(\Magento\Directory\Model\PriceCurrency $subject, callable $proceed, $price) {
        return round($price, 4);
    }
}

My code doesn't work. I can easily override other public methods in the PriceCurrency file! Can that method be overridden?

0

In etc/frontend/di.xml, I'd expect to have your plugin definition like below?

<?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\Directory\Model\PriceCurrency">
        <plugin name="round_4" type="Vendor\Module\Model\PriceCurrency" />
    </type>
</config>

Now, instead of around plugin (which is fine in practice), Magento does recommend to use either before or after plugin as they are less likely to break the plugins system in Magento.

so

class PriceCurrency
{
    public function afterRound(\Magento\Directory\Model\PriceCurrency $subject, $roundedPrice, $price) {
        return round($price, 4);
    }
}

Finally, just below round, there is a function called roundPrice and you can specify your precision.. just in case you have flexibility.

All the code above has to be in a working module. SO, maybe before implementing the plugin, do verify your module is enabled.

  • Thank you. Your code seems valid to me, but the total values in the cart (e.g. subtotal and grand total) ignore it and use the round function that is located in the core PriceCurrency.php file. As a result, if the subtotal is 0.6789 with your solution it would show up as 0.6800. But if instead of using a plugin, I modify the core file it would show 0.6789 as expected. – DevOnStack Oct 11 '20 at 21:47
  • Changing precision is not a small change.. however you see to say my answer helped. Please accept it then – Herve Tribouilloy Oct 12 '20 at 5:12
  • thanks for validating, if you need to deal with cart totals, please explain the deliverable you are tying to make (in another question that is) and surely there is a way to improve this answer – Herve Tribouilloy Oct 12 '20 at 12:07
  • I accepted your helpful answer. I'm very curious to see how a change in the core file is taken into account but the same change in the plugin is ignored. Total calculation is somehow bypassing the interception, but I can't figure out how! – DevOnStack Oct 12 '20 at 12:08
  • write you change in the core in your question – Herve Tribouilloy Oct 12 '20 at 12:12

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.