Passed
Pull Request — 1.11.x (#3859)
by Angel Fernando Quiroz
09:48
created

displayForm()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 76
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 42
c 1
b 0
f 0
nc 7
nop 1
dl 0
loc 76
rs 8.9368

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CourseBundle\Entity\CLp;
6
use Chamilo\CourseBundle\Entity\CLpView;
7
use Symfony\Component\HttpFoundation\Request as HttpRequest;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, HttpRequest. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
8
9
require_once __DIR__.'/../global.inc.php';
10
11
api_protect_course_script(true);
12
13
$httpRequest = HttpRequest::createFromGlobals();
14
15
$isAllowedToEdit = api_is_allowed_to_edit();
16
17
switch ($httpRequest->get('a')) {
18
    case 'form_adquisition':
19
        displayForm(
20
            $httpRequest->query->getInt('lp_view')
21
        );
22
        break;
23
    case 'views_invisible':
24
        processViewsInvisible(
25
            $httpRequest->request->get('chkb_view') ?: [],
26
            $httpRequest->request->getBoolean('state')
27
        );
28
        break;
29
}
30
31
function displayForm(int $lpViewId)
32
{
33
    $em = Database::getManager();
34
35
    $lpView = $em->find(CLpView::class, $lpViewId);
36
37
    if (null === $lpView) {
38
        return;
39
    }
40
41
    $lp = $em->find(CLp::class, $lpView->getLpId());
42
43
    $extraField = new ExtraField('lp_view');
44
    $field = $extraField->get_handler_field_info_by_field_variable(StudentFollowPage::VARIABLE_ACQUISITION);
45
46
    $extraFieldValue = new ExtraFieldValue('lp_view');
47
    $value = $extraFieldValue->get_values_by_handler_and_field_variable(
48
        $lpViewId,
49
        StudentFollowPage::VARIABLE_ACQUISITION
50
    );
51
52
    $options = [];
53
54
    foreach ($field['options'] as $option) {
55
        $options[$option['option_value']] = $option['display_text'];
56
    }
57
58
    $frmId = 'frm_lp_acquisition_'.$lpView->getLpId();
59
    $frmAction = api_get_self().'?'.http_build_query(['lp_view' => $lpViewId, 'a' => 'form_adquisition']);
60
61
    $form = new FormValidator($frmId, 'post', $frmAction);
62
    $form->addRadio(StudentFollowPage::VARIABLE_ACQUISITION, get_lang('Acquisition'), $options);
63
    $form->addHidden('lp_view', $lpViewId);
64
    $form->addButtonSave(get_lang('Save'));
65
66
    if ($form->validate()) {
67
        $values = $form->exportValues();
68
69
        $extraFieldValue = new ExtraFieldValue('lp_view');
70
        $extraFieldValue->save(
71
            [
72
                'variable' => StudentFollowPage::VARIABLE_ACQUISITION,
73
                'item_id' => $lpViewId,
74
                'comment' => json_encode(['user' => api_get_user_id(), 'datetime' => api_get_utc_datetime()]),
75
                'value' => $values[StudentFollowPage::VARIABLE_ACQUISITION]
76
            ]
77
        );
78
79
        echo StudentFollowPage::getLpAcquisition(
80
            [
81
                'iid' => $lp->getIid(),
82
                'lp_name' => $lp->getName(),
83
            ],
84
            $lpView->getUserId(),
85
            $lpView->getCId(),
86
            $lpView->getSessionId(),
87
            true
88
        );
89
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
90
    }
91
92
    if (!empty($value)) {
93
        $form->setDefaults([StudentFollowPage::VARIABLE_ACQUISITION => $value['value']]);
94
    }
95
96
    echo $form->returnForm()
97
        ."<script>$(function () {
98
            $('#$frmId').on('submit', function (e) {
99
                e.preventDefault();
100
101
                var self = $(this);
102
103
                self.find(':submit').prop('disabled', true);
104
105
                $.post(this.action, self.serialize()).done(function (response) {
106
                    $('#acquisition-$lpViewId').html(response);
107
108
                    $('#global-modal').modal('hide');
109
110
                    self.find(':submit').prop('disabled', false);
111
                });
112
            })
113
        })</script>";
114
}
115
116
function processViewsInvisible(array $lpViewsIds, bool $state)
117
{
118
    $lpViewsIds = array_map('intval', $lpViewsIds);
119
    $lpViewsIds = array_filter($lpViewsIds);
120
121
    if (empty($lpViewsIds)) {
122
        return;
123
    }
124
125
    foreach ($lpViewsIds as $lpViewId) {
126
        $extraFieldValue = new ExtraFieldValue('lp_view');
127
        $extraFieldValue->save(
128
            [
129
                'variable' => StudentFollowPage::VARIABLE_INVISIBLE,
130
                'item_id' => $lpViewId,
131
                'comment' => json_encode(['user' => api_get_user_id(), 'datetime' => api_get_utc_datetime()]),
132
                'value' => !$state,
133
            ]
134
        );
135
    }
136
137
}
138