Passed
Push — master ( 954af2...d7a453 )
by Julito
09:56
created

CourseDescriptionController::add()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 67
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 49
c 0
b 0
f 0
nc 5
nop 0
dl 0
loc 67
rs 8.4905

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\CoreBundle\Framework\Container;
6
use Chamilo\CourseBundle\Entity\CCourseDescription;
7
8
/**
9
 * Class CourseDescriptionController
10
 * This file contains class used like controller,
11
 * it should be included inside a dispatcher file (e.g: index.php).
12
 *
13
 * @author Christian Fasanando <[email protected]>
14
 */
15
class CourseDescriptionController
16
{
17
    private $toolname;
18
19
    /**
20
     * Constructor.
21
     */
22
    public function __construct()
23
    {
24
        $this->toolname = 'course_description';
25
    }
26
27
    public function getToolbar()
28
    {
29
        $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
30
        $course_description = new CourseDescription();
31
        $list = $course_description->get_default_description_title();
32
        $iconList = $course_description->get_default_description_icon();
33
        $actions = '';
34
        $actionLeft = '';
35
        if ($is_allowed_to_edit) {
36
            $categories = [];
37
            foreach ($list as $id => $title) {
38
                $categories[$id] = $title;
39
            }
40
            $categories[ADD_BLOCK] = get_lang('Other');
41
            $i = 1;
42
43
            ksort($categories);
44
            foreach ($categories as $id => $title) {
45
                if (ADD_BLOCK == $i) {
46
                    $actionLeft .= '<a href="index.php?'.api_get_cidreq().'&action=add">'.
47
                        Display::return_icon(
48
                            $iconList[$id],
49
                            $title,
50
                            '',
51
                            ICON_SIZE_MEDIUM
52
                        ).
53
                        '</a>';
54
                    break;
55
                } else {
56
                    $actionLeft .= '<a href="index.php?action=edit&'.api_get_cidreq().'&description_type='.$id.'">'.
57
                        Display::return_icon(
58
                            $iconList[$id],
59
                            $title,
60
                            '',
61
                            ICON_SIZE_MEDIUM
62
                        ).
63
                        '</a>';
64
                    $i++;
65
                }
66
            }
67
            $actions = Display::toolbarAction('toolbar', [0 => $actionLeft]);
68
        }
69
70
        return $actions;
71
    }
72
73
    /**
74
     * It's used for listing course description,
75
     * render to listing view.
76
     *
77
     * @param bool    true for listing history (optional)
78
     * @param array    message for showing by action['edit','add','destroy'] (optional)
79
     */
80
    public function listing($history = false, $messages = [])
81
    {
82
        $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
83
        $course_description = new CourseDescription();
84
        $session_id = api_get_session_id();
85
        $data = [];
86
        $course_description->set_session_id($session_id);
87
        $data['descriptions'] = $course_description->get_description_data();
88
        $data['default_description_titles'] = $course_description->get_default_description_title();
89
        $data['default_description_title_editable'] = $course_description->get_default_description_title_editable();
90
        $data['default_description_icon'] = $course_description->get_default_description_icon();
91
        $data['messages'] = $messages;
92
93
        api_protect_course_script(true);
94
95
        // Prepare confirmation code for item deletion
96
        global $htmlHeadXtra;
97
        $htmlHeadXtra[] = "<script>
98
        function confirmation(name) {
99
            if (confirm(\" ".trim(get_lang('Are you sure to delete'))." \"+name+\"?\")) {
100
                return true;
101
            } else {
102
                return false;
103
            }
104
        }
105
        </script>";
106
107
        /*foreach ($data['descriptions'] as $id => $description) {
108
            if (!empty($description['content'])
109
                && false !== strpos($description['content'], '<iframe')
110
            ) {
111
                header("X-XSS-Protection: 0");
112
            }
113
            // Add an escape version for the JS code of delete confirmation
114
            if ($description) {
115
                $data['descriptions'][$id]['title_js'] = addslashes(strip_tags($description['title']));
116
            }
117
        }*/
118
        $actions = self::getToolbar();
0 ignored issues
show
Bug Best Practice introduced by
The method CourseDescriptionController::getToolbar() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

118
        /** @scrutinizer ignore-call */ 
119
        $actions = self::getToolbar();
Loading history...
119
120
        $tpl = new Template(get_lang('Description'));
121
        $tpl->assign('listing', $data);
122
        $tpl->assign('is_allowed_to_edit', $is_allowed_to_edit);
123
        $tpl->assign('actions', $actions);
124
        $tpl->assign('session_id', $session_id);
125
        $templateName = $tpl->get_template('course_description/index.tpl');
126
        $content = $tpl->fetch($templateName);
127
        $tpl->assign('content', $content);
128
        $tpl->display_one_col_template();
129
    }
130
131
    /**
132
     * It's used for editing a course description,
133
     * render to listing or edit view.
134
     *
135
     * @param int $id               description item id
136
     * @param int $description_type description type id
137
     */
138
    public function edit($id, $description_type)
139
    {
140
        $course_description = new CourseDescription();
141
        $session_id = api_get_session_id();
142
        $course_description->set_session_id($session_id);
143
        $data = [];
144
        $affected_rows = null;
145
        if ('POST' === strtoupper($_SERVER['REQUEST_METHOD'])) {
146
            if (!empty($_POST['title']) && !empty($_POST['contentDescription'])) {
147
                $title = $_POST['title'];
148
                $content = $_POST['contentDescription'];
149
                $description_type = $_POST['description_type'];
150
                $id = $_POST['id'];
151
                if (empty($id)) {
152
                    // If the ID was not provided, find the first matching description item given the item type
153
                    $description = $course_description->get_data_by_description_type(
154
                        $description_type
155
                    );
156
                    if (count($description) > 0) {
157
                        $id = $description['iid'];
158
                    }
159
                    // If no corresponding description is found, edit a new one
160
                }
161
                $progress = isset($_POST['progress']) ? $_POST['progress'] : 0;
162
                $repo = Container::getCourseDescriptionRepository();
163
164
                /** @var CCourseDescription $courseDescription */
165
                $courseDescription = $repo->find($id);
166
                if ($courseDescription) {
0 ignored issues
show
introduced by
$courseDescription is of type Chamilo\CourseBundle\Entity\CCourseDescription, thus it always evaluated to true.
Loading history...
167
                    $courseDescription
168
                        ->setTitle($title)
169
                        ->setProgress($progress)
170
                        ->setContent($content)
171
                    ;
172
                    $repo->update($courseDescription);
173
                } else {
174
                    $course_description->set_description_type($description_type);
175
                    $course_description->set_title($title);
176
                    $course_description->set_progress($progress);
177
                    $course_description->set_content($content);
178
                    $course_description->insert(api_get_course_int_id());
179
                }
180
181
                Display::addFlash(
182
                    Display::return_message(
183
                        get_lang('The description has been updated')
184
                    )
185
                );
186
187
                $url = api_get_path(WEB_CODE_PATH).'course_description/index.php?'.api_get_cidreq();
188
                api_location($url);
189
            }
190
        } else {
191
            $default_description_titles = $course_description->get_default_description_title();
192
            $default_description_title_editable = $course_description->get_default_description_title_editable();
193
            $default_description_icon = $course_description->get_default_description_icon();
194
            $question = $course_description->get_default_question();
195
            $information = $course_description->get_default_information();
196
            $description_type = $description_type;
197
            if (empty($id)) {
198
                // If the ID was not provided, find the first matching description item given the item type
199
                $description = $course_description->get_data_by_description_type($description_type);
200
                if (count($description) > 0) {
201
                    $id = $description['id'];
202
                }
203
                // If no corresponding description is found, edit a new one
204
            }
205
            if (!empty($id)) {
206
                if (isset($_GET['id_session'])) {
207
                    $session_id = intval($_GET['id_session']);
208
                }
209
                $course_description_data = $course_description->get_data_by_id(
210
                    $id,
211
                    null,
212
                    $session_id
213
                );
214
                $description_type = $course_description_data['description_type'];
215
                $description_title = $course_description_data['description_title'];
216
                $description_content = $course_description_data['description_content'];
217
                $progress = $course_description_data['progress'];
218
                $descriptions = $course_description->get_data_by_description_type(
219
                    $description_type,
220
                    null,
221
                    $session_id
222
                );
223
            }
224
225
            if (empty($id)) {
226
                $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : '';
227
                if (empty($id)) {
228
                    // If the ID was not provided, find the first matching description item given the item type
229
                    $course_description = new CourseDescription();
230
                    $description = $course_description->get_data_by_description_type($description_type);
231
                    if (count($description) > 0) {
232
                        $id = $description['id'];
233
                    }
234
                    // If no corresponding description is found, edit a new one
235
                    unset($course_description);
236
                }
237
            }
238
            $original_id = $id;
239
            // display categories
240
            $categories = [];
241
            foreach ($default_description_titles as $id => $title) {
0 ignored issues
show
introduced by
$id is overwriting one of the parameters of this function.
Loading history...
242
                $categories[$id] = $title;
243
            }
244
            $categories[ADD_BLOCK] = get_lang('Other');
245
246
            // default header title form
247
            $description_type = intval($description_type);
248
            $header = $default_description_titles[$description_type];
249
            if ($description_type >= ADD_BLOCK) {
250
                $header = $default_description_titles[ADD_BLOCK];
251
            }
252
253
            // display form
254
            $form = new FormValidator(
255
                'course_description',
256
                'POST',
257
                'index.php?action=edit&id='.$original_id.'&description_type='.$description_type.'&'.api_get_cidreq()
258
            );
259
            $form->addElement('header', $header);
260
            $form->addElement('hidden', 'id', $original_id);
261
            $form->addElement('hidden', 'description_type', $description_type);
262
            //$form->addElement('hidden', 'sec_token', $token);
263
264
            if (api_get_configuration_value('save_titles_as_html')) {
265
                $form->addHtmlEditor(
266
                    'title',
267
                    get_lang('Title'),
268
                    true,
269
                    false,
270
                    ['ToolbarSet' => 'TitleAsHtml']
271
                );
272
            } else {
273
                $form->addText('title', get_lang('Title'));
274
                $form->applyFilter('title', 'html_filter');
275
            }
276
            $form->addHtmlEditor(
277
                'contentDescription',
278
                get_lang('Content'),
279
                true,
280
                false,
281
                [
282
                    'ToolbarSet' => 'Basic',
283
                    'Width' => '100%',
284
                    'Height' => '200',
285
                ]
286
            );
287
            $form->addButtonCreate(get_lang('Save'));
288
289
            $actions = self::getToolbar();
0 ignored issues
show
Bug Best Practice introduced by
The method CourseDescriptionController::getToolbar() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

289
            /** @scrutinizer ignore-call */ 
290
            $actions = self::getToolbar();
Loading history...
290
            // Set some default values
291
            if (!empty($description_title)) {
292
                $default['title'] = Security::remove_XSS($description_title);
0 ignored issues
show
Comprehensibility Best Practice introduced by
$default was never initialized. Although not strictly required by PHP, it is generally a good practice to add $default = array(); before regardless.
Loading history...
293
            }
294
            if (!empty($description_content)) {
295
                $default['contentDescription'] = Security::remove_XSS($description_content, COURSEMANAGERLOWSECURITY);
296
            }
297
            $default['description_type'] = $description_type;
298
299
            $form->setDefaults($default);
300
301
            if (isset($question[$description_type])) {
302
                $message = '<strong>'.get_lang('Help').'</strong><br />';
303
                $message .= $question[$description_type];
304
                Display::addFlash(Display::return_message($message, 'normal', false));
305
            }
306
            $tpl = new Template(get_lang('Description'));
307
            //$tpl->assign('is_allowed_to_edit', $is_allowed_to_edit);
308
            $tpl->assign('actions', $actions);
309
            $tpl->assign('session_id', $session_id);
310
            $tpl->assign('content', $form->returnForm());
311
            $tpl->display_one_col_template();
312
313
        }
314
    }
315
316
    /**
317
     * It's used for adding a course description,
318
     * render to listing or add view.
319
     */
320
    public function add()
321
    {
322
        $course_description = new CourseDescription();
323
        $session_id = api_get_session_id();
324
        $course_description->set_session_id($session_id);
325
        $actions = self::getToolbar();
0 ignored issues
show
Bug Best Practice introduced by
The method CourseDescriptionController::getToolbar() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

325
        /** @scrutinizer ignore-call */ 
326
        $actions = self::getToolbar();
Loading history...
326
327
        if ('POST' === strtoupper($_SERVER['REQUEST_METHOD'])) {
328
            if (!empty($_POST['title']) && !empty($_POST['contentDescription'])) {
329
                $title = $_POST['title'];
330
                $content = $_POST['contentDescription'];
331
                $description_type = $_POST['description_type'];
332
                if ($description_type >= ADD_BLOCK) {
333
                    $course_description->set_description_type($description_type);
334
                    $course_description->set_title($title);
335
                    $course_description->set_content($content);
336
                    $course_description->insert(api_get_course_int_id());
337
                }
338
339
                Display::addFlash(
340
                    Display::return_message(
341
                        get_lang('The description has been added')
342
                    )
343
                );
344
                $url = api_get_path(WEB_CODE_PATH).'course_description/index.php?'.api_get_cidreq();
345
                api_location($url);
346
            }
347
        } else {
348
            // display form
349
            $form = new FormValidator(
350
                'course_description',
351
                'POST',
352
                'index.php?action=add&'.api_get_cidreq()
353
            );
354
            //$form->addElement('header', $header);
355
            $form->addElement('hidden', 'description_type', ADD_BLOCK);
356
            if (api_get_configuration_value('save_titles_as_html')) {
357
                $form->addHtmlEditor(
358
                    'title',
359
                    get_lang('Title'),
360
                    true,
361
                    false,
362
                    ['ToolbarSet' => 'TitleAsHtml']
363
                );
364
            } else {
365
                $form->addText('title', get_lang('Title'));
366
                $form->applyFilter('title', 'html_filter');
367
            }
368
            $form->addHtmlEditor(
369
                'contentDescription',
370
                get_lang('Content'),
371
                true,
372
                false,
373
                [
374
                    'ToolbarSet' => 'Basic',
375
                    'Width' => '100%',
376
                    'Height' => '200',
377
                ]
378
            );
379
            $form->addButtonCreate(get_lang('Save'));
380
381
            $tpl = new Template(get_lang('Description'));
382
            //$tpl->assign('is_allowed_to_edit', $is_allowed_to_edit);
383
            $tpl->assign('actions', $actions);
384
            $tpl->assign('session_id', $session_id);
385
            $tpl->assign('content', $form->returnForm());
386
            $tpl->display_one_col_template();
387
        }
388
    }
389
390
    /**
391
     * It's used for destroy a course description,
392
     * render to listing view.
393
     *
394
     * @param int $id description type
395
     */
396
    public function delete($id)
397
    {
398
        $course_description = new CourseDescription();
399
        $session_id = api_get_session_id();
400
        $course_description->set_session_id($session_id);
401
        if (!empty($id)) {
402
            $course_description->delete($id);
403
            Display::addFlash(
404
                Display::return_message(get_lang('Description has been deleted'))
405
            );
406
        }
407
408
        $url = api_get_path(WEB_CODE_PATH).'course_description/index.php?'.api_get_cidreq();
409
        api_location($url);
410
    }
411
}
412