Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
80.00% covered (warning)
80.00%
4 / 5
CRAP
94.12% covered (success)
94.12%
16 / 17
Basket
0.00% covered (danger)
0.00%
0 / 1
80.00% covered (warning)
80.00%
4 / 5
7.01
94.12% covered (success)
94.12%
16 / 17
 boot
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
1 / 1
 anonymous function
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 items
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
1 / 1
 user
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 addItem
100.00% covered (success)
100.00%
1 / 1
3
100.00% covered (success)
100.00%
11 / 11
<?php
namespace Mtc\Shop;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Mtc\Shop\Contracts\BasketContract;
use Mtc\Shop\Variant;
class Basket extends Model implements BasketContract
{
    /**
     * The attributes that should be casted to native types.
     * @var array
     */
    protected $casts = [
        'meta' => 'array',
    ];
    /**
     * The attributes that are mass assignable.
     * @var array
     */
    protected $fillable = [
        'user_id',
        'meta',
    ];
    /**
     * Capture the boot event to save the basket_id within
     * the session if basket created.
     * @return void
     */
    public static function boot()
    {
        parent::boot();
        static::created(function($basket) {
            session(['basket_id' => $basket->id]);
        });
    }
    /**
     * Get the list of items within the basket.
     * @return Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function items()
    {
        return $this->hasMany(BasketItem::class);
    }
    /**
     * Get the user this belongs to
     * @return Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function addItem(Variant $variant, $quantity = 1)
    {
        // Get any existing item (if exists)
        $item = $this->items()
            ->where('variant_id', $variant->id)
            ->first();
        if ($item) {
            // We update the quantity if it exists
            // e.g. adding another X to basket
            $item->quantity += $quantity;
        } else {
            // If doesn't exist, add it.
            $item = new BasketItem([
                'variant_id' => $variant->id,
                'quantity' => $quantity,
                ]);
        }
        // If we don't have a basket yet, spool it up.
        if (!$this->exists) {
            $this->save();
        }
        return $this->items()->save($item);
    }
}