/**
  * @throws NotFoundHttpException
  *
  * @param string $id
  *
  * @return MediaInterface
  */
 private function getMedia($id)
 {
     $media = $this->mediaManager->findOneBy(array('id' => $id));
     if (!$media) {
         throw new NotFoundHttpException('Media not found');
     }
     return $media;
 }
 /**
  * Retrieves media with id $id or throws an exception if not found
  *
  * @param $id
  *
  * @return Media
  * @throws \Symfony\Component\Security\Core\Exception\AccessDeniedException
  * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  */
 protected function getMedium($id)
 {
     $media = $this->mediaManager->findOneBy(array('id' => $id));
     if (null === $media) {
         throw new NotFoundHttpException(sprintf('Media (%d) was not found', $id));
     }
     return $media;
 }
 /**
  * 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
  */
 protected function handleWriteMedium(Request $request, MediaInterface $media, MediaProviderInterface $provider)
 {
     $form = $this->formFactory->createNamed(null, 'sonata_media_api_form_media', $media, array('provider_name' => $provider->getName(), 'csrf_protection' => false));
     $form->handleRequest($request);
     if ($form->isValid()) {
         $media = $form->getData();
         $this->mediaManager->save($media);
         $view = FOSRestView::create($media);
         $serializationContext = SerializationContext::create();
         $serializationContext->setGroups(array('sonata_api_read'));
         $serializationContext->enableMaxDepthChecks();
         $view->setSerializationContext($serializationContext);
         return $view;
     }
     return $form;
 }
 /**
  * @param Request $request
  * @param string  $hash
  * @param string  $id
  *
  * @return RedirectResponse
  */
 public function targetAction(Request $request, $hash, $id)
 {
     $media = $this->getMedia($id);
     $this->checkMedia($hash, $media);
     $provider = $this->pool->getProvider($media->getProviderName());
     /*
      * Pixlr send back the new image as an url, add some security check before downloading the file
      */
     if (!preg_match($this->allowEreg, $request->get('image'), $matches)) {
         throw new NotFoundHttpException(sprintf('Invalid image host : %s', $request->get('image')));
     }
     $file = $provider->getReferenceFile($media);
     $file->setContent(file_get_contents($request->get('image')));
     $provider->updateMetadata($media);
     $provider->generateThumbnails($media);
     $this->mediaManager->save($media);
     return new Response($this->templating->render('SonataMediaBundle:Extra:pixlr_exit.html.twig'));
 }