Completed
Branch delegated-factory (41b3c7)
by Albert
02:04
created

MessageParser::setValidationData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
nc 1
cc 1
eloc 3
nop 1
1
<?php
2
3
namespace Proengsoft\JsValidation\Javascript;
4
use Proengsoft\JsValidation\Support\DelegatedValidator;
5
use Proengsoft\JsValidation\Support\UseDelegatedValidatorTrait;
6
7
class MessageParser
8
{
9
    use UseDelegatedValidatorTrait;
10
11
    /**
12
     * Create a new JsValidation instance.
13
     *
14
     * @param \Proengsoft\JsValidation\Support\DelegatedValidator $validator
15
     */
16
    public function __construct(DelegatedValidator $validator)
17
    {
18
        $this->validator = $validator;
19
    }
20
21
    /**
22
     *  Replace javascript error message place-holders with actual values.
23
     *
24
     * @param string $attribute
25
     * @param string $rule
26
     * @param array  $parameters
27
     *
28
     * @return mixed
29
     */
30
    public function getJsMessage($attribute, $rule, $parameters)
31
    {
32
33
        $data = $this->fakeValidationData($attribute, $rule, $parameters);
34
35
        $message = $this->validator->getMessage($attribute, $rule);
36
        $message = $this->validator->doReplacements($message, $attribute, $rule, $parameters);
37
38
        $this->setValidationData($data);
39
40
        return $message;
41
    }
42
43
44
    /**
45
     * Creates fake data needed to parse messages
46
     * Returns original data
47
     *
48
     * @param string $attribute
49
     * @param string $rule
50
     * @param $parameters
51
     *
52
     * @return array
53
     */
54
    protected function fakeValidationData($attribute, $rule, $parameters) {
55
56
        $data = $this->validator->getFiles();
57
        $files = $this->validator->getData();
58
59
        if (array_key_exists($attribute, $data) ||array_key_exists($attribute, $files)) {
60
            return compact('data', 'files');
61
        }
62
63
        if ($rule == 'RequiredIf') {
64
            $newData = $data;
65
            $newData[$parameters[0]] = $parameters[1];
66
            $this->validator->setData($newData);
67
        }
68
69
        if ($this->validator->hasRule($attribute, array('Mimes', 'Image'))) {
70
            $newFiles = $files;
71
            $newFiles[$attribute] = false;
72
            $this->validator->setFiles($newFiles);
73
        }
74
75
        return compact('data', 'files');
76
77
    }
78
79
    /**
80
     * Sets validation data
81
     *
82
     * @param array $data
83
     */
84
    protected function setValidationData($data) {
85
        $this->validator->setFiles($data['files']);
86
        $this->validator->setData($data['data']);
87
    }
88
89
90
}