Commit f760d243 authored by Sebastian Castro's avatar Sebastian Castro

Improve file import, puttings files in diffferent folder depending on SAAS project

parent 4273ae9a
......@@ -172,17 +172,19 @@ ivory_ck_editor:
- [ -, Styles,Format,Font,FontSize, TextColor, BGColor]
- [ -, JustifyLeft,JustifyCenter,JustifyRight,JustifyBlock]
# Those upload_destinations should remain at the root public directory
# To customize the different path, please do it in the CoreBundle UploadDirectoryNamer.php
vich_uploader:
db_driver: mongodb
mappings:
import_file:
uri_prefix: /imports
upload_destination: '%kernel.root_dir%/../web/uploads/imports'
upload_destination: '%kernel.root_dir%/../web'
directory_namer: biopen.upload_directory_namer
element_image:
uri_prefix: /images/elements
upload_destination: '%kernel.root_dir%/../web/uploads/images/elements'
upload_destination: '%kernel.root_dir%/../web'
inject_on_load: true
directory_namer: biopen.upload_directory_namer
namer: vich_uploader.namer_origname
<?php
namespace Biopen\CoreBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Biopen\CoreBundle\Helper\HostResolverHelper;
use Biopen\CoreBundle\Services\UploadDirectoryNamer;
/**
* Represent a common File. Need to be extended by real Document
* You need to implement $vichUploadFileKey and the annotation of the $file to specify the mapping key inside it (defined also in config.yml -> vich_uploader)
*/
class AbstractFile
{
protected $vichUploadFileKey = "default_file";
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* @Vich\UploadableField(mapping="default_file", fileNameProperty="fileName", size="fileSize")
*
* @var File
*/
protected $file;
/**
* @var string
* @MongoDB\Field(type="string")
*/
public $fileName = "";
/**
* @var string
* @MongoDB\Field(type="int")
*/
public $fileSize = "";
/**
* @var string
* memory
* @MongoDB\Field(type="string")
*/
public $fileUrl = "";
/**
* @MongoDB\Field(type="date")
*
* @var \DateTime
*/
private $updatedAt;
public function toJson()
{
return json_encode($this->fileUrl);
}
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* @param File|UploadedFile $file
*/
public function setFile($file = null)
{
$this->file = $file;
if (null !== $file) {
// store the absolute url of the file so we can directly use it in the json conversion
$this->fileUrl = $this->calculateFileUrl();
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTimeImmutable();
}
}
public function calculateFileUrl()
{
$hostHelper = new HostResolverHelper();
$fileUrl = $hostHelper->getPublicFolderUrl();
$fileUrl .= '/' . $this->calculateFilePath();
return $fileUrl;
}
public function calculateFilePath()
{
$uploadDirHelper = new UploadDirectoryNamer();
$filePath = $uploadDirHelper->getDirectoryPathFromKey($this->vichUploadFileKey) .'/' . $this->fileName;
return $filePath;
}
public function getFile()
{
return $this->file;
}
/**
* Set fileName
*
* @param string $fileName
* @return $this
*/
public function setFileName($fileName)
{
$this->fileName = $fileName;
return $this;
}
/**
* Get fileName
*
* @return string $fileName
*/
public function getFileName()
{
return $this->fileName;
}
/**
* Set fileSize
*
* @param int $fileSize
* @return $this
*/
public function setFileSize($fileSize)
{
$this->fileSize = $fileSize;
return $this;
}
/**
* Get fileSize
*
* @return int $fileSize
*/
public function getFileSize()
{
return $this->fileSize;
}
/**
* Set updatedAt
*
* @param date $updatedAt
* @return $this
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* @return date $updatedAt
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set fileUrl
*
* @param string $fileUrl
* @return $this
*/
public function setFileUrl($fileUrl)
{
$this->fileUrl = $fileUrl;
return $this;
}
/**
* Get fileUrl
*
* @return string $fileUrl
*/
public function getFileUrl()
{
return $this->fileUrl;
}
}
<?php
namespace Biopen\CoreBundle\Helper;
class HostResolverHelper
{
// GoGoCarto can be use as a SAAS. in this case, each subdomain map a projet
// project1.gog.carto, project2.gogo.carto etc...
// by default, the projet code is "gogocarto_default"
public function getCurrentProjectCode()
{
$dbName = "gogocarto_default";
$host = $_SERVER["HTTP_HOST"];
if ($host)
{
$exploded = explode('.', $host);
$subdomain = $exploded[0];
if (count($exploded) >= 3 && !in_array($subdomain, ['dev', 'test', 'demo', 'carto', 'carto-dev', 'www'])) $dbName = $subdomain;
}
return $dbName;
}
// return the Url to the actual public folder (the web/ folder)
public function getPublicFolderUrl()
{
$url = $_SERVER["REQUEST_SCHEME"] . '://' . $_SERVER["HTTP_HOST"];
if (strpos($url, 'localhost') !== false) $url .= explode('/app',$_SERVER["SCRIPT_NAME"])[0]; // ugly fix to support localhost !
return $url;
}
}
......@@ -9,4 +9,8 @@ services:
biopen.newsletter_service:
class: Biopen\CoreBundle\Services\NewsletterService
arguments: [ "@doctrine.odm.mongoDB.document_manager", "@biopen.mail_service" ]
\ No newline at end of file
arguments: [ "@doctrine.odm.mongoDB.document_manager", "@biopen.mail_service" ]
biopen.upload_directory_namer:
class: Biopen\CoreBundle\Services\UploadDirectoryNamer
arguments: []
\ No newline at end of file
<?php
namespace Biopen\CoreBundle\Services;
use Vich\UploaderBundle\Mapping\PropertyMapping;
use Vich\UploaderBundle\Naming\DirectoryNamerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Biopen\CoreBundle\Helper\HostResolverHelper;
/**
* Directory namer wich can create subfolder depends on generated filename.
*
* @author Konstantin Myakshin <koc-dp@yandex.ru>
*/
class UploadDirectoryNamer implements DirectoryNamerInterface
{
private $BASE_PATH = "uploads/";
private $PATHS = [
"element_image" => "/images/elements",
"import_file" => "/imports",
"default_file" => '/default'
];
public function directoryName($object, PropertyMapping $mapping)
{
$name = $this->getDirectoryPathFromKey($mapping->getMappingName());
dump($name);
return $name;
}
public function getDirectoryPathFromKey($key)
{
$hostHelper = new HostResolverHelper();
return $this->BASE_PATH . $hostHelper->getCurrentProjectCode() . $this->PATHS[$key];
}
}
\ No newline at end of file
......@@ -15,26 +15,26 @@ class ElementImageAdmin extends AbstractAdmin
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('image', 'file', array('label' => 'Fichier à importer', 'required' => false))
->add('file', 'file', array('label' => 'Fichier à importer', 'required' => false))
->add('externalImageUrl', null, array('label' => 'Lien vers une image externe', 'required' => false))
;
}
protected function configureShowFields(ShowMapper $show)
{
$show->add('imageName');
$show->add('fileName');
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('imageName')
->add('fileName')
;
}
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('imageName')
->addIdentifier('fileName')
->add('_action', 'actions', array(
'actions' => array(
'edit' => array(),
......
......@@ -14,7 +14,7 @@ class ImportAdmin extends AbstractAdmin
{
$formMapper
->add('sourceName', 'text', array('required' => false, 'label' => 'Nom de la source'))
->add('fileToImport', 'file', array('label' => 'Fichier à importer'))
->add('file', 'file', array('label' => 'Fichier à importer'))
->add('geocodeIfNecessary', null, array('required' => false, 'label' => 'Géocoder si élements sans latitude ni longitude'))
->add('createMissingOptions', null, array('required' => false, 'label' => 'Créer les options manquantes'))
->add('parentCategoryToCreateOptions', 'sonata_type_model', array(
......
......@@ -4,156 +4,38 @@ namespace Biopen\GeoDirectoryBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Biopen\CoreBundle\Helper\HostResolverHelper;
use Biopen\CoreBundle\Document\AbstractFile;
/** @MongoDB\EmbeddedDocument
/**
* @MongoDB\EmbeddedDocument
* @Vich\Uploadable
*/
class ElementImage
class ElementImage extends AbstractFile
{
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
protected $vichUploadFileKey = "element_image";
/**
* This is not a mapped field of entity metadata, just a simple property.
*
* @Vich\UploadableField(mapping="element_image", fileNameProperty="imageName", size="imageSize")
* @Vich\UploadableField(mapping="element_image", fileNameProperty="fileName", size="fileSize")
*
* @var File
*/
private $image;
/**
* @var string
* @MongoDB\Field(type="string")
*/
public $imageName = "";
protected $file;
/**
* @var string
* @MongoDB\Field(type="int")
*/
public $imageSize = "";
/**
* @var string
* memory
* @MongoDB\Field(type="string")
*/
public $imageRealPath = "";
/**
* @var string
*
* Instead of uploading a file, we can give an external url to an image
* @MongoDB\Field(type="string")
*/
public $externalImageUrl = "";
/**
* @MongoDB\Field(type="date")
*
* @var \DateTime
*/
private $updatedAt;
public function toJson()
{
$url = $this->imageRealPath ? $this->imageRealPath : $this->externalImageUrl;
$url = $this->fileUrl ? $this->fileUrl : $this->externalImageUrl;
return json_encode($url);
}
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* @param File|UploadedFile $image
*/
public function setImage($image = null)
{
$this->image = $image;
if (null !== $image) {
// store the absolute url of the file so we can directly use it in the json conversion
// if this "realPath" property does not give an absolute Url, we probably need to use
// the vich upload helper https://github.com/dustin10/VichUploaderBundle/blob/master/Resources/doc/generating_urls.md
$this->imageRealPath = $image->getRealPath();
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTimeImmutable();
}
}
public function getImage()
{
return $this->image;
}
/**
* Set imageName
*
* @param string $imageName
* @return $this
*/
public function setImageName($imageName)
{
$this->imageName = $imageName;
return $this;
}
/**
* Get imageName
*
* @return string $imageName
*/
public function getImageName()
{
return $this->imageName;
}
/**
* Set imageSize
*
* @param int $imageSize
* @return $this
*/
public function setImageSize($imageSize)
{
$this->imageSize = $imageSize;
return $this;
}
/**
* Get imageSize
*
* @return int $imageSize
*/
public function getImageSize()
{
return $this->imageSize;
}
/**
* Set updatedAt
*
* @param date $updatedAt
* @return $this
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* @return date $updatedAt
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
}
/**
* Set externalImageUrl
......@@ -176,26 +58,4 @@ class ElementImage
{
return $this->externalImageUrl;
}
/**
* Set imageRealPath
*
* @param string $imageRealPath
* @return $this
*/
public function setImageRealPath($imageRealPath)
{
$this->imageRealPath = $imageRealPath;
return $this;
}
/**
* Get imageRealPath
*
* @return string $imageRealPath
*/
public function getImageRealPath()
{
return $this->imageRealPath;
}
}
......@@ -5,13 +5,13 @@ namespace Biopen\GeoDirectoryBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Biopen\CoreBundle\Document\AbstractFile;
/**
* @MongoDB\Document
* @Vich\Uploadable
*/
class Import
class Import extends AbstractFile
{
/**
* @var int
......@@ -46,9 +46,7 @@ class Import
private $geocodeIfNecessary;
protected $vichUploadFileKey = "import_file";
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
......@@ -56,56 +54,12 @@ class Import
*
* @var File
*/
private $fileToImport;
/**
* @var string
* @MongoDB\Field(type="string")
*/
public $fileName = "";
/**
* @var string
* @MongoDB\Field(type="int")
*/
public $fileSize = "";
/**
* @MongoDB\Field(type="date")
*
* @var \DateTime
*/
private $updatedAt;
protected $file;
public function __construct()
{
}
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* @param File|UploadedFile $image
*/
public function setFileToImport($file = null)
{
$this->fileToImport = $file;
if (null !== $file) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTimeImmutable();
}
}
public function getFileToImport()
{
return $this->fileToImport;
}
/**
* Get id
*
......@@ -138,72 +92,6 @@ class Import
return $this->sourceName;
}
/**
* Set updatedAt
*
* @param date $updatedAt
* @return $this
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**