Create form for media entity, use for edit or add a media

@param Media $media
@return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
195277
private function createMedia(Media $media)
    {
        $request = $this->getRequest();
        $thumbSizes = $this->container->getParameter('fulgurio_light_cms.thumbs');
        $form = $this->createForm(new AdminMediaType($this->container), $media);
        $formHandler = new AdminMediaHandler();
        $formHandler->setForm($form)
                ->setRequest($request)
                ->setDoctrine($this->getDoctrine())
                ->setUser($this->getUser())
                ->setMediaLibraryService($this->get('fulgurio_light_cms.media_library'));
        if ($formHandler->process($media))
        {
            if ($request->isXmlHttpRequest())
            {
                return $this->jsonResponse((object) array('files' => array(
                    (object) array(
                        'id' => $media->getId(),
                        'name' => $media->getOriginalName(),
                        'url' => $media->getFullPath(),
                        'thumbnail_url' => LightCMSUtils::getThumbFilename($media->getFullPath(), $media->getMediaType(), $thumbSizes['medium']),
                        'delete_url' => $this->generateUrl('AdminMediasRemove', array('mediaId' => $media->getId(), 'confirm' => 'yes')),
                        'delete_type' => 'GET'
                    )
                )));
            }
            $this->get('session')->getFlashBag()->add(
                'success',
                $this->get('translator')->trans(
                    isset($options['pageId']) ? 'fulgurio.lightcms.medias.edit_form.success_msg' : 'fulgurio.lightcms.medias.add_form.success_msg',
                    array(),
                    'admin'
                )
            );
            return $this->redirect($this->generateUrl('AdminMedias'));
        }
        else if ($request->isXmlHttpRequest())
        {
            //@todo : well, we only manage one error, not the others ...
            return $this->jsonResponse((object) array('files' => array(
                    (object) array(
                            'error' => $this->get('translator')->trans('fulgurio.lightcms.medias.add_form.error_msg', array('%MAX_FILE_SIZE%' => ini_get('upload_max_filesize')), 'admin'),
                    )
            )));
        }
        $options['form'] = $form->createView();
        return $this->render('FulgurioLightCMSBundle:AdminMedia:add.html.twig', $options);
    }
1318672
public function moveMedia(Request $request)
    {
        @trigger_error(sprintf('The "%s" controller action is deprecated in KunstmaanMediaBundle 5.1 and will be removed in KunstmaanMediaBundle 6.0.', __METHOD__), E_USER_DEPRECATED);

        $mediaId = $request->request->get('mediaId');
        $folderId = $request->request->get('folderId');

        if (empty($mediaId) || empty($folderId)) {
            return new JsonResponse(['error' => ['title' => 'Missing media id or folder id']], 400);
        }

        $em = $this->getDoctrine()->getManager();
        $mediaRepo = $em->getRepository('KunstmaanMediaBundle:Media');

        $media = $mediaRepo->getMedia($mediaId);
        $folder = $em->getRepository('KunstmaanMediaBundle:Folder')->getFolder($folderId);

        $media->setFolder($folder);
        $mediaRepo->save($media);

        return new JsonResponse();
    }
1066079
public function deleteAction(Request $request, Media $media)
    {
        $user = $this->getBlogUser();
        $mediaLibrary = $this->container->get('sonata.media.manager.gallery')->findOneBy(array('name' => 'Media Library'));
        $em = $this->getDoctrine()->getManager();

        foreach($media->getGalleryHasMedias() as $hasMedia)
        {
            if($hasMedia->getGallery() == $mediaLibrary)
            {
                $em->remove($hasMedia);
            }
        }

        $em->flush();

        if($request->isXmlHttpRequest())
        {
            return new JsonResponse(array('success' => 'true'));
        }

        $this->get('session')->getFlashBag()->add('success', 'Photo removed successfully.');
        return $this->redirectToRoute('ed_blog_admin_media_list');
    }
509499
public function searchMediaAction(Request $request)
    {
        $response = $this->getFilter($request);
        if ($response['success'] === false) {
            return $response['value'];
        }
        $filter = $response['crypted'];

        $mm = $this->getMediaManager();

        $q = ($request->query->has('q')) ? $request->query->get('q') : null;
        $type = ($request->query->has('type')) ? $request->query->get('type') : null;

        $medias = $mm->search($filter, $q, $type);

        return $this->createResponse($medias);
    }
602989
public function save(MediaInterface $media): MediaInterface
    {
        $data = $this->serializer()->serialize($media);

        if ($media->getId() !== 0) {
            $this->shopware()
                 ->put('/api/media/'.(string)$media->getId(), [], $data);
        } else {
            $response = $this->shopware()->post('/api/media', [], $data);
            $data     = json_decode((string)$response->getBody(), true);
            $media->setId((int)$data['data']['id']);
        }

        return $media;
    }
897458
public function renderMedia(MediaInterface $media, array $options)
    {
        $options = $this->validateOptions($options, __METHOD__);

        return $this->render(
            'OpenOrchestraMediaBundle:RenderMedia:default.html.twig',
            array(
                'media_url' => $this->getFileUrl($media->getFilesystemName()),
                'media_name' => $media->getName(),
                'id' => $options['id'],
                'class' => $options['class'],
                'style' => $options['style']
            )
        );
    }
91490
public function getHandler($media)
    {
        foreach ($this->handlers as $handler) {
            if ($handler->canHandle($media)) {
                return $handler;
            }
        }

        return new FileHandler();
    }
1144822
public function postAction(Request $request)
    {
        $contentUid = $request->request->get('content_uid');
        $contentType = $request->request->get('content_type', null);
        $mediaFolderUid = $request->request->get('folder_uid', null);
        $mediaTitle = $request->request->get('title', 'Untitled media');

        if (null === $mediaFolderUid) {
            $mediaFolder = $this->getMediaFolderRepository()->getRoot();
        } else {
            $mediaFolder = $this->getMediaFolderRepository()->find($mediaFolderUid);
        }

        if (null === $mediaFolder) {
            throw new NotFoundHttpException('Cannot find a media folder');
        }

        if (null !== $content = $this->getClassContentManager()->findOneByTypeAndUid($contentType, $contentUid)) {
            $this->autoCommitContent($content);
        }

        $media = new Media();
        $media->setContent($content);
        $media->setTitle($mediaTitle);
        $media->setMediaFolder($mediaFolder);

        $this->getEntityManager()->persist($media);
        $this->getEntityManager()->flush();

        return $this->createJsonResponse(null, 201, [
            'BB-RESOURCE-UID' => $media->getId(),
            'Location'        => $this->getApplication()->getRouting()->getUrlByRouteName(
                'bb.rest.media.get',
                [
                    'version' => $request->attributes->get('version'),
                    'uid'     => $media->getId(),
                ],
                '',
                false
            ),
        ]);
    }
1157924
public function postMediaAction(Request $request)
    {
        $response = $this->getFilter($request);
        if ($response['success'] === false) {
            return $response['value'];
        }
        $filter = $response['value'];

        $mm = $this->getMediaManager();

        $media = $mm->create();
        $media
            ->setFilter($filter)
            ->setCryptedFilter($response['crypted'])
            ;

        if (!$request->files->has('file')) {
            return new Response($this->get('translator')->trans('error.fileNotFound', array(), 'ApoutchikaMediaBundle'), 500);
        }

        $media->setFile($request->files->get('file'));

        if ($mm->save($media) === false) {
            $error = $mm->getError();

            return new Response($this->get('translator')->trans($error[0], $error[1], 'ApoutchikaMediaBundle'), 500);
        }

        return $this->createResponse($media, $request->request->has('iframe'));
    }
1096951
public function process(Media $media)
    {
        if ($this->request->getMethod() == 'POST')
        {
            $this->form->handleRequest($this->request);
            if ($this->form->isValid())
            {
                $file = $this->form->get('media')->getData();
                if (!is_null($file))
                {
                    $media->setMediaType($file->getMimeType());
                    $media->setOriginalName($file->getClientOriginalName());
                    $filename = $this->mediaLibraryService->add($file, $media);
                    if ($filename)
                    {
                        // New media
                        if ($media->getId() == 0)
                        {
                            if (is_a($this->user, 'Symfony\Component\Security\Core\User\UserInterface')
                                    && method_exists($this->user, 'getId'))
                            {
                                $media->setOwnerId($this->user->getId());
                            }
                        }
                        else
                        {
                            // We remove old files
                            $this->mediaLibraryService->remove($media);
                        }

                        // We set new file
                        $media->setFullPath($filename);

                        $em = $this->doctrine->getManager();
                        $em->persist($media);
                        $em->flush();
                        return TRUE;
                    }
                }
            }
        }
        return FALSE;
    }
600962
public function getMediasAction(Request $request)
    {
        if (!$request->query->has('filters')) {
            return $this->createResponse(array());
        }

        $mediaManager = $this->getMediaManager();

        $filtersKeys = explode(',', $request->query->get('filters'));
        $medias = $mediaManager->findAllByFiltersKeys($filtersKeys);

        return $this->createResponse($medias);
    }
295047
protected function createMediaEntity( $item ) {
		$m = new \Pressbooks\Entities\Cloner\Media();

		$m->id = $item['post_id'];
		$m->title = $item['post_title'];
		$m->description = $item['post_content'];
		$m->caption = $item['post_excerpt'];

		if ( isset( $item['postmeta'] ) && is_array( $item['postmeta'] ) ) {
			foreach ( $item['postmeta'] as $meta ) {
				if ( str_starts_with( $meta['key'], '_' ) === false ) {
					$m->meta[ $meta['key'] ] = $meta['value'];
				}
				if ( $meta['key'] === '_wp_attachment_image_alt' ) {
					$m->altText = $meta['value'];
				}
			}
		}

		$m->sourceUrl = $item['attachment_url'];

		return $m;
	}
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()];
    }
1371621
public function saveMedia()
    {
        $mediaMapper = ($this->container->dataMapper)('MediaMapper');
        $mediaCategoryMapper = ($this->container->dataMapper)('MediaCategoryMapper');

        $media = $mediaMapper->make();
        $media->id = $this->request->getParsedBodyParam('id');
        $media->caption = $this->request->getParsedBodyParam('caption');
        $mediaMapper->save($media);

        // Save category mappings
        $mediaCategoryMapper->saveMediaCategoryAssignments($media->id, $this->request->getParsedBodyParam('category'));

        // Set the response type
        if ($this->request->isXhr()) {
            $r = $this->response->withHeader('Content-Type', 'application/json');
            return $r->write(json_encode(["status" => "success"]));
        }

        return $this->redirect('adminShowMedia');
    }
816826
public function createAction(Request $request)
    {
        $templateRepository = $this->get('phlexible_media_template.template_manager');

        $type = $request->get('type');
        $key = $request->get('key');

        switch ($type) {
            case 'image':
                $template = new ImageTemplate();
                $template->setCache(false);
                break;
            case 'video':
                $template = new VideoTemplate();
                $template->setCache(true);
                break;
            case 'audio':
                $template = new AudioTemplate();
                $template->setCache(true);
                break;
            default:
                throw new InvalidArgumentException("Unknown template type $type");
        }

        $template->setKey($key);

        $templateRepository->updateTemplate($template);

        return new ResultResponse(true, 'New "'.$type.'" template "'.$key.'" created.');
    }
374990
public function editAction(Request $request, $id)
    {
        $mediaManager = $this->get('opifer.media.media_manager');
        $media = $mediaManager->getRepository()->find($id);

        $dispatcher = $this->get('event_dispatcher');
        $event = new MediaResponseEvent($media, $request);
        $dispatcher->dispatch(OpiferMediaEvents::MEDIA_CONTROLLER_EDIT, $event);

        if (null !== $event->getResponse()) {
            return $event->getResponse();
        }

        $provider = $this->get('opifer.media.provider.pool')->getProvider($media->getProvider());

        // Clone the old Media, so we don't perform any useless actions inside the provider
        $media->old = clone $media;

        $form = $this->createForm(MediaType::class, $media, ['provider' => $provider]);
        $form->handleRequest($request);

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

            $this->addFlash('success', sprintf('%s was succesfully updated', $media->getName()));

            return $this->redirectToRoute('opifer_media_media_index');
        }

        return $this->render($this->container->getParameter('opifer_media.media_edit_view'), [
            'form' => $form->createView(),
            'media' => $media,
        ]);
    }
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;
    }