Passed
Push — master ( 6eaef8...9a3a70 )
by Angel Fernando Quiroz
08:17
created

PlatformConfigurationController::list()   D

Complexity

Conditions 12
Paths 192

Size

Total Lines 159
Code Lines 128

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 2 Features 1
Metric Value
cc 12
eloc 128
c 6
b 2
f 1
nc 192
nop 3
dl 0
loc 159
rs 4.96

How to fix   Long Method    Complexity   

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
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Controller;
8
9
use Bbb;
10
use Chamilo\CoreBundle\Helpers\AuthenticationConfigHelper;
11
use Chamilo\CoreBundle\Helpers\ThemeHelper;
12
use Chamilo\CoreBundle\Helpers\TicketProjectHelper;
13
use Chamilo\CoreBundle\Helpers\UserHelper;
14
use Chamilo\CoreBundle\Repository\Node\CourseRepository;
15
use Chamilo\CoreBundle\Settings\SettingsManager;
16
use Chamilo\CoreBundle\Traits\ControllerTrait;
17
use Chamilo\CourseBundle\Settings\SettingsCourseManager;
18
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
19
use Symfony\Component\HttpFoundation\JsonResponse;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\HttpFoundation\Response;
22
use Symfony\Component\Routing\Attribute\Route;
23
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
24
use Throwable;
25
26
#[Route('/platform-config')]
27
class PlatformConfigurationController extends AbstractController
28
{
29
    use ControllerTrait;
30
31
    public function __construct(
32
        private readonly TicketProjectHelper $ticketProjectHelper,
33
        private readonly UserHelper $userHelper,
34
        private readonly ThemeHelper $themeHelper,
35
    ) {}
36
37
    #[Route('/list', name: 'platform_config_list', methods: ['GET'])]
38
    public function list(
39
        SettingsManager $settingsManager,
40
        AuthenticationConfigHelper $authenticationConfigHelper,
41
        UrlGeneratorInterface $urlGenerator,
42
    ): Response {
43
        $requestSession = $this->getRequest()->getSession();
44
45
        $enabledOAuthProviders = $authenticationConfigHelper->getEnabledOAuthProviders();
46
        $forcedLoginMethod = $authenticationConfigHelper->getForcedLoginMethod();
47
48
        if ($forcedLoginMethod) {
49
            if (\in_array($forcedLoginMethod, array_keys($enabledOAuthProviders))) {
50
                $enabledOAuthProviders = [$forcedLoginMethod => $enabledOAuthProviders[$forcedLoginMethod]];
51
            } else {
52
                $enabledOAuthProviders = [];
53
            }
54
        }
55
56
        $configuration = [
57
            'settings' => [],
58
            'studentview' => $requestSession->get('studentview'),
59
            'plugins' => [],
60
            'visual_theme' => $this->themeHelper->getVisualTheme(),
61
            'oauth2_providers' => array_map(
62
                fn ($providerName, $providerParams) => [
63
                    'name' => $providerName,
64
                    'title' => $providerParams['title'] ?? ucwords($providerName),
65
                    'url' => $urlGenerator->generate(\sprintf('chamilo.oauth2_%s_start', $providerName)),
66
                ],
67
                array_keys($enabledOAuthProviders),
68
                $enabledOAuthProviders
69
            ),
70
            'ldap_auth' => null,
71
            'forced_login_method' => $forcedLoginMethod,
72
        ];
73
74
        $ldapConfig = $authenticationConfigHelper->getLdapConfig();
75
76
        if ($ldapConfig['enabled'] && \in_array($forcedLoginMethod, ['ldap', null], true)) {
77
            $configuration['ldap_auth'] = [
78
                'enabled' => true,
79
                'title' => $ldapConfig['title'],
80
            ];
81
        }
82
83
        $configuration['settings']['registration.allow_registration'] = $settingsManager->getSetting('registration.allow_registration', true);
84
        $configuration['settings']['catalog.course_catalog_published'] = $settingsManager->getSetting('catalog.course_catalog_published', true);
85
        $configuration['settings']['catalog.hide_public_link'] = $settingsManager->getSetting('catalog.hide_public_link', true);
86
        $configuration['settings']['catalog.course_catalog_display_in_home'] = $settingsManager->getSetting('catalog.course_catalog_display_in_home', true);
87
        $configuration['settings']['catalog.only_show_course_from_selected_category'] = $settingsManager->getSetting('catalog.only_show_course_from_selected_category', true);
88
        $configuration['settings']['catalog.allow_students_to_browse_courses'] = $settingsManager->getSetting('catalog.allow_students_to_browse_courses', true);
89
        $configuration['settings']['catalog.allow_session_auto_subscription'] = $settingsManager->getSetting('catalog.allow_session_auto_subscription', true);
90
        $configuration['settings']['catalog.course_subscription_in_user_s_session'] = $settingsManager->getSetting('catalog.course_subscription_in_user_s_session', true);
91
        $rawCourseCatalogSetting = $settingsManager->getSetting('catalog.course_catalog_settings', true);
92
        $configuration['settings']['catalog.course_catalog_settings'] = 'false' !== $rawCourseCatalogSetting ? $this->decodeSettingArray($rawCourseCatalogSetting) : 'false';
93
        $rawSessionCatalogSetting = $settingsManager->getSetting('catalog.session_catalog_settings', true);
94
        $configuration['settings']['catalog.session_catalog_settings'] = 'false' !== $rawSessionCatalogSetting ? $this->decodeSettingArray($rawSessionCatalogSetting) : 'false';
95
        $configuration['settings']['admin.chamilo_latest_news'] = $settingsManager->getSetting('admin.chamilo_latest_news', true);
96
        $configuration['settings']['admin.chamilo_support'] = $settingsManager->getSetting('admin.chamilo_support', true);
97
        $configuration['settings']['platform.session_admin_access_to_all_users_on_all_urls'] = $settingsManager->getSetting('platform.session_admin_access_to_all_users_on_all_urls', true);
98
        $configuration['settings']['profile.login_is_email'] = $settingsManager->getSetting('profile.login_is_email', true);
99
100
        $variables = [];
101
102
        if ($this->isGranted('ROLE_USER')) {
103
            $variables = [
104
                'platform.site_name',
105
                'platform.timezone',
106
                'platform.registered',
107
                'platform.donotlistcampus',
108
                'platform.load_term_conditions_section',
109
                'platform.cookie_warning',
110
                'platform.show_tabs',
111
                'catalog.show_courses_sessions',
112
                'admin.administrator_name',
113
                'admin.administrator_surname',
114
                'editor.enabled_mathjax',
115
                'editor.translate_html',
116
                'display.show_admin_toolbar',
117
                'registration.allow_terms_conditions',
118
                'agenda.allow_personal_agenda',
119
                'agenda.personal_calendar_show_sessions_occupation',
120
                'social.social_enable_messages_feedback',
121
                'social.disable_dislike_option',
122
                'skill.allow_skills_tool',
123
                'gradebook.gradebook_enable_grade_model',
124
                'gradebook.gradebook_dependency',
125
                'course.course_validation',
126
                'course.student_view_enabled',
127
                'course.allow_edit_tool_visibility_in_session',
128
                'session.limit_session_admin_role',
129
                'session.allow_session_admin_read_careers',
130
                'session.limit_session_admin_list_users',
131
                'platform.redirect_index_to_url_for_logged_users',
132
                'language.platform_language',
133
                'language.language_priority_1',
134
                'language.language_priority_2',
135
                'language.language_priority_3',
136
                'language.language_priority_4',
137
                'profile.allow_social_map_fields',
138
                'forum.global_forums_course_id',
139
                'document.students_download_folders',
140
                'social.hide_social_groups_block',
141
                'course.show_course_duration',
142
                'attendance.attendance_allow_comments',
143
                'attendance.multilevel_grading',
144
                'attendance.enable_sign_attendance_sheet',
145
                'exercise.allow_exercise_auto_launch',
146
                'course.access_url_specific_files',
147
                'catalog.show_courses_descriptions_in_catalog',
148
                'session.session_automatic_creation_user_id',
149
                'session.session_list_view_remaining_days',
150
                'profile.use_users_timezone',
151
                'registration.redirect_after_login',
152
                'platform.show_tabs_per_role',
153
                'platform.session_admin_user_subscription_search_extra_field_to_search',
154
                'platform.push_notification_settings',
155
                'session.user_session_display_mode',
156
                'course.resource_sequence_show_dependency_in_course_intro',
157
                'message.allow_message_tool',
158
                'course.hide_scorm_export_link',
159
                'ai_helpers.enable_ai_helpers',
160
                'course.hide_scorm_pdf_link',
161
                'platform.table_default_row',
162
                'platform.table_row_list',
163
                'social.allow_social_tool',
164
            ];
165
166
            $user = $this->userHelper->getCurrent();
167
168
            $configuration['settings']['display.show_link_ticket_notification'] = 'false';
169
170
            if (!empty($user)) {
171
                $userIsAllowedInProject = $this->ticketProjectHelper->userIsAllowInProject(1);
172
173
                if ($userIsAllowedInProject
174
                    && 'true' === $settingsManager->getSetting('display.show_link_ticket_notification')
175
                ) {
176
                    $configuration['settings']['display.show_link_ticket_notification'] = 'true';
177
                }
178
            }
179
180
            $configuration['plugins']['bbb'] = [
181
                'show_global_conference_link' => Bbb::showGlobalConferenceLink([
182
                    'username' => $user->getUserIdentifier(),
183
                    'status' => $user->getStatus(),
184
                ]),
185
                'listingURL' => (new Bbb('', '', true, $user->getId()))->getListingUrl(),
186
            ];
187
        }
188
189
        foreach ($variables as $variable) {
190
            $value = $settingsManager->getSetting($variable, true);
191
192
            $configuration['settings'][$variable] = $value;
193
        }
194
195
        return new JsonResponse($configuration);
196
    }
197
198
    #[Route('/list/course_settings', name: 'course_settings_list', methods: ['GET'])]
199
    public function courseSettingsList(
200
        SettingsCourseManager $courseSettingsManager,
201
        CourseRepository $courseRepository,
202
        Request $request
203
    ): JsonResponse {
204
        $courseId = $request->query->get('cid');
205
        if (!$courseId) {
206
            return new JsonResponse(['error' => 'Course ID is required'], Response::HTTP_BAD_REQUEST);
207
        }
208
209
        $course = $courseRepository->find($courseId);
210
        if (!$course) {
211
            return new JsonResponse(['error' => 'Course not found'], Response::HTTP_NOT_FOUND);
212
        }
213
214
        $courseSettingsManager->setCourse($course);
215
        $settings = [
216
            'show_course_in_user_language' => $courseSettingsManager->getCourseSettingValue('show_course_in_user_language'),
217
            'allow_user_edit_agenda' => $courseSettingsManager->getCourseSettingValue('allow_user_edit_agenda'),
218
            'enable_document_auto_launch' => $courseSettingsManager->getCourseSettingValue('enable_document_auto_launch'),
219
            'enable_exercise_auto_launch' => $courseSettingsManager->getCourseSettingValue('enable_exercise_auto_launch'),
220
            'enable_lp_auto_launch' => $courseSettingsManager->getCourseSettingValue('enable_lp_auto_launch'),
221
            'enable_forum_auto_launch' => $courseSettingsManager->getCourseSettingValue('enable_forum_auto_launch'),
222
            'learning_path_generator' => $courseSettingsManager->getCourseSettingValue('learning_path_generator'),
223
        ];
224
225
        return new JsonResponse(['settings' => $settings]);
226
    }
227
228
    /**
229
     * Attempts to decode a setting value that may be stored as:
230
     * - native PHP array
231
     * - JSON string
232
     * - PHP array code string
233
     */
234
    private function decodeSettingArray(mixed $setting): array
235
    {
236
        // Already an array, return as is
237
        if (\is_array($setting)) {
238
            return $setting;
239
        }
240
241
        // Try to decode JSON string
242
        if (\is_string($setting)) {
243
            $json = json_decode($setting, true);
244
            if (\is_array($json)) {
245
                return $json;
246
            }
247
248
            // Try to evaluate PHP-style array string
249
            $trimmed = rtrim($setting, ';');
250
251
            try {
252
                $evaluated = eval("return $trimmed;");
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
253
                if (\is_array($evaluated)) {
254
                    return $evaluated;
255
                }
256
            } catch (Throwable $e) {
257
                // Log error and continue
258
                error_log('Failed to eval setting value: '.$e->getMessage());
259
            }
260
        }
261
262
        // Return empty array as fallback
263
        return [];
264
    }
265
}
266