Get chapter by its slug.

@EXT\Route("/chapters/{chapterSlug}", name="apiv2_lesson_chapter_get")
@EXT\Method("GET")

@param Request $request
@param Lesson  $lesson
@param string  $chapterSlug

@return JsonResponse
976895
public function getAction(Request $request, Lesson $lesson, $chapterSlug)
    {
        $this->checkPermission('OPEN', $lesson->getResourceNode(), [], true);

        $chapter = $this->chapterRepository->getChapterBySlug($chapterSlug, $lesson->getId());

        if (is_null($chapter)) {
            throw new NotFoundHttpException();
        }

        return new JsonResponse($this->chapterSerializer->serialize($chapter));
    }
1166841
public static function load($lessonid) {
        global $DB;

        if (!$lesson = $DB->get_record('lesson', array('id' => $lessonid))) {
            print_error('invalidcoursemodule');
        }
        return new lesson($lesson);
    }
251183
protected function cgetContent(Request $request)
    {
        $parent = $request->get('parentId');
        $properties = array_filter(explode(',', $request->get('fields', '')));
        $excludeGhosts = $this->getBooleanRequestParameter($request, 'exclude-ghosts', false, false);
        $excludeShadows = $this->getBooleanRequestParameter($request, 'exclude-shadows', false, false);
        $expandedIds = $this->getRequestParameter(
            $request,
            'expandedIds',
            false,
            $this->getRequestParameter($request, 'selectedIds', false, null)
        );
        $webspaceNodes = $this->getRequestParameter($request, 'webspace-nodes');
        $locale = $this->getLocale($request);
        $webspaceKey = $this->getRequestParameter($request, 'webspace', false);

        if (!$locale) {
            throw new MissingParameterException(get_class($this), 'locale');
        }

        if (!$webspaceKey && !$webspaceNodes && !$parent) {
            throw new MissingParameterChoiceException(get_class($this), ['webspace', 'webspace-nodes', 'parentId']);
        }

        if (!in_array($webspaceNodes, [self::WEBSPACE_NODE_SINGLE, static::WEBSPACE_NODES_ALL, null])) {
            throw new ParameterDataTypeException(get_class($this), 'webspace-nodes');
        }

        $contentRepository = $this->get('sulu_page.content_repository');
        $user = $this->getUser();

        $mapping = MappingBuilder::create()
            ->setHydrateGhost(!$excludeGhosts)
            ->setHydrateShadow(!$excludeShadows)
            ->setResolveConcreteLocales(true)
            ->addProperties($properties)
            ->setResolveUrl(true)
            ->getMapping();

        try {
            if ($expandedIds) {
                return $this->getTreeContent($expandedIds, $locale, $webspaceKey, $webspaceNodes, $mapping, $user);
            }
        } catch (EntityNotFoundException $e) {
            $view = $this->view($e->toArray(), 404);

            return $this->handleView($view);
        }

        $contents = [];

        if ($parent) {
            $contents = $contentRepository->findByParentUuid($parent, $locale, $webspaceKey, $mapping, $user);
        } elseif ($webspaceKey) {
            $contents = $contentRepository->findByWebspaceRoot($locale, $webspaceKey, $mapping, $user);
        }

        if ($webspaceNodes === static::WEBSPACE_NODES_ALL) {
            $contents = $this->getWebspaceNodes($mapping, $contents, $locale, $user);
        } elseif ($webspaceNodes === static::WEBSPACE_NODE_SINGLE) {
            $contents = $this->getWebspaceNode($mapping, $contents, $webspaceKey, $locale, $user);
        }

        $list = new CollectionRepresentation($contents, static::$relationName);
        $view = $this->view($list);

        return $this->handleView($view);
    }
1038466
public function treeAction(Request $request)
    {
        $language = $request->get('language');
        $treeId = (int) $request->get('tid');

        if (!$treeId || !$language) {
            return new Response('', 500);
        }

        $translator = $this->get('translator');
        $treeManager = $this->get('phlexible_tree.tree_manager');
        $teaserService = $this->get('phlexible_teaser.teaser_service');
        $elementService = $this->get('phlexible_element.element_service');
        $elementSourceManager = $this->get('phlexible_element.element_source_manager');
        $iconResolver = $this->get('phlexible_element.icon_resolver');

        $tree = $treeManager->getByNodeId($treeId);
        $treeNode = $tree->get($treeId);
        $element = $elementService->findElement($treeNode->getTypeId());
        $elementMasterLanguage = $element->getMasterLanguage();
        $elementtype = $elementService->findElementtype($element);

        $treeNodePath = $tree->getPath($treeNode);

        $layouts = [];
        $layoutareas = [];
        // TODO: repair
        foreach ($elementSourceManager->findElementtypesByType('layout') as $layoutarea) {
            if (in_array($elementtype, $elementService->findAllowedParents($layoutarea))) {
                $layoutareas[] = $layoutarea;
            }
        }

        foreach ($layoutareas as $layoutarea) {
            $teasers = $teaserService->findForLayoutAreaAndTreeNodePath($layoutarea, $treeNodePath);
            $areaRoot = [
                'id' => 'area_'.$layoutarea->getId(),
                'area_id' => $layoutarea->getId(),
                'parent_tid' => $treeId,
                'parent_eid' => $element->getEid(),
                'text' => $layoutarea->getTitle(),
                'icon' => $iconResolver->resolveElementtype($layoutarea),
                'type' => $layoutarea->getType(),
                'inherited' => null, //true,
                'cls' => 'siteroot-node',
                'leaf' => true,
                'expanded' => true,
                'allowDrag' => true,
                'allowDrop' => false,
                'children' => [],
                'qtip' => $translator->trans('elements.doubleclick_to_sort', [], 'gui'),
            ];

            foreach ($teasers as $teaser) {
                /* @var $teaser Teaser */
                $teaserData = [
                    'id' => $teaser->getId(),
                    'layoutarea_id' => $layoutarea->getId(),
                    'parent_tid' => $treeId,
                    'parent_eid' => $element->getEid(),
                    'type' => $teaser->getType(),
                    'sort' => $teaser->getInheritSort($treeId),
                    'inherited' => false,
                    'inherit' => false,
                    'leaf' => true,
                    'hide' => false,
                    'expanded' => false,
                    'cls' => '',
                    'children' => [],
                    'allowDrag' => false,
                    'allowDrop' => false,
                ];

                switch ($teaser->getType()) {
                    case 'inherited':
                    case 'teaser':
                    case 'element':
                        $teaserElement = $elementService->findElement($teaser->getTypeId());
                        $teaserElementVersion = $elementService->findLatestElementVersion($teaserElement);

                        $cls = '';
                        if (!$teaser->isStopped()) {
                            $cls .= 'inherit ';
                        }
                        if ($teaser->isHidden()) {
                            $cls .= 'dont-show ';
                        }
                        if ($teaser->getTreeId() !== $treeId) {
                            $cls .= 'inherited ';
                        }

                        $teaserData = array_merge(
                            $teaserData,
                            [
                                'text' => $teaserElementVersion->getBackendTitle($language),
                                'icon' => $iconResolver->resolveTeaser($teaser, $language),
                                'eid' => $teaserElement->getEid(),
                                'inherited' => $teaser->getTreeId() !== $treeId,
                                'inherit' => !$teaser->isStopped(),
                                'cls' => trim($cls),
                                'hide' => $teaser->isHidden(),
                            ]
                        );
                        break;

                    default:
                        continue;
                }

                $areaRoot['children'][] = $teaserData;
            }

            if (count($areaRoot['children'])) {
                $areaRoot['leaf'] = false;
            }

            $layouts[] = $areaRoot;
        }

        return new JsonResponse($layouts);
    }
744568
public function display_eol_page(lesson $lesson, $data) {

        $output = '';
        $canmanage = $lesson->can_manage();
        $course = $lesson->courserecord;

        if ($lesson->custom && !$canmanage && (($data->gradeinfo->nquestions < $lesson->minquestions))) {
            $output .= $this->box_start('generalbox boxaligncenter');
        }

        if ($data->gradelesson) {
            // We are using level 3 header because the page title is a sub-heading of lesson title (MDL-30911).
            $output .= $this->heading(get_string("congratulations", "lesson"), 3);
            $output .= $this->box_start('generalbox boxaligncenter');
        }

        if ($data->notenoughtimespent !== false) {
            $output .= $this->paragraph(get_string("notenoughtimespent", "lesson", $data->notenoughtimespent), 'center');
        }

        if ($data->numberofpagesviewed !== false) {
            $output .= $this->paragraph(get_string("numberofpagesviewed", "lesson", $data->numberofpagesviewed), 'center');
        }
        if ($data->youshouldview !== false) {
            $output .= $this->paragraph(get_string("youshouldview", "lesson", $data->youshouldview), 'center');
        }
        if ($data->numberofcorrectanswers !== false) {
            $output .= $this->paragraph(get_string("numberofcorrectanswers", "lesson", $data->numberofcorrectanswers), 'center');
        }

        if ($data->displayscorewithessays !== false) {
            $output .= $this->box(get_string("displayscorewithessays", "lesson", $data->displayscorewithessays), 'center');
        } else if ($data->displayscorewithoutessays !== false) {
            $output .= $this->box(get_string("displayscorewithoutessays", "lesson", $data->displayscorewithoutessays), 'center');
        }

        if ($data->yourcurrentgradeisoutof !== false) {
            $output .= $this->paragraph(get_string("yourcurrentgradeisoutof", "lesson", $data->yourcurrentgradeisoutof), 'center');
        }
        if ($data->eolstudentoutoftimenoanswers !== false) {
            $output .= $this->paragraph(get_string("eolstudentoutoftimenoanswers", "lesson"));
        }
        if ($data->welldone !== false) {
            $output .= $this->paragraph(get_string("welldone", "lesson"));
        }

        if ($data->progresscompleted !== false) {
            $output .= $this->progress_bar($lesson, $data->progresscompleted);
        }

        if ($data->displayofgrade !== false) {
            $output .= $this->paragraph(get_string("displayofgrade", "lesson"), 'center');
        }

        $output .= $this->box_end(); // End of Lesson button to Continue.

        if ($data->reviewlesson !== false) {
            $output .= html_writer::link($data->reviewlesson, get_string('reviewlesson', 'lesson'), array('class' => 'centerpadded lessonbutton standardbutton p-r-1'));
        }
        if ($data->modattemptsnoteacher !== false) {
            $output .= $this->paragraph(get_string("modattemptsnoteacher", "lesson"), 'centerpadded');
        }

        if ($data->activitylink !== false) {
            $output .= $data->activitylink;
        }

        $url = new moodle_url('/course/view.php', array('id' => $course->id));
        $output .= html_writer::link($url, get_string('returnto', 'lesson', format_string($course->fullname, true)),
                array('class' => 'centerpadded lessonbutton standardbutton p-r-1'));

        if (has_capability('gradereport/user:view', context_course::instance($course->id))
                && $course->showgrades && $lesson->grade != 0 && !$lesson->practice) {
            $url = new moodle_url('/grade/index.php', array('id' => $course->id));
            $output .= html_writer::link($url, get_string('viewgrades', 'lesson'),
                array('class' => 'centerpadded lessonbutton standardbutton p-r-1'));
        }
        return $output;
    }
847126
public function findAction(Request $request, $class)
    {
        $query = $request->query->all();
        $data = $this->finder->fetch($class, $query['filters'], [], 0, 2);

        $options = $this->options['get'];

        if (isset($query['options'])) {
            $options = $query['options'];
        }

        switch (count($data)) {
            case 0:
                return new JsonResponse('No object found', 404);
                break;
            case 1:
                return new JsonResponse(
                    $this->serializer->serialize($data[0], $options)
                );
                break;
            default:
                return new JsonResponse('Multiple results, use "list" instead', 400);
        }
    }
706852
public function queryAnswerTrain(Request $request)
    {
        if (null === $optionsSerial = $request->get('options_serial')) {
            $this->app->abort(400, 'Search engine options are missing');
        }

        try {
            $options = SearchEngineOptions::hydrate($this->app, $optionsSerial);
        } catch (\Exception $e) {
            $this->app->abort(400, 'Provided search engine options are not valid');
        }

        $pos = (int) $request->request->get('pos', 0);
        $query = $request->request->get('query', '');

        $record = new \record_preview($this->app, 'RESULT', $pos, '', $this->getSearchEngine(), $query, $options);

        $index = ($pos - 3) < 0 ? 0 : ($pos - 3);
        return $this->app->json([
            'current' => $this->render('prod/preview/result_train.html.twig', [
                'records'  => $record->get_train(),
                'index' => $index,
                'selected' => $pos,
            ])
        ]);
    }
650947
public static function getClass(Request $Request)
    {
        foreach (static::$_registry as $registered) {
            if (in_array($Request->ext, $registered['extensions'])) {
                return $registered['resolve']($Request);
            }
        }

        throw new ErrorException("The following extension is not handled: {$Request->ext}");
    }
257222
private function callLaravelRoute(Request $request): \Symfony\Component\HttpFoundation\Response
    {
        $kernel = app(\Illuminate\Contracts\Http\Kernel::class);
        $response = $kernel->handle($request);
        $kernel->terminate($request, $response);

        return $response;
    }
324728
protected function nextStep(Request $request)
    {
        // Apply the current step. If success, we can redirect to next one
        $currentStep = \SetupWizard::currentStep();
        if (!$currentStep->apply($request->all())) {
            return view()->make('setup_wizard::steps.default', ['errors' => $currentStep->getMessageBag()]);
        }

        // If we have a next step, go for it. Else we redirect to somewhere else
        try {
            $nextStep = \SetupWizard::nextStep();

            return redirect()->route('setup_wizard.show', ['slug' => $nextStep->getSlug()]);
        } catch (StepNotFoundException $e) {
            $finalRouteName = config('setup_wizard.routing.success_route', '');
            if (!empty($finalRouteName)) return redirect()->route($finalRouteName);

            $finalRouteUrl = config('setup_wizard.routing.success_url', '');
            if (!empty($finalRouteUrl)) return redirect()->to($finalRouteUrl);

            return redirect('/');
        }
    }
84909
public function cgetAction(Request $request)
    {
        $locale = $this->getUser()->getLocale();

        if ('true' == $request->get('flat')) {
            /** @var RestHelperInterface $restHelper */
            $restHelper = $this->get('sulu_core.doctrine_rest_helper');

            $fieldDescriptors = $this->getFieldDescriptors();
            $listBuilder = $this->generateFlatListBuilder();
            $restHelper->initializeListBuilder($listBuilder, $fieldDescriptors);
            $this->applyRequestParameters($request, $listBuilder);

            $listResponse = $listBuilder->execute();
            $listResponse = $this->addLogos($listResponse, $locale);

            $list = new ListRepresentation(
                $listResponse,
                self::$entityKey,
                'get_accounts',
                $request->query->all(),
                $listBuilder->getCurrentPage(),
                $listBuilder->getLimit(),
                $listBuilder->count()
            );
            $view = $this->view($list, 200);
        } else {
            $filter = $this->retrieveFilter($request);
            $accountManager = $this->getAccountManager();
            $accounts = $accountManager->findAll($locale, $filter);
            $list = new CollectionRepresentation($accounts, self::$entityKey);
            $view = $this->view($list, 200);
        }

        $context = new Context();
        $context->setGroups(['fullAccount', 'partialContact', 'Default']);
        $view->setContext($context);

        return $this->handleView($view);
    }
419093
public function cgetAction(Request $request)
    {
        $webspaceKey = $request->get('webspace');

        /** @var WebspaceManagerInterface $webspaceManager */
        $webspaceManager = $this->get('sulu_core.webspace.webspace_manager');

        $webspace = $webspaceManager->findWebspaceByKey($webspaceKey);

        if ($webspace) {
            $localizations = new CollectionRepresentation($webspace->getAllLocalizations(), 'localizations');
            $view = $this->view($localizations, 200);
        } else {
            $error = new RestException(sprintf('No webspace found for key \'%s\'', $webspaceKey));
            $view = $this->view($error->toArray(), 400);
        }

        return $this->handleView($view);
    }
213072
public function getAction(Request $request)
    {
        $structureProvider = $this->get('sulu.content.structure_manager');
        $type = $request->get('type', 'default');

        $templates = [];
        foreach ($structureProvider->getStructures('article') as $structure) {
            if ($this->getType($structure->getStructure()) !== $type) {
                continue;
            }

            $templates[] = [
                'internal' => $structure->getInternal(),
                'template' => $structure->getKey(),
                'title' => $structure->getLocalizedTitle($this->getUser()->getLocale()),
            ];
        }

        return new JsonResponse(
            [
                '_embedded' => $templates,
                'total' => count($templates),
            ]
        );
    }
1248207
public function previewAction(Request $request)
    {
        $tid = $request->get('tid');
        $teaserId = $request->get('teaser_id', null);
        $language = $request->get('language');
        $languages = $request->get('languages');
        $version = $request->get('version', null);
        $includeElements = (bool) $request->get('include_elements', false);
        $includeElementInstances = (bool) $request->get('include_element_instances', false);
        $includeTeasers = (bool) $request->get('include_teasers', false);
        $includeTeaserInstances = (bool) $request->get('include_teaser_instances', false);
        $recursive = (bool) $request->get('recursive', false);
        $onlyOffline = (bool) $request->get('only_offline', false);
        $onlyAsync = (bool) $request->get('only_async', false);

        if ($languages) {
            $languages = explode(',', $languages);
        } else {
            $languages = [$language];
        }

        $selector = $this->get('phlexible_element.publish.selector');
        $iconResolver = $this->get('phlexible_element.icon_resolver');

        $selection = new Selection();
        foreach ($languages as $language) {
            $langSelection = $selector->select(
                $tid,
                $language,
                $version,
                $includeElements,
                $includeElementInstances,
                $includeTeasers,
                $includeTeaserInstances,
                $recursive,
                $onlyOffline,
                $onlyAsync
            );
            $selection->merge($langSelection);
        }

        $result = [];
        foreach ($selection->all() as $selectionItem) {
            if ($selectionItem->getTarget() instanceof TreeNodeInterface) {
                $id = $selectionItem->getTarget()->getId();
                $icon = $iconResolver->resolveTreeNode($selectionItem->getTarget(), $selectionItem->getLanguage());
            } else {
                $id = $selectionItem->getTarget()->getId();
                $icon = $iconResolver->resolveTeaser($selectionItem->getTarget(), $selectionItem->getLanguage());
            }

            $result[] = [
                'type' => $selectionItem->getTarget() instanceof TreeNodeInterface ? 'full_element' : 'part_element',
                'instance' => $selectionItem->isInstance(),
                'depth' => $selectionItem->getDepth(),
                'path' => $selectionItem->getPath(),
                'id' => $id,
                'eid' => $selectionItem->getTarget()->getTypeId(),
                'version' => $selectionItem->getVersion(),
                'language' => $selectionItem->getLanguage(),
                'title' => $selectionItem->getTitle(),
                'icon' => $icon,
                'action' => true,
            ];
        }

        return new JsonResponse(['preview' => $result]);
    }
1309750
protected function getRequestClass($request)
    {
        $parts = explode('\\', $request);
        $lastIndex = count($parts) - 1;

        switch ($parts[$lastIndex]) {
            case 'Void':
                $parts[$lastIndex] = 'Cancel';
                break;
            case 'AVS':
            case 'INPay':
            case 'ABNiDEAL':
                $this->throwDeprecatedTransactionType();
                break;
            case 'Payin':
            case 'Payout':
                if ($this->getParentClass($parts, $lastIndex) === 'Citadel') {
                    $this->throwDeprecatedTransactionType();
                }
                break;
            case 'oBeP':
                if ($this->getParentClass($parts, $lastIndex) === 'PayByVouchers') {
                    $this->throwDeprecatedTransactionType();
                }
                break;
        }

        return sprintf(
            '\Genesis\API\Request\%s',
            implode('\\', $parts)
        );
    }
441827
protected function getSession(Request $request) : Session\Session
    {
        $session = $request->getAttribute(SessionHandler::SESSION_ATTRIBUTE);

        if (! $session instanceof Session\Session) {
            throw new \Exception(
                'Session not available in request at: '
                . SessionHandler::SESSION_ATTRIBUTE
            );
        }
        return $session;
    }
616909
public function copyBulkAction(Request $request, $class)
    {
        $query = $request->query->all();
        $serializer = $this->serializer;
        $options = $this->options['copyBulk'];

        if (isset($query['options'])) {
            $options = $query['options'];
        }

        $copies = $this->crud->copyBulk(
            $class,
            $this->decodeIdsString($request, $class),
            $options
        );

        return new JsonResponse(array_map(function ($copy) use ($serializer, $options) {
            return $serializer->serialize($copy, $this->options['get']);
        }, $copies), 200);
    }