Completed
Push — master ( f1c5d8...b7eb80 )
by Gregorio
01:54
created

Validator   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 234
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 98.21%

Importance

Changes 0
Metric Value
wmc 17
lcom 1
cbo 4
dl 0
loc 234
ccs 55
cts 56
cp 0.9821
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A make() 0 4 1
A getValidator() 0 15 2
A bootValidatorExtensions() 0 21 3
A validateIsValid() 0 15 3
A validateIsModel() 0 19 4
A replaceIsModel() 0 8 2
A __call() 0 4 1
1
<?php
2
3
namespace Gregoriohc\Moneta\Common\Validation;
4
5
use Gregoriohc\Moneta\Common\Concerns\Parametrizable;
6
use Illuminate\Translation\ArrayLoader;
7
use Illuminate\Translation\Translator;
8
use Illuminate\Validation\Factory as ValidatorFactory;
9
10
class Validator
11
{
12
    /**
13
     * @var \Illuminate\Validation\Validator
14
     */
15
    protected $validator;
16
17
    protected $validationMessages = [
18
        /*
19
        |--------------------------------------------------------------------------
20
        | Validation Language Lines
21
        |--------------------------------------------------------------------------
22
        |
23
        | The following language lines contain the default error messages used by
24
        | the validator class. Some of these rules have multiple versions such
25
        | as the size rules. Feel free to tweak each of these messages here.
26
        |
27
        */
28
        "accepted"         => "The :attribute must be accepted.",
29
        "active_url"       => "The :attribute is not a valid URL.",
30
        "after"            => "The :attribute must be a date after :date.",
31
        "alpha"            => "The :attribute may only contain letters.",
32
        "alpha_dash"       => "The :attribute may only contain letters, numbers, and dashes.",
33
        "alpha_num"        => "The :attribute may only contain letters and numbers.",
34
        "array"            => "The :attribute must be an array.",
35
        "before"           => "The :attribute must be a date before :date.",
36
        "between"          => [
37
            "numeric" => "The :attribute must be between :min and :max.",
38
            "file"    => "The :attribute must be between :min and :max kilobytes.",
39
            "string"  => "The :attribute must be between :min and :max characters.",
40
            "array"   => "The :attribute must have between :min and :max items.",
41
        ],
42
        "confirmed"        => "The :attribute confirmation does not match.",
43
        "date"             => "The :attribute is not a valid date.",
44
        "date_format"      => "The :attribute does not match the format :format.",
45
        "different"        => "The :attribute and :other must be different.",
46
        "digits"           => "The :attribute must be :digits digits.",
47
        "digits_between"   => "The :attribute must be between :min and :max digits.",
48
        "email"            => "The :attribute format is invalid.",
49
        "exists"           => "The selected :attribute is invalid.",
50
        "image"            => "The :attribute must be an image.",
51
        "in"               => "The selected :attribute is invalid.",
52
        "integer"          => "The :attribute must be an integer.",
53
        "ip"               => "The :attribute must be a valid IP address.",
54
        "max"              => [
55
            "numeric" => "The :attribute may not be greater than :max.",
56
            "file"    => "The :attribute may not be greater than :max kilobytes.",
57
            "string"  => "The :attribute may not be greater than :max characters.",
58
            "array"   => "The :attribute may not have more than :max items.",
59
        ],
60
        "mimes"            => "The :attribute must be a file of type: :values.",
61
        "min"              => [
62
            "numeric" => "The :attribute must be at least :min.",
63
            "file"    => "The :attribute must be at least :min kilobytes.",
64
            "string"  => "The :attribute must be at least :min characters.",
65
            "array"   => "The :attribute must have at least :min items.",
66
        ],
67
        "not_in"           => "The selected :attribute is invalid.",
68
        "numeric"          => "The :attribute must be a number.",
69
        "regex"            => "The :attribute format is invalid.",
70
        "required"         => "The :attribute field is required.",
71
        "required_if"      => "The :attribute field is required when :other is :value.",
72
        "required_with"    => "The :attribute field is required when :values is present.",
73
        "required_without" => "The :attribute field is required when :values is not present.",
74
        "required_without_all" => "The :attribute field is required when :values are not present.",
75
        "same"             => "The :attribute and :other must match.",
76
        "size"             => [
77
            "numeric" => "The :attribute must be :size.",
78
            "file"    => "The :attribute must be :size kilobytes.",
79
            "string"  => "The :attribute must be :size characters.",
80
            "array"   => "The :attribute must contain :size items.",
81
        ],
82
        "unique"           => "The :attribute has already been taken.",
83
        "url"              => "The :attribute format is invalid.",
84
        'custom' => [],
85
        'attributes' => [],
86
    ];
87
88
    protected $validationMessagesCustom = [
89
        "is_valid"         => "The :attribute must be a validable object.",
90
        "is_model"         => "The :attribute must be a model of type :model.",
91
    ];
92
93
    protected $context;
94
95
    /**
96
     * Validator constructor.
97
     *
98
     * @param array $parameters
99
     * @param array $rules
100
     * @param mixed $context
101
     */
102 30
    public function __construct($parameters, $rules, $context = null)
103
    {
104 30
        $this->context = $context;
105 30
        $this->validator = $this->getValidator($parameters, $rules);
106 30
    }
107
108
    /**
109
     * @param array $parameters
110
     * @param array $rules
111
     * @param mixed $context
112
     * @return static|\Illuminate\Validation\Validator
113
     */
114 30
    public static function make($parameters, $rules, $context = null)
115
    {
116 30
        return new static($parameters, $rules, $context);
117
    }
118
119
    /**
120
     * @param array $parameters
121
     * @param array $rules
122
     * @return \Illuminate\Validation\Validator
123
     */
124 30
    public function getValidator($parameters, $rules)
125
    {
126 30
        if (!class_exists('\Validator')) {
127 30
            $loader = new ArrayLoader();
128 30
            $loader->addMessages('en_US', 'validation', $this->validationMessages);
129 30
            $translator = new Translator($loader, 'en_US');
130 30
            $validatorFactory = new ValidatorFactory($translator);
131 30
            $validator = $validatorFactory->make($parameters, $rules, $this->validationMessagesCustom);
132
        } else {
133
            $validator = \Validator::make($parameters, $rules, $this->validationMessagesCustom);
134
        }
135 30
        $this->bootValidatorExtensions($validator, ['is_valid', 'is_model']);
136
137 30
        return $validator;
138
    }
139
140
    /**
141
     * @param \Illuminate\Validation\Validator $validator
142
     * @param array $names
143
     */
144 30
    public function bootValidatorExtensions(&$validator, $names)
145
    {
146 30
        $context = $this->context;
147
148 30
        foreach ($names as $name) {
149 30
            $validator->addExtension($name, function ($attribute, $value, $parameters, $validator) use ($name, $context) {
150 24
                $parameters[] = $context;
151 24
                $method = 'validate' . studly_case($name);
152 24
                return call_user_func_array([static::class, $method], [$attribute, $value, $parameters, $validator]);
153 30
            });
154
155 30
            $validator->addReplacer($name, function ($message, $attribute, $rule, $parameters) use ($name, $context) {
156 6
                $parameters[] = $context;
157 6
                $method = 'replace' . studly_case($name);
158 6
                if (!method_exists(static::class, $method)) {
159 3
                    return $message;
160
                }
161 6
                return call_user_func_array([static::class, $method], [$message, $attribute, $rule, $parameters]);
162 30
            });
163
        }
164 30
    }
165
166
    /**
167
     * @param string $attribute
168
     * @param mixed $value
169
     * @param array $parameters
170
     * @param \Illuminate\Validation\Validator $validator
171
     * @return bool
172
     */
173 24
    protected static function validateIsValid($attribute, $value, $parameters, $validator)
0 ignored issues
show
Unused Code introduced by
The parameter $parameters is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $validator is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
174
    {
175 24
        if (!is_object($value)) {
176 3
            return "Parameter '$attribute' must be an object";
177
        }
178
179 21
        if (!method_exists($value, 'validateParameters')) {
180 3
            return false;
181
        }
182
183
        /** @var Parametrizable $parameterValue */
184 18
        $value->validateParameters();
185
186 15
        return true;
187
    }
188
189
    /**
190
     * @param string $attribute
191
     * @param mixed $value
192
     * @param array $parameters
193
     * @param \Illuminate\Validation\Validator $validator
194
     * @return bool
195
     */
196 24
    protected static function validateIsModel($attribute, $value, $parameters, $validator)
0 ignored issues
show
Unused Code introduced by
The parameter $attribute is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $validator is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
197
    {
198 24
        $basePackageNamespace = implode('\\', array_slice(explode('\\', static::class), 0, 2));
199 24
        if (count($parameters) == 1) {
200 3
            array_unshift($parameters, $basePackageNamespace . '\\Common\\Models\\AbstractModel');
201
        }
202
203 24
        $contextClass = get_class($parameters[1]);
204 24
        $baseContextNamespace = implode('\\', array_slice(explode('\\', $contextClass), 0, 2));;
205 24
        if (!strstr($parameters[0], '\\')) {
206 21
            $parameters[0] = $baseContextNamespace . '\\Common\\Models\\' . $parameters[0];
207
        }
208
209 24
        if (!is_a($value, $parameters[0], true)) {
210 6
            return false;
211
        }
212
213 18
        return true;
214
    }
215
216
    /**
217
     * @param string $message
218
     * @param string $attribute
219
     * @param string $rule
220
     * @param array $parameters
221
     * @return bool
222
     */
223 6
    protected static function replaceIsModel($message, $attribute, $rule, $parameters)
0 ignored issues
show
Unused Code introduced by
The parameter $attribute is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $rule is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
224
    {
225 6
        if (count($parameters) == 1) {
226 3
            array_unshift($parameters, 'AbstractModel');
227
        }
228
229 6
        return str_replace(':model', $parameters[0], $message);
230
    }
231
232
    /**
233
     * @param string $name
234
     * @param array $arguments
235
     * @return mixed
236
     */
237 30
    public function __call($name, $arguments)
238
    {
239 30
        return call_user_func_array([$this->validator, $name], $arguments);
240
    }
241
242
243
}
244