ErrorMessageResolver::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Flugg\Responder;
4
5
use Flugg\Responder\Contracts\ErrorMessageResolver as ErrorMessageResolverContract;
6
use Illuminate\Translation\Translator;
7
8
/**
9
 * A resolver class responsible for resolving messages from error codes.
10
 *
11
 * @package flugger/laravel-responder
12
 * @author  Alexander Tømmerås <[email protected]>
13
 * @license The MIT License
14
 */
15
class ErrorMessageResolver implements ErrorMessageResolverContract
16
{
17
    /**
18
     * A serivce for resolving messages from language files.
19
     *
20
     * @var \Illuminate\Translation\Translator
21
     */
22
    protected $translator;
23
24
    /**
25
     * A list of registered messages mapped to error codes.
26
     *
27
     * @var array
28
     */
29
    protected $messages = [];
30
31
    /**
32
     * Construct the resolver class.
33
     *
34
     * @param \Illuminate\Translation\Translator $translator
35
     */
36 58
    public function __construct(Translator $translator)
37
    {
38 58
        $this->translator = $translator;
39 58
    }
40
41
    /**
42
     * Register a message mapped to an error code.
43
     *
44
     * @param  mixed  $errorCode
45
     * @param  string $message
46
     * @return void
47
     */
48 1
    public function register($errorCode, string $message)
49
    {
50 1
        $this->messages = array_merge($this->messages, is_array($errorCode) ? $errorCode : [
51 1
            $errorCode => $message,
52
        ]);
53 1
    }
54
55
    /**
56
     * Resolve a message from the given error code.
57
     *
58
     * @param  mixed $errorCode
59
     * @return string|null
60
     */
61 3
    public function resolve($errorCode)
62
    {
63 3
        if (key_exists($errorCode, $this->messages)) {
64 1
            return $this->messages[$errorCode];
65
        }
66
67 2
        if ($this->translator->has($errorCode = "errors.$errorCode")) {
68 1
            return $this->translator->get($errorCode);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->translator->get($errorCode); of type string|array adds the type array to the return on line 68 which is incompatible with the return type declared by the interface Flugg\Responder\Contract...essageResolver::resolve of type string|null.
Loading history...
69
        }
70
71 1
        return null;
72
    }
73
}