Restoired file events compatibility, factorised code

This commit is contained in:
Franck Allimant
2014-06-26 20:18:06 +02:00
parent fcceaa630d
commit d969f84ae0
11 changed files with 846 additions and 865 deletions

View File

@@ -12,6 +12,10 @@
namespace Thelia\Action; namespace Thelia\Action;
use Thelia\Core\Event\CachedFileEvent; use Thelia\Core\Event\CachedFileEvent;
use Thelia\Core\Event\File\FileCreateOrUpdateEvent;
use Thelia\Core\Event\Image\FileDeleteEvent;
use Thelia\Core\Event\UpdateFilePositionEvent;
use Thelia\Exception\FileException;
use Thelia\Files\FileManager; use Thelia\Files\FileManager;
use Thelia\Tools\URL; use Thelia\Tools\URL;
@@ -176,4 +180,77 @@ abstract class BaseCachedFile extends BaseAction
return $path; return $path;
} }
/**
* Take care of saving a file in the database and file storage
*
* @param FileCreateOrUpdateEvent $event Image event
*
* @throws \Thelia\Exception\FileException
*
*/
public function saveFile(FileCreateOrUpdateEvent $event)
{
$model = $event->getModel();
$nbModifiedLines = $model->save();
$event->setModel($model);
if (!$nbModifiedLines) {
throw new FileException(
sprintf(
'File "%s" (type %s) with parent id %s failed to be saved',
$event->getParentName(),
get_class($model),
$event->getParentId()
)
);
}
$newUploadedFile = $this->fileManager->copyUploadedFile($event->getModel(), $event->getUploadedFile());
$event->setUploadedFile($newUploadedFile);
}
/**
* Take care of updating file in the database and file storage
*
* @param FileCreateOrUpdateEvent $event Image event
*
* @throws \Thelia\Exception\FileException
*/
public function updateFile(FileCreateOrUpdateEvent $event)
{
// Copy and save file
if ($event->getUploadedFile()) {
// Remove old picture file from file storage
$url = $event->getModel()->getUploadDir() . '/' . $event->getOldModel()->getFile();
unlink(str_replace('..', '', $url));
$newUploadedFile = $this->fileManager->copyUploadedFile($event->getModel(), $event->getUploadedFile());
$event->setUploadedFile($newUploadedFile);
}
// Update image modifications
$event->getModel()->save();
$event->setModel($event->getModel());
}
/**
* Deleting file in the database and in storage
*
* @param FileDeleteEvent $event Image event
*/
public function deleteImage(FileDeleteEvent $event)
{
$this->fileManager->deleteFile($event->getFileToDelete());
}
public function updatePosition(UpdateFilePositionEvent $event)
{
$this->genericUpdatePosition($event->getQuery(), $event);
}
} }

View File

@@ -105,93 +105,16 @@ class Document extends BaseCachedFile implements EventSubscriberInterface
$event->setDocumentUrl(URL::getInstance()->absoluteUrl($documentUrl, null, URL::PATH_TO_FILE)); $event->setDocumentUrl(URL::getInstance()->absoluteUrl($documentUrl, null, URL::PATH_TO_FILE));
} }
/**
* Take care of saving document in the database and file storage
*
* @param \Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent $event Document event
*
* @throws \Thelia\Exception\ImageException
* @todo refactor make all documents using propel inheritance and factorise image behaviour into one single clean action
*/
public function saveDocument(DocumentCreateOrUpdateEvent $event)
{
$model = $event->getModelDocument();
$nbModifiedLines = $model->save();
$event->setModelDocument($model);
if (!$nbModifiedLines) {
throw new ImageException(
sprintf(
'Document "%s" with parent id %s failed to be saved',
$event->getParentName(),
$event->getParentId()
)
);
}
$newUploadedFile = $this->fileManager->copyUploadedFile($event->getModelDocument(), $event->getUploadedFile());
$event->setUploadedFile($newUploadedFile);
}
/**
* Take care of updating document in the database and file storage
*
* @param \Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent $event Document event
*
* @throws \Thelia\Exception\ImageException
* @todo refactor make all documents using propel inheritance and factorise image behaviour into one single clean action
*/
public function updateDocument(DocumentCreateOrUpdateEvent $event)
{
if (null !== $event->getUploadedFile()) {
$event->getModelDocument()->setTitle($event->getUploadedFile()->getClientOriginalName());
}
// Copy and save file
if ($event->getUploadedFile()) {
// Remove old picture file from file storage
$url = $event->getModelDocument()->getUploadDir() . '/' . $event->getOldModelDocument()->getFile();
unlink(str_replace('..', '', $url));
$newUploadedFile = $this->fileManager->copyUploadedFile($event->getModelDocument(), $event->getUploadedFile());
$event->setUploadedFile($newUploadedFile);
}
// Update document modifications
$event->getModelDocument()->save();
$event->setModelDocument($event->getModelDocument());
}
public function updatePosition(UpdateFilePositionEvent $event)
{
$this->genericUpdatePosition($event->getQuery(), $event);
}
/**
* Take care of deleting document in the database and file storage
*
* @param \Thelia\Core\Event\Document\DocumentDeleteEvent $event Image event
*
* @throws \Exception
*/
public function deleteDocument(DocumentDeleteEvent $event)
{
$this->fileManager->deleteFile($event->getDocumentToDelete());
}
public static function getSubscribedEvents() public static function getSubscribedEvents()
{ {
return array( return array(
TheliaEvents::DOCUMENT_PROCESS => array("processDocument", 128), TheliaEvents::DOCUMENT_PROCESS => array("processDocument", 128),
// Implemented in parent class BaseCachedFile
TheliaEvents::DOCUMENT_CLEAR_CACHE => array("clearCache", 128), TheliaEvents::DOCUMENT_CLEAR_CACHE => array("clearCache", 128),
TheliaEvents::DOCUMENT_DELETE => array("deleteDocument", 128), TheliaEvents::DOCUMENT_DELETE => array("deleteFile", 128),
TheliaEvents::DOCUMENT_SAVE => array("saveDocument", 128), TheliaEvents::DOCUMENT_SAVE => array("saveFile", 128),
TheliaEvents::DOCUMENT_UPDATE => array("updateDocument", 128), TheliaEvents::DOCUMENT_UPDATE => array("updateFile", 128),
TheliaEvents::DOCUMENT_UPDATE_POSITION => array("updatePosition", 128), TheliaEvents::DOCUMENT_UPDATE_POSITION => array("updatePosition", 128),
); );
} }

View File

@@ -14,10 +14,8 @@ 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\Document\DocumentCreateOrUpdateEvent; use Thelia\Core\Event\File\FileCreateOrUpdateEvent;
use Thelia\Core\Event\Document\DocumentDeleteEvent; use Thelia\Core\Event\Image\FileDeleteEvent;
use Thelia\Core\Event\Image\ImageCreateOrUpdateEvent;
use Thelia\Core\Event\Image\ImageDeleteEvent;
use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\UpdateFilePositionEvent; use Thelia\Core\Event\UpdateFilePositionEvent;
use Thelia\Core\HttpFoundation\Response; use Thelia\Core\HttpFoundation\Response;
@@ -56,107 +54,16 @@ class FileController extends BaseAdminController
} }
/** /**
* Manage how a image collection has to be saved * Manage how a file collection has to be saved
* *
* @param int $parentId Parent id owning images being saved * @param int $parentId Parent id owning files being saved
* @param string $parentType Parent Type owning images being saved * @param string $parentType Parent Type owning files being saved (product, category, content, etc.)
* @param string $objectType Object type, e.g. image or document
* @param array $validMimeTypes an array of valid mime types. If empty, any mime type is allowed.
* *
* @return Response * @return Response
*/ */
public function saveImageAjaxAction($parentId, $parentType) public function saveFileAjaxAction($parentId, $parentType, $objectType, $validMimeTypes = array())
{
$this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE);
$this->checkXmlHttpRequest();
if ($this->getRequest()->isMethod('POST')) {
/** @var UploadedFile $fileBeingUploaded */
$fileBeingUploaded = $this->getRequest()->files->get('file');
$fileManager = $this->getFileManager();
// Validate if file is too big
if ($fileBeingUploaded->getError() == 1) {
$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(
'You can only upload images (.png, .jpg, .jpeg, .gif)',
array(),
'image'
);
return new ResponseRest($message, 'text', 415);
}
$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);
}
/**
* Manage how a document collection has to be saved
*
* @param int $parentId Parent id owning documents being saved
* @param string $parentType Parent Type owning documents being saved
*
* @return Response
*/
public function saveDocumentAjaxAction($parentId, $parentType)
{ {
$this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE);
$this->checkXmlHttpRequest(); $this->checkXmlHttpRequest();
@@ -173,46 +80,76 @@ class FileController extends BaseAdminController
$message = $this->getTranslator() $message = $this->getTranslator()
->trans( ->trans(
'File is too large, 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('upload_max_filesize')),
'document' 'core'
); );
return new ResponseRest($message, 'text', 403); return new ResponseRest($message, 'text', 403);
} }
$documentModel = $fileManager->getModelInstance('document', $parentType); if (! empty($validMimeTypes)) {
$parentModel = $documentModel->getParentFileModel($parentType, $parentId);
if ($parentModel === null || $documentModel === null || $fileBeingUploaded === null) { // Check if we have the proper file type
$isValid = false;
$mimeType = $fileBeingUploaded->getMimeType();
if (in_array($mimeType, $validMimeTypes)) {
$isValid = true;
}
if (! $isValid) {
$message = $this->getTranslator()
->trans(
'Only files having the following mime type are allowed: %types%',
[ '%types%' => implode(', ', $validMimeTypes)]
);
return new ResponseRest($message, 'text', 415);
}
}
$fileModel = $fileManager->getModelInstance($objectType, $parentType);
$parentModel = $fileModel->getParentFileModel();
if ($parentModel === null || $fileModel === null || $fileBeingUploaded === null) {
return new Response('', 404); return new Response('', 404);
} }
$documentModel->setParentId($parentId); $defaultTitle = $parentModel->getTitle();
$documentModel->setLocale(Lang::getDefaultLanguage()->getLocale());
$documentModel->setTitle($fileBeingUploaded->getClientOriginalName());
$documentCreateOrUpdateEvent = new DocumentCreateOrUpdateEvent($parentId); if (empty($defaultTitle)) {
$defaultTitle = $fileBeingUploaded->getClientOriginalName();
}
$documentCreateOrUpdateEvent->setModelDocument($documentModel); $fileModel
$documentCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded); ->setParentId($parentId)
$documentCreateOrUpdateEvent->setParentName($parentModel->getTitle()); ->setLocale(Lang::getDefaultLanguage()->getLocale())
->setTitle($defaultTitle)
;
$fileCreateOrUpdateEvent = new FileCreateOrUpdateEvent($parentId);
$fileCreateOrUpdateEvent->setModel($fileModel);
$fileCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded);
$fileCreateOrUpdateEvent->setParentName($parentModel->getTitle());
// Dispatch Event to the Action // Dispatch Event to the Action
$this->dispatch( $this->dispatch(
TheliaEvents::DOCUMENT_SAVE, TheliaEvents::IMAGE_SAVE,
$documentCreateOrUpdateEvent $fileCreateOrUpdateEvent
); );
$this->adminLogAppend( $this->adminLogAppend(
AdminResources::retrieve($parentType), AdminResources::retrieve($parentType),
AccessManager::UPDATE, AccessManager::UPDATE,
$this->container->get('thelia.translator')->trans( $this->getTranslator()->trans(
'Saving document for %parentName% parent id %parentId%', 'Saving %obj% for %parentName% parent id %parentId%',
array( array(
'%parentName%' => $documentCreateOrUpdateEvent->getParentName(), '%parentName%' => $fileCreateOrUpdateEvent->getParentName(),
'%parentId%' => $documentCreateOrUpdateEvent->getParentId() '%parentId%' => $fileCreateOrUpdateEvent->getParentId(),
), '%obj%' => $objectType
'document' )
) )
); );
@@ -222,6 +159,32 @@ class FileController extends BaseAdminController
return new Response('', 404); return new Response('', 404);
} }
/**
* Manage how a image collection has to be saved
*
* @param int $parentId Parent id owning images being saved
* @param string $parentType Parent Type owning images being saved
*
* @return Response
*/
public function saveImageAjaxAction($parentId, $parentType)
{
return $this->saveFileAjaxAction($parentId, $parentType, 'image', ['image/jpeg' , 'image/png' ,'image/gif']);
}
/**
* Manage how a document collection has to be saved
*
* @param int $parentId Parent id owning documents being saved
* @param string $parentType Parent Type owning documents being saved
*
* @return Response
*/
public function saveDocumentAjaxAction($parentId, $parentType)
{
return $this->saveFileAjaxAction($parentId, $parentType, 'document');
}
/** /**
* Manage how a image list will be displayed in AJAX * Manage how a image list will be displayed in AJAX
* *
@@ -359,6 +322,106 @@ class FileController extends BaseAdminController
)); ));
} }
/**
* Manage how a file is updated
*
* @param int $fileId File identifier
* @param string $parentType Parent Type owning file being saved
* @param string $objectType the type of the file, image or document
* @param string $eventName the event type.
*
* @return FileModelInterface
*/
public function updateFileAction($fileId, $parentType, $objectType, $eventName)
{
$message = false;
$fileManager = $this->getFileManager();
$fileModelInstance = $fileManager->getModelInstance($objectType, $parentType);
$fileUpdateForm = $fileModelInstance->getUpdateFormInstance($this->getRequest());
/** @var FileModelInterface $file */
$file = $fileModelInstance->getQueryInstance()->findPk($fileId);
try {
$oldFile = clone $file;
if (null === $file) {
throw new \InvalidArgumentException(sprintf('%d %s id does not exist', $fileId, $objectType));
}
$data = $this->validateForm($fileUpdateForm)->getData();
$event = new FileCreateOrUpdateEvent(null);
$file->setLocale($data['locale']);
if (isset($data['title'])) {
$file->setTitle($data['title']);
}
if (isset($data['chapo'])) {
$file->setChapo($data['chapo']);
}
if (isset($data['description'])) {
$file->setDescription($data['description']);
}
if (isset($data['file'])) {
$file->setFile($data['file']);
}
if (isset($data['postscriptum'])) {
$file->setPostscriptum($data['postscriptum']);
}
$event->setModel($file);
$event->setOldModel($oldFile);
$files = $this->getRequest()->files;
$fileForm = $files->get($fileUpdateForm->getName());
if (isset($fileForm['file'])) {
$event->setUploadedFile($fileForm['file']);
}
$this->dispatch($eventName, $event);
$fileUpdated = $event->getModel();
$this->adminLogAppend(AdminResources::retrieve($parentType), AccessManager::UPDATE,
sprintf('%s with Ref %s (ID %d) modified', ucfirst($objectType), $fileUpdated->getTitle(), $fileUpdated->getId())
);
if ($this->getRequest()->get('save_mode') == 'close') {
$this->redirect(URL::getInstance()->absoluteUrl($fileModelInstance->getRedirectionUrl($fileId)));
} else {
$this->redirectSuccess($fileUpdateForm);
}
} catch (FormValidationException $e) {
$message = sprintf('Please check your input: %s', $e->getMessage());
} catch (PropelException $e) {
$message = $e->getMessage();
} catch (\Exception $e) {
$message = sprintf('Sorry, an error occurred: %s', $e->getMessage().' '.$e->getFile());
}
if ($message !== false) {
Tlog::getInstance()->error(sprintf('Error during %s editing : %s.', $objectType, $message));
$fileUpdateForm->setErrorMessage($message);
$this->getParserContext()
->addForm($fileUpdateForm)
->setGeneralError($message);
}
return $fileModelInstance;
}
/** /**
* Manage how an image is updated * Manage how an image is updated
* *
@@ -373,72 +436,13 @@ class FileController extends BaseAdminController
return $response; return $response;
} }
$message = false; $imageInstance = $this->updateFileAction($imageId, $parentType, 'image', TheliaEvents::IMAGE_UPDATE);
$fileManager = $this->getFileManager();
$modelInstance = $fileManager->getModelInstance('image', $parentType);
$imageModification = $modelInstance->getUpdateFormInstance($this->getRequest());
/** @var FileModelInterface $image */
$image = $modelInstance->getQueryInstance()->findPk($imageId);
try {
$oldImage = clone $image;
if (null === $image) {
throw new \InvalidArgumentException(sprintf('%d image id does not exist', $imageId));
}
$form = $this->validateForm($imageModification);
$event = $this->createImageEventInstance($parentType, $image, $form->getData());
$event->setOldModelImage($oldImage);
$files = $this->getRequest()->files;
$fileForm = $files->get($imageModification->getName());
if (isset($fileForm['file'])) {
$event->setUploadedFile($fileForm['file']);
}
$this->dispatch(TheliaEvents::IMAGE_UPDATE, $event);
$imageUpdated = $event->getModelImage();
$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') {
$this->redirect(URL::getInstance()->absoluteUrl($modelInstance->getRedirectionUrl($imageId)));
} else {
$this->redirectSuccess($imageModification);
}
} catch (FormValidationException $e) {
$message = sprintf('Please check your input: %s', $e->getMessage());
} catch (PropelException $e) {
$message = $e->getMessage();
} catch (\Exception $e) {
$message = sprintf('Sorry, an error occurred: %s', $e->getMessage().' '.$e->getFile());
}
if ($message !== false) {
Tlog::getInstance()->error(sprintf('Error during image editing : %s.', $message));
$imageModification->setErrorMessage($message);
$this->getParserContext()
->addForm($imageModification)
->setGeneralError($message);
}
$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' => $imageInstance,
'formId' => $modelInstance->getUpdateFormId() 'formId' => $imageInstance->getUpdateFormId()
)); ));
} }
@@ -452,79 +456,97 @@ class FileController extends BaseAdminController
*/ */
public function updateDocumentAction($documentId, $parentType) public function updateDocumentAction($documentId, $parentType)
{ {
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;
} }
$message = false; $documentInstance = $this->updateFileAction($documentId, $parentType, 'document', TheliaEvents::DOCUMENT_UPDATE);
$fileManager = $this->getFileManager();
$modelInstance = $fileManager->getModelInstance('document', $parentType);
$documentModification = $modelInstance->getUpdateFormInstance($this->getRequest());
/** @var FileModelInterface $document */
$document = $modelInstance->getQueryInstance()->findPk($documentId);
try {
$oldDocument = clone $document;
if (null === $document) {
throw new \InvalidArgumentException(sprintf('%d document id does not exist', $documentId));
}
$form = $this->validateForm($documentModification);
$event = $this->createDocumentEventInstance($parentType, $document, $form->getData());
$event->setOldModelDocument($oldDocument);
$files = $this->getRequest()->files;
$fileForm = $files->get($documentModification->getName());
if (isset($fileForm['file'])) {
$event->setUploadedFile($fileForm['file']);
}
$this->dispatch(TheliaEvents::DOCUMENT_UPDATE, $event);
$documentUpdated = $event->getModelDocument();
$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') {
$this->redirect(URL::getInstance()->absoluteUrl($modelInstance->getRedirectionUrl($documentId)));
} else {
$this->redirectSuccess($documentModification);
}
} catch (FormValidationException $e) {
$message = sprintf('Please check your input: %s', $e->getMessage());
} catch (PropelException $e) {
$message = $e->getMessage();
} catch (\Exception $e) {
$message = sprintf('Sorry, an error occurred: %s', $e->getMessage().' '.$e->getFile());
}
if ($message !== false) {
Tlog::getInstance()->error(sprintf('Error during document editing : %s.', $message));
$documentModification->setErrorMessage($message);
$this->getParserContext()
->addForm($documentModification)
->setGeneralError($message);
}
$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' => $documentInstance->getRedirectionUrl($documentId),
'formId' => $modelInstance->getUpdateFormId() 'formId' => $documentInstance->getUpdateFormId()
)); ));
} }
/**
* Manage how a image has to be deleted (AJAX)
*
* @param int $fileId Parent id owning image being deleted
* @param string $parentType Parent Type owning image being deleted
* @param string $objectType the type of the file, image or document
* @param string $eventName the event type.
*
* @return Response
*/
public function deleteFileAction($fileId, $parentType, $objectType, $eventName)
{
$message = null;
$this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE);
$this->checkXmlHttpRequest();
$fileManager = $this->getFileManager();
$modelInstance = $fileManager->getModelInstance($objectType, $parentType);
$model = $modelInstance->getQueryInstance()->findPk($fileId);
if ($model == null) {
return $this->pageNotFound();
}
// Feed event
$fileDeleteEvent = new FileDeleteEvent($model);
// Dispatch Event to the Action
try {
$this->dispatch($eventName, $fileDeleteEvent);
$this->adminLogAppend(
AdminResources::retrieve($parentType),
AccessManager::UPDATE,
$this->getTranslator()->trans(
'Deleting %obj% for %id% with parent id %parentId%',
array(
'%obj%' => $objectType,
'%id%' => $fileDeleteEvent->getFileToDelete()->getId(),
'%parentId%' => $fileDeleteEvent->getFileToDelete()->getParentId(),
)
)
);
} catch (\Exception $e) {
$message = $this->getTranslator()->trans(
'Fail to delete %obj% for %id% with parent id %parentId% (Exception : %e%)',
array(
'%obj%' => $objectType,
'%id%' => $fileDeleteEvent->getFileToDelete()->getId(),
'%parentId%' => $fileDeleteEvent->getFileToDelete()->getParentId(),
'%e%' => $e->getMessage()
)
);
$this->adminLogAppend(
AdminResources::retrieve($parentType),
AccessManager::UPDATE,
$message
);
}
if (null === $message) {
$message = $this->getTranslator()->trans(
'%obj%s deleted successfully',
['%obj%' => ucfirst($objectType)],
'image'
);
}
return new Response($message);
}
/** /**
* Manage how a image has to be deleted (AJAX) * Manage how a image has to be deleted (AJAX)
* *
@@ -535,189 +557,7 @@ class FileController extends BaseAdminController
*/ */
public function deleteImageAction($imageId, $parentType) public function deleteImageAction($imageId, $parentType)
{ {
$message = null; return $this->deleteFileAction($imageId, $parentType, 'image', TheliaEvents::IMAGE_DELETE);
$this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE);
$this->checkXmlHttpRequest();
$fileManager = $this->getFileManager();
$modelInstance = $fileManager->getModelInstance('image', $parentType);
$model = $modelInstance->getQueryInstance()->findPk($imageId);
if ($model == null) {
return $this->pageNotFound();
}
// Feed event
$imageDeleteEvent = new ImageDeleteEvent(
$model,
$parentType
);
// Dispatch Event to the Action
try {
$this->dispatch(
TheliaEvents::IMAGE_DELETE,
$imageDeleteEvent
);
$this->adminLogAppend(
AdminResources::retrieve($parentType),
AccessManager::UPDATE,
$this->container->get('thelia.translator')->trans(
'Deleting image for %id% with parent id %parentId%',
array(
'%id%' => $imageDeleteEvent->getImageToDelete()->getId(),
'%parentId%' => $imageDeleteEvent->getImageToDelete()->getParentId(),
),
'image'
)
);
} catch (\Exception $e) {
$this->adminLogAppend(
AdminResources::retrieve($parentType),
AccessManager::UPDATE,
$this->container->get('thelia.translator')->trans(
'Fail to delete image for %id% with parent id %parentId% (Exception : %e%)',
array(
'%id%' => $imageDeleteEvent->getImageToDelete()->getId(),
'%parentId%' => $imageDeleteEvent->getImageToDelete()->getParentId(),
'%e%' => $e->getMessage()
),
'image'
)
);
$message = $this->getTranslator()
->trans(
'Fail to delete image for %id% with parent id %parentId% (Exception : %e%)',
array(
'%id%' => $imageDeleteEvent->getImageToDelete()->getId(),
'%parentId%' => $imageDeleteEvent->getImageToDelete()->getParentId(),
'%e%' => $e->getMessage()
),
'image'
);
}
if (null === $message) {
$message = $this->getTranslator()
->trans(
'Images deleted successfully',
array(),
'image'
);
}
return new Response($message);
}
public function updateImagePositionAction($parentType, /** @noinspection PhpUnusedParameterInspection */ $parentId)
{
$message = null;
$imageId = $this->getRequest()->request->get('image_id');
$position = $this->getRequest()->request->get('position');
$this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE);
$this->checkXmlHttpRequest();
$fileManager = $this->getFileManager();
$modelInstance = $fileManager->getModelInstance('image', $parentType);
$model = $modelInstance->getQueryInstance()->findPk($imageId);
if ($model === null || $position === null) {
return $this->pageNotFound();
}
// Feed event
$imageUpdateImagePositionEvent = new UpdateFilePositionEvent(
$modelInstance->getQueryInstance($parentType),
$imageId,
UpdateFilePositionEvent::POSITION_ABSOLUTE,
$position
);
// Dispatch Event to the Action
try {
$this->dispatch(
TheliaEvents::IMAGE_UPDATE_POSITION,
$imageUpdateImagePositionEvent
);
} catch (\Exception $e) {
$message = $this->getTranslator()
->trans(
'Fail to update image position',
array(),
'image'
) . $e->getMessage();
}
if (null === $message) {
$message = $this->getTranslator()
->trans(
'Image position updated',
array(),
'image'
);
}
return new Response($message);
}
public function updateDocumentPositionAction($parentType, /** @noinspection PhpUnusedParameterInspection */ $parentId)
{
$message = null;
$documentId = $this->getRequest()->request->get('document_id');
$position = $this->getRequest()->request->get('position');
$this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE);
$this->checkXmlHttpRequest();
$fileManager = $this->getFileManager();
$modelInstance = $fileManager->getModelInstance('document', $parentType);
$model = $modelInstance->getQueryInstance()->findPk($documentId);
if ($model === null || $position === null) {
return $this->pageNotFound();
}
// Feed event
$documentUpdateDocumentPositionEvent = new UpdateFilePositionEvent(
$modelInstance->getQueryInstance(),
$documentId,
UpdateFilePositionEvent::POSITION_ABSOLUTE,
$position
);
// Dispatch Event to the Action
try {
$this->dispatch(
TheliaEvents::DOCUMENT_UPDATE_POSITION,
$documentUpdateDocumentPositionEvent
);
} catch (\Exception $e) {
$message = $this->getTranslator()
->trans(
'Fail to update document position',
array(),
'document'
) . $e->getMessage();
}
if (null === $message) {
$message = $this->getTranslator()
->trans(
'Document position updated',
array(),
'document'
);
}
return new Response($message);
} }
/** /**
@@ -730,160 +570,66 @@ class FileController extends BaseAdminController
*/ */
public function deleteDocumentAction($documentId, $parentType) public function deleteDocumentAction($documentId, $parentType)
{ {
return $this->deleteFileAction($documentId, $parentType, 'document', TheliaEvents::DOCUMENT_DELETE);
}
public function updateFilePositionAction($parentType, $parentId, $objectType, $eventName)
{
$message = null;
$position = $this->getRequest()->request->get('position');
$this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE); $this->checkAuth(AdminResources::retrieve($parentType), array(), AccessManager::UPDATE);
$this->checkXmlHttpRequest(); $this->checkXmlHttpRequest();
$fileManager = $this->getFileManager(); $fileManager = $this->getFileManager();
$modelInstance = $fileManager->getModelInstance('document', $parentType); $modelInstance = $fileManager->getModelInstance($objectType, $parentType);
$model = $modelInstance->getQueryInstance()->findPk($documentId); $model = $modelInstance->getQueryInstance()->findPk($parentId);
if ($model == null) { if ($model === null || $position === null) {
return $this->pageNotFound(); return $this->pageNotFound();
} }
// Feed event // Feed event
$documentDeleteEvent = new DocumentDeleteEvent( $event = new UpdateFilePositionEvent(
$model, $modelInstance->getQueryInstance($parentType),
$parentType $parentId,
UpdateFilePositionEvent::POSITION_ABSOLUTE,
$position
); );
// Dispatch Event to the Action // Dispatch Event to the Action
try { try {
$this->dispatch( $this->dispatch($eventName,$event);
TheliaEvents::DOCUMENT_DELETE,
$documentDeleteEvent
);
$this->adminLogAppend(
AdminResources::retrieve($parentType),
AccessManager::UPDATE,
$this->container->get('thelia.translator')->trans(
'Deleting document for %id% with parent id %parentId%',
array(
'%id%' => $documentDeleteEvent->getDocumentToDelete()->getId(),
'%parentId%' => $documentDeleteEvent->getDocumentToDelete()->getParentId(),
),
'document'
)
);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->adminLogAppend(
AdminResources::retrieve($parentType), $message = $this->getTranslator()->trans(
AccessManager::UPDATE, 'Fail to update %type% position: %err%',
$this->container->get('thelia.translator')->trans( [ '%type%' => $objectType, '%err%' => $e->getMessage() ]
'Fail to delete document for %id% with parent id %parentId% (Exception : %e%)',
array(
'%id%' => $documentDeleteEvent->getDocumentToDelete()->getId(),
'%parentId%' => $documentDeleteEvent->getDocumentToDelete()->getParentId(),
'%e%' => $e->getMessage()
),
'document'
)
); );
} }
$message = $this->getTranslator() if (null === $message) {
->trans( $message = $this->getTranslator()->trans(
'Document deleted successfully', '%type% position updated',
array(), [ '%type%' => ucfirst($objectType) ]
'document'
); );
}
return new Response($message); return new Response($message);
} }
/** public function updateImagePositionAction($parentType, /** @noinspection PhpUnusedParameterInspection */ $parentId)
* Log error message
*
* @param string $parentType Parent type
* @param string $action Creation|Update|Delete
* @param string $message Message to log
* @param \Exception $e Exception to log
*
* @return $this
*/
protected function logError($parentType, $action, $message, $e)
{ {
Tlog::getInstance()->error( $imageId = $this->getRequest()->request->get('image_id');
sprintf(
'Error during ' . $parentType . ' ' . $action . ' process : %s. Exception was %s',
$message,
$e->getMessage()
)
);
return $this; return $this->updateFilePositionAction($parentType, $imageId, 'image', TheliaEvents::IMAGE_UPDATE_POSITION);
} }
/** public function updateDocumentPositionAction($parentType, /** @noinspection PhpUnusedParameterInspection */ $parentId)
* Create Image Event instance
*
* @param string $parentType Parent Type owning images being saved
* @param FileModelInterface $model the model
* @param array $data Post data
*
* @return ImageCreateOrUpdateEvent
*/
protected function createImageEventInstance($parentType, $model, $data)
{ {
$imageCreateEvent = new ImageCreateOrUpdateEvent(null); $documentId = $this->getRequest()->request->get('document_id');
$model->setLocale($data['locale']); return $this->updateFilePositionAction($parentType, $documentId, 'document', TheliaEvents::DOCUMENT_UPDATE_POSITION);
if (isset($data['title'])) {
$model->setTitle($data['title']);
} }
if (isset($data['chapo'])) {
$model->setChapo($data['chapo']);
}
if (isset($data['description'])) {
$model->setDescription($data['description']);
}
if (isset($data['file'])) {
$model->setFile($data['file']);
}
if (isset($data['postscriptum'])) {
$model->setPostscriptum($data['postscriptum']);
}
$imageCreateEvent->setModelImage($model);
return $imageCreateEvent;
}
/**
* Create Document Event instance
*
* @param string $parentType Parent Type owning documents being saved
* @param FileModelInterface $model the model
* @param array $data Post data
*
* @return DocumentCreateOrUpdateEvent
*/
protected function createDocumentEventInstance($parentType, $model, $data)
{
$documentCreateEvent = new DocumentCreateOrUpdateEvent(null);
$model->setLocale($data['locale']);
if (isset($data['title'])) {
$model->setTitle($data['title']);
}
if (isset($data['chapo'])) {
$model->setChapo($data['chapo']);
}
if (isset($data['description'])) {
$model->setDescription($data['description']);
}
if (isset($data['file'])) {
$model->setFile($data['file']);
}
if (isset($data['postscriptum'])) {
$model->setPostscriptum($data['postscriptum']);
}
$documentCreateEvent->setModelDocument($model);
return $documentCreateEvent;
}
} }

View File

@@ -11,167 +11,121 @@
/*************************************************************************************/ /*************************************************************************************/
namespace Thelia\Core\Event\Document; namespace Thelia\Core\Event\Document;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Thelia\Core\Event\ActionEvent; use Thelia\Core\Event\File\FileCreateOrUpdateEvent;
use Thelia\Files\FileModelInterface; use Thelia\Files\FileModelInterface;
use Thelia\Model\CategoryDocument;
use Thelia\Model\ContentDocument;
use Thelia\Model\FolderDocument;
use Thelia\Model\ProductDocument;
/** /**
* Created by JetBrains PhpStorm. * Created by JetBrains PhpStorm.
* Date: 9/18/13 * Date: 9/18/13
* Time: 3:56 PM * Time: 3:56 PM
* *
* Occurring when a Document is saved * Occurring when an Document is saved
* *
* @package Document * @package Document
* @author Guillaume MOREL <gmorel@openstudio.fr> * @author Guillaume MOREL <gmorel@openstudio.fr>
* * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
class DocumentCreateOrUpdateEvent extends ActionEvent class DocumentCreateOrUpdateEvent extends FileCreateOrUpdateEvent
{ {
/** @var CategoryDocument|ProductDocument|ContentDocument|FolderDocument model to save */
protected $modelDocument = array();
/** @var CategoryDocument|ProductDocument|ContentDocument|FolderDocument model to save */
protected $oldModelDocument = array();
/** @var UploadedFile Document file to save */
protected $uploadedFile = null;
/** @var int Document parent id */
protected $parentId = null;
/** @var string Parent name */
protected $parentName = null;
/** /**
* Constructor * Constructor
* *
* @param string $documentType Document type
* ex : FileManager::TYPE_CATEGORY
* @param int $parentId Document parent id * @param int $parentId Document parent id
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
public function __construct($parentId) public function __construct($documentType, $parentId)
{ {
$this->parentId = $parentId; parent::__construct($parentId);
}
/**
* @param mixed $locale
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/
public function setLocale($locale)
{
return $this;
}
/**
* @return mixed
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/
public function getLocale()
{
throw new \RuntimeException("getLocale() is deprecated and no longer supported");
} }
/** /**
* Set Document to save * Set Document to save
* *
* @param FileModelInterface $document Document to save * @param $document FileModelInterface
* *
* @return $this * @return $this
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
public function setModelDocument($document) public function setModelDocument($document)
{ {
$this->modelDocument = $document; parent::setModel($document);
return $this;
} }
/** /**
* Get Document being saved * Get Document being saved
* *
* @return FileModelInterface * @return FileModelInterface
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
public function getModelDocument() public function getModelDocument()
{ {
return $this->modelDocument; return parent::getModel();
} }
/** /**
* Set Document parent id * Set picture type
* *
* @param int $parentId Document parent id * @param string $documentType Document type
* *
* @return $this * @return $this
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
public function setParentId($parentId) public function setDocumentType($documentType)
{ {
$this->parentId = $parentId;
return $this; return $this;
} }
/** /**
* Get Document parent id * Get picture type
*
* @return int
*/
public function getParentId()
{
return $this->parentId;
}
/**
* Set uploaded file
*
* @param UploadedFile $uploadedFile File being uploaded
*
* @return $this
*/
public function setUploadedFile($uploadedFile)
{
$this->uploadedFile = $uploadedFile;
return $this;
}
/**
* Get uploaded file
*
* @return UploadedFile
*/
public function getUploadedFile()
{
return $this->uploadedFile;
}
/**
* Set parent name
*
* @param string $parentName Parent name
*
* @return $this
*/
public function setParentName($parentName)
{
$this->parentName = $parentName;
return $this;
}
/**
* Get parent name
* *
* @return string * @return string
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
public function getParentName() public function getDocumentType()
{ {
return $this->parentName; throw new \RuntimeException("getDocumentType() is deprecated and no longer supported");
} }
/** /**
* Set old model value * Set old model value
* *
* @param FileModelInterface $oldModelDocument * @param FileModelInterface $oldModelDocument
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
public function setOldModelDocument($oldModelDocument) public function setOldModelDocument($oldModelDocument)
{ {
$this->oldModelDocument = $oldModelDocument; parent::setOldModel($oldModelDocument);
} }
/** /**
* Get old model value * Get old model value
* *
* @return FileModelInterface * @return FileModelInterface
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
public function getOldModelDocument() public function getOldModelDocument()
{ {
return $this->oldModelDocument; return parent::getOldModel();
} }
} }

View File

@@ -12,8 +12,11 @@
namespace Thelia\Core\Event\Document; namespace Thelia\Core\Event\Document;
use Thelia\Core\Event\ActionEvent; use Thelia\Core\Event\Image\FileDeleteEvent;
use Thelia\Files\FileModelInterface; use Thelia\Model\CategoryDocument;
use Thelia\Model\ContentDocument;
use Thelia\Model\FolderDocument;
use Thelia\Model\ProductDocument;
/** /**
* Created by JetBrains PhpStorm. * Created by JetBrains PhpStorm.
@@ -24,34 +27,58 @@ use Thelia\Files\FileModelInterface;
* *
* @package Document * @package Document
* @author Guillaume MOREL <gmorel@openstudio.fr> * @author Guillaume MOREL <gmorel@openstudio.fr>
* * @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead
*/ */
class DocumentDeleteEvent extends ActionEvent class DocumentDeleteEvent extends FileDeleteEvent
{ {
/** @var FileModelInterface Document about to be deleted */
protected $documentToDelete = null;
/** /**
* Constructor * Constructor
* *
* @param FileModelInterface $documentToDelete Document about to be deleted * @param CategoryDocument|ProductDocument|ContentDocument|FolderDocument $documentToDelete Document about to be deleted
* @param string $documentType Document type
* ex : FileManager::TYPE_CATEGORY
* @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead
*/ */
public function __construct($documentToDelete) public function __construct($documentToDelete, $documentType)
{ {
$this->documentToDelete = $documentToDelete; parent::__construct($documentToDelete);
}
/**
* Set picture type
*
* @param string $documentType Document type
*
* @return $this
* @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead
*/
public function setDocumentType($documentType)
{
return $this;
}
/**
* Get picture type
*
* @return string
* @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead
*/
public function getDocumentType()
{
throw new \RuntimeException("getDocumentType() is deprecated and no longer supported");
} }
/** /**
* Set Document about to be deleted * Set Document about to be deleted
* *
* @param FileModelInterface $documentToDelete Document about to be deleted * @param CategoryDocument|ProductDocument|ContentDocument|FolderDocument $documentToDelete Document about to be deleted
* *
* @return $this * @return $this
* @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead
*/ */
public function setDocumentToDelete($documentToDelete) public function setDocumentToDelete($documentToDelete)
{ {
$this->documentToDelete = $documentToDelete; parent::setFileToDelete($documentToDelete);
return $this; return $this;
} }
@@ -59,11 +86,12 @@ class DocumentDeleteEvent extends ActionEvent
/** /**
* Get Document about to be deleted * Get Document about to be deleted
* *
* @return FileModelInterface * @return CategoryDocument|ProductDocument|ContentDocument|FolderDocument
* @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead
*/ */
public function getDocumentToDelete() public function getDocumentToDelete()
{ {
return $this->documentToDelete; return parent::getFileToDelete();
} }
} }

View File

@@ -0,0 +1,168 @@
<?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\Core\Event\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Thelia\Core\Event\ActionEvent;
use Thelia\Files\FileModelInterface;
/**
* Event fired when a file is created or updated.
*
* @package Thelia\Core\Event\Document
* @author Franck Allimant <franck@cqfdev.fr>
*
*/
class FileCreateOrUpdateEvent extends ActionEvent
{
/** @var FileModelInterface model to save */
protected $model = array();
/** @var FileModelInterface model to save */
protected $oldModel = array();
/** @var UploadedFile Document file to save */
protected $uploadedFile = null;
/** @var int Document parent id */
protected $parentId = null;
/** @var string Parent name */
protected $parentName = null;
/**
* Constructor
*
* @param int $parentId file parent id
*/
public function __construct($parentId)
{
$this->parentId = $parentId;
}
/**
* Set file to save
*
* @param FileModelInterface $model Document to save
*
* @return $this
*/
public function setModel($model)
{
$this->model = $model;
return $this;
}
/**
* Get file being saved
*
* @return FileModelInterface
*/
public function getModel()
{
return $this->model;
}
/**
* Set Document parent id
*
* @param int $parentId Document parent id
*
* @return $this
*/
public function setParentId($parentId)
{
$this->parentId = $parentId;
return $this;
}
/**
* Get Document parent id
*
* @return int
*/
public function getParentId()
{
return $this->parentId;
}
/**
* Set uploaded file
*
* @param UploadedFile $uploadedFile File being uploaded
*
* @return $this
*/
public function setUploadedFile($uploadedFile)
{
$this->uploadedFile = $uploadedFile;
return $this;
}
/**
* Get uploaded file
*
* @return UploadedFile
*/
public function getUploadedFile()
{
return $this->uploadedFile;
}
/**
* Set parent name
*
* @param string $parentName Parent name
*
* @return $this
*/
public function setParentName($parentName)
{
$this->parentName = $parentName;
return $this;
}
/**
* Get parent name
*
* @return string
*/
public function getParentName()
{
return $this->parentName;
}
/**
* Set old model value
*
* @param FileModelInterface $oldModel
*/
public function setOldModel($oldModel)
{
$this->oldModel = $oldModel;
}
/**
* Get old model value
*
* @return FileModelInterface
*/
public function getOldModel()
{
return $this->oldModel;
}
}

View File

@@ -0,0 +1,62 @@
<?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\Core\Event\Image;
use Thelia\Core\Event\ActionEvent;
use Thelia\Files\FileModelInterface;
/**
* Event fired when a file is about to be deleted
*
* @author Franck Allimant <franck@cqfdev.fr>
*/
class FileDeleteEvent extends ActionEvent
{
/** @var FileModelInterface Image about to be deleted */
protected $fileToDelete = null;
/**
* Constructor
*
* @param FileModelInterface $fileToDelete Image about to be deleted
*/
public function __construct($fileToDelete)
{
$this->fileToDelete = $fileToDelete;
}
/**
* Set Image about to be deleted
*
* @param FileModelInterface $fileToDelete Image about to be deleted
*
* @return $this
*/
public function setFileToDelete($fileToDelete)
{
$this->fileToDelete = $fileToDelete;
return $this;
}
/**
* Get Image about to be deleted
*
* @return FileModelInterface
*/
public function getFileToDelete()
{
return $this->fileToDelete;
}
}

View File

@@ -11,8 +11,8 @@
/*************************************************************************************/ /*************************************************************************************/
namespace Thelia\Core\Event\Image; namespace Thelia\Core\Event\Image;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Thelia\Core\Event\ActionEvent; use Thelia\Core\Event\File\FileCreateOrUpdateEvent;
use Thelia\Files\FileModelInterface; use Thelia\Files\FileModelInterface;
/** /**
@@ -24,170 +24,108 @@ use Thelia\Files\FileModelInterface;
* *
* @package Image * @package Image
* @author Guillaume MOREL <gmorel@openstudio.fr> * @author Guillaume MOREL <gmorel@openstudio.fr>
* * @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
class ImageCreateOrUpdateEvent extends ActionEvent class ImageCreateOrUpdateEvent extends FileCreateOrUpdateEvent
{ {
/** @var FileModelInterface model to save */
protected $modelImage = array();
/** @var FileModelInterface model to save */
protected $oldModelImage = array();
/** @var UploadedFile Image file to save */
protected $uploadedFile = null;
/** @var int Image parent id */
protected $parentId = null;
/** @var string Parent name */
protected $parentName = null;
protected $locale;
/** /**
* Constructor * Constructor
* *
* @param string $imageType Image type
* ex : FileManager::TYPE_CATEGORY
* @param int $parentId Image parent id * @param int $parentId Image parent id
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
public function __construct($parentId) public function __construct($imageType, $parentId)
{ {
$this->parentId = $parentId; parent::__construct($parentId);
} }
/** /**
* @param string $locale * @param mixed $locale
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
public function setLocale($locale) public function setLocale($locale)
{ {
$this->locale = $locale;
return $this; return $this;
} }
/** /**
* @return mixed * @return mixed
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
public function getLocale() public function getLocale()
{ {
return $this->locale; throw new \RuntimeException("getLocale() is deprecated and no longer supported");
} }
/** /**
* Set Image to save * Set Image to save
* *
* @param FileModelInterface $image * @param $image FileModelInterface
* *
* @return $this * @return $this
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
public function setModelImage($image) public function setModelImage($image)
{ {
$this->modelImage = $image; parent::setModel($image);
return $this;
} }
/** /**
* Get Image being saved * Get Image being saved
* *
* @return FileModelInterface * @return FileModelInterface
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
public function getModelImage() public function getModelImage()
{ {
return $this->modelImage; return parent::getModel();
} }
/** /**
* Set Image parent id * Set picture type
* *
* @param int $parentId Image parent id * @param string $imageType Image type
* *
* @return $this * @return $this
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
public function setParentId($parentId) public function setImageType($imageType)
{ {
$this->parentId = $parentId;
return $this; return $this;
} }
/** /**
* Get Image parent id * Get picture type
*
* @return int
*/
public function getParentId()
{
return $this->parentId;
}
/**
* Set uploaded file
*
* @param UploadedFile $uploadedFile File being uploaded
*
* @return $this
*/
public function setUploadedFile($uploadedFile)
{
$this->uploadedFile = $uploadedFile;
return $this;
}
/**
* Get uploaded file
*
* @return UploadedFile
*/
public function getUploadedFile()
{
return $this->uploadedFile;
}
/**
* Set parent name
*
* @param string $parentName Parent name
*
* @return $this
*/
public function setParentName($parentName)
{
$this->parentName = $parentName;
return $this;
}
/**
* Get parent name
* *
* @return string * @return string
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
public function getParentName() public function getImageType()
{ {
return $this->parentName; throw new \RuntimeException("getImageType() is deprecated and no longer supported");
} }
/** /**
* Set old model value * Set old model value
* *
* @param \Thelia\Model\CategoryImage|\Thelia\Model\ContentImage|\Thelia\Model\FolderImage|\Thelia\Model\ProductImage $oldModelImage * @param FileModelInterface $oldModelImage
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
public function setOldModelImage($oldModelImage) public function setOldModelImage($oldModelImage)
{ {
$this->oldModelImage = $oldModelImage; parent::setOldModel($oldModelImage);
} }
/** /**
* Get old model value * Get old model value
* *
* @return \Thelia\Model\CategoryImage|\Thelia\Model\ContentImage|\Thelia\Model\FolderImage|\Thelia\Model\ProductImage * @return FileModelInterface
* @deprecated deprecated since version 2.0.3. Use FileCreateOrUpdateEvent instead
*/ */
public function getOldModelImage() public function getOldModelImage()
{ {
return $this->oldModelImage; return parent::getOldModel();
} }
} }

View File

@@ -12,8 +12,10 @@
namespace Thelia\Core\Event\Image; namespace Thelia\Core\Event\Image;
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.
@@ -24,36 +26,58 @@ use Thelia\Files\FileModelInterface;
* *
* @package Image * @package Image
* @author Guillaume MOREL <gmorel@openstudio.fr> * @author Guillaume MOREL <gmorel@openstudio.fr>
* * @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead
*/ */
class ImageDeleteEvent extends ActionEvent class ImageDeleteEvent extends FileDeleteEvent
{ {
/** @var string Image type */
protected $imageType = null;
/** @var FileModelInterface Image about to be deleted */
protected $imageToDelete = null;
/** /**
* Constructor * Constructor
* *
* @param FileModelInterface $imageToDelete Image about to be deleted * @param CategoryImage|ProductImage|ContentImage|FolderImage $imageToDelete Image about to be deleted
* @param string $imageType Image type
* ex : FileManager::TYPE_CATEGORY
* @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead
*/ */
public function __construct($imageToDelete) public function __construct($imageToDelete, $imageType)
{ {
$this->imageToDelete = $imageToDelete; parent::__construct($imageToDelete);
}
/**
* Set picture type
*
* @param string $imageType Image type
*
* @return $this
* @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead
*/
public function setImageType($imageType)
{
return $this;
}
/**
* Get picture type
*
* @return string
* @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead
*/
public function getImageType()
{
throw new \RuntimeException("getImageType() is deprecated and no longer supported");
} }
/** /**
* Set Image about to be deleted * Set Image about to be deleted
* *
* @param FileModelInterface $imageToDelete Image about to be deleted * @param CategoryImage|ProductImage|ContentImage|FolderImage $imageToDelete Image about to be deleted
* *
* @return $this * @return $this
* @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead
*/ */
public function setImageToDelete($imageToDelete) public function setImageToDelete($imageToDelete)
{ {
$this->imageToDelete = $imageToDelete; parent::setFileToDelete($imageToDelete);
return $this; return $this;
} }
@@ -61,11 +85,12 @@ class ImageDeleteEvent extends ActionEvent
/** /**
* Get Image about to be deleted * Get Image about to be deleted
* *
* @return FileModelInterface * @return CategoryImage|ProductImage|ContentImage|FolderImage
* @deprecated deprecated since version 2.0.3. Use FileDeleteEvent instead
*/ */
public function getImageToDelete() public function getImageToDelete()
{ {
return $this->imageToDelete; return parent::getFileToDelete();
} }
} }

View File

@@ -84,10 +84,27 @@ interface FileModelInterface
*/ */
public function getQueryInstance(); public function getQueryInstance();
/**
* Save the model object.
*
* @return mixed
*/
public function save(); public function save();
/**
* Delete the model object.
*
* @return mixed
*/
public function delete(); public function delete();
/**
* Get the model object ID
*
* @return int
*/
public function getId(); public function getId();
@@ -95,12 +112,39 @@ interface FileModelInterface
* Set the current title * Set the current title
* *
* @param string $title the title in the current locale * @param string $title the title in the current locale
* @return FileModelInterface
*/ */
public function setTitle($title); public function setTitle($title);
/**
* Get the current title
*
* @param string $title the title in the current locale
* @return FileModelInterface
*/
public function getTitle();
/**
* Set the chapo
*
* @param string $chapo the chapo in the current locale
* @return FileModelInterface
*/
public function setChapo($chapo); public function setChapo($chapo);
/**
* Set the description
*
* @param string $description the description in the current locale
* @return FileModelInterface
*/
public function setDescription($description); public function setDescription($description);
/**
* Set the postscriptum
*
* @param string $postscriptum the postscriptum in the current locale
* @return FileModelInterface
*/
public function setPostscriptum($postscriptum); public function setPostscriptum($postscriptum);
/** /**

View File

@@ -32,13 +32,15 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup
protected $session; protected $session;
public function getDispatcher() {
return $this->getMock("Symfony\\Component\\EventDispatcher\\EventDispatcherInterface");
}
public function getContainer() public function getContainer()
{ {
$container = new \Symfony\Component\DependencyInjection\ContainerBuilder(); $container = new \Symfony\Component\DependencyInjection\ContainerBuilder();
$dispatcher = $this->getMock("Symfony\Component\EventDispatcher\EventDispatcherInterface"); $container->set("event_dispatcher", $this->getDispatcher());
$container->set("event_dispatcher", $dispatcher);
$request = new Request(); $request = new Request();
$request->setSession($this->session); $request->setSession($this->session);
@@ -137,6 +139,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup
public function testProcessNonExistentImage() public function testProcessNonExistentImage()
{ {
$event = new ImageEvent($this->request); $event = new ImageEvent($this->request);
$event->setDispatcher($this->getDispatcher());
$image = new Image($this->getFileManager()); $image = new Image($this->getFileManager());
@@ -155,6 +158,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup
public function testProcessImageOutsideValidPath() public function testProcessImageOutsideValidPath()
{ {
$event = new ImageEvent($this->request); $event = new ImageEvent($this->request);
$event->setDispatcher($this->getDispatcher());
$image = new Image($this->getFileManager()); $image = new Image($this->getFileManager());
@@ -170,6 +174,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup
public function testProcessImageWithoutAnyTransformationsCopy() public function testProcessImageWithoutAnyTransformationsCopy()
{ {
$event = new ImageEvent($this->request); $event = new ImageEvent($this->request);
$event->setDispatcher($this->getDispatcher());
$event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-1.png"); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-1.png");
$event->setCacheSubdirectory("tests"); $event->setCacheSubdirectory("tests");
@@ -199,6 +204,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup
public function testProcessImageWithoutAnyTransformationsSymlink() public function testProcessImageWithoutAnyTransformationsSymlink()
{ {
$event = new ImageEvent($this->request); $event = new ImageEvent($this->request);
$event->setDispatcher($this->getDispatcher());
$event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-9.png"); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-9.png");
$event->setCacheSubdirectory("tests"); $event->setCacheSubdirectory("tests");
@@ -228,6 +234,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup
public function testProcessImageResizeHorizWithBands() public function testProcessImageResizeHorizWithBands()
{ {
$event = new ImageEvent($this->request); $event = new ImageEvent($this->request);
$event->setDispatcher($this->getDispatcher());
$event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-2.png"); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-2.png");
$event->setCacheSubdirectory("tests"); $event->setCacheSubdirectory("tests");
@@ -248,6 +255,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup
public function testProcessImageResizeVertWithBands() public function testProcessImageResizeVertWithBands()
{ {
$event = new ImageEvent($this->request); $event = new ImageEvent($this->request);
$event->setDispatcher($this->getDispatcher());
$event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-3.png"); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-3.png");
$event->setCacheSubdirectory("tests"); $event->setCacheSubdirectory("tests");
@@ -268,6 +276,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup
public function testProcessImageWithTransformations() public function testProcessImageWithTransformations()
{ {
$event = new ImageEvent($this->request); $event = new ImageEvent($this->request);
$event->setDispatcher($this->getDispatcher());
$event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-4.png"); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-4.png");
$event->setCacheSubdirectory("tests"); $event->setCacheSubdirectory("tests");
@@ -285,6 +294,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup
public function testProcessImageResizeHorizWithCrop() public function testProcessImageResizeHorizWithCrop()
{ {
$event = new ImageEvent($this->request); $event = new ImageEvent($this->request);
$event->setDispatcher($this->getDispatcher());
$event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-5.png"); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-5.png");
$event->setCacheSubdirectory("tests"); $event->setCacheSubdirectory("tests");
@@ -305,6 +315,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup
public function testProcessImageResizeVertWithCrop() public function testProcessImageResizeVertWithCrop()
{ {
$event = new ImageEvent($this->request); $event = new ImageEvent($this->request);
$event->setDispatcher($this->getDispatcher());
$event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-6.png"); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-6.png");
$event->setCacheSubdirectory("tests"); $event->setCacheSubdirectory("tests");
@@ -325,6 +336,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup
public function testProcessImageResizeHorizKeepRatio() public function testProcessImageResizeHorizKeepRatio()
{ {
$event = new ImageEvent($this->request); $event = new ImageEvent($this->request);
$event->setDispatcher($this->getDispatcher());
$event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-7.png"); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-7.png");
$event->setCacheSubdirectory("tests"); $event->setCacheSubdirectory("tests");
@@ -343,6 +355,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup
public function testProcessImageResizeVertKeepRatio() public function testProcessImageResizeVertKeepRatio()
{ {
$event = new ImageEvent($this->request); $event = new ImageEvent($this->request);
$event->setDispatcher($this->getDispatcher());
$event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-8.png"); $event->setSourceFilepath(__DIR__."/assets/images/sources/test-image-8.png");
$event->setCacheSubdirectory("tests"); $event->setCacheSubdirectory("tests");
@@ -358,6 +371,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup
public function testClearTestsCache() public function testClearTestsCache()
{ {
$event = new ImageEvent($this->request); $event = new ImageEvent($this->request);
$event->setDispatcher($this->getDispatcher());
$event->setCacheSubdirectory('tests'); $event->setCacheSubdirectory('tests');
@@ -369,6 +383,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup
public function testClearWholeCache() public function testClearWholeCache()
{ {
$event = new ImageEvent($this->request); $event = new ImageEvent($this->request);
$event->setDispatcher($this->getDispatcher());
$image = new Image($this->getFileManager()); $image = new Image($this->getFileManager());
@@ -383,6 +398,7 @@ class ImageTest extends \Thelia\Tests\TestCaseWithURLToolSetup
public function testClearUnallowedPathCache() public function testClearUnallowedPathCache()
{ {
$event = new ImageEvent($this->request); $event = new ImageEvent($this->request);
$event->setDispatcher($this->getDispatcher());
$event->setCacheSubdirectory('../../../..'); $event->setCacheSubdirectory('../../../..');