Passed
Push — master ( b8999c...a2f941 )
by Curtis
09:12 queued 03:15
created

ValidateCompanyRequest::rules()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 15
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 17
rs 9.7666
1
<?php
2
3
namespace App\Http\Requests\enso\companies;
4
5
use Illuminate\Foundation\Http\FormRequest;
6
use Illuminate\Validation\Rule;
7
use LaravelEnso\Companies\Enums\Statuses;
8
use LaravelEnso\Helpers\Traits\FiltersRequest;
9
10
class ValidateCompanyRequest extends FormRequest
11
{
12
    use FiltersRequest;
13
14
    public function authorize()
15
    {
16
        return true;
17
    }
18
19
    public function rules()
20
    {
21
        return [
22
            'mandatary' => 'nullable|exists:people,id',
23
            'name' => ['required', 'string', $this->unique('name')],
24
            'status' => 'required|numeric|in:'.Statuses::keys()->implode(','),
25
            'fiscal_code' => ['string', 'nullable', $this->unique('fiscal_code')],
26
            'reg_com_nr' => ['string', 'nullable', $this->unique('reg_com_nr')],
27
            'email' => 'email|nullable',
28
            'phone' => 'nullable',
29
            'fax' => 'nullable',
30
            'website' => 'nullable|url',
31
            'bank' => 'string|nullable',
32
            'bank_account' => 'string|nullable',
33
            'notes' => 'string|nullable',
34
            'pays_vat' => 'required|boolean',
35
            'is_tenant' => 'required|boolean',
36
        ];
37
    }
38
39
    public function withValidator($validator)
40
    {
41
        if ($this->filled('mandatary') && $this->mandataryIsNotAssociated()) {
42
            $validator->after(fn ($validator) => $validator->errors()
43
                ->add('mandatary', __('The selected person is not associated to this company')));
44
        }
45
    }
46
47
    protected function mandataryIsNotAssociated()
48
    {
49
        return ! $this->route('company')->people()
50
            ->pluck('id')->contains($this->get('mandatary'));
51
    }
52
53
    protected function unique(string $attribute)
54
    {
55
        return Rule::unique('companies', $attribute)
56
            ->ignore(optional($this->route('company'))->id);
57
    }
58
}
59