Completed
Push — master ( 1e1451...9449be )
by David
02:05
created

Field::isIdField()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 4
rs 10
cc 2
eloc 2
nc 2
nop 1
1
<?php
2
3
namespace Taskforcedev\CrudApi\Helpers;
4
5
/**
6
 * Class Field.
7
 */
8
class Field
9
{
10
    public $crudApi;
11
12
    /**
13
     * Field constructor.
14
     *
15
     * @param CrudApi $crudApi
16
     */
17
    public function __construct(CrudApi $crudApi)
18
    {
19
        $this->crudApi = $crudApi;
20
    }
21
22
    /**
23
     * Determine if the field is an id field.
24
     *
25
     * @param $field
26
     *
27
     * @return bool
28
     */
29
    public function isIdField($field)
30
    {
31
        return strpos($field, '_id') === false ? false : true;
32
    }
33
34
    /**
35
     * Parse a relation field name into the relation name.
36
     *
37
     * @param string $field Field name
38
     *
39
     * @return string
40
     */
41
    public function getRelatedField($field)
42
    {
43
        $relation = str_replace('_id', '', $field);
44
45
        return $relation;
46
    }
47
48
    /**
49
     * Retrieve the models primary field for display purposes.
50
     *
51
     * @param            $item   Model to retrieve primary field of
52
     * @param null|array $config CrudApi Configuration
53
     *
54
     * @return string
55
     */
56
    public function getPrimaryField($item, $config = null)
57
    {
58
        /* If config is not overridden then load crudapi config */
59
        if ($config === null) {
60
            $config = config('crudapi');
61
        }
62
        if (!isset($config['models']['fields']['default'])) {
63
            $defaultField = 'name';
64
        } else {
65
            $defaultField = $config['models']['fields']['default'];
66
        }
67
68
        /* Get the items Class */
69
        $class = get_class($item);
70
71
        $stripped_class = str_replace($this->crudApi->namespace, '', $class);
72
        // if class starts with a \ remove it.
73
        if (substr($stripped_class, 0, 1) == '\\') {
74
            $stripped_class = substr($stripped_class, 1);
75
        }
76
77
        $primaryFields = $config['models']['fields']['primary'];
78
79
        if (array_key_exists($stripped_class, $primaryFields)) {
80
            return $primaryFields[$stripped_class];
81
        } else {
82
            //return the default
83
            return $defaultField;
84
        }
85
    }
86
87
    public function displayPrimaryField($item, $config = null)
88
    {
89
        $field = $this->getPrimaryField($item, $config);
90
91
        return $item->$field;
92
    }
93
94
    /**
95
     * Render fields into appropriate format for an item creation form.
96
     *
97
     * @param $fields
98
     *
99
     * @return string
100
     */
101 View Code Duplication
    public function formCreate($fields)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
102
    {
103
        $output = '';
104
105
        foreach ($fields as $f) {
106
            $ucF = ucfirst($f);
107
108
            $input_attr = [
109
                'class' => 'form-control',
110
                'id' => 'createItem'.$f,
111
                'name' => $f,
112
            ];
113
114
            $output .= '<fieldset class="form-group">';
115
116
            $output .= '<label for="'.$input_attr['id'].'">'.$ucF.'</label>';
117
118
            if ($this->isIdField($f)) {
119
                $input_attr['type'] = 'select';
120
121
                $output .= '<select ';
122
                foreach ($input_attr as $attr => $value) {
123
                    $output .= "{$attr}='{$value}'";
124
                }
125
126
                $relation = $this->crudApi->getRelatedModel($f);
127
                $output .= '>';
128
129
                $output .= $this->crudApi->getRelatedOptions($relation);
130
131
                $output .= '</select>';
132
            } else {
133
                $input_attr['type'] = 'text';
134
135
                $output .= '<input ';
136
                foreach ($input_attr as $attr => $value) {
137
                    $output .= "{$attr}='{$value}'";
138
                }
139
                $output .= '>';
140
            }
141
142
            $output .= '</fieldset>';
143
        }
144
145
        return $output;
146
    }
147
148
    /**
149
     * Render fields into appropriate format for an edit form.
150
     * @param array $fields Fields to render.
151
     * @return string
152
     */
153 View Code Duplication
    public function formEdit($fields)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
154
    {
155
        $output = '';
156
        foreach ($fields as $f) {
157
            $ucF = ucfirst($f);
158
159
            $input_attr = [
160
                'class' => 'form-control',
161
                'id' => 'editItem'.$ucF,
162
                'name' => $f,
163
            ];
164
165
            $output .= '<fieldset class="form-group">';
166
167
            $output .= '<label for="'.$input_attr['id'].'">'.$ucF.'</label>';
168
169
            if ($this->fieldHelper->isIdField($f)) {
0 ignored issues
show
Bug introduced by
The property fieldHelper does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
170
                $input_attr['type'] = 'select';
171
172
                $output .= '<select ';
173
                foreach ($input_attr as $attr => $value) {
174
                    $output .= "{$attr}='{$value}'";
175
                }
176
177
                $relation = $this->getRelatedModel($f);
0 ignored issues
show
Bug introduced by
The method getRelatedModel() does not seem to exist on object<Taskforcedev\CrudApi\Helpers\Field>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
178
                $output .= '>';
179
180
                $output .= $this->getRelatedOptions($relation);
0 ignored issues
show
Bug introduced by
The method getRelatedOptions() does not seem to exist on object<Taskforcedev\CrudApi\Helpers\Field>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
181
                $output .= '</select>';
182
            } else {
183
                $input_attr['type'] = 'text';
184
185
                $output .= '<input ';
186
                foreach ($input_attr as $attr => $value) {
187
                    $output .= "{$attr}='{$value}'";
188
                }
189
                $output .= '>';
190
            }
191
192
            $output .= '</fieldset>';
193
        }
194
        return $output;
195
    }
196
197
    /**
198
     * Return fields as table headings.
199
     *
200
     * @param $fields
201
     *
202
     * @return string
203
     */
204
    public function tableHeadings($fields)
205
    {
206
        $output = '';
207
        foreach ($fields as $f) {
208
            $output .= '<th>'.ucfirst($f).'</th>';
209
        }
210
211
        return $output;
212
    }
213
214
    public function tableContent($fields, $instance)
215
    {
216
        $output = '';
217
        foreach ($fields as $f) {
218
            if ($this->isIdField($f)) {
219
                $related = $this->getRelatedField($f);
220
                $relation = $instance->$related;
221
                $field = $this->getPrimaryField($relation);
222
                if (strpos($field, ',')) {
223
                    $subfields = explode(',', $field);
224
                    $display = '';
225
                    foreach ($subfields as $sf) {
226
                        $display .= $relation->$sf.' ';
227
                    }
228
                } else {
229
                    $display = $relation->$field;
230
                }
231
                $output .= '<td>'.$display.'</td>';
232
            } else {
233
                $output .= '<td>'.$instance->$f.'</td>';
234
            }
235
        }
236
237
        return $output;
238
    }
239
}
240