Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top