Passed
Push — master ( 859bd5...c750b1 )
by Julito
10:16 queued 10s
created

SettingsManager   C

Complexity

Total Complexity 56

Size/Duplication

Total Lines 1021
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 649
dl 0
loc 1021
rs 5.471
c 0
b 0
f 0
wmc 56

19 Methods

Rating   Name   Duplication   Size   Complexity  
A getUrl() 0 3 1
A setUrl() 0 3 1
A __construct() 0 14 1
A getParameters() 0 9 2
A getSchemas() 0 3 1
A getParametersFromKeywordOrderedByCategory() 0 14 2
A convertNameSpaceToService() 0 3 1
A getSetting() 0 31 4
A transformParameters() 0 11 3
A updateSchemas() 0 12 2
C save() 0 123 11
B load() 0 46 9
A renameVariable() 0 28 2
B fixCategory() 0 139 2
A convertServiceToNameSpace() 0 3 1
A getParametersFromKeyword() 0 23 4
B update() 0 63 6
B getVariablesAndCategories() 0 296 1
A installSchemas() 0 12 2

How to fix   Complexity   

Complex Class

Complex classes like SettingsManager 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.

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 SettingsManager, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\SettingsBundle\Manager;
5
6
use Chamilo\CoreBundle\Entity\AccessUrl;
7
use Chamilo\CoreBundle\Entity\Course;
8
use Chamilo\CoreBundle\Entity\SettingsCurrent;
9
use Doctrine\ORM\EntityManager;
10
use Doctrine\ORM\EntityRepository;
11
use Sylius\Bundle\ResourceBundle\Controller\EventDispatcherInterface;
12
use Sylius\Bundle\SettingsBundle\Event\SettingsEvent;
13
use Sylius\Bundle\SettingsBundle\Manager\SettingsManagerInterface;
14
use Sylius\Bundle\SettingsBundle\Model\Settings;
15
use Sylius\Bundle\SettingsBundle\Model\SettingsInterface;
16
use Sylius\Bundle\SettingsBundle\Schema\SchemaInterface;
17
use Sylius\Bundle\SettingsBundle\Schema\SettingsBuilder;
18
use Sylius\Component\Registry\ServiceRegistryInterface;
19
use Sylius\Component\Resource\Factory\FactoryInterface;
20
use Symfony\Component\Validator\ConstraintViolationListInterface;
21
use Symfony\Component\Validator\Exception\ValidatorException;
22
23
/**
24
 * Class SettingsManager.
25
 *
26
 * @package Chamilo\SettingsBundle\Manager
27
 */
28
class SettingsManager implements SettingsManagerInterface
29
{
30
    protected $url;
31
32
    /**
33
     * @var ServiceRegistryInterface
34
     */
35
    protected $schemaRegistry;
36
37
    /**
38
     * @var ServiceRegistryInterface
39
     */
40
    protected $resolverRegistry;
41
42
    /**
43
     * @var EntityManager
44
     */
45
    protected $manager;
46
47
    /**
48
     * @var EntityRepository
49
     */
50
    protected $repository;
51
52
    /**
53
     * @var FactoryInterface
54
     */
55
    protected $settingsFactory;
56
57
    /**
58
     * @var EventDispatcherInterface
59
     */
60
    protected $eventDispatcher;
61
62
    /**
63
     * Runtime cache for resolved parameters.
64
     *
65
     * @var Settings[]
66
     */
67
    protected $resolvedSettings = [];
68
69
    /**
70
     * SettingsManager constructor.
71
     *
72
     * @param ServiceRegistryInterface $schemaRegistry
73
     * @param ServiceRegistryInterface $resolverRegistry
74
     * @param EntityManager            $manager
75
     * @param EntityRepository         $repository
76
     * @param FactoryInterface         $settingsFactory
77
     * @param $eventDispatcher
78
     */
79
    public function __construct(
80
        ServiceRegistryInterface $schemaRegistry,
81
        ServiceRegistryInterface $resolverRegistry,
82
        EntityManager $manager,
83
        EntityRepository $repository,
84
        FactoryInterface $settingsFactory,
85
        $eventDispatcher
86
    ) {
87
        $this->schemaRegistry = $schemaRegistry;
88
        $this->resolverRegistry = $resolverRegistry;
89
        $this->manager = $manager;
90
        $this->repository = $repository;
91
        $this->settingsFactory = $settingsFactory;
92
        $this->eventDispatcher = $eventDispatcher;
93
    }
94
95
    /**
96
     * @return AccessUrl
97
     */
98
    public function getUrl()
99
    {
100
        return $this->url;
101
    }
102
103
    /**
104
     * @param AccessUrl $url
105
     */
106
    public function setUrl(AccessUrl $url)
107
    {
108
        $this->url = $url;
109
    }
110
111
    /**
112
     * @param AccessUrl $url
113
     */
114
    public function updateSchemas(AccessUrl $url)
115
    {
116
        $this->url = $url;
117
        $schemas = array_keys($this->getSchemas());
118
119
        /**
120
         * @var string
121
         * @var \Sylius\Bundle\SettingsBundle\Schema\SchemaInterface $schema
122
         */
123
        foreach ($schemas as $schema) {
124
            $settings = $this->load($this->convertServiceToNameSpace($schema));
125
            $this->update($settings);
0 ignored issues
show
Bug introduced by
It seems like $settings can also be of type array; however, parameter $settings of Chamilo\SettingsBundle\M...ttingsManager::update() does only seem to accept Sylius\Bundle\SettingsBu...Model\SettingsInterface, maybe add an additional type check? ( Ignorable by Annotation )

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

125
            $this->update(/** @scrutinizer ignore-type */ $settings);
Loading history...
126
        }
127
    }
128
129
    /**
130
     * @param AccessUrl $url
131
     */
132
    public function installSchemas(AccessUrl $url)
133
    {
134
        $this->url = $url;
135
        $schemas = array_keys($this->getSchemas());
136
137
        /**
138
         * @var string
139
         * @var \Sylius\Bundle\SettingsBundle\Schema\SchemaInterface $schema
140
         */
141
        foreach ($schemas as $schema) {
142
            $settings = $this->load($this->convertServiceToNameSpace($schema));
143
            $this->save($settings);
0 ignored issues
show
Bug introduced by
It seems like $settings can also be of type array; however, parameter $settings of Chamilo\SettingsBundle\M...SettingsManager::save() does only seem to accept Sylius\Bundle\SettingsBu...Model\SettingsInterface, maybe add an additional type check? ( Ignorable by Annotation )

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

143
            $this->save(/** @scrutinizer ignore-type */ $settings);
Loading history...
144
        }
145
    }
146
147
    /**
148
     * @return array
149
     */
150
    public function getSchemas()
151
    {
152
        return $this->schemaRegistry->all();
153
    }
154
155
    /**
156
     * Get variables and categories as in 1.11.x.
157
     *
158
     * @return array
159
     */
160
    public function getVariablesAndCategories()
161
    {
162
        $oldItems = [
163
            'Institution' => 'Platform',
164
            'InstitutionUrl' => 'Platform',
165
            'siteName' => 'Platform',
166
            'emailAdministrator' => 'admin', //'emailAdministrator' => 'Platform',
167
            'administratorSurname' => 'admin',
168
            'administratorTelephone' => 'admin',
169
            'administratorName' => 'admin',
170
            'show_administrator_data' => 'Platform',
171
            'show_tutor_data' => 'Session',
172
            'show_teacher_data' => 'Platform',
173
            'homepage_view' => 'Course',
174
            'show_toolshortcuts' => 'Course',
175
            'allow_group_categories' => 'Course',
176
            'server_type' => 'Platform',
177
            'platformLanguage' => 'Language',
178
            'showonline' => 'Platform',
179
            'profile' => 'User',
180
            'default_document_quotum' => 'Course',
181
            'registration' => 'User',
182
            'default_group_quotum' => 'Course',
183
            'allow_registration' => 'Platform',
184
            'allow_registration_as_teacher' => 'Platform',
185
            'allow_lostpassword' => 'Platform',
186
            'allow_user_headings' => 'Course',
187
            'allow_personal_agenda' => 'agenda',
188
            'display_coursecode_in_courselist' => 'Platform',
189
            'display_teacher_in_courselist' => 'Platform',
190
            'permanently_remove_deleted_files' => 'Tools',
191
            'dropbox_allow_overwrite' => 'Tools',
192
            'dropbox_max_filesize' => 'Tools',
193
            'dropbox_allow_just_upload' => 'Tools',
194
            'dropbox_allow_student_to_student' => 'Tools',
195
            'dropbox_allow_group' => 'Tools',
196
            'dropbox_allow_mailing' => 'Tools',
197
            'extended_profile' => 'User',
198
            'student_view_enabled' => 'Platform',
199
            'show_navigation_menu' => 'Course',
200
            'enable_tool_introduction' => 'course',
201
            'page_after_login' => 'Platform',
202
            'time_limit_whosonline' => 'Platform',
203
            'breadcrumbs_course_homepage' => 'Course',
204
            'example_material_course_creation' => 'Platform',
205
            'account_valid_duration' => 'Platform',
206
            'use_session_mode' => 'Session',
207
            'allow_email_editor' => 'Tools',
208
            //'registered' => null',
209
            //'donotlistcampus' =>'null',
210
            'show_email_addresses' => 'Platform',
211
            'service_ppt2lp' => 'NULL',
212
            'stylesheets' => 'stylesheets',
213
            'upload_extensions_list_type' => 'Security',
214
            'upload_extensions_blacklist' => 'Security',
215
            'upload_extensions_whitelist' => 'Security',
216
            'upload_extensions_skip' => 'Security',
217
            'upload_extensions_replace_by' => 'Security',
218
            'show_number_of_courses' => 'Platform',
219
            'show_empty_course_categories' => 'Platform',
220
            'show_back_link_on_top_of_tree' => 'Platform',
221
            'show_different_course_language' => 'Platform',
222
            'split_users_upload_directory' => 'Tuning',
223
            'hide_dltt_markup' => 'Languages',
224
            'display_categories_on_homepage' => 'Platform',
225
            'permissions_for_new_directories' => 'Security',
226
            'permissions_for_new_files' => 'Security',
227
            'show_tabs' => 'Platform',
228
            'default_forum_view' => 'Course',
229
            'platform_charset' => 'Languages',
230
            'noreply_email_address' => 'Platform',
231
            'survey_email_sender_noreply' => 'Course',
232
            'gradebook_enable' => 'Gradebook',
233
            'gradebook_score_display_coloring' => 'Gradebook',
234
            'gradebook_score_display_custom' => 'Gradebook',
235
            'gradebook_score_display_colorsplit' => 'Gradebook',
236
            'gradebook_score_display_upperlimit' => 'Gradebook',
237
            'gradebook_number_decimals' => 'Gradebook',
238
            'user_selected_theme' => 'Platform',
239
            'allow_course_theme' => 'Course',
240
            'show_closed_courses' => 'Platform',
241
            'extendedprofile_registration' => 'User',
242
            'extendedprofile_registrationrequired' => 'User',
243
            'add_users_by_coach' => 'Session',
244
            'extend_rights_for_coach' => 'Security',
245
            'extend_rights_for_coach_on_survey' => 'Security',
246
            'course_create_active_tools' => 'Tools',
247
            'show_session_coach' => 'Session',
248
            'allow_users_to_create_courses' => 'Platform',
249
            'allow_message_tool' => 'Tools',
250
            'allow_social_tool' => 'Tools',
251
            'allow_students_to_browse_courses' => 'Platform',
252
            'show_session_data' => 'Session',
253
            'allow_use_sub_language' => 'language',
254
            'show_glossary_in_documents' => 'Course',
255
            'allow_terms_conditions' => 'Platform',
256
            'search_enabled' => 'Search',
257
            'search_prefilter_prefix' => 'Search',
258
            'search_show_unlinked_results' => 'Search',
259
            'show_courses_descriptions_in_catalog' => 'Course',
260
            'allow_coach_to_edit_course_session' => 'Session',
261
            'show_glossary_in_extra_tools' => 'Course',
262
            'send_email_to_admin_when_create_course' => 'Platform',
263
            'go_to_course_after_login' => 'Course',
264
            'math_asciimathML' => 'Editor',
265
            'enabled_asciisvg' => 'Editor',
266
            'include_asciimathml_script' => 'Editor',
267
            'youtube_for_students' => 'Editor',
268
            'block_copy_paste_for_students' => 'Editor',
269
            'more_buttons_maximized_mode' => 'Editor',
270
            'students_download_folders' => 'Document',
271
            'users_copy_files' => 'Tools',
272
            'allow_students_to_create_groups_in_social' => 'Tools',
273
            'allow_send_message_to_all_platform_users' => 'Message',
274
            'message_max_upload_filesize' => 'Tools',
275
            'use_users_timezone' => 'profile', //'use_users_timezone' => 'Timezones',
276
            'timezone_value' => 'platform', //'timezone_value' => 'Timezones',
277
            'allow_user_course_subscription_by_course_admin' => 'Security',
278
            'show_link_bug_notification' => 'Platform',
279
            'show_link_ticket_notification' => 'Platform',
280
            'course_validation' => 'course', //'course_validation' => 'Platform',
281
            'course_validation_terms_and_conditions_url' => 'Platform',
282
            'enabled_wiris' => 'Editor',
283
            'allow_spellcheck' => 'Editor',
284
            'force_wiki_paste_as_plain_text' => 'Editor',
285
            'enabled_googlemaps' => 'Editor',
286
            'enabled_imgmap' => 'Editor',
287
            'enabled_support_svg' => 'Tools',
288
            'pdf_export_watermark_enable' => 'Platform',
289
            'pdf_export_watermark_by_course' => 'Platform',
290
            'pdf_export_watermark_text' => 'Platform',
291
            'enabled_insertHtml' => 'Editor',
292
            'students_export2pdf' => 'Document',
293
            'exercise_min_score' => 'Course',
294
            'exercise_max_score' => 'Course',
295
            'show_users_folders' => 'Tools',
296
            'show_default_folders' => 'Tools',
297
            'show_chat_folder' => 'Tools',
298
            'enabled_text2audio' => 'Tools',
299
            'course_hide_tools' => 'Course',
300
            'enabled_support_pixlr' => 'Tools',
301
            'show_groups_to_users' => 'Session',
302
            'accessibility_font_resize' => 'Platform',
303
            'hide_courses_in_sessions' => 'Session',
304
            'enable_quiz_scenario' => 'Course',
305
            'filter_terms' => 'Security',
306
            'header_extra_content' => 'Tracking',
307
            'footer_extra_content' => 'Tracking',
308
            'show_documents_preview' => 'Tools',
309
            'htmlpurifier_wiki' => 'Editor',
310
            'cas_activate' => 'CAS',
311
            'cas_server' => 'CAS',
312
            'cas_server_uri' => 'CAS',
313
            'cas_port' => 'CAS',
314
            'cas_protocol' => 'CAS',
315
            'cas_add_user_activate' => 'CAS',
316
            'update_user_info_cas_with_ldap' => 'CAS',
317
            'student_page_after_login' => 'Platform',
318
            'teacher_page_after_login' => 'Platform',
319
            'drh_page_after_login' => 'Platform',
320
            'sessionadmin_page_after_login' => 'Session',
321
            'student_autosubscribe' => 'Platform',
322
            'teacher_autosubscribe' => 'Platform',
323
            'drh_autosubscribe' => 'Platform',
324
            'sessionadmin_autosubscribe' => 'Session',
325
            'scorm_cumulative_session_time' => 'Course',
326
            'allow_hr_skills_management' => 'Gradebook',
327
            'enable_help_link' => 'Platform',
328
            'teachers_can_change_score_settings' => 'Gradebook',
329
            'allow_users_to_change_email_with_no_password' => 'User',
330
            'show_admin_toolbar' => 'display',
331
            'allow_global_chat' => 'Platform',
332
            'languagePriority1' => 'language',
333
            'languagePriority2' => 'language',
334
            'languagePriority3' => 'language',
335
            'languagePriority4' => 'language',
336
            'login_is_email' => 'Platform',
337
            'courses_default_creation_visibility' => 'Course',
338
            'gradebook_enable_grade_model' => 'Gradebook',
339
            'teachers_can_change_grade_model_settings' => 'Gradebook',
340
            'gradebook_default_weight' => 'Gradebook',
341
            'ldap_description' => 'LDAP',
342
            'shibboleth_description' => 'Shibboleth',
343
            'facebook_description' => 'Facebook',
344
            'gradebook_locking_enabled' => 'Gradebook',
345
            'gradebook_default_grade_model_id' => 'Gradebook',
346
            'allow_session_admins_to_manage_all_sessions' => 'Session',
347
            'allow_skills_tool' => 'Platform',
348
            'allow_public_certificates' => 'Course',
349
            'platform_unsubscribe_allowed' => 'Platform',
350
            'enable_iframe_inclusion' => 'Editor',
351
            'show_hot_courses' => 'Platform',
352
            'enable_webcam_clip' => 'Tools',
353
            'use_custom_pages' => 'Platform',
354
            'tool_visible_by_default_at_creation' => 'Tools',
355
            'prevent_session_admins_to_manage_all_users' => 'Session',
356
            'documents_default_visibility_defined_in_course' => 'Tools',
357
            'enabled_mathjax' => 'Editor',
358
            'meta_twitter_site' => 'Tracking',
359
            'meta_twitter_creator' => 'Tracking',
360
            'meta_title' => 'Tracking',
361
            'meta_description' => 'Tracking',
362
            'meta_image_path' => 'Tracking',
363
            'allow_teachers_to_create_sessions' => 'Session',
364
            'institution_address' => 'Platform',
365
            'chamilo_database_version' => 'null',
366
            'cron_remind_course_finished_activate' => 'Crons',
367
            'cron_remind_course_expiration_frequency' => 'Crons',
368
            'cron_remind_course_expiration_activate' => 'Crons',
369
            'allow_coach_feedback_exercises' => 'Session',
370
            'allow_my_files' => 'Platform',
371
            'ticket_allow_student_add' => 'Ticket',
372
            'ticket_send_warning_to_all_admins' => 'Ticket',
373
            'ticket_warn_admin_no_user_in_category' => 'Ticket',
374
            'ticket_allow_category_edition' => 'Ticket',
375
            'load_term_conditions_section' => 'Platform',
376
            'show_terms_if_profile_completed' => 'Ticket',
377
            'hide_home_top_when_connected' => 'Platform',
378
            'hide_global_announcements_when_not_connected' => 'Platform',
379
            'course_creation_use_template' => 'Course',
380
            'allow_strength_pass_checker' => 'Security',
381
            'allow_captcha' => 'Security',
382
            'captcha_number_mistakes_to_block_account' => 'Security',
383
            'captcha_time_to_block' => 'Security',
384
            'drh_can_access_all_session_content' => 'Session',
385
            'display_groups_forum_in_general_tool' => 'Tools',
386
            'allow_tutors_to_assign_students_to_session' => 'Session',
387
            'allow_lp_return_link' => 'Course',
388
            'hide_scorm_export_link' => 'Course',
389
            'hide_scorm_copy_link' => 'Course',
390
            'hide_scorm_pdf_link' => 'Course',
391
            'session_days_before_coach_access' => 'Session',
392
            'session_days_after_coach_access' => 'Session',
393
            'pdf_logo_header' => 'Course',
394
            'order_user_list_by_official_code' => 'Platform',
395
            'email_alert_manager_on_new_quiz' => 'exercise',
396
            'show_official_code_exercise_result_list' => 'Tools',
397
            'course_catalog_hide_private' => 'Platform',
398
            'catalog_show_courses_sessions' => 'Platform',
399
            'auto_detect_language_custom_pages' => 'Platform',
400
            'lp_show_reduced_report' => 'Course',
401
            'allow_session_course_copy_for_teachers' => 'Session',
402
            'hide_logout_button' => 'Platform',
403
            'redirect_admin_to_courses_list' => 'Platform',
404
            'course_images_in_courses_list' => 'Course',
405
            'student_publication_to_take_in_gradebook' => 'Gradebook',
406
            'certificate_filter_by_official_code' => 'Gradebook',
407
            'exercise_max_ckeditors_in_page' => 'Tools',
408
            'document_if_file_exists_option' => 'Tools',
409
            'add_gradebook_certificates_cron_task_enabled' => 'Gradebook',
410
            'openbadges_backpack' => 'Gradebook',
411
            'cookie_warning' => 'Tools',
412
            'hide_course_group_if_no_tools_available' => 'Tools',
413
            'catalog_allow_session_auto_subscription' => 'Session',
414
            'registration.soap.php.decode_utf8' => 'Platform',
415
            'allow_delete_attendance' => 'Tools',
416
            'gravatar_enabled' => 'Platform',
417
            'gravatar_type' => 'Platform',
418
            'limit_session_admin_role' => 'Session',
419
            'show_session_description' => 'Session',
420
            'hide_certificate_export_link_students' => 'Gradebook',
421
            'hide_certificate_export_link' => 'Gradebook',
422
            'dropbox_hide_course_coach' => 'Tools',
423
            'dropbox_hide_general_coach' => 'Tools',
424
            'session_course_ordering' => 'Session',
425
            'gamification_mode' => 'Platform',
426
            'prevent_multiple_simultaneous_login' => 'Security',
427
            'gradebook_detailed_admin_view' => 'Gradebook',
428
            'course_catalog_published' => 'Course',
429
            'user_reset_password' => 'Security',
430
            'user_reset_password_token_limit' => 'Security',
431
            'my_courses_view_by_session' => 'Session',
432
            'show_full_skill_name_on_skill_wheel' => 'Platform',
433
            'messaging_allow_send_push_notification' => 'WebServices',
434
            'messaging_gdc_project_number' => 'WebServices',
435
            'messaging_gdc_api_key' => 'WebServices',
436
            'teacher_can_select_course_template' => 'Course',
437
            'enable_record_audio' => 'Tools',
438
            'allow_show_skype_account' => 'Platform',
439
            'allow_show_linkedin_url' => 'Platform',
440
            'enable_profile_user_address_geolocalization' => 'User',
441
            'show_official_code_whoisonline' => 'Profile',
442
            'icons_mode_svg' => 'display',
443
            'user_name_order' => 'display',
444
            'user_name_sort_by' => 'display',
445
            'default_calendar_view' => 'agenda',
446
            'exercise_invisible_in_session' => 'exercise',
447
            'configure_exercise_visibility_in_course' => 'exercise',
448
            'allow_download_documents_by_api_key' => 'Webservices',
449
            'ProfilingFilterAddingUsers' => 'profile',
450
            'donotlistcampus' => 'platform',
451
            'gradebook_show_percentage_in_reports' => 'gradebook',
452
            'course_creation_splash_screen' => 'Course',
453
        ];
454
455
        return $oldItems;
456
    }
457
458
    /**
459
     * Rename old variable with variable used in Chamilo 2.0.
460
     *
461
     * @param string $variable
462
     *
463
     * @return mixed
464
     */
465
    public function renameVariable($variable)
466
    {
467
        $list = [
468
            'timezone_value' => 'timezone',
469
            'Institution' => 'institution',
470
            'SiteName' => 'site_name',
471
            'siteName' => 'site_name',
472
            'InstitutionUrl' => 'institution_url',
473
            'registration' => 'required_profile_fields',
474
            'stylesheets' => 'theme',
475
            'platformLanguage' => 'platform_language',
476
            'languagePriority1' => 'language_priority_1',
477
            'languagePriority2' => 'language_priority_2',
478
            'languagePriority3' => 'language_priority_3',
479
            'languagePriority4' => 'language_priority_4',
480
            'gradebook_score_display_coloring' => 'my_display_coloring',
481
            'document_if_file_exists_option' => 'if_file_exists_option',
482
            'ProfilingFilterAddingUsers' => 'profiling_filter_adding_users',
483
            'course_create_active_tools' => 'active_tools_on_create',
484
            'emailAdministrator' => 'administrator_email',
485
            'administratorSurname' => 'administrator_surname',
486
            'administratorName' => 'administrator_name',
487
            'administratorTelephone' => 'administrator_phone',
488
            'registration.soap.php.decode_utf8' => 'decode_utf8',
489
            'profile' => 'changeable_options',
490
        ];
491
492
        return isset($list[$variable]) ? $list[$variable] : $variable;
493
    }
494
495
    /**
496
     * Replace old Chamilo 1.x category with 2.0 version.
497
     *
498
     * @param string $variable
499
     * @param string $defaultCategory
500
     *
501
     * @return mixed
502
     */
503
    public function fixCategory($variable, $defaultCategory)
504
    {
505
        $settings = [
506
            'cookie_warning' => 'platform',
507
            'donotlistcampus' => 'platform',
508
            'administrator_email' => 'admin',
509
            'administrator_surname' => 'admin',
510
            'administrator_name' => 'admin',
511
            'administrator_phone' => 'admin',
512
            'exercise_max_ckeditors_in_page' => 'exercise',
513
            'allow_hr_skills_management' => 'skill',
514
            'accessibility_font_resize' => 'display',
515
            'account_valid_duration' => 'profile',
516
            'allow_global_chat' => 'chat',
517
            'allow_lostpassword' => 'registration',
518
            'allow_registration' => 'registration',
519
            'allow_registration_as_teacher' => 'registration',
520
            'required_profile_fields' => 'registration',
521
            'allow_skills_tool' => 'skill',
522
            'allow_students_to_browse_courses' => 'display',
523
            'allow_terms_conditions' => 'registration',
524
            'allow_users_to_create_courses' => 'course',
525
            'auto_detect_language_custom_pages' => 'language',
526
            'platform_language' => 'language',
527
            'course_validation' => 'course',
528
            'course_validation_terms_and_conditions_url' => 'course',
529
            'display_categories_on_homepage' => 'display',
530
            'display_coursecode_in_courselist' => 'course',
531
            'display_teacher_in_courselist' => 'course',
532
            'drh_autosubscribe' => 'registration',
533
            'drh_page_after_login' => 'registration',
534
            'enable_help_link' => 'display',
535
            'example_material_course_creation' => 'course',
536
            'login_is_email' => 'profile',
537
            'noreply_email_address' => 'mail',
538
            'page_after_login' => 'registration',
539
            'pdf_export_watermark_by_course' => 'document',
540
            'pdf_export_watermark_enable' => 'document',
541
            'pdf_export_watermark_text' => 'document',
542
            'platform_unsubscribe_allowed' => 'registration',
543
            'send_email_to_admin_when_create_course' => 'course',
544
            'show_admin_toolbar' => 'display',
545
            'show_administrator_data' => 'display',
546
            'show_back_link_on_top_of_tree' => 'display',
547
            'show_closed_courses' => 'display',
548
            'show_different_course_language' => 'display',
549
            'show_email_addresses' => 'display',
550
            'show_empty_course_categories' => 'display',
551
            'show_full_skill_name_on_skill_wheel' => 'skill',
552
            'show_hot_courses' => 'display',
553
            'show_link_bug_notification' => 'display',
554
            'show_number_of_courses' => 'display',
555
            'show_teacher_data' => 'display',
556
            'showonline' => 'display',
557
            'student_autosubscribe' => 'registration',
558
            'student_page_after_login' => 'registration',
559
            'student_view_enabled' => 'course',
560
            'teacher_autosubscribe' => 'registration',
561
            'teacher_page_after_login' => 'registration',
562
            'time_limit_whosonline' => 'display',
563
            'user_selected_theme' => 'profile',
564
            'hide_global_announcements_when_not_connected' => 'announcement',
565
            'hide_home_top_when_connected' => 'display',
566
            'hide_logout_button' => 'display',
567
            'institution_address' => 'platform',
568
            'redirect_admin_to_courses_list' => 'admin',
569
            'use_custom_pages' => 'platform',
570
            'allow_group_categories' => 'group',
571
            'allow_user_headings' => 'display',
572
            'default_document_quotum' => 'document',
573
            'default_forum_view' => 'forum',
574
            'default_group_quotum' => 'document',
575
            'enable_quiz_scenario' => 'exercise',
576
            'exercise_max_score' => 'exercise',
577
            'exercise_min_score' => 'exercise',
578
            'pdf_logo_header' => 'platform',
579
            'show_glossary_in_documents' => 'document',
580
            'show_glossary_in_extra_tools' => 'glossary',
581
            'survey_email_sender_noreply' => 'survey',
582
            'allow_coach_feedback_exercises' => 'exercise',
583
            'sessionadmin_autosubscribe' => 'registration',
584
            'sessionadmin_page_after_login' => 'registration',
585
            'show_tutor_data' => 'display',
586
            'allow_social_tool' => 'social',
587
            'allow_message_tool' => 'message',
588
            'allow_email_editor' => 'editor',
589
            'show_link_ticket_notification' => 'display',
590
            'permissions_for_new_directories' => 'document',
591
            'enable_profile_user_address_geolocalization' => 'profile',
592
            'allow_show_skype_account' => 'profile',
593
            'allow_show_linkedin_url' => 'profile',
594
            'allow_students_to_create_groups_in_social' => 'social',
595
            'default_calendar_view' => 'agenda',
596
            'documents_default_visibility_defined_in_course' => 'document',
597
            'message_max_upload_filesize' => 'message',
598
            'course_create_active_tools' => 'course',
599
            'tool_visible_by_default_at_creation' => 'document',
600
            'show_users_folders' => 'document',
601
            'show_default_folders' => 'document',
602
            'show_chat_folder' => 'chat',
603
            'enabled_support_svg' => 'editor',
604
            'enabled_support_pixlr' => 'editor',
605
            'enable_webcam_clip' => 'document',
606
            'enable_record_audio' => 'course',
607
            'enabled_text2audio' => 'document',
608
            'permanently_remove_deleted_files' => 'document',
609
            'allow_delete_attendance' => 'attendance',
610
            'display_groups_forum_in_general_tool' => 'forum',
611
            'dropbox_allow_overwrite' => 'dropbox',
612
            'allow_user_course_subscription_by_course_admin' => 'course',
613
            'hide_course_group_if_no_tools_available' => 'group',
614
            'extend_rights_for_coach_on_survey' => 'survey',
615
            'show_official_code_exercise_result_list' => 'exercise',
616
            'dropbox_max_filesize' => 'dropbox',
617
            'dropbox_allow_just_upload' => 'dropbox',
618
            'dropbox_allow_student_to_student' => 'dropbox',
619
            'dropbox_allow_group' => 'dropbox',
620
            'dropbox_allow_mailing' => 'dropbox',
621
            'upload_extensions_list_type' => 'document',
622
            'upload_extensions_blacklist' => 'document',
623
            'upload_extensions_skip' => 'document',
624
            'changeable_options' => 'profile',
625
            'users_copy_files' => 'document',
626
            'if_file_exists_option' => 'document',
627
            'permissions_for_new_files' => 'document',
628
            'extended_profile' => 'profile',
629
            'split_users_upload_directory' => 'profile',
630
            'show_documents_preview' => 'document',
631
            'decode_utf8' => 'webservice',
632
            'messaging_allow_send_push_notification' => 'webservice',
633
            'messaging_gdc_project_number' => 'webservice',
634
            'messaging_gdc_api_key' => 'webservice',
635
            'allow_download_documents_by_api_key' => 'webservice',
636
            'profiling_filter_adding_users' => 'profile',
637
            'hide_dltt_markup' => 'language',
638
            'active_tools_on_create' => 'course',
639
        ];
640
641
        return isset($settings[$variable]) ? $settings[$variable] : $defaultCategory;
642
    }
643
644
    /**
645
     * @param string $name
646
     *
647
     * @throws \InvalidArgumentException
648
     *
649
     * @return mixed
650
     */
651
    public function getSetting($name)
652
    {
653
        if (false === strpos($name, '.')) {
654
            //throw new \InvalidArgumentException(sprintf('Parameter must be in format "namespace.name", "%s" given.', $name));
655
656
            // This code allows the possibility of calling
657
            // api_get_setting('allow_skills_tool') instead of
658
            // the "correct" way api_get_setting('platform.allow_skills_tool')
659
            $items = $this->getVariablesAndCategories();
660
661
            if (isset($items[$name])) {
662
                $originalName = $name;
663
                $name = $this->renameVariable($name);
664
                $category = $this->fixCategory(
665
                    strtolower($name),
666
                    strtolower($items[$originalName])
667
                );
668
                $name = $category.'.'.$name;
669
            } else {
670
                throw new \InvalidArgumentException(sprintf('Parameter must be in format "category.name", "%s" given.', $name));
671
            }
672
        }
673
674
        list($category, $name) = explode('.', $name);
675
        $settings = $this->load($category, $name);
676
677
        if (!$settings) {
678
            throw new \InvalidArgumentException(sprintf("Parameter '$name' not found in category '$category'"));
679
        }
680
681
        return $settings->get($name);
682
    }
683
684
    /**
685
     * @param string $category
686
     *
687
     * @return string
688
     */
689
    public function convertNameSpaceToService($category)
690
    {
691
        return 'chamilo_core.settings.'.$category;
692
    }
693
694
    /**
695
     * @param string $category
696
     *
697
     * @return string
698
     */
699
    public function convertServiceToNameSpace($category)
700
    {
701
        return str_replace('chamilo_core.settings.', '', $category);
702
    }
703
704
    /**
705
     * {@inheritdoc}
706
     */
707
    public function load($schemaAlias, $namespace = null, $ignoreUnknown = true)
708
    {
709
        $schemaAliasNoPrefix = $schemaAlias;
710
        $schemaAlias = 'chamilo_core.settings.'.$schemaAlias;
711
712
        if ($this->schemaRegistry->has($schemaAlias)) {
713
            /** @var SchemaInterface $schema */
714
            $schema = $this->schemaRegistry->get($schemaAlias);
715
        } else {
716
            return [];
717
        }
718
719
        /** @var \Sylius\Bundle\SettingsBundle\Model\Settings $settings */
720
        $settings = $this->settingsFactory->createNew();
721
        $settings->setSchemaAlias($schemaAlias);
722
723
        // We need to get a plain parameters array since we use the options resolver on it
724
        $parameters = $this->getParameters($schemaAliasNoPrefix);
725
        $settingsBuilder = new SettingsBuilder();
726
        $schema->buildSettings($settingsBuilder);
727
728
        // Remove unknown settings' parameters (e.g. From a previous version of the settings schema)
729
        if (true === $ignoreUnknown) {
730
            foreach ($parameters as $name => $value) {
731
                if (!$settingsBuilder->isDefined($name)) {
732
                    unset($parameters[$name]);
733
                }
734
            }
735
        }
736
737
        foreach ($settingsBuilder->getTransformers() as $parameter => $transformer) {
738
            if (array_key_exists($parameter, $parameters)) {
739
                if ($parameter === 'course_creation_use_template') {
740
                    if (empty($parameters[$parameter])) {
741
                        $parameters[$parameter] = null;
742
                    }
743
                } else {
744
                    $parameters[$parameter] = $transformer->reverseTransform($parameters[$parameter]);
745
                }
746
            }
747
        }
748
749
        $parameters = $settingsBuilder->resolve($parameters);
750
        $settings->setParameters($parameters);
751
752
        return $settings;
753
    }
754
755
    /**
756
     * @param SettingsInterface $settings
757
     *
758
     * @throws \Doctrine\ORM\ORMException
759
     * @throws \Doctrine\ORM\OptimisticLockException
760
     */
761
    public function update(SettingsInterface $settings)
762
    {
763
        $namespace = $settings->getSchemaAlias();
764
765
        /** @var SchemaInterface $schema */
766
        $schema = $this->schemaRegistry->get($settings->getSchemaAlias());
767
768
        $settingsBuilder = new SettingsBuilder();
769
        $schema->buildSettings($settingsBuilder);
770
        $parameters = $settingsBuilder->resolve($settings->getParameters());
771
        // Transform value. Example array to string using transformer. Example:
772
        // 1. Setting "tool_visible_by_default_at_creation" it's a multiple select
773
        // 2. Is defined as an array in class DocumentSettingsSchema
774
        // 3. Add transformer for that variable "ArrayToIdentifierTransformer"
775
        // 4. Here we recover the transformer and convert the array to string
776
        foreach ($settingsBuilder->getTransformers() as $parameter => $transformer) {
777
            if (array_key_exists($parameter, $parameters)) {
778
                $parameters[$parameter] = $transformer->transform($parameters[$parameter]);
779
            }
780
        }
781
        $settings->setParameters($parameters);
782
        $persistedParameters = $this->repository->findBy(
783
            ['category' => $this->convertServiceToNameSpace($settings->getSchemaAlias())]
784
        );
785
786
        $persistedParametersMap = [];
787
        /** @var SettingsCurrent $parameter */
788
        foreach ($persistedParameters as $parameter) {
789
            $persistedParametersMap[$parameter->getVariable()] = $parameter;
790
        }
791
792
        /** @var SettingsCurrent $url */
793
        $url = $this->getUrl();
794
        $simpleCategoryName = str_replace('chamilo_core.settings.', '', $namespace);
795
796
        foreach ($parameters as $name => $value) {
797
            if (isset($persistedParametersMap[$name])) {
798
                $parameter = $persistedParametersMap[$name];
799
                $parameter->setSelectedValue($value);
800
                $parameter->setCategory($simpleCategoryName);
801
                $this->manager->merge($parameter);
802
            } else {
803
                $parameter = new SettingsCurrent();
804
                $parameter
805
                    ->setVariable($name)
806
                    ->setCategory($simpleCategoryName)
807
                    ->setTitle($name)
808
                    ->setSelectedValue($value)
809
                    ->setUrl($url)
810
                    ->setAccessUrlChangeable(1)
811
                    ->setAccessUrlLocked(1)
812
                ;
813
814
                /* @var $errors ConstraintViolationListInterface */
815
                /*$errors = $this->validator->validate($parameter);
816
                if (0 < $errors->count()) {
817
                    throw new ValidatorException($errors->get(0)->getMessage());
818
                }*/
819
                $this->manager->persist($parameter);
820
            }
821
        }
822
823
        $this->manager->flush();
824
    }
825
826
    /**
827
     * {@inheritdoc}
828
     *
829
     * @throws ValidatorException
830
     */
831
    public function save(SettingsInterface $settings)
832
    {
833
        $namespace = $settings->getSchemaAlias();
834
835
        /** @var SchemaInterface $schema */
836
        $schema = $this->schemaRegistry->get($settings->getSchemaAlias());
837
838
        $settingsBuilder = new SettingsBuilder();
839
        $schema->buildSettings($settingsBuilder);
840
        $parameters = $settingsBuilder->resolve($settings->getParameters());
841
        // Transform value. Example array to string using transformer. Example:
842
        // 1. Setting "tool_visible_by_default_at_creation" it's a multiple select
843
        // 2. Is defined as an array in class DocumentSettingsSchema
844
        // 3. Add transformer for that variable "ArrayToIdentifierTransformer"
845
        // 4. Here we recover the transformer and convert the array to string
846
        foreach ($settingsBuilder->getTransformers() as $parameter => $transformer) {
847
            if (array_key_exists($parameter, $parameters)) {
848
                $parameters[$parameter] = $transformer->transform($parameters[$parameter]);
849
            }
850
        }
851
        $settings->setParameters($parameters);
852
        $persistedParameters = $this->repository->findBy(
853
            ['category' => $this->convertServiceToNameSpace($settings->getSchemaAlias())]
854
        );
855
        $persistedParametersMap = [];
856
857
        foreach ($persistedParameters as $parameter) {
858
            $persistedParametersMap[$parameter->getTitle()] = $parameter;
859
        }
860
861
        /** @var SettingsEvent $event */
862
        /*$event = $this->eventDispatcher->dispatch(
863
            SettingsEvent::PRE_SAVE,
864
            new SettingsEvent($settings, $parameters)
865
        );*/
866
867
        /** @var SettingsCurrent $url */
868
        $url = $this->getUrl();
869
        $simpleCategoryName = str_replace('chamilo_core.settings.', '', $namespace);
870
871
        foreach ($parameters as $name => $value) {
872
            if (isset($persistedParametersMap[$name])) {
873
                $parameter = $persistedParametersMap[$name];
874
                $parameter->setSelectedValue($value);
875
            } else {
876
                $parameter = new SettingsCurrent();
877
                $parameter
878
                    ->setVariable($name)
879
                    ->setCategory($simpleCategoryName)
880
                    ->setTitle($name)
881
                    ->setSelectedValue($value)
882
                    ->setUrl($url)
883
                    ->setAccessUrlChangeable(1)
884
                    ->setAccessUrlLocked(1)
885
                ;
886
887
                /* @var $errors ConstraintViolationListInterface */
888
                /*$errors = $this->validator->validate($parameter);
889
                if (0 < $errors->count()) {
890
                    throw new ValidatorException($errors->get(0)->getMessage());
891
                }*/
892
                $this->manager->persist($parameter);
893
            }
894
            $this->manager->persist($parameter);
895
        }
896
897
        $this->manager->flush();
898
899
        return;
900
901
        ////
902
        $schemaAlias = $settings->getSchemaAlias();
0 ignored issues
show
Unused Code introduced by
$schemaAlias = $settings->getSchemaAlias() is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
903
        $schemaAliasChamilo = str_replace('chamilo_core.settings.', '', $schemaAlias);
904
905
        $schema = $this->schemaRegistry->get($schemaAlias);
906
907
        $settingsBuilder = new SettingsBuilder();
908
        $schema->buildSettings($settingsBuilder);
909
910
        $parameters = $settingsBuilder->resolve($settings->getParameters());
911
912
        foreach ($settingsBuilder->getTransformers() as $parameter => $transformer) {
913
            if (array_key_exists($parameter, $parameters)) {
914
                $parameters[$parameter] = $transformer->transform($parameters[$parameter]);
915
            }
916
        }
917
918
        /** @var \Sylius\Bundle\SettingsBundle\Event\SettingsEvent $event */
919
        $event = $this->eventDispatcher->dispatch(
920
            SettingsEvent::PRE_SAVE,
921
            new SettingsEvent($settings)
922
        );
923
924
        /** @var SettingsCurrent $url */
925
        $url = $event->getSettings()->getAccessUrl();
926
927
        foreach ($parameters as $name => $value) {
928
            if (isset($persistedParametersMap[$name])) {
929
                if ($value instanceof Course) {
930
                    $value = $value->getId();
931
                }
932
                $persistedParametersMap[$name]->setValue($value);
933
            } else {
934
                /** @var SettingsCurrent $setting */
935
                $setting = $this->settingsFactory->createNew();
936
                $setting->setSchemaAlias($schemaAlias);
937
938
                $setting
939
                    ->setNamespace($schemaAliasChamilo)
940
                    ->setName($name)
941
                    ->setValue($value)
942
                    ->setUrl($url)
943
                    ->setAccessUrlLocked(0)
944
                    ->setAccessUrlChangeable(1)
945
                ;
946
947
                /* @var $errors ConstraintViolationListInterface */
948
                /*$errors = $this->->validate($parameter);
949
                if (0 < $errors->count()) {
950
                    throw new ValidatorException($errors->get(0)->getMessage());
951
                }*/
952
                $this->manager->persist($setting);
953
                $this->manager->flush();
954
            }
955
        }
956
        /*$parameters = $settingsBuilder->resolve($settings->getParameters());
957
        $settings->setParameters($parameters);
958
959
        $this->eventDispatcher->dispatch(SettingsEvent::PRE_SAVE, new SettingsEvent($settings));
960
961
        $this->manager->persist($settings);
962
        $this->manager->flush();
963
964
        $this->eventDispatcher->dispatch(SettingsEvent::POST_SAVE, new SettingsEvent($settings));*/
965
    }
966
967
    /**
968
     * @param string $keyword
969
     *
970
     * @return array
971
     */
972
    public function getParametersFromKeywordOrderedByCategory($keyword)
973
    {
974
        $query = $this->repository->createQueryBuilder('s')
975
            ->where('s.variable LIKE :keyword')
976
            ->setParameter('keyword', "%$keyword%")
977
        ;
978
        $parametersFromDb = $query->getQuery()->getResult();
979
        $parameters = [];
980
        /** @var \Chamilo\CoreBundle\Entity\SettingsCurrent $parameter */
981
        foreach ($parametersFromDb as $parameter) {
982
            $parameters[$parameter->getCategory()][] = $parameter;
983
        }
984
985
        return $parameters;
986
    }
987
988
    /**
989
     * @param string $namespace
990
     * @param string $keyword
991
     * @param bool   $returnObjects
992
     *
993
     * @return array
994
     */
995
    public function getParametersFromKeyword($namespace, $keyword = '', $returnObjects = false)
996
    {
997
        if (empty($keyword)) {
998
            $criteria = ['category' => $namespace];
999
            $parametersFromDb = $this->repository->findBy($criteria);
1000
        } else {
1001
            $query = $this->repository->createQueryBuilder('s')
1002
                ->where('s.variable LIKE :keyword')
1003
                ->setParameter('keyword', "%$keyword%")
1004
            ;
1005
            $parametersFromDb = $query->getQuery()->getResult();
1006
        }
1007
1008
        if ($returnObjects) {
1009
            return $parametersFromDb;
1010
        }
1011
        $parameters = [];
1012
        /** @var \Chamilo\CoreBundle\Entity\SettingsCurrent $parameter */
1013
        foreach ($parametersFromDb as $parameter) {
1014
            $parameters[$parameter->getVariable()] = $parameter->getSelectedValue();
1015
        }
1016
1017
        return $parameters;
1018
    }
1019
1020
    /**
1021
     * Load parameter from database.
1022
     *
1023
     * @param string $namespace
1024
     *
1025
     * @return array
1026
     */
1027
    private function getParameters($namespace)
1028
    {
1029
        $parameters = [];
1030
        /** @var SettingsCurrent $parameter */
1031
        foreach ($this->repository->findBy(['category' => $namespace]) as $parameter) {
1032
            $parameters[$parameter->getVariable()] = $parameter->getSelectedValue();
1033
        }
1034
1035
        return $parameters;
1036
    }
1037
1038
    private function transformParameters(SettingsBuilder $settingsBuilder, array $parameters)
0 ignored issues
show
Unused Code introduced by
The method transformParameters() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
1039
    {
1040
        $transformedParameters = $parameters;
1041
1042
        foreach ($settingsBuilder->getTransformers() as $parameter => $transformer) {
1043
            if (array_key_exists($parameter, $parameters)) {
1044
                $transformedParameters[$parameter] = $transformer->reverseTransform($parameters[$parameter]);
1045
            }
1046
        }
1047
1048
        return $transformedParameters;
1049
    }
1050
}
1051