Passed
Pull Request — master (#7159)
by
unknown
09:00
created

CourseDescriptionController::listing()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 55
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 35
nc 3
nop 2
dl 0
loc 55
rs 9.36
c 0
b 0
f 0

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::getMdiIcon($iconList[$id], 'ch-tool-icon', null, 32, $title).
48
                        '</a>';
49
                    break;
50
                } else {
51
                    $actionLeft .= '<a href="index.php?action=edit&'.api_get_cidreq().'&description_type='.$id.'">'.
52
                        Display::getMdiIcon($iconList[$id], 'ch-tool-icon', null, 32, $title).
53
                        '</a>';
54
                    $i++;
55
                }
56
            }
57
            $actions = Display::toolbarAction('toolbar', [$actionLeft]);
58
        }
59
60
        return $actions;
61
    }
62
63
    /**
64
     * It's used for listing course description,
65
     * render to listing view.
66
     *
67
     * @param bool    true for listing history (optional)
68
     * @param array    message for showing by action['edit','add','destroy'] (optional)
69
     */
70
    public function listing($history = false, $messages = [])
71
    {
72
        $is_allowed_to_edit = api_is_allowed_to_edit(null, true);
73
        $course_description = new CourseDescription();
74
        $session_id = api_get_session_id();
75
        $data = [];
76
        $course_description->set_session_id($session_id);
77
        $descriptions = $course_description->get_description_data();
78
79
        $data['descriptions'] = [];
80
        foreach ($descriptions as $description) {
81
            $description_data = [
82
                'iid' => $description->getIid(),
83
                'title' => $description->getTitle(),
84
                'content' => $description->getContent(),
85
                'descriptionType' => $description->getDescriptionType(),
86
                'resourceNode' => $description->getResourceNode(),
87
                'sessionId' => $description->getFirstResourceLink()->getSession() ? $description->getFirstResourceLink()->getSession()->getId() : null,
88
            ];
89
            $description_data['icon_session'] = api_get_session_image($description->getFirstResourceLink()->getSession()?->getId(), api_get_user_entity());
90
            $data['descriptions'][] = $description_data;
91
        }
92
93
        $data['default_description_titles'] = $course_description->get_default_description_title();
94
        $data['default_description_title_editable'] = $course_description->get_default_description_title_editable();
95
        $data['default_description_icon'] = $course_description->get_default_description_icon();
96
        $data['messages'] = $messages;
97
98
        api_protect_course_script(true);
99
100
        // Prepare confirmation code for item deletion
101
        global $htmlHeadXtra;
102
        $htmlHeadXtra[] = "<script>
103
    function confirmation(name) {
104
        if (confirm(\" ".trim(get_lang('Are you sure to delete'))." \"+name+\"?\")) {
105
            return true;
106
        } else {
107
            return false;
108
        }
109
    }
110
    </script>";
111
112
        $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

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

308
            /** @scrutinizer ignore-call */ 
309
            $actions = self::getToolbar();
Loading history...
309
            // Set some default values
310
            if (!empty($description_title)) {
311
                $default['title'] = Security::remove_XSS($description_title);
312
            }
313
            if (!empty($description_content)) {
314
                $default['contentDescription'] = Security::remove_XSS($description_content, COURSEMANAGERLOWSECURITY);
315
            }
316
            $default['description_type'] = $description_type;
317
318
            $form->setDefaults($default);
319
320
            if (isset($question[$description_type])) {
321
                $message = '<strong>'.get_lang('Help').'</strong><br />';
322
                $message .= $question[$description_type];
323
                Display::addFlash(Display::return_message($message, 'normal', false));
324
            }
325
            $tpl = new Template(get_lang('Description'));
326
            //$tpl->assign('is_allowed_to_edit', $is_allowed_to_edit);
327
            $tpl->assign('actions', $actions);
328
            $tpl->assign('session_id', $session_id);
329
            $tpl->assign('content', $form->returnForm());
330
            $tpl->display_one_col_template();
331
        }
332
    }
333
334
    /**
335
     * It's used for adding a course description,
336
     * render to listing or add view.
337
     */
338
    public function add()
339
    {
340
        $course_description = new CourseDescription();
341
        $session_id = api_get_session_id();
342
        $course_description->set_session_id($session_id);
343
        $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

343
        /** @scrutinizer ignore-call */ 
344
        $actions = self::getToolbar();
Loading history...
344
345
        if ('POST' === strtoupper($_SERVER['REQUEST_METHOD'])) {
346
            if (!empty($_POST['title']) && !empty($_POST['contentDescription'])) {
347
                $title            = $_POST['title'];
348
                $content          = $_POST['contentDescription'];
349
                $description_type = $_POST['description_type'];
350
351
                $searchEnabled = api_get_setting('search.search_enabled');
352
                $enableSearch  = $searchEnabled === 'true' && !empty($_POST['enable_search']);
353
354
                if ($description_type >= ADD_BLOCK) {
355
                    $course_description->set_description_type($description_type);
356
                    $course_description->set_title($title);
357
                    $course_description->set_content($content);
358
359
                    // Pass flag
360
                    $course_description->insert($enableSearch);
361
                }
362
363
                Display::addFlash(
364
                    Display::return_message(
365
                        get_lang('Course Description added')
366
                    )
367
                );
368
                $url = api_get_path(WEB_CODE_PATH).'course_description/index.php?'.api_get_cidreq();
369
                api_location($url);
370
            }
371
        } else {
372
            // display form
373
            $form = new FormValidator(
374
                'course_description',
375
                'POST',
376
                'index.php?action=add&'.api_get_cidreq()
377
            );
378
            $form->addElement('hidden', 'description_type', ADD_BLOCK);
379
            if ('true' === api_get_setting('editor.save_titles_as_html')) {
380
                $form->addHtmlEditor(
381
                    'title',
382
                    get_lang('Title'),
383
                    true,
384
                    false,
385
                    ['ToolbarSet' => 'TitleAsHtml']
386
                );
387
            } else {
388
                $form->addText('title', get_lang('Title'));
389
                $form->applyFilter('title', 'html_filter');
390
            }
391
            $form->addHtmlEditor(
392
                'contentDescription',
393
                get_lang('Content'),
394
                true,
395
                false,
396
                [
397
                    'ToolbarSet' => 'Basic',
398
                    'Width' => '100%',
399
                    'Height' => '200',
400
                ]
401
            );
402
403
            if ('true' === api_get_setting('search.search_enabled')) {
404
                $form->addCheckBox(
405
                    'enable_search',
406
                    null,
407
                    get_lang('Index this description in global search')
408
                );
409
410
                $form->setDefaults([
411
                    'enable_search' => 1,
412
                ]);
413
            }
414
415
            $form->addButtonCreate(get_lang('Save'));
416
417
            $tpl = new Template(get_lang('Description'));
418
            $tpl->assign('actions', $actions);
419
            $tpl->assign('session_id', $session_id);
420
            $tpl->assign('content', $form->returnForm());
421
            $tpl->display_one_col_template();
422
        }
423
    }
424
425
    /**
426
     * It's used for destroy a course description,
427
     * render to listing view.
428
     *
429
     * @param int $id description type
430
     */
431
    public function delete($id)
432
    {
433
        $course_description = new CourseDescription();
434
        $session_id = api_get_session_id();
435
        $course_description->set_session_id($session_id);
436
        if (!empty($id)) {
437
            $course_description->delete($id);
438
            Display::addFlash(
439
                Display::return_message(get_lang('Description has been deleted'))
440
            );
441
        }
442
443
        $url = api_get_path(WEB_CODE_PATH).'course_description/index.php?'.api_get_cidreq();
444
        api_location($url);
445
    }
446
}
447