Example #1
0
 /**
  * Uploads the file to the Amazon s3.
  * Entity, type, and entityId are the unique keys
  * @param $filePath Path of the file
  * @param $entity type of entity i.e User
  * @param $type type of file related to the entity i.e Spotlight, Profile Pic etc
  * @param $entity_id i.e user_id, course_id
  */
 public function upload($filePath, $entity, $type, $entity_id, $extension = null, $uniqueKey = null)
 {
     $client = $this->getS3Client();
     $em = $this->container->get('doctrine')->getManager();
     $logger = $this->getLogger();
     $name = $this->generateFileName($filePath, $extension);
     // Check if the file already exists
     $file = $this->getFile($entity, $type, $entity_id);
     if ($file) {
         // Delete the original file
         try {
             $result = $client->deleteObject(array('Bucket' => $this->s3Bucket, 'Key' => $this->getKeyName($file)));
         } catch (\Exception $e) {
             $logger->error("Error trying to delete file during upload " . $e->getMessage(), array('Entity' => $entity, 'Entity_Id' => $entity_id, 'Type' => $type));
         }
         // Update the file name
         $file->setFileName($name);
         $file->setFileType(mime_content_type($filePath));
     } else {
         $file = new File();
         $file->setEntity($entity);
         $file->setType($type);
         $file->setEntityId($entity_id);
         $file->setFileName($name);
         $file->setFileType(mime_content_type($filePath));
     }
     // Update the key
     $file->setUniqueKey($uniqueKey);
     try {
         // Upload the file
         $result = $client->putObject(array('Bucket' => $this->s3Bucket, 'Key' => $this->getKeyName($file), 'SourceFile' => $filePath));
         $logger->info("File uploaded for Entity {$entity} with type {$type} and Entity Id {$entity_id}", (array) $result);
         $em->persist($file);
         $em->flush();
         return $file;
     } catch (\Exception $e) {
         // Log the exception
         $logger->error("Exception occurred while uploading file - " . $e->getMessage(), array('Entity' => $entity, 'Entity_Id' => $entity_id, 'Type' => $type));
         return false;
     }
 }