예제 #1
0
 /**
  * Returns a list of uploadable fields for the given object and mapping.
  *
  * @param mixed $object The object to use.
  *
  * @return array<string> A list of field names.
  */
 protected function getUploadableFields($object)
 {
     $fields = $this->metadata->getUploadableFields(ClassUtils::getClass($object), $this->mapping);
     return array_map(function ($data) {
         return $data['propertyName'];
     }, $fields);
 }
 /**
  * Dans le cas d'un document nouvellement enregistré, je vais renommer le nom du fichier uploadé si besoin
  * @param  LifecycleEventArgs $eventArgs [description]
  * @return [type]                        [description]
  */
 public function postPersist(LifecycleEventArgs $eventArgs)
 {
     $document = $eventArgs->getDocument();
     $dm = $eventArgs->getDocumentManager();
     $is_uploadable = $this->metadata_reader->isUploadable(ClassUtils::getClass($document));
     if ($is_uploadable) {
         // Récupération des champs uploadable
         $fields = $this->metadata_reader->getUploadableFields(ClassUtils::getClass($document));
         // Pour chacun de ces champs, je récupère le mapping associé pour vérifier le namer et le nom du champ
         foreach ($fields as $field) {
             $mapping = $this->mapping_factory->fromField($document, $field['propertyName']);
             if ($mapping->getNamer() instanceof \Redking\Bundle\UploadBundle\Naming\ObjectNamer) {
                 $filename = $mapping->getFileName($document);
                 $file = $mapping->getFile($document);
                 // Si il y a bien un fichier, je vérifie son nom
                 if (!is_null($filename) && $file instanceof File) {
                     $filename_normalized = $mapping->getNamer()->getNormalizedName($document, $filename);
                     // Si les deux noms ne correspondent pas, je renomme et réassigne
                     if (strcmp($filename, $filename_normalized) !== 0) {
                         $base_directory = $mapping->hasDirectoryNamer() ? $mapping->getDirectoryNamer()->directoryName($document, $mapping) . '/' : '';
                         $adapter = $this->filesystem_map->get($mapping->getUploadDestination())->getAdapter();
                         $adapter->rename($base_directory . $filename, $base_directory . $filename_normalized);
                         if ($adapter->exists($base_directory . $filename)) {
                             $adapter->delete($base_directory . $filename);
                         }
                         // On vérifie si il y a des fichiers resized à renommer
                         foreach ($this->resizes as $suffix => $resize_conf) {
                             $resize_filename = $base_directory . ResizedNamer::getName($filename, $suffix);
                             $resize_filename_normalized = $base_directory . ResizedNamer::getName($filename_normalized, $suffix);
                             if ($adapter->exists($resize_filename)) {
                                 $adapter->rename($resize_filename, $resize_filename_normalized);
                                 if ($adapter->exists($resize_filename)) {
                                     $adapter->delete($resize_filename);
                                 }
                             }
                         }
                         $mapping->setFileName($document, $filename_normalized);
                         // Ré-enregistrement
                         $class = $dm->getClassMetadata(get_class($document));
                         $dm->getUnitOfWork()->recomputeSingleDocumentChangeSet($class, $document);
                     }
                 }
             }
             // Traitement du répertoire basé sur l'id pour voir si le fichier est bien dedans
             $directory_namer = $mapping->getDirectoryNamer();
             if (!is_null($directory_namer) && $directory_namer instanceof BaseDirectoryIdNamer) {
                 $adapter = $this->filesystem_map->get($mapping->getUploadDestination())->getAdapter();
                 $filename = $mapping->getFileName($document);
                 $good_path = ltrim($directory_namer->directoryName($document, $mapping) . '/' . $filename, '/');
                 $bad_path = ltrim($directory_namer->directoryNameError($document, $mapping) . '/' . $filename, '/');
                 if (!$adapter->exists($good_path) && $adapter->exists($bad_path)) {
                     $success = $adapter->rename($bad_path, $good_path);
                 }
             }
         }
     }
 }
 /**
  * @param PreSerializeEvent $event
  */
 public function onPreSerializeFile(PreSerializeEvent $event)
 {
     $entity = $event->getObject();
     $type = $event->getType();
     $className = $type['name'];
     $request = $this->requestStack->getCurrentRequest();
     $isUploadable = $this->metadataReader->isUploadable($className);
     if (!$isUploadable) {
         return;
     }
     $cacheKey = md5($className . '_' . $entity->getId());
     if (isset(self::$cache[$cacheKey])) {
         return;
     }
     self::$cache[$cacheKey] = true;
     $uploadableFields = $this->metadataReader->getUploadableFields($className);
     foreach ($uploadableFields as $uploadableField) {
         $propertyName = $uploadableField['propertyName'];
         $fileNameProperty = $uploadableField['fileNameProperty'];
         $getterFile = 'get' . $fileNameProperty;
         if ($entity->{$getterFile}()) {
             $setterFile = 'set' . $fileNameProperty;
             $originUrl = $this->uploaderHelper->asset($entity, $propertyName);
             if ($originUrl) {
                 /** @var ImagineFilters $imagineFiltersAnnotation */
                 $reflectionClass = new \ReflectionClass($className);
                 $imagineFiltersAnnotation = $this->annotationsReader->getPropertyAnnotation($reflectionClass->getProperty($fileNameProperty), new ImagineFilters());
                 if ($imagineFiltersAnnotation) {
                     $urls = [];
                     foreach ($imagineFiltersAnnotation->getFilters() as $filter) {
                         $urls[$filter] = $this->imagineHelper->filter($originUrl, $filter);
                     }
                     $property = $imagineFiltersAnnotation->getProperty();
                     $entity->{$property} = $urls;
                 }
             }
             if ($request) {
                 $originUrl = $request->getSchemeAndHttpHost() . $originUrl;
             }
             $entity->{$setterFile}($originUrl);
         }
     }
 }
예제 #4
0
 public function testConfiguredNamerRetrievedFromContainer()
 {
     $obj = new DummyEntity();
     $mappings = array('dummy_file' => array('upload_destination' => 'images', 'delete_on_remove' => true, 'delete_on_update' => true, 'namer' => 'my.custom.namer', 'inject_on_load' => true, 'directory_namer' => null));
     $namer = $this->getMock('Vich\\UploaderBundle\\Naming\\NamerInterface');
     $this->container->expects($this->once())->method('get')->with('my.custom.namer')->will($this->returnValue($namer));
     $this->metadata->expects($this->once())->method('isUploadable')->with('Vich\\UploaderBundle\\Tests\\DummyEntity')->will($this->returnValue(true));
     $this->metadata->expects($this->once())->method('getUploadableFields')->with('Vich\\UploaderBundle\\Tests\\DummyEntity')->will($this->returnValue(array('file' => array('mapping' => 'dummy_file', 'propertyName' => 'file', 'fileNameProperty' => 'fileName'))));
     $factory = new PropertyMappingFactory($this->container, $this->metadata, $mappings);
     $mappings = $factory->fromObject($obj);
     $this->assertEquals(1, count($mappings));
     $mapping = $mappings['dummy_file'];
     $this->assertEquals($namer, $mapping->getNamer());
     $this->assertTrue($mapping->hasNamer());
 }
 /**
  * Checks to see if the class is uploadable.
  *
  * @param string $class The class name (FQCN).
  *
  * @throws \InvalidArgumentException
  */
 protected function checkUploadable($class)
 {
     if (!$this->metadata->isUploadable($class)) {
         throw new \InvalidArgumentException('The object is not uploadable.');
     }
 }
예제 #6
0
 /**
  * Checks if the given object is uploadable using the current mapping.
  *
  * @param mixed $object The object to test.
  *
  * @return bool
  */
 protected function isUploadable($object)
 {
     return $this->metadata->isUploadable(ClassUtils::getClass($object), $this->mapping);
 }
 /**
  * Checks to see if the class is uploadable.
  *
  * @param string $class The class name (FQCN).
  *
  * @throws NotUploadableException
  */
 protected function checkUploadable($class)
 {
     if (!$this->metadata->isUploadable($class)) {
         throw new NotUploadableException(sprintf('The class "%s" is not uploadable. If you use annotations to configure VichUploaderBundle, you probably just forgot to add `@Vich\\Uploadable` on top of your entity. If you don\'t use annotations, check that the configuration files are in the right place. In both cases, clearing the cache can also solve the issue.', $class));
     }
 }