Refactoring of images and documents management

This commit is contained in:
Franck Allimant
2014-06-26 10:36:12 +02:00
parent b49f8a6423
commit 114a55c1e8
33 changed files with 1795 additions and 2216 deletions

View File

@@ -12,6 +12,7 @@
namespace Thelia\Action; namespace Thelia\Action;
use Thelia\Core\Event\CachedFileEvent; use Thelia\Core\Event\CachedFileEvent;
use Thelia\Files\FileManager;
use Thelia\Tools\URL; use Thelia\Tools\URL;
/** /**
@@ -32,6 +33,16 @@ use Thelia\Tools\URL;
*/ */
abstract class BaseCachedFile extends BaseAction abstract class BaseCachedFile extends BaseAction
{ {
/**
* @var FileManager
*/
protected $fileManager;
public function __construct(FileManager $fileManager)
{
$this->fileManager = $fileManager;
}
/** /**
* @return string root of the file cache directory in web space * @return string root of the file cache directory in web space
*/ */
@@ -60,6 +71,7 @@ abstract class BaseCachedFile extends BaseAction
{ {
$iterator = new \DirectoryIterator($path); $iterator = new \DirectoryIterator($path);
/** @var \DirectoryIterator $fileinfo */
foreach ($iterator as $fileinfo) { foreach ($iterator as $fileinfo) {
if ($fileinfo->isDot()) continue; if ($fileinfo->isDot()) continue;
@@ -75,8 +87,8 @@ abstract class BaseCachedFile extends BaseAction
/** /**
* Return the absolute URL to the cached file * Return the absolute URL to the cached file
* *
* @param string $subdir the subdirectory related to cache base * @param string $subdir the subdirectory related to cache base
* @param string $filename the safe filename, as returned by getCacheFilePath() * @param string $safe_filename the safe filename, as returned by getCacheFilePath()
* @return string the absolute URL to the cached file * @return string the absolute URL to the cached file
*/ */
protected function getCacheFileURL($subdir, $safe_filename) protected function getCacheFileURL($subdir, $safe_filename)
@@ -89,10 +101,10 @@ abstract class BaseCachedFile extends BaseAction
/** /**
* Return the full path of the cached file * Return the full path of the cached file
* *
* @param string $subdir the subdirectory related to cache base * @param string $subdir the subdirectory related to cache base
* @param string $filename the filename * @param string $filename the filename
* @param string $hashed_options a hash of transformation options, or null if no transformations have been applied * @param boolean $forceOriginalFile if true, the original file path in the cache dir is returned.
* @param boolean $forceOriginalDocument if true, the original file path in the cache dir is returned. * @param string $hashed_options a hash of transformation options, or null if no transformations have been applied
* @return string the cache directory path relative to Web Root * @return string the cache directory path relative to Web Root
*/ */
protected function getCacheFilePath($subdir, $filename, $forceOriginalFile = false, $hashed_options = null) protected function getCacheFilePath($subdir, $filename, $forceOriginalFile = false, $hashed_options = null)
@@ -132,9 +144,13 @@ abstract class BaseCachedFile extends BaseAction
/** /**
* Return the absolute cache directory path * Return the absolute cache directory path
* *
* @param string $subdir the subdirectory related to cache base, or null to get the cache base directory. * @param string $subdir the subdirectory related to cache base, or null to get the cache base directory.
* @throws \RuntimeException if cache directory cannot be created * @param bool $create_if_not_exists create the directory if it is not found
* @return string the absolute cache directory path *
* @throws \RuntimeException if cache directory cannot be created
* @throws \InvalidArgumentException ii path is invalid, e.g. not in the cache dir
*
* @return string the absolute cache directory path
*/ */
protected function getCachePath($subdir = null, $create_if_not_exists = true) protected function getCachePath($subdir = null, $create_if_not_exists = true)
{ {

View File

@@ -12,19 +12,16 @@
namespace Thelia\Action; namespace Thelia\Action;
use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent; use Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent;
use Thelia\Core\Event\Document\DocumentDeleteEvent; use Thelia\Core\Event\Document\DocumentDeleteEvent;
use Thelia\Core\Event\Document\DocumentEvent; use Thelia\Core\Event\Document\DocumentEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\UpdateFilePositionEvent; use Thelia\Core\Event\UpdateFilePositionEvent;
use Thelia\Exception\DocumentException;
use Thelia\Exception\ImageException; use Thelia\Exception\ImageException;
use Thelia\Model\ConfigQuery; use Thelia\Model\ConfigQuery;
use Thelia\Tools\FileManager;
use Thelia\Tools\URL; use Thelia\Tools\URL;
use Thelia\Exception\DocumentException;
use Thelia\Core\Event\TheliaEvents;
/** /**
* *
* Document management actions. This class handles document processing an caching. * Document management actions. This class handles document processing an caching.
@@ -71,7 +68,7 @@ class Document extends BaseCachedFile implements EventSubscriberInterface
*/ */
public function processDocument(DocumentEvent $event) public function processDocument(DocumentEvent $event)
{ {
$subdir = $event->getCacheSubdirectory(); $subdir = $event->getCacheSubdirectory();
$sourceFile = $event->getSourceFilepath(); $sourceFile = $event->getSourceFilepath();
if (null == $subdir || null == $sourceFile) { if (null == $subdir || null == $sourceFile) {
@@ -118,7 +115,6 @@ class Document extends BaseCachedFile implements EventSubscriberInterface
*/ */
public function saveDocument(DocumentCreateOrUpdateEvent $event) public function saveDocument(DocumentCreateOrUpdateEvent $event)
{ {
$fileManager = new FileManager();
$model = $event->getModelDocument(); $model = $event->getModelDocument();
$nbModifiedLines = $model->save(); $nbModifiedLines = $model->save();
@@ -128,15 +124,15 @@ class Document extends BaseCachedFile implements EventSubscriberInterface
if (!$nbModifiedLines) { if (!$nbModifiedLines) {
throw new ImageException( throw new ImageException(
sprintf( sprintf(
'Document "%s" with parent id %s (%s) failed to be saved', 'Document "%s" with parent id %s failed to be saved',
$event->getParentName(), $event->getParentName(),
$event->getParentId(), $event->getParentId()
$event->getDocumentType()
) )
); );
} }
$newUploadedFile = $fileManager->copyUploadedFile($event->getParentId(), $event->getDocumentType(), $event->getModelDocument(), $event->getUploadedFile(), FileManager::FILE_TYPE_DOCUMENTS); $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModelDocument(), $event->getUploadedFile());
$event->setUploadedFile($newUploadedFile); $event->setUploadedFile($newUploadedFile);
} }
@@ -154,14 +150,15 @@ class Document extends BaseCachedFile implements EventSubscriberInterface
$event->getModelDocument()->setTitle($event->getUploadedFile()->getClientOriginalName()); $event->getModelDocument()->setTitle($event->getUploadedFile()->getClientOriginalName());
} }
$fileManager = new FileManager();
// Copy and save file // Copy and save file
if ($event->getUploadedFile()) { if ($event->getUploadedFile()) {
// Remove old picture file from file storage // Remove old picture file from file storage
$url = $fileManager->getUploadDir($event->getDocumentType(), FileManager::FILE_TYPE_DOCUMENTS) . '/' . $event->getOldModelDocument()->getFile(); $url = $event->getModelDocument()->getUploadDir() . '/' . $event->getOldModelDocument()->getFile();
unlink(str_replace('..', '', $url)); unlink(str_replace('..', '', $url));
$newUploadedFile = $fileManager->copyUploadedFile($event->getParentId(), $event->getDocumentType(), $event->getModelDocument(), $event->getUploadedFile(), FileManager::FILE_TYPE_DOCUMENTS); $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModelDocument(), $event->getUploadedFile());
$event->setUploadedFile($newUploadedFile); $event->setUploadedFile($newUploadedFile);
} }
@@ -181,13 +178,10 @@ class Document extends BaseCachedFile implements EventSubscriberInterface
* @param \Thelia\Core\Event\Document\DocumentDeleteEvent $event Image event * @param \Thelia\Core\Event\Document\DocumentDeleteEvent $event Image event
* *
* @throws \Exception * @throws \Exception
* @todo refactor make all documents using propel inheritance and factorise image behaviour into one single clean action
*/ */
public function deleteDocument(DocumentDeleteEvent $event) public function deleteDocument(DocumentDeleteEvent $event)
{ {
$fileManager = new FileManager(); $this->fileManager->deleteFile($event->getDocumentToDelete());
$fileManager->deleteFile($event->getDocumentToDelete(), $event->getDocumentType(), FileManager::FILE_TYPE_DOCUMENTS);
} }
public static function getSubscribedEvents() public static function getSubscribedEvents()

View File

@@ -12,23 +12,20 @@
namespace Thelia\Action; namespace Thelia\Action;
use Imagine\Image\Box;
use Imagine\Image\Color;
use Imagine\Image\ImageInterface;
use Imagine\Image\ImagineInterface;
use Imagine\Image\Point;
use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Core\Event\Image\ImageCreateOrUpdateEvent; use Thelia\Core\Event\Image\ImageCreateOrUpdateEvent;
use Thelia\Core\Event\Image\ImageDeleteEvent; use Thelia\Core\Event\Image\ImageDeleteEvent;
use Thelia\Core\Event\Image\ImageEvent; use Thelia\Core\Event\Image\ImageEvent;
use Thelia\Core\Event\UpdateFilePositionEvent;
use Thelia\Model\ConfigQuery;
use Thelia\Tools\FileManager;
use Thelia\Tools\URL;
use Imagine\Image\ImagineInterface;
use Imagine\Image\ImageInterface;
use Imagine\Image\Box;
use Imagine\Image\Color;
use Imagine\Image\Point;
use Thelia\Exception\ImageException;
use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\UpdateFilePositionEvent;
use Thelia\Exception\ImageException;
use Thelia\Model\ConfigQuery;
use Thelia\Tools\URL;
/** /**
* *
@@ -242,7 +239,6 @@ class Image extends BaseCachedFile implements EventSubscriberInterface
*/ */
public function saveImage(ImageCreateOrUpdateEvent $event) public function saveImage(ImageCreateOrUpdateEvent $event)
{ {
$fileManager = new FileManager();
$model = $event->getModelImage(); $model = $event->getModelImage();
$nbModifiedLines = $model->save(); $nbModifiedLines = $model->save();
@@ -251,15 +247,14 @@ class Image extends BaseCachedFile implements EventSubscriberInterface
if (!$nbModifiedLines) { if (!$nbModifiedLines) {
throw new ImageException( throw new ImageException(
sprintf( sprintf(
'Image "%s" with parent id %s (%s) failed to be saved', 'Image "%s" with parent id %s failed to be saved',
$event->getParentName(), $event->getParentName(),
$event->getParentId(), $event->getParentId()
$event->getImageType()
) )
); );
} }
$newUploadedFile = $fileManager->copyUploadedFile($event->getParentId(), $event->getImageType(), $event->getModelImage(), $event->getUploadedFile(), FileManager::FILE_TYPE_IMAGES); $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModelImage(), $event->getUploadedFile());
$event->setUploadedFile($newUploadedFile); $event->setUploadedFile($newUploadedFile);
} }
@@ -273,14 +268,13 @@ class Image extends BaseCachedFile implements EventSubscriberInterface
*/ */
public function updateImage(ImageCreateOrUpdateEvent $event) public function updateImage(ImageCreateOrUpdateEvent $event)
{ {
$fileManager = new FileManager();
// Copy and save file // Copy and save file
if ($event->getUploadedFile()) { if ($event->getUploadedFile()) {
// Remove old picture file from file storage // Remove old picture file from file storage
$url = $fileManager->getUploadDir($event->getImageType(), FileManager::FILE_TYPE_IMAGES) . '/' . $event->getOldModelImage()->getFile(); $url = $event->getModelImage()->getUploadDir() . '/' . $event->getOldModelImage()->getFile();
unlink(str_replace('..', '', $url)); unlink(str_replace('..', '', $url));
$newUploadedFile = $fileManager->copyUploadedFile($event->getParentId(), $event->getImageType(), $event->getModelImage(), $event->getUploadedFile(), FileManager::FILE_TYPE_IMAGES); $newUploadedFile = $this->fileManager->copyUploadedFile($event->getModelImage(), $event->getUploadedFile());
$event->setUploadedFile($newUploadedFile); $event->setUploadedFile($newUploadedFile);
} }
@@ -304,9 +298,7 @@ class Image extends BaseCachedFile implements EventSubscriberInterface
*/ */
public function deleteImage(ImageDeleteEvent $event) public function deleteImage(ImageDeleteEvent $event)
{ {
$fileManager = new FileManager(); $this->fileManager->deleteFile($event->getImageToDelete());
$fileManager->deleteFile($event->getImageToDelete(), $event->getImageType(), FileManager::FILE_TYPE_IMAGES);
} }
/** /**

View File

@@ -9,8 +9,34 @@
<parameter key="esi_listener.class">Symfony\Component\HttpKernel\EventListener\EsiListener</parameter> <parameter key="esi_listener.class">Symfony\Component\HttpKernel\EventListener\EsiListener</parameter>
<parameter key="fragment.renderer.esi.class">Symfony\Component\HttpKernel\Fragment\EsiFragmentRenderer</parameter> <parameter key="fragment.renderer.esi.class">Symfony\Component\HttpKernel\Fragment\EsiFragmentRenderer</parameter>
<parameter key="fragment.renderer.inline.class">Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer</parameter> <parameter key="fragment.renderer.inline.class">Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer</parameter>
<!--
The list of Model classes which suppoorts image or document management.
The key should have form type.parent, where type is the file type (document or image)
and parent is the parent object of the file, form example product, brand, folder, etc.
-->
<parameter key="file_model.classes" type="collection">
<parameter key="document.product">Thelia\Model\ProductDocument</parameter>
<parameter key="image.product">Thelia\Model\ProductImage</parameter>
<parameter key="document.category">Thelia\Model\CategoryDocument</parameter>
<parameter key="image.category">Thelia\Model\CategoryImage</parameter>
<parameter key="document.content">Thelia\Model\ContentDocument</parameter>
<parameter key="image.content">Thelia\Model\ContentImage</parameter>
<parameter key="document.folder">Thelia\Model\FolderDocument</parameter>
<parameter key="image.folder">Thelia\Model\FolderImage</parameter>
<parameter key="document.brand">Thelia\Model\BrandDocument</parameter>
<parameter key="image.brand">Thelia\Model\BrandImage</parameter>
</parameter>
</parameters> </parameters>
<services> <services>
<!-- URL maganement --> <!-- URL maganement -->
@@ -80,6 +106,11 @@
<argument >%kernel.debug%</argument> <argument >%kernel.debug%</argument>
</service> </service>
<!-- The file manager -->
<service id="thelia.file_manager" class="Thelia\Files\FileManager">
<argument>%file_model.classes%</argument>
</service>
<service id="http_kernel" class="Thelia\Core\TheliaHttpKernel"> <service id="http_kernel" class="Thelia\Core\TheliaHttpKernel">
<argument type="service" id="event_dispatcher" /> <argument type="service" id="event_dispatcher" />
<argument type="service" id="service_container" /> <argument type="service" id="service_container" />

View File

@@ -329,12 +329,12 @@ class BaseAdminController extends BaseController
* Return the current list order identifier for a given object name, * Return the current list order identifier for a given object name,
* updating in using the current request. * updating in using the current request.
* *
* @param unknown $objectName the object name (e.g. 'attribute', 'message') * @param string $objectName the object name (e.g. 'attribute', 'message')
* @param unknown $requestParameterName the name of the request parameter that defines the list order * @param string $requestParameterName the name of the request parameter that defines the list order
* @param unknown $defaultListOrder the default order to use, if none is defined * @param string $defaultListOrder the default order to use, if none is defined
* @param string $updateSession if true, the session will be updated with the current order. * @param bool $updateSession if true, the session will be updated with the current order.
* *
* @return String the current liste order. * @return String the current list order.
*/ */
protected function getListOrderFromSession($objectName, $requestParameterName, $defaultListOrder, $updateSession = true) protected function getListOrderFromSession($objectName, $requestParameterName, $defaultListOrder, $updateSession = true)
{ {

View File

@@ -14,27 +14,20 @@ namespace Thelia\Controller\Admin;
use Propel\Runtime\Exception\PropelException; use Propel\Runtime\Exception\PropelException;
use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\File\UploadedFile;
use Thelia\Core\Event\UpdateFilePositionEvent;
use Thelia\Core\HttpFoundation\Response;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent; use Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent;
use Thelia\Core\Event\Document\DocumentDeleteEvent; use Thelia\Core\Event\Document\DocumentDeleteEvent;
use Thelia\Core\Event\Image\ImageCreateOrUpdateEvent; use Thelia\Core\Event\Image\ImageCreateOrUpdateEvent;
use Thelia\Core\Event\Image\ImageDeleteEvent; use Thelia\Core\Event\Image\ImageDeleteEvent;
use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\UpdateFilePositionEvent;
use Thelia\Core\HttpFoundation\Response;
use Thelia\Core\Security\AccessManager; use Thelia\Core\Security\AccessManager;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Files\FileManager;
use Thelia\Files\FileModelInterface;
use Thelia\Form\Exception\FormValidationException; use Thelia\Form\Exception\FormValidationException;
use Thelia\Log\Tlog; use Thelia\Log\Tlog;
use Thelia\Model\CategoryDocument;
use Thelia\Model\CategoryImage;
use Thelia\Model\ContentDocument;
use Thelia\Model\ContentImage;
use Thelia\Model\FolderDocument;
use Thelia\Model\FolderImage;
use Thelia\Model\Lang; use Thelia\Model\Lang;
use Thelia\Model\ProductDocument;
use Thelia\Model\ProductImage;
use Thelia\Tools\FileManager;
use Thelia\Tools\Rest\ResponseRest; use Thelia\Tools\Rest\ResponseRest;
use Thelia\Tools\URL; use Thelia\Tools\URL;
@@ -52,6 +45,15 @@ use Thelia\Tools\URL;
*/ */
class FileController extends BaseAdminController class FileController extends BaseAdminController
{ {
/**
* Get the FileManager
*
* @return FileManager
*/
public function getFileManager()
{
return $this->container->get('thelia.file_manager');
}
/** /**
* Manage how a image collection has to be saved * Manage how a image collection has to be saved
@@ -66,78 +68,81 @@ class FileController extends BaseAdminController
$this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE);
$this->checkXmlHttpRequest(); $this->checkXmlHttpRequest();
if ($this->isParentTypeValid($parentType)) { if ($this->getRequest()->isMethod('POST')) {
if ($this->getRequest()->isMethod('POST')) {
/** @var UploadedFile $fileBeingUploaded */ /** @var UploadedFile $fileBeingUploaded */
$fileBeingUploaded = $this->getRequest()->files->get('file'); $fileBeingUploaded = $this->getRequest()->files->get('file');
$fileManager = new FileManager(); $fileManager = $this->getFileManager();
// Validate if file is too big // Validate if file is too big
if ($fileBeingUploaded->getError() == 1) { if ($fileBeingUploaded->getError() == 1) {
$message = $this->getTranslator() $message = $this->getTranslator()
->trans(
'File is too heavy, please retry with a file having a size less than %size%.',
array('%size%' => ini_get('upload_max_filesize')),
'core'
);
return new ResponseRest($message, 'text', 403);
}
// Validate if it is a image or file
if (!$fileManager->isImage($fileBeingUploaded->getMimeType())) {
$message = $this->getTranslator()
->trans( ->trans(
'File is too heavy, please retry with a file having a size less than %size%.', 'You can only upload images (.png, .jpg, .jpeg, .gif)',
array('%size%' => ini_get('upload_max_filesize')), array(),
'core' 'image'
); );
return new ResponseRest($message, 'text', 403); return new ResponseRest($message, 'text', 415);
}
// Validate if it is a image or file
if (!$fileManager->isImage($fileBeingUploaded->getMimeType())) {
$message = $this->getTranslator()
->trans(
'You can only upload images (.png, .jpg, .jpeg, .gif)',
array(),
'image'
);
return new ResponseRest($message, 'text', 415);
}
$parentModel = $fileManager->getParentFileModel($parentType, $parentId);
$imageModel = $fileManager->getImageModel($parentType);
if ($parentModel === null || $imageModel === null || $fileBeingUploaded === null) {
return new Response('', 404);
}
$defaultTitle = $parentModel->getTitle();
$imageModel->setParentId($parentId);
$imageModel->setTitle($defaultTitle);
$imageCreateOrUpdateEvent = new ImageCreateOrUpdateEvent(
$parentType,
$parentId
);
$imageCreateOrUpdateEvent->setModelImage($imageModel);
$imageCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded);
$imageCreateOrUpdateEvent->setParentName($parentModel->getTitle());
// Dispatch Event to the Action
$this->dispatch(
TheliaEvents::IMAGE_SAVE,
$imageCreateOrUpdateEvent
);
$this->adminLogAppend(
AdminResources::retrieve($parentType),
AccessManager::UPDATE,
$this->container->get('thelia.translator')->trans(
'Saving images for %parentName% parent id %parentId% (%parentType%)',
array(
'%parentName%' => $imageCreateOrUpdateEvent->getParentName(),
'%parentId%' => $imageCreateOrUpdateEvent->getParentId(),
'%parentType%' => $imageCreateOrUpdateEvent->getImageType()
),
'image'
)
);
return new ResponseRest(array('status' => true, 'message' => ''));
} }
$imageModel = $fileManager->getModelInstance('image', $parentType);
$parentModel = $imageModel->getParentFileModel();
if ($parentModel === null || $imageModel === null || $fileBeingUploaded === null) {
return new Response('', 404);
}
$defaultTitle = $parentModel->getTitle();
if (empty($defaultTitle)) {
$defaultTitle = $fileBeingUploaded->getClientOriginalName();
}
$imageModel
->setParentId($parentId)
->setLocale(Lang::getDefaultLanguage()->getLocale())
->setTitle($defaultTitle)
;
$imageCreateOrUpdateEvent = new ImageCreateOrUpdateEvent($parentId);
$imageCreateOrUpdateEvent->setModelImage($imageModel);
$imageCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded);
$imageCreateOrUpdateEvent->setParentName($parentModel->getTitle());
// Dispatch Event to the Action
$this->dispatch(
TheliaEvents::IMAGE_SAVE,
$imageCreateOrUpdateEvent
);
$this->adminLogAppend(
AdminResources::retrieve($parentType),
AccessManager::UPDATE,
$this->container->get('thelia.translator')->trans(
'Saving images for %parentName% parent id %parentId%',
array(
'%parentName%' => $imageCreateOrUpdateEvent->getParentName(),
'%parentId%' => $imageCreateOrUpdateEvent->getParentId()
),
'image'
)
);
return new ResponseRest(array('status' => true, 'message' => ''));
} }
return new Response('', 404); return new Response('', 404);
@@ -156,67 +161,62 @@ class FileController extends BaseAdminController
$this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE);
$this->checkXmlHttpRequest(); $this->checkXmlHttpRequest();
if ($this->isParentTypeValid($parentType)) { if ($this->getRequest()->isMethod('POST')) {
if ($this->getRequest()->isMethod('POST')) {
/** @var UploadedFile $fileBeingUploaded */ /** @var UploadedFile $fileBeingUploaded */
$fileBeingUploaded = $this->getRequest()->files->get('file'); $fileBeingUploaded = $this->getRequest()->files->get('file');
$fileManager = new FileManager(); $fileManager = $this->getFileManager();
// Validate if file is too big // Validate if file is too big
if ($fileBeingUploaded->getError() == 1) { if ($fileBeingUploaded->getError() == 1) {
$message = $this->getTranslator() $message = $this->getTranslator()
->trans( ->trans(
'File is too heavy, please retry with a file having a size less than %size%.', 'File is too large, please retry with a file having a size less than %size%.',
array('%size%' => ini_get('post_max_size')), array('%size%' => ini_get('post_max_size')),
'document'
);
return new ResponseRest($message, 'text', 403);
}
$parentModel = $fileManager->getParentFileModel($parentType, $parentId);
$documentModel = $fileManager->getDocumentModel($parentType);
if ($parentModel === null || $documentModel === null || $fileBeingUploaded === null) {
return new Response('', 404);
}
$documentModel->setParentId($parentId);
$documentModel->setLocale(Lang::getDefaultLanguage()->getLocale());
$documentModel->setTitle($fileBeingUploaded->getClientOriginalName());
$documentCreateOrUpdateEvent = new DocumentCreateOrUpdateEvent(
$parentType,
$parentId
);
$documentCreateOrUpdateEvent->setModelDocument($documentModel);
$documentCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded);
$documentCreateOrUpdateEvent->setParentName($parentModel->getTitle());
// Dispatch Event to the Action
$this->dispatch(
TheliaEvents::DOCUMENT_SAVE,
$documentCreateOrUpdateEvent
);
$this->adminLogAppend(
AdminResources::retrieve($parentType),
AccessManager::UPDATE,
$this->container->get('thelia.translator')->trans(
'Saving documents for %parentName% parent id %parentId% (%parentType%)',
array(
'%parentName%' => $documentCreateOrUpdateEvent->getParentName(),
'%parentId%' => $documentCreateOrUpdateEvent->getParentId(),
'%parentType%' => $documentCreateOrUpdateEvent->getDocumentType()
),
'document' 'document'
) );
);
return new ResponseRest(array('status' => true, 'message' => '')); return new ResponseRest($message, 'text', 403);
} }
$documentModel = $fileManager->getModelInstance('document', $parentType);
$parentModel = $documentModel->getParentFileModel($parentType, $parentId);
if ($parentModel === null || $documentModel === null || $fileBeingUploaded === null) {
return new Response('', 404);
}
$documentModel->setParentId($parentId);
$documentModel->setLocale(Lang::getDefaultLanguage()->getLocale());
$documentModel->setTitle($fileBeingUploaded->getClientOriginalName());
$documentCreateOrUpdateEvent = new DocumentCreateOrUpdateEvent($parentId);
$documentCreateOrUpdateEvent->setModelDocument($documentModel);
$documentCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded);
$documentCreateOrUpdateEvent->setParentName($parentModel->getTitle());
// Dispatch Event to the Action
$this->dispatch(
TheliaEvents::DOCUMENT_SAVE,
$documentCreateOrUpdateEvent
);
$this->adminLogAppend(
AdminResources::retrieve($parentType),
AccessManager::UPDATE,
$this->container->get('thelia.translator')->trans(
'Saving document for %parentName% parent id %parentId%',
array(
'%parentName%' => $documentCreateOrUpdateEvent->getParentName(),
'%parentId%' => $documentCreateOrUpdateEvent->getParentId()
),
'document'
)
);
return new ResponseRest(array('status' => true, 'message' => ''));
} }
return new Response('', 404); return new Response('', 404);
@@ -303,21 +303,25 @@ class FileController extends BaseAdminController
if (null !== $response = $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE)) { if (null !== $response = $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE)) {
return $response; return $response;
} }
try { $fileManager = $this->getFileManager();
$fileManager = new FileManager(); $imageModel = $fileManager->getModelInstance('image', $parentType);
$image = $fileManager->getImageModelQuery($parentType)->findPk($imageId);
$redirectUrl = $fileManager->getRedirectionUrl($parentType, $image->getParentId(), FileManager::FILE_TYPE_IMAGES);
return $this->render('image-edit', array( $redirectUrl = $imageModel->getRedirectionUrl($imageId);
'imageId' => $imageId,
'imageType' => $parentType, $image = $imageModel->getQueryInstance()->findPk($imageId);
'redirectUrl' => $redirectUrl,
'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_IMAGES), return $this->render('image-edit', array(
'breadcrumb' => $image->getBreadcrumb($this->getRouter($this->getCurrentRouter()), $this->container, 'images') 'imageId' => $imageId,
)); 'imageType' => $parentType,
} catch (\Exception $e) { 'redirectUrl' => $redirectUrl,
$this->pageNotFound(); 'formId' => $imageModel->getUpdateFormId(),
} 'breadcrumb' => $image->getBreadcrumb(
$this->getRouter($this->getCurrentRouter()),
$this->container,
'images',
$this->getCurrentEditionLocale()
)
));
} }
/** /**
@@ -333,21 +337,26 @@ class FileController extends BaseAdminController
if (null !== $response = $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE)) { if (null !== $response = $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE)) {
return $response; return $response;
} }
try {
$fileManager = new FileManager();
$document = $fileManager->getDocumentModelQuery($parentType)->findPk($documentId);
$redirectUrl = $fileManager->getRedirectionUrl($parentType, $document->getParentId(), FileManager::FILE_TYPE_DOCUMENTS);
return $this->render('document-edit', array( $fileManager = $this->getFileManager();
'documentId' => $documentId, $documentModel = $fileManager->getModelInstance('document', $parentType);
'documentType' => $parentType,
'redirectUrl' => $redirectUrl, $document = $documentModel->getQueryInstance()->findPk($documentId);
'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_DOCUMENTS),
'breadcrumb' => $document->getBreadcrumb($this->getRouter($this->getCurrentRouter()), $this->container, 'documents') $redirectUrl = $documentModel->getRedirectionUrl($documentId);
));
} catch (\Exception $e) { return $this->render('document-edit', array(
$this->pageNotFound(); 'documentId' => $documentId,
} 'documentType' => $parentType,
'redirectUrl' => $redirectUrl,
'formId' => $documentModel->getUpdateFormId(),
'breadcrumb' => $document->getBreadcrumb(
$this->getRouter($this->getCurrentRouter()),
$this->container,
'documents',
$this->getCurrentEditionLocale()
)
));
} }
/** /**
@@ -366,12 +375,18 @@ class FileController extends BaseAdminController
$message = false; $message = false;
$fileManager = new FileManager(); $fileManager = $this->getFileManager();
$imageModification = $fileManager->getImageForm($parentType, $this->getRequest());
$modelInstance = $fileManager->getModelInstance('image', $parentType);
$imageModification = $modelInstance->getUpdateFormInstance($this->getRequest());
/** @var FileModelInterface $image */
$image = $modelInstance->getQueryInstance()->findPk($imageId);
try { try {
$image = $fileManager->getImageModelQuery($parentType)->findPk($imageId);
$oldImage = clone $image; $oldImage = clone $image;
if (null === $image) { if (null === $image) {
throw new \InvalidArgumentException(sprintf('%d image id does not exist', $imageId)); throw new \InvalidArgumentException(sprintf('%d image id does not exist', $imageId));
} }
@@ -394,7 +409,7 @@ class FileController extends BaseAdminController
$this->adminLogAppend(AdminResources::retrieve($parentType), AccessManager::UPDATE, sprintf('Image with Ref %s (ID %d) modified', $imageUpdated->getTitle(), $imageUpdated->getId())); $this->adminLogAppend(AdminResources::retrieve($parentType), AccessManager::UPDATE, sprintf('Image with Ref %s (ID %d) modified', $imageUpdated->getTitle(), $imageUpdated->getId()));
if ($this->getRequest()->get('save_mode') == 'close') { if ($this->getRequest()->get('save_mode') == 'close') {
$this->redirect(URL::getInstance()->absoluteUrl($fileManager->getRedirectionUrl($parentType, $image->getParentId(), FileManager::FILE_TYPE_IMAGES))); $this->redirect(URL::getInstance()->absoluteUrl($modelInstance->getRedirectionUrl($imageId)));
} else { } else {
$this->redirectSuccess($imageModification); $this->redirectSuccess($imageModification);
} }
@@ -417,13 +432,13 @@ class FileController extends BaseAdminController
->setGeneralError($message); ->setGeneralError($message);
} }
$redirectUrl = $fileManager->getRedirectionUrl($parentType, $image->getParentId(), FileManager::FILE_TYPE_IMAGES); $redirectUrl = $modelInstance->getRedirectionUrl($imageId);
return $this->render('image-edit', array( return $this->render('image-edit', array(
'imageId' => $imageId, 'imageId' => $imageId,
'imageType' => $parentType, 'imageType' => $parentType,
'redirectUrl' => $redirectUrl, 'redirectUrl' => $redirectUrl,
'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_IMAGES) 'formId' => $modelInstance->getUpdateFormId()
)); ));
} }
@@ -443,12 +458,18 @@ class FileController extends BaseAdminController
$message = false; $message = false;
$fileManager = new FileManager(); $fileManager = $this->getFileManager();
$documentModification = $fileManager->getDocumentForm($parentType, $this->getRequest());
$modelInstance = $fileManager->getModelInstance('document', $parentType);
$documentModification = $modelInstance->getUpdateFormInstance($this->getRequest());
/** @var FileModelInterface $document */
$document = $modelInstance->getQueryInstance()->findPk($documentId);
try { try {
$document = $fileManager->getDocumentModelQuery($parentType)->findPk($documentId);
$oldDocument = clone $document; $oldDocument = clone $document;
if (null === $document) { if (null === $document) {
throw new \InvalidArgumentException(sprintf('%d document id does not exist', $documentId)); throw new \InvalidArgumentException(sprintf('%d document id does not exist', $documentId));
} }
@@ -471,7 +492,7 @@ class FileController extends BaseAdminController
$this->adminLogAppend(AdminResources::retrieve($parentType), AccessManager::UPDATE, sprintf('Document with Ref %s (ID %d) modified', $documentUpdated->getTitle(), $documentUpdated->getId())); $this->adminLogAppend(AdminResources::retrieve($parentType), AccessManager::UPDATE, sprintf('Document with Ref %s (ID %d) modified', $documentUpdated->getTitle(), $documentUpdated->getId()));
if ($this->getRequest()->get('save_mode') == 'close') { if ($this->getRequest()->get('save_mode') == 'close') {
$this->redirect(URL::getInstance()->absoluteUrl($fileManager->getRedirectionUrl($parentType, $document->getParentId(), FileManager::FILE_TYPE_DOCUMENTS))); $this->redirect(URL::getInstance()->absoluteUrl($modelInstance->getRedirectionUrl($documentId)));
} else { } else {
$this->redirectSuccess($documentModification); $this->redirectSuccess($documentModification);
} }
@@ -494,13 +515,13 @@ class FileController extends BaseAdminController
->setGeneralError($message); ->setGeneralError($message);
} }
$redirectUrl = $fileManager->getRedirectionUrl($parentType, $document->getParentId(), FileManager::FILE_TYPE_DOCUMENTS); $redirectUrl = $modelInstance->getRedirectionUrl($documentId);
return $this->render('document-edit', array( return $this->render('document-edit', array(
'documentId' => $documentId, 'documentId' => $documentId,
'documentType' => $parentType, 'documentType' => $parentType,
'redirectUrl' => $redirectUrl, 'redirectUrl' => $redirectUrl,
'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_DOCUMENTS) 'formId' => $modelInstance->getUpdateFormId()
)); ));
} }
@@ -519,9 +540,10 @@ class FileController extends BaseAdminController
$this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE);
$this->checkXmlHttpRequest(); $this->checkXmlHttpRequest();
$fileManager = new FileManager(); $fileManager = $this->getFileManager();
$imageModelQuery = $fileManager->getImageModelQuery($parentType); $modelInstance = $fileManager->getModelInstance('image', $parentType);
$model = $imageModelQuery->findPk($imageId);
$model = $modelInstance->getQueryInstance()->findPk($imageId);
if ($model == null) { if ($model == null) {
return $this->pageNotFound(); return $this->pageNotFound();
@@ -590,7 +612,7 @@ class FileController extends BaseAdminController
return new Response($message); return new Response($message);
} }
public function updateImagePositionAction($parentType, $parentId) public function updateImagePositionAction($parentType, /** @noinspection PhpUnusedParameterInspection */ $parentId)
{ {
$message = null; $message = null;
@@ -600,9 +622,9 @@ class FileController extends BaseAdminController
$this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE);
$this->checkXmlHttpRequest(); $this->checkXmlHttpRequest();
$fileManager = new FileManager(); $fileManager = $this->getFileManager();
$imageModelQuery = $fileManager->getImageModelQuery($parentType); $modelInstance = $fileManager->getModelInstance('image', $parentType);
$model = $imageModelQuery->findPk($imageId); $model = $modelInstance->getQueryInstance()->findPk($imageId);
if ($model === null || $position === null) { if ($model === null || $position === null) {
return $this->pageNotFound(); return $this->pageNotFound();
@@ -610,7 +632,7 @@ class FileController extends BaseAdminController
// Feed event // Feed event
$imageUpdateImagePositionEvent = new UpdateFilePositionEvent( $imageUpdateImagePositionEvent = new UpdateFilePositionEvent(
$fileManager->getImageModelQuery($parentType), $modelInstance->getQueryInstance($parentType),
$imageId, $imageId,
UpdateFilePositionEvent::POSITION_ABSOLUTE, UpdateFilePositionEvent::POSITION_ABSOLUTE,
$position $position
@@ -644,7 +666,7 @@ class FileController extends BaseAdminController
return new Response($message); return new Response($message);
} }
public function updateDocumentPositionAction($parentType, $parentId) public function updateDocumentPositionAction($parentType, /** @noinspection PhpUnusedParameterInspection */ $parentId)
{ {
$message = null; $message = null;
@@ -654,9 +676,9 @@ class FileController extends BaseAdminController
$this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE);
$this->checkXmlHttpRequest(); $this->checkXmlHttpRequest();
$fileManager = new FileManager(); $fileManager = $this->getFileManager();
$documentModelQuery = $fileManager->getDocumentModelQuery($parentType); $modelInstance = $fileManager->getModelInstance('document', $parentType);
$model = $documentModelQuery->findPk($documentId); $model = $modelInstance->getQueryInstance()->findPk($documentId);
if ($model === null || $position === null) { if ($model === null || $position === null) {
return $this->pageNotFound(); return $this->pageNotFound();
@@ -664,7 +686,7 @@ class FileController extends BaseAdminController
// Feed event // Feed event
$documentUpdateDocumentPositionEvent = new UpdateFilePositionEvent( $documentUpdateDocumentPositionEvent = new UpdateFilePositionEvent(
$fileManager->getDocumentModelQuery($parentType), $modelInstance->getQueryInstance(),
$documentId, $documentId,
UpdateFilePositionEvent::POSITION_ABSOLUTE, UpdateFilePositionEvent::POSITION_ABSOLUTE,
$position $position
@@ -711,9 +733,9 @@ class FileController extends BaseAdminController
$this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE);
$this->checkXmlHttpRequest(); $this->checkXmlHttpRequest();
$fileManager = new FileManager(); $fileManager = $this->getFileManager();
$documentModelQuery = $fileManager->getDocumentModelQuery($parentType); $modelInstance = $fileManager->getModelInstance('document', $parentType);
$model = $documentModelQuery->findPk($documentId); $model = $modelInstance->getQueryInstance()->findPk($documentId);
if ($model == null) { if ($model == null) {
return $this->pageNotFound(); return $this->pageNotFound();
@@ -793,30 +815,19 @@ class FileController extends BaseAdminController
return $this; return $this;
} }
/**
* Check if parent type is valid or not
*
* @param string $parentType Parent type
*
* @return bool
*/
public function isParentTypeValid($parentType)
{
return (in_array($parentType, FileManager::getAvailableTypes()));
}
/** /**
* Create Image Event instance * Create Image Event instance
* *
* @param string $parentType Parent Type owning images being saved * @param string $parentType Parent Type owning images being saved
* @param CategoryImage|ProductImage|ContentImage|FolderImage $model Image model * @param FileModelInterface $model the model
* @param array $data Post data * @param array $data Post data
* *
* @return ImageCreateOrUpdateEvent * @return ImageCreateOrUpdateEvent
*/ */
protected function createImageEventInstance($parentType, $model, $data) protected function createImageEventInstance($parentType, $model, $data)
{ {
$imageCreateEvent = new ImageCreateOrUpdateEvent($parentType, null); $imageCreateEvent = new ImageCreateOrUpdateEvent(null);
$model->setLocale($data['locale']); $model->setLocale($data['locale']);
if (isset($data['title'])) { if (isset($data['title'])) {
@@ -843,15 +854,16 @@ class FileController extends BaseAdminController
/** /**
* Create Document Event instance * Create Document Event instance
* *
* @param string $parentType Parent Type owning documents being saved * @param string $parentType Parent Type owning documents being saved
* @param CategoryDocument|ProductDocument|ContentDocument|FolderDocument $model Document model * @param FileModelInterface $model the model
* @param array $data Post data * @param array $data Post data
* *
* @return DocumentCreateOrUpdateEvent * @return DocumentCreateOrUpdateEvent
*/ */
protected function createDocumentEventInstance($parentType, $model, $data) protected function createDocumentEventInstance($parentType, $model, $data)
{ {
$documentCreateEvent = new DocumentCreateOrUpdateEvent($parentType, null); $documentCreateEvent = new DocumentCreateOrUpdateEvent(null);
$model->setLocale($data['locale']); $model->setLocale($data['locale']);
if (isset($data['title'])) { if (isset($data['title'])) {
$model->setTitle($data['title']); $model->setTitle($data['title']);

View File

@@ -13,6 +13,7 @@
namespace Thelia\Core\Event\Document; namespace Thelia\Core\Event\Document;
use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\File\UploadedFile;
use Thelia\Core\Event\ActionEvent; use Thelia\Core\Event\ActionEvent;
use Thelia\Files\FileModelInterface;
use Thelia\Model\CategoryDocument; use Thelia\Model\CategoryDocument;
use Thelia\Model\ContentDocument; use Thelia\Model\ContentDocument;
use Thelia\Model\FolderDocument; use Thelia\Model\FolderDocument;
@@ -44,29 +45,23 @@ class DocumentCreateOrUpdateEvent extends ActionEvent
/** @var int Document parent id */ /** @var int Document parent id */
protected $parentId = null; protected $parentId = null;
/** @var string Document type */
protected $documentType = null;
/** @var string Parent name */ /** @var string Parent name */
protected $parentName = null; protected $parentName = null;
/** /**
* Constructor * Constructor
* *
* @param string $documentType Document type * @param int $parentId Document parent id
* ex : FileManager::TYPE_CATEGORY
* @param int $parentId Document parent id
*/ */
public function __construct($documentType, $parentId) public function __construct($parentId)
{ {
$this->documentType = $documentType;
$this->parentId = $parentId; $this->parentId = $parentId;
} }
/** /**
* Set Document to save * Set Document to save
* *
* @param CategoryDocument|ProductDocument|ContentDocument|FolderDocument $document Document to save * @param FileModelInterface $document Document to save
* *
* @return $this * @return $this
*/ */
@@ -80,37 +75,13 @@ class DocumentCreateOrUpdateEvent extends ActionEvent
/** /**
* Get Document being saved * Get Document being saved
* *
* @return CategoryDocument|ProductDocument|ContentDocument|FolderDocument * @return FileModelInterface
*/ */
public function getModelDocument() public function getModelDocument()
{ {
return $this->modelDocument; return $this->modelDocument;
} }
/**
* Set document type
*
* @param string $documentType Document type
*
* @return $this
*/
public function setDocumentType($documentType)
{
$this->documentType = $documentType;
return $this;
}
/**
* Get document type
*
* @return string
*/
public function getDocumentType()
{
return $this->documentType;
}
/** /**
* Set Document parent id * Set Document parent id
* *
@@ -186,7 +157,7 @@ class DocumentCreateOrUpdateEvent extends ActionEvent
/** /**
* Set old model value * Set old model value
* *
* @param CategoryDocument|ContentDocument|FolderDocument|ProductDocument $oldModelDocument * @param FileModelInterface $oldModelDocument
*/ */
public function setOldModelDocument($oldModelDocument) public function setOldModelDocument($oldModelDocument)
{ {
@@ -196,7 +167,7 @@ class DocumentCreateOrUpdateEvent extends ActionEvent
/** /**
* Get old model value * Get old model value
* *
* @return CategoryDocument|ContentDocument|FolderDocument|ProductDocument * @return FileModelInterface
*/ */
public function getOldModelDocument() public function getOldModelDocument()
{ {

View File

@@ -13,10 +13,7 @@
namespace Thelia\Core\Event\Document; namespace Thelia\Core\Event\Document;
use Thelia\Core\Event\ActionEvent; use Thelia\Core\Event\ActionEvent;
use Thelia\Model\CategoryDocument; use Thelia\Files\FileModelInterface;
use Thelia\Model\ContentDocument;
use Thelia\Model\FolderDocument;
use Thelia\Model\ProductDocument;
/** /**
* Created by JetBrains PhpStorm. * Created by JetBrains PhpStorm.
@@ -31,53 +28,24 @@ use Thelia\Model\ProductDocument;
*/ */
class DocumentDeleteEvent extends ActionEvent class DocumentDeleteEvent extends ActionEvent
{ {
/** @var string Document type */
protected $documentType = null;
/** @var CategoryDocument|ProductDocument|ContentDocument|FolderDocument Document about to be deleted */ /** @var FileModelInterface Document about to be deleted */
protected $documentToDelete = null; protected $documentToDelete = null;
/** /**
* Constructor * Constructor
* *
* @param CategoryDocument|ProductDocument|ContentDocument|FolderDocument $documentToDelete Document about to be deleted * @param FileModelInterface $documentToDelete Document about to be deleted
* @param string $documentType Document type
* ex : FileManager::TYPE_CATEGORY
*/ */
public function __construct($documentToDelete, $documentType) public function __construct($documentToDelete)
{ {
$this->documentToDelete = $documentToDelete; $this->documentToDelete = $documentToDelete;
$this->documentType = $documentType;
}
/**
* Set picture type
*
* @param string $documentType Document type
*
* @return $this
*/
public function setDocumentType($documentType)
{
$this->documentType = $documentType;
return $this;
}
/**
* Get picture type
*
* @return string
*/
public function getDocumentType()
{
return $this->documentType;
} }
/** /**
* Set Document about to be deleted * Set Document about to be deleted
* *
* @param CategoryDocument|ProductDocument|ContentDocument|FolderDocument $documentToDelete Document about to be deleted * @param FileModelInterface $documentToDelete Document about to be deleted
* *
* @return $this * @return $this
*/ */
@@ -91,7 +59,7 @@ class DocumentDeleteEvent extends ActionEvent
/** /**
* Get Document about to be deleted * Get Document about to be deleted
* *
* @return CategoryDocument|ProductDocument|ContentDocument|FolderDocument * @return FileModelInterface
*/ */
public function getDocumentToDelete() public function getDocumentToDelete()
{ {

View File

@@ -13,6 +13,7 @@
namespace Thelia\Core\Event\Image; namespace Thelia\Core\Event\Image;
use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\File\UploadedFile;
use Thelia\Core\Event\ActionEvent; use Thelia\Core\Event\ActionEvent;
use Thelia\Files\FileModelInterface;
/** /**
* Created by JetBrains PhpStorm. * Created by JetBrains PhpStorm.
@@ -28,10 +29,10 @@ use Thelia\Core\Event\ActionEvent;
class ImageCreateOrUpdateEvent extends ActionEvent class ImageCreateOrUpdateEvent extends ActionEvent
{ {
/** @var \Thelia\Model\CategoryImage|\Thelia\Model\ProductImage|\Thelia\Model\ContentImage|\Thelia\Model\FolderImage model to save */ /** @var FileModelInterface model to save */
protected $modelImage = array(); protected $modelImage = array();
/** @var \Thelia\Model\CategoryImage|\Thelia\Model\ProductImage|\Thelia\Model\ContentImage|\Thelia\Model\FolderImage model to save */ /** @var FileModelInterface model to save */
protected $oldModelImage = array(); protected $oldModelImage = array();
/** @var UploadedFile Image file to save */ /** @var UploadedFile Image file to save */
@@ -40,9 +41,6 @@ class ImageCreateOrUpdateEvent extends ActionEvent
/** @var int Image parent id */ /** @var int Image parent id */
protected $parentId = null; protected $parentId = null;
/** @var string Image type */
protected $imageType = null;
/** @var string Parent name */ /** @var string Parent name */
protected $parentName = null; protected $parentName = null;
@@ -51,18 +49,15 @@ class ImageCreateOrUpdateEvent extends ActionEvent
/** /**
* Constructor * Constructor
* *
* @param string $imageType Image type * @param int $parentId Image parent id
* ex : FileManager::TYPE_CATEGORY
* @param int $parentId Image parent id
*/ */
public function __construct($imageType, $parentId) public function __construct($parentId)
{ {
$this->imageType = $imageType;
$this->parentId = $parentId; $this->parentId = $parentId;
} }
/** /**
* @param mixed $locale * @param string $locale
*/ */
public function setLocale($locale) public function setLocale($locale)
{ {
@@ -82,7 +77,7 @@ class ImageCreateOrUpdateEvent extends ActionEvent
/** /**
* Set Image to save * Set Image to save
* *
* @param $image \Thelia\Model\CategoryImage|\Thelia\Model\ProductImage|\Thelia\Model\ContentImage|\Thelia\Model\FolderImage * @param FileModelInterface $image
* *
* @return $this * @return $this
*/ */
@@ -96,37 +91,13 @@ class ImageCreateOrUpdateEvent extends ActionEvent
/** /**
* Get Image being saved * Get Image being saved
* *
* @return \Thelia\Model\CategoryImage|\Thelia\Model\ProductImage|\Thelia\Model\ContentImage|\Thelia\Model\FolderImage * @return FileModelInterface
*/ */
public function getModelImage() public function getModelImage()
{ {
return $this->modelImage; return $this->modelImage;
} }
/**
* Set picture type
*
* @param string $imageType Image type
*
* @return $this
*/
public function setImageType($imageType)
{
$this->imageType = $imageType;
return $this;
}
/**
* Get picture type
*
* @return string
*/
public function getImageType()
{
return $this->imageType;
}
/** /**
* Set Image parent id * Set Image parent id
* *

View File

@@ -13,10 +13,7 @@
namespace Thelia\Core\Event\Image; namespace Thelia\Core\Event\Image;
use Thelia\Core\Event\ActionEvent; use Thelia\Core\Event\ActionEvent;
use Thelia\Model\CategoryImage; use Thelia\Files\FileModelInterface;
use Thelia\Model\ContentImage;
use Thelia\Model\FolderImage;
use Thelia\Model\ProductImage;
/** /**
* Created by JetBrains PhpStorm. * Created by JetBrains PhpStorm.
@@ -34,50 +31,23 @@ class ImageDeleteEvent extends ActionEvent
/** @var string Image type */ /** @var string Image type */
protected $imageType = null; protected $imageType = null;
/** @var CategoryImage|ProductImage|ContentImage|FolderImage Image about to be deleted */ /** @var FileModelInterface Image about to be deleted */
protected $imageToDelete = null; protected $imageToDelete = null;
/** /**
* Constructor * Constructor
* *
* @param CategoryImage|ProductImage|ContentImage|FolderImage $imageToDelete Image about to be deleted * @param FileModelInterface $imageToDelete Image about to be deleted
* @param string $imageType Image type
* ex : FileManager::TYPE_CATEGORY
*/ */
public function __construct($imageToDelete, $imageType) public function __construct($imageToDelete)
{ {
$this->imageToDelete = $imageToDelete; $this->imageToDelete = $imageToDelete;
$this->imageType = $imageType;
}
/**
* Set picture type
*
* @param string $imageType Image type
*
* @return $this
*/
public function setImageType($imageType)
{
$this->imageType = $imageType;
return $this;
}
/**
* Get picture type
*
* @return string
*/
public function getImageType()
{
return $this->imageType;
} }
/** /**
* Set Image about to be deleted * Set Image about to be deleted
* *
* @param CategoryImage|ProductImage|ContentImage|FolderImage $imageToDelete Image about to be deleted * @param FileModelInterface $imageToDelete Image about to be deleted
* *
* @return $this * @return $this
*/ */
@@ -91,7 +61,7 @@ class ImageDeleteEvent extends ActionEvent
/** /**
* Get Image about to be deleted * Get Image about to be deleted
* *
* @return CategoryImage|ProductImage|ContentImage|FolderImage * @return FileModelInterface
*/ */
public function getImageToDelete() public function getImageToDelete()
{ {

View File

@@ -61,7 +61,8 @@ function smarty_outputfilter_trimwhitespace($source, &$smarty)
return $source; return $source;
} }
function smarty_outputfilter_trimwhitespace_replace($search_str, $replace, &$subject) { function smarty_outputfilter_trimwhitespace_replace($search_str, $replace, &$subject)
{
$_len = strlen($search_str); $_len = strlen($search_str);
$_pos = 0; $_pos = 0;
for ($_i=0, $_count=count($replace); $_i<$_count; $_i++) for ($_i=0, $_count=count($replace); $_i<$_count; $_i++)
@@ -71,5 +72,3 @@ function smarty_outputfilter_trimwhitespace_replace($search_str, $replace, &$sub
break; break;
} }
?>

View File

@@ -0,0 +1,25 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Exception;
use Thelia\Log\Tlog;
class FileException extends \RuntimeException
{
public function __construct($message, $code = null, $previous = null)
{
Tlog::getInstance()->addError($message);
parent::__construct($message, $code, $previous);
}
}

View File

@@ -0,0 +1,265 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Files;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent;
use Thelia\Core\Event\Image\ImageCreateOrUpdateEvent;
use Thelia\Exception\FileException;
use Thelia\Exception\ImageException;
/**
* File Manager
*
* @package File
* @author Guillaume MOREL <gmorel@openstudio.fr>, Franck Allimant <franck@cqfdev.fr>
*
*/
class FileManager
{
protected $supportedFileModels = array();
/**
* Create a new FileManager instance.
*
* @param array $supportedFileModels The key should have form type.parent, where type is the file type (document or image) and parent is the parent object of the file, form example product, brand, folder, etc.
*/
public function __construct($supportedFileModels) {
$this->supportedFileModels = $supportedFileModels;
}
/**
* Create the file type identifier, to access the related class in the supportedFileModels table.
*
* @param string $fileType the file type, e.g. document or image.
* @param string $parentType the parent object type, e.g. product, folder, brand, etc.
* @return string
*/
protected function getFileTypeIdentifier($fileType, $parentType) {
return strtolower("$fileType.$parentType");
}
/**
* Create a new FileModelInterface instance, from the supportedFileModels table
*
* @param string $fileType the file type, such as document, image, etc.
* @param string $parentType the parent type, such as product, category, etc.
*
* @return FileModelInterface a file model interface instance
*
* @throws FileException if the file type is not supported, or if the class does not implements FileModelInterface
*/
public function getModelInstance($fileType, $parentType) {
if (! isset($this->supportedFileModels[$this->getFileTypeIdentifier($fileType, $parentType)])) {
throw new FileException(
sprintf("Unsupported file type '%s' for parent type '%s'", $fileType, $parentType)
);
}
$className = $this->supportedFileModels[$this->getFileTypeIdentifier($fileType, $parentType)];
$instance = new $className;
if (! $instance instanceof FileModelInterface) {
throw new FileException(
sprintf("Wrong class type for file type '%s', parent type '%s'. Class '%s' should implements FileModelInterface",
$fileType, $parentType, $className
)
);
}
return $instance;
}
/**
* A a new FileModelInterface class name to the supported class list.
*
* @param string $fileType the file type, such as document, image, etc.
* @param string $parentType the parent type, such as Product, Category, etc.
* @param string $fullyQualifiedClassName the fully qualified class name
*/
public function addFileModel($fileType, $parentType, $fullyQualifiedClassName) {
$this->supportedFileModels[$this->getFileTypeIdentifier($fileType, $parentType)] = $fullyQualifiedClassName;
}
/**
* Copy UploadedFile into the server storage directory
*
* @param FileModelInterface $model Model saved
* @param UploadedFile $uploadedFile Ready to be uploaded file
*
* @throws \Thelia\Exception\ImageException
* @return UploadedFile
*/
public function copyUploadedFile($model, $uploadedFile)
{
$newUploadedFile = null;
if ($uploadedFile !== null) {
$directory = $model->getUploadDir();
$fileName = $this->renameFile($model->getId(), $uploadedFile);
$newUploadedFile = $uploadedFile->move($directory, $fileName);
$model->setFile($fileName);
if (!$model->save()) {
throw new ImageException(
sprintf(
'Failed to update model after copy of uploaded file %s to %s',
$uploadedFile,
$model->getFile()
)
);
}
}
return $newUploadedFile;
}
/**
* Save file into the database
*
* @param int $parentId the parent object ID
* @param FileModelInterface $fileModel the file model object (image or document) to save.
*
* @return int number of modified rows in database
*
* @throws \Thelia\Exception\ImageException
*/
protected function saveFile($parentId, $fileModel)
{
$nbModifiedLines = 0;
if ($fileModel->getFile() !== null) {
$fileModel->setParentId($parentId);
$nbModifiedLines = $fileModel->save();
if (!$nbModifiedLines) {
throw new ImageException(
sprintf(
'Failed to update %s file model',
$fileModel->getFile()
)
);
}
}
return $nbModifiedLines;
}
/**
* Save file into the database
*
* @param ImageCreateOrUpdateEvent $event the event
* @param FileModelInterface $imageModel the file model object (image or document) to save.
*
* @return int number of modified rows in database
*/
public function saveImage($event, $imageModel)
{
return $this->saveFile($event->getParentId(), $imageModel);
}
/**
* Save file into the database
*
* @param DocumentCreateOrUpdateEvent $event the event
* @param FileModelInterface $documentModel the file model object (image or document) to save.
*
* @return int number of modified rows in database
*/
public function saveDocument($event, $documentModel)
{
return $this->saveFile($event->getParentId(), $documentModel);
}
/**
* Sanitizes a filename replacing whitespace with dashes
*
* Removes special characters that are illegal in filenames on certain
* operating systems and special characters requiring special escaping
* to manipulate at the command line.
*
* @param string $string The filename to be sanitized
*
* @return string The sanitized filename
*/
public function sanitizeFileName($string)
{
return strtolower(preg_replace('/[^a-zA-Z0-9-_\.]/', '', $string));
}
/**
* Delete image from file storage and database
*
* @param FileModelInterface $model File being deleted
*/
public function c($model)
{
$url = $model->getUploadDir() . DS . $model->getFile();
@unlink(str_replace('..', '', $url));
$model->delete();
}
/**
* Rename file with image model id
*
* @param int $modelId Model id
* @param UploadedFile $uploadedFile File being saved
*
* @return string
*/
public function renameFile($modelId, $uploadedFile)
{
$extension = $uploadedFile->getClientOriginalExtension();
if (!empty($extension)) {
$extension = '.' . strtolower($extension);
}
$fileName = $this->sanitizeFileName(
str_replace(
$extension,
'',
$uploadedFile->getClientOriginalName()
) . '-' . $modelId . $extension
);
return $fileName;
}
/**
* Check if a file is an image
* Check based on mime type
*
* @param string $mimeType File mime type
*
* @return bool
*/
public function isImage($mimeType)
{
$isValid = false;
$allowedType = array('image/jpeg' , 'image/png' ,'image/gif');
if (in_array($mimeType, $allowedType)) {
$isValid = true;
}
return $isValid;
}
}

View File

@@ -0,0 +1,113 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Files;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Propel\Runtime\ActiveRecord\ActiveRecordInterface;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Form\BaseForm;
interface FileModelInterface
{
/**
* Set file parent id
*
* @param int $parentId parent id
*
* @return $this
*/
public function setParentId($parentId);
/**
* Get file parent id
*
* @return int parent id
*/
public function getParentId();
/**
* @return string the file name
*/
public function getFile();
/**
* @param string $file the file name
*/
public function setFile($file);
/**
* @return FileModelParentInterface the parent file model
*/
public function getParentFileModel();
/**
* Get the ID of the form used to change this object information
*
* @return BaseForm the form
*/
public function getUpdateFormId();
/**
* Get the form instance used to change this object information
*
* @param Request $request the current request
*
* @return BaseForm the form
*/
public function getUpdateFormInstance(Request $request);
/**
* @return string the path to the upload directory where files are stored, without final slash
*/
public function getUploadDir();
/**
* @param int $objectId the object ID
*
* @return string the URL to redirect to after update from the back-office
*/
public function getRedirectionUrl($objectId);
/**
* Get the Query instance for this object
*
* @return ModelCriteria
*/
public function getQueryInstance();
public function save();
public function delete();
public function getId();
/**
* Set the current title
*
* @param string $title the title in the current locale
* @return FileModelInterface
*/
public function setTitle($title);
public function setChapo($chapo);
public function setDescription($description);
public function setPostscriptum($postscriptum);
/**
* Set the current locale
*
* @param string $locale the locale string
* @return FileModelInterface
*/
public function setLocale($locale);
}

View File

@@ -0,0 +1,21 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Files;
use Propel\Runtime\ActiveRecord\ActiveRecordInterface;
use Thelia\Form\BaseForm;
interface FileModelParentInterface
{
public function getTitle();
}

View File

@@ -31,24 +31,7 @@ use Thelia\Form\BaseForm;
abstract class DocumentModification extends BaseForm abstract class DocumentModification extends BaseForm
{ {
/** /**
* * @inheritdoc
* in this function you add all the fields you need for your Form.
* Form this you have to call add method on $this->form attribute :
*
* $this->form->add('name', 'text')
* ->add('email', 'email', array(
* 'attr' => array(
* 'class' => 'field'
* ),
* 'label' => 'email',
* 'constraints' => array(
* new NotBlank()
* )
* )
* )
* ->add('age', 'integer');
*
* @return null
*/ */
protected function buildForm() protected function buildForm()
{ {
@@ -56,68 +39,80 @@ abstract class DocumentModification extends BaseForm
'file', 'file',
'file', 'file',
array( array(
'required' => false,
'constraints' => array(), 'constraints' => array(),
'label' => Translator::getInstance()->trans('Replace current document by this file'), 'label' => Translator::getInstance()->trans('Replace current document by this file'),
'label_attr' => array( 'label_attr' => array(
'for' => 'file' 'for' => 'file'
) )
) )
); )
->add(
$this->formBuilder 'title',
->add( 'text',
'title', array(
'text', 'required' => true,
array( 'constraints' => array(
'constraints' => array( new NotBlank()
new NotBlank() ),
), 'label' => Translator::getInstance()->trans('Title'),
'label' => Translator::getInstance()->trans('Title'), 'label_attr' => array(
'label_attr' => array( 'for' => 'title'
'for' => 'title'
)
) )
) )
->add( )
'description', ->add(
'text', 'description',
array( 'textarea',
'constraints' => array(), array(
'label' => Translator::getInstance()->trans('Description'), 'required' => false,
'label_attr' => array( 'constraints' => array(),
'for' => 'description' 'label' => Translator::getInstance()->trans('Description'),
) 'label_attr' => array(
'for' => 'description',
'rows' => 5
) )
) )
->add( )
'chapo', ->add(
'text', 'chapo',
array( 'textarea',
'constraints' => array(), array(
'label' => Translator::getInstance()->trans('Chapo'), 'required' => false,
'label_attr' => array( 'constraints' => array(),
'for' => 'chapo' 'label' => Translator::getInstance()->trans('Chapo'),
) 'label_attr' => array(
'for' => 'chapo',
'rows' => 3
) )
) )
->add( )
'postscriptum', ->add(
'text', 'postscriptum',
array( 'textarea',
'constraints' => array(), array(
'label' => Translator::getInstance()->trans('Post Scriptum'), 'required' => false,
'label_attr' => array( 'constraints' => array(),
'for' => 'postscriptum' 'label' => Translator::getInstance()->trans('Post Scriptum'),
) 'label_attr' => array(
'for' => 'postscriptum',
'rows' => 3
) )
) )
)
->add("locale", "text", array( ->add(
"locale",
"hidden",
array(
'required' => true,
"constraints" => array( "constraints" => array(
new NotBlank() new NotBlank()
), ),
"label_attr" => array("for" => "locale_create") "label_attr" => array(
)) "for" => "locale_create"
)
)
)
; ;
} }
} }

View File

@@ -33,24 +33,7 @@ abstract class ImageModification extends BaseForm
{ {
/** /**
* * @inheritdoc
* in this function you add all the fields you need for your Form.
* Form this you have to call add method on $this->form attribute :
*
* $this->form->add('name', 'text')
* ->add('email', 'email', array(
* 'attr' => array(
* 'class' => 'field'
* ),
* 'label' => 'email',
* 'constraints' => array(
* new NotBlank()
* )
* )
* )
* ->add('age', 'integer');
*
* @return null
*/ */
protected function buildForm() protected function buildForm()
{ {
@@ -58,6 +41,7 @@ abstract class ImageModification extends BaseForm
'file', 'file',
'file', 'file',
array( array(
'required' => false,
'constraints' => array( 'constraints' => array(
new Image( new Image(
array( array(
@@ -71,61 +55,73 @@ abstract class ImageModification extends BaseForm
'for' => 'file' 'for' => 'file'
) )
) )
); )
->add(
$this->formBuilder 'title',
->add( 'text',
'title', array(
'text', 'required' => true,
array( 'constraints' => array(
'constraints' => array( new NotBlank()
new NotBlank() ),
), 'label' => Translator::getInstance()->trans('Title'),
'label' => Translator::getInstance()->trans('Title'), 'label_attr' => array(
'label_attr' => array( 'for' => 'title'
'for' => 'title'
)
) )
) )
->add( )
'description', ->add(
'text', 'description',
array( 'textarea',
'constraints' => array(), array(
'label' => Translator::getInstance()->trans('Description'), 'required' => false,
'label_attr' => array( 'constraints' => array(),
'for' => 'description' 'label' => Translator::getInstance()->trans('Description'),
) 'label_attr' => array(
'for' => 'description',
'rows' => 5
) )
) )
->add( )
'chapo', ->add(
'text', 'chapo',
array( 'textarea',
'constraints' => array(), array(
'label' => Translator::getInstance()->trans('Chapo'), 'required' => false,
'label_attr' => array( 'constraints' => array(),
'for' => 'chapo' 'label' => Translator::getInstance()->trans('Chapo'),
) 'label_attr' => array(
'for' => 'chapo',
'rows' => 3
) )
) )
->add( )
'postscriptum', ->add(
'text', 'postscriptum',
array( 'textarea',
'constraints' => array(), array(
'label' => Translator::getInstance()->trans('Post Scriptum'), 'required' => false,
'label_attr' => array( 'constraints' => array(),
'for' => 'postscriptum' 'label' => Translator::getInstance()->trans('Post Scriptum'),
) 'label_attr' => array(
'for' => 'postscriptum',
'rows' => 3
) )
) )
->add("locale", "text", array( )
->add(
"locale",
"hidden",
array(
'required' => true,
"constraints" => array( "constraints" => array(
new NotBlank() new NotBlank()
), ),
"label_attr" => array("for" => "locale_create") "label_attr" => array(
)) "for" => "locale_create"
)
)
)
; ;
} }
} }

View File

@@ -2,16 +2,23 @@
namespace Thelia\Model; namespace Thelia\Model;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Router; use Symfony\Component\Routing\Router;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Files\FileModelParentInterface;
use Thelia\Form\BaseForm;
use Thelia\Form\CategoryImageModification;
use Thelia\Model\Base\CategoryImage as BaseCategoryImage; use Thelia\Model\Base\CategoryImage as BaseCategoryImage;
use Propel\Runtime\Connection\ConnectionInterface; use Propel\Runtime\Connection\ConnectionInterface;
use Thelia\Model\Base\CategoryImageQuery;
use Thelia\Model\Breadcrumb\BreadcrumbInterface; use Thelia\Model\Breadcrumb\BreadcrumbInterface;
use Thelia\Model\Breadcrumb\CatalogBreadcrumbTrait; use Thelia\Model\Breadcrumb\CatalogBreadcrumbTrait;
use Thelia\Files\FileModelInterface;
use Thelia\Model\Tools\ModelEventDispatcherTrait; use Thelia\Model\Tools\ModelEventDispatcherTrait;
use Thelia\Model\Tools\PositionManagementTrait; use Thelia\Model\Tools\PositionManagementTrait;
class CategoryImage extends BaseCategoryImage implements BreadcrumbInterface class CategoryImage extends BaseCategoryImage implements BreadcrumbInterface, FileModelInterface
{ {
use ModelEventDispatcherTrait; use ModelEventDispatcherTrait;
use PositionManagementTrait; use PositionManagementTrait;
@@ -19,6 +26,8 @@ class CategoryImage extends BaseCategoryImage implements BreadcrumbInterface
/** /**
* Calculate next position relative to our parent * Calculate next position relative to our parent
*
* @param CategoryImageQuery $query
*/ */
protected function addCriteriaToPositionQuery($query) protected function addCriteriaToPositionQuery($query)
{ {
@@ -36,11 +45,7 @@ class CategoryImage extends BaseCategoryImage implements BreadcrumbInterface
} }
/** /**
* Set Image parent id * @inheritdoc
*
* @param int $parentId parent id
*
* @return $this
*/ */
public function setParentId($parentId) public function setParentId($parentId)
{ {
@@ -50,9 +55,7 @@ class CategoryImage extends BaseCategoryImage implements BreadcrumbInterface
} }
/** /**
* Get Image parent id * @inheritdoc
*
* @return int parent id
*/ */
public function getParentId() public function getParentId()
{ {
@@ -71,13 +74,68 @@ class CategoryImage extends BaseCategoryImage implements BreadcrumbInterface
} }
/** /**
* * @inheritdoc
* return the complete breadcrumb for a given resource.
*
* @return array
*/ */
public function getBreadcrumb(Router $router, ContainerInterface $container, $tab) public function getBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale)
{ {
return $this->getCategoryBreadcrumb($router, $container, $tab); return $this->getCategoryBreadcrumb($router, $container, $tab, $locale);
}
/**
* @return FileModelParentInterface the parent file model
*/
public function getParentFileModel()
{
return new Category();
}
/**
* Get the ID of the form used to change this object information
*
* @return BaseForm the form
*/
public function getUpdateFormId()
{
return 'thelia.admin.category.image.modification';
}
/**
* Get the form instance used to change this object information
*
* @param \Thelia\Core\HttpFoundation\Request $request
*
* @return BaseForm the form
*/
public function getUpdateFormInstance(Request $request)
{
return new CategoryImageModification($request);
}
/**
* @return string the path to the upload directory where files are stored, without final slash
*/
public function getUploadDir()
{
return THELIA_LOCAL_DIR . 'media'.DS.'images'.DS.'category';
}
/**
* @param int $objectId the ID of the object
*
* @return string the URL to redirect to after update from the back-office
*/
public function getRedirectionUrl($objectId)
{
return '/admin/categories/update?category_id=' . $objectId . '?current_tab=image';
}
/**
* Get the Query instance for this object
*
* @return ModelCriteria
*/
public function getQueryInstance()
{
return CategoryImageQuery::create();
} }
} }

View File

@@ -6,19 +6,23 @@ use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\Propel; use Propel\Runtime\Propel;
use Thelia\Core\Event\Content\ContentEvent; use Thelia\Core\Event\Content\ContentEvent;
use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Event\TheliaEvents;
use Thelia\Files\FileModelParentInterface;
use Thelia\Model\Base\Content as BaseContent; use Thelia\Model\Base\Content as BaseContent;
use Thelia\Model\Map\ContentTableMap; use Thelia\Model\Map\ContentTableMap;
use Propel\Runtime\Connection\ConnectionInterface; use Propel\Runtime\Connection\ConnectionInterface;
use Thelia\Model\Tools\ModelEventDispatcherTrait;
use Thelia\Model\Tools\PositionManagementTrait;
use Thelia\Model\Tools\UrlRewritingTrait;
class Content extends BaseContent class Content extends BaseContent implements FileModelParentInterface
{ {
use \Thelia\Model\Tools\ModelEventDispatcherTrait; use ModelEventDispatcherTrait;
use \Thelia\Model\Tools\PositionManagementTrait; use PositionManagementTrait;
use \Thelia\Model\Tools\UrlRewritingTrait; use UrlRewritingTrait;
/** /**
* {@inheritDoc} * {@inheritDoc}

View File

@@ -2,14 +2,21 @@
namespace Thelia\Model; namespace Thelia\Model;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Router; use Symfony\Component\Routing\Router;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Files\FileModelParentInterface;
use Thelia\Form\BaseForm;
use Thelia\Form\ContentDocumentModification;
use Thelia\Model\Base\ContentDocument as BaseContentDocument; use Thelia\Model\Base\ContentDocument as BaseContentDocument;
use Propel\Runtime\Connection\ConnectionInterface; use Propel\Runtime\Connection\ConnectionInterface;
use Thelia\Model\Base\ContentDocumentQuery;
use Thelia\Model\Breadcrumb\BreadcrumbInterface; use Thelia\Model\Breadcrumb\BreadcrumbInterface;
use Thelia\Model\Breadcrumb\FolderBreadcrumbTrait; use Thelia\Model\Breadcrumb\FolderBreadcrumbTrait;
use Thelia\Files\FileModelInterface;
class ContentDocument extends BaseContentDocument implements BreadcrumbInterface class ContentDocument extends BaseContentDocument implements BreadcrumbInterface, FileModelInterface
{ {
use \Thelia\Model\Tools\ModelEventDispatcherTrait; use \Thelia\Model\Tools\ModelEventDispatcherTrait;
use \Thelia\Model\Tools\PositionManagementTrait; use \Thelia\Model\Tools\PositionManagementTrait;
@@ -17,6 +24,8 @@ class ContentDocument extends BaseContentDocument implements BreadcrumbInterface
/** /**
* Calculate next position relative to our parent * Calculate next position relative to our parent
*
* @param ContentDocumentQuery $query
*/ */
protected function addCriteriaToPositionQuery($query) protected function addCriteriaToPositionQuery($query)
{ {
@@ -34,11 +43,7 @@ class ContentDocument extends BaseContentDocument implements BreadcrumbInterface
} }
/** /**
* Set Document parent id * @inheritdoc
*
* @param int $parentId parent id
*
* @return $this
*/ */
public function setParentId($parentId) public function setParentId($parentId)
{ {
@@ -48,9 +53,7 @@ class ContentDocument extends BaseContentDocument implements BreadcrumbInterface
} }
/** /**
* Get Document parent id * @inheritdoc
*
* @return int parent id
*/ */
public function getParentId() public function getParentId()
{ {
@@ -69,13 +72,68 @@ class ContentDocument extends BaseContentDocument implements BreadcrumbInterface
} }
/** /**
* * @inheritdoc
* return the complete breadcrumb for a given resource.
*
* @return array
*/ */
public function getBreadcrumb(Router $router, ContainerInterface $container, $tab) public function getBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale)
{ {
return $this->getContentBreadcrumb($router, $container, $tab); return $this->getContentBreadcrumb($router, $container, $tab, $locale);
}
/**
* @return FileModelParentInterface the parent file model
*/
public function getParentFileModel()
{
return new Content();
}
/**
* Get the ID of the form used to change this object information
*
* @return BaseForm the form
*/
public function getUpdateFormId()
{
return 'thelia.admin.content.document.modification';
}
/**
* Get the form instance used to change this object information
*
* @param \Thelia\Core\HttpFoundation\Request $request
*
* @return BaseForm the form
*/
public function getUpdateFormInstance(Request $request)
{
return new ContentDocumentModification($request);
}
/**
* @return string the path to the upload directory where files are stored, without final slash
*/
public function getUploadDir()
{
return THELIA_LOCAL_DIR . 'media'.DS.'documents'.DS.'content';
}
/**
* @param int $objectId the ID of the object
*
* @return string the URL to redirect to after update from the back-office
*/
public function getRedirectionUrl($objectId)
{
return '/admin/content/update/' . $objectId . '?current_tab=document';
}
/**
* Get the Query instance for this object
*
* @return ModelCriteria
*/
public function getQueryInstance()
{
return ContentDocumentQuery::create();
} }
} }

View File

@@ -2,14 +2,20 @@
namespace Thelia\Model; namespace Thelia\Model;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Router; use Symfony\Component\Routing\Router;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Files\FileModelParentInterface;
use Thelia\Form\BaseForm;
use Thelia\Form\ContentImageModification;
use Thelia\Model\Base\ContentImage as BaseContentImage; use Thelia\Model\Base\ContentImage as BaseContentImage;
use Propel\Runtime\Connection\ConnectionInterface; use Propel\Runtime\Connection\ConnectionInterface;
use Thelia\Model\Breadcrumb\BreadcrumbInterface; use Thelia\Model\Breadcrumb\BreadcrumbInterface;
use Thelia\Model\Breadcrumb\FolderBreadcrumbTrait; use Thelia\Model\Breadcrumb\FolderBreadcrumbTrait;
use Thelia\Files\FileModelInterface;
class ContentImage extends BaseContentImage implements BreadcrumbInterface class ContentImage extends BaseContentImage implements BreadcrumbInterface, FileModelInterface
{ {
use \Thelia\Model\Tools\ModelEventDispatcherTrait; use \Thelia\Model\Tools\ModelEventDispatcherTrait;
use \Thelia\Model\Tools\PositionManagementTrait; use \Thelia\Model\Tools\PositionManagementTrait;
@@ -17,6 +23,8 @@ class ContentImage extends BaseContentImage implements BreadcrumbInterface
/** /**
* Calculate next position relative to our parent * Calculate next position relative to our parent
*
* @param ContentImageQuery $query
*/ */
protected function addCriteriaToPositionQuery($query) protected function addCriteriaToPositionQuery($query)
{ {
@@ -34,11 +42,7 @@ class ContentImage extends BaseContentImage implements BreadcrumbInterface
} }
/** /**
* Set Image parent id * @inheritdoc
*
* @param int $parentId parent id
*
* @return $this
*/ */
public function setParentId($parentId) public function setParentId($parentId)
{ {
@@ -48,9 +52,7 @@ class ContentImage extends BaseContentImage implements BreadcrumbInterface
} }
/** /**
* Get Image parent id * @inheritdoc
*
* @return int parent id
*/ */
public function getParentId() public function getParentId()
{ {
@@ -69,13 +71,69 @@ class ContentImage extends BaseContentImage implements BreadcrumbInterface
} }
/** /**
* * @inheritdoc
* return the complete breadcrumb for a given resource.
*
* @return array
*/ */
public function getBreadcrumb(Router $router, ContainerInterface $container, $tab) public function getBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale)
{ {
return $this->getContentBreadcrumb($router, $container, $tab); return $this->getContentBreadcrumb($router, $container, $tab, $locale);
} }
/**
* @return FileModelParentInterface the parent file model
*/
public function getParentFileModel()
{
return new Content();
}
/**
* Get the ID of the form used to change this object information
*
* @return BaseForm the form
*/
public function getUpdateFormId()
{
return 'thelia.admin.content.image.modification';
}
/**
* Get the form instance used to change this object information
*
* @param \Thelia\Core\HttpFoundation\Request $request
*
* @return BaseForm the form
*/
public function getUpdateFormInstance(Request $request)
{
return new ContentImageModification($request);
}
/**
* @return string the path to the upload directory where files are stored, without final slash
*/
public function getUploadDir()
{
return THELIA_LOCAL_DIR . 'media'.DS.'images'.DS.'content';
}
/**
* @param int $objectId the ID of the object
*
* @return string the URL to redirect to after update from the back-office
*/
public function getRedirectionUrl($objectId)
{
return '/admin/content/update/' . $objectId . '?current_tab=image';
}
/**
* Get the Query instance for this object
*
* @return ModelCriteria
*/
public function getQueryInstance()
{
return ContentImageQuery::create();
}
} }

View File

@@ -4,11 +4,12 @@ namespace Thelia\Model;
use Thelia\Core\Event\Folder\FolderEvent; use Thelia\Core\Event\Folder\FolderEvent;
use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Event\TheliaEvents;
use Thelia\Files\FileModelParentInterface;
use Thelia\Model\Base\Folder as BaseFolder; use Thelia\Model\Base\Folder as BaseFolder;
use Propel\Runtime\Connection\ConnectionInterface; use Propel\Runtime\Connection\ConnectionInterface;
class Folder extends BaseFolder class Folder extends BaseFolder implements FileModelParentInterface
{ {
use \Thelia\Model\Tools\ModelEventDispatcherTrait; use \Thelia\Model\Tools\ModelEventDispatcherTrait;

View File

@@ -2,14 +2,20 @@
namespace Thelia\Model; namespace Thelia\Model;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Router; use Symfony\Component\Routing\Router;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Files\FileModelParentInterface;
use Thelia\Form\BaseForm;
use Thelia\Form\FolderDocumentModification;
use Thelia\Model\Base\FolderDocument as BaseFolderDocument; use Thelia\Model\Base\FolderDocument as BaseFolderDocument;
use Propel\Runtime\Connection\ConnectionInterface; use Propel\Runtime\Connection\ConnectionInterface;
use Thelia\Model\Breadcrumb\BreadcrumbInterface; use Thelia\Model\Breadcrumb\BreadcrumbInterface;
use Thelia\Model\Breadcrumb\FolderBreadcrumbTrait; use Thelia\Model\Breadcrumb\FolderBreadcrumbTrait;
use Thelia\Files\FileModelInterface;
class FolderDocument extends BaseFolderDocument implements BreadcrumbInterface class FolderDocument extends BaseFolderDocument implements BreadcrumbInterface, FileModelInterface
{ {
use \Thelia\Model\Tools\ModelEventDispatcherTrait; use \Thelia\Model\Tools\ModelEventDispatcherTrait;
use \Thelia\Model\Tools\PositionManagementTrait; use \Thelia\Model\Tools\PositionManagementTrait;
@@ -17,6 +23,8 @@ class FolderDocument extends BaseFolderDocument implements BreadcrumbInterface
/** /**
* Calculate next position relative to our parent * Calculate next position relative to our parent
*
* @param FolderDocumentQuery $query
*/ */
protected function addCriteriaToPositionQuery($query) protected function addCriteriaToPositionQuery($query)
{ {
@@ -34,11 +42,7 @@ class FolderDocument extends BaseFolderDocument implements BreadcrumbInterface
} }
/** /**
* Set Document parent id * @inheritdoc
*
* @param int $parentId parent id
*
* @return $this
*/ */
public function setParentId($parentId) public function setParentId($parentId)
{ {
@@ -48,9 +52,7 @@ class FolderDocument extends BaseFolderDocument implements BreadcrumbInterface
} }
/** /**
* Get Document parent id * @inheritdoc
*
* @return int parent id
*/ */
public function getParentId() public function getParentId()
{ {
@@ -68,8 +70,68 @@ class FolderDocument extends BaseFolderDocument implements BreadcrumbInterface
return true; return true;
} }
public function getBreadcrumb(Router $router, ContainerInterface $container, $tab) /**
* @inheritdoc
*/
public function getBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale)
{ {
return $this->getFolderBreadcrumb($router, $container, $tab); return $this->getFolderBreadcrumb($router, $container, $tab, $locale);
}
/**
* @return FileModelParentInterface the parent file model
*/
public function getParentFileModel()
{
return new Folder();
}
/**
* Get the ID of the form used to change this object information
*
* @return BaseForm the form
*/
public function getUpdateFormId()
{
return 'thelia.admin.folder.document.modification';
}
/**
* Get the form instance used to change this object information
*
* @param \Thelia\Core\HttpFoundation\Request $request
*
* @return BaseForm the form
*/
public function getUpdateFormInstance(Request $request)
{
return new FolderDocumentModification($request);
}
/**
* @return string the path to the upload directory where files are stored, without final slash
*/
public function getUploadDir()
{
return THELIA_LOCAL_DIR . 'media'.DS.'documents'.DS.'folder';
}
/**
* @param int $objectId the ID of the parent object
* @return string the URL to redirect to after update from the back-office
*/
public function getRedirectionUrl($objectId)
{
return '/admin/folder/update/' . $objectId . '?current_tab=image';
}
/**
* Get the Query instance for this object
*
* @return ModelCriteria
*/
public function getQueryInstance()
{
return FolderDocumentQuery::create();
} }
} }

View File

@@ -2,14 +2,20 @@
namespace Thelia\Model; namespace Thelia\Model;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Router; use Symfony\Component\Routing\Router;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Files\FileModelParentInterface;
use Thelia\Form\BaseForm;
use Thelia\Form\FolderImageModification;
use Thelia\Model\Base\FolderImage as BaseFolderImage; use Thelia\Model\Base\FolderImage as BaseFolderImage;
use Propel\Runtime\Connection\ConnectionInterface; use Propel\Runtime\Connection\ConnectionInterface;
use Thelia\Model\Breadcrumb\BreadcrumbInterface; use Thelia\Model\Breadcrumb\BreadcrumbInterface;
use Thelia\Model\Breadcrumb\FolderBreadcrumbTrait; use Thelia\Model\Breadcrumb\FolderBreadcrumbTrait;
use Thelia\Files\FileModelInterface;
class FolderImage extends BaseFolderImage implements BreadcrumbInterface class FolderImage extends BaseFolderImage implements BreadcrumbInterface, FileModelInterface
{ {
use \Thelia\Model\Tools\ModelEventDispatcherTrait; use \Thelia\Model\Tools\ModelEventDispatcherTrait;
use \Thelia\Model\Tools\PositionManagementTrait; use \Thelia\Model\Tools\PositionManagementTrait;
@@ -17,6 +23,8 @@ class FolderImage extends BaseFolderImage implements BreadcrumbInterface
/** /**
* Calculate next position relative to our parent * Calculate next position relative to our parent
*
* @param FolderImageQuery $query
*/ */
protected function addCriteriaToPositionQuery($query) protected function addCriteriaToPositionQuery($query)
{ {
@@ -34,11 +42,7 @@ class FolderImage extends BaseFolderImage implements BreadcrumbInterface
} }
/** /**
* Set Image parent id * @inheritdoc
*
* @param int $parentId parent id
*
* @return $this
*/ */
public function setParentId($parentId) public function setParentId($parentId)
{ {
@@ -48,9 +52,7 @@ class FolderImage extends BaseFolderImage implements BreadcrumbInterface
} }
/** /**
* Get Image parent id * @inheritdoc
*
* @return int parent id
*/ */
public function getParentId() public function getParentId()
{ {
@@ -69,13 +71,67 @@ class FolderImage extends BaseFolderImage implements BreadcrumbInterface
} }
/** /**
* * @inheritdoc
* return the complete breadcrumb for a given resource.
*
* @return array
*/ */
public function getBreadcrumb(Router $router, ContainerInterface $container, $tab) public function getBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale)
{ {
return $this->getFolderBreadcrumb($router, $container, $tab); return $this->getFolderBreadcrumb($router, $container, $tab, $locale);
}
/**
* @return FileModelParentInterface the parent file model
*/
public function getParentFileModel()
{
return new Folder();
}
/**
* Get the ID of the form used to change this object information
*
* @return BaseForm the form
*/
public function getUpdateFormId()
{
return 'thelia.admin.folder.image.modification';
}
/**
* Get the form instance used to change this object information
*
* @param \Thelia\Core\HttpFoundation\Request $request
*
* @return BaseForm the form
*/
public function getUpdateFormInstance(Request $request)
{
return new FolderImageModification($request);
}
/**
* @return string the path to the upload directory where files are stored, without final slash
*/
public function getUploadDir()
{
return THELIA_LOCAL_DIR . 'media'.DS.'images'.DS.'folder';
}
/**
* @param int $objectId the ID of the parent object
* @return string the URL to redirect to after update from the back-office
*/
public function getRedirectionUrl($objectId)
{
return '/admin/folder/update/' . $objectId . '?current_tab=image';
}
/**
* Get the Query instance for this object
*
* @return ModelCriteria
*/
public function getQueryInstance()
{
return FolderImageQuery::create();
} }
} }

View File

@@ -4,7 +4,6 @@ namespace Thelia\Model;
use Thelia\Model\Base\OrderVersionQuery as BaseOrderVersionQuery; use Thelia\Model\Base\OrderVersionQuery as BaseOrderVersionQuery;
/** /**
* Skeleton subclass for performing query and update operations on the 'order_version' table. * Skeleton subclass for performing query and update operations on the 'order_version' table.
* *

View File

@@ -3,6 +3,7 @@
namespace Thelia\Model; namespace Thelia\Model;
use Propel\Runtime\Exception\PropelException; use Propel\Runtime\Exception\PropelException;
use Thelia\Files\FileModelParentInterface;
use Thelia\Model\Base\Product as BaseProduct; use Thelia\Model\Base\Product as BaseProduct;
use Thelia\TaxEngine\Calculator; use Thelia\TaxEngine\Calculator;
@@ -13,7 +14,7 @@ use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\Propel; use Propel\Runtime\Propel;
use Thelia\Model\Map\ProductTableMap; use Thelia\Model\Map\ProductTableMap;
class Product extends BaseProduct class Product extends BaseProduct implements FileModelParentInterface
{ {
use \Thelia\Model\Tools\ModelEventDispatcherTrait; use \Thelia\Model\Tools\ModelEventDispatcherTrait;

View File

@@ -2,16 +2,22 @@
namespace Thelia\Model; namespace Thelia\Model;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Router; use Symfony\Component\Routing\Router;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Files\FileModelParentInterface;
use Thelia\Form\BaseForm;
use Thelia\Form\ProductDocumentModification;
use Thelia\Model\Base\ProductDocument as BaseProductDocument; use Thelia\Model\Base\ProductDocument as BaseProductDocument;
use Propel\Runtime\Connection\ConnectionInterface; use Propel\Runtime\Connection\ConnectionInterface;
use Thelia\Model\Breadcrumb\BreadcrumbInterface; use Thelia\Model\Breadcrumb\BreadcrumbInterface;
use Thelia\Model\Breadcrumb\CatalogBreadcrumbTrait; use Thelia\Model\Breadcrumb\CatalogBreadcrumbTrait;
use Thelia\Files\FileModelInterface;
use Thelia\Model\Tools\PositionManagementTrait; use Thelia\Model\Tools\PositionManagementTrait;
use Thelia\Model\Tools\ModelEventDispatcherTrait; use Thelia\Model\Tools\ModelEventDispatcherTrait;
class ProductDocument extends BaseProductDocument implements BreadcrumbInterface class ProductDocument extends BaseProductDocument implements BreadcrumbInterface, FileModelInterface
{ {
use ModelEventDispatcherTrait; use ModelEventDispatcherTrait;
use PositionManagementTrait; use PositionManagementTrait;
@@ -19,6 +25,8 @@ class ProductDocument extends BaseProductDocument implements BreadcrumbInterface
/** /**
* Calculate next position relative to our parent * Calculate next position relative to our parent
*
* @param ProductDocumentQuery $query
*/ */
protected function addCriteriaToPositionQuery($query) protected function addCriteriaToPositionQuery($query)
{ {
@@ -36,11 +44,7 @@ class ProductDocument extends BaseProductDocument implements BreadcrumbInterface
} }
/** /**
* Set Document parent id * @inheritdoc
*
* @param int $parentId parent id
*
* @return $this
*/ */
public function setParentId($parentId) public function setParentId($parentId)
{ {
@@ -50,9 +54,7 @@ class ProductDocument extends BaseProductDocument implements BreadcrumbInterface
} }
/** /**
* Get Document parent id * @inheritdoc
*
* @return int parent id
*/ */
public function getParentId() public function getParentId()
{ {
@@ -71,13 +73,68 @@ class ProductDocument extends BaseProductDocument implements BreadcrumbInterface
} }
/** /**
* * @inheritdoc
* return the complete breadcrumb for a given resource.
*
* @return array
*/ */
public function getBreadcrumb(Router $router, ContainerInterface $container, $tab) public function getBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale)
{ {
return $this->getProductBreadcrumb($router, $container, $tab); return $this->getProductBreadcrumb($router, $container, $tab, $locale);
}
/**
* @return FileModelParentInterface the parent file model
*/
public function getParentFileModel()
{
return new Product();
}
/**
* Get the ID of the form used to change this object information
*
* @return BaseForm the form
*/
public function getUpdateFormId()
{
return 'thelia.admin.product.document.modification';
}
/**
* Get the form instance used to change this object information
*
* @param \Thelia\Core\HttpFoundation\Request $request
*
* @return BaseForm the form
*/
public function getUpdateFormInstance(Request $request)
{
return new ProductDocumentModification($request);
}
/**
* @return string the path to the upload directory where files are stored, without final slash
*/
public function getUploadDir()
{
return THELIA_LOCAL_DIR . 'media'.DS.'documents'.DS.'product';
}
/**
* @param int $objectId the ID of the object
*
* @return string the URL to redirect to after update from the back-office
*/
public function getRedirectionUrl($objectId)
{
return '/admin/products/update?product_id=' . $objectId . '?current_tab=document';
}
/**
* Get the Query instance for this object
*
* @return ModelCriteria
*/
public function getQueryInstance()
{
return ProductDocumentQuery::create();
} }
} }

View File

@@ -2,16 +2,21 @@
namespace Thelia\Model; namespace Thelia\Model;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Router; use Symfony\Component\Routing\Router;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Form\BaseForm;
use Thelia\Form\ProductImageModification;
use Thelia\Model\Base\ProductImage as BaseProductImage; use Thelia\Model\Base\ProductImage as BaseProductImage;
use Propel\Runtime\Connection\ConnectionInterface; use Propel\Runtime\Connection\ConnectionInterface;
use Thelia\Model\Breadcrumb\BreadcrumbInterface; use Thelia\Model\Breadcrumb\BreadcrumbInterface;
use Thelia\Model\Breadcrumb\CatalogBreadcrumbTrait; use Thelia\Model\Breadcrumb\CatalogBreadcrumbTrait;
use Thelia\Files\FileModelInterface;
use Thelia\Model\Tools\ModelEventDispatcherTrait; use Thelia\Model\Tools\ModelEventDispatcherTrait;
use Thelia\Model\Tools\PositionManagementTrait; use Thelia\Model\Tools\PositionManagementTrait;
class ProductImage extends BaseProductImage implements BreadcrumbInterface class ProductImage extends BaseProductImage implements BreadcrumbInterface, FileModelInterface
{ {
use ModelEventDispatcherTrait; use ModelEventDispatcherTrait;
use PositionManagementTrait; use PositionManagementTrait;
@@ -19,6 +24,8 @@ class ProductImage extends BaseProductImage implements BreadcrumbInterface
/** /**
* Calculate next position relative to our parent * Calculate next position relative to our parent
*
* @param ProductImageQuery $query
*/ */
protected function addCriteriaToPositionQuery($query) protected function addCriteriaToPositionQuery($query)
{ {
@@ -26,7 +33,7 @@ class ProductImage extends BaseProductImage implements BreadcrumbInterface
} }
/** /**
* {@inheritDoc} * @inheritDoc
*/ */
public function preInsert(ConnectionInterface $con = null) public function preInsert(ConnectionInterface $con = null)
{ {
@@ -36,11 +43,7 @@ class ProductImage extends BaseProductImage implements BreadcrumbInterface
} }
/** /**
* Set Image parent id * @inheritdoc
*
* @param int $parentId parent id
*
* @return $this
*/ */
public function setParentId($parentId) public function setParentId($parentId)
{ {
@@ -50,9 +53,7 @@ class ProductImage extends BaseProductImage implements BreadcrumbInterface
} }
/** /**
* Get Image parent id * @inheritdoc
*
* @return int parent id
*/ */
public function getParentId() public function getParentId()
{ {
@@ -71,13 +72,68 @@ class ProductImage extends BaseProductImage implements BreadcrumbInterface
} }
/** /**
* * @inheritdoc
* return the complete breadcrumb for a given resource.
*
* @return array
*/ */
public function getBreadcrumb(Router $router, ContainerInterface $container, $tab) public function getBreadcrumb(Router $router, ContainerInterface $container, $tab, $locale)
{ {
return $this->getProductBreadcrumb($router, $container, $tab); return $this->getProductBreadcrumb($router, $container, $tab, $locale);
}
/**
* @return FileModelParentInterface the parent file model
*/
public function getParentFileModel()
{
return new Product();
}
/**
* Get the ID of the form used to change this object information
*
* @return BaseForm the form
*/
public function getUpdateFormId()
{
return 'thelia.admin.product.image.modification';
}
/**
* Get the form instance used to change this object information
*
* @param \Thelia\Core\HttpFoundation\Request $request
*
* @return BaseForm the form
*/
public function getUpdateFormInstance(Request $request)
{
return new ProductImageModification($request);
}
/**
* @return string the path to the upload directory where files are stored, without final slash
*/
public function getUploadDir()
{
return THELIA_LOCAL_DIR . 'media'.DS.'images'.DS.'product';
}
/**
* @param int $objectId the ID of the object
*
* @return string the URL to redirect to after update from the back-office
*/
public function getRedirectionUrl($objectId)
{
return '/admin/products/update?product_id=' . $objectId . '?current_tab=image';
}
/**
* Get the Query instance for this object
*
* @return ModelCriteria
*/
public function getQueryInstance()
{
return ProductImageQuery::create();
} }
} }

View File

@@ -0,0 +1,398 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Tests\Files;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Thelia\Files\FileManager;
use Thelia\Model\Base\CategoryQuery;
use Thelia\Model\Base\ContentImageQuery;
use Thelia\Model\Base\FolderImageQuery;
use Thelia\Model\BrandDocument;
use Thelia\Model\BrandDocumentQuery;
use Thelia\Model\BrandImage;
use Thelia\Model\BrandImageQuery;
use Thelia\Model\BrandQuery;
use Thelia\Model\CategoryDocument;
use Thelia\Model\CategoryDocumentQuery;
use Thelia\Model\CategoryImage;
use Thelia\Model\CategoryImageQuery;
use Thelia\Model\ContentDocument;
use Thelia\Model\ContentDocumentQuery;
use Thelia\Model\ContentImage;
use Thelia\Model\ContentQuery;
use Thelia\Model\FolderDocument;
use Thelia\Model\FolderDocumentQuery;
use Thelia\Model\FolderImage;
use Thelia\Model\FolderQuery;
use Thelia\Model\ProductDocument;
use Thelia\Model\ProductDocumentQuery;
use Thelia\Model\ProductImage;
use Thelia\Model\ProductImageQuery;
use Thelia\Model\ProductQuery;
/**
* Class FileManagerTest
*
* @package Thelia\Tests\Files
*/
class FileManagerTest extends \PHPUnit_Framework_TestCase
{
/** @var FileManager */
protected $fileManager;
protected function setUp()
{
$this->container = new ContainerBuilder();
$this->fileManager = new FileManager([
"document.product" => "Thelia\\Model\\ProductDocument",
"image.product" => "Thelia\\Model\\ProductImage",
"document.category" => "Thelia\\Model\\CategoryDocument",
"image.category" => "Thelia\\Model\\CategoryImage",
"document.content" => "Thelia\\Model\\ContentDocument",
"image.content" => "Thelia\\Model\\ContentImage",
"document.folder" => "Thelia\\Model\\FolderDocument",
"image.folder" => "Thelia\\Model\\FolderImage",
"document.brand" => "Thelia\\Model\\BrandDocument",
"image.brand" => "Thelia\\Model\\BrandImage",
]);
$this->container->set("thelia.file_manager", $this->fileManager);
}
public function testGetFileTypeIdentifier() {
$obj = $this->fileManager->getModelInstance('document', 'product');
$this->assertInstanceOf("Thelia\\Model\\ProductDocument", $obj);
$obj = $this->fileManager->getModelInstance('image', 'product');
$this->assertInstanceOf("Thelia\\Model\\ProductImage", $obj);
$obj = $this->fileManager->getModelInstance('document', 'category');
$this->assertInstanceOf("Thelia\\Model\\CategoryDocument", $obj);
$obj = $this->fileManager->getModelInstance('image', 'category');
$this->assertInstanceOf("Thelia\\Model\\CategoryImage", $obj);
$obj = $this->fileManager->getModelInstance('document', 'content');
$this->assertInstanceOf("Thelia\\Model\\ContentDocument", $obj);
$obj = $this->fileManager->getModelInstance('image', 'content');
$this->assertInstanceOf("Thelia\\Model\\ContentImage", $obj);
$obj = $this->fileManager->getModelInstance('document', 'folder');
$this->assertInstanceOf("Thelia\\Model\\FolderDocument", $obj);
$obj = $this->fileManager->getModelInstance('image', 'folder');
$this->assertInstanceOf("Thelia\\Model\\FolderImage", $obj);
$obj = $this->fileManager->getModelInstance('document', 'brand');
$this->assertInstanceOf("Thelia\\Model\\BrandDocument", $obj);
$obj = $this->fileManager->getModelInstance('image', 'brand');
$this->assertInstanceOf("Thelia\\Model\\BrandImage", $obj);
}
/**
* @expectedException \Thelia\Exception\FileException
*/
public function testGetFileTypeIdentifierWrongType() {
$obj = $this->fileManager->getModelInstance('docment', 'product');
}
/**
* @expectedException \Thelia\Exception\FileException
*/
public function testGetFileTypeIdentifierWrongObject() {
$obj = $this->fileManager->getModelInstance('document', 'poney');
}
/**
* @expectedException \Thelia\Exception\FileException
*/
public function testGetFileTypeIdentifierWrongTypeAndObject() {
$obj = $this->fileManager->getModelInstance('licorne', 'poney');
}
public function testAddFileModel() {
$this->fileManager->addFileModel("licorne", "poney", "Thelia\\Model\\ProductDocument");
$obj = $this->fileManager->getModelInstance('licorne', 'poney');
$this->assertInstanceOf("Thelia\\Model\\ProductDocument", $obj);
}
/**
* @expectedException \Thelia\Exception\FileException
*/
public function addFileModelWrongClassTest() {
$this->fileManager->addFileModel("licorne", "poney", "Thelia\\Model\\Product");
$obj = $this->fileManager->getModelInstance('licorne', 'poney');
}
public function dotTestImageUpload($model, $type) {
$old_file = $model->getFile();
$model->setFile(null)->save();
$testFile = __DIR__ .DS. 'fixtures' .DS. 'move-test.gif';
$targetFile = THELIA_LOCAL_DIR . 'media'.DS.'images'.DS.$type.DS."original-".$model->getId().".gif";
@unlink($testFile);
@unlink($targetFile);
copy(__DIR__ .DS. 'fixtures' .DS. 'test.gif', $testFile);
$uploadedFile = new UploadedFile(
$testFile,
'original.gif',
'image/gif',
filesize($testFile),
UPLOAD_ERR_OK,
true
);
$file = $this->fileManager->copyUploadedFile($model, $uploadedFile);
$this->assertEquals("".$file, $targetFile);
$this->assertEquals(basename($targetFile), $model->getFile());
$this->assertFileExists($targetFile);
@unlink($targetFile);
@unlink($testFile);
$model->setFile($old_file)->save();
}
public function dotTestDocumentUpload($model, $type) {
$old_file = $model->getFile();
$model->setFile(null)->save();
$testFile = __DIR__ .DS. 'fixtures' .DS. 'move-test.txt';
$targetFile = THELIA_LOCAL_DIR . 'media'.DS.'documents'.DS.$type.DS."original-".$model->getId().".txt";
@unlink($testFile);
@unlink($targetFile);
copy(__DIR__ .DS. 'fixtures' .DS. 'test.txt', $testFile);
$uploadedFile = new UploadedFile(
$testFile,
'original.txt',
'plain/text',
filesize($testFile),
UPLOAD_ERR_OK,
true
);
$file = $this->fileManager->copyUploadedFile($model, $uploadedFile);
$this->assertEquals("".$file, $targetFile);
$this->assertEquals(basename($targetFile), $model->getFile());
$this->assertFileExists($targetFile);
@unlink($targetFile);
@unlink($testFile);
$model->setFile($old_file)->save();
}
public function testCopyUploadedFileProductImage() {
$this->dotTestImageUpload(
ProductImageQuery::create()->findOne(),
'product'
);
}
public function testCopyUploadedFileCategoryImage() {
$this->dotTestImageUpload(
CategoryImageQuery::create()->findOne(),
'category'
);
}
public function testCopyUploadedFileContentImage() {
$this->dotTestImageUpload(
ContentImageQuery::create()->findOne(),
'content'
);
}
public function testCopyUploadedFileFolderImage() {
$this->dotTestImageUpload(
FolderImageQuery::create()->findOne(),
'folder'
);
}
public function testCopyUploadedFileBrandImage() {
$this->dotTestImageUpload(
BrandImageQuery::create()->findOne(),
'brand'
);
}
public function testCopyUploadedFileProductDocument() {
$this->dotTestDocumentUpload(
ProductDocumentQuery::create()->findOne(),
'product'
);
}
public function testCopyUploadedFileCategoryDocument() {
$this->dotTestDocumentUpload(
CategoryDocumentQuery::create()->findOne(),
'category'
);
}
public function testCopyUploadedFileContentDocument() {
$this->dotTestDocumentUpload(
ContentDocumentQuery::create()->findOne(),
'content'
);
}
public function testCopyUploadedFileFolderDocument() {
$this->dotTestDocumentUpload(
FolderDocumentQuery::create()->findOne(),
'folder'
);
}
public function testCopyUploadedFileBrandDocument() {
$this->dotTestDocumentUpload(
BrandDocumentQuery::create()->findOne(),
'brand'
);
}
public function testSanitizeFileName() {
$file = $this->fileManager->sanitizeFileName("C:\\../test/\\..file/%ù^name \t\n\r²&²:.txt");
$this->assertEquals("c..test..filename.txt", $file);
$file = $this->fileManager->sanitizeFileName("/etc/passwd");
$this->assertEquals("etcpasswd", $file);
}
public function doTestDeleteFile($model, $modelParent, $type, $obj) {
$targetFile = THELIA_LOCAL_DIR . 'media'.DS.$type.DS.$obj.DS."original-".$model->getId().".txt";
$model->setParentId($modelParent->getId())->setFile(basename($targetFile))->save();
@unlink($targetFile);
copy(__DIR__ .DS. 'fixtures' .DS. 'test.txt', $targetFile);
$this->assertFileExists($targetFile);
$this->fileManager->deleteFile($model);
$this->assertFileNotExists($targetFile);
}
public function testDeleteFileProductDocument() {
$this->doTestDeleteFile(
new ProductDocument(),
ProductQuery::create()->findOne(),
'documents', 'product'
);
}
public function testDeleteFileProductImage() {
$this->doTestDeleteFile(
new ProductImage(),
ProductQuery::create()->findOne(),
'images', 'product'
);
}
public function testDeleteFileCategoryDocument() {
$this->doTestDeleteFile(
new CategoryDocument(),
CategoryQuery::create()->findOne(),
'documents', 'category'
);
}
public function testDeleteFileCategoryImage() {
$this->doTestDeleteFile(
new CategoryImage(),
CategoryQuery::create()->findOne(),
'images', 'category'
);
}
public function testDeleteFileFolderDocument() {
$this->doTestDeleteFile(
new FolderDocument(),
FolderQuery::create()->findOne(),
'documents', 'folder'
);
}
public function testDeleteFileFolderImage() {
$this->doTestDeleteFile(
new FolderImage(),
FolderQuery::create()->findOne(),
'images', 'folder'
);
}
public function testDeleteFileContentDocument() {
$this->doTestDeleteFile(
new ContentDocument(),
ContentQuery::create()->findOne(),
'documents', 'content'
);
}
public function testDeleteFileContentImage() {
$this->doTestDeleteFile(
new ContentImage(),
ContentQuery::create()->findOne(),
'images', 'content'
);
}
public function testDeleteFileBrandDocument() {
$this->doTestDeleteFile(
new BrandDocument(),
BrandQuery::create()->findOne(),
'documents', 'brand'
);
}
public function testDeleteFileBrandImage() {
$this->doTestDeleteFile(
new BrandImage(),
BrandQuery::create()->findOne(),
'images', 'brand'
);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 B

View File

@@ -1,901 +0,0 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Tests\Tools;
use Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent;
use Thelia\Core\Event\Image\ImageCreateOrUpdateEvent;
use Thelia\Model\CategoryQuery;
use Thelia\Model\ContentQuery;
use Thelia\Model\FolderQuery;
use Thelia\Model\ProductQuery;
use Thelia\Tools\FileManager;
/**
* Class FileManagerTest
*
* @package Thelia\Tests\Tools
*/
class FileManagerTest extends \PHPUnit_Framework_TestCase
{
/**
* @covers Thelia\Tools\FileManager::copyUploadedFile
*/
/* public function testCopyUploadedFile()
{
$this->markTestIncomplete(
'This test has not been implemented yet : Mock issue'
);
$stubTranslator = $this->getMockBuilder('\Thelia\Core\Translation\Translator')
->disableOriginalConstructor()
->getMock();
$stubTranslator->expects($this->any())
->method('trans')
->will($this->returnValue('translated'));
$stubRequest = $this->getMockBuilder('\Thelia\Core\HttpFoundation\Request')
->disableOriginalConstructor()
->getMock();
$stubSecurity = $this->getMockBuilder('\Thelia\Core\Security\SecurityContext')
->disableOriginalConstructor()
->getMock();
$stubSecurity->expects($this->any())
->method('getAdminUser')
->will($this->returnValue(new Admin()));
// Create a map of arguments to return values.
$map = array(
array('thelia.translator', $stubTranslator),
array('request', $stubRequest),
array('thelia.securityContext', $stubSecurity)
);
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$stubContainer->expects($this->any())
->method('get')
->will($this->returnValueMap($map));
$stubProductImage = $this->getMockBuilder('\Thelia\Model\ProductImage')
->disableOriginalConstructor()
->getMock();
$stubProductImage->expects($this->any())
->method('getUploadDir')
->will($this->returnValue(THELIA_LOCAL_DIR . 'media/images/product'));
$stubProductImage->expects($this->any())
->method('getId')
->will($this->returnValue(42));
$stubProductImage->expects($this->any())
->method('setFile')
->will($this->returnValue(true));
$stubProductImage->expects($this->any())
->method('save')
->will($this->returnValue(0));
$stubUploadedFile = $this->getMockBuilder('\Symfony\Component\HttpFoundation\File\UploadedFile')
->disableOriginalConstructor()
->getMock();
$stubUploadedFile->expects($this->any())
->method('getClientOriginalName')
->will($this->returnValue('goodName'));
$stubUploadedFile->expects($this->any())
->method('getClientOriginalExtension')
->will($this->returnValue('png'));
$stubUploadedFile->expects($this->any())
->method('move')
->will($this->returnValue($stubUploadedFile));
$fileManager = new FileManager($stubContainer);
$newUploadedFiles = array();
$actual = $fileManager->copyUploadedFile(24, FileManager::TYPE_PRODUCT, $stubProductImage, $stubUploadedFile, $newUploadedFiles, FileManager::FILE_TYPE_IMAGES);
$this->assertCount(1, $actual);
}*/
/**
* @covers Thelia\Tools\FileManager::copyUploadedFile
* @expectedException \Thelia\Exception\ImageException
*/
/*public function testCopyUploadedFileExceptionImageException()
{
$this->markTestIncomplete(
'This test has not been implemented yet : Mock issue'
);
$stubTranslator = $this->getMockBuilder('\Thelia\Core\Translation\Translator')
->disableOriginalConstructor()
->getMock();
$stubTranslator->expects($this->any())
->method('trans')
->will($this->returnValue('translated'));
$stubRequest = $this->getMockBuilder('\Thelia\Core\HttpFoundation\Request')
->disableOriginalConstructor()
->getMock();
$stubSecurity = $this->getMockBuilder('\Thelia\Core\Security\SecurityContext')
->disableOriginalConstructor()
->getMock();
$stubSecurity->expects($this->any())
->method('getAdminUser')
->will($this->returnValue(new Admin()));
// Create a map of arguments to return values.
$map = array(
array('thelia.translator', $stubTranslator),
array('request', $stubRequest),
array('thelia.securityContext', $stubSecurity)
);
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$stubContainer->expects($this->any())
->method('get')
->will($this->returnValueMap($map));
$stubProductImage = $this->getMockBuilder('\Thelia\Model\ProductImage')
->disableOriginalConstructor()
->getMock();
$stubProductImage->expects($this->any())
->method('getUploadDir')
->will($this->returnValue(THELIA_LOCAL_DIR . 'media/images/product'));
$stubProductImage->expects($this->any())
->method('getId')
->will($this->returnValue(42));
$stubProductImage->expects($this->any())
->method('setFile')
->will($this->returnValue(true));
$stubProductImage->expects($this->any())
->method('save')
->will($this->returnValue(0));
$stubUploadedFile = $this->getMockBuilder('\Symfony\Component\HttpFoundation\File\UploadedFile')
->disableOriginalConstructor()
->getMock();
$stubUploadedFile->expects($this->any())
->method('getClientOriginalName')
->will($this->returnValue('goodName'));
$stubUploadedFile->expects($this->any())
->method('getClientOriginalExtension')
->will($this->returnValue('png'));
$stubUploadedFile->expects($this->any())
->method('move')
->will($this->returnValue($stubUploadedFile));
$fileManager = new FileManager($stubContainer);
$newUploadedFiles = array();
$actual = $fileManager->copyUploadedFile(24, FileManager::TYPE_PRODUCT, $stubProductImage, $stubUploadedFile, $newUploadedFiles, FileManager::FILE_TYPE_DOCUMENTS);
}*/
/**
* @covers Thelia\Tools\FileManager::saveImage
*/
public function testSaveImageProductImage()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$stubProductImage = $this->getMockBuilder('\Thelia\Model\ProductImage')
->disableOriginalConstructor()
->getMock();
$stubProductImage->expects($this->any())
->method('save')
->will($this->returnValue(10));
$stubProductImage->expects($this->any())
->method('getFile')
->will($this->returnValue('file'));
$fileManager = new FileManager();
$event = new ImageCreateOrUpdateEvent(FileManager::TYPE_PRODUCT, 24);
$expected = 10;
$actual = $fileManager->saveImage($event, $stubProductImage);
$this->assertEquals($expected, $actual);
}
/**
* @covers Thelia\Tools\FileManager::saveDocument
*/
public function testSaveDocumentProductDocument()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$stubProductDocument = $this->getMockBuilder('\Thelia\Model\ProductDocument')
->disableOriginalConstructor()
->getMock();
$stubProductDocument->expects($this->any())
->method('save')
->will($this->returnValue(10));
$stubProductDocument->expects($this->any())
->method('getFile')
->will($this->returnValue('file'));
$fileManager = new FileManager();
$event = new DocumentCreateOrUpdateEvent(FileManager::TYPE_PRODUCT, 24);
$expected = 10;
$actual = $fileManager->saveDocument($event, $stubProductDocument);
$this->assertEquals($expected, $actual);
}
/**
* @covers Thelia\Tools\FileManager::saveImage
*/
public function testSaveImageCategoryImage()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$stubCategoryImage = $this->getMockBuilder('\Thelia\Model\CategoryImage')
->disableOriginalConstructor()
->getMock();
$stubCategoryImage->expects($this->any())
->method('save')
->will($this->returnValue(10));
$stubCategoryImage->expects($this->any())
->method('getFile')
->will($this->returnValue('file'));
$fileManager = new FileManager();
$event = new ImageCreateOrUpdateEvent(FileManager::TYPE_CATEGORY, 24);
$expected = 10;
$actual = $fileManager->saveImage($event, $stubCategoryImage);
$this->assertEquals($expected, $actual);
}
/**
* @covers Thelia\Tools\FileManager::saveDocument
*/
public function testSaveDocumentCategoryDocument()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$stubCategoryDocument = $this->getMockBuilder('\Thelia\Model\CategoryDocument')
->disableOriginalConstructor()
->getMock();
$stubCategoryDocument->expects($this->any())
->method('save')
->will($this->returnValue(10));
$stubCategoryDocument->expects($this->any())
->method('getFile')
->will($this->returnValue('file'));
$fileManager = new FileManager();
$event = new DocumentCreateOrUpdateEvent(FileManager::TYPE_CATEGORY, 24);
$expected = 10;
$actual = $fileManager->saveDocument($event, $stubCategoryDocument);
$this->assertEquals($expected, $actual);
}
/**
* @covers Thelia\Tools\FileManager::saveImage
*/
public function testSaveImageFolderImage()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$stubFolderImage = $this->getMockBuilder('\Thelia\Model\FolderImage')
->disableOriginalConstructor()
->getMock();
$stubFolderImage->expects($this->any())
->method('save')
->will($this->returnValue(10));
$stubFolderImage->expects($this->any())
->method('getFile')
->will($this->returnValue('file'));
$fileManager = new FileManager();
$event = new ImageCreateOrUpdateEvent(FileManager::TYPE_FOLDER, 24);
$expected = 10;
$actual = $fileManager->saveImage($event, $stubFolderImage);
$this->assertEquals($expected, $actual);
}
/**
* @covers Thelia\Tools\FileManager::saveDocument
*/
public function testSaveDocumentFolderDocument()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$stubFolderDocument = $this->getMockBuilder('\Thelia\Model\FolderDocument')
->disableOriginalConstructor()
->getMock();
$stubFolderDocument->expects($this->any())
->method('save')
->will($this->returnValue(10));
$stubFolderDocument->expects($this->any())
->method('getFile')
->will($this->returnValue('file'));
$fileManager = new FileManager();
$event = new DocumentCreateOrUpdateEvent(FileManager::TYPE_FOLDER, 24);
$expected = 10;
$actual = $fileManager->saveDocument($event, $stubFolderDocument);
$this->assertEquals($expected, $actual);
}
/**
* @covers Thelia\Tools\FileManager::saveImage
*/
public function testSaveImageContentImage()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$stubContentImage = $this->getMockBuilder('\Thelia\Model\ContentImage')
->disableOriginalConstructor()
->getMock();
$stubContentImage->expects($this->any())
->method('save')
->will($this->returnValue(10));
$stubContentImage->expects($this->any())
->method('getFile')
->will($this->returnValue('file'));
$fileManager = new FileManager();
$event = new ImageCreateOrUpdateEvent(FileManager::TYPE_CONTENT, 24);
$expected = 10;
$actual = $fileManager->saveImage($event, $stubContentImage);
$this->assertEquals($expected, $actual);
}
/**
* @covers Thelia\Tools\FileManager::saveDocument
*/
public function testSaveDocumentContentDocument()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$stubContentDocument = $this->getMockBuilder('\Thelia\Model\ContentDocument')
->disableOriginalConstructor()
->getMock();
$stubContentDocument->expects($this->any())
->method('save')
->will($this->returnValue(10));
$stubContentDocument->expects($this->any())
->method('getFile')
->will($this->returnValue('file'));
$fileManager = new FileManager();
$event = new DocumentCreateOrUpdateEvent(FileManager::TYPE_CONTENT, 24);
$expected = 10;
$actual = $fileManager->saveDocument($event, $stubContentDocument);
$this->assertEquals($expected, $actual);
}
/**
* @covers Thelia\Tools\FileManager::saveImage
* @expectedException \Thelia\Exception\ImageException
*/
public function testSaveImageExceptionImageException()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$fileManager = new FileManager();
$stubProductImage = $this->getMockBuilder('\Thelia\Model\ProductImage')
->disableOriginalConstructor()
->getMock();
$stubProductImage->expects($this->any())
->method('save')
->will($this->returnValue(10));
$stubProductImage->expects($this->any())
->method('getFile')
->will($this->returnValue('file'));
$event = new ImageCreateOrUpdateEvent('bad', 24);
$fileManager->saveImage($event, $stubProductImage);
}
/**
* @covers Thelia\Tools\FileManager::saveDocument
* @expectedException \Thelia\Model\Exception\InvalidArgumentException
*/
public function testSaveDocumentExceptionDocumentException()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$fileManager = new FileManager();
$stubProductDocument = $this->getMockBuilder('\Thelia\Model\ProductDocument')
->disableOriginalConstructor()
->getMock();
$stubProductDocument->expects($this->any())
->method('save')
->will($this->returnValue(10));
$stubProductDocument->expects($this->any())
->method('getFile')
->will($this->returnValue('file'));
$event = new DocumentCreateOrUpdateEvent('bad', 24);
$fileManager->saveDocument($event, $stubProductDocument);
}
/**
* @covers Thelia\Tools\FileManager::saveImage
* @expectedException \Thelia\Exception\ImageException
*/
public function testSaveImageExceptionImageException2()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$fileManager = new FileManager();
$stubProductImage = $this->getMockBuilder('\Thelia\Model\ProductImage')
->disableOriginalConstructor()
->getMock();
$stubProductImage->expects($this->any())
->method('save')
->will($this->returnValue(0));
$stubProductImage->expects($this->any())
->method('getFile')
->will($this->returnValue('file'));
$event = new ImageCreateOrUpdateEvent(FileManager::TYPE_PRODUCT, 24);
$fileManager->saveImage($event, $stubProductImage);
}
/**
* @covers Thelia\Tools\FileManager::saveDocument
* @expectedException \Thelia\Model\Exception\InvalidArgumentException
*/
public function testSaveDocumentExceptionDocumentException2()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$fileManager = new FileManager();
$stubProductDocument = $this->getMockBuilder('\Thelia\Model\ProductDocument')
->disableOriginalConstructor()
->getMock();
$stubProductDocument->expects($this->any())
->method('save')
->will($this->returnValue(0));
$stubProductDocument->expects($this->any())
->method('getFile')
->will($this->returnValue('file'));
$event = new DocumentCreateOrUpdateEvent(FileManager::TYPE_PRODUCT, 24);
$fileManager->saveDocument($event, $stubProductDocument);
}
/**
* @covers Thelia\Tools\FileManager::sanitizeFileName
*/
public function testSanitizeFileName()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$fileManager = new FileManager();
$badFileName = 'a/ze\érà~çè§^"$*+-_°)(&é<>@#ty2/[\/:*?"<>|]/fi?.fUPPERile.exel../e*';
$expected = 'azer-_ty2fi.fupperile.exel..e';
$actual = $fileManager->sanitizeFileName($badFileName);
$this->assertEquals($expected, $actual);
}
/**
* @covers Thelia\Tools\FileManager::getImageModel
*/
public function testGetImageModel()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$fileManager = new FileManager();
$actual = $fileManager->getImageModel(FileManager::TYPE_PRODUCT);
$this->assertInstanceOf('\Thelia\Model\ProductImage', $actual);
$actual = $fileManager->getImageModel(FileManager::TYPE_CATEGORY);
$this->assertInstanceOf('\Thelia\Model\CategoryImage', $actual);
$actual = $fileManager->getImageModel(FileManager::TYPE_CONTENT);
$this->assertInstanceOf('\Thelia\Model\ContentImage', $actual);
$actual = $fileManager->getImageModel(FileManager::TYPE_FOLDER);
$this->assertInstanceOf('\Thelia\Model\FolderImage', $actual);
$actual = $fileManager->getImageModel('bad');
$this->assertNull($actual);
}
/**
* @covers Thelia\Tools\FileManager::getDocumentModel
*/
public function testGetDocumentModel()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$fileManager = new FileManager();
$actual = $fileManager->getDocumentModel(FileManager::TYPE_PRODUCT);
$this->assertInstanceOf('\Thelia\Model\ProductDocument', $actual);
$actual = $fileManager->getDocumentModel(FileManager::TYPE_CATEGORY);
$this->assertInstanceOf('\Thelia\Model\CategoryDocument', $actual);
$actual = $fileManager->getDocumentModel(FileManager::TYPE_CONTENT);
$this->assertInstanceOf('\Thelia\Model\ContentDocument', $actual);
$actual = $fileManager->getDocumentModel(FileManager::TYPE_FOLDER);
$this->assertInstanceOf('\Thelia\Model\FolderDocument', $actual);
$actual = $fileManager->getDocumentModel('bad');
$this->assertNull($actual);
}
/**
* @covers Thelia\Tools\FileManager::getImageModelQuery
*/
public function testGetImageModelQuery()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$fileManager = new FileManager();
$actual = $fileManager->getImageModelQuery(FileManager::TYPE_PRODUCT);
$this->assertInstanceOf('\Thelia\Model\ProductImageQuery', $actual);
$actual = $fileManager->getImageModelQuery(FileManager::TYPE_CATEGORY);
$this->assertInstanceOf('\Thelia\Model\CategoryImageQuery', $actual);
$actual = $fileManager->getImageModelQuery(FileManager::TYPE_CONTENT);
$this->assertInstanceOf('\Thelia\Model\ContentImageQuery', $actual);
$actual = $fileManager->getImageModelQuery(FileManager::TYPE_FOLDER);
$this->assertInstanceOf('\Thelia\Model\FolderImageQuery', $actual);
$actual = $fileManager->getImageModelQuery('bad');
$this->assertNull($actual);
}
/**
* @covers Thelia\Tools\FileManager::getDocumentModelQuery
*/
public function testGetDocumentModelQuery()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$fileManager = new FileManager();
$actual = $fileManager->getDocumentModelQuery(FileManager::TYPE_PRODUCT);
$this->assertInstanceOf('\Thelia\Model\ProductDocumentQuery', $actual);
$actual = $fileManager->getDocumentModelQuery(FileManager::TYPE_CATEGORY);
$this->assertInstanceOf('\Thelia\Model\CategoryDocumentQuery', $actual);
$actual = $fileManager->getDocumentModelQuery(FileManager::TYPE_CONTENT);
$this->assertInstanceOf('\Thelia\Model\ContentDocumentQuery', $actual);
$actual = $fileManager->getDocumentModelQuery(FileManager::TYPE_FOLDER);
$this->assertInstanceOf('\Thelia\Model\FolderDocumentQuery', $actual);
$actual = $fileManager->getDocumentModelQuery('bad');
$this->assertNull($actual);
}
/**
* @covers Thelia\Tools\FileManager::getParentFileModel
*/
public function testGetParentFileModel()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$fileManager = new FileManager();
$actual = $fileManager->getParentFileModel(FileManager::TYPE_PRODUCT, ProductQuery::create()->findOne()->getId());
$this->assertInstanceOf('\Thelia\Model\Product', $actual);
$actual = $fileManager->getParentFileModel(FileManager::TYPE_CATEGORY, CategoryQuery::create()->findOne()->getId());
$this->assertInstanceOf('\Thelia\Model\Category', $actual);
$actual = $fileManager->getParentFileModel(FileManager::TYPE_CONTENT, ContentQuery::create()->findOne()->getId());
$this->assertInstanceOf('\Thelia\Model\Content', $actual);
$actual = $fileManager->getParentFileModel(FileManager::TYPE_FOLDER, FolderQuery::create()->findOne()->getId());
$this->assertInstanceOf('\Thelia\Model\Folder', $actual, 1);
$actual = $fileManager->getParentFileModel('bad', 1);
$this->assertNull($actual);
}
/**
* @covers Thelia\Tools\FileManager::getImageForm
*/
/* public function testGetImageForm()
{
// Mock issue
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}*/
/**
* @covers Thelia\Tools\FileManager::getDocumentForm
*/
/* public function testGetDocumentForm()
{
// Mock issue
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}*/
/**
* @covers Thelia\Tools\FileManager::getUploadDir
*/
public function testGetUploadDir()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$fileManager = new FileManager();
$actual = $fileManager->getUploadDir(FileManager::TYPE_PRODUCT, FileManager::FILE_TYPE_IMAGES);
$this->assertEquals(THELIA_LOCAL_DIR . 'media/images/product', $actual);
$actual = $fileManager->getUploadDir(FileManager::TYPE_CATEGORY, FileManager::FILE_TYPE_IMAGES);
$this->assertEquals(THELIA_LOCAL_DIR . 'media/images/category', $actual);
$actual = $fileManager->getUploadDir(FileManager::TYPE_CONTENT, FileManager::FILE_TYPE_IMAGES);
$this->assertEquals(THELIA_LOCAL_DIR . 'media/images/content', $actual);
$actual = $fileManager->getUploadDir(FileManager::TYPE_FOLDER, FileManager::FILE_TYPE_IMAGES);
$this->assertEquals(THELIA_LOCAL_DIR . 'media/images/folder', $actual);
$actual = $fileManager->getUploadDir('bad', FileManager::FILE_TYPE_IMAGES);
$this->assertEquals(false, $actual);
$actual = $fileManager->getUploadDir(FileManager::TYPE_PRODUCT, FileManager::FILE_TYPE_DOCUMENTS);
$this->assertEquals(THELIA_LOCAL_DIR . 'media/documents/product', $actual);
$actual = $fileManager->getUploadDir(FileManager::TYPE_CATEGORY, FileManager::FILE_TYPE_DOCUMENTS);
$this->assertEquals(THELIA_LOCAL_DIR . 'media/documents/category', $actual);
$actual = $fileManager->getUploadDir(FileManager::TYPE_CONTENT, FileManager::FILE_TYPE_DOCUMENTS);
$this->assertEquals(THELIA_LOCAL_DIR . 'media/documents/content', $actual);
$actual = $fileManager->getUploadDir(FileManager::TYPE_FOLDER, FileManager::FILE_TYPE_DOCUMENTS);
$this->assertEquals(THELIA_LOCAL_DIR . 'media/documents/folder', $actual);
$actual = $fileManager->getUploadDir('bad', FileManager::FILE_TYPE_DOCUMENTS);
$this->assertEquals(false, $actual);
$actual = $fileManager->getUploadDir(FileManager::TYPE_FOLDER, 'bad');
$this->assertEquals(false, $actual);
}
/**
* @covers Thelia\Tools\FileManager::getRedirectionUrl
*/
public function testGetRedirectionUrl()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$fileManager = new FileManager();
$actual = $fileManager->getRedirectionUrl(FileManager::TYPE_PRODUCT, 1, FileManager::FILE_TYPE_IMAGES);
$this->assertEquals('/admin/products/update?product_id=1&current_tab=images', $actual);
$actual = $fileManager->getRedirectionUrl(FileManager::TYPE_CATEGORY, 1, FileManager::FILE_TYPE_IMAGES);
$this->assertEquals('/admin/categories/update?category_id=1&current_tab=images', $actual);
$actual = $fileManager->getRedirectionUrl(FileManager::TYPE_CONTENT, 1, FileManager::FILE_TYPE_IMAGES);
$this->assertEquals('/admin/content/update/1?current_tab=images', $actual);
$actual = $fileManager->getRedirectionUrl(FileManager::TYPE_FOLDER, 1, FileManager::FILE_TYPE_IMAGES);
$this->assertEquals('/admin/folders/update/1?current_tab=images', $actual);
$actual = $fileManager->getRedirectionUrl('bad', 1, FileManager::FILE_TYPE_IMAGES);
$this->assertEquals(false, $actual);
$actual = $fileManager->getRedirectionUrl(FileManager::TYPE_PRODUCT, 1, FileManager::FILE_TYPE_DOCUMENTS);
$this->assertEquals('/admin/products/update?product_id=1&current_tab=documents', $actual);
$actual = $fileManager->getRedirectionUrl(FileManager::TYPE_CATEGORY, 1, FileManager::FILE_TYPE_DOCUMENTS);
$this->assertEquals('/admin/categories/update?category_id=1&current_tab=documents', $actual);
$actual = $fileManager->getRedirectionUrl(FileManager::TYPE_CONTENT, 1, FileManager::FILE_TYPE_DOCUMENTS);
$this->assertEquals('/admin/content/update/1?current_tab=documents', $actual);
$actual = $fileManager->getRedirectionUrl(FileManager::TYPE_FOLDER, 1, FileManager::FILE_TYPE_DOCUMENTS);
$this->assertEquals('/admin/folders/update/1?current_tab=documents', $actual);
$actual = $fileManager->getRedirectionUrl('bad', 1, FileManager::FILE_TYPE_DOCUMENTS);
$this->assertEquals(false, $actual);
$actual = $fileManager->getRedirectionUrl(FileManager::TYPE_FOLDER, 1, 'bad');
$this->assertEquals(false, $actual);
}
/**
* @covers Thelia\Tools\FileManager::getFormId
*/
public function testGetFormId()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$fileManager = new FileManager();
$actual = $fileManager->getFormId(FileManager::TYPE_PRODUCT, FileManager::FILE_TYPE_IMAGES);
$this->assertEquals('thelia.admin.product.image.modification', $actual);
$actual = $fileManager->getFormId(FileManager::TYPE_CATEGORY, FileManager::FILE_TYPE_IMAGES);
$this->assertEquals('thelia.admin.category.image.modification', $actual);
$actual = $fileManager->getFormId(FileManager::TYPE_CONTENT, FileManager::FILE_TYPE_IMAGES);
$this->assertEquals('thelia.admin.content.image.modification', $actual);
$actual = $fileManager->getFormId(FileManager::TYPE_FOLDER, FileManager::FILE_TYPE_IMAGES);
$this->assertEquals('thelia.admin.folder.image.modification', $actual);
$actual = $fileManager->getFormId('bad', FileManager::FILE_TYPE_IMAGES);
$this->assertEquals(false, $actual);
$actual = $fileManager->getFormId(FileManager::TYPE_PRODUCT, FileManager::FILE_TYPE_DOCUMENTS);
$this->assertEquals('thelia.admin.product.document.modification', $actual);
$actual = $fileManager->getFormId(FileManager::TYPE_CATEGORY, FileManager::FILE_TYPE_DOCUMENTS);
$this->assertEquals('thelia.admin.category.document.modification', $actual);
$actual = $fileManager->getFormId(FileManager::TYPE_CONTENT, FileManager::FILE_TYPE_DOCUMENTS);
$this->assertEquals('thelia.admin.content.document.modification', $actual);
$actual = $fileManager->getFormId(FileManager::TYPE_FOLDER, FileManager::FILE_TYPE_DOCUMENTS);
$this->assertEquals('thelia.admin.folder.document.modification', $actual);
$actual = $fileManager->getFormId('bad', FileManager::FILE_TYPE_DOCUMENTS);
$this->assertEquals(false, $actual);
}
/**
* @covers Thelia\Tools\FileManager::renameFile
*/
public function testRenameFile()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$stubUploadedFile = $this->getMockBuilder('\Symfony\Component\HttpFoundation\File\UploadedFile')
->setConstructorArgs([__DIR__ . '/fixtures/test.xml', 'test.xml'])
->getMock();
$stubUploadedFile->expects($this->any())
->method('getClientOriginalExtension')
->will($this->returnValue('yml'));
$stubUploadedFile->expects($this->any())
->method('getClientOriginalName')
->will($this->returnValue('or1-g_n?al*/&é"filen@me#'));
$fileManager = new FileManager();
$expected = 'or1-g_nalfilenme-1.yml';
$actual = $fileManager->renameFile(1, $stubUploadedFile);
$this->assertEquals($expected, $actual);
}
/**
* @covers Thelia\Tools\FileManager::renameFile
*/
public function testRenameFileWithoutExtension()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$stubUploadedFile = $this->getMockBuilder('\Symfony\Component\HttpFoundation\File\UploadedFile')
->setConstructorArgs([__DIR__ . '/fixtures/test.xml', 'test.xml'])
->getMock();
$stubUploadedFile->expects($this->any())
->method('getClientOriginalExtension')
->will($this->returnValue(''));
$stubUploadedFile->expects($this->any())
->method('getClientOriginalName')
->will($this->returnValue('or1-g_n?al*/&é"filen@me#'));
$fileManager = new FileManager();
$expected = 'or1-g_nalfilenme-1';
$actual = $fileManager->renameFile(1, $stubUploadedFile);
$this->assertEquals($expected, $actual);
}
/**
* @covers Thelia\Tools\FileManager::isImage
*/
public function testIsImage()
{
$stubContainer = $this->getMockBuilder('\Symfony\Component\DependencyInjection\ContainerInterface')
->disableOriginalConstructor()
->getMock();
$fileManager = new FileManager();
$actual = $fileManager->isImage('image/jpeg');
$this->assertTrue($actual);
$actual = $fileManager->isImage('image/png');
$this->assertTrue($actual);
$actual = $fileManager->isImage('image/gif');
$this->assertTrue($actual);
$actual = $fileManager->isImage('bad');
$this->assertFalse($actual);
$actual = $fileManager->isImage('image/jpg');
$this->assertFalse($actual);
$actual = $fileManager->isImage('application/x-msdownload');
$this->assertFalse($actual);
$actual = $fileManager->isImage('application/x-sh');
$this->assertFalse($actual);
}
/**
* @covers Thelia\Tools\FileManager::getAvailableTypes
*/
public function testGetAvailableTypes()
{
$expected = array(
FileManager::TYPE_CATEGORY,
FileManager::TYPE_CONTENT,
FileManager::TYPE_FOLDER,
FileManager::TYPE_PRODUCT,
FileManager::TYPE_MODULE,
);
$actual = FileManager::getAvailableTypes();
$this->assertEquals($expected, $actual);
}
/**
* @covers Thelia\Tools\FileManager::adminLogAppend
*/
/* public function testAdminLogAppend()
{
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}*/
/**
* @covers Thelia\Tools\FileManager::deleteFile
*/
/* public function testDeleteFile()
{
// @todo see http://tech.vg.no/2011/03/09/mocking-the-file-system-using-phpunit-and-vfsstream/
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}*/
}

View File

@@ -1,667 +0,0 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Tools;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent;
use Thelia\Core\Event\Image\ImageCreateOrUpdateEvent;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Exception\ImageException;
use Thelia\Form\CategoryDocumentModification;
use Thelia\Form\CategoryImageModification;
use Thelia\Form\ContentDocumentModification;
use Thelia\Form\ContentImageModification;
use Thelia\Form\FolderDocumentModification;
use Thelia\Form\FolderImageModification;
use Thelia\Form\ProductDocumentModification;
use Thelia\Form\ProductImageModification;
use Thelia\Model\CategoryDocument;
use Thelia\Model\CategoryDocumentQuery;
use Thelia\Model\CategoryImage;
use Thelia\Model\CategoryImageQuery;
use Thelia\Model\CategoryQuery;
use Thelia\Model\ContentDocument;
use Thelia\Model\ContentDocumentQuery;
use Thelia\Model\ContentImage;
use Thelia\Model\ContentImageQuery;
use Thelia\Model\ContentQuery;
use Thelia\Model\Exception\InvalidArgumentException;
use Thelia\Model\FolderDocument;
use Thelia\Model\FolderDocumentQuery;
use Thelia\Model\FolderImage;
use Thelia\Model\FolderImageQuery;
use Thelia\Model\FolderQuery;
use Thelia\Model\ProductDocument;
use Thelia\Model\ProductDocumentQuery;
use Thelia\Model\ProductImage;
use Thelia\Model\ProductImageQuery;
use Thelia\Model\ProductQuery;
/**
* Created by JetBrains PhpStorm.
* Date: 9/19/13
* Time: 3:24 PM
*
* File Manager
*
* @package File
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class FileManager
{
CONST TYPE_PRODUCT = 'product';
CONST TYPE_CATEGORY = 'category';
CONST TYPE_CONTENT = 'content';
CONST TYPE_FOLDER = 'folder';
CONST TYPE_MODULE = 'module';
CONST FILE_TYPE_IMAGES = 'images';
CONST FILE_TYPE_DOCUMENTS = 'documents';
/**
* Copy UploadedFile into the server storage directory
*
* @param int $parentId Parent id
* @param string $parentType Image type
* @param FolderImage|ContentImage|CategoryImage|ProductImage|FolderDocument|ContentDocument|CategoryDocument|ProductDocument $model Model saved
* @param UploadedFile $uploadedFile Ready to be uploaded file
* @param string $fileType File type ex FileManager::FILE_TYPE_IMAGES
*
* @throws \Thelia\Exception\ImageException
* @return UploadedFile
*/
public function copyUploadedFile($parentId, $parentType, $model, $uploadedFile, $fileType)
{
$newUploadedFile = null;
if ($uploadedFile !== null) {
$directory = $this->getUploadDir($parentType, $fileType);
$fileName = $this->renameFile($model->getId(), $uploadedFile);
$newUploadedFile = $uploadedFile->move($directory, $fileName);
$model->setFile($fileName);
if (!$model->save()) {
throw new ImageException(
sprintf(
'%s %s (%s) failed to be saved (image file)',
ucfirst($parentType),
$model->getFile(),
$fileType
)
);
}
}
return $newUploadedFile;
}
/**
* Save image into the database
*
* @param ImageCreateOrUpdateEvent $event Image event
* @param FolderImage|ContentImage|CategoryImage|ProductImage $modelImage Image to save
*
* @return int Nb lines modified
* @throws \Thelia\Exception\ImageException
* @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action
*/
public function saveImage(ImageCreateOrUpdateEvent $event, $modelImage)
{
$nbModifiedLines = 0;
if ($modelImage->getFile() !== null) {
switch ($event->getImageType()) {
case self::TYPE_PRODUCT:
/** @var ProductImage $modelImage */
$modelImage->setProductId($event->getParentId());
break;
case self::TYPE_CATEGORY:
/** @var CategoryImage $modelImage */
$modelImage->setCategoryId($event->getParentId());
break;
case self::TYPE_CONTENT:
/** @var ContentImage $modelImage */
$modelImage->setContentId($event->getParentId());
break;
case self::TYPE_FOLDER:
/** @var FolderImage $modelImage */
$modelImage->setFolderId($event->getParentId());
break;
default:
throw new ImageException(
sprintf(
'Picture parent type is unknown (available types : %s)',
implode(
',',
self::getAvailableTypes()
)
)
);
}
$nbModifiedLines = $modelImage->save();
if (!$nbModifiedLines) {
throw new ImageException(
sprintf(
'Image %s failed to be saved (image content)',
$modelImage->getFile()
)
);
}
}
return $nbModifiedLines;
}
/**
* Save document into the database
*
* @param DocumentCreateOrUpdateEvent $event Image event
* @param FolderDocument|ContentDocument|CategoryDocument|ProductDocument $modelDocument Document to save
*
* @throws \Thelia\Model\Exception\InvalidArgumentException
* @return int Nb lines modified
* @todo refactor make all documents using propel inheritance and factorise image behaviour into one single clean action
*/
public function saveDocument(DocumentCreateOrUpdateEvent $event, $modelDocument)
{
$nbModifiedLines = 0;
if ($modelDocument->getFile() !== null) {
switch ($event->getDocumentType()) {
case self::TYPE_PRODUCT:
/** @var ProductImage $modelImage */
$modelDocument->setProductId($event->getParentId());
break;
case self::TYPE_CATEGORY:
/** @var CategoryImage $modelImage */
$modelDocument->setCategoryId($event->getParentId());
break;
case self::TYPE_CONTENT:
/** @var ContentImage $modelImage */
$modelDocument->setContentId($event->getParentId());
break;
case self::TYPE_FOLDER:
/** @var FolderImage $modelImage */
$modelDocument->setFolderId($event->getParentId());
break;
default:
throw new InvalidArgumentException(
sprintf(
'Document parent type is unknown (available types : %s)',
implode(
',',
self::getAvailableTypes()
)
)
);
}
$nbModifiedLines = $modelDocument->save();
if (!$nbModifiedLines) {
throw new InvalidArgumentException(
sprintf(
'Document %s failed to be saved (document content)',
$modelDocument->getFile()
)
);
}
}
return $nbModifiedLines;
}
/**
* Sanitizes a filename replacing whitespace with dashes
*
* Removes special characters that are illegal in filenames on certain
* operating systems and special characters requiring special escaping
* to manipulate at the command line.
*
* @param string $string The filename to be sanitized
*
* @return string The sanitized filename
*/
public function sanitizeFileName($string)
{
return strtolower(preg_replace('/[^a-zA-Z0-9-_\.]/', '', $string));
}
/**
* Delete image from file storage and database
*
* @param CategoryImage|ProductImage|ContentImage|FolderImage|CategoryDocument|ProductDocument|ContentDocument|FolderDocument $model File being deleted
* @param string $parentType Parent type ex : self::TYPE_PRODUCT
* @param string $fileType File type ex FileManager::FILE_TYPE_DOCUMENTS
*
* @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action
*/
public function deleteFile($model, $parentType, $fileType)
{
$url = $this->getUploadDir($parentType, $fileType) . '/' . $model->getFile();
unlink(str_replace('..', '', $url));
$model->delete();
}
/**
* Get image model from type
*
* @param string $parentType Parent type ex : self::TYPE_PRODUCT
*
* @return null|\Thelia\Model\CategoryImage|\Thelia\Model\ContentImage|\Thelia\Model\FolderImage|\Thelia\Model\ProductImage
*
* @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action
*/
public function getImageModel($parentType)
{
switch ($parentType) {
case self::TYPE_PRODUCT:
$model = new ProductImage();
break;
case self::TYPE_CATEGORY:
$model = new CategoryImage();
break;
case self::TYPE_CONTENT:
$model = new ContentImage();
break;
case self::TYPE_FOLDER:
$model = new FolderImage();
break;
default:
$model = null;
}
return $model;
}
/**
* Get document model from type
*
* @param string $parentType Parent type ex : self::TYPE_PRODUCT
*
* @return null|ProductDocument|CategoryDocument|ContentDocument|FolderDocument
*
* @todo refactor make all documents using propel inheritance and factorise image behaviour into one single clean action
*/
public function getDocumentModel($parentType)
{
switch ($parentType) {
case self::TYPE_PRODUCT:
$model = new ProductDocument();
break;
case self::TYPE_CATEGORY:
$model = new CategoryDocument();
break;
case self::TYPE_CONTENT:
$model = new ContentDocument();
break;
case self::TYPE_FOLDER:
$model = new FolderDocument();
break;
default:
$model = null;
}
return $model;
}
/**
* Get image model query from type
*
* @param string $parentType Parent type ex : self::TYPE_PRODUCT
*
* @return null|\Thelia\Model\CategoryImageQuery|\Thelia\Model\ContentImageQuery|\Thelia\Model\FolderImageQuery|\Thelia\Model\ProductImageQuery
*
* @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action
*/
public function getImageModelQuery($parentType)
{
switch ($parentType) {
case self::TYPE_PRODUCT:
$model = new ProductImageQuery();
break;
case self::TYPE_CATEGORY:
$model = new CategoryImageQuery();
break;
case self::TYPE_CONTENT:
$model = new ContentImageQuery();
break;
case self::TYPE_FOLDER:
$model = new FolderImageQuery();
break;
default:
$model = null;
}
return $model;
}
/**
* Get document model query from type
*
* @param string $parentType Parent type ex : self::TYPE_PRODUCT
*
* @return null|ProductDocumentQuery|CategoryDocumentQuery|ContentDocumentQuery|FolderDocumentQuery
*
* @todo refactor make all documents using propel inheritance and factorise image behaviour into one single clean action
*/
public function getDocumentModelQuery($parentType)
{
switch ($parentType) {
case self::TYPE_PRODUCT:
$model = new ProductDocumentQuery();
break;
case self::TYPE_CATEGORY:
$model = new CategoryDocumentQuery();
break;
case self::TYPE_CONTENT:
$model = new ContentDocumentQuery();
break;
case self::TYPE_FOLDER:
$model = new FolderDocumentQuery();
break;
default:
$model = null;
}
return $model;
}
/**
* Get form service id from type
*
* @param string $parentType Parent type ex : self::TYPE_PRODUCT
* @param string $fileType Parent id
*
* @return string
*
* @todo refactor make all documents using propel inheritance and factorise image behaviour into one single clean action
*/
public function getFormId($parentType, $fileType)
{
switch ($fileType) {
case self::FILE_TYPE_IMAGES:
$type = 'image';
break;
case self::FILE_TYPE_DOCUMENTS:
$type = 'document';
break;
default:
return false;
}
switch ($parentType) {
case self::TYPE_PRODUCT:
$formId = 'thelia.admin.product.' . $type . '.modification';
break;
case self::TYPE_CATEGORY:
$formId = 'thelia.admin.category.' . $type . '.modification';
break;
case self::TYPE_CONTENT:
$formId = 'thelia.admin.content.' . $type . '.modification';
break;
case self::TYPE_FOLDER:
$formId = 'thelia.admin.folder.' . $type . '.modification';
break;
default:
$formId = false;
}
return $formId;
}
/**
* Get image parent model from type
*
* @param string $parentType Parent type ex : self::TYPE_PRODUCT
* @param int $parentId Parent Id
*
* @return null|\Thelia\Model\Category|\Thelia\Model\Content|\Thelia\Model\Folder|\Thelia\Model\Product
*
* @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action
*/
public function getParentFileModel($parentType, $parentId)
{
switch ($parentType) {
case self::TYPE_PRODUCT:
$model = ProductQuery::create()->findPk($parentId);
break;
case self::TYPE_CATEGORY:
$model = CategoryQuery::create()->findPk($parentId);
break;
case self::TYPE_CONTENT:
$model = ContentQuery::create()->findPk($parentId);
break;
case self::TYPE_FOLDER:
$model = FolderQuery::create()->findPk($parentId);
break;
default:
$model = null;
}
return $model;
}
/**
* Get image parent model from type
*
* @param string $parentType Parent type ex : self::TYPE_PRODUCT
* @param Request $request Request service
*
* @todo refactor make all pictures using propel inheritance and factorise image behaviour into one single clean action
* @return ProductImageModification|CategoryImageModification|ContentImageModification|FolderImageModification
*/
public function getImageForm($parentType, Request $request)
{
switch ($parentType) {
case self::TYPE_PRODUCT:
$form = new ProductImageModification($request);
break;
case self::TYPE_CATEGORY:
$form = new CategoryImageModification($request);
break;
case self::TYPE_CONTENT:
$form = new ContentImageModification($request);
break;
case self::TYPE_FOLDER:
$form = new FolderImageModification($request);
break;
default:
$form = null;
}
return $form;
}
/**
* Get document parent model from type
*
* @param string $parentType Parent type ex : self::TYPE_PRODUCT
* @param Request $request Request service
*
* @todo refactor make all document using propel inheritance and factorise image behaviour into one single clean action
* @return ProductDocumentModification|CategoryDocumentModification|ContentDocumentModification|FolderDocumentModification
*/
public function getDocumentForm($parentType, Request $request)
{
switch ($parentType) {
case self::TYPE_PRODUCT:
$form = new ProductDocumentModification($request);
break;
case self::TYPE_CATEGORY:
$form = new CategoryDocumentModification($request);
break;
case self::TYPE_CONTENT:
$form = new ContentDocumentModification($request);
break;
case self::TYPE_FOLDER:
$form = new FolderDocumentModification($request);
break;
default:
$form = null;
}
return $form;
}
/**
* Get image upload dir
*
* @param string $parentType Parent type ex FileManager::TYPE_PRODUCT
* @param string $fileType File type ex : self::FILE_TYPE_DOCUMENTS
*
* @return string Uri
*/
public function getUploadDir($parentType, $fileType)
{
if (!in_array($fileType, self::$availableFileType)) {
return false;
}
switch ($parentType) {
case self::TYPE_PRODUCT:
$uri = THELIA_LOCAL_DIR . 'media/' . $fileType . '/' . self::TYPE_PRODUCT;
break;
case self::TYPE_CATEGORY:
$uri = THELIA_LOCAL_DIR . 'media/' . $fileType . '/' . self::TYPE_CATEGORY;
break;
case self::TYPE_CONTENT:
$uri = THELIA_LOCAL_DIR . 'media/' . $fileType . '/' . self::TYPE_CONTENT;
break;
case self::TYPE_FOLDER:
$uri = THELIA_LOCAL_DIR . 'media/' . $fileType . '/' . self::TYPE_FOLDER;
break;
default:
$uri = false;
}
return $uri;
}
/**
* Deduce image redirecting URL from parent type
*
* @param string $parentType Parent type ex : self::TYPE_PRODUCT
* @param int $parentId Parent id
* @param string $fileType File type ex : self::FILE_TYPE_DOCUMENTS
*
* @return string
*/
public function getRedirectionUrl($parentType, $parentId, $fileType)
{
if (!in_array($fileType, self::$availableFileType)) {
return false;
}
switch ($parentType) {
case self::TYPE_PRODUCT:
$uri = '/admin/products/update?product_id=' . $parentId . '&current_tab=' . $fileType;
break;
case self::TYPE_CATEGORY:
$uri = '/admin/categories/update?category_id=' . $parentId . '&current_tab=' . $fileType;
break;
case self::TYPE_CONTENT:
$uri = '/admin/content/update/' . $parentId . '?current_tab=' . $fileType;
break;
case self::TYPE_FOLDER:
$uri = '/admin/folders/update/' . $parentId . '?current_tab=' . $fileType;
break;
default:
$uri = false;
}
return $uri;
}
/** @var array Available file parent type */
public static $availableType = array(
self::TYPE_PRODUCT,
self::TYPE_CATEGORY,
self::TYPE_CONTENT,
self::TYPE_FOLDER,
self::TYPE_MODULE
);
/** @var array Available file type type */
public static $availableFileType = array(
self::FILE_TYPE_DOCUMENTS,
self::FILE_TYPE_IMAGES
);
/**
* Rename file with image model id
*
* @param int $modelId Model id
* @param UploadedFile $uploadedFile File being saved
*
* @return string
*/
public function renameFile($modelId, $uploadedFile)
{
$extension = $uploadedFile->getClientOriginalExtension();
if (!empty($extension)) {
$extension = '.' . strtolower($extension);
}
$fileName = $this->sanitizeFileName(
str_replace(
$extension,
'',
$uploadedFile->getClientOriginalName()
) . '-' . $modelId . $extension
);
return $fileName;
}
/**
* Check if a file is an image
* Check based on mime type
*
* @param string $mimeType File mime type
*
* @return bool
*/
public function isImage($mimeType)
{
$isValid = false;
$allowedType = array('image/jpeg' , 'image/png' ,'image/gif');
if (in_array($mimeType, $allowedType)) {
$isValid = true;
}
return $isValid;
}
/**
* Return all document and image types
*
* @return array
*/
public static function getAvailableTypes()
{
return array(
self::TYPE_CATEGORY,
self::TYPE_CONTENT,
self::TYPE_FOLDER,
self::TYPE_PRODUCT,
self::TYPE_MODULE,
);
}
}