HandlesValidationErrors   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 10
c 1
b 0
f 0
dl 0
loc 46
rs 10

3 Methods

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