/** * {@inheritdoc} */ public function reverseTransform($media) { if (!$media instanceof MediaInterface) { return $media; } $binaryContent = $media->getBinaryContent(); // no binary if (empty($binaryContent)) { // and no media id if ($media->getId() === null && $this->options['empty_on_new']) { return; } elseif ($media->getId()) { return $media; } $media->setProviderStatus(MediaInterface::STATUS_PENDING); $media->setProviderReference(MediaInterface::MISSING_BINARY_REFERENCE); return $media; } // create a new media to avoid erasing other media or not ... $newMedia = $this->options['new_on_update'] ? new $this->class() : $media; $newMedia->setProviderName($media->getProviderName()); $newMedia->setContext($media->getContext()); $newMedia->setBinaryContent($binaryContent); if (!$newMedia->getProviderName() && $this->options['provider']) { $newMedia->setProviderName($this->options['provider']); } if (!$newMedia->getContext() && $this->options['context']) { $newMedia->setContext($this->options['context']); } $provider = $this->pool->getProvider($newMedia->getProviderName()); $provider->transform($newMedia); return $newMedia; }
/** * {@inheritdoc} */ public function buildEditForm(FormMapper $formMapper, BlockInterface $block) { $contextChoices = array(); foreach ($this->pool->getContexts() as $name => $context) { $contextChoices[$name] = $name; } $formMapper->add('settings', 'sonata_type_immutable_array', array('keys' => array(array('title', 'text', array('label' => 'form.label_title', 'required' => false)), array('number', 'integer', array('label' => 'form.label_number', 'required' => true)), array('context', 'choice', array('required' => true, 'label' => 'form.label_context', 'choices' => $contextChoices)), array('mode', 'choice', array('label' => 'form.label_mode', 'choices' => array('public' => 'form.label_mode_public', 'admin' => 'form.label_mode_admin'))), array('order', 'choice', array('label' => 'form.label_order', 'choices' => array('name' => 'form.label_order_name', 'createdAt' => 'form.label_order_created_at', 'updatedAt' => 'form.label_order_updated_at'))), array('sort', 'choice', array('label' => 'form.label_sort', 'choices' => array('desc' => 'form.label_sort_desc', 'asc' => 'form.label_sort_asc')))), 'translation_domain' => 'SonataMediaBundle')); }
/** * Add the meta information. * * @param SeoPageInterface $seoPage * @param ProductInterface $product */ public function alterPage(SeoPageInterface $seoPage, ProductInterface $product) { $seoPage->addMeta('name', 'twitter:card', 'product')->addMeta('name', 'twitter:title', $product->getName())->addMeta('name', 'twitter:description', substr($product->getDescription(), 0, 200))->addMeta('name', 'twitter:label1', 'Price')->addMeta('name', 'twitter:data1', $this->numberHelper->formatCurrency($product->getPrice(), $this->currencyDetector->getCurrency()))->addMeta('name', 'twitter:label2', 'SKU')->addMeta('name', 'twitter:data2', $product->getSku())->addMeta('name', 'twitter:site', $this->site)->addMeta('name', 'twitter:creator', $this->creator)->addMeta('name', 'twitter:domain', $this->domain); if ($image = $product->getImage()) { $provider = $this->mediaPool->getProvider($image->getProviderName()); $seoPage->addMeta('property', 'twitter:image:src', $provider->generatePublicUrl($image, $this->mediaFormat)); } }
/** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { $formats = $this->pool->getFormatNamesByContext($value->getContext()); if (!$value instanceof GalleryInterface) { $this->context->addViolationAtPath('defaultFormat', 'Invalid instance, expected GalleryInterface'); } if (!array_key_exists($value->getDefaultFormat(), $formats)) { $this->context->addViolation('invalid format'); } }
/** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addModelTransformer(new ProviderDataTransformer($this->pool, $this->class, array('provider' => $options['provider'], 'context' => $options['context'], 'empty_on_new' => $options['empty_on_new'], 'new_on_update' => $options['new_on_update']))); $builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) { if ($event->getForm()->has('unlink') && $event->getForm()->get('unlink')->getData()) { $event->setData(null); } }); $this->pool->getProvider($options['provider'])->buildMediaType($builder); $builder->add('unlink', 'checkbox', array('label' => 'widget_label_unlink', 'mapped' => false, 'data' => false, 'required' => false)); }
public function testReverseTransformValidProvider() { $provider = $this->getMock('Sonata\\MediaBundle\\Provider\\MediaProviderInterface'); $provider->expects($this->once())->method('transform'); $pool = new Pool('default'); $pool->addProvider('default', $provider); $media = $this->getMock('Sonata\\MediaBundle\\Model\\MediaInterface'); $media->expects($this->exactly(2))->method('getProviderName')->will($this->returnValue('default')); $transformer = new ProviderDataTransformer($pool); $transformer->reverseTransform($media); }
public function testReverseTransformWithMediaAndUploadFileInstance() { $provider = $this->getMock('Sonata\\MediaBundle\\Provider\\MediaProviderInterface'); $pool = new Pool('default'); $pool->addProvider('default', $provider); $media = $this->getMock('Sonata\\MediaBundle\\Model\\MediaInterface'); $media->expects($this->exactly(3))->method('getProviderName')->will($this->returnValue('default')); $media->expects($this->any())->method('getId')->will($this->returnValue(1)); $media->expects($this->any())->method('getBinaryContent')->will($this->returnValue(new UploadedFile(__FILE__, 'ProviderDataTransformerTest'))); $transformer = new ProviderDataTransformer($pool, 'stdClass', array('new_on_update' => false)); $transformer->reverseTransform($media); }
/** * {@Inheritdoc} * @param Image $image * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ public function getAdditionalData($image) { $media = $image->getFile(); $provider = $this->sonataMediaPool->getProvider($media->getProviderName()); $formatNames = $this->sonataMediaPool->getFormatNamesByContext($media->getContext()); $thumbnails = []; foreach ($formatNames as $formatName => $details) { $thumbnails[$formatName] = $this->generateFullPublicUrl($provider->generatePublicUrl($media, $formatName)); } $reference = $this->generateFullPublicUrl($provider->generatePublicUrl($media, 'reference')); return ['url' => $reference, 'thumbnails' => $thumbnails]; }
public function testValidateWithValidContext() { $pool = new Pool('defaultContext'); $pool->addContext('test'); $gallery = $this->getMock('Sonata\\MediaBundle\\Model\\GalleryInterface'); $gallery->expects($this->once())->method('getDefaultFormat')->will($this->returnValue('format1')); $gallery->expects($this->once())->method('getContext')->will($this->returnValue('test')); $context = $this->getMock('Symfony\\Component\\Validator\\ExecutionContext', array(), array(), '', false); $context->expects($this->once())->method('addViolation'); $validator = new FormatValidator($pool); $validator->initialize($context); $validator->validate($gallery, new ValidMediaFormat()); }
/** * {@inheritdoc} */ public function process(ConsumerEvent $event) { $media = $this->mediaManager->findOneBy(array('id' => $event->getMessage()->getValue('mediaId'))); if (!$media) { throw new HandlingException(sprintf('Media not found - id: %s', $event->getMessage()->getValue('mediaId'))); } // solve race condition between message queue and database transaction $media->setProviderReference($event->getMessage()->getValue('providerReference')); try { $this->getThumbnail($event)->generate($this->pool->getProvider($media->getProviderName()), $media); } catch (\LogicException $e) { throw new HandlingException(sprintf('Error while generating exception for media.id: %s', $event->getMessage()->getValue('mediaId')), 0, $e); } }
/** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { $formats = $this->pool->getFormatNamesByContext($value->getContext()); if (!$value instanceof GalleryInterface) { // Interface compatibility, support for LegacyExecutionContextInterface can be removed when support for Symfony <2.5 is dropped if ($this->context instanceof LegacyExecutionContextInterface) { $this->context->addViolationAt('defaultFormat', 'Invalid instance, expected GalleryInterface'); } else { $this->context->buildViolation('Invalid instance, expected GalleryInterface')->atPath('defaultFormat')->addViolation(); } } if (!array_key_exists($value->getDefaultFormat(), $formats)) { $this->context->addViolation('invalid format'); } }
/** * {@inheritdoc} */ public function getPersistentParameters() { $parameters = parent::getPersistentParameters(); if (!$this->hasRequest()) { return $parameters; } return array_merge($parameters, array('context' => $this->getRequest()->get('context', $this->pool->getDefaultContext()))); }
/** * Serialize images styles if the provider is an image type * * @param ObjectEvent $event */ public function onPostSerialize(ObjectEvent $event) { $visitor = $event->getVisitor(); $object = $event->getObject(); $context = $event->getContext(); if ($object instanceof Media) { $styles = []; $provider = $this->mediaPool->getProvider($object->getProviderName()); $formats = $this->mediaPool->getFormatNamesByContext($object->getContext()); if (is_array($formats)) { foreach ($formats as $formatName => $format) { $styles[$formatName] = $provider->generatePublicUrl($object, $formatName); } } $visitor->addData('src', $provider->generatePublicUrl($object, 'reference')); $visitor->addData('styles', $styles); } }
/** * {@inheritdoc} */ protected function configureFormFields(FormMapper $formMapper) { // define group zoning $formMapper->with('Gallery', array('class' => 'col-md-9'))->end()->with('Options', array('class' => 'col-md-3'))->end(); $context = $this->getPersistentParameter('context'); if (!$context) { $context = $this->pool->getDefaultContext(); } $formats = array(); foreach ((array) $this->pool->getFormatNamesByContext($context) as $name => $options) { $formats[$name] = $name; } $contexts = array(); foreach ((array) $this->pool->getContexts() as $contextItem => $format) { $contexts[$contextItem] = $contextItem; } $formMapper->with('Options')->add('context', 'choice', array('choices' => $contexts, 'translation_domain' => 'SonataMediaBundle'))->add('enabled', null, array('required' => false))->add('name')->add('defaultFormat', 'choice', array('choices' => $formats))->end()->with('Gallery')->add('galleryHasMedias', 'sonata_type_collection', array('cascade_validation' => true), array('edit' => 'inline', 'inline' => 'table', 'sortable' => 'position', 'link_parameters' => array('context' => $context), 'admin_code' => 'sonata.media.admin.gallery_has_media'))->end(); }
/** * Returns media urls for each format * * @ApiDoc( * requirements={ * {"name"="id", "dataType"="integer", "requirement"="\d+", "description"="media id"}, * {"name"="format", "dataType"="string", "description"="media format"} * }, * statusCodes={ * 200="Returned when successful", * 404="Returned when media is not found" * } * ) * * @param integer $id The media id * @param string $format The format * @param Request $request * * @return \Symfony\Component\HttpFoundation\Response */ public function getMediumBinaryAction($id, $format, Request $request) { $media = $this->getMedium($id); $response = $this->mediaPool->getProvider($media->getProviderName())->getDownloadResponse($media, $format, $this->mediaPool->getDownloadMode($media)); if ($response instanceof BinaryFileResponse) { $response->prepare($request); } return $response; }
/** * Adds a medium of given provider * If you need to upload a file (depends on the provider) you will need to do so by sending content as a multipart/form-data HTTP Request * See documentation for more details. * * @ApiDoc( * resource=true, * input={"class"="sonata_media_api_form_media", "name"="", "groups"={"sonata_api_write"}}, * output={"class"="Sonata\MediaBundle\Model\Media", "groups"={"sonata_api_read"}}, * statusCodes={ * 200="Returned when successful", * 400="Returned when an error has occurred while medium creation", * 404="Returned when unable to find medium" * } * ) * * @Route(requirements={"provider"="[A-Za-z0-9.]*"}) * * @param string $provider A media provider * @param Request $request A Symfony request * * @return Media * * @throws NotFoundHttpException */ public function postProviderMediumAction($provider, Request $request) { $medium = $this->mediaManager->create(); $medium->setProviderName($provider); try { $mediaProvider = $this->mediaPool->getProvider($provider); } catch (\RuntimeException $ex) { throw new NotFoundHttpException($ex->getMessage(), $ex); } return $this->handleWriteMedium($request, $medium, $mediaProvider); }
public function testExecuteWithNew() { $context = array('providers' => array(), 'formats' => array(), 'download' => array()); $this->pool->expects($this->any())->method('getContexts')->will($this->returnValue(array('foo' => $context))); $contextModel = $this->getMock('Sonata\\ClassificationBundle\\Model\\ContextInterface'); $this->contextManger->expects($this->once())->method('findOneBy')->with($this->equalTo(array('id' => 'foo')))->will($this->returnValue(null)); $this->contextManger->expects($this->once())->method('create')->will($this->returnValue($contextModel)); $this->contextManger->expects($this->once())->method('save')->with($this->equalTo($contextModel)); $category = $this->getMock('Sonata\\ClassificationBundle\\Model\\CategoryInterface'); $this->categoryManger->expects($this->once())->method('getRootCategory')->with($this->equalTo($contextModel))->will($this->returnValue(null)); $this->categoryManger->expects($this->once())->method('create')->will($this->returnValue($category)); $this->categoryManger->expects($this->once())->method('save')->with($this->equalTo($category)); $output = $this->tester->execute(array()); $this->assertRegExp('@ > default category for \'foo\' is missing, creating one\\s+Done!@', $this->tester->getDisplay()); $this->assertSame(0, $output); }
/** * @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')); }
/** * {@inheritdoc} */ protected function configureFormFields(FormMapper $formMapper) { $media = $this->getSubject(); if (!$media) { $media = $this->getNewInstance(); } if (!$media || !$media->getProviderName()) { return; } $formMapper->add('providerName', 'hidden'); $formMapper->getFormBuilder()->addModelTransformer(new ProviderDataTransformer($this->pool, $this->getClass()), true); $provider = $this->pool->getProvider($media->getProviderName()); if ($media->getId()) { $provider->buildEditForm($formMapper); } else { $provider->buildCreateForm($formMapper); } $formMapper->add('category', 'sonata_type_model_list', array(), array('link_parameters' => array('context' => $media->getContext(), 'hide_context' => true, 'mode' => 'tree'))); }
/** * @param MediaInterface $media * * @return MediaProviderInterface */ private function getProvider(MediaInterface $media) { return $this->pool->getProvider($media->getProviderName()); }
/** * {@inheritdoc} */ public function getObjectMetadata($object) { $provider = $this->pool->getProvider($object->getProviderName()); $url = $provider->generatePublicUrl($object, $provider->getFormatName($object, 'admin')); return new Metadata($object->getName(), $object->getDescription(), $url); }
/** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->addModelTransformer(new ProviderDataTransformer($this->mediaPool, $this->class, array('empty_on_new' => false)), true); $provider = $this->mediaPool->getProvider($options['provider_name']); $provider->buildMediaType($builder); }
/** * @param MediaInterface $image * @param SeoPageInterface $seoPage */ protected function addImageInfo(MediaInterface $image, SeoPageInterface $seoPage) { $provider = $this->mediaPool->getProvider($image->getProviderName()); $seoPage->addMeta('property', 'og:image', $provider->generatePublicUrl($image, $this->mediaFormat))->addMeta('property', 'og:image:width', $image->getWidth())->addMeta('property', 'og:image:height', $image->getHeight())->addMeta('property', 'og:image:type', $image->getContentType()); }