Request::labels()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Finder\Http\Requests\User;
4
5
use Illuminate\Contracts\Validation\Validator;
6
use Illuminate\Foundation\Http\FormRequest;
7
8
abstract class Request extends FormRequest
9
{
10
    /**
11
     * Validation rules that apply to the request.
12
     *
13
     * @var array
14
     */
15
    public $rules = [];
16
17
    /**
18
     * Human friendly names of the request fields under validation.
19
     *
20
     * @var array
21
     */
22
    protected $labels = [];
23
24
    /**
25
     * Class constructor.
26
     *
27
     * @param  array
28
     * @return void
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
29
     */
30
    public function __construct(array $rules = [])
31
    {
32
        if($rules) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $rules of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
33
            list($this->labels, $this->rules) = self::parseRulesAndLabels($rules);
34
        }
35
    }
36
37
    /**
38
     * Get the validation rules that apply to the request.
39
     *
40
     * @return array
41
     */
42
    public function rules()
43
    {
44
        // Set the id to be excluded in the 'unique' rules
45
        static $replacement = null;
46
        if(is_null($replacement)) {
47
            $id = $this->getKey();
48
            $replacement = (is_integer($id)) ? ",$id" : '';
49
50
            foreach($this->rules as $field => $rules) {
51
                $this->rules[$field] = str_replace('{excludeCurrentId}', $replacement, $rules); //TODO refactor to support array of rules
52
            }
53
        }
54
55
        return $this->rules;
56
    }
57
58
    /**
59
     * Get the human friendly names of the request fields under validation.
60
     *
61
     * @return object
62
     */
63
    public function labels()
64
    {
65
        return (object) $this->labels;
66
    }
67
68
    /**
69
     * Set custom attributes for validator errors.
70
     *
71
     * @return array
72
     */
73
    public function attributes()
74
    {
75
        return $this->labels;
76
    }
77
78
    /**
79
     * Determine if the user is authorized to make this request.
80
     *
81
     * @return bool
82
     */
83
    public function authorize()
84
    {
85
        //NOTE use $this->user() to access current user instance
86
87
        return true;
88
    }
89
90
    /**
91
     * Get the resource primary key (id) from request URL.
92
     *
93
     * NOTE: It can also be retrieved from the route parameter name using
94
     * $this->route('paramName') method, but that involves knowing the name
95
     * of the parameter beforehand. i.e:
96
     *
97
     * For the route
98
     *     Route::post('comment/{comment}')
99
     *
100
     * the value of $comment can be retrieved by
101
     *
102
     *     $this->route('comment');
103
     *
104
     * @return integer|null
105
     */
106
    public function getKey()
107
    {
108
        $segments = $this->segments();
109
        $last = array_pop($segments);
110
111
        return (ctype_digit($last)) ? intval($last) : null;
112
    }
113
114
    /**
115
     * Parse validation rules in compact format.
116
     *
117
     * Converts:
118
     *
119
     * [
120
     *   'field1' => ['Label1', 'A|B'],
121
     *   'field2' => ['Label2', ['C','D']],
122
     * ];
123
     *
124
     * To:
125
     *
126
     * [
127
     *   'labels' => [
128
     *     'field1' => 'Label1',
129
     *     'field2' => 'Label2',
130
     *   ],
131
     *   'rules' => [
132
     *     'field1' => ['A', 'B'],
133
     *     'field2' => ['C', 'D'],
134
     *  ]
135
     * ];
136
     *
137
     * @param  array
138
     * @return array
139
     */
140
    public static function parseRulesAndLabels(array $originalRules)
141
    {
142
        $parsed = ['labels' => [], 'rules' => []];
143
144
        foreach($originalRules as $field => $labelAndRules)
145
        {
146
            list($label, $rules) = $labelAndRules;
147
148
            // Add label
149
            $parsed['labels'][$field] = $label;
150
151
            // Sometimes a column has no rules
152
            if(is_null($rules)) {
153
                continue;
154
            }
155
156
            // Convert rules to array
157
            if(! is_array($rules)) {
158
                $rules = explode('|', $rules);
159
            }
160
161
            // Convert rules to associative array
162
            foreach($rules as $key => $value)
163
            {
164
                $new_key = explode(':', $value);
165
                $rules[$new_key[0]] = $value;
166
                unset($rules[$key]);
167
            }
168
169
            // Add rules
170
            $parsed['rules'][$field] = $rules;
171
        }
172
173
        return array_values($parsed);
174
    }
175
}
176