Passed
Push — master ( bd59c3...bb2815 )
by Pascal
05:04 queued 03:02
created

HandlesValidationErrors   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 3
eloc 8
c 1
b 0
f 0
dl 0
loc 33
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A hasError() 0 7 1
A hasErrorAndShow() 0 5 2
1
<?php
2
3
namespace ProtoneMedia\LaravelFormComponents\Components;
4
5
use Illuminate\Support\Facades\View;
6
use Illuminate\Support\ViewErrorBag;
7
8
trait HandlesValidationErrors
9
{
10
    public $showErrors = true;
11
12
    /**
13
     * Returns a boolean wether the given attribute has an error
14
     * and the should be shown.
15
     *
16
     * @param string $name
17
     * @param string $bag
18
     * @return boolean
19
     */
20
    public function hasErrorAndShow(string $name, string $bag = 'default'): bool
21
    {
22
        return $this->showErrors
23
            ? $this->hasError($name, $bag)
24
            : false;
25
    }
26
27
    /**
28
     * Returns a boolean wether the given attribute has an error.
29
     *
30
     * @param string $name
31
     * @param string $bag
32
     * @return boolean
33
     */
34
    public function hasError(string $name, string $bag = 'default'): bool
35
    {
36
        $errors = View::shared('errors', fn () => request()->session()->get('errors', new ViewErrorBag));
37
38
        $name = str_replace(['[', ']'], ['.', ''], $name);
39
40
        return $errors->getBag($bag)->has($name);
41
    }
42
}
43