On continue à adapter le template...

This commit is contained in:
2021-04-16 19:23:51 +02:00
parent 1e2e612349
commit c160eb2141
127 changed files with 42260 additions and 36 deletions

View File

@@ -0,0 +1,523 @@
<?php
namespace Selection\Controller;
use Selection\Model\SelectionContainer;
use Selection\Model\SelectionContainerImage;
use Selection\Model\SelectionContainerImageQuery;
use Selection\Model\SelectionImage;
use Selection\Model\SelectionImageQuery;
use Selection\Selection;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Thelia\Controller\Admin\FileController;
use Thelia\Core\Event\File\FileCreateOrUpdateEvent;
use Thelia\Core\Event\File\FileDeleteEvent;
use Thelia\Core\Event\File\FileToggleVisibilityEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\UpdateFilePositionEvent;
use Thelia\Core\HttpFoundation\Response;
use Thelia\Core\Security\AccessManager;
use Thelia\Files\Exception\ProcessFileException;
use Thelia\Files\FileModelInterface;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Log\Tlog;
use Thelia\Tools\Rest\ResponseRest;
use Thelia\Tools\URL;
class ImageUploadController extends FileController
{
protected $currentRouter = Selection::ROUTER;
/**
* @inheritdoc
* @throws \Exception
*/
public function getImageListAjaxAction($parentId, $parentType)
{
$this->addModuleResource($parentType);
$this->registerFileModel($parentType);
$this->checkAccessForType(AccessManager::UPDATE, $parentType);
$this->checkXmlHttpRequest();
$args = array('imageType' => $parentType, 'parentId' => $parentId);
return $this->render('image-upload-list-ajax', $args);
}
/**
* @inheritdoc
* @throws \Exception
*/
public function getImageFormAjaxAction($parentId, $parentType)
{
$this->addModuleResource($parentType);
$this->registerFileModel($parentType);
$this->checkAccessForType(AccessManager::UPDATE, $parentType);
$this->checkXmlHttpRequest();
$args = array('imageType' => $parentType, 'parentId' => $parentId);
return $this->render('selectionImageUpdate', $args);
}
/**
* @param $imageId
* @param $parentType
* @return mixed|\Symfony\Component\HttpFoundation\Response
* @throws \Exception
*/
public function updateImageTitleAction($imageId, $parentType)
{
$this->addModuleResource($parentType);
$parentId = $this->getRequest()->get('parentId');
$this->registerFileModel($parentType);
if (null !== $response = $this->checkAccessForType(AccessManager::UPDATE, $parentType)) {
return $response;
}
$fileManager = $this->getFileManager();
$fileModelInstance = $fileManager->getModelInstance('image', $parentType);
/** @var FileModelInterface $file */
$file = $fileModelInstance->getQueryInstance()->findPk($imageId);
$new_title = $this->getRequest()->request->get('title');
$locale = $this->getRequest()->request->get('locale');
if (!empty($new_title)) {
$file->setLocale($locale);
$file->setTitle($new_title);
$file->save();
}
return $this->getImagetTypeUpdateRedirectionUrl($parentType, $parentId);
}
/**
* @param int $fileId
* @param string $parentType
* @param string $objectType
* @param string $eventName
* @return \Symfony\Component\HttpFoundation\Response|Response
* @throws \Exception
*/
public function deleteFileAction($fileId, $parentType, $objectType, $eventName)
{
$message = null;
$this->addModuleResource($parentType);
$parentId = $this->getRequest()->get('parentId');
$this->registerFileModel($parentType);
$this->checkAccessForType(AccessManager::UPDATE, $parentType);
$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->adminUpadteLogAppend(
$parentType,
$this->getTranslator()->trans(
'Deleting %obj% for %id% with parent id %parentId%',
array(
'%obj%' => $objectType,
'%id%' => $fileDeleteEvent->getFileToDelete()->getId(),
'%parentId%' => $fileDeleteEvent->getFileToDelete()->getParentId(),
)
),
$fileDeleteEvent->getFileToDelete()->getId()
);
} 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()
)
);
}
if (null === $message) {
$message = $this->getTranslator()->trans(
'%obj%s deleted successfully',
['%obj%' => ucfirst($objectType)],
Selection::DOMAIN_NAME
);
}
$this->adminUpadteLogAppend($parentType, $message, $fileDeleteEvent->getFileToDelete()->getId());
return $this->getImagetTypeUpdateRedirectionUrl($parentType, $parentId);
}
/*----------------- My parts */
/**
* @param int $parentId
* @param string $parentType
* @param string $objectType
* @param array $validMimeTypes
* @param array $extBlackList
* @return mixed|\Symfony\Component\HttpFoundation\Response|Response|ResponseRest
* @throws \Exception
*/
public function saveFileAjaxAction(
$parentId,
$parentType,
$objectType,
$validMimeTypes = array(),
$extBlackList = array()
) {
$this->addModuleResource($parentType);
$this->registerFileModel($parentType);
if (null !== $response = $this->checkAccessForType(AccessManager::UPDATE, $parentType)) {
return $response;
}
$this->checkXmlHttpRequest();
if ($this->getRequest()->isMethod('POST')) {
/** @var UploadedFile $fileBeingUploaded */
$fileBeingUploaded = $this->getRequest()->files->get('file');
try {
if (null !== $fileBeingUploaded) {
$this->processFile(
$fileBeingUploaded,
$parentId,
$parentType,
$objectType,
$validMimeTypes,
$extBlackList
);
}
} catch (ProcessFileException $e) {
return new ResponseRest($e->getMessage(), 'text', $e->getCode());
}
return $this->getImagetTypeUpdateRedirectionUrl($parentType, $parentId);
}
return new Response('', 404);
}
/**
* @param int $imageId
* @param string $parentType
* @return mixed|Response
* @throws \Exception
*/
public function viewImageAction($imageId, $parentType)
{
$this->addModuleResource($parentType);
$this->registerFileModel($parentType);
if (null !== $response = $this->checkAccessForType(AccessManager::UPDATE, $parentType)) {
return $response;
}
$fileManager = $this->getFileManager();
$imageModel = $fileManager->getModelInstance('image', $parentType);
$image = null;
$parentId = null;
if (SelectionContainer::IMAGE_TYPE_LABEL === $parentType) {
$image = SelectionContainerImageQuery::create()->findPk($imageId);
if ($image !== null) {
$parentId = $image->getSelectionContainerId();
}
} else {
$image = SelectionImageQuery::create()->findPk($imageId);
if ($image !== null) {
$parentId = $image->getSelectionId();
}
}
if ($image === null) {
return $this->pageNotFound();
}
$redirectUrl = $this->getImagetTypeUpdateRedirectionUrl($parentType, $parentId);
return $this->render('selection-image-edit', array(
'imageId' => $imageId,
'imageType' => $parentType,
'redirectUrl' => $redirectUrl,
'formId' => $imageModel->getUpdateFormId(),
'breadcrumb' => $image->getBreadcrumb(
$this->getRouter($this->getCurrentRouter()),
$this->container,
'images',
$this->getCurrentEditionLocale()
)
));
}
/**
* @param int $fileId
* @param string $parentType
* @param string $objectType
* @param string $eventName
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function updateFileAction($fileId, $parentType, $objectType, $eventName)
{
$message = false;
$fileManager = $this->getFileManager();
$fileModelInstance = $fileManager->getModelInstance($objectType, $parentType);
$fileUpdateForm = $this->createForm($fileModelInstance->getUpdateFormId());
/** @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);
if (array_key_exists('visible', $data)) {
$file->setVisible($data['visible'] ? 1 : 0);
}
$file->setLocale($data['locale']);
if (array_key_exists('title', $data)) {
$file->setTitle($data['title']);
}
if (array_key_exists('chapo', $data)) {
$file->setChapo($data['chapo']);
}
if (array_key_exists('description', $data)) {
$file->setDescription($data['description']);
}
if (array_key_exists('postscriptum', $data)) {
$file->setPostscriptum($data['postscriptum']);
}
if (isset($data['file'])) {
$file->setFile($data['file']);
}
$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->adminUpadteLogAppend(
$parentType,
sprintf(
'%s with Ref %s (ID %d) modified',
ucfirst($objectType),
$fileUpdated->getTitle(),
$fileUpdated->getId()
),
$fileUpdated->getId()
);
} catch (FormValidationException $e) {
$message = sprintf('Please check your input: %s', $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);
}
if ($this->getRequest()->get('save_mode') === 'close') {
return $this->generateRedirect(
URL::getInstance()->absoluteUrl($file->getRedirectionUrl(), ['current_tab' => 'images'])
);
}
return $this->generateSuccessRedirect($fileUpdateForm);
}
/**
* @param int $imageId
* @param string $parentType
* @return mixed|Response|FileModelInterface
* @throws \Exception
*/
public function updateImageAction($imageId, $parentType)
{
$this->addModuleResource($parentType);
if (null !== $response = $this->checkAccessForType(AccessManager::UPDATE, $parentType)) {
return $response;
}
$this->registerFileModel($parentType);
return $this->updateFileAction($imageId, $parentType, 'image', TheliaEvents::IMAGE_UPDATE);
}
/**
* @param $documentId
* @param string $parentType
* @param string $objectType
* @param string $eventName
* @return \Symfony\Component\HttpFoundation\Response|Response
* @throws \Exception
*/
public function toggleVisibilityFileAction($documentId, $parentType, $objectType, $eventName)
{
$message = null;
$this->addModuleResource($parentType);
$parentId = $this->getRequest()->get('parentId');
$this->registerFileModel($parentType);
$this->checkAccessForType(AccessManager::UPDATE, $parentType);
$this->checkXmlHttpRequest();
$fileManager = $this->getFileManager();
$modelInstance = $fileManager->getModelInstance($objectType, $parentType);
$model = $modelInstance->getQueryInstance()->findPk($documentId);
if ($model === null) {
return $this->pageNotFound();
}
// Feed event
$event = new FileToggleVisibilityEvent(
$modelInstance->getQueryInstance(),
$documentId
);
// Dispatch Event to the Action
try {
$this->dispatch($eventName, $event);
} catch (\Exception $e) {
$message = $this->getTranslator()->trans(
'Fail to update %type% visibility: %err%',
['%type%' => $objectType, '%err%' => $e->getMessage()]
);
}
if (null === $message) {
$message = $this->getTranslator()->trans(
'%type% visibility updated',
['%type%' => ucfirst($objectType)]
);
}
$this->adminUpadteLogAppend($parentType, $message, $documentId);
return $this->generateRedirectFromRoute('selection.update', [], ['selectionId' => $parentId], null);
}
/**
* @param $parentType
* @param $parentId
* @param $objectType
* @param $eventName
* @return Response
* @throws \Exception
*/
public function updateFilePositionAction($parentType, $parentId, $objectType, $eventName)
{
$message = null;
$this->addModuleResource($parentType);
$this->registerFileModel($parentType);
$position = $this->getRequest()->request->get('position');
$this->checkAccessForType(AccessManager::UPDATE, $parentType);
$this->checkXmlHttpRequest();
$fileManager = $this->getFileManager();
$modelInstance = $fileManager->getModelInstance($objectType, $parentType);
$model = $modelInstance->getQueryInstance()->findPk($parentId);
if ($model === null || $position === null) {
return $this->pageNotFound();
}
// Feed event
$event = new UpdateFilePositionEvent(
$modelInstance->getQueryInstance(),
$parentId,
UpdateFilePositionEvent::POSITION_ABSOLUTE,
$position
);
// Dispatch Event to the Action
try {
$this->dispatch($eventName, $event);
} catch (\Exception $e) {
$message = $this->getTranslator()->trans(
'Fail to update %type% position: %err%',
['%type%' => $objectType, '%err%' => $e->getMessage()]
);
}
if (null === $message) {
$message = $this->getTranslator()->trans(
'%type% position updated',
['%type%' => ucfirst($objectType)]
);
}
return new Response($message);
}
/**
* @param string $type
* @param $message string
* @param string|null $resourceId
*/
protected function adminUpadteLogAppend($type, $message, $resourceId = null)
{
$this->adminLogAppend(
$this->getAdminResources()->getResource($type, ucfirst(Selection::DOMAIN_NAME)),
AccessManager::UPDATE,
$message,
$resourceId
);
}
/**
* @param string $type
* @throws \Exception
*/
protected function addModuleResource($type)
{
$data = [strtoupper($type) => "admin.selection"];
$module = ucfirst(Selection::DOMAIN_NAME);
/** @noinspection PhpParamsInspection */
$this->getAdminResources()->addModuleResources($data, $module);
}
/**
* @param string $access
* @param string $type
* @return mixed null if authorization is granted, or a Response object which contains the error page otherwise
*/
protected function checkAccessForType($access, $type)
{
return $this->checkAuth(
$this->getAdminResources()->getResource($type, ucfirst(Selection::DOMAIN_NAME)),
array(),
$access
);
}
/**
* @param string $type
*/
private function registerFileModel($type)
{
$this->getFileManager()->addFileModel(
'image',
$type,
$type === 'SelectionContainer' ? SelectionContainerImage::class : SelectionImage::class
);
}
private function getImagetTypeUpdateRedirectionUrl($parentType, $parentId)
{
if ($parentType === SelectionContainer::IMAGE_TYPE_LABEL) {
return $this->generateRedirectFromRoute('admin.selection.container.update', [], ['selectionContainerId' => $parentId, 'current_tab' => 'images'], null);
}
return $this->generateRedirectFromRoute('selection.update', [], ['selectionId' => $parentId, 'current_tab' => 'images'], null);
}
}

View File

@@ -0,0 +1,362 @@
<?php
/**
* Created by PhpStorm.
* User: audreymartel
* Date: 10/07/2018
* Time: 09:38
*/
namespace Selection\Controller;
use Propel\Runtime\ActiveQuery\Criteria;
use Selection\Event\SelectionContainerEvent;
use Selection\Event\SelectionEvents;
use Selection\Form\SelectionCreateForm;
use Selection\Model\SelectionContainer;
use Selection\Model\SelectionContainerQuery;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Thelia\Controller\Admin\AbstractSeoCrudController;
use Thelia\Core\Security\AccessManager;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Form\BaseForm;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Tools\URL;
class SelectionContainerUpdateController extends AbstractSeoCrudController
{
public function __construct()
{
parent::__construct(
'selection_container',
'selection_container_id',
'order',
AdminResources::MODULE,
SelectionEvents::SELECTION_CONTAINER_CREATE,
SelectionEvents::SELECTION_CONTAINER_UPDATE,
SelectionEvents::SELECTION_CONTAINER_DELETE,
null,
SelectionEvents::SELECTION_CONTAINER_UPDATE_POSITION,
SelectionEvents::SELECTION_CONTAINER_UPDATE_SEO,
'Selection'
);
}
/**
* Return the creation form for this object
* @return BaseForm
*/
protected function getCreationForm()
{
return $this->createForm('admin.selection.container.create');
}
/**
* Return the update form for this object
* @param array $data
* @return BaseForm
*/
protected function getUpdateForm($data = [])
{
if (!is_array($data)) {
$data = array();
}
return $this->createForm('admin.selection.container.update', 'form', $data);
}
/**
* Hydrate the update form for this object, before passing it to the update template
* @param SelectionContainer $object
* @return BaseForm
*/
protected function hydrateObjectForm($object)
{
$this->hydrateSeoForm($object);
$data = array(
'selection_container_id'=> $object->getId(),
'id' => $object->getId(),
'locale' => $object->getLocale(),
'selection_container_code' => $object->getCode(),
'selection_container_chapo' => $object->getChapo(),
'selection_container_title' => $object->getTitle(),
'selection_container_description' => $object->getDescription(),
'selection_container_postscriptum' => $object->getPostscriptum(),
'current_id' => $object->getId(),
);
return $this->getUpdateForm($data);
}
/**
* Creates the creation event with the provided form data
* @param mixed $formData
* @return \Thelia\Core\Event\ActionEvent
*/
protected function getCreationEvent($formData)
{
$event = new SelectionContainerEvent();
$event->setTitle($formData['title']);
$event->setCode($formData['code']);
$event->setChapo($formData['chapo']);
$event->setDescription($formData['description']);
$event->setPostscriptum($formData['postscriptum']);
$event->setLocale($this->getCurrentEditionLocale());
return $event;
}
/**
* Creates the update event with the provided form data
* @param mixed $formData
* @return \Thelia\Core\Event\ActionEvent
*/
protected function getUpdateEvent($formData)
{
$selectionContainer = SelectionContainerQuery::create()->findPk($formData['selection_container_id']);
$event = new SelectionContainerEvent($selectionContainer);
$event->setId($formData['selection_container_id']);
$event->setCode($formData['selection_container_code']);
$event->setTitle($formData['selection_container_title']);
$event->setChapo($formData['selection_container_chapo']);
$event->setDescription($formData['selection_container_description']);
$event->setPostscriptum($formData['selection_container_postscriptum']);
$event->setLocale($this->getCurrentEditionLocale());
return $event;
}
/**
* Creates the delete event with the provided form data
* @return \Thelia\Core\Event\ActionEvent
*/
protected function getDeleteEvent()
{
$event = new SelectionContainerEvent();
$selectionId = $this->getRequest()->request->get('selection_container_id');
$event->setId($selectionId);
return $event;
}
/**
* Return true if the event contains the object, e.g. the action has updated the object in the event.
* @param SelectionContainerEvent $event
* @return bool
*/
protected function eventContainsObject($event)
{
return $event->hasSelection();
}
/**
* Get the created object from an event.
* @param SelectionContainerEvent $event
* @return SelectionContainer
*/
protected function getObjectFromEvent($event)
{
return $event->getSelectionContainer();
}
/**
* Load an existing object from the database
*/
protected function getExistingObject()
{
$selectionContainer = SelectionContainerQuery::create()
->findPk($this->getRequest()->get('selection_container_id', 0));
if (null !== $selectionContainer) {
$selectionContainer->setLocale($this->getCurrentEditionLocale());
}
return $selectionContainer;
}
/**
* Returns the object label form the object event (name, title, etc.)
* @param SelectionContainer|null $object
* @return string
*/
protected function getObjectLabel($object)
{
return empty($object) ? '' : $object->getTitle();
}
/**
* Returns the object ID from the object
* @param SelectionContainer|null $object
* @return int
*/
protected function getObjectId($object)
{
return $object->getId();
}
/**
* Render the main list template
* @param mixed $currentOrder , if any, null otherwise.
* @return \Thelia\Core\HttpFoundation\Response
*/
protected function renderListTemplate($currentOrder)
{
return $this->render(
'selection-list',
['order' => $currentOrder]
);
}
/**
* Render the edition template
* @return \Thelia\Core\HttpFoundation\Response
*/
protected function renderEditionTemplate()
{
$selectionContainerId = $this->getRequest()->get('selection_container_id');
$currentTab = $this->getRequest()->get('current_tab');
return $this->render(
"container-edit",
[
'selection_container_id' => $selectionContainerId,
'current_tab' => $currentTab
]
);
}
/**
* Must return a RedirectResponse instance
* @return RedirectResponse
*/
protected function redirectToEditionTemplate()
{
$id = $this->getRequest()->get('selection_container_id');
return new RedirectResponse(
URL::getInstance()->absoluteUrl(
"/admin/selection/container/update/".$id
)
);
}
/**
* Must return a RedirectResponse instance
* @return \Symfony\Component\HttpFoundation\RedirectResponse
*/
protected function redirectToListTemplate()
{
return new RedirectResponse(
URL::getInstance()->absoluteUrl("/admin/selection")
);
}
/**
* Online status toggle
*/
public function setToggleVisibilityAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) {
return $response;
}
$event = new SelectionContainerEvent($this->getExistingObject());
try {
$this->dispatch(SelectionEvents::SELECTION_CONTAINER_TOGGLE_VISIBILITY, $event);
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
// Ajax response -> no action
return $this->nullResponse();
}
public function createSelectionContainerAction()
{
$form = new SelectionCreateForm($this->getRequest());
try {
$validForm = $this->validateForm($form);
$data = $validForm->getData();
$title = $data['title'];
$chapo = $data['chapo'];
$description = $data['description'];
$postscriptum = $data['postscriptum'];
$date = new \DateTime();
$selectionContainer = new SelectionContainer();
$lastSelection = SelectionContainerQuery::create()->orderByPosition(Criteria::DESC)->findOne();
if (null !== $lastSelection) {
$position = $lastSelection->getPosition() + 1;
} else {
$position = 1;
}
$selectionContainer
->setCreatedAt($date->format('Y-m-d H:i:s'))
->setUpdatedAt($date->format('Y-m-d H:i:s'))
->setVisible(1)
->setPosition($position)
->setLocale($this->getCurrentEditionLocale())
->setTitle($title)
->setChapo($chapo)
->setDescription($description)
->setPostscriptum($postscriptum);
$selectionContainer->save();
return $this->generateRedirect("/admin/selection");
} catch (FormValidationException $ex) {
// Form cannot be validated
$error_msg = $this->createStandardFormValidationErrorMessage($ex);
} catch (\Exception $ex) {
// Any other error
$error_msg = $ex->getMessage();
}
if (false !== $error_msg) {
$this->setupFormErrorContext(
$this->getTranslator()->trans("%obj creation", ['%obj' => $this->objectName]),
$error_msg,
$form,
$ex
);
// At this point, the form has error, and should be redisplayed.
return $this->renderList();
}
}
/**
* Show the default template : selectionList
* display selections inide the container
* @param $selectionContainerId
* @return \Thelia\Core\HttpFoundation\Response
*/
public function viewAction($selectionContainerId)
{
$this->getRequest()->request->set("selectionContainerId", $selectionContainerId);
$selectionContainer = $this->getExistingObject();
if (!is_null($selectionContainer)) {
$changeForm = $this->hydrateObjectForm($selectionContainer);
$this->getParserContext()->addForm($changeForm);
}
return $this->render("container-view",
array(
'selected_container_id' => $selectionContainerId
));
}
/**
* @param $selectionContainerId
* @return \Thelia\Core\HttpFoundation\Response
*/
public function updateContainerAction($selectionContainerId)
{
$this->getRequest()->request->set("selection_container_id", $selectionContainerId);
return parent::updateAction();
}
public function processUpdateSeoAction()
{
$selectionContainerId = $this->getRequest()->get('current_id');
$this->getRequest()->request->set("selection_container_id", $selectionContainerId);
return parent::processUpdateSeoAction();
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Selection\Controller;
use Thelia\Controller\Admin\BaseAdminController;
use Thelia\Core\Event\UpdatePositionEvent;
class SelectionController extends BaseAdminController
{
/**
* Show the default template : selectionList
*
* @return \Thelia\Core\HttpFoundation\Response
*/
public function viewAction()
{
return $this->render(
"selection-list",
[
'selection_order' => $this->getAttributeSelectionOrder(),
'selection_container_order' => $this->getAttributeContainerOrder()
]
);
}
private function getAttributeSelectionOrder()
{
return $this->getListOrderFromSession(
'selection',
'selection_order',
'manual'
);
}
private function getAttributeContainerOrder()
{
return $this->getListOrderFromSession(
'selectioncontainer',
'selection_container_order',
'manual'
);
}
protected function createUpdatePositionEvent($positionChangeMode, $positionValue)
{
return new UpdatePositionEvent(
$this->getRequest()->get('selection_id', null),
$positionChangeMode,
$positionValue
);
}
}

View File

@@ -0,0 +1,172 @@
<?php
namespace Selection\Controller;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\Join;
use Selection\Model\Map\SelectionContentTableMap;
use Selection\Model\SelectionContent;
use Selection\Model\SelectionContentQuery;
use Selection\Selection;
use Thelia\Controller\Admin\BaseAdminController;
use Thelia\Model\Content;
use Thelia\Model\ContentFolder;
use Thelia\Model\ContentFolderQuery;
use Thelia\Model\ContentQuery;
use Thelia\Model\Map\ContentTableMap;
class SelectionRelatedContentController extends BaseAdminController
{
protected $currentRouter = Selection::ROUTER;
/**
* Return content id & title
*
* @return \Thelia\Core\HttpFoundation\Response
*/
public function getContentRelated()
{
$folderId = $this->getRequest()->get('folderID');
$contentCategory = ContentFolderQuery::create();
$lang = $this->getRequest()->getSession()->get('thelia.current.lang');
$result = array();
if ($folderId !== null) {
$contentCategory->filterByFolderId($folderId)->find();
if ($contentCategory !== null) {
/** @var ContentFolder $item */
foreach ($contentCategory as $item) {
$content = ContentQuery::create()
->filterById($item->getContentId())
->findOne();
$result[] =
[
'id' => $content->getId(),
'title' => $content->getTranslation($lang->getLocale())->getTitle()
];
}
}
}
return $this->jsonResponse(json_encode($result));
}
/**
* Add content to current selection
*
* @return \Thelia\Core\HttpFoundation\Response
* @throws \Propel\Runtime\Exception\PropelException
*/
public function addContentRelated()
{
$contentId = $this->getRequest()->get('contentID');
$selectionID = $this->getRequest()->get('selectionID');
$contentRelated = new SelectionContent();
if ($contentId !== null) {
$SelectionContent = SelectionContentQuery::create()
->filterBySelectionId($selectionID)
->filterByContentId($contentId)
->findOne();
if (is_null($SelectionContent)) {
$contentRelated->setSelectionId($selectionID);
$contentRelated->setContentId($contentId);
$position = SelectionContentQuery::create()
->filterBySelectionId($selectionID)
->orderByPosition(Criteria::DESC)
->select('position')
->findOne();
if (null === $position) {
$contentRelated->setPosition(1);
} else {
$contentRelated->setPosition($position+1);
}
$contentRelated->save();
}
$lang = $this->getRequest()->getSession()->get('thelia.current.lang');
$search = ContentQuery::create();
$selectionContentRelated = new Join(
ContentTableMap::ID,
SelectionContentTableMap::CONTENT_ID,
Criteria::INNER_JOIN
);
$search->addJoinObject($selectionContentRelated, 'selectionContentRelated');
$search->addJoinCondition(
'selectionContentRelated',
SelectionContentTableMap::SELECTION_ID.'='.$selectionID
);
$search->find();
/** @var Content $row */
foreach ($search as $row) {
$selectionContentPos = SelectionContentQuery::create()
->filterBySelectionId($selectionID)
->filterByContentId($row->getId())
->findOne();
$result = [
'id' => $row->getId() ,
'title' => $row->getTranslation($lang->getLocale())->getTitle(),
'position' => $selectionContentPos->getPosition()
];
}
}
return $this->render('related/contentRelated', ['selection_id' => $selectionID]);
}
/**
* Show content related to a selection
*
* @param null $p
* @return array|\Thelia\Core\HttpFoundation\Response
* @throws \Propel\Runtime\Exception\PropelException
*/
public function showContent($p = null)
{
$selectionID = $this->getRequest()->get('selectionID');
$lang = $this->getRequest()->getSession()->get('thelia.current.lang');
$search = ContentQuery::create();
$selectionContentRelated = new Join(
ContentTableMap::ID,
SelectionContentTableMap::CONTENT_ID,
Criteria::INNER_JOIN
);
$search->addJoinObject($selectionContentRelated, 'selectionContentRelated');
$search->addJoinCondition(
'selectionContentRelated',
SelectionContentTableMap::SELECTION_ID.'='.$selectionID
);
$search->find();
/** @var Content $row */
foreach ($search as $row) {
$selectionContentPos = SelectionContentQuery::create()
->filterBySelectionId($selectionID)
->filterByContentId($row->getId())
->findOne();
$result = [
'id' => $row->getId() ,
'title' => $row->getTranslation($lang->getLocale())->getTitle(),
'position' => $selectionContentPos->getPosition()
];
}
if ($p === null) {
return $this->render('related/contentRelated', ['selection_id' => $selectionID]);
} else {
return $result;
}
}
}

View File

@@ -0,0 +1,179 @@
<?php
namespace Selection\Controller;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\Join;
use Selection\Model\Map\SelectionProductTableMap;
use Selection\Model\SelectionProduct;
use Selection\Model\SelectionProductQuery;
use Thelia\Controller\Admin\BaseAdminController;
use Thelia\Core\Event\Loop\LoopExtendsBuildModelCriteriaEvent;
use Thelia\Model\Map\ProductTableMap;
use Thelia\Model\Product;
use Thelia\Model\ProductCategory;
use Thelia\Model\ProductCategoryQuery;
use Thelia\Model\ProductQuery;
class SelectionRelatedProductController extends BaseAdminController
{
/**
* Return product which they are related to a category id in a select.
*
* @return \Thelia\Core\HttpFoundation\Response
*/
public function getProductRelated()
{
$categoryID = $this->getRequest()->get('categoryID');
$lang = $this->getRequest()->getSession()->get('thelia.current.lang');
$productCategory = ProductCategoryQuery::create();
$result = array();
if ($categoryID !== null) {
$productCategory->filterByCategoryId($categoryID)
->find();
if ($productCategory !== null) {
/** @var ProductCategory $item */
foreach ($productCategory as $item) {
$product = ProductQuery::create()
->filterById($item->getProductId())
->filterByVisible(1)
->findOne();
if (null !== $product) {
$result[] = [
'id' => $product->getId(),
'title' => $product->getTranslation($lang->getLocale())->getTitle()
];
}
}
}
}
return $this->jsonResponse(json_encode($result));
}
/**
* Add product to the current selection
*
* @return \Thelia\Core\HttpFoundation\Response
* @throws \Propel\Runtime\Exception\PropelException
*/
public function addProductRelated()
{
$productID = $this->getRequest()->get('productID');
$selectionID = $this->getRequest()->get('selectionID');
$lang = $this->getRequest()->getSession()->get('thelia.current.lang');
$productRelated = new SelectionProduct();
if ($productID !== null) {
$SelectionProduit = SelectionProductQuery::create()
->filterByProductId($productID)
->filterBySelectionId($selectionID)
->findOne();
if (is_null($SelectionProduit)) {
//Insert in the table Selection_product
$productRelated->setSelectionId($selectionID);
$productRelated->setProductId($productID);
$position = SelectionProductQuery::create()
->filterBySelectionId($selectionID)
->orderByPosition(Criteria::DESC)
->select('position')
->findOne();
if (null === $position) {
$productRelated->setPosition(1);
} else {
$productRelated->setPosition($position + 1);
}
$productRelated->save();
}
/** @var \Thelia\Model\Product $search */
/** @var LoopExtendsBuildModelCriteriaEvent $event */
$search = ProductQuery::create();
$selectionProductRelated = new Join(
ProductTableMap::ID,
SelectionProductTableMap::PRODUCT_ID,
Criteria::INNER_JOIN
);
$search->addJoinObject($selectionProductRelated, 'selectionProductRelated');
$search->addJoinCondition(
'selectionProductRelated',
SelectionProductTableMap::SELECTION_ID.' = '.$selectionID
);
$search->find();
$result = array();
/** @var Product $row */
foreach ($search as $row) {
$selectionProductPos = SelectionProductQuery::create()
->filterBySelectionId($selectionID)
->filterByProductId($row->getId())
->findOne();
$result = [
'id' => $row->getId() ,
'title' => $row->getTranslation($lang->getLocale())->getTitle(),
'position' => $selectionProductPos->getPosition(),
];
}
}
return $this->render('related/productRelated', ['selection_id' => $selectionID]);
}
/**
* Show product related to a selection
*
* @param null $p
* @return array|\Thelia\Core\HttpFoundation\Response
* @throws \Propel\Runtime\Exception\PropelException
*/
public function showProduct($p = null)
{
$selectionID = $this->getRequest()->get('selectionID');
$lang = $this->getRequest()->getSession()->get('thelia.current.lang');
/** @var \Thelia\Model\Product $search */
/** @var LoopExtendsBuildModelCriteriaEvent $event */
$search = ProductQuery::create();
$selectionProductRelated = new Join(
ProductTableMap::ID,
SelectionProductTableMap::PRODUCT_ID,
Criteria::INNER_JOIN
);
$search->addJoinObject($selectionProductRelated, 'selectionProductRelated');
$search->addJoinCondition(
'selectionProductRelated',
SelectionProductTableMap::SELECTION_ID.' = '.$selectionID
);
$search->find();
$result = array();
/** @var Product $row */
foreach ($search as $row) {
$selectionProductPos = SelectionProductQuery::create()
->filterBySelectionId($selectionID)
->filterByProductId($row->getId())
->findOne();
$result = [
'id' => $row->getId() ,
'title' => $row->getTranslation($lang->getLocale())->getTitle(),
'position' => $selectionProductPos->getPosition(),
];
}
if ($p === null) {
return $this->render('related/productRelated', ['selection_id' => $selectionID]);
} else {
return $result;
}
}
}

View File

@@ -0,0 +1,466 @@
<?php
namespace Selection\Controller;
use Propel\Runtime\ActiveQuery\Criteria;
use Selection\Event\SelectionContainerEvent;
use Selection\Event\SelectionEvent;
use Selection\Event\SelectionEvents;
use Selection\Form\SelectionCreateForm;
use Selection\Form\SelectionUpdateForm;
use Selection\Model\Selection as SelectionModel;
use Selection\Model\SelectionContainer;
use Selection\Model\SelectionContainerAssociatedSelection;
use Selection\Model\SelectionContentQuery;
use Selection\Model\SelectionI18nQuery;
use Selection\Model\SelectionProductQuery;
use Selection\Model\SelectionQuery;
use Selection\Selection;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Thelia\Controller\Admin\AbstractSeoCrudController;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Core\Security\AccessManager;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Log\Tlog;
use Thelia\Tools\URL;
class SelectionUpdateController extends AbstractSeoCrudController
{
protected $currentRouter = Selection::ROUTER;
protected $deleteGroupEventIdentifier = SelectionEvents::SELECTION_CONTAINER_DELETE;
/**
* Save content of the selection
*
* @return \Symfony\Component\HttpFoundation\Response|\Thelia\Core\HttpFoundation\Response
* @throws \Propel\Runtime\Exception\PropelException
*/
public function saveSelection()
{
$form = new SelectionUpdateForm($this->getRequest());
$validForm = $this->validateForm($form);
$data = $validForm->getData();
$selectionID = $data['selection_id'];
$selectionCode = $data['selection_code'];
$selectionTitle = $data['selection_title'];
$selectionChapo = $data['selection_chapo'];
$selectionDescription = $data['selection_description'];
$selectionPostscriptum = $data['selection_postscriptum'];
$aSelection = SelectionQuery::create()->findPk($selectionID);
$aSelection
->setCode($selectionCode)
->setLocale($this->getCurrentEditionLocale())
->setTitle($selectionTitle)
->setChapo($selectionChapo)
->setDescription($selectionDescription)
->setPostscriptum($selectionPostscriptum)
->save();
if ($validForm->get('save_and_close')->isClicked()) {
return $this->render("electionlist");
}
return $this->generateRedirectFromRoute('selection.update', [], ['selectionId' => $selectionID], null);
}
public function createSelection()
{
$form = new SelectionCreateForm($this->getRequest());
try {
$validForm = $this->validateForm($form);
$data = $validForm->getData();
$code = $data['code'];
$title = $data['title'];
$chapo = $data['chapo'];
$description = $data['description'];
$postscriptum = $data['postscriptum'];
$containerId = (int) $data['container_id'];
$date = new \DateTime();
$selection = new SelectionModel();
$lastSelectionQuery = SelectionQuery::create()->orderByPosition(Criteria::DESC);
if ($containerId > 0) {
$lastSelectionQuery
->useSelectionContainerAssociatedSelectionQuery('toto', Criteria::LEFT_JOIN)
->filterBySelectionContainerId($containerId)
->endUse();
}
$position = 1;
if (null !== $lastSelection = $lastSelectionQuery->findOne()) {
$position = $lastSelection->getPosition() + 1;
}
$selection
->setCreatedAt($date->format('Y-m-d H:i:s'))
->setUpdatedAt($date->format('Y-m-d H:i:s'))
->setVisible(1)
->setCode($code)
->setPosition($position)
->setLocale($this->getCurrentEditionLocale())
->setTitle($title)
->setChapo($chapo)
->setDescription($description)
->setPostscriptum($postscriptum)
->save()
;
if ($containerId > 0) {
// Required, see Selection::preInsert();
$selection->setPosition($position)->save();
(new SelectionContainerAssociatedSelection())
->setSelectionContainerId($containerId)
->setSelectionId($selection->getId())
->save();
return $this->generateRedirect(URL::getInstance()->absoluteUrl("/admin/selection/container/view/" . $containerId));
}
return $this->generateRedirect(URL::getInstance()->absoluteUrl("/admin/selection"));
} catch (FormValidationException $ex) {
// Form cannot be validated
$error_msg = $this->createStandardFormValidationErrorMessage($ex);
} catch (\Exception $ex) {
// Any other error
$error_msg = $ex->getMessage();
}
if (false !== $error_msg) {
$this->setupFormErrorContext(
$this->getTranslator()->trans("%obj creation", ['%obj' => $this->objectName]),
$error_msg,
$form,
$ex
);
// At this point, the form has error, and should be redisplayed.
return $this->renderList();
}
}
public function updateSelectionPositionAction()
{
if (null !== $response = $this->checkAuth(array(AdminResources::MODULE), array(Selection::DOMAIN_NAME), AccessManager::UPDATE)) {
return $response;
}
try {
$mode = $this->getRequest()->get('mode', null);
if ($mode === 'up') {
$mode = UpdatePositionEvent::POSITION_UP;
} elseif ($mode === 'down') {
$mode = UpdatePositionEvent::POSITION_DOWN;
} else {
$mode = UpdatePositionEvent::POSITION_ABSOLUTE;
}
$position = $this->getRequest()->get('position', null);
$event = $this->createUpdateSelectionPositionEvent($mode, $position);
$this->dispatch(SelectionEvents::SELECTION_UPDATE_POSITION, $event);
} catch (\Exception $ex) {
Tlog::getInstance()->error($ex->getMessage());
}
return $this->forward('Selection\Controller\SelectionController::viewAction');
}
public function deleteRelatedProduct()
{
$selectionID = $this->getRequest()->get('selectionID');
$productID = $this->getRequest()->get('productID');
try {
$selection = SelectionProductQuery::create()
->filterByProductId($productID)
->findOneBySelectionId($selectionID);
if (null !== $selection) {
$selection->delete();
}
} catch (\Exception $e) {
Tlog::getInstance()->error($e->getMessage());
}
return $this->generateRedirectFromRoute('selection.update', [], ['selectionId' => $selectionID], null);
}
public function deleteRelatedContent()
{
$selectionID = $this->getRequest()->get('selectionID');
$contentID = $this->getRequest()->get('contentID');
try {
$selection = SelectionContentQuery::create()
->filterByContentId($contentID)
->findOneBySelectionId($selectionID);
if (null !== $selection) {
$selection->delete();
}
} catch (\Exception $e) {
Tlog::getInstance()->error($e->getMessage());
}
return $this->generateRedirectFromRoute('selection.update', [], ['selectionId' => $selectionID], null);
}
/*-------------------------- Part Controller SEO */
public function __construct()
{
parent::__construct(
'selection',
'selection_id',
'order',
AdminResources::MODULE,
SelectionEvents::SELECTION_CREATE,
SelectionEvents::SELECTION_UPDATE,
SelectionEvents::SELECTION_DELETE,
null,
SelectionEvents::RELATED_PRODUCT_UPDATE_POSITION,
SelectionEvents::SELECTION_UPDATE_SEO,
Selection::DOMAIN_NAME
);
}
protected function getCreationForm()
{
return $this->createForm('admin.selection.update');
}
protected function getUpdateForm($data = array())
{
if (!is_array($data)) {
$data = array();
}
return $this->createForm('admin.selection.update', 'form', $data);
}
/**
* $object Selection
* @param \Selection\Model\Selection $selection
* @return \Thelia\Form\BaseForm
* @throws \Propel\Runtime\Exception\PropelException
*/
protected function hydrateObjectForm($selection)
{
$this->hydrateSeoForm($selection);
$associatedContainer = $selection->getSelectionContainerAssociatedSelections();
$container = null;
if (!empty($associatedContainer) && count($associatedContainer) > 0) {
/** @var SelectionContainerAssociatedSelection[] $associatedContainer */
$container = $associatedContainer[0]->getSelectionContainerId();
}
$data = array(
'selection_id' => $selection->getId(),
'selection_container' => $container,
'id' => $selection->getId(),
'locale' => $selection->getLocale(),
'selection_code' => $selection->getCode(),
'selection_title' => $selection->getTitle(),
'selection_chapo' => $selection->getChapo(),
'selection_description' => $selection->getDescription(),
'selection_postscriptum'=> $selection->getPostscriptum(),
'current_id' => $selection->getId(),
);
return $this->getUpdateForm($data);
}
protected function getCreationEvent($formData)
{
$event = new SelectionEvent();
$event->setCode($formData['code']);
$event->setTitle($formData['title']);
$event->setChapo($formData['chapo']);
$event->setDescription($formData['description']);
$event->setPostscriptum($formData['postscriptum']);
$event->setContainerId($formData['container_id']);
return $event;
}
protected function getUpdateEvent($formData)
{
$selection = SelectionQuery::create()->findPk($formData['selection_id']);
$event = new SelectionEvent($selection);
$event->setId($formData['selection_id']);
$event->setContainerId($formData['selection_container_id']);
$event->setCode($formData['selection_code']);
$event->setTitle($formData['selection_title']);
$event->setChapo($formData['selection_chapo']);
$event->setDescription($formData['selection_description']);
$event->setPostscriptum($formData['selection_postscriptum']);
$event->setLocale($this->getCurrentEditionLocale());
return $event;
}
protected function getDeleteEvent()
{
$event = new SelectionEvent();
$selectionId = $this->getRequest()->request->get('selection_id');
$event->setId($selectionId);
return $event;
}
protected function getDeleteGroupEvent()
{
$event = new SelectionContainerEvent();
$selectionGroupId = $this->getRequest()->request->get('selection_group_id');
$event->setId($selectionGroupId);
return $event;
}
protected function eventContainsObject($event)
{
return $event->hasSelection();
}
protected function getObjectFromEvent($event)
{
return $event->getSelection();
}
protected function getExistingObject()
{
$selection = SelectionQuery::create()
->findPk($this->getRequest()->get('selectionId', 0));
if (null !== $selection) {
$selection->setLocale($this->getCurrentEditionLocale());
}
return $selection;
}
protected function getObjectLabel($object)
{
return '';
}
/**
* Returns the object ID from the object
* @param \Selection\Model\Selection $object
* @return int selection id
*/
protected function getObjectId($object)
{
return $object->getId();
}
protected function renderListTemplate($currentOrder)
{
$this->getParser()->assign("order", $currentOrder);
return $this->render('selection-list');
}
protected function renderEditionTemplate()
{
$selectionId = $this->getRequest()->get('selectionId');
$currentTab = $this->getRequest()->get('current_tab');
return $this->render(
'selection-edit',
[
'selection_id' => $selectionId,
'current_tab' => $currentTab
]
);
}
protected function redirectToEditionTemplate()
{
if (!$id = $this->getRequest()->get('selection_id')) {
$id = $this->getRequest()->get('admin_selection_update')['selection_id'];
}
return new RedirectResponse(
URL::getInstance()->absoluteUrl(
"/admin/selection/update/".$id
)
);
}
protected function redirectToListTemplate()
{
return new RedirectResponse(
URL::getInstance()->absoluteUrl("/admin/selection")
);
}
/**
* Online status toggle product
*/
public function setToggleVisibilityAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) {
return $response;
}
$event = new SelectionEvent($this->getExistingObject());
try {
$this->dispatch(SelectionEvents::SELECTION_TOGGLE_VISIBILITY, $event);
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
// Ajax response -> no action
return $this->nullResponse();
}
protected function createUpdatePositionEvent($positionChangeMode, $positionValue)
{
return new UpdatePositionEvent(
$this->getRequest()->get('product_id', null),
$positionChangeMode,
$positionValue,
$this->getRequest()->get('selection_id', null)
);
}
protected function createUpdateSelectionPositionEvent($positionChangeMode, $positionValue)
{
return new UpdatePositionEvent(
$this->getRequest()->get('selection_id', null),
$positionChangeMode,
$positionValue,
Selection::getModuleId()
);
}
protected function performAdditionalUpdatePositionAction($positionEvent)
{
$selectionID = $this->getRequest()->get('selection_id');
return $this->generateRedirectFromRoute('selection.update', [], ['selectionId' => $selectionID], null);
}
protected function performAdditionalDeleteAction($deleteEvent)
{
$containerId = (int) $this->getRequest()->get('container_id');
if ($containerId > 0) {
return $this->generateRedirect(URL::getInstance()->absoluteUrl("/admin/selection/container/view/" . $containerId));
}
return null;
}
public function processUpdateSeoAction()
{
$selectionId = $this->getRequest()->get('current_id');
$this->getRequest()->request->set("selectionId", $selectionId);
return parent::processUpdateSeoAction();
}
}