duncanmcclean / simple-commerce

A simple, yet powerful e-commerce addon for Statamic.
https://statamic.com/addons/duncanmcclean/simple-commerce
Other
143 stars 37 forks source link

Refactor Calculator with Pipelines #873

Closed duncanmcclean closed 1 year ago

duncanmcclean commented 1 year ago

This pull request refactors the "order calculator" to use Laravel Pipelines, allowing for logic to be better split up rather than being in one big class.

All of the existing tests are passing. I've just had to change how information is fetched from the calculations as we're no longer passing around the $data array like we were before.

The code for this PR was written almost exclusively in CLT/BFS airports on the way back from Flat Camp. ✈️

Change: extending the Calculator

Overriding the Calculator class was documented up until v5.x. This could have been useful if you need to do your own kinds of calculations.

I don't think anyone is doing this from support requests & bug reports. However, if you are, you will need to move any custom logic into a pipeline class, like this one, then override the static calculate method and include your pipe class.

// app/SimpleCommerce/MyCustomCalculator.php

namespace App\SimpleCommerce;

use DoubleThreeDigital\SimpleCommerce\Contracts\Calculator as CalculatorContract;

class MyCustomCalculator implements CalculatorContract
{
    public static function calculate(Order $order): Order
        {
            return Pipeline::send($order)
                ->through([
                    LineItemCalculator::class,
                    LineItemTaxCalculator::class,
                    CalculateItemsTotal::class,
                    CouponCalculator::class,
                    ShippingCalculator::class,
                    CalculateGrandTotal::class,
                    MyCustomCalculations::class, // Added for this example
                ])
                ->thenReturn();
        }
    }
// app/SimpleCommerce/MyCustomCalculations.php

namespace App\SimpleCommerce;

use Closure;
use DoubleThreeDigital\SimpleCommerce\Contracts\Order;

class MyCustomCalculations
{
    public function handle(Order $order, Closure $next)
    {
        // Do whatever you want to here... you can touch the $order if you need to.

        return $next($order);
    }
}
github-actions[bot] commented 1 year ago

Released as part of v5.1.0.