Passed
Push — main ( f4f1f6...b3a018 )
by PRATIK
14:01
created

CategoryRequest::getMainCategory()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 10
c 0
b 0
f 0
nc 4
nop 1
dl 0
loc 15
rs 9.9332
1
<?php
2
3
namespace Adminetic\Website\Http\Requests;
4
5
use Adminetic\Website\Models\Admin\Category;
6
use Illuminate\Foundation\Http\FormRequest;
7
use Illuminate\Support\Str;
8
9
class CategoryRequest extends FormRequest
10
{
11
    /**
12
     * Determine if the user is authorized to make this request.
13
     *
14
     * @return bool
15
     */
16
    public function authorize()
17
    {
18
        return true;
19
    }
20
21
    /**
22
     * Prepare the data for validation.
23
     *
24
     * @return void
25
     */
26
    protected function prepareForValidation()
27
    {
28
        $this->merge([
29
            'code' => $this->category->code ?? rand(100000, 999999),
30
            'slug' => Str::slug($this->name),
31
            'main_category_id' => $this->getMainCategory($this->category->parent_id ?? null),
32
            'model' => $this->model ?? $this->category->model ?? "All",
33
        ]);
34
    }
35
36
    /**
37
     * Get the validation rules that apply to the request.
38
     *
39
     * @return array
40
     */
41
    public function rules()
42
    {
43
        $id = $this->category->id ?? '';
44
45
        return [
46
            'model' => 'required|max:255',
47
            'code' => 'required|unique:categories,code,' . $id,
48
            'name' => 'required|max:255',
49
            'slug' => 'required|unique:categories,slug,' . $id,
50
            'parent_id' => 'nullable|numeric',
51
            'main_category_id' => 'nullable|numeric',
52
            'active' => 'sometimes|boolean',
53
            'color' => 'nullable|max:12',
54
            'icon' => 'nullable|max:20',
55
            'image' => 'nullable|file|image|max:3000',
56
            'description' => 'nullable|max:3000',
57
            'meta_name' => 'nullable|max:255',
58
            'meta_description' => 'nullable|max:255',
59
            'meta_name' => 'nullable',
60
        ];
61
    }
62
63
    // Get Main Category
64
    public function getMainCategory($given_category_id = null)
65
    {
66
        $parent_id = $given_category_id ?? $this->parent_id ?? null;
67
        $category = Category::find($parent_id);
68
        if (isset($category)) {
69
            while (true) {
70
                if (isset($category->parent_id)) {
71
                    $category = Category::find($category->parent_id);
72
                } else {
73
                    break;
74
                }
75
            }
76
            return $category->id;
77
        }
78
        return null;
79
    }
80
}
81