Голосование в опросе.

@param  ItemsServiceContract  $pollsService
@param  Request  $request

@return VoteResponseContract

@throws BindingResolutionException
171300
public function vote(
        ItemsServiceContract $pollsService,
        Request $request
    ): VoteResponseContract {
        $pollID = $request->get('id', 0);
        $optionID = $request->get('answer', 0);

        $item = $pollsService->vote($pollID, $optionID);

        return $this->app->make(VoteResponseContract::class, compact('item'));
    }
1098915
public function updateRole($roleId, Request $request)
    {
        $createStruct = $this->inputDispatcher->parse(
            new Message(
                array('Content-Type' => $request->headers->get('Content-Type')),
                $request->getContent()
            )
        );

        return $this->roleService->updateRole(
            $this->roleService->loadRole($roleId),
            $this->mapToUpdateStruct($createStruct)
        );
    }
759020
protected function resolveValidator(Request $request)
    {
        if (! isset($this->validators[$request->getHandler()])) {
            return null;
        }

        try {
            $validatorClass = $this->validators[$request->getHandler()];
            return $this->container->make($validatorClass);
        } catch (BindingResolutionException $e) {
            return null;
        }
    }
1212449
public function transform(PollOptionModelContract $item): array
    {
        return [
            'id' => $item['id'],
            'answer' => $item['answer'],
            'votes' => $item['votes_count'],
            'votes_percent' => ($this->totalVotes == 0) ? 0 : round(($item['votes_count'] / $this->totalVotes) * 100),
        ];
    }
12677
public function bindRequest(Request $request)
    {
        $query = $request->query;
        $session = $request->getSession();

        $adminListName = 'listconfig_' . $request->get('_route');

        $this->page = $request->query->getInt('page', 1);
        $this->limit = $request->query->getInt('limit', $this->getLimitOptions()[0]);

        $adminListSessionData = $request->getSession()->get($adminListName);
        if (!$query->has('limit') && null !== $adminListSessionData && isset($adminListSessionData['limit'])) {
            $this->limit = $adminListSessionData['limit'];
        }

        if ($request->query->has('limit') && !$request->query->has('page')) {
            $this->page = 1;
        }

        // Allow alphanumeric, _ & . in order by parameter!
        $this->orderBy = preg_replace('/[^[a-zA-Z0-9\_\.]]/', '', $request->query->get('orderBy', ''));
        $this->orderDirection = $request->query->getAlpha('orderDirection', '');

        // there is a session and the filter param is not set
        if ($session->has($adminListName) && !$query->has('filter')) {
            if (!$query->has('page') && !$query->has('limit')) {
                $this->page = $adminListSessionData['page'];
            }

            if (!$query->has('orderBy')) {
                $this->orderBy = $adminListSessionData['orderBy'];
            }

            if (!$query->has('orderDirection')) {
                $this->orderDirection = $adminListSessionData['orderDirection'];
            }
        }

        // save current parameters
        $session->set(
            $adminListName,
            [
                'page' => $this->page,
                'limit' => $this->limit,
                'orderBy' => $this->orderBy,
                'orderDirection' => $this->orderDirection,
            ]
        );

        // Remove limit from query param so it doesn't affect the session of the filter builder
        $request->query->remove('limit');
        $this->getFilterBuilder()->bindRequest($request);
    }
631832
public function createAnswer(int $pollId, string $answer): PodiumResponse
    {
        /* @var $pollAnswerForm AnswerFormInterface */
        $pollAnswerForm = $this->getAnswerForm();

        $pollAnswerForm->setPollId($pollId);
        $pollAnswerForm->setAnswer($answer);

        return $pollAnswerForm->create();
    }
336882
public function execute(ViewPostRequest $request)
    {
        $post = $this->repository->findById(new PostId($request->getId()));

        if (null === $post) {
            throw new PostDoesNotExistException();
        }

        return $post;
    }
1205061
public function generalFormAction(Request $request)
    {
        $descriptions = $this->contentManager->getTranslatedContent(array('type' => 'platformDescription'));
        $platformConfig = $this->configHandler->getPlatformConfig();
        $role = $this->roleManager->getRoleByName($platformConfig->getDefaultRole());
        $form = $this->formFactory->create(
            new AdminForm\GeneralType(
                $this->localeManager->getAvailableLocales(),
                $role,
                $descriptions,
                $this->translator->trans('date_form_format', array(), 'platform'),
                $this->localeManager->getUserLocale($request),
                $this->configHandler->getLockedParamaters()
            ),
            $platformConfig
        );

        if ($this->request->isMethod('POST')) {
            $form->handleRequest($request);
            if ($form->isValid()) {
                try {
                    $portfolioUrlOptions = $request->get('portfolioUrlOptions', 0);
                    $this->configHandler->setParameters(
                        array(
                            'allow_self_registration' => $form['selfRegistration']->getData(),
                            'locale_language' => $form['localeLanguage']->getData(),
                            'name' => $form['name']->getData(),
                            'support_email' => $form['support_email']->getData(),
                            'default_role' => $form['defaultRole']->getData()->getName(),
                            'redirect_after_login' => $form['redirect_after_login']->getData(),
                            'form_captcha' => $form['formCaptcha']->getData(),
                            'platform_init_date' => $form['platform_init_date']->getData(),
                            'platform_limit_date' => $form['platform_limit_date']->getData(),
                            'account_duration' => $form['account_duration']->getData(),
                            'anonymous_public_profile' => $form['anonymous_public_profile']->getData(),
                            'portfolio_url' => $portfolioUrlOptions ? $form['portfolio_url']->getData() : null,
                            'is_notification_active' => $form['isNotificationActive']->getData(),
                            'max_storage_size' => $form['maxStorageSize']->getData(),
                            'max_upload_resources' => $form['maxUploadResources']->getData(),
                            'max_workspace_users' => $form['workspaceMaxUsers']->getData(),
                            'show_help_button' => $form['showHelpButton']->getData(),
                            'help_url' => $form['helpUrl']->getData(),
                            'register_button_at_login' => $form['registerButtonAtLogin']->getData(),
                            'send_mail_at_workspace_registration' => $form['sendMailAtWorkspaceRegistration']->getData(),
                            'domain_name' => $form['domainName']->getData(),
                            'default_workspace_tag' => $form['defaultWorkspaceTag']->getData(),
                            'registration_mail_validation' => $form['registrationMailValidation']->getData(),
                            'is_pdf_export_active' => $form['isPdfExportActive']->getData(),
                        )
                    );

                    $content = $request->get('platform_parameters_form');

                    if (isset($content['description'])) {
                        $descriptionContent = $this->contentManager->getContent(array('type' => 'platformDescription'));
                        if ($descriptionContent) {
                            $this->contentManager->updateContent($descriptionContent, $content['description']);
                        } else {
                            $this->contentManager->createContent($content['description'], 'platformDescription');
                        }
                    }

                    $logo = $request->files->get('logo');

                    if ($logo) {
                        $this->get('claroline.common.logo_service')->createLogo($logo);
                    }

                    $this->addFlashMessage('general_parameters_updated_success');

                    return $this->redirect($this->generateUrl('claro_admin_index'));
                } catch (UnwritableException $e) {
                    $form->addError(
                        new FormError(
                            $this->translator->trans(
                                'unwritable_file_exception',
                                array('%path%' => $e->getPath()),
                                'platform'
                            )
                        )
                    );
                }
            }
        }
        $event = $this->eventDispatcher->dispatch(
            'claroline_retrieve_tags',
            'GenericDatas',
            array()
        );
        $response = $event->getResponse();
        $tags = is_array($response) ? $response : array();

        return array(
            'form_settings' => $form->createView(),
            'logos' => $this->get('claroline.common.logo_service')->listLogos(),
            'tags' => $tags
        );
    }
848344
public function createView(Request $request)
    {
        $viewInput = $this->inputDispatcher->parse(
            new Message(
                array('Content-Type' => $request->headers->get('Content-Type')),
                $request->getContent()
            )
        );

        if ($viewInput->query instanceof LocationQuery) {
            $method = 'findLocations';
        } else {
            $method = 'findContent';
        }

        return new Values\RestExecutedView(
            array(
                'identifier' => $viewInput->identifier,
                'searchResults' => $this->searchService->$method(
                    $viewInput->query,
                    ['languages' => Language::ALL]
                ),
            )
        );
    }
268521
public function listPlatformRolesAction(Request $request)
    {
        return new JsonResponse(
            $this->finder->search('Claroline\CoreBundle\Entity\Role', array_merge(
                $request->query->all(),
                ['hiddenFilters' => ['type' => 1]]
            ))
        );
    }
307636
public function bindContext($context, Request $request)
    {
        $security = $this->getSecurity($context);

        $this->container->instance(SecurityApi::class, $security);

        $this->container->bind(UrlGeneratorContract::class, function() use ($security){
            return $security->url();
        });

        $this->container->bind(UrlGenerator::class, function(Container $container) use ($security){
            /** @var PermissionAwareUrlGeneratorExtension $url */
            $url = $container->make(PermissionAwareUrlGeneratorExtension::class);
            $url->setUrlGenerator($security->url());

            return $url;
        });

        $this->container->alias(UrlGenerator::class, 'url');

        $request->setUserResolver(function() use ($security){
            return $security->getUser();
        });
    }
954786
public function injectParticipants(Poll $poll)
    {
        $info = $this->injectInfo($poll);
        $options = $poll->getOptions();
        $countOptions = count($options);
        $participants = [];
        foreach ($info['participants'] as $p) {
            $preferences = [];
            for ($i = 0; $i < $countOptions; $i++) {
                $preferences[] = new Preference($options[$i], $p['preferences'][$i]);
            }

            $participant = new Participant($p['id']);
            $participant
                ->setName($p['name'])
                ->setAvatar(isset($p['largeAvatarUrl']) ? $p['largeAvatarUrl'] : '')
                ->setPreferences($preferences)
                ->setUserBehindParticipant(isset($p['userId']) ? $p['userId'] : '');

            $participants[] = $participant;
        }
        $poll->setParticipants($participants);
    }
308025
public function addChoiceAction(Request $request)
    {
        $manager = $this->getDoctrine()->getManager();
        $class = $request->get('class');
        if ($class === null) {
            throw new \Exception('"class" parameter not sent');
        }
        $field = $request->get('field');
        if ($field === null) {
            throw new \Exception('"field" parameter not sent');
        }
        $value = $request->get('value');
        if ($value === null) {
            throw new \Exception('"value" parameter not sent');
        }
        $choice = new $class();
        $choice->setLabel($field);
        $choice->setValue($value);
        $manager->persist($choice);
        $manager->flush();

        return new JsonResponse(array(
            'name'  => $choice->getLabel(),
            'value' => $choice->getValue(),
            'id'    => $choice->getId(),
            )
        );
    }
227054
public function upVoteAction(Request $request)
    {
        $reference = $request->get('reference');
        $value = $request->get('value');
        $this->get('event_dispatcher')->dispatch(Events::VOTE_UP, new UpVoteEvent($request, $reference, $value));

        return;
    }
1195265
public function updateManyToOneAction(Request $request)
    {
        /** @var AbstractAdmin $admin */
        $admin = $this->getAdmin();

        $admin->checkAccess('edit');

        $em = $admin->getDoctrine()->getManager();

        $ids = $request->request->get('value');
        $id = $request->request->get('pk');
        $field = $request->request->get('field');

        $object = $admin->getObject($id);

        /** @var \Sonata\DoctrineORMAdminBundle\Model\ModelManager $mm */
        $mm = $admin->getModelManager();

        $ClassMetadata = $mm->getMetadata($admin->getClass());

        $associationMapping = $ClassMetadata->getAssociationMapping($field);

        $items = $em->getRepository($associationMapping['targetEntity'])->find($ids);

        \call_user_func([$object, 'set' . ucfirst($field)], $items);

        $admin->update($object);

        $result = [
        ];

        $associationAdmin = $admin->getAdminByClass($associationMapping['targetEntity']);

        $twigSonataAdminExtension = $admin->getContainer()->get('sonata.admin.twig.extension');

        $fieldDescription = $admin->getListFieldDescription($field);

        if ($items) {
            $result[] = [
                'id' => $items->getId(),
                'label' => $twigSonataAdminExtension->renderRelationElement($items, $fieldDescription),
                'edit_url' => $associationAdmin->generateObjectUrl('edit', $items),
            ];
        }

        return new JsonResponse([
            'items' => $result,
        ]);
    }
811459
public function bind(Request $request)
    {
        $this->compileRoute();

        $this->parameters = (new RouteParameterBinder($this))
                        ->parameters($request);

        $this->originalParameters = $this->parameters;

        return $this;
    }
1326146
protected function save(
        ItemsServiceContract $resourceService,
        SaveItemRequestContract $request,
        int $id = 0
    ): SaveResponseContract {
        $data = $request->all();

        $item = $resourceService->save($data, $id);

        return $this->app->make(SaveResponseContract::class, compact('item'));
    }