Rajout du dossier core + MAJ .gitignore

This commit is contained in:
2019-11-21 12:48:42 +01:00
parent f4aabcb9b1
commit 459f8966b0
10448 changed files with 1835600 additions and 1 deletions

View File

@@ -0,0 +1,505 @@
<?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\Controller\Api;
use Propel\Runtime\Propel;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Thelia\Core\HttpFoundation\JsonResponse;
use Thelia\Core\Security\AccessManager;
/**
* Class AbstractCrudApiController
* @package Thelia\Controller\Api
* @author Benjamin Perche <bperche@openstudio.fr>
*/
abstract class AbstractCrudApiController extends BaseApiController
{
/**
* @var string
*
* The entity name to display errors
*/
protected $objName;
/**
* @var mixed|array
*
* ACL resources used for rights checking
*/
protected $resources;
/**
* @var array
*
* Events to call on entity creation
*/
protected $createEvents;
/**
* @var array
*
* Events to call on entity update
*/
protected $updateEvents;
/**
* @var array
*
* Events to call on entity deletion
*/
protected $deleteEvents;
/**
* @var mixed|array
*
* ACL modules used for rights checking
*/
protected $modules;
/**
* @var integer
*
* limit for the list operation
*/
protected $defaultLoopArgs;
/**
* @var string
*
* The id parameter used to filter in the loop
*/
protected $idParameterName;
/**
* @param $objName
* @param $resources
* @param $createEvents
* @param $updateEvents
* @param $deleteEvents
* @param array $modules The module codes related to the ACL
* @param array $defaultLoopArgs The loop default arguments
* @param string $idParameterName The "id" parameter name in your loop. Generally "id"
*/
public function __construct(
$objName,
$resources,
$createEvents,
$updateEvents,
$deleteEvents,
$modules = [],
$defaultLoopArgs = null,
$idParameterName = "id"
) {
$this->objName = $objName;
$this->resources = $resources;
$this->initializeEvents([
"createEvents" => $createEvents,
"updateEvents" => $updateEvents,
"deleteEvents" => $deleteEvents,
]);
$this->modules = $modules;
$this->defaultLoopArgs = $defaultLoopArgs ?: ["limit" => 10, "offset" => 0, "visible" => "*"];
$this->idParameterName = $idParameterName;
}
/**
* @return JsonResponse
*
* The method provides the "list" feed for an entity.
*/
public function listAction()
{
$this->checkAuth($this->resources, $this->modules, AccessManager::VIEW);
$request = $this->getRequest();
if ($request->query->has('id')) {
$request->query->remove('id');
}
$params = array_merge(
$this->defaultLoopArgs,
$request->query->all()
);
try {
$results = $this->getLoopResults($params);
} catch (\Exception $e) {
throw new HttpException(500, json_encode(["error" => $e->getMessage()]));
}
return JsonResponse::create($results);
}
/**
* @param $entityId
* @return \Symfony\Component\HttpFoundation\Response
*
* This method provides the "GET" feed for an entity,
* you can define a route like this:
*
* <route id="api.my-entity.get" path="/api/my-entity/{entityId}" methods="get">
* <default key="_controller">Thelia:Api\MyEntity:get</default>
* <requirement key="entityId">\d+</requirement>
* </route>
*/
public function getAction($entityId)
{
$this->checkAuth($this->resources, $this->modules, AccessManager::VIEW);
$request = $this->getRequest();
$params = array_merge(
$request->query->all(),
[
$this->idParameterName => $entityId,
]
);
$result = $this->getLoopResults($params);
if ($result->isEmpty()) {
$this->entityNotFound($entityId);
}
return JsonResponse::create($result);
}
/**
* @return JsonResponse
*
* This feed creates your entity.
*/
public function createAction()
{
$this->checkAuth($this->resources, $this->modules, AccessManager::CREATE);
$baseForm = $this->getCreationForm();
$con = Propel::getConnection();
$con->beginTransaction();
try {
$form = $this->validateForm($baseForm);
$data = $form->getData();
$event = $this->getCreationEvent($data);
$dispatcher = $this->getDispatcher();
foreach ($this->createEvents as $eventName) {
$dispatcher->dispatch($eventName, $event);
}
$this->afterCreateEvents($event, $data);
$con->commit();
} catch (HttpException $e) {
$con->rollBack();
return new JsonResponse(["error" => $e->getMessage()], $e->getStatusCode());
} catch (\Exception $e) {
$con->rollBack();
return new JsonResponse(["error" => $e->getMessage()], 500);
}
$obj = $this->extractObjectFromEvent($event);
$id = $this->extractIdFromObject($obj);
return new JsonResponse(
$this->getLoopResults(
array_merge(
$this->getRequest()->query->all(),
[$this->idParameterName => $id]
)
),
201
);
}
/**
* @return JsonResponse
*
* Generic action to update an entity
*/
public function updateAction()
{
$this->checkAuth($this->resources, $this->modules, AccessManager::UPDATE);
$baseForm = $this->getUpdateForm();
$baseForm->getFormBuilder()
->addEventListener(
FormEvents::PRE_SUBMIT,
[$this, "hydrateUpdateForm"]
)
;
$con = Propel::getConnection();
$con->beginTransaction();
try {
$form = $this->validateForm($baseForm);
$data = $form->getData();
$event = $this->getUpdateEvent($data);
$dispatcher = $this->getDispatcher();
foreach ($this->updateEvents as $eventName) {
$dispatcher->dispatch($eventName, $event);
}
$this->afterUpdateEvents($event, $data);
$con->commit();
} catch (HttpException $e) {
$con->rollBack();
return new JsonResponse(["error" => $e->getMessage()], $e->getStatusCode());
} catch (\Exception $e) {
$con->rollBack();
return new JsonResponse(["error" => $e->getMessage()], 500);
}
$obj = $this->extractObjectFromEvent($event);
$id = $this->extractIdFromObject($obj);
return new JsonResponse(
$this->getLoopResults(
array_merge(
$this->getRequest()->query->all(),
[$this->idParameterName => $id]
)
),
201
);
}
/**
* @param $entityId
* @return JsonResponse|\Thelia\Core\HttpFoundation\Response
*
* generic feed for deleting an entity
*/
public function deleteAction($entityId)
{
$this->checkAuth($this->resources, $this->modules, AccessManager::DELETE);
$con = Propel::getConnection();
$con->beginTransaction();
try {
$event = $this->getDeleteEvent($entityId);
$obj = $this->extractObjectFromEvent($event);
if (null === $obj || false === $obj) {
$this->entityNotFound($entityId);
}
$dispatcher = $this->getDispatcher();
foreach ($this->deleteEvents as $eventName) {
$dispatcher->dispatch($eventName, $event);
}
$con->commit();
} catch (HttpException $e) {
$con->rollBack();
return new JsonResponse(["error" => $e->getMessage()], $e->getStatusCode());
} catch (\Exception $e) {
$con->rollBack();
return new JsonResponse(["error" => $e->getMessage()], 500);
}
return $this->nullResponse(204);
}
/**
* @param $loopParams
* @return \Thelia\Core\Template\Element\LoopResult
*
* Returns the current class' loop results with the given parameters
*/
protected function getLoopResults($loopParams)
{
$loop = $this->getLoop();
$loop->initializeArgs(
array_merge($this->defaultLoopArgs, $loopParams)
);
return $loop->exec($pagination);
}
// Helpers
/**
* @param $entityId
*
* Throws a 404 exception building an error message with $this->objName and the entity id
*/
protected function entityNotFound($entityId)
{
throw new NotFoundHttpException(
json_encode([
"error" => sprintf("%s %s %d not found", $this->objName, $this->idParameterName, $entityId)
])
);
}
/**
* @param $eventsDefinition
*
* Register events into the class' variables
*/
protected function initializeEvents($eventsDefinition)
{
foreach ($eventsDefinition as $variableName => $eventValue) {
$value = array();
if (!empty($eventValue) && !is_array($eventValue)) {
$value = [$eventValue];
} elseif (is_array($eventValue)) {
$value = $eventValue;
}
$this->$variableName = $value;
}
}
/**
* @param $locale
* @param string $parameterName
*
* This helper defines the lang into the query ( you can use it to force a lang into a loop )
*/
protected function setLocaleIntoQuery($locale, $parameterName = 'lang')
{
$request = $this->getRequest();
if (!$request->query->has($parameterName)) {
$request->query->set($parameterName, $locale);
}
}
// Inner logic, override those methods to use your logic
/**
* @param mixed $obj
* @return mixed
*
* After having extracted the object, now extract the id.
*/
protected function extractIdFromObject($obj)
{
return $obj->getId();
}
/**
* @param FormEvent $event
*
* This method in called on your update form FormEvents::PRE_SUBMIT event.
*
* You can treat the given form, rewrite some data ...
*/
public function hydrateUpdateForm(FormEvent $event)
{
// This method is called on FormEvents::PRE_SUBMIT
}
/**
* @param Event $event
* @param array $data
*
* Hook after the entity creation
*/
protected function afterCreateEvents(Event $event, array &$data)
{
// This method is called after dispatches in createAction
}
/**
* @param Event $event
* @param array $data
*
* Hook after the entity update
*/
protected function afterUpdateEvents(Event $event, array &$data)
{
// This method is called after dispatches in updateAction
}
// Abstract methods
/**
* @return \Thelia\Core\Template\Element\BaseLoop
*
* Get the entity loop instance
*/
abstract protected function getLoop();
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*
* Gives the form used for entities creation.
*/
abstract protected function getCreationForm(array $data = array());
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*
* Gives the form used for entities update
*/
abstract protected function getUpdateForm(array $data = array());
/**
* @param Event $event
* @return null|mixed
*
* Get the object from the event
*
* if return null or false, the action will throw a 404
*/
abstract protected function extractObjectFromEvent(Event $event);
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on creation.
*/
abstract protected function getCreationEvent(array &$data);
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on update.
*/
abstract protected function getUpdateEvent(array &$data);
/**
* @param mixed $entityId
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on entity deletion.
*/
abstract protected function getDeleteEvent($entityId);
}

View File

@@ -0,0 +1,112 @@
<?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\Controller\Api;
use Symfony\Component\EventDispatcher\Event;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Template\Loop\AttributeAvailability;
/**
* Class AttributeAvController
* @package Thelia\Controller\Api
* @author Benjamin Perche <bperche@openstudio.fr>
*/
class AttributeAvController extends AbstractCrudApiController
{
public function __construct()
{
parent::__construct(
"attribute av",
AdminResources::ATTRIBUTE,
[],
[],
[]
);
}
/**
* @return \Thelia\Core\Template\Element\BaseLoop
*
* Get the entity loop instance
*/
protected function getLoop()
{
return new AttributeAvailability($this->container);
}
/**
* @TODO: Implement Create - Update - Delete
*/
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*
* Gives the form used for entities creation.
*/
protected function getCreationForm(array $data = array())
{
}
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*
* Gives the form used for entities update
*/
protected function getUpdateForm(array $data = array())
{
}
/**
* @param Event $event
* @return null|mixed
*
* Get the object from the event
*
* if return null or false, the action will throw a 404
*/
protected function extractObjectFromEvent(Event $event)
{
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on creation.
*/
protected function getCreationEvent(array &$data)
{
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on update.
*/
protected function getUpdateEvent(array &$data)
{
}
/**
* @param mixed $entityId
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on entity deletion.
*/
protected function getDeleteEvent($entityId)
{
}
}

View File

@@ -0,0 +1,125 @@
<?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\Controller\Api;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Thelia\Controller\a;
use Thelia\Controller\BaseController;
use Thelia\Core\HttpFoundation\Response;
use Thelia\Model\Api;
/**
* Class BaseApiController
* @package Thelia\Controller\Api
* @author Manuel Raynaud <manu@raynaud.io>
*/
class BaseApiController extends BaseController
{
const CONTROLLER_TYPE = 'api';
const EMPTY_FORM_NAME = "thelia.api.empty";
protected $apiUser;
protected $currentRouter = "router.api";
protected function checkAuth($resources, $modules, $accesses)
{
$resources = is_array($resources) ? $resources : array($resources);
$modules = is_array($modules) ? $modules : array($modules);
$accesses = is_array($accesses) ? $accesses : array($accesses);
if (true !== $this->getSecurityContext()->isUserGranted(array("API"), $resources, $modules, $accesses, $this->getApiUser())) {
throw new AccessDeniedHttpException();
}
}
public function setApiUser(Api $apiUser)
{
$this->apiUser = $apiUser;
}
public function getApiUser()
{
return $this->apiUser;
}
/**
* @param null|mixed $template
* @return a ParserInterface instance parser
*/
protected function getParser($template = null)
{
throw new \RuntimeException("The parser is not available in an API controller");
}
/**
* Render the given template, and returns the result as an Http Response.
*
* @param mixed $content the response content
* @param array $args the template arguments
* @param int $status http code status
* @param array $headers The HTTP headers of the response
* @return \Thelia\Core\HttpFoundation\Response
*/
protected function render($content, $args = array(), $status = 200, $headers = array())
{
return Response::create($this->renderRaw($content), $status, $headers);
}
/**
* Render the given template, and returns the result as a string.
*
* @param $content
* @param array $args the template arguments
* @param null $templateDir
*
* @return string
*/
protected function renderRaw($content, $args = array(), $templateDir = null)
{
if (is_array($content)) {
$content = json_encode($content);
}
return $content;
}
/**
* @param $name
* @param string $type
* @param array $data
* @param array $options
* @return \Thelia\Form\BaseForm
*
* Deactivate csrf token by default on API
*/
public function createForm($name, $type = "form", array $data = array(), array $options = array())
{
$options = array_merge(
[
"csrf_protection" => false,
],
$options
);
return parent::createForm($name, $type, $data, $options);
}
/**
* @return string
*/
public function getControllerType()
{
return self::CONTROLLER_TYPE;
}
}

View File

@@ -0,0 +1,112 @@
<?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\Controller\Api;
use Symfony\Component\EventDispatcher\Event;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Template\Loop\Brand;
/**
* Class BrandController
* @package Thelia\Controller\Api
* @author Benjamin Perche <bperche@openstudio.fr>
*/
class BrandController extends AbstractCrudApiController
{
public function __construct()
{
parent::__construct(
"brand",
AdminResources::BRAND,
[],
[],
[]
);
}
/**
* @return \Thelia\Core\Template\Element\BaseLoop
*
* Get the entity loop instance
*/
protected function getLoop()
{
return new Brand($this->container);
}
/**
* @TODO: Implement Create - Update - Delete
*/
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*
* Gives the form used for entities creation.
*/
protected function getCreationForm(array $data = array())
{
}
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*
* Gives the form used for entities update
*/
protected function getUpdateForm(array $data = array())
{
}
/**
* @param Event $event
* @return null|mixed
*
* Get the object from the event
*
* if return null or false, the action will throw a 404
*/
protected function extractObjectFromEvent(Event $event)
{
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on creation.
*/
protected function getCreationEvent(array &$data)
{
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on update.
*/
protected function getUpdateEvent(array &$data)
{
}
/**
* @param mixed $entityId
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on entity deletion.
*/
protected function getDeleteEvent($entityId)
{
}
}

View File

@@ -0,0 +1,152 @@
<?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\Controller\Api;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Form\FormEvent;
use Thelia\Core\Event\Category\CategoryCreateEvent;
use Thelia\Core\Event\Category\CategoryDeleteEvent;
use Thelia\Core\Event\Category\CategoryUpdateEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Template\Loop\Category;
use Thelia\Model\CategoryQuery;
use Thelia\Form\Definition\ApiForm;
/**
* Class CategoryController
* @package Thelia\Controller\Api
* @author Manuel Raynaud <manu@raynaud.io>
*/
class CategoryController extends AbstractCrudApiController
{
public function __construct()
{
parent::__construct(
"category",
AdminResources::CATEGORY,
TheliaEvents::CATEGORY_CREATE,
TheliaEvents::CATEGORY_UPDATE,
TheliaEvents::CATEGORY_DELETE
);
}
/**
* @return \Thelia\Core\Template\Element\BaseLoop
*
* Get the entity loop instance
*/
protected function getLoop()
{
return new Category($this->container);
}
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*/
protected function getCreationForm(array $data = array())
{
return $this->createForm(ApiForm::CATEGORY_CREATION, "form", $data);
}
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*/
protected function getUpdateForm(array $data = array())
{
return $this->createForm(ApiForm::CATEGORY_MODIFICATION, "form", $data, [
'method' => 'PUT',
]);
}
/**
* @param Event $event
* @return null|mixed
*
* Get the object from the event
*
* if return null or false, the action will throw a 404
*/
protected function extractObjectFromEvent(Event $event)
{
return $event->getCategory();
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*/
protected function getCreationEvent(array &$data)
{
$event = new CategoryCreateEvent();
$event
->setLocale($data['locale'])
->setTitle($data['title'])
->setVisible($data['visible'])
->setParent($data['parent'])
;
$this->setLocaleIntoQuery($data["locale"]);
return $event;
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*/
protected function getUpdateEvent(array &$data)
{
$event = new CategoryUpdateEvent($data["id"]);
$event
->setLocale($data['locale'])
->setParent($data['parent'])
->setTitle($data['title'])
->setVisible($data['visible'])
->setChapo($data['chapo'])
->setDescription($data['description'])
->setPostscriptum($data['postscriptum'])
->setDefaultTemplateId($data['default_template_id'])
;
$this->setLocaleIntoQuery($data["locale"]);
return $event;
}
/**
* @param mixed $entityId
* @return \Symfony\Component\EventDispatcher\Event
*/
protected function getDeleteEvent($entityId)
{
$event = new CategoryDeleteEvent($entityId);
$event->setCategory(CategoryQuery::create()->findPk($entityId));
return $event;
}
public function hydrateUpdateForm(FormEvent $event)
{
$id = $event->getData()["id"];
if (null === CategoryQuery::create()->findPk($id)) {
$this->entityNotFound($id);
}
}
}

View File

@@ -0,0 +1,112 @@
<?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\Controller\Api;
use Symfony\Component\EventDispatcher\Event;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Template\Loop\Country;
/**
* Class CountryController
* @package Thelia\Controller\Api
* @author Benjamin Perche <bperche@openstudio.fr>
*/
class CountryController extends AbstractCrudApiController
{
public function __construct()
{
parent::__construct(
"country",
AdminResources::COUNTRY,
[],
[],
[]
);
}
/**
* @return \Thelia\Core\Template\Element\BaseLoop
*
* Get the entity loop instance
*/
protected function getLoop()
{
return new Country($this->container);
}
/**
* @TODO: implement Create - Update - Delete
*/
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*
* Gives the form used for entities creation.
*/
protected function getCreationForm(array $data = array())
{
}
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*
* Gives the form used for entities update
*/
protected function getUpdateForm(array $data = array())
{
}
/**
* @param Event $event
* @return null|mixed
*
* Get the object from the event
*
* if return null or false, the action will throw a 404
*/
protected function extractObjectFromEvent(Event $event)
{
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on creation.
*/
protected function getCreationEvent(array &$data)
{
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on update.
*/
protected function getUpdateEvent(array &$data)
{
}
/**
* @param mixed $entityId
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on entity deletion.
*/
protected function getDeleteEvent($entityId)
{
}
}

View File

@@ -0,0 +1,112 @@
<?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\Controller\Api;
use Symfony\Component\EventDispatcher\Event;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Template\Loop\Currency;
/**
* Class CurrencyController
* @package Thelia\Controller\Api
* @author Benjamin Perche <bperche@openstudio.fr>
*/
class CurrencyController extends AbstractCrudApiController
{
public function __construct()
{
parent::__construct(
"currency",
AdminResources::CURRENCY,
[],
[],
[]
);
}
/**
* @return \Thelia\Core\Template\Element\BaseLoop
*
* Get the entity loop instance
*/
protected function getLoop()
{
return new Currency($this->container);
}
/**
* @TODO: Implement Create - Update - Delete
*/
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*
* Gives the form used for entities creation.
*/
protected function getCreationForm(array $data = array())
{
}
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*
* Gives the form used for entities update
*/
protected function getUpdateForm(array $data = array())
{
}
/**
* @param Event $event
* @return null|mixed
*
* Get the object from the event
*
* if return null or false, the action will throw a 404
*/
protected function extractObjectFromEvent(Event $event)
{
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on creation.
*/
protected function getCreationEvent(array &$data)
{
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on update.
*/
protected function getUpdateEvent(array &$data)
{
}
/**
* @param mixed $entityId
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on entity deletion.
*/
protected function getDeleteEvent($entityId)
{
}
}

View File

@@ -0,0 +1,216 @@
<?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\Controller\Api;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Thelia\Core\Event\Customer\CustomerCreateOrUpdateEvent;
use Thelia\Core\Event\Customer\CustomerEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\HttpFoundation\JsonResponse;
use Thelia\Core\Security\AccessManager;
use Thelia\Core\Security\Authentication\CustomerUsernamePasswordFormAuthenticator;
use Thelia\Core\Security\Exception\UsernameNotFoundException;
use Thelia\Core\Security\Exception\WrongPasswordException;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Security\User\UserInterface;
use Thelia\Core\Template\Loop\Customer;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Model\CustomerQuery;
use Thelia\Form\Definition\ApiForm;
/**
* Class CustomerController
* @package Thelia\Controller\Api
* @author Manuel Raynaud <manu@raynaud.io>
* @author Benjamin Perche <bperche@openstudio.fr>
*/
class CustomerController extends AbstractCrudApiController
{
public function __construct()
{
parent::__construct(
"customer",
AdminResources::CUSTOMER,
TheliaEvents::CUSTOMER_CREATEACCOUNT,
TheliaEvents::CUSTOMER_UPDATEACCOUNT,
TheliaEvents::CUSTOMER_DELETEACCOUNT,
[],
[
"limit" => 10,
"offset" => 0,
"current" => false,
]
);
}
/**
* @return \Thelia\Core\Template\Element\BaseLoop
*
* Get the entity loop instance
*/
protected function getLoop()
{
return new Customer($this->container);
}
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*/
protected function getCreationForm(array $data = array())
{
return $this->createForm(ApiForm::CUSTOMER_CREATE);
}
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*/
protected function getUpdateForm(array $data = array())
{
return $this->createForm(
ApiForm::CUSTOMER_UPDATE,
"form",
[],
['method' => 'PUT']
);
}
/**
* @param Event $event
* @return null|mixed
*
* Get the object from the event
*
* if return null or false, the action will throw a 404
*/
protected function extractObjectFromEvent(Event $event)
{
return $event->getCustomer();
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*/
protected function getCreationEvent(array &$data)
{
return $this->hydrateEvent($data);
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*/
protected function getUpdateEvent(array &$data)
{
return $this->hydrateEvent($data);
}
/**
* @param mixed $entityId
* @return \Symfony\Component\EventDispatcher\Event
*/
protected function getDeleteEvent($entityId)
{
$customer = CustomerQuery::create()->findPk($entityId);
if (null === $customer) {
throw new HttpException(404, sprintf('{"error": "customer with id %d not found"}', $entityId));
}
return new CustomerEvent($customer);
}
protected function hydrateEvent(array $data)
{
$customerCreateEvent = new CustomerCreateOrUpdateEvent(
$data['title'],
$data['firstname'],
$data['lastname'],
$data['address1'],
$data['address2'],
$data['address3'],
$data['phone'],
$data['cellphone'],
$data['zipcode'],
$data['city'],
$data['country'],
$data['email'],
$data['password'],
$data['lang_id'],
isset($data["reseller"]) ? $data["reseller"] : null,
isset($data["sponsor"]) ? $data["sponsor"] : null,
isset($data["discount"]) ? $data["discount"] : null,
$data['company'],
null
);
if (isset($data["id"])) {
$customerCreateEvent->setCustomer(CustomerQuery::create()->findPk($data["id"]));
}
return $customerCreateEvent;
}
public function deleteAction($entityId)
{
$query = CustomerQuery::create()
->joinOrder()
->filterById($entityId)
->findOne()
;
if (null !== $query) {
throw new HttpException(403, json_encode([
"error" => sprintf("You can't delete the customer %d as he has orders", $entityId),
]));
}
return parent::deleteAction($entityId);
}
/**
* @return \Symfony\Component\HttpFoundation\Response|JsonResponse
*
* Get a customer given its email and password.
* @author Baptiste Cabarrou <bcabarrou@openstudio.fr>
*/
public function checkLoginAction()
{
$this->checkAuth($this->resources, $this->modules, AccessManager::VIEW);
$request = $this->getRequest();
$customerLoginForm = $this->createForm(ApiForm::CUSTOMER_LOGIN);
try {
$this->validateForm($customerLoginForm, "post");
$authenticator = new CustomerUsernamePasswordFormAuthenticator($request, $customerLoginForm);
/** @var UserInterface $customer */
$customer = $authenticator->getAuthentifiedUser();
return $this->getAction($customer->getId());
} catch (UsernameNotFoundException $e) {
return new JsonResponse(["error" => $e->getMessage()], 404);
} catch (WrongPasswordException $e) {
return new JsonResponse(["error" => $e->getMessage()], 404);
} catch (HttpException $e) {
return new JsonResponse(["error" => $e->getMessage()], $e->getStatusCode());
} catch (\Exception $e) {
return new JsonResponse(["error" => $e->getMessage()], 500);
}
}
}

View File

@@ -0,0 +1,374 @@
<?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\Controller\Api;
use Propel\Runtime\Propel;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Thelia\Controller\Admin\FileController;
use Thelia\Core\Event\File\FileDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\HttpFoundation\Response;
use Thelia\Core\Security\AccessManager;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Template\Loop\Image;
use Thelia\Files\FileConfiguration;
/**
* Class ImageController
* @package Thelia\Controller\Api
* @author manuel raynaud <manu@raynaud.io>
*/
class ImageController extends BaseApiController
{
/**
* @param integer $entityId source's primary key (product's pk, category's pk, etc)
* @return \Symfony\Component\HttpFoundation\Response
*/
public function listAction($entityId)
{
$request = $this->getRequest();
$entity = $request->attributes->get('entity');
$this->checkAuth($this->getAdminResources()->getResource($entity), [], AccessManager::VIEW);
$this->checkEntityExists($entity, $entityId);
if ($request->query->has('id')) {
$request->query->remove('id');
}
$params = array_merge(
[
'limit' => 10,
'offset' => 0,
],
$request->query->all(),
[
'source' => strtolower($entity),
'source_id' => $entityId
]
);
$imageLoop = new Image($this->getContainer());
$imageLoop->initializeArgs($params);
return JsonResponse::create($imageLoop->exec($paginate));
}
public function getImageAction($entityId, $imageId)
{
$request = $this->getRequest();
$entity = $request->attributes->get('entity');
$this->checkAuth($this->getAdminResources()->getResource($entity), [], AccessManager::VIEW);
$this->checkEntityExists($entity, $entityId);
$params = array_merge(
$request->query->all(),
[
'source' => strtolower($entity),
'source_id' => $entityId,
'id' => $imageId
]
);
$imageLoop = new Image($this->getContainer());
$imageLoop->initializeArgs($params);
$results = $imageLoop->exec($paginate);
if ($results->isEmpty()) {
return JsonResponse::create(
array(
'error' => sprintf('image with id %d not found', $imageId)
),
404
);
}
return JsonResponse::create($results);
}
public function createImageAction($entityId)
{
$request = $this->getRequest();
$entity = $request->attributes->get('entity');
$this->checkAuth($this->getAdminResources()->getResource($entity), [], AccessManager::UPDATE);
$fileController = new FileController();
$fileController->setContainer($this->getContainer());
$config = FileConfiguration::getImageConfig();
$files = $request->files->all();
$errors = null;
foreach ($files as $file) {
$errors = $this->processImage($fileController, $file, $entityId, $entity, $config);
}
if (!empty($errors)) {
$response = JsonResponse::create($errors, 500);
} else {
$response = $this->listAction($entityId);
$response->setStatusCode(201);
}
return $response;
}
public function updateImageAction($entityId, $imageId)
{
$request = $this->getRequest();
$entity = $request->attributes->get('entity');
$this->checkAuth($this->getAdminResources()->getResource($entity), [], AccessManager::UPDATE);
$this->checkEntityExists($entity, $entityId);
$this->checkImage($entity, $imageId);
/**
* If there is a file, treat it
*/
$hasImage = $request->files->count() == 1;
if ($hasImage) {
$this->processImageUpdate($entityId, $entity);
}
/**
* Then treat i18n form
*/
$baseForm = $this->createForm(null, "image", [], array(
"csrf_protection" => false,
"method" => "PUT",
));
$baseForm->getFormBuilder()
->addEventListener(
FormEvents::PRE_SUBMIT,
function (FormEvent $event) use ($entity, $imageId) {
$this->onFormPreSubmit($event, $imageId, $entity);
}
)
;
$con = Propel::getConnection();
$con->beginTransaction();
try {
$form = $this->validateForm($baseForm);
$image = $this->checkImage($entity, $imageId);
foreach ($form->getData()["i18n"] as $locale => $i18nRow) {
$image->getTranslation($locale)
->setTitle($i18nRow["title"])
->setChapo($i18nRow["chapo"])
->setDescription($i18nRow["description"])
->setPostscriptum($i18nRow["postscriptum"])
;
}
$image->save();
$con->commit();
} catch (\Exception $e) {
$con->rollBack();
if (!$hasImage) {
throw new HttpException(500, $e->getMessage());
}
}
return $this->getImageAction($entityId, $imageId)->setStatusCode(201);
}
protected function onFormPreSubmit(FormEvent $event, $entityId, $entity)
{
$data = $event->getData();
$temporaryRegister = array();
foreach ($data["i18n"] as $key => &$value) {
$temporaryRegister["i18n"][$value["locale"]] = $value;
unset($data["i18n"][$key]);
}
$data = $temporaryRegister;
$i18ns = $this->getImageI18ns($entity, $entityId);
foreach ($i18ns as $i18n) {
$row = array(
"locale" => $i18n->getLocale(),
"title" => $i18n->getTitle(),
"chapo" => $i18n->getChapo(),
"description" => $i18n->getDescription(),
"postscriptum" => $i18n->getPostscriptum(),
);
if (!isset($data["i18n"][$i18n->getLocale()])) {
$data["i18n"][$i18n->getLocale()] = array();
}
$data["i18n"][$i18n->getLocale()] = array_merge(
$row,
$data["i18n"][$i18n->getLocale()]
);
}
$event->setData($data);
}
protected function processImageUpdate($entityId, $entity)
{
$file = $this->getRequest()->files->all();
reset($file);
$file = current($file);
$fileController = new FileController();
$fileController->setContainer($this->getContainer());
$config = FileConfiguration::getImageConfig();
$errors = $this->processImage($fileController, $file, $entityId, $entity, $config);
if (!empty($errors)) {
throw new HttpException(500, json_encode($errors), null, ["Content-Type" => "application/json"]);
}
}
protected function processImage(FileController $fileController, $file, $entityId, $entity, array $config)
{
try {
$fileController->processImage(
$file,
$entityId,
$entity,
$config['objectType'],
$config['validMimeTypes'],
$config['extBlackList']
);
} catch (\Exception $e) {
return [
'file' => $file->getClientOriginalName(),
'message' => $e->getMessage(),
];
}
return null;
}
public function deleteImageAction($entityId, $imageId)
{
$request = $this->getRequest();
$entity = $request->attributes->get('entity');
$this->checkAuth($this->getAdminResources()->getResource($entity), [], AccessManager::UPDATE);
$this->checkEntityExists($entity, $entityId);
$entityModel = $this->checkImage($entity, $imageId);
if (null === $entityModel) {
throw new HttpException(404, sprintf('{"error": "image with id %d not found"}', $imageId));
}
try {
$fileDeleteEvent = new FileDeleteEvent($entityModel);
$this->dispatch(TheliaEvents::IMAGE_DELETE, $fileDeleteEvent);
return Response::create('', 204);
} catch (\Exception $e) {
return JsonResponse::create(['error' => $e->getMessage()], 500);
}
}
/**
* @param string $entity image's source (eg : Product, Category, etc)
* @param int $entityId source's primary key
*/
protected function checkEntityExists($entity, $entityId)
{
$entity = ucfirst($entity);
$class = sprintf("Thelia\\Model\\%sQuery", $entity);
$method = new \ReflectionMethod($class, 'create');
$search = $method->invoke(null);
$entityModel = $search->findPk($entityId);
if (null === $entityModel) {
throw new HttpException(
404,
sprintf('{"error": "%s with id %d not found"}', $entity, $entityId),
null,
["Content-Type" => "application/json"]
);
}
return $entityModel;
}
/**
* @param $entity
* @param $imageId
* @return \Thelia\Files\FileModelInterface
*/
protected function checkImage($entity, $imageId)
{
$class = sprintf("Thelia\\Model\\%sImageQuery", ucfirst($entity));
$method = new \ReflectionMethod($class, 'create');
$search = $method->invoke(null);
$imageModel = $search->findPk($imageId);
if (null === $imageModel) {
throw new HttpException(
404,
sprintf('{"error": "image with id %d not found"}', $imageId),
null,
["Content-Type" => "application/json"]
);
}
return $imageModel;
}
/**
* @param $entity
* @param $imageId
* @return \Propel\Runtime\Collection\ObjectCollection
*/
protected function getImageI18ns($entity, $imageId)
{
$class = sprintf("Thelia\\Model\\%sImageI18nQuery", ucfirst($entity));
$method = new \ReflectionMethod($class, 'create');
$search = $method->invoke(null);
$search->orderByLocale();
return $search->findById($imageId);
}
}

View File

@@ -0,0 +1,31 @@
<?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\Controller\Api;
use Symfony\Component\HttpFoundation\Response;
/**
*
* This controller allow to test if api server is up or down
*
* Class IndexController
* @package Thelia\Controller\Api
* @author Manuel Raynaud <manu@raynaud.io>
*/
class IndexController extends BaseApiController
{
public function indexAction()
{
return Response::create("OK");
}
}

View File

@@ -0,0 +1,112 @@
<?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\Controller\Api;
use Symfony\Component\EventDispatcher\Event;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Template\Loop\Lang;
/**
* Class LangController
* @package Thelia\Controller\Api
* @author Benjamin Perche <bperche@openstudio.fr>
*/
class LangController extends AbstractCrudApiController
{
public function __construct()
{
parent::__construct(
"lang",
AdminResources::LANGUAGE,
[],
[],
[]
);
}
/**
* @return \Thelia\Core\Template\Element\BaseLoop
*
* Get the entity loop instance
*/
protected function getLoop()
{
return new Lang($this->container);
}
/**
* @TODO: Implement Create - Update - Delete
*/
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*
* Gives the form used for entities creation.
*/
protected function getCreationForm(array $data = array())
{
}
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*
* Gives the form used for entities update
*/
protected function getUpdateForm(array $data = array())
{
}
/**
* @param Event $event
* @return null|mixed
*
* Get the object from the event
*
* if return null or false, the action will throw a 404
*/
protected function extractObjectFromEvent(Event $event)
{
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on creation.
*/
protected function getCreationEvent(array &$data)
{
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on update.
*/
protected function getUpdateEvent(array &$data)
{
}
/**
* @param mixed $entityId
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on entity deletion.
*/
protected function getDeleteEvent($entityId)
{
}
}

View File

@@ -0,0 +1,189 @@
<?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\Controller\Api;
use Propel\Runtime\Propel;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Thelia\Core\Event\Product\ProductCreateEvent;
use Thelia\Core\Event\Product\ProductDeleteEvent;
use Thelia\Core\Event\Product\ProductUpdateEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\HttpFoundation\Response;
use Thelia\Core\Security\AccessManager;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Template\Loop\Product;
use Thelia\Form\Api\Product\ProductCreationForm;
use Thelia\Form\Api\Product\ProductModificationForm;
use Thelia\Model\ProductQuery;
use Thelia\Form\Definition\ApiForm;
/**
* Class ProductController
* @package Thelia\Controller\Api
* @author Manuel Raynaud <manu@raynaud.io>
*/
class ProductController extends BaseApiController
{
public function listAction()
{
$this->checkAuth(AdminResources::PRODUCT, [], AccessManager::VIEW);
$request = $this->getRequest();
if ($request->query->has('id')) {
$request->query->remove('id');
}
$params = array_merge(
$request->query->all(),
[
'limit' => $request->query->get('limit', 10),
'offset' => $request->query->get('offset', 0)
]
);
return JsonResponse::create($this->baseProductSearch($params));
}
public function getProductAction($productId)
{
$this->checkAuth(AdminResources::PRODUCT, [], AccessManager::VIEW);
$request = $this->getRequest();
$params = array_merge(
$request->query->all(),
['id' => $productId]
);
$results = $this->baseProductSearch($params);
if ($results->isEmpty()) {
return JsonResponse::create(
array(
'error' => sprintf('product with id %d not found', $productId)
),
404
);
}
return JsonResponse::create($results);
}
private function baseProductSearch($params)
{
$productLoop = new Product($this->getContainer());
$productLoop->initializeArgs($params);
return $productLoop->exec($paginate);
}
public function createAction()
{
$this->checkAuth(AdminResources::PRODUCT, [], AccessManager::CREATE);
$form = $this->createForm(ApiForm::PRODUCT_CREATION, 'form', [], ['csrf_protection' => false]);
try {
$creationForm = $this->validateForm($form);
$event = new ProductCreateEvent();
$event->bindForm($creationForm);
$this->dispatch(TheliaEvents::PRODUCT_CREATE, $event);
$product = $event->getProduct();
$updateEvent = new ProductUpdateEvent($product->getId());
$updateEvent->bindForm($creationForm);
$this->dispatch(TheliaEvents::PRODUCT_UPDATE, $updateEvent);
$this->getRequest()->query->set('lang', $creationForm->get('locale')->getData());
$response = $this->getProductAction($product->getId());
$response->setStatusCode(201);
return $response;
} catch (\Exception $e) {
return JsonResponse::create(['error' => $e->getMessage()], 500);
}
}
public function updateAction($productId)
{
$this->checkAuth(AdminResources::PRODUCT, [], AccessManager::UPDATE);
$this->checkProductExists($productId);
$form = $this->createForm(
ApiForm::PRODUCT_MODIFICATION,
'form',
['id' => $productId],
[
'csrf_protection' => false,
'method' => 'PUT'
]
);
$request = $this->getRequest();
$data = $request->request->all();
$data['id'] = $productId;
$request->request->add($data);
try {
$updateForm = $this->validateForm($form);
$event = new ProductUpdateEvent($productId);
$event->bindForm($updateForm);
$this->dispatch(TheliaEvents::PRODUCT_UPDATE, $event);
return JsonResponse::create(null, 204);
} catch (\Exception $e) {
return JsonResponse::create(['error' => $e->getMessage()], 500);
}
}
public function deleteAction($productId)
{
$this->checkAuth(AdminResources::PRODUCT, [], AccessManager::DELETE);
$this->checkProductExists($productId);
try {
$event = new ProductDeleteEvent($productId);
$this->dispatch(TheliaEvents::PRODUCT_DELETE, $event);
return Response::create('', 204);
} catch (\Exception $e) {
return JsonResponse::create(['error' => $e->getMessage()], 500);
}
}
/**
* @param $productId
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*/
protected function checkProductExists($productId)
{
$product = ProductQuery::create()
->findPk($productId);
if (null === $product) {
throw new HttpException(404, sprintf('{"error": "product with id %d not found"}', $productId), null, [
"Content-Type" => "application/json"
]);
}
}
}

View File

@@ -0,0 +1,467 @@
<?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\Controller\Api;
use Propel\Runtime\Propel;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Thelia\Core\Event\ProductSaleElement\ProductSaleElementCreateEvent;
use Thelia\Core\Event\ProductSaleElement\ProductSaleElementDeleteEvent;
use Thelia\Core\Event\ProductSaleElement\ProductSaleElementUpdateEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\HttpFoundation\JsonResponse;
use Thelia\Core\Security\AccessManager;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Form\Definition\AdminForm;
use Thelia\Model\Country;
use Thelia\Model\Map\ProductSaleElementsTableMap;
use Thelia\Model\Product;
use Thelia\Model\ProductPriceQuery;
use Thelia\Model\ProductQuery;
use Thelia\Model\ProductSaleElements;
use Thelia\Core\Template\Loop\ProductSaleElements as ProductSaleElementsLoop;
use Thelia\Model\ProductSaleElementsQuery;
use Thelia\Model\TaxRuleQuery;
use Thelia\TaxEngine\Calculator;
use Thelia\Form\Definition\ApiForm;
/**
* Class ProductSaleElementsController
* @package Thelia\Controller\Api
* @author Benjamin Perche <bperche@openstudio.fr>
*
* API Controller for Product sale elements management
*/
class ProductSaleElementsController extends BaseApiController
{
protected $product;
/**
* Read actions
*/
/**
* @param $productId
* @return JsonResponse
*
* List a product pses
*/
public function listAction($productId)
{
$this->checkAuth(AdminResources::PRODUCT, [], AccessManager::VIEW);
if (null !== $response = $this->checkProduct($productId)) {
return $response;
}
$request = $this->getRequest();
if ($request->query->has('id')) {
$request->query->remove('id');
}
$params = array_merge(
array(
"limit" => 10,
"offset" => 0,
),
$request->query->all(),
array(
"product" => $productId,
)
);
return new JsonResponse($this->getProductSaleElements($params));
}
/**
* @param $pseId
* @return JsonResponse
*
* Get a pse details
*/
public function getPseAction($pseId)
{
$this->checkAuth(AdminResources::PRODUCT, [], AccessManager::VIEW);
$request = $this->getRequest();
$params = array_merge(
$request->query->all(),
[
'id' => $pseId,
]
);
$results = $this->getProductSaleElements($params);
if ($results->getCount() == 0) {
return new JsonResponse(
sprintf(
"The product sale elements id '%d' doesn't exist",
$pseId
),
404
);
}
return new JsonResponse($results);
}
/**
* Create action
*/
/**
* @return JsonResponse
*
* Create product sale elements
*/
public function createAction()
{
$this->checkAuth(AdminResources::PRODUCT, [], AccessManager::CREATE);
$baseForm = $this->createForm(ApiForm::PRODUCT_SALE_ELEMENTS, "form", [], [
"validation_groups" => ["create", "Default"],
'csrf_protection' => false,
"cascade_validation" => true,
]);
$con = Propel::getConnection(ProductSaleElementsTableMap::DATABASE_NAME);
$con->beginTransaction();
$createdIds = array();
try {
$form = $this->validateForm($baseForm);
$entries = $form->getData();
foreach ($entries["pse"] as $entry) {
$createEvent = new ProductSaleElementCreateEvent(
ProductQuery::create()->findPk($entry["product_id"]),
$entry["attribute_av"],
$entry["currency_id"]
);
$createEvent->bindForm($form);
$this->dispatch(TheliaEvents::PRODUCT_ADD_PRODUCT_SALE_ELEMENT, $createEvent);
$this->processUpdateAction(
$entry,
$pse = $createEvent->getProductSaleElement(),
$createEvent->getProduct()
);
$createdIds[] = $pse->getId();
}
$con->commit();
} catch (\Exception $e) {
$con->rollBack();
return new JsonResponse(["error" => $e->getMessage()], 500);
}
return new JsonResponse(
$this->getProductSaleElements(
array_merge(
$this->getRequest()->query->all(),
["id" => implode(",", $createdIds)]
)
),
201
);
}
/**
* @return JsonResponse
*
* Create product sale elements
*/
public function updateAction()
{
$this->checkAuth(AdminResources::PRODUCT, [], AccessManager::UPDATE);
$baseForm = $this->createForm(ApiForm::PRODUCT_SALE_ELEMENTS, "form", [], [
"validation_groups" => ["update", "Default"],
'csrf_protection' => false,
"cascade_validation" => true,
"method" => "PUT",
]);
$baseForm->getFormBuilder()
->addEventListener(
FormEvents::PRE_SUBMIT,
[$this, "loadProductSaleElements"],
192
);
$updatedId = array();
$con = Propel::getConnection(ProductSaleElementsTableMap::DATABASE_NAME);
$con->beginTransaction();
try {
$form = $this->validateForm($baseForm);
$entries = $form->getData();
foreach ($entries["pse"] as $entry) {
$this->processUpdateAction(
$entry,
$pse = ProductSaleElementsQuery::create()->findPk($entry["id"]),
$pse->getProduct()
);
$updatedId[] = $pse->getId();
}
$con->commit();
} catch (\Exception $e) {
$con->rollBack();
return new JsonResponse(["error" => $e->getMessage()], 500);
}
return new JsonResponse(
$this->getProductSaleElements(
array_merge(
$this->getRequest()->query->all(),
[
"id" => implode(",", $updatedId),
"limit" => count($updatedId),
]
)
),
201
);
}
/**
* Delete Action
*/
/**
* @param $pseId
* @return JsonResponse|\Thelia\Core\HttpFoundation\Response
*
* Delete a pse
*/
public function deleteAction($pseId)
{
$this->checkAuth(AdminResources::PRODUCT, [], AccessManager::VIEW);
$results = $this->getProductSaleElements([
'id' => $pseId
]);
if ($results->getCount() == 0) {
return new JsonResponse(
sprintf(
"The product sale elements id '%d' doesn't exist",
$pseId
),
404
);
}
$event = new ProductSaleElementDeleteEvent($pseId, null);
try {
$this->dispatch(TheliaEvents::PRODUCT_DELETE_PRODUCT_SALE_ELEMENT, $event);
} catch (\Exception $e) {
return new JsonResponse(array("error" => $e->getMessage()), 500);
}
return $this->nullResponse(204);
}
/**
* @param array $data
* @param ProductSaleElements $pse
* @param Product $product
*
* Process update on product sale elements values
*/
protected function processUpdateAction(
array $data,
ProductSaleElements $pse,
Product $product
) {
list($price, $salePrice) = $this->extractPrices($data);
$event = new ProductSaleElementUpdateEvent($product, $pse->getId());
$event
->setWeight($data["weight"])
->setTaxRuleId($data["tax_rule_id"])
->setEanCode($data["ean_code"])
->setOnsale($data["onsale"])
->setReference($data["reference"])
->setIsdefault($data["isdefault"])
->setIsnew($data["isnew"])
->setCurrencyId($data["currency_id"])
->setPrice($price)
->setSalePrice($salePrice)
->setQuantity($data["quantity"])
->setFromDefaultCurrency($data["use_exchange_rate"])
;
$this->dispatch(TheliaEvents::PRODUCT_UPDATE_PRODUCT_SALE_ELEMENT, $event);
}
/**
* @param array $data
* @return array
*
* Return the untaxed prices to store
*/
protected function extractPrices(array $data)
{
$calculator = new Calculator();
$calculator->loadTaxRuleWithoutProduct(
TaxRuleQuery::create()->findPk($data["tax_rule_id"]),
Country::getShopLocation()
);
$price = null === $data["price_with_tax"] ?
$data["price"] :
$calculator->getUntaxedPrice($data["price_with_tax"])
;
$salePrice = null === $data["sale_price_with_tax"] ?
$data["sale_price"] :
$calculator->getUntaxedPrice($data["sale_price_with_tax"])
;
return [$price, $salePrice];
}
protected function retrievePrices(ProductSaleElements $pse)
{
$query = ProductPriceQuery::create()
->useCurrencyQuery()
->orderByByDefault()
->endUse()
;
$prices = $pse->getProductPrices($query);
if ($prices->count() === 0) {
return array(null, null, null, null);
}
/** @var \Thelia\Model\ProductPrice $currentPrices */
$currentPrices = $prices->get(0);
return [
$currentPrices->getPrice(),
$currentPrices->getPromoPrice(),
$currentPrices->getCurrencyId(),
$currentPrices->getFromDefaultCurrency()
];
}
/**
* @param FormEvent $event
*
* Loads initial pse data into a form.
* It is used in for a form event on pse update
*/
public function loadProductSaleElements(FormEvent $event)
{
$productSaleElementIds = array();
$data = array();
foreach ($event->getData()["pse"] as $entry) {
$productSaleElementIds[$entry["id"]] = $entry;
}
$productSaleElements = ProductSaleElementsQuery::create()
->findPks(array_keys($productSaleElementIds))
;
/** @var ProductSaleElements $productSaleElement */
foreach ($productSaleElements as $productSaleElement) {
$product = $productSaleElement->getProduct();
list($price, $salePrice, $currencyId, $fromDefaultCurrency) = $this->retrievePrices($productSaleElement);
$data["pse"][$productSaleElement->getId()] = array_merge(
[
"id" => $productSaleElement->getId(),
"reference" => $productSaleElement->getRef(),
"tax_rule_id" => $product->getTaxRuleId(),
"ean_code" => $productSaleElement->getEanCode(),
"onsale" => $productSaleElement->getPromo(),
"isdefault" => $productSaleElement->getIsDefault(),
"isnew" => $productSaleElement->getNewness(),
"quantity" => $productSaleElement->getQuantity(),
"weight" => $productSaleElement->getWeight(),
"price" => $price,
"sale_price" => $salePrice,
"currency_id" => $currencyId,
"use_exchange_rate" => $fromDefaultCurrency
],
$productSaleElementIds[$productSaleElement->getId()]
);
}
$event->setData($data);
}
/**
* @param $productId
* @return null|JsonResponse
*
* Checks if a productId exists
*/
protected function checkProduct($productId)
{
$this->product = ProductQuery::create()
->findPk($productId)
;
if (null === $this->product) {
return new JsonResponse(
[
"error" => sprintf(
"The product id '%d' doesn't exist",
$productId
)
],
404
);
}
return null;
}
/**
* @param $params
* @return \Thelia\Core\Template\Element\LoopResult
*
* Return loop results for a product sale element
*/
protected function getProductSaleElements($params)
{
$loop = new ProductSaleElementsLoop($this->container);
$loop->initializeArgs($params);
return $loop->exec($pagination);
}
}

View File

@@ -0,0 +1,112 @@
<?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\Controller\Api;
use Symfony\Component\EventDispatcher\Event;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Template\Loop\Tax;
/**
* Class TaxController
* @package Thelia\Controller\Api
* @author Benjamin Perche <bperche@openstudio.fr>
*/
class TaxController extends AbstractCrudApiController
{
public function __construct()
{
parent::__construct(
"tax",
AdminResources::TAX,
[],
[],
[]
);
}
/**
* @return \Thelia\Core\Template\Element\BaseLoop
*
* Get the entity loop instance
*/
protected function getLoop()
{
return new Tax($this->container);
}
/**
* @TODO: implement Create - Update - Delete
*/
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*
* Gives the form used for entities creation.
*/
protected function getCreationForm(array $data = array())
{
}
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*
* Gives the form used for entities update
*/
protected function getUpdateForm(array $data = array())
{
}
/**
* @param Event $event
* @return null|mixed
*
* Get the object from the event
*
* if return null or false, the action will throw a 404
*/
protected function extractObjectFromEvent(Event $event)
{
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on creation.
*/
protected function getCreationEvent(array &$data)
{
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on update.
*/
protected function getUpdateEvent(array &$data)
{
}
/**
* @param mixed $entityId
* @return \Symfony\Component\EventDispatcher\Event
*
* Hydrates an event object to dispatch on entity deletion.
*/
protected function getDeleteEvent($entityId)
{
}
}

View File

@@ -0,0 +1,257 @@
<?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\Controller\Api;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Thelia\Core\Event\Tax\TaxRuleEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Template\Loop\TaxRule;
use Thelia\Model\Map\TaxRuleCountryTableMap;
use Thelia\Model\ProductQuery;
use Thelia\Model\TaxRuleCountryQuery;
use Thelia\Model\TaxRuleI18nQuery;
use Thelia\Model\TaxRuleQuery;
/**
* Class TaxRuleController
* @package Thelia\Controller\Api
* @author Benjamin Perche <bperche@openstudio.fr>
* @author manuel raynaud <manu@raynaud.io>
*/
class TaxRuleController extends AbstractCrudApiController
{
public function __construct()
{
parent::__construct(
"tax rule",
AdminResources::TAX,
[TheliaEvents::TAX_RULE_CREATE, TheliaEvents::TAX_RULE_TAXES_UPDATE],
[TheliaEvents::TAX_RULE_UPDATE, TheliaEvents::TAX_RULE_TAXES_UPDATE],
TheliaEvents::TAX_RULE_DELETE
);
}
/**
* @return \Thelia\Core\Template\Element\BaseLoop
*
* Get the entity loop instance
*/
protected function getLoop()
{
return new TaxRule($this->container);
}
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*/
protected function getCreationForm(array $data = array())
{
return $this->createForm(null, "tax_rule", $data);
}
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*/
protected function getUpdateForm(array $data = array())
{
return $this->createForm(null, "tax_rule", $data, array(
"validation_groups" => ["Default", "update"],
"method" => "PUT",
));
}
/**
* @param Event $event
* @return null|mixed
*
* Get the object from the event
*
* if return null or false, the action will throw a 404
*/
protected function extractObjectFromEvent(Event $event)
{
return $event->getTaxRule();
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*/
protected function getCreationEvent(array &$data)
{
return $this->hydrateEvent($data);
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*/
protected function getUpdateEvent(array &$data)
{
return $this->hydrateEvent($data);
}
/**
* @param mixed $entityId
* @return \Symfony\Component\EventDispatcher\Event
*/
protected function getDeleteEvent($entityId)
{
$data = ["id" => $entityId];
return $this->hydrateEvent($data);
}
protected function afterCreateEvents(Event $event, array &$data)
{
$dispatcher = $this->getDispatcher();
if ($data["default"]) {
$dispatcher->dispatch(TheliaEvents::TAX_RULE_SET_DEFAULT, $event);
}
foreach ($data["i18n"] as $i18nRow) {
$this->hydrateI18nEvent($i18nRow, $event);
foreach ($this->updateEvents as $eventName) {
$dispatcher->dispatch($eventName, $event);
}
}
}
protected function afterUpdateEvents(Event $event, array &$data)
{
$this->afterCreateEvents($event, $data);
}
protected function hydrateEvent(array &$data)
{
$event = new TaxRuleEvent();
if (isset($data["country"])) {
$event->setCountryList($data["country"]);
}
if (isset($data["tax"])) {
$event->setTaxList($data["tax"]);
}
if (isset($data["id"])) {
$event->setId($data["id"]);
$event->setTaxRule(TaxRuleQuery::create()->findPk($data["id"]));
}
if (isset($data["i18n"]) && null !== $row = array_shift($data["i18n"])) {
$this->hydrateI18nEvent($row, $event);
}
return $event;
}
protected function hydrateI18nEvent(array $i18nRow, TaxRuleEvent $event)
{
$event
->setLocale($i18nRow["locale"])
->setTitle($i18nRow["title"])
->setDescription($i18nRow["description"])
;
}
public function hydrateUpdateForm(FormEvent $event)
{
$data = $event->getData();
$keys = array_keys($data["i18n"]);
foreach ($keys as $key) {
$value = $data["i18n"][$key];
$data["i18n"][$value["locale"]] = $value;
unset($data["i18n"][$key]);
}
$persistentI18n = $this->getI18nPersistentData($data["id"]);
foreach ($persistentI18n["i18n"] as $locale => $value) {
$data["i18n"][$locale] = array_merge($value, $data["i18n"][$locale]);
}
$data = array_merge($this->getPersistentData($data["id"]), $data);
$event->setData($data);
}
protected function getPersistentData($taxRuleId)
{
$taxRule = TaxRuleQuery::create()->findPk($taxRuleId);
if (null === $taxRule) {
throw new HttpException(404, json_encode([
"error" => sprintf("The tax rule %d doesn't exist", $taxRuleId)
]));
}
$countries = TaxRuleCountryQuery::create()
->filterByTaxRuleId($taxRuleId)
->distinct()
->select(TaxRuleCountryTableMap::COUNTRY_ID)
->find()
->toArray()
;
$taxes = TaxRuleCountryQuery::create()
->filterByTaxRuleId($taxRuleId)
->distinct()
->select(TaxRuleCountryTableMap::TAX_ID)
->find()
->toArray()
;
$data = [
"default" => (bool) $taxRule->getIsDefault(),
"tax" => $taxes,
"country" => $countries,
];
return $data;
}
/**
* @param int $taxRuleId
* @return array
*/
protected function getI18nPersistentData($taxRuleId)
{
$i18ns = TaxRuleI18NQuery::create()
->findById($taxRuleId)
;
$data = ['i18n' => []];
/** @var \Thelia\Model\TaxRuleI18n $i18n */
foreach ($i18ns as $i18n) {
$data["i18n"][$i18n->getLocale()] = array(
"locale" => $i18n->getLocale(),
"title" => $i18n->getTitle(),
"description" => $i18n->getDescription(),
);
}
return $data;
}
}

View File

@@ -0,0 +1,235 @@
<?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\Controller\Api;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Form\FormEvent;
use Thelia\Core\Event\CustomerTitle\CustomerTitleEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Template\Loop\Title;
use Thelia\Model\CustomerTitleI18nQuery;
use Thelia\Model\CustomerTitleQuery;
/**
* Class TitleController
* @package Thelia\Controller\Api
* @author Benjamin Perche <bperche@openstudio.fr>
* @author Manuel Raynaud <manu@raynaud.io>
*/
class TitleController extends AbstractCrudApiController
{
public function __construct()
{
parent::__construct(
"customer title",
AdminResources::TITLE,
[
TheliaEvents::CUSTOMER_TITLE_BEFORE_CREATE,
TheliaEvents::CUSTOMER_TITLE_CREATE,
TheliaEvents::CUSTOMER_TITLE_AFTER_CREATE,
],
[
TheliaEvents::CUSTOMER_TITLE_BEFORE_UPDATE,
TheliaEvents::CUSTOMER_TITLE_UPDATE,
TheliaEvents::CUSTOMER_TITLE_AFTER_UPDATE,
],
TheliaEvents::CUSTOMER_TITLE_DELETE
);
}
/**
* @return \Thelia\Core\Template\Element\BaseLoop
*
* Get the entity loop instance
*/
protected function getLoop()
{
return new Title($this->container);
}
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*/
protected function getCreationForm(array $data = array())
{
return $this->createForm(null, "customer_title", $data);
}
/**
* @param array $data
* @return \Thelia\Form\BaseForm
*/
protected function getUpdateForm(array $data = array())
{
return $this->createForm(null, "customer_title", $data, array(
"validation_groups" => ["Default", "update"],
"method" => "PUT",
));
}
/**
* @param Event $event
* @return null|mixed
*
* Get the object from the event
*
* if return null or false, the action will throw a 404
*/
protected function extractObjectFromEvent(Event $event)
{
return $event->getCustomerTitle();
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*/
protected function getCreationEvent(array &$data)
{
return $this->createEvent($data);
}
/**
* @param array $data
* @return \Symfony\Component\EventDispatcher\Event
*/
protected function getUpdateEvent(array &$data)
{
return $this->createEvent($data);
}
/**
* @param mixed $entityId
* @return \Symfony\Component\EventDispatcher\Event
*/
protected function getDeleteEvent($entityId)
{
$data = ["title_id" => $entityId];
return $this->createEvent($data);
}
/**
* @param array $data
* @return CustomerTitleEvent
*
* Handler to create the customer title event
*/
protected function createEvent(array &$data)
{
$event = new CustomerTitleEvent();
if (isset($data["default"])) {
$event->setDefault($data["default"]);
}
if (isset($data["title_id"])) {
$event->setCustomerTitle(CustomerTitleQuery::create()->findPk($data["title_id"]));
}
if (isset($data["i18n"]) && !empty($data["i18n"])) {
$row = array_shift($data["i18n"]);
$this->hydrateEvent($row, $event);
}
return $event;
}
/**
* @param array $i18nRow
* @param CustomerTitleEvent $event
*
* Handler to hydrate the event with i18n data
*/
protected function hydrateEvent(array $i18nRow, CustomerTitleEvent $event)
{
$event
->setShort($i18nRow["short"])
->setLong($i18nRow["long"])
->setLocale($i18nRow["locale"])
;
}
protected function afterCreateEvents(Event $event, array &$data)
{
$dispatcher = $this->getDispatcher();
while (null !== $i18nRow = array_shift($data["i18n"])) {
$this->hydrateEvent($i18nRow, $event);
foreach ($this->updateEvents as $eventName) {
$dispatcher->dispatch($eventName, $event);
}
}
}
protected function afterUpdateEvents(Event $event, array &$data)
{
$this->afterCreateEvents($event, $data);
}
/**
* @param FormEvent $event
*
* This methods loads current title data into the update form.
* It uses an event to load only needed ids.
*/
public function hydrateUpdateForm(FormEvent $event)
{
$data = $event->getData();
$title = CustomerTitleQuery::create()->findPk($data["title_id"]);
if (null === $title) {
$this->entityNotFound($data["title_id"]);
}
$data["default"] |= (bool) $title->getByDefault();
$titleI18ns = CustomerTitleI18nQuery::create()
->filterById($data["title_id"])
->find()
->toKeyIndex('Locale')
;
$i18n = &$data["i18n"];
foreach ($data["i18n"] as $key => $value) {
$i18n[$value["locale"]] = $value;
unset($i18n[$key]);
}
/** @var \Thelia\Model\CustomerTitleI18n $titleI18n */
foreach ($titleI18ns as $titleI18n) {
$row = array();
$row["locale"] = $locale = $titleI18n->getLocale();
$row["short"] = $titleI18n->getShort();
$row["long"] = $titleI18n->getLong();
if (!isset($i18n[$locale])) {
$i18n[$locale] = array();
}
$i18n[$locale] = array_merge($row, $i18n[$locale]);
}
$event->setData($data);
}
}