File "ValidateRange.php"

Full Path: /home/clickysoft/public_html/jmapi5.clickysoft.net/app/Rules/ValidateRange.php
File size: 1.5 KB
MIME-type: text/x-php
Charset: utf-8

<?php

namespace App\Rules;

use App\Models\ProductPrice;
use App\Models\ProductVariationRange;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\InvokableRule;

class ValidateRange implements DataAwareRule, InvokableRule
{
    /**
     * All the data under validation.
     *
     * @var array
     */
    protected $data = [];

    /**
     * Set the data under validation.
     *
     * @param  array  $data
     * @return $this
     */
    public function setData($data)
    {
        $this->data = $data;

        return $this;
    }
    /**
     * Run the validation rule.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     * @return void
     */
    public function __invoke($attribute, $value, $fail)
    {
        $product_id = str_replace('quantity', 'product_id', $attribute);
        $price_id = str_replace('quantity', 'price_id', $attribute);
        $price = ProductPrice::where(['id' => request($price_id), 'product_id' => request($product_id)])->first();
        if (!$price) return $fail('Invalid quantity for product #:position.');
        $price_range = ProductVariationRange::where('product_price_id', $price->id)
            ->where('qty_from', '<=', $value)
            ->where('qty_to', '>=', $value)->first();

        if (!$price_range) return $fail('Invalid quantity for product #:position. We don\'t have enough quantity to fulfill the request.');
    }
}