Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 14
PerProductSave
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 3
20
0.00% covered (danger)
0.00%
0 / 14
 __construct
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 handle
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 7
 anonymous function
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
<?php
namespace Mtc\Shop\PriceMethods\Listeners;
use Mtc\Shop\Events\PriceUpdated;
use Mtc\Shop\PriceMethods\Models\PricePerProduct;
use Mtc\Shop\Product;
use Request;
class PerProductSave
{
    public function __construct()
    {
    }
    public function handle(Product $product)
    {
        $quantities = Request::input('price_per_product.quantity', []);
        $prices = Request::input('price_per_product.price', []);
        // Store a list of all saved price ids so we can delete any old ones.
        $saved_prices = [];
        collect(compact('quantities', 'prices'))
            ->transpose()
            // Ditch any whitespace
            ->map(function($item) {
                return array_map('trim', $item);
            })
            // Reject any empty inputs
            ->reject(function ($item) {
                return empty($item[0]) || empty($item[1]);
            })
            // Save the price and store in the $saved_prices aray
            ->each(function($item) use ($product, &$saved_prices) {
                $price = PricePerProduct::firstOrNew([
                    'product_id' => $product->id,
                    'quantity' => $item[0],
                ]);
                $price->price = $item[1];
                $price->save();
                $saved_prices[] = $price->id;
            });
        // Delete any non-existing prices for this product
        PricePerProduct::whereProductId($product->id)
            ->whereNotIn('id', $saved_prices)
            ->delete();
        event(new PriceUpdated($product));
    }
}