Write a medium, this method is used by both POST and PUT action methods.

@param Request                $request
@param MediaInterface         $media
@param MediaProviderInterface $provider

@return View|FormInterface
430022
protected function handleWriteMedium(Request $request, MediaInterface $media, MediaProviderInterface $provider)
    {
        $form = $this->formFactory->createNamed(null, 'sonata_media_api_form_media', $media, [
            'provider_name' => $provider->getName(),
            'csrf_protection' => false,
        ]);

        $form->handleRequest($request);

        if ($form->isValid()) {
            $media = $form->getData();
            $this->mediaManager->save($media);

            $context = new Context();
            $context->setGroups(['sonata_api_read']);
            $context->enableMaxDepth();

            $view = FOSRestView::create($media);
            $view->setContext($context);

            return $view;
        }

        return $form;
    }
208064
public function redirectAction(Request $request, $id)
    {
        $locale = $this->getRequestParameter($request, 'locale', true);
        $format = $this->getRequestParameter($request, 'format');

        /** @var Media $media */
        $media = $this->container->get('sulu_media.media_manager')->getById($id, $locale);

        if (null === $format) {
            return $this->redirect($media->getUrl());
        }

        if (!array_key_exists($format, $media->getFormats())) {
            throw $this->createNotFoundException();
        }

        return $this->redirect($media->getFormats()[$format]);
    }
1342164
public function negotiate($request)
    {
        $media = $this->_classes['media'];
        foreach ($request->accepts() as $mime => $value) {
            if ($format = $media::suitable($request, $mime)) {
                $this->format($format);
                return;
            }
        }
        $mimes = join('", "', array_keys($request->accepts()));
        throw new NetException("Unsupported Media Type: [\"{$mimes}\"].", 415);
    }
905908
public function postAction($id, Request $request)
    {
        return $this->addMediaToEntity($this->getAccountEntityName(), $id, $request->get('mediaId', ''));
    }
955261
public function putAction(Request $request, $id)
    {
        /** @var RoleInterface $role */
        $role = $this->getRoleRepository()->findRoleById($id);

        try {
            if (!$role) {
                throw new EntityNotFoundException($this->getRoleRepository()->getClassName(), $id);
            } else {
                $em = $this->getDoctrine()->getManager();

                $name = $request->get('name');

                $role->setName($name);
                $role->setSystem($request->get('system'));

                if (!$this->processPermissions($role, $request->get('permissions', []))) {
                    throw new RestException('Could not update dependencies!');
                }

                $securityTypeData = $request->get('securityType');
                if ($this->checkSecurityTypeData($securityTypeData)) {
                    $this->setSecurityType($role, $securityTypeData);
                } else {
                    $role->setSecurityType(null);
                }

                $em->flush();
                $view = $this->view($this->convertRole($role), 200);
            }
        } catch (EntityNotFoundException $enfe) {
            $view = $this->view($enfe->toArray(), 404);
        } catch (DoctrineUniqueConstraintViolationException $e) {
            throw new RoleNameAlreadyExistsException($name);
        } catch (RestException $re) {
            $view = $this->view($re->toArray(), 400);
        }

        return $this->handleView($view);
    }
532089
public function store( Request $request )
    {
        $data = $request->getContent();
        $patientInterface = $this->patientAdapter->toPatientInterface( $data );
        $this->patientRepository->create( $patientInterface );
        // TODO return response code
    }
595679
public function configureAction(Request $request)
    {
        $this->checkAdmin();
        $mediacenterManager = $this->getMediacenterManager();
        $mediacenter = $mediacenterManager->getMediacenterOrEmpty();
        try {
            $mediacenter = $mediacenterManager->processForm($mediacenter, $request);
        } catch (InvalidMediacenterFormException $imfe) {
            return ['form' => $imfe->getForm()->createView()];
        }

        $response = $this->forward(
            'IcapInwicastBundle:MediaCenter:success',
            [
                'mediacenter' => $mediacenter,
            ]
        );

        return $response;
    }
469383
private function saveFile(MediaInterface $media)
    {
        $file = $media->getFile();

        $fileInfo = new FileInfo($file);
        $type = $fileInfo->getType();

        $media->setType($type);

        if ($media->getName() === null) {
            $media->setName($fileInfo->getName());
            $media->setAlt($fileInfo->getName());
        }

        $media
            ->setMimeType($fileInfo->getMimeType())
            ->setExtension($fileInfo->getExtension())
            ;

        if (!$this->createReference($media)) {
            return false;
        }

        $key = $this->originalDir.'/'.$media->getReference();
        $this->filesystemManipulator->save($key, $file->getPathname());

        $this->setSizeWidthAndHeight($media);

        $media->setFile();

        if ($this->limit === null || $media->getType() !== $media::IMAGE) {
            return $media;
        }

        // resize if image > limit
        if ($media->getWidth() > $this->limit || $media->getHeight() > $this->limit) {
            $resize = new Resize($this, $media);
            $resize->setTargetSize($this->limit, $this->limit);
            $resize->apply();
        }

        return $media;
    }
518921
public function showMediaAction(Request $request, Media $media, $filter = null)
    {
        $response = new Response();
        $lastModified = new \DateTime('now');

        //Checking if it is an image or not
        $src = $this->get('alpixel_media.manager')->getAbsolutePath($media);
        $isImage = @getimagesize($src);

        try {
            if ($isImage) {
                $response->headers->set('Content-disposition', 'inline;filename='.$media->getName());
                if (!empty($filter) && $isImage) {
                    $src = $this->get('alpixel_media.manager')->getAbsolutePath($media, $filter);
                    $dataManager = $this->get('liip_imagine.data.manager'); // the data manager service
                    $filterManager = $this->get('liip_imagine.filter.manager'); // the filter manager service
                    $uploadDir = $this->get('alpixel_media.manager')->getUploadDir($filter);

                    if (!is_file($src)) {
                        $fs = new Filesystem();
                        if (!$fs->exists($uploadDir.$media->getFolder())) {
                            $fs->mkdir($uploadDir.$media->getFolder());
                        }

                        $path = 'upload/'.$media->getUri();

                        // find the image and determine its type
                        $image = $dataManager->find($filter, $path);

                        // run the filter
                        $responseData = $filterManager->applyFilter($image, $filter);
                        $data = $responseData->getContent();
                        file_put_contents($uploadDir.$media->getUri(), $data);
                    } else {
                        $data = file_get_contents($src);
                        $lastModified->setTimestamp(filemtime($src));
                    }
                } else {
                    $src = $this->get('alpixel_media.manager')->getAbsolutePath($media);
                    $lastModified->setTimestamp(filemtime($src));
                    $data = file_get_contents($src);
                }
            } else {
                $lastModified->setTimestamp(filemtime($src));
                $data = file_get_contents($src);
                $response->headers->set('Content-disposition', 'attachment;filename='.basename($media->getUri()));
            }

            if ($data === false) {
                throw $this->createNotFoundException();
            }
        } catch (\Exception $e) {
            throw $this->createNotFoundException($e->getMessage());
        }

        $response->setLastModified($lastModified);
        $response->setPublic();
        $response->headers->set('Content-Type', $media->getMime());

        if ($response->isNotModified($request)) {
            return $response;
        }

        $response->setContent($data);

        return $response;
    }
1058798
public function preSave(MediaInterface $media)
    {
        preg_match('/(?<=v(\=|\/))([-a-zA-Z0-9_]+)|(?<=youtu\.be\/)([-a-zA-Z0-9_]+)/', $media->getReference(), $matches);

        $media->setReference($matches[2]);

        //Check if the reference already exists
        if (!isset($media->old) && $referenceMedia = $this->mediaManager->getRepository()->findOneBy(['reference' => $media->getReference()])) {
            throw new \Exception(sprintf('Video with reference: %s already exists for under the name: %s', $media->getReference(), $referenceMedia->getName()));
        }

        if (!isset($media->old) || $media->old->getReference() !== $media->getReference()) {
            $this->updateMedadata($media);
        }
    }
628522
public function deleteAction($id, Request $request)
    {
        try {
            $mediaManager = $this->getMediaManager();

            $locale = $this->getLocale($request);

            $media = $mediaManager->getById($id, $locale);
            /** @var MediaInterface $mediaEntity */
            $mediaEntity = $media->getEntity();

            if (null !== $mediaEntity->getPreviewImage()) {
                $oldPreviewImageId = $mediaEntity->getPreviewImage()->getId();

                $mediaEntity->setPreviewImage(null);

                $mediaManager->delete($oldPreviewImageId);
            }

            $view = $this->view(null, 204);
        } catch (MediaNotFoundException $e) {
            $view = $this->view($e->toArray(), 404);
        } catch (MediaException $e) {
            $view = $this->view($e->toArray(), 400);
        }

        return $this->handleView($view);
    }
137954
public function newAction(Request $request)
    {
        $stream = $this->get('oktolab_media_stream')->createStream();
        $form = $this->createForm(StreamType::class, $stream);
        $form->add(
            'submit',
            SubmitType::class,
            [
                'label' => 'oktolab_media.new_stream_button',
                'attr' => ['class' => 'btn btn-primary']
            ]
        );

        if ($request->getMethod() == "POST") {
            $form->handleRequest($request);
            if ($form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $em->persist($stream);
                $em->flush();

                $this->get('session')->getFlashBag()->add(
                    'success',
                    'oktolab_media.success_create_stream'
                );

                return $this->redirect(
                    $this->generateUrl(
                        'oktolab_media_stream_show',
                        ['uniqID' => $stream->getUniqID()]
                    )
                );
            } else {
                $this->get('session')->getFlashBag()->add(
                    'error',
                    'oktolab_media.error_create_stream'
                );
            }
        }

        return ['form'   => $form->createView()];
    }
531703
public function importMediaAction(Request $request)
    {
        if (!$request->isXmlHttpRequest()) {
            throw new NotFoundHttpException();
        }

        $modal = $this->createModal();
        $modal->setTitle('ekyna_media.import.title');

        $folderId = $request->attributes->get('id');
        $folder = $this->findFolderById($folderId);

        $import = new MediaImport($folder);

        $flow = $this->get('ekyna_media.import_media.form_flow');
        $flow->bind($import);

        $form = $flow->createForm();
        if ($flow->isValid($form)) {
            $flow->saveCurrentStepData($form);

            if ($flow->nextStep()) {
                $form = $flow->createForm();
            } else {
                // TODO use ResourceManager
                $operator = $this->get('ekyna_media.media.operator');
                foreach ($import->getMedias() as $media) {
                    $event = $operator->create($media);
                    if ($event->isPropagationStopped()) {
                        $this->addFlash(sprintf('Failed to create "%s" media.', $media->getPath()), 'danger');
                    }
                }

                $modal->setContent(array('success' => true));
                return $this->get('ekyna_core.modal')->render($modal);
            }
        }

        $modal->setContent($form->createView());

        return $this->get('ekyna_core.modal')->render($modal);
    }
1302496
public function handleForm(FormPageInterface $page, Request $request, RenderContext $context)
    {
        /* @var $em EntityManager */
        $em = $this->container->get('doctrine.orm.entity_manager');
        /* @var $formBuilder FormBuilderInterface */
        $formBuilder = $this->container->get('form.factory')->createBuilder(FormType::class);
        /* @var $router RouterInterface */
        $router = $this->container->get('router');
        /* @var $fields ArrayObject */
        $fields = new ArrayObject();
        $pageParts = $em->getRepository('KunstmaanPagePartBundle:PagePartRef')->getPageParts($page, $page->getFormElementsContext());
        foreach ($pageParts as $sequence => $pagePart) {
            if ($pagePart instanceof FormAdaptorInterface) {
                $pagePart->adaptForm($formBuilder, $fields, $sequence);
            }
        }

        $form = $formBuilder->getForm();
        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);
            if ($form->isSubmitted() && $form->isValid()) {
                $formSubmission = new FormSubmission();
                $formSubmission->setIpAddress($request->getClientIp());
                $formSubmission->setNode($em->getRepository('KunstmaanNodeBundle:Node')->getNodeFor($page));
                $formSubmission->setLang($request->getLocale());
                $em->persist($formSubmission);

                /* @var $field FormSubmissionField */
                foreach ($fields as $field) {
                    $field->setSubmission($formSubmission);
                    $field->onValidPost($form, $formBuilder, $request, $this->container);
                    $em->persist($field);
                }

                $em->flush();
                $em->refresh($formSubmission);

                $event = new SubmissionEvent($formSubmission, $page);
                $this->container->get('event_dispatcher')->dispatch(FormEvents::ADD_SUBMISSION, $event);

                return new RedirectResponse($page->generateThankYouUrl($router, $context));
            }
        }
        $context['frontendform'] = $form->createView();
        $context['frontendformobject'] = $form;

        return null;
    }
221995
public function mapProviderSave(ServerRequestInterface $request): ResponseInterface
    {
        $provider = $request->getParsedBody()['provider'] ?? '';

        Site::setPreference('map-provider', $provider);

        return redirect(route('admin-control-panel'));
    }
1327611
public function formAction(Request $request, $mediaId)
    {
        $media = $this->get('open_orchestra_media.repository.media')->find($mediaId);
        $this->denyAccessUnlessGranted(ContributionActionInterface::EDIT, $media);

        $formTypeAlias = $this->get('open_orchestra_media_admin.media_form.manager')->getFormType($media);

        $form = $this->createForm($formTypeAlias, $media, array(
            'action' => $this->generateUrl('open_orchestra_media_admin_media_form', array(
                'mediaId' => $mediaId,
            )),
            'enable_delete_button' => $this->get('open_orchestra_backoffice.business_rules_manager')->isGranted(ContributionActionInterface::DELETE, $media),
            'delete_button' => $this->isGranted(ContributionActionInterface::DELETE, $media)
        ));

        $form->handleRequest($request);
        if ($form->isValid()) {
            $this->get('open_orchestra_media_admin.media_form.manager')->runAdditionalProcess($media, $form);
            $this->dispatchEvent(MediaEvents::MEDIA_UPDATE, new MediaEvent($media));
            $this->get('session')->getFlashBag()->add(
                'success',
                $this->get('translator')->trans('open_orchestra_media_admin.form.media.success')
            );
        }

        return $this->renderAdminForm($form);
    }
1041884
public function viewImageAction(Request $request, $id, $format = MediaProviderInterface::FORMAT_REFERENCE)
    {
        $media = $this->getMedia($id);

        if (!$media) {
            throw new NotFoundHttpException(sprintf('unable to find the media with the id : %s', $id));
        }

        if (!$this->get('sonata.media.pool')->getDownloadStrategy($media)->isGranted($media, $request)) {
            throw new AccessDeniedException();
        }
        $provider = $this->getProvider($media);

        return new RedirectResponse($provider->generatePublicUrl($media, $format));
    }