Passed
Pull Request — master (#5329)
by Angel Fernando Quiroz
07:32
created

CourseController::grade()   B

Complexity

Conditions 8
Paths 17

Size

Total Lines 104
Code Lines 63

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 63
nc 17
nop 1
dl 0
loc 104
rs 7.5628
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
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\LtiBundle\Controller;
8
9
use Category;
10
use Chamilo\CoreBundle\Component\Utils\ToolIcon;
11
use Chamilo\CoreBundle\Entity\Course;
12
use Chamilo\CoreBundle\Entity\Session;
13
use Chamilo\CoreBundle\Entity\User;
14
use Chamilo\CourseBundle\Controller\ToolBaseController;
15
use Chamilo\CourseBundle\Entity\CTool;
16
use Chamilo\CourseBundle\Repository\CShortcutRepository;
17
use Chamilo\LtiBundle\Entity\ExternalTool;
18
use Chamilo\LtiBundle\Form\ExternalToolType;
19
use Chamilo\LtiBundle\Util\Utils;
20
use Display;
21
use Doctrine\Persistence\ManagerRegistry;
22
use EvalForm;
23
use Evaluation;
24
use Exception;
25
use HTML_QuickForm_select;
26
use OAuthConsumer;
27
use OAuthRequest;
28
use OAuthSignatureMethod_HMAC_SHA1;
29
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
30
use Symfony\Component\HttpFoundation\Request;
31
use Symfony\Component\HttpFoundation\Response;
32
use Symfony\Component\Routing\Annotation\Route;
33
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
34
use UserManager;
35
36
#[Route(path: '/courses/{cid}/lti')] // ;
37
class CourseController extends ToolBaseController
38
{
39
    public function __construct(
40
        private readonly CShortcutRepository $shortcutRepository,
41
        private readonly ManagerRegistry $managerRegistry
42
    ) {}
43
44
    #[Route(path: '/edit/{id}', name: 'chamilo_lti_edit', requirements: ['id' => '\d+'])]
45
    public function edit(int $id, Request $request): Response
46
    {
47
        $em = $this->managerRegistry->getManager();
48
49
        /** @var ExternalTool $tool */
50
        $tool = $em->find(ExternalTool::class, $id);
51
52
        if (empty($tool)) {
53
            throw $this->createNotFoundException('External tool not found');
54
        }
55
56
        $course = $this->getCourse();
57
58
        $form = $this->createForm(ExternalToolType::class, $tool);
59
        $form->get('shareName')->setData($tool->isSharingName());
60
        $form->get('shareEmail')->setData($tool->isSharingEmail());
61
        $form->get('sharePicture')->setData($tool->isSharingPicture());
62
        $form->handleRequest($request);
63
64
        if (!$form->isSubmitted() || !$form->isValid()) {
65
            return $this->render(
66
                '@ChamiloCore/Lti/course_configure.twig',
67
                [
68
                    'title' => $this->trans('Edit external tool'),
69
                    'added_tools' => [],
70
                    'global_tools' => [],
71
                    'form' => $form->createView(),
72
                    'course' => $course,
73
                ]
74
            );
75
        }
76
77
        /** @var ExternalTool $tool */
78
        $tool = $form->getData();
79
80
        $em->persist($tool);
81
82
        if (!$tool->isActiveDeepLinking()) {
83
            $courseTool = $em->getRepository(CTool::class)
84
                ->findOneBy(
85
                    [
86
                        'course' => $course,
87
                        'link' => $this->generateUrl(
88
                            'chamilo_lti_show',
89
                            [
90
                                'code' => $course->getCode(),
91
                                'id' => $tool->getId(),
92
                            ]
93
                        ),
94
                    ]
95
                )
96
            ;
97
98
            if (empty($courseTool)) {
99
                throw $this->createNotFoundException('Course tool not found.');
100
            }
101
102
            $courseTool->setTitle($tool->getTitle());
103
104
            $em->persist($courseTool);
105
        }
106
107
        $em->flush();
108
109
        $this->addFlash('success', $this->trans('External tool edited'));
110
111
        return $this->redirectToRoute(
112
            'chamilo_lti_edit',
113
            [
114
                'id' => $tool->getId(),
115
                'cid' => $course->getId(),
116
            ]
117
        );
118
    }
119
120
    #[Route(path: '/launch/{id}', name: 'chamilo_lti_launch', requirements: ['id' => '\d+'])]
121
    public function launch(int $id, Utils $ltiUtil): Response
122
    {
123
        $em = $this->managerRegistry->getManager();
124
125
        /** @var null|ExternalTool $tool */
126
        $tool = $em->find(ExternalTool::class, $id);
127
128
        if (empty($tool)) {
129
            throw $this->createNotFoundException();
130
        }
131
132
        $settingsManager = $this->get('chamilo.settings.manager');
133
134
        /** @var User $user */
135
        $user = $this->getUser();
136
        $course = $this->getCourse();
137
        $session = $this->getCourseSession();
138
139
        if (empty($tool->getCourse()) || $tool->getCourse()->getId() !== $course->getId()) {
140
            throw $this->createAccessDeniedException('');
141
        }
142
143
        $institutionDomain = $ltiUtil->getInstitutionDomain();
144
        $toolUserId = $ltiUtil->generateToolUserId($user->getId());
145
146
        $params = [];
147
        $params['lti_version'] = 'LTI-1p0';
148
149
        if ($tool->isActiveDeepLinking()) {
150
            $params['lti_message_type'] = 'ContentItemSelectionRequest';
151
            $params['content_item_return_url'] = $this->generateUrl(
152
                'chamilo_lti_return_item',
153
                [
154
                    'code' => $course->getCode(),
155
                ],
156
                UrlGeneratorInterface::ABSOLUTE_URL
157
            );
158
            $params['accept_media_types'] = '*/*';
159
            $params['accept_presentation_document_targets'] = 'iframe';
160
            $params['title'] = $tool->getTitle();
161
            $params['text'] = $tool->getDescription();
162
            $params['data'] = 'tool:'.$tool->getId();
163
        } else {
164
            $params['lti_message_type'] = 'basic-lti-launch-request';
165
            $params['resource_link_id'] = $tool->getId();
166
            $params['resource_link_title'] = $tool->getTitle();
167
            $params['resource_link_description'] = $tool->getDescription();
168
169
            $toolEval = $tool->getGradebookEval();
170
171
            if (!empty($toolEval)) {
172
                $params['lis_result_sourcedid'] = json_encode(
173
                    [
174
                        'e' => $toolEval->getId(),
175
                        'u' => $user->getId(),
176
                        'l' => uniqid(),
177
                        'lt' => time(),
178
                    ]
179
                );
180
                $params['lis_outcome_service_url'] = api_get_path(WEB_PATH).'lti/os';
181
                /* $params['lis_outcome_service_url'] = $this->generateUrl(
182
                    'chamilo_lti_os',
183
                    [],
184
                    UrlGeneratorInterface::ABSOLUTE_URL
185
                ); */
186
                $params['lis_person_sourcedid'] = "{$institutionDomain}:{$toolUserId}";
187
                $params['lis_course_section_sourcedid'] = "{$institutionDomain}:".$course->getId();
188
189
                if ($session) {
190
                    $params['lis_course_section_sourcedid'] .= ':'.$session->getId();
191
                }
192
            }
193
        }
194
195
        $params['user_id'] = $toolUserId;
196
197
        if ($tool->isSharingPicture()) {
198
            $params['user_image'] = UserManager::getUserPicture($user->getId());
199
        }
200
201
        $params['roles'] = Utils::generateUserRoles($user);
202
203
        if ($tool->isSharingName()) {
204
            $params['lis_person_name_given'] = $user->getFirstname();
205
            $params['lis_person_name_family'] = $user->getLastname();
206
            $params['lis_person_name_full'] = $user->getFirstname().' '.$user->getLastname();
207
        }
208
209
        if ($tool->isSharingEmail()) {
210
            $params['lis_person_contact_email_primary'] = $user->getEmail();
211
        }
212
213
        if ($user->hasRole('ROLE_RRHH')) {
214
            $scopeMentor = $ltiUtil->generateRoleScopeMentor($user);
215
216
            if (!empty($scopeMentor)) {
217
                $params['role_scope_mentor'] = $scopeMentor;
218
            }
219
        }
220
221
        $params['context_id'] = $course->getId();
222
        $params['context_type'] = 'CourseSection';
223
        $params['context_label'] = $course->getCode();
224
        $params['context_title'] = $course->getTitle();
225
        $params['launch_presentation_locale'] = 'en';
226
        $params['launch_presentation_document_target'] = 'iframe';
227
        $params['tool_consumer_info_product_family_code'] = 'Chamilo LMS';
228
        $params['tool_consumer_info_version'] = '2.0';
229
        $params['tool_consumer_instance_guid'] = $institutionDomain;
230
        $params['tool_consumer_instance_name'] = $settingsManager->getSetting('platform.site_name');
231
        $params['tool_consumer_instance_url'] = $this->generateUrl(
232
            'home',
233
            [],
234
            UrlGeneratorInterface::ABSOLUTE_URL
235
        );
236
        $params['tool_consumer_instance_contact_email'] = $settingsManager->getSetting('admin.administrator_email');
237
238
        $params['oauth_callback'] = 'about:blank';
239
240
        $customParams = $tool->parseCustomParams();
241
        Utils::trimParams($customParams);
242
        $this->variableSubstitution($params, $customParams, $user, $course, $session);
243
244
        $params += $customParams;
245
        Utils::trimParams($params);
246
247
        if (!empty($tool->getConsumerKey()) && !empty($tool->getSharedSecret())) {
248
            $consumer = new OAuthConsumer(
249
                $tool->getConsumerKey(),
250
                $tool->getSharedSecret(),
251
                null
252
            );
253
            $hmacMethod = new OAuthSignatureMethod_HMAC_SHA1();
254
255
            $request = OAuthRequest::from_consumer_and_token(
256
                $consumer,
257
                '',
258
                'POST',
259
                $tool->getLaunchUrl(),
260
                $params
261
            );
262
            $request->sign_request($hmacMethod, $consumer, '');
263
264
            $params = $request->get_parameters();
265
        }
266
267
        Utils::removeQueryParamsFromLaunchUrl($tool, $params);
268
269
        return $this->render(
270
            '@ChamiloCore/Lti/launch.html.twig',
271
            [
272
                'params' => $params,
273
                'launch_url' => $tool->getLaunchUrl(),
274
            ]
275
        );
276
    }
277
278
    #[Route(path: '/item_return', name: 'chamilo_lti_return_item')]
279
    public function returnItem(Request $request): Response
280
    {
281
        $contentItems = $request->get('content_items');
282
        $data = $request->get('data');
283
284
        if (empty($contentItems) || empty($data)) {
285
            throw $this->createAccessDeniedException();
286
        }
287
288
        $em = $this->managerRegistry->getManager();
289
290
        /** @var ExternalTool $tool */
291
        $tool = $em->find(ExternalTool::class, str_replace('tool:', '', $data));
292
293
        if (empty($tool)) {
294
            throw $this->createNotFoundException('External tool not found');
295
        }
296
297
        $course = $this->getCourse();
298
        $url = $this->generateUrl(
299
            'chamilo_lti_return_item',
300
            [
301
                'code' => $course->getCode(),
302
            ],
303
            UrlGeneratorInterface::ABSOLUTE_URL
304
        );
305
306
        $signatureIsValid = Utils::checkRequestSignature(
307
            $url,
308
            $request->get('oauth_consumer_key'),
309
            $request->get('oauth_signature'),
310
            $tool
311
        );
312
313
        if (!$signatureIsValid) {
314
            throw $this->createAccessDeniedException();
315
        }
316
317
        $contentItems = json_decode($contentItems, true)['@graph'];
318
319
        $supportedItemTypes = ['LtiLinkItem'];
320
321
        foreach ($contentItems as $contentItem) {
322
            if (!\in_array($contentItem['@type'], $supportedItemTypes, true)) {
323
                continue;
324
            }
325
326
            if ('LtiLinkItem' === $contentItem['@type']) {
327
                $newTool = $this->createLtiLink($contentItem, $tool);
328
329
                $this->addFlash(
330
                    'success',
331
                    sprintf(
332
                        $this->trans('External tool added: %s'),
333
                        $newTool->getTitle()
334
                    )
335
                );
336
            }
337
        }
338
339
        return $this->render(
340
            '@ChamiloCore/Lti/item_return.html.twig',
341
            [
342
                'course' => $course,
343
            ]
344
        );
345
    }
346
347
    #[Route(path: '/{id}', name: 'chamilo_lti_show', requirements: ['id' => '\d+'])]
348
    public function show(int $id): Response
349
    {
350
        $course = $this->getCourse();
351
352
        $em = $this->managerRegistry->getManager();
353
354
        /** @var null|ExternalTool $externalTool */
355
        $externalTool = $em->find(ExternalTool::class, $id);
356
357
        if (empty($externalTool)) {
358
            throw $this->createNotFoundException();
359
        }
360
361
        if (empty($externalTool->getCourse()) || $externalTool->getCourse()->getId() !== $course->getId()) {
362
            throw $this->createAccessDeniedException('');
363
        }
364
365
        return $this->render(
366
            '@ChamiloCore/Lti/iframe.html.twig',
367
            [
368
                'tool' => $externalTool,
369
                'course' => $course,
370
            ]
371
        );
372
    }
373
374
    /**
375
     * @Security("is_granted('ROLE_TEACHER')")
376
     */
377
    #[Route(path: '/', name: 'chamilo_lti_configure')]
378
    #[Route(path: '/add/{id}', name: 'chamilo_lti_configure_global', requirements: ['id' => '\d+'])]
379
    public function courseConfigure(?int $id, Request $request): Response
380
    {
381
        $em = $this->managerRegistry->getManager();
382
        $repo = $em->getRepository(ExternalTool::class);
383
384
        $externalTool = new ExternalTool();
385
386
        if (null !== $id) {
387
            $parentTool = $repo->findOneBy([
388
                'id' => $id,
389
                'course' => null,
390
            ]);
391
392
            if (empty($parentTool)) {
393
                throw $this->createNotFoundException('External tool not found');
394
            }
395
396
            $externalTool = clone $parentTool;
397
            $externalTool->setToolParent($parentTool);
398
        }
399
400
        $course = $this->getCourse();
401
402
        $form = $this->createForm(ExternalToolType::class, $externalTool);
403
        $form->get('shareName')->setData($externalTool->isSharingName());
404
        $form->get('shareEmail')->setData($externalTool->isSharingEmail());
405
        $form->get('sharePicture')->setData($externalTool->isSharingPicture());
406
        $form->handleRequest($request);
407
408
        if (!$form->isSubmitted() || !$form->isValid()) {
409
            $categories = Category::load(null, null, $course->getId());
410
            $actions = '';
411
412
            if (!empty($categories)) {
413
                $actions .= Display::url(
414
                    Display::getMdiIcon(ToolIcon::GRADEBOOK, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Add to gradebook')),
415
                    $this->generateUrl(
416
                        'chamilo_lti_grade',
417
                        [
418
                            'catId' => $categories[0]->get_id(),
419
                            'course_code' => $course->getCode(),
420
                        ]
421
                    )
422
                );
423
            }
424
425
            return $this->render(
426
                '@ChamiloCore/Lti/course_configure.twig',
427
                [
428
                    'title' => $this->trans('Add external tool'),
429
                    'added_tools' => $repo->findBy([
430
                        'course' => $course,
431
                    ]),
432
                    'global_tools' => $repo->findBy([
433
                        'parent' => null,
434
                        'course' => null,
435
                    ]),
436
                    'form' => $form->createView(),
437
                    'course' => $course,
438
                    'actions' => $actions,
439
                ]
440
            );
441
        }
442
443
        /** @var ExternalTool $externalTool */
444
        $externalTool = $form->getData();
445
        $externalTool
446
            ->setCourse($course)
447
            ->setParent($course)
448
            ->addCourseLink($course)
449
        ;
450
451
        $em->persist($externalTool);
452
        $em->flush();
453
454
        $this->addFlash('success', $this->trans('External tool added'));
455
456
        /** @var User $user */
457
        $user = $this->getUser();
458
459
        if (!$externalTool->isActiveDeepLinking()) {
460
            $this->shortcutRepository->addShortCut($externalTool, $user, $course);
461
462
            return $this->redirectToRoute(
463
                'chamilo_core_course_home',
464
                [
465
                    'cid' => $course->getId(),
466
                ]
467
            );
468
        }
469
470
        return $this->redirectToRoute(
471
            'chamilo_lti_configure',
472
            [
473
                'course' => $course->getCode(),
474
            ]
475
        );
476
    }
477
478
    /**
479
     * @Security("is_granted('ROLE_TEACHER')")
480
     *
481
     * @param string $catId
482
     *
483
     * @throws Exception
484
     */
485
    #[Route(path: '/grade/{catId}', name: 'chamilo_lti_grade', requirements: ['catId' => '\d+'])]
486
    public function grade(int $catId): Response
487
    {
488
        $em = $this->managerRegistry->getManager();
489
        $toolRepo = $em->getRepository(ExternalTool::class);
490
        $course = $this->getCourse();
491
492
        /** @var User $user */
493
        $user = $this->getUser();
494
495
        $categories = Category::load(null, null, $course->getId());
496
497
        if (empty($categories)) {
498
            throw $this->createNotFoundException();
499
        }
500
501
        $evaladd = new Evaluation();
502
        $evaladd->set_user_id($user->getId());
503
504
        if (!empty($catId)) {
505
            $evaladd->set_category_id($catId);
506
            $evaladd->set_course_code($course->getCode());
0 ignored issues
show
Bug introduced by
The method set_course_code() does not exist on Evaluation. ( Ignorable by Annotation )

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

506
            $evaladd->/** @scrutinizer ignore-call */ 
507
                      set_course_code($course->getCode());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
507
        } else {
508
            $evaladd->set_category_id(0);
509
        }
510
511
        $form = new EvalForm(
512
            EvalForm::TYPE_ADD,
513
            $evaladd,
514
            null,
515
            'add_eval_form',
516
            null,
517
            $this->generateUrl(
518
                'chamilo_lti_grade',
519
                [
520
                    'catId' => $catId,
521
                    'code' => $course->getCode(),
522
                ]
523
            ).'?'.api_get_cidreq()
524
        );
525
        $form->removeElement('name');
526
        $form->removeElement('addresult');
527
528
        /** @var HTML_QuickForm_select $slcLtiTools */
529
        $slcLtiTools = $form->createElement('select', 'name', $this->trans('External tool'));
530
        $form->insertElementBefore($slcLtiTools, 'hid_category_id');
531
        $form->addRule('name', get_lang('Required field'), 'required');
532
533
        $tools = $toolRepo->findBy([
534
            'course' => $course,
535
            'gradebookEval' => null,
536
        ]);
537
538
        /** @var ExternalTool $tool */
539
        foreach ($tools as $tool) {
540
            $slcLtiTools->addOption($tool->getTitle(), $tool->getId());
541
        }
542
543
        if (!$form->validate()) {
544
            return $this->render(
545
                '@ChamiloCore/Lti/gradebook.html.twig',
546
                [
547
                    'form' => $form->returnForm(),
548
                ]
549
            );
550
        }
551
552
        $values = $form->exportValues();
553
554
        $tool = $toolRepo->find($values['name']);
555
556
        if (empty($tool)) {
557
            throw $this->createNotFoundException();
558
        }
559
560
        $eval = new Evaluation();
561
        $eval->set_name($tool->getTitle());
562
        $eval->set_description($values['description']);
563
        $eval->set_user_id($values['hid_user_id']);
564
565
        if (!empty($values['hid_course_code'])) {
566
            $eval->set_course_code($values['hid_course_code']);
567
        }
568
569
        $eval->set_course_code($course->getCode());
570
        $eval->set_category_id($values['hid_category_id']);
571
572
        $values['weight'] = $values['weight_mask'];
573
574
        $eval->set_weight($values['weight']);
575
        $eval->set_max($values['max']);
576
        $eval->set_visible(empty($values['visible']) ? 0 : 1);
577
        $eval->add();
578
579
        $gradebookEval = $em->find('ChamiloCoreBundle:GradebookEvaluation', $eval->get_id());
580
581
        $tool->setGradebookEval($gradebookEval);
582
583
        $em->persist($tool);
584
        $em->flush();
585
586
        $this->addFlash('success', $this->trans('Evaluation for external tool added'));
587
588
        return $this->redirect(api_get_course_url());
589
    }
590
591
    private function variableSubstitution(
592
        array $params,
593
        array &$customParams,
594
        User $user,
595
        Course $course,
596
        ?Session $session = null
597
    ): void {
598
        $replaceable = self::getReplaceableVariables($user, $course, $session);
599
        $variables = array_keys($replaceable);
600
601
        foreach ($customParams as $customKey => $customValue) {
602
            if (!\in_array($customValue, $variables, true)) {
603
                continue;
604
            }
605
606
            $val = $replaceable[$customValue];
607
608
            if (\is_array($val)) {
609
                $val = current($val);
610
611
                if (\array_key_exists($val, $params)) {
612
                    $customParams[$customKey] = $params[$val];
613
614
                    continue;
615
                }
616
                $val = false;
617
            }
618
619
            if (false === $val) {
620
                $customParams[$customKey] = $customValue;
621
622
                continue;
623
            }
624
625
            $customParams[$customKey] = $replaceable[$customValue];
626
        }
627
    }
628
629
    private static function getReplaceableVariables(User $user, Course $course, ?Session $session = null): array
630
    {
631
        return [
632
            '$User.id' => $user->getId(),
633
            '$User.image' => ['user_image'],
634
            '$User.username' => $user->getUsername(),
635
636
            '$Person.sourcedId' => false,
637
            '$Person.name.full' => $user->getFullname(),
638
            '$Person.name.family' => $user->getLastname(),
639
            '$Person.name.given' => $user->getFirstname(),
640
            '$Person.name.middle' => false,
641
            '$Person.name.prefix' => false,
642
            '$Person.name.suffix' => false,
643
            '$Person.address.street1' => $user->getAddress(),
644
            '$Person.address.street2' => false,
645
            '$Person.address.street3' => false,
646
            '$Person.address.street4' => false,
647
            '$Person.address.locality' => false,
648
            '$Person.address.statepr' => false,
649
            '$Person.address.country' => false,
650
            '$Person.address.postcode' => false,
651
            '$Person.address.timezone' => false,
652
            // $user->getTimezone(),
653
            '$Person.phone.mobile' => false,
654
            '$Person.phone.primary' => $user->getPhone(),
655
            '$Person.phone.home' => false,
656
            '$Person.phone.work' => false,
657
            '$Person.email.primary' => $user->getEmail(),
658
            '$Person.email.personal' => false,
659
            '$Person.webaddress' => false,
660
            // $user->getWebsite(),
661
            '$Person.sms' => false,
662
663
            '$CourseTemplate.sourcedId' => false,
664
            '$CourseTemplate.label' => false,
665
            '$CourseTemplate.title' => false,
666
            '$CourseTemplate.shortDescription' => false,
667
            '$CourseTemplate.longDescription' => false,
668
            '$CourseTemplate.courseNumber' => false,
669
            '$CourseTemplate.credits' => false,
670
671
            '$CourseOffering.sourcedId' => false,
672
            '$CourseOffering.label' => false,
673
            '$CourseOffering.title' => false,
674
            '$CourseOffering.shortDescription' => false,
675
            '$CourseOffering.longDescription' => false,
676
            '$CourseOffering.courseNumber' => false,
677
            '$CourseOffering.credits' => false,
678
            '$CourseOffering.academicSession' => false,
679
680
            '$CourseSection.sourcedId' => ['lis_course_section_sourcedid'],
681
            '$CourseSection.label' => $course->getCode(),
682
            '$CourseSection.title' => $course->getTitle(),
683
            '$CourseSection.shortDescription' => false,
684
            '$CourseSection.longDescription' => $session && $session->getShowDescription()
685
                ? $session->getDescription()
686
                : false,
687
            '$CourseSection.courseNumber' => false,
688
            '$CourseSection.credits' => false,
689
            '$CourseSection.maxNumberofStudents' => false,
690
            '$CourseSection.numberofStudents' => false,
691
            '$CourseSection.dept' => false,
692
            '$CourseSection.timeFrame.begin' => $session && $session->getDisplayStartDate()
693
                ? $session->getDisplayStartDate()->format('Y-m-d\TH:i:sP')
694
                : false,
695
            '$CourseSection.timeFrame.end' => $session && $session->getDisplayEndDate()
696
                ? $session->getDisplayEndDate()->format('Y-m-d\TH:i:sP')
697
                : false,
698
            '$CourseSection.enrollControl.accept' => false,
699
            '$CourseSection.enrollControl.allowed' => false,
700
            '$CourseSection.dataSource' => false,
701
            '$CourseSection.sourceSectionId' => false,
702
703
            '$Group.sourcedId' => false,
704
            '$Group.grouptype.scheme' => false,
705
            '$Group.grouptype.typevalue' => false,
706
            '$Group.grouptype.level' => false,
707
            '$Group.email' => false,
708
            '$Group.url' => false,
709
            '$Group.timeFrame.begin' => false,
710
            '$Group.timeFrame.end' => false,
711
            '$Group.enrollControl.accept' => false,
712
            '$Group.enrollControl.allowed' => false,
713
            '$Group.shortDescription' => false,
714
            '$Group.longDescription' => false,
715
            '$Group.parentId' => false,
716
717
            '$Membership.sourcedId' => false,
718
            '$Membership.collectionSourcedId' => false,
719
            '$Membership.personSourcedId' => false,
720
            '$Membership.status' => false,
721
            '$Membership.role' => ['roles'],
722
            '$Membership.createdTimestamp' => false,
723
            '$Membership.dataSource' => false,
724
725
            '$LineItem.sourcedId' => false,
726
            '$LineItem.type' => false,
727
            '$LineItem.type.displayName' => false,
728
            '$LineItem.resultValue.max' => false,
729
            '$LineItem.resultValue.list' => false,
730
            '$LineItem.dataSource' => false,
731
732
            '$Result.sourcedGUID' => ['lis_result_sourcedid'],
733
            '$Result.sourcedId' => ['lis_result_sourcedid'],
734
            '$Result.createdTimestamp' => false,
735
            '$Result.status' => false,
736
            '$Result.resultScore' => false,
737
            '$Result.dataSource' => false,
738
739
            '$ResourceLink.title' => ['resource_link_title'],
740
            '$ResourceLink.description' => ['resource_link_description'],
741
        ];
742
    }
743
744
    private function createLtiLink(array &$contentItem, ExternalTool $baseTool): ExternalTool
745
    {
746
        $newTool = clone $baseTool;
747
        $newTool->setToolParent($baseTool);
748
        $newTool->setActiveDeepLinking(false);
749
750
        if (!empty($contentItem['title'])) {
751
            $newTool->setTitle($contentItem['title']);
752
        }
753
754
        if (!empty($contentItem['text'])) {
755
            $newTool->setDescription($contentItem['text']);
756
        }
757
758
        if (!empty($contentItem['url'])) {
759
            $newTool->setLaunchUrl($contentItem['url']);
760
        }
761
762
        if (!empty($contentItem['custom'])) {
763
            $newTool->setCustomParams(
764
                $newTool->encodeCustomParams($contentItem['custom'])
765
            );
766
        }
767
768
        $em = $this->managerRegistry->getManager();
769
770
        $course = $newTool->getCourse();
771
772
        $newTool->addCourseLink($course);
773
774
        $em->persist($newTool);
775
        $em->flush();
776
777
        /** @var User $user */
778
        $user = $this->getUser();
779
        $this->shortcutRepository->addShortCut($newTool, $user, $course);
780
781
        return $newTool;
782
    }
783
}
784