BuildController   F
last analyzed

Complexity

Total Complexity 104

Size/Duplication

Total Lines 641
Duplicated Lines 6.4 %

Coupling/Cohesion

Components 1
Dependencies 17

Importance

Changes 0
Metric Value
wmc 104
lcom 1
cbo 17
dl 41
loc 641
rs 1.4494
c 0
b 0
f 0

32 Methods

Rating   Name   Duplication   Size   Complexity  
A resultsTemplateForBuilder() 0 4 1
A prependNullOption() 0 6 1
A myAPI() 0 6 1
A addKeysToThingsToBuild() 0 18 3
primaryThingsToBuild() 0 1 ?
secondaryThingsToBuild() 0 1 ?
A Link() 0 10 2
A LoadTemplateLink() 0 4 1
A Title() 0 4 1
A jQueryLink() 0 4 1
A startover() 0 6 1
A loadtemplate() 0 19 2
A turnStaticsIntoSessionData() 0 21 4
A index() 0 4 1
A primaryformstart() 8 8 1
A PrimaryForm() 0 6 1
A doprimaryform() 0 6 1
A secondaryformstart() 9 9 1
A SecondaryForm() 0 6 1
A dosecondaryform() 0 6 1
A results() 0 10 1
A debug() 0 7 1
A Form() 0 4 1
A FinalData() 0 4 1
A PrevLink() 0 4 1
A ClassNameForObject() 0 8 2
B MyCanMethodBuilder() 0 16 5
F createForm() 24 244 37
A additionalPrimaryFields() 0 4 1
A saveData() 0 19 4
B retrieveData() 0 21 8
C processedFormData() 0 57 17

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like BuildController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use BuildController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
4
namespace SunnySideUp\BuildDataObject;
5
6
abstract class BuildController extends \Controller
7
{
8
    private static $form_data_session_variable = 'SunnySideUp\BuildDataObject\DataObjectBuildController';
0 ignored issues
show
Unused Code introduced by
The property $form_data_session_variable is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
9
10
    private static $url_segment = 'build';
0 ignored issues
show
Unused Code introduced by
The property $url_segment is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
11
12
    private static $allowed_actions = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $allowed_actions is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
13
        'primaryformstart' => true,
14
        'PrimaryForm' => true,
15
        'doprimaryform' => true,
16
        'secondaryformstart' => true,
17
        'SecondaryForm' => true,
18
        'dosecondaryform' => true,
19
        'results' => true,
20
        'startover' => true,
21
        'loadtemplate' => true,
22
        'debug' => true
23
    ];
24
25
    protected $myBaseClass = 'DataObject';
26
27
    protected $apiProvider = 'SunnySideUp\BuildDataObject\API';
28
29
    abstract protected function primaryThingsToBuild();
0 ignored issues
show
Documentation introduced by
For interfaces and abstract methods it is generally a good practice to add a @return annotation even if it is just @return void or @return null, so that implementors know what to do in the overridden method.

For interface and abstract methods, it is impossible to infer the return type from the immediate code. In these cases, it is generally advisible to explicitly annotate these methods with a @return doc comment to communicate to implementors of these methods what they are expected to return.

Loading history...
30
31
    abstract protected function secondaryThingsToBuild();
0 ignored issues
show
Documentation introduced by
For interfaces and abstract methods it is generally a good practice to add a @return annotation even if it is just @return void or @return null, so that implementors know what to do in the overridden method.

For interface and abstract methods, it is impossible to infer the return type from the immediate code. In these cases, it is generally advisible to explicitly annotate these methods with a @return doc comment to communicate to implementors of these methods what they are expected to return.

Loading history...
32
33
    public function Link($action = null)
34
    {
35
        if ($action) {
36
            $action .= '/';
37
        }
38
        return
39
            '/'.$this->Config()->get('url_segment').
40
            '/'.strtolower($this->myBaseClass).
41
            '/'.$action;
42
    }
43
44
    public function LoadTemplateLink($className = '')
45
    {
46
        return $this->Link('loadtemplate').'?classname='.$className;
47
    }
48
49
    public function Title()
50
    {
51
        return 'Build a '.$this->myBaseClass.' - Step '.$this->step.' of 2';
52
    }
53
54
55
    public function jQueryLink()
56
    {
57
        return \Director::absoluteURL('/framework/thirdparty/jquery/jquery.js');
58
    }
59
60
    public function startover()
61
    {
62
        $this->saveData('_PrimaryForm', null);
63
        $this->saveData('_SecondaryForm', null);
64
        return $this->redirect($this->link('primaryformstart'));
65
    }
66
67
    public function loadtemplate($request)
68
    {
69
        $className = $request->getVar('classname');
70
        if (class_exists($className)) {
71
            $obj = \Injector::inst()->get($className);
72
            $primaryData = $this->turnStaticsIntoSessionData('primaryThingsToBuild', $className);
73
            $primaryData['Name'] = $className;
74
            $extends = get_parent_class($className);
75
            $primaryData['Extends'] = $extends;
76
            $primaryData['singular_name'] = $obj->i18n_singular_name();
77
            $primaryData['plural_name'] = $obj->i18n_plural_name();
78
            $this->saveData('_PrimaryForm', $primaryData);
79
80
            $secondaryData = $this->turnStaticsIntoSessionData('secondaryThingsToBuild', $className);
81
            $this->saveData('_SecondaryForm', $secondaryData);
82
83
            return $this->redirect($this->link('primaryformstart'));
84
        }
85
    }
86
87
    protected function turnStaticsIntoSessionData($method, $className)
88
    {
89
        $data = [];
90
        $thingsToBuild = $this->$method();
91
        foreach ($thingsToBuild as $static) {
92
            $varName = $static['Name'];
93
            $varValue = \Config::inst()->get($className, $varName);
94
            if (is_array($varValue)) {
95
                $count = 0;
96
                foreach ($varValue as $varInnerKey => $varInnerValue) {
97
                    $count++;
98
                    $data[$varName.'__KEY__'.$count] = $varInnerKey;
99
                    $data[$varName.'__VALUE__'.$count] = trim(preg_replace("/\([^)]+\)/", "", $varInnerValue));
100
                }
101
            } else {
102
                $data[$varName] = $varValue;
103
            }
104
        }
105
106
        return $data;
107
    }
108
109
    /**
110
     *
111
     * @var Form
112
     */
113
    protected $step = 1;
114
115
    /**
116
     *
117
     * @var Form
118
     */
119
    protected $form = null;
120
121
    /**
122
     *
123
     * @var Form
124
     */
125
    protected $prevLink = null;
126
127
    /**
128
     *
129
     * @var ArrayList
130
     */
131
    protected $finalData = null;
132
133
    public function index()
134
    {
135
        return $this->redirect($this->Link('primaryformstart'));
136
    }
137
138 View Code Duplication
    public function primaryformstart()
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...
139
    {
140
        $this->PrimaryForm();
141
        $this->prevLink = $this->Link('startover');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->Link('startover') of type string is incompatible with the declared type object<SunnySideUp\BuildDataObject\Form> of property $prevLink.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
142
        \SSViewer::set_source_file_comments(false);
0 ignored issues
show
Deprecated Code introduced by
The method SSViewer::set_source_file_comments() has been deprecated with message: 4.0 Use the "SSViewer.source_file_comments" config setting instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
143
144
        return $this->renderWith('BuildControllerForm');
145
    }
146
147
    public function PrimaryForm()
148
    {
149
        $this->form = $this->createForm('PrimaryForm', 'Build Model');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->createForm('PrimaryForm', 'Build Model') of type object<Form> is incompatible with the declared type object<SunnySideUp\BuildDataObject\Form> of property $form.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
150
151
        return $this->form;
152
    }
153
154
    public function doprimaryform($data, $form)
0 ignored issues
show
Unused Code introduced by
The parameter $form 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...
155
    {
156
        $this->saveData('_PrimaryForm', $data);
157
158
        return $this->redirect($this->Link('secondaryformstart'));
159
    }
160
161
162 View Code Duplication
    public function secondaryformstart()
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...
163
    {
164
        $this->step = 2;
0 ignored issues
show
Documentation Bug introduced by
It seems like 2 of type integer is incompatible with the declared type object<SunnySideUp\BuildDataObject\Form> of property $step.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
165
        $this->SecondaryForm();
166
        $this->prevLink = $this->Link('primaryformstart');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->Link('primaryformstart') of type string is incompatible with the declared type object<SunnySideUp\BuildDataObject\Form> of property $prevLink.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
167
        \SSViewer::set_source_file_comments(false);
0 ignored issues
show
Deprecated Code introduced by
The method SSViewer::set_source_file_comments() has been deprecated with message: 4.0 Use the "SSViewer.source_file_comments" config setting instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
168
169
        return $this->renderWith('BuildControllerForm');
170
    }
171
172
    public function SecondaryForm()
173
    {
174
        $this->form = $this->createForm('SecondaryForm', 'Download Example Class');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->createForm('Secon...ownload Example Class') of type object<Form> is incompatible with the declared type object<SunnySideUp\BuildDataObject\Form> of property $form.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
175
176
        return $this->form;
177
    }
178
179
180
    public function dosecondaryform($data, $form)
0 ignored issues
show
Unused Code introduced by
The parameter $form 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...
181
    {
182
        $this->saveData('_SecondaryForm', $data);
183
184
        return $this->redirect($this->Link('results'));
185
    }
186
187
    public function results()
188
    {
189
        $this->finalData = $this->processedFormData($this->retrieveData());
190
        \SSViewer::set_source_file_comments(false);
0 ignored issues
show
Deprecated Code introduced by
The method SSViewer::set_source_file_comments() has been deprecated with message: 4.0 Use the "SSViewer.source_file_comments" config setting instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
191
192
        return \SS_HTTPRequest::send_file(
193
            $this->renderWith($this->resultsTemplateForBuilder()),
194
            $this->finalData->Name.'.php'
195
        );
196
    }
197
198
    public function debug()
199
    {
200
        $this->finalData = $this->processedFormData($this->retrieveData());
201
        print_r($this->CanMethodBuilder('canEdit'));
0 ignored issues
show
Bug introduced by
The method CanMethodBuilder() does not exist on SunnySideUp\BuildDataObject\BuildController. Did you maybe mean MyCanMethodBuilder()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
202
        print_r($this->finalData);
203
        die('-----------------------------');
0 ignored issues
show
Coding Style Compatibility introduced by
The method debug() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
204
    }
205
206
    public function Form()
207
    {
208
        return $this->form;
209
    }
210
211
    public function FinalData()
212
    {
213
        return $this->finalData;
214
    }
215
216
    public function PrevLink()
217
    {
218
        return $this->prevLink;
219
    }
220
221
    protected function ClassNameForObject()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
222
    {
223
        if (isset($this->finalData->Name)) {
224
            return $this->finalData->Name;
225
        } else {
226
            return 'self::$class';
227
        }
228
    }
229
230
    public function MyCanMethodBuilder($type, $value)
0 ignored issues
show
Unused Code introduced by
The parameter $type 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...
231
    {
232
        if ($value === 'parent') {
233
            return null;
234
        } elseif ($value === 'one') {
235
            $str = 'DataObject::get_one($this->class) ? false : true;';
236
        } elseif ($value === 'true') {
237
            $str = 'true;';
238
        } elseif ($value === 'false') {
239
            $str = 'false;';
240
        } else {
241
            $str = 'Permission::check(\''.$value.'\', \'any\', $member);';
242
        }
243
244
        return \DBField::create_field('Varchar', $str);
245
    }
246
247
248
    protected function createForm($formName, $actionTitle)
249
    {
250
        if ($formName === 'PrimaryForm') {
251
            $isPrimary = true;
252
            $isSecond = false;
0 ignored issues
show
Unused Code introduced by
$isSecond is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
253
        } elseif ($formName === 'SecondaryForm') {
254
            $isPrimary = false;
255
            $isSecond = true;
0 ignored issues
show
Unused Code introduced by
$isSecond is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
256
        } else {
257
            user_error('Set right form type: '.$formName.' is not valid');
258
        }
259
260
        $finalFields = \FieldList::create();
261
262
        if ($isPrimary) {
0 ignored issues
show
Bug introduced by
The variable $isPrimary does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
263
            $toBuild = $this->primaryThingsToBuild();
264
            $possibleExtensions = $this->myAPI()->PossibleRelationsWithBaseClass($this->myBaseClass);
265
            $finalFields->push(\HeaderField::create('Based On (OPTIONAL) ...'));
266
            $possibleBasedOn = $possibleExtensions;
267
            unset($possibleBasedOn['DataObject']);
268
            $possibleBasedOn = ['' => '--- PRELOAD VALUES FROM ---'] + $possibleBasedOn;
269
            $finalFields->push(\DropdownField::create('Template', '', $possibleBasedOn));
270
            $finalFields->push(\HeaderField::create('Name your '.$this->myBaseClass));
271
            $finalFields->push(\TextField::create('Name', ''));
272
            $finalFields->push(\HeaderField::create('Extends'));
273
            asort($possibleExtensions);
274
            $finalFields->push(
275
                \DropdownField::create(
276
                    'Extends',
277
                    '',
278
                    $possibleExtensions
279
                )
280
            );
281
            $additionalFields = $this->additionalPrimaryFields();
282
            foreach ($additionalFields as $additionalField) {
283
                $finalFields->push($additionalField);
284
            }
285
        } else {
286
            $toBuild = $this->secondaryThingsToBuild();
287
        }
288
        $formFields = [];
289
        $formFieldsWithMultiple = [];
290
291
        $count = 0;
292
        //build fields ...
293
        foreach ($toBuild as $item) {
294
            $name = $item['Name'];
295
            $sourceMethod1 = $item['SourceMethod1'];
296
            $sourceMethod2 = $item['SourceMethod2'];
297
            $isMultiple = $item['IsMultiple'];
298
299
300
            //work out style
301
            $hasKeyAndValue = false;
302
            if ($sourceMethod1 && $sourceMethod2) {
303
                $hasKeyAndValue = true;
304
            }
305
            $formFields[$count] = [];
306
            if ($isMultiple) {
307
                $max = 12;
308
            } else {
309
                $max = 1;
310
            }
311
            $formFields[$count][0] = [
312
                $name.'_HEADER',
313
                'HeaderField',
314
                $name
315
            ];
316
317
318
            //work out sources
319
            if ($sourceMethod1 && $this->myAPI()->hasMethod($sourceMethod1)) {
320
                $source1 = $this->myAPI()->$sourceMethod1();
321
            } else {
322
                $source1 = null;
323
            }
324
            if ($sourceMethod2 && $this->myAPI()->hasMethod($sourceMethod2)) {
325
                $source2 = $this->myAPI()->$sourceMethod2();
326
            } elseif ($sourceMethod2) {
327
                $source2 = null;
328
            } else {
329
                $source2 = 'ignore';
330
            }
331
332
            //work out field names
333
334
            for ($i = 1; $i <= $max; $i++) {
335
                if ($hasKeyAndValue) {
336
                    if ($isMultiple) {
337
                        $nameKey = $name.'__KEY__'.$i;
338
                        $nameValue = $name.'__VALUE__'.$i;
339
                        $formFieldsWithMultiple[$nameKey] = $nameKey;
340
                    } else {
341
                        $nameKey = $name.'__KEY__';
342
                        $nameValue = $name.'__VALUE__';
343
                    }
344
                } else {
345
                    if ($isMultiple) {
346
                        $nameKey = $name.$i;
347
                        $nameValue = '';
348
                        $formFieldsWithMultiple[$nameKey] = $nameKey;
349
                    } else {
350
                        $nameKey = $name;
351
                        $nameValue = '';
352
                    }
353
                }
354
                if ($hasKeyAndValue) {
355
                    //key field
356 View Code Duplication
                    if ($source1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
357
                        $formFields[$count][$i]['KEY'] = [
358
                            $nameKey,
359
                            'DropdownField',
360
                            $source1
361
                        ];
362
                    } else {
363
                        $formFields[$count][$i]['KEY'] = [
364
                            $nameKey,
365
                            'TextField'
366
                        ];
367
                    }
368
369
                    //value field
370 View Code Duplication
                    if ($source2) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
371
                        $formFields[$count][$i]['VALUE'] = [
372
                            $nameValue,
373
                            'DropdownField',
374
                            $source2
375
                        ];
376
                    } else {
377
                        $formFields[$count][$i]['VALUE'] = [
378
                            $nameValue,
379
                            'TextField'
380
                        ];
381
                    }
382
                } else {
383
                    //keys only!
384
                    if ($source1) {
385
                        $formFields[$count][$i] = [
386
                            $nameKey,
387
                            'DropdownField',
388
                            $source1
389
                        ];
390
                    } else {
391
                        $formFields[$count][$i] = [
392
                            $nameKey,
393
                            'TextField'
394
                        ];
395
                    }
396
                }
397
            }
398
            if ($i > 2) {
399
                $formFields[$count][$i + 1] = [
400
                    $name.'_ADD_'.$i,
401
                    'LiteralField',
402
                    '
403
                    <div class="CompositeField add-and-remove">
404
                        <a href="#" class="add first-add"><i class="material-icons">add_circle_outline</i></a>
405
                        <a href="#" class="remove"><i class="material-icons">remove_circle_outline</i></a>
406
                    </div>
407
                    '
408
                ];
409
            }
410
            $count++;
411
        }
412
        //create fields ...
413
        $count = 0;
414
        foreach ($formFields as $outerCount => $subFieldList) {
415
            $count++;
416
            $compositeField = \CompositeField::create();
417
            $compositeField->addExtraClass('OuterComposite pos'.$count);
418
            $innerCount = 0;
419
            foreach ($subFieldList as $innerCount => $fieldDetails) {
420
                $innerCount++;
421
                if (isset($fieldDetails['KEY']) && isset($fieldDetails['VALUE'])) {
422
                    $subCompositeField = \CompositeField::create();
423
                    $subCompositeField->addExtraClass('InnerComposite pos'.$innerCount);
424
                    foreach ($fieldDetails as $fieldDetailsInner) {
425
                        $fieldName = $fieldDetailsInner[0];
426
                        $fieldType = $fieldDetailsInner[1];
427
                        $additionalClasses = [];
428
                        if (strpos($fieldName, '__KEY__')) {
429
                            $additionalClasses[] = 'mykey';
430
                        }
431
                        if (strpos($fieldName, '__VALUE__')) {
432
                            $additionalClasses[] = 'myvalue';
433
                        }
434
                        if (isset($fieldDetailsInner[2])) {
435
                            $source = $fieldDetailsInner[2];
436
                            asort($source);
437
                            $source = $this->prependNullOption($source);
438
                            $tempField = $fieldType::create($fieldName, '', $source);
439
                        } else {
440
                            $tempField = $fieldType::create($fieldName, '');
441
                        }
442
                        if (count($additionalClasses)) {
443
                            $classes = implode(' ', $additionalClasses);
444
                            $tempField->addExtraClass($classes);
445
                        }
446
                        $subCompositeField->push($tempField);
447
                    }
448
                    $compositeField->push($subCompositeField);
449
                } else {
450
                    $fieldName = $fieldDetails[0];
451
                    if (isset($formFieldsWithMultiple[$fieldName])) {
452
                        $subCompositeField = \CompositeField::create();
453
                        $subCompositeField->addExtraClass('InnerComposite pos'.$innerCount);
454
                    } else {
455
                        $subCompositeField = null;
456
                    }
457
                    $fieldType = $fieldDetails[1];
458
                    if ($fieldType === 'DropdownField') {
459
                        $source = $fieldDetails[2];
460
                        asort($source);
461
                        $source = $this->prependNullOption($source);
462
                        $myTempfield = $fieldType::create($fieldName, '', $source);
463
                    } elseif ($fieldType === 'HeaderField') {
464
                        $title = str_replace('_', ' ', $fieldDetails[2]);
465
                        $myTempfield = $fieldType::create($fieldName, $title);
466
                    } elseif ($fieldType === 'LiteralField') {
467
                        $title = $fieldDetails[2];
468
                        $myTempfield = $fieldType::create($fieldName, $title);
469
                    } else {
470
                        $myTempfield = $fieldType::create($fieldName, '');
471
                    }
472
                    if ($subCompositeField) {
473
                        $subCompositeField->push($myTempfield);
474
                        $compositeField->push($subCompositeField);
475
                    } else {
476
                        $compositeField->push($myTempfield);
477
                    }
478
                }
479
            }
480
            $finalFields->push($compositeField);
481
        }
482
        $actions = \FieldList::create(
483
            [\FormAction::create('do'.strtolower($formName), $actionTitle)]
484
        );
485
486
        $form = \Form::create($this, $formName, $finalFields, $actions);
487
        $form->setFormAction($this->Link($formName));
488
        $form->loadDataFrom($this->retrieveData());
489
490
        return $form;
491
    }
492
493
    /**
494
     * returns an array of fields
495
     * @return array
496
     */
497
    protected function additionalPrimaryFields()
498
    {
499
        return [];
500
    }
501
502
    protected function saveData($name, $data)
503
    {
504
        unset($data['url']);
505
        unset($data['SecurityID']);
506
        if (is_array($data)) {
507
            foreach ($data as $key => $value) {
508
                if (strpos($key, 'action_') === 0) {
509
                    unset($data[$key]);
510
                }
511
            }
512
        }
513
        $var = $this->Config()->get('form_data_session_variable');
514
        \Session::clear($var.$name);
515
        \Session::save();
516
        \Session::set($var.$name, null);
517
        \Session::save();
518
        \Session::set($var.$name, $data);
519
        \Session::save();
520
    }
521
522
    private $_data = null;
523
524
    protected function retrieveData()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
525
    {
526
        if (! $this->_data) {
527
            $var = $this->Config()->get('form_data_session_variable');
528
            $retrieveDataPrimary = \Session::get($var.'_PrimaryForm');
529
            if ($retrieveDataPrimary && (is_array($retrieveDataPrimary) || is_object($retrieveDataPrimary))) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
530
                //do nothing
531
            } else {
532
                $retrieveDataPrimary = [];
533
            }
534
            $retrieveDataSecondary = \Session::get($var.'_SecondaryForm');
535
            if ($retrieveDataSecondary && (is_array($retrieveDataSecondary) || is_object($retrieveDataSecondary))) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
536
                //do nothing
537
            } else {
538
                $retrieveDataSecondary = [];
539
            }
540
            $this->_data = $retrieveDataPrimary + $retrieveDataSecondary;
541
        }
542
543
        return $this->_data;
544
    }
545
546
    private $_processed_data = null;
547
548
    protected function processedFormData($data = null)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
549
    {
550
        if (! $this->_processed_data) {
551
            if (! $data) {
552
                $data = $this->retrieveData();
553
            }
554
            $array = [];
555
            foreach ($data as $key => $value) {
556
                if ($key && $value) {
557
                    if (
558
                        strpos($key, '__KEY__') ||
559
                        strpos($key, '__VALUE__')
560
                    ) {
561
                        $parts = explode('__', $key);
562
                        if (!isset($array[$parts[0]])) {
563
                            $array[$parts[0]] = [];
564
                        }
565
                        if (! isset($array[$parts[0]][$parts[2]])) {
566
                            $array[$parts[0]][$parts[2]] = [];
567
                        }
568
                        $array[$parts[0]][$parts[2]][$parts[1]] = $value;
569
                    } elseif (substr($key, 0, 3) === 'can') {
570
                        $array[$key] = $this->MyCanMethodBuilder($key, $value);
571
                    } else {
572
                        $array[$key] = $value;
573
                    }
574
                }
575
            }
576
            foreach ($array as $field => $values) {
577
                $alInner = \ArrayList::create();
578
                if (is_array($values)) {
579
                    foreach ($values as $key => $valuePairs) {
580
                        if (isset($valuePairs['KEY']) && isset($valuePairs['VALUE'])) {
581
                            if ($valuePairs['VALUE'] == 'true') {
582
                                $valuePairArray = [
583
                                    'Key' => $valuePairs['KEY'],
584
                                    'UnquotedValue' => $valuePairs['VALUE'],
585
                                ];
586
                            } else {
587
                                $valuePairArray = [
588
                                    'Key' => $valuePairs['KEY'],
589
                                    'Value' => $valuePairs['VALUE'],
590
                                ];
591
                            }
592
                            $alInner->push(\ArrayData::create($valuePairArray));
593
                        }
594
                    }
595
                    $array[$field] = $alInner;
596
                } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
597
                    //do nothing
598
                }
599
            }
600
            $this->_processed_data = \ArrayData::create($array);
601
        }
602
603
        return $this->_processed_data;
604
    }
605
606
607
    protected function resultsTemplateForBuilder()
608
    {
609
        return str_replace(__NAMESPACE__ .'\\', '', $this->class).'Results';
610
    }
611
612
613
    protected function prependNullOption($source)
614
    {
615
        $source = ['' => '--- Please Select ---'] + $source;
616
617
        return $source;
618
    }
619
620
621
    protected function myAPI()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
622
    {
623
        $class = $this->apiProvider;
624
625
        return $class::inst($this->myBaseClass, $this->processedFormData());
626
    }
627
628
    protected function addKeysToThingsToBuild($array)
629
    {
630
        $newArray = [];
631
        $fields = [
632
            'Name',
633
            'SourceMethod1',
634
            'SourceMethod2',
635
            'IsMultiple'
636
        ];
637
        foreach ($array as $arrayRowKey => $arrayRowValues) {
638
            $newArray[$arrayRowKey] = [];
639
            foreach ($arrayRowValues as $arrayColumnKey => $arrayColumnValue) {
640
                $newArray[$arrayRowKey][$fields[$arrayColumnKey]] = $arrayColumnValue;
641
            }
642
        }
643
644
        return $newArray;
645
    }
646
}
647