ValidationException::create()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Slides\Connector\Auth\Exceptions;
4
5
use Illuminate\Support\Arr;
6
7
/**
8
 * Class ValidationException
9
 *
10
 * @package Slides\Connector\Auth\Exceptions
11
 */
12
class ValidationException extends \Illuminate\Validation\ValidationException
13
{
14
    /**
15
     * The attribute names which should be renamed
16
     *
17
     * @var array
18
     */
19
    protected static $attributeMap = [
20
        'username' => 'email'
21
    ];
22
23
    /**
24
     * The list of attributes which should be hidden
25
     *
26
     * @var array
27
     */
28
    protected static $attributeHides = [
29
        'userId'
30
    ];
31
32 3
    public static function create(string $message)
33
    {
34 3
        $messages = static::createMessages($message);
35
36 3
        return static::withMessages($messages);
37
    }
38
39
    /**
40
     * Create messages
41
     *
42
     * @param string $message
43
     *
44
     * @return array
45
     */
46 3
    private static function createMessages(string $message): array
47
    {
48 3
        $messages = [];
49
50 3
        foreach (json_decode($message, true) as $property => $attributeMessages) {
51 3
            if(in_array($property, static::$attributeHides)) {
52
                continue;
53
            }
54
55
            // Rename an attribute according the mapping, if not listed, use the same
56 3
            $property = Arr::get(static::$attributeMap, $property, $property);
57
58 3
            $messages[$property] = static::formatMessages($attributeMessages);
59
        }
60
61 3
        return $messages;
62
    }
63
64
    /**
65
     * Format given messages
66
     *
67
     * @param array $messages
68
     *
69
     * @return array
70
     */
71 3
    private static function formatMessages(array $messages): array
72
    {
73 3
        foreach ($messages as $key => $message) {
74 3
            foreach (static::$attributeMap as $attribute => $replacement) {
75 3
                $messages[$key] = str_replace($attribute, $replacement, $message);
76
            }
77
        }
78
79 3
        return $messages;
80
    }
81
}