mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2025-08-20 14:43:49 +00:00
Merge branch 'master' into fix-person-tests
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
/*
|
||||
* Copyright (C) 2018 Champs Libres Cooperative <info@champs-libres.coop>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
namespace Chill\MainBundle\CRUD\CompilerPass;
|
||||
|
||||
use Symfony\Component\DependencyInjection\ContainerBuilder;
|
||||
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
|
||||
use Symfony\Component\DependencyInjection\Reference;
|
||||
use Chill\MainBundle\Routing\MenuComposer;
|
||||
use Symfony\Component\DependencyInjection\Definition;
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
*/
|
||||
class CRUDControllerCompilerPass implements CompilerPassInterface
|
||||
{
|
||||
public function process(ContainerBuilder $container)
|
||||
{
|
||||
$crudConfig = $container->getParameter('chill_main_crud_route_loader_config');
|
||||
$apiConfig = $container->getParameter('chill_main_api_route_loader_config');
|
||||
|
||||
foreach ($crudConfig as $crudEntry) {
|
||||
$this->configureCrudController($container, $crudEntry, 'crud');
|
||||
}
|
||||
|
||||
foreach ($apiConfig as $crudEntry) {
|
||||
$this->configureCrudController($container, $crudEntry, 'api');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a controller for each definition, and add a methodCall to inject crud configuration to controller
|
||||
*/
|
||||
private function configureCrudController(ContainerBuilder $container, array $crudEntry, string $apiOrCrud): void
|
||||
{
|
||||
$controllerClass = $crudEntry['controller'];
|
||||
|
||||
$controllerServiceName = 'cs'.$apiOrCrud.'_'.$crudEntry['name'].'_controller';
|
||||
|
||||
if ($container->hasDefinition($controllerClass)) {
|
||||
$controller = $container->getDefinition($controllerClass);
|
||||
$container->removeDefinition($controllerClass);
|
||||
$alreadyDefined = true;
|
||||
} else {
|
||||
$controller = new Definition($controllerClass);
|
||||
$alreadyDefined = false;
|
||||
}
|
||||
|
||||
$controller->addTag('controller.service_arguments');
|
||||
if (FALSE === $alreadyDefined) {
|
||||
$controller->setAutoconfigured(true);
|
||||
$controller->setPublic(true);
|
||||
}
|
||||
|
||||
$param = 'chill_main_'.$apiOrCrud.'_config_'.$crudEntry['name'];
|
||||
$container->setParameter($param, $crudEntry);
|
||||
$controller->addMethodCall('setCrudConfig', ['%'.$param.'%']);
|
||||
|
||||
$container->setDefinition($controllerServiceName, $controller);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,225 @@
|
||||
<?php
|
||||
|
||||
namespace Chill\MainBundle\CRUD\Controller;
|
||||
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Routing\Annotation\Route;
|
||||
use Chill\MainBundle\Pagination\PaginatorFactory;
|
||||
use Chill\MainBundle\Pagination\PaginatorInterface;
|
||||
|
||||
class AbstractCRUDController extends AbstractController
|
||||
{
|
||||
/**
|
||||
* The crud configuration
|
||||
*
|
||||
* This configuration si defined by `chill_main['crud']` or `chill_main['apis']`
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected array $crudConfig = [];
|
||||
|
||||
/**
|
||||
* get the instance of the entity with the given id
|
||||
*
|
||||
* @param string $id
|
||||
* @return object
|
||||
*/
|
||||
protected function getEntity($action, $id, Request $request): ?object
|
||||
{
|
||||
return $this->getDoctrine()
|
||||
->getRepository($this->getEntityClass())
|
||||
->find($id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Count the number of entities
|
||||
*
|
||||
* By default, count all entities. You can customize the query by
|
||||
* using the method `customizeQuery`.
|
||||
*
|
||||
* @param string $action
|
||||
* @param Request $request
|
||||
* @return int
|
||||
*/
|
||||
protected function countEntities(string $action, Request $request, $_format): int
|
||||
{
|
||||
return $this->buildQueryEntities($action, $request)
|
||||
->select('COUNT(e)')
|
||||
->getQuery()
|
||||
->getSingleScalarResult()
|
||||
;
|
||||
}
|
||||
|
||||
/**
|
||||
* Query the entity.
|
||||
*
|
||||
* By default, get all entities. You can customize the query by using the
|
||||
* method `customizeQuery`.
|
||||
*
|
||||
* The method `orderEntity` is called internally to order entities.
|
||||
*
|
||||
* It returns, by default, a query builder.
|
||||
*
|
||||
*/
|
||||
protected function queryEntities(string $action, Request $request, string $_format, PaginatorInterface $paginator)
|
||||
{
|
||||
$query = $this->buildQueryEntities($action, $request)
|
||||
->setFirstResult($paginator->getCurrentPage()->getFirstItemNumber())
|
||||
->setMaxResults($paginator->getItemsPerPage());
|
||||
|
||||
// allow to order queries and return the new query
|
||||
return $this->orderQuery($action, $query, $request, $paginator, $_format);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add ordering fields in the query build by self::queryEntities
|
||||
*
|
||||
*/
|
||||
protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator, $_format)
|
||||
{
|
||||
return $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the base query for listing all entities.
|
||||
*
|
||||
* This method is used internally by `countEntities` `queryEntities`
|
||||
*
|
||||
* This base query does not contains any `WHERE` or `SELECT` clauses. You
|
||||
* can add some by using the method `customizeQuery`.
|
||||
*
|
||||
* The alias for the entity is "e".
|
||||
*
|
||||
* @param string $action
|
||||
* @param Request $request
|
||||
* @return QueryBuilder
|
||||
*/
|
||||
protected function buildQueryEntities(string $action, Request $request)
|
||||
{
|
||||
$qb = $this->getDoctrine()->getManager()
|
||||
->createQueryBuilder()
|
||||
->select('e')
|
||||
->from($this->getEntityClass(), 'e')
|
||||
;
|
||||
|
||||
$this->customizeQuery($action, $request, $qb);
|
||||
|
||||
return $qb;
|
||||
}
|
||||
|
||||
protected function customizeQuery(string $action, Request $request, $query): void {}
|
||||
|
||||
/**
|
||||
* Get the result of the query
|
||||
*/
|
||||
protected function getQueryResult(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator, $query)
|
||||
{
|
||||
return $query->getQuery()->getResult();
|
||||
}
|
||||
|
||||
protected function onPreIndex(string $action, Request $request, string $_format): ?Response
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* method used by indexAction
|
||||
*/
|
||||
protected function onPreIndexBuildQuery(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator): ?Response
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* method used by indexAction
|
||||
*/
|
||||
protected function onPostIndexBuildQuery(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator, $query): ?Response
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* method used by indexAction
|
||||
*/
|
||||
protected function onPostIndexFetchQuery(string $action, Request $request, string $_format, int $totalItems, PaginatorInterface $paginator, $entities): ?Response
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the complete FQDN of the class
|
||||
*
|
||||
* @return string the complete fqdn of the class
|
||||
*/
|
||||
protected function getEntityClass(): string
|
||||
{
|
||||
return $this->crudConfig['class'];
|
||||
}
|
||||
|
||||
/**
|
||||
* called on post fetch entity
|
||||
*/
|
||||
protected function onPostFetchEntity(string $action, Request $request, $entity, $_format): ?Response
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called on post check ACL
|
||||
*/
|
||||
protected function onPostCheckACL(string $action, Request $request, string $_format, $entity): ?Response
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* check the acl. Called by every action.
|
||||
*
|
||||
* By default, check the role given by `getRoleFor` for the value given in
|
||||
* $entity.
|
||||
*
|
||||
* Throw an \Symfony\Component\Security\Core\Exception\AccessDeniedHttpException
|
||||
* if not accessible.
|
||||
*
|
||||
* @throws \Symfony\Component\Security\Core\Exception\AccessDeniedHttpException
|
||||
*/
|
||||
protected function checkACL(string $action, Request $request, string $_format, $entity = null)
|
||||
{
|
||||
$this->denyAccessUnlessGranted($this->getRoleFor($action, $request, $entity, $_format), $entity);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return string the crud name
|
||||
*/
|
||||
protected function getCrudName(): string
|
||||
{
|
||||
return $this->crudConfig['name'];
|
||||
}
|
||||
|
||||
protected function getActionConfig(string $action)
|
||||
{
|
||||
return $this->crudConfig['actions'][$action];
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the crud configuration
|
||||
*
|
||||
* Used by the container to inject configuration for this crud.
|
||||
*/
|
||||
public function setCrudConfig(array $config): void
|
||||
{
|
||||
$this->crudConfig = $config;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return PaginatorFactory
|
||||
*/
|
||||
protected function getPaginatorFactory(): PaginatorFactory
|
||||
{
|
||||
return $this->container->get('chill_main.paginator_factory');
|
||||
}
|
||||
}
|
220
src/Bundle/ChillMainBundle/CRUD/Controller/ApiController.php
Normal file
220
src/Bundle/ChillMainBundle/CRUD/Controller/ApiController.php
Normal file
@@ -0,0 +1,220 @@
|
||||
<?php
|
||||
|
||||
namespace Chill\MainBundle\CRUD\Controller;
|
||||
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Routing\Annotation\Route;
|
||||
use Symfony\Component\Serializer\SerializerInterface;
|
||||
use Chill\MainBundle\Serializer\Model\Collection;
|
||||
use Chill\MainBundle\Pagination\PaginatorInterface;
|
||||
|
||||
class ApiController extends AbstractCRUDController
|
||||
{
|
||||
/**
|
||||
* The view action.
|
||||
*
|
||||
* Some steps may be overriden during this process of rendering:
|
||||
*
|
||||
* This method:
|
||||
*
|
||||
* 1. fetch the entity, using `getEntity`
|
||||
* 2. launch `onPostFetchEntity`. If postfetch is an instance of Response,
|
||||
* this response is returned.
|
||||
* 2. throw an HttpNotFoundException if entity is null
|
||||
* 3. check ACL using `checkACL` ;
|
||||
* 4. launch `onPostCheckACL`. If the result is an instance of Response,
|
||||
* this response is returned ;
|
||||
* 5. Serialize the entity and return the result. The serialization context is given by `getSerializationContext`
|
||||
*
|
||||
*/
|
||||
protected function entityGet(string $action, Request $request, $id, $_format = 'html'): Response
|
||||
{
|
||||
$entity = $this->getEntity($action, $id, $request, $_format);
|
||||
|
||||
$postFetch = $this->onPostFetchEntity($action, $request, $entity, $_format);
|
||||
|
||||
if ($postFetch instanceof Response) {
|
||||
return $postFetch;
|
||||
}
|
||||
|
||||
if (NULL === $entity) {
|
||||
throw $this->createNotFoundException(sprintf("The %s with id %s "
|
||||
. "is not found", $this->getCrudName(), $id));
|
||||
}
|
||||
|
||||
$response = $this->checkACL($action, $request, $_format, $entity);
|
||||
if ($response instanceof Response) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$response = $this->onPostCheckACL($action, $request, $_format, $entity);
|
||||
if ($response instanceof Response) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$response = $this->onBeforeSerialize($action, $request, $_format, $entity);
|
||||
if ($response instanceof Response) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
if ($_format === 'json') {
|
||||
$context = $this->getContextForSerialization($action, $request, $_format, $entity);
|
||||
|
||||
return $this->json($entity, Response::HTTP_OK, [], $context);
|
||||
} else {
|
||||
throw new \Symfony\Component\HttpFoundation\Exception\BadRequestException("This format is not implemented");
|
||||
}
|
||||
}
|
||||
|
||||
public function onBeforeSerialize(string $action, Request $request, $_format, $entity): ?Response
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base method for handling api action
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function entityApi(Request $request, $id, $_format): Response
|
||||
{
|
||||
switch ($request->getMethod()) {
|
||||
case Request::METHOD_GET:
|
||||
case REQUEST::METHOD_HEAD:
|
||||
return $this->entityGet('_entity', $request, $id, $_format);
|
||||
default:
|
||||
throw new \Symfony\Component\HttpFoundation\Exception\BadRequestException("This method is not implemented");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Base action for indexing entities
|
||||
*/
|
||||
public function indexApi(Request $request, string $_format)
|
||||
{
|
||||
switch ($request->getMethod()) {
|
||||
case Request::METHOD_GET:
|
||||
case REQUEST::METHOD_HEAD:
|
||||
return $this->indexApiAction('_index', $request, $_format);
|
||||
default:
|
||||
throw $this->createNotFoundException("This method is not supported");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an index page.
|
||||
*
|
||||
* Some steps may be overriden during this process of rendering.
|
||||
*
|
||||
* This method:
|
||||
*
|
||||
* 1. Launch `onPreIndex`
|
||||
* x. check acl. If it does return a response instance, return it
|
||||
* x. launch `onPostCheckACL`. If it does return a response instance, return it
|
||||
* 1. count the items, using `countEntities`
|
||||
* 2. build a paginator element from the the number of entities ;
|
||||
* 3. Launch `onPreIndexQuery`. If it does return a response instance, return it
|
||||
* 3. build a query, using `queryEntities`
|
||||
* x. fetch the results, using `getQueryResult`
|
||||
* x. Launch `onPostIndexFetchQuery`. If it does return a response instance, return it
|
||||
* 4. Serialize the entities in a Collection, using `SerializeCollection`
|
||||
*
|
||||
* @param string $action
|
||||
* @param Request $request
|
||||
* @return type
|
||||
*/
|
||||
protected function indexApiAction($action, Request $request, $_format)
|
||||
{
|
||||
$this->onPreIndex($action, $request, $_format);
|
||||
|
||||
$response = $this->checkACL($action, $request, $_format);
|
||||
if ($response instanceof Response) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
if (!isset($entity)) {
|
||||
$entity = '';
|
||||
}
|
||||
|
||||
$response = $this->onPostCheckACL($action, $request, $_format, $entity);
|
||||
if ($response instanceof Response) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$totalItems = $this->countEntities($action, $request, $_format);
|
||||
$paginator = $this->getPaginatorFactory()->create($totalItems);
|
||||
|
||||
$response = $this->onPreIndexBuildQuery($action, $request, $_format, $totalItems,
|
||||
$paginator);
|
||||
|
||||
if ($response instanceof Response) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$query = $this->queryEntities($action, $request, $_format, $paginator);
|
||||
|
||||
$response = $this->onPostIndexBuildQuery($action, $request, $_format, $totalItems,
|
||||
$paginator, $query);
|
||||
|
||||
if ($response instanceof Response) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$entities = $this->getQueryResult($action, $request, $_format, $totalItems, $paginator, $query);
|
||||
|
||||
$response = $this->onPostIndexFetchQuery($action, $request, $_format, $totalItems,
|
||||
$paginator, $entities);
|
||||
|
||||
if ($response instanceof Response) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
return $this->serializeCollection($action, $request, $_format, $paginator, $entities);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize collections
|
||||
*
|
||||
*/
|
||||
protected function serializeCollection(string $action, Request $request, string $_format, PaginatorInterface $paginator, $entities): Response
|
||||
{
|
||||
$model = new Collection($entities, $paginator);
|
||||
|
||||
$context = $this->getContextForSerialization($action, $request, $_format, $entities);
|
||||
|
||||
return $this->json($model, Response::HTTP_OK, [], $context);
|
||||
}
|
||||
|
||||
|
||||
protected function getContextForSerialization(string $action, Request $request, string $_format, $entity): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* get the role given from the config.
|
||||
*/
|
||||
protected function getRoleFor(string $action, Request $request, $entity, $_format): string
|
||||
{
|
||||
$actionConfig = $this->getActionConfig($action);
|
||||
|
||||
if (NULL !== $actionConfig['roles'][$request->getMethod()]) {
|
||||
return $actionConfig['roles'][$request->getMethod()];
|
||||
}
|
||||
|
||||
if ($this->crudConfig['base_role']) {
|
||||
return $this->crudConfig['base_role'];
|
||||
}
|
||||
|
||||
throw new \RuntimeException(sprintf("the config does not have any role for the ".
|
||||
"method %s nor a global role for the whole action. Add those to your ".
|
||||
"configuration or override the required method", $request->getMethod()));
|
||||
|
||||
}
|
||||
|
||||
protected function getSerializer(): SerializerInterface
|
||||
{
|
||||
return $this->get('serializer');
|
||||
}
|
||||
}
|
@@ -34,6 +34,7 @@ use Chill\MainBundle\CRUD\Form\CRUDDeleteEntityForm;
|
||||
use Chill\MainBundle\Pagination\PaginatorFactory;
|
||||
use Chill\MainBundle\Pagination\PaginatorInterface;
|
||||
use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
|
||||
use Symfony\Component\Serializer\SerializerInterface;
|
||||
|
||||
/**
|
||||
* Class CRUDController
|
||||
@@ -484,7 +485,7 @@ class CRUDController extends AbstractController
|
||||
* @param mixed $id
|
||||
* @return Response
|
||||
*/
|
||||
protected function viewAction(string $action, Request $request, $id)
|
||||
protected function viewAction(string $action, Request $request, $id, $_format = 'html'): Response
|
||||
{
|
||||
$entity = $this->getEntity($action, $id, $request);
|
||||
|
||||
@@ -496,7 +497,7 @@ class CRUDController extends AbstractController
|
||||
|
||||
if (NULL === $entity) {
|
||||
throw $this->createNotFoundException(sprintf("The %s with id %s "
|
||||
. "is not found"), $this->getCrudName(), $id);
|
||||
. "is not found", $this->getCrudName(), $id));
|
||||
}
|
||||
|
||||
$response = $this->checkACL($action, $entity);
|
||||
@@ -508,17 +509,36 @@ class CRUDController extends AbstractController
|
||||
if ($response instanceof Response) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$defaultTemplateParameters = [
|
||||
'entity' => $entity,
|
||||
'crud_name' => $this->getCrudName()
|
||||
];
|
||||
|
||||
return $this->render(
|
||||
$this->getTemplateFor($action, $entity, $request),
|
||||
$this->generateTemplateParameter($action, $entity, $request, $defaultTemplateParameters)
|
||||
|
||||
if ($_format === 'html') {
|
||||
$defaultTemplateParameters = [
|
||||
'entity' => $entity,
|
||||
'crud_name' => $this->getCrudName()
|
||||
];
|
||||
|
||||
return $this->render(
|
||||
$this->getTemplateFor($action, $entity, $request),
|
||||
$this->generateTemplateParameter($action, $entity, $request, $defaultTemplateParameters)
|
||||
);
|
||||
} elseif ($_format === 'json') {
|
||||
$context = $this->getContextForSerialization($action, $request, $entity, $_format);
|
||||
|
||||
return $this->json($entity, Response::HTTP_OK, [], $context);
|
||||
} else {
|
||||
throw new \Symfony\Component\HttpFoundation\Exception\BadRequestException("This format is not implemented");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the context for the serialization
|
||||
*/
|
||||
public function getContextForSerialization(string $action, Request $request, $entity, string $_format): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* The edit action.
|
||||
@@ -799,7 +819,7 @@ class CRUDController extends AbstractController
|
||||
*/
|
||||
protected function getRoleFor($action)
|
||||
{
|
||||
if (NULL !== ($this->getActionConfig($action)['role'])) {
|
||||
if (\array_key_exists('role', $this->getActionConfig($action))) {
|
||||
return $this->getActionConfig($action)['role'];
|
||||
}
|
||||
|
||||
@@ -1181,6 +1201,7 @@ class CRUDController extends AbstractController
|
||||
AuthorizationHelper::class => AuthorizationHelper::class,
|
||||
EventDispatcherInterface::class => EventDispatcherInterface::class,
|
||||
Resolver::class => Resolver::class,
|
||||
SerializerInterface::class => SerializerInterface::class,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
@@ -23,6 +23,9 @@ namespace Chill\MainBundle\CRUD\Routing;
|
||||
use Symfony\Component\Config\Loader\Loader;
|
||||
use Symfony\Component\Routing\Route;
|
||||
use Symfony\Component\Routing\RouteCollection;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Chill\MainBundle\CRUD\Controller\ApiController;
|
||||
use Chill\MainBundle\CRUD\Controller\CRUDController;
|
||||
|
||||
/**
|
||||
* Class CRUDRoutesLoader
|
||||
@@ -32,24 +35,34 @@ use Symfony\Component\Routing\RouteCollection;
|
||||
*/
|
||||
class CRUDRoutesLoader extends Loader
|
||||
{
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $config = [];
|
||||
protected array $crudConfig = [];
|
||||
|
||||
protected array $apiCrudConfig = [];
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
private $isLoaded = false;
|
||||
|
||||
private const ALL_SINGLE_METHODS = [
|
||||
Request::METHOD_GET,
|
||||
Request::METHOD_POST,
|
||||
Request::METHOD_PUT,
|
||||
Request::METHOD_DELETE
|
||||
];
|
||||
|
||||
private const ALL_INDEX_METHODS = [ Request::METHOD_GET, Request::METHOD_HEAD ];
|
||||
|
||||
/**
|
||||
* CRUDRoutesLoader constructor.
|
||||
*
|
||||
* @param $config
|
||||
* @param $crudConfig the config from cruds
|
||||
* @param $apicrudConfig the config from api_crud
|
||||
*/
|
||||
public function __construct($config)
|
||||
public function __construct(array $crudConfig, array $apiConfig)
|
||||
{
|
||||
$this->config = $config;
|
||||
$this->crudConfig = $crudConfig;
|
||||
$this->apiConfig = $apiConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -63,53 +76,161 @@ class CRUDRoutesLoader extends Loader
|
||||
}
|
||||
|
||||
/**
|
||||
* @return RouteCollection
|
||||
* Load routes for CRUD and CRUD Api
|
||||
*/
|
||||
public function load($resource, $type = null)
|
||||
public function load($resource, $type = null): RouteCollection
|
||||
{
|
||||
|
||||
if (true === $this->isLoaded) {
|
||||
throw new \RuntimeException('Do not add the "CRUD" loader twice');
|
||||
}
|
||||
|
||||
|
||||
$collection = new RouteCollection();
|
||||
|
||||
foreach ($this->config as $config) {
|
||||
$collection->addCollection($this->loadConfig($config));
|
||||
foreach ($this->crudConfig as $crudConfig) {
|
||||
$collection->addCollection($this->loadCrudConfig($crudConfig));
|
||||
}
|
||||
|
||||
foreach ($this->apiConfig as $crudConfig) {
|
||||
$collection->addCollection($this->loadApi($crudConfig));
|
||||
}
|
||||
|
||||
return $collection;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $config
|
||||
* Load routes for CRUD (without api)
|
||||
*
|
||||
* @param $crudConfig
|
||||
* @return RouteCollection
|
||||
*/
|
||||
protected function loadConfig($config): RouteCollection
|
||||
protected function loadCrudConfig($crudConfig): RouteCollection
|
||||
{
|
||||
$collection = new RouteCollection();
|
||||
foreach ($config['actions'] as $name => $action) {
|
||||
$controller ='cscrud_'.$crudConfig['name'].'_controller';
|
||||
|
||||
foreach ($crudConfig['actions'] as $name => $action) {
|
||||
// defaults (controller name)
|
||||
$defaults = [
|
||||
'_controller' => 'cscrud_'.$config['name'].'_controller'.':'.($action['controller_action'] ?? $name)
|
||||
'_controller' => $controller.':'.($action['controller_action'] ?? $name)
|
||||
];
|
||||
|
||||
if ($name === 'index') {
|
||||
$path = "{_locale}".$config['base_path'];
|
||||
$path = "{_locale}".$crudConfig['base_path'];
|
||||
$route = new Route($path, $defaults);
|
||||
} elseif ($name === 'new') {
|
||||
$path = "{_locale}".$config['base_path'].'/'.$name;
|
||||
$path = "{_locale}".$crudConfig['base_path'].'/'.$name;
|
||||
$route = new Route($path, $defaults);
|
||||
} else {
|
||||
$path = "{_locale}".$config['base_path'].($action['path'] ?? '/{id}/'.$name);
|
||||
$path = "{_locale}".$crudConfig['base_path'].($action['path'] ?? '/{id}/'.$name);
|
||||
$requirements = $action['requirements'] ?? [
|
||||
'{id}' => '\d+'
|
||||
];
|
||||
$route = new Route($path, $defaults, $requirements);
|
||||
}
|
||||
|
||||
$collection->add('chill_crud_'.$config['name'].'_'.$name, $route);
|
||||
$collection->add('chill_crud_'.$crudConfig['name'].'_'.$name, $route);
|
||||
}
|
||||
|
||||
return $collection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load routes for api single
|
||||
*
|
||||
* @param $crudConfig
|
||||
* @return RouteCollection
|
||||
*/
|
||||
protected function loadApi(array $crudConfig): RouteCollection
|
||||
{
|
||||
$collection = new RouteCollection();
|
||||
$controller ='csapi_'.$crudConfig['name'].'_controller';
|
||||
|
||||
foreach ($crudConfig['actions'] as $name => $action) {
|
||||
// filter only on single actions
|
||||
$singleCollection = $action['single-collection'] ?? $name === '_entity' ? 'single' : NULL;
|
||||
if ('collection' === $singleCollection) {
|
||||
// continue;
|
||||
}
|
||||
|
||||
// compute default action
|
||||
switch ($name) {
|
||||
case '_entity':
|
||||
$controllerAction = 'entityApi';
|
||||
break;
|
||||
case '_index':
|
||||
$controllerAction = 'indexApi';
|
||||
break;
|
||||
default:
|
||||
$controllerAction = $name.'Api';
|
||||
break;
|
||||
}
|
||||
|
||||
$defaults = [
|
||||
'_controller' => $controller.':'.($action['controller_action'] ?? $controllerAction)
|
||||
];
|
||||
|
||||
// path are rewritten
|
||||
// if name === 'default', we rewrite it to nothing :-)
|
||||
$localName = \in_array($name, [ '_entity', '_index' ]) ? '' : '/'.$name;
|
||||
if ('collection' === $action['single-collection'] || '_index' === $name) {
|
||||
$localPath = $action['path'] ?? $localName.'.{_format}';
|
||||
} else {
|
||||
$localPath = $action['path'] ?? '/{id}'.$localName.'.{_format}';
|
||||
}
|
||||
$path = $crudConfig['base_path'].$localPath;
|
||||
|
||||
$requirements = $action['requirements'] ?? [ '{id}' => '\d+' ];
|
||||
|
||||
$methods = \array_keys(\array_filter($action['methods'], function($value, $key) { return $value; },
|
||||
ARRAY_FILTER_USE_BOTH));
|
||||
|
||||
$route = new Route($path, $defaults, $requirements);
|
||||
$route->setMethods($methods);
|
||||
|
||||
$collection->add('chill_api_single_'.$crudConfig['name'].'_'.$name, $route);
|
||||
}
|
||||
|
||||
return $collection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load routes for api multi
|
||||
*
|
||||
* @param $crudConfig
|
||||
* @return RouteCollection
|
||||
*/
|
||||
protected function loadApiMultiConfig(array $crudConfig): RouteCollection
|
||||
{
|
||||
$collection = new RouteCollection();
|
||||
$controller ='csapi_'.$crudConfig['name'].'_controller';
|
||||
|
||||
foreach ($crudConfig['actions'] as $name => $action) {
|
||||
// filter only on single actions
|
||||
$singleCollection = $action['single-collection'] ?? $name === '_index' ? 'collection' : NULL;
|
||||
if ('single' === $singleCollection) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$defaults = [
|
||||
'_controller' => $controller.':'.($action['controller_action'] ?? '_entity' === $name ? 'entityApi' : $name.'Api')
|
||||
];
|
||||
|
||||
// path are rewritten
|
||||
// if name === 'default', we rewrite it to nothing :-)
|
||||
$localName = '_entity' === $name ? '' : '/'.$name;
|
||||
$localPath = $action['path'] ?? '/{id}'.$localName.'.{_format}';
|
||||
$path = $crudConfig['base_path'].$localPath;
|
||||
|
||||
$requirements = $action['requirements'] ?? [ '{id}' => '\d+' ];
|
||||
|
||||
$methods = \array_keys(\array_filter($action['methods'], function($value, $key) { return $value; },
|
||||
ARRAY_FILTER_USE_BOTH));
|
||||
|
||||
$route = new Route($path, $defaults, $requirements);
|
||||
$route->setMethods($methods);
|
||||
|
||||
$collection->add('chill_api_single_'.$crudConfig['name'].'_'.$name, $route);
|
||||
}
|
||||
|
||||
return $collection;
|
||||
}
|
||||
}
|
||||
|
@@ -14,6 +14,7 @@ use Chill\MainBundle\DependencyInjection\CompilerPass\NotificationCounterCompile
|
||||
use Chill\MainBundle\DependencyInjection\CompilerPass\MenuCompilerPass;
|
||||
use Chill\MainBundle\DependencyInjection\CompilerPass\ACLFlagsCompilerPass;
|
||||
use Chill\MainBundle\DependencyInjection\CompilerPass\GroupingCenterCompilerPass;
|
||||
use Chill\MainBundle\CRUD\CompilerPass\CRUDControllerCompilerPass;
|
||||
use Chill\MainBundle\Templating\Entity\CompilerPass as RenderEntityCompilerPass;
|
||||
|
||||
|
||||
@@ -33,5 +34,6 @@ class ChillMainBundle extends Bundle
|
||||
$container->addCompilerPass(new ACLFlagsCompilerPass());
|
||||
$container->addCompilerPass(new GroupingCenterCompilerPass());
|
||||
$container->addCompilerPass(new RenderEntityCompilerPass());
|
||||
$container->addCompilerPass(new CRUDControllerCompilerPass());
|
||||
}
|
||||
}
|
||||
|
63
src/Bundle/ChillMainBundle/Controller/AddressController.php
Normal file
63
src/Bundle/ChillMainBundle/Controller/AddressController.php
Normal file
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace Chill\MainBundle\Controller;
|
||||
|
||||
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
|
||||
use Symfony\Component\Routing\Annotation\Route;
|
||||
use Chill\MainBundle\Entity\Address;
|
||||
use Chill\MainBundle\Entity\AddressReference;
|
||||
|
||||
/**
|
||||
* Class AddressController
|
||||
*
|
||||
* @package Chill\MainBundle\Controller
|
||||
*/
|
||||
class AddressController extends AbstractController
|
||||
{
|
||||
|
||||
|
||||
/**
|
||||
* Get API Data for showing endpoint
|
||||
*
|
||||
* @Route(
|
||||
* "/{_locale}/main/api/1.0/address/{address_id}/show.{_format}",
|
||||
* name="chill_main_address_api_show"
|
||||
* )
|
||||
* @ParamConverter("address", options={"id": "address_id"})
|
||||
*/
|
||||
public function showAddress(Address $address, $_format): Response
|
||||
{
|
||||
// TODO check ACL ?
|
||||
switch ($_format) {
|
||||
case 'json':
|
||||
return $this->json($address);
|
||||
default:
|
||||
throw new BadRequestException('Unsupported format');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get API Data for showing endpoint
|
||||
*
|
||||
* @Route(
|
||||
* "/{_locale}/main/api/1.0/address-reference/{address_reference_id}/show.{_format}",
|
||||
* name="chill_main_address_reference_api_show"
|
||||
* )
|
||||
* @ParamConverter("addressReference", options={"id": "address_reference_id"})
|
||||
*/
|
||||
public function showAddressReference(AddressReference $addressReference, $_format): Response
|
||||
{
|
||||
// TODO check ACL ?
|
||||
switch ($_format) {
|
||||
case 'json':
|
||||
return $this->json($addressReference);
|
||||
default:
|
||||
throw new BadRequestException('Unsupported format');
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace Chill\MainBundle\DataFixtures\ORM;
|
||||
|
||||
use Doctrine\Common\DataFixtures\AbstractFixture;
|
||||
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
use Doctrine\Persistence\ObjectManager;
|
||||
use Chill\MainBundle\DataFixtures\ORM\LoadPostalCodes;
|
||||
use Chill\MainBundle\Entity\AddressReference;
|
||||
use Chill\MainBundle\Doctrine\Model\Point;
|
||||
|
||||
/**
|
||||
* Load reference addresses into database
|
||||
*
|
||||
* @author Champs Libres
|
||||
*/
|
||||
class LoadAddressReferences extends AbstractFixture implements ContainerAwareInterface, OrderedFixtureInterface {
|
||||
|
||||
|
||||
protected $faker;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->faker = \Faker\Factory::create('fr_FR');
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @var ContainerInterface
|
||||
*/
|
||||
private $container;
|
||||
|
||||
public function setContainer(ContainerInterface $container = null)
|
||||
{
|
||||
$this->container = $container;
|
||||
}
|
||||
|
||||
public function getOrder() {
|
||||
return 51;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Create a random point
|
||||
*
|
||||
* @return Point
|
||||
*/
|
||||
private function getRandomPoint()
|
||||
{
|
||||
$lonBrussels = 4.35243;
|
||||
$latBrussels = 50.84676;
|
||||
$lon = $lonBrussels + 0.01 * rand(-5, 5);
|
||||
$lat = $latBrussels + 0.01 * rand(-5, 5);
|
||||
return Point::fromLonLat($lon, $lat);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a random reference address
|
||||
*
|
||||
* @return AddressReference
|
||||
*/
|
||||
private function getRandomAddressReference()
|
||||
{
|
||||
$ar= new AddressReference();
|
||||
|
||||
$ar->setRefId($this->faker->numerify('ref-id-######'));
|
||||
$ar->setStreet($this->faker->streetName);
|
||||
$ar->setStreetNumber(rand(0,199));
|
||||
$ar ->setPoint($this->getRandomPoint());
|
||||
$ar->setPostcode($this->getReference(
|
||||
LoadPostalCodes::$refs[array_rand(LoadPostalCodes::$refs)]
|
||||
));
|
||||
|
||||
$ar->setMunicipalityCode($ar->getPostcode()->getCode());
|
||||
|
||||
return $ar
|
||||
;
|
||||
}
|
||||
|
||||
public function load(ObjectManager $manager) {
|
||||
|
||||
echo "loading some reference address... \n";
|
||||
|
||||
for ($i=0; $i<10; $i++) {
|
||||
$ar = $this->getRandomAddressReference();
|
||||
$manager->persist($ar);
|
||||
}
|
||||
|
||||
$manager->flush();
|
||||
}
|
||||
|
||||
|
||||
}
|
@@ -133,7 +133,7 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface,
|
||||
$loader->load('services/search.yaml');
|
||||
$loader->load('services/serializer.yaml');
|
||||
|
||||
$this->configureCruds($container, $config['cruds'], $loader);
|
||||
$this->configureCruds($container, $config['cruds'], $config['apis'], $loader);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -188,7 +188,12 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface,
|
||||
$container->prependExtensionConfig('doctrine', array(
|
||||
'dbal' => [
|
||||
'types' => [
|
||||
'dateinterval' => \Chill\MainBundle\Doctrine\Type\NativeDateIntervalType::class
|
||||
'dateinterval' => [
|
||||
'class' => \Chill\MainBundle\Doctrine\Type\NativeDateIntervalType::class
|
||||
],
|
||||
'point' => [
|
||||
'class' => \Chill\MainBundle\Doctrine\Type\PointType::class
|
||||
]
|
||||
]
|
||||
]
|
||||
));
|
||||
@@ -210,51 +215,24 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface,
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ContainerBuilder $container
|
||||
* @param array $config the config under 'cruds' key
|
||||
* @return null
|
||||
* Load parameter for configuration and set parameters for api
|
||||
*/
|
||||
protected function configureCruds(ContainerBuilder $container, $config, Loader\YamlFileLoader $loader)
|
||||
protected function configureCruds(
|
||||
ContainerBuilder $container,
|
||||
array $crudConfig,
|
||||
array $apiConfig,
|
||||
Loader\YamlFileLoader $loader
|
||||
): void
|
||||
{
|
||||
if (count($config) === 0) {
|
||||
if (count($crudConfig) === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$loader->load('services/crud.yaml');
|
||||
|
||||
$container->setParameter('chill_main_crud_route_loader_config', $config);
|
||||
$container->setParameter('chill_main_crud_route_loader_config', $crudConfig);
|
||||
$container->setParameter('chill_main_api_route_loader_config', $apiConfig);
|
||||
|
||||
$definition = new Definition();
|
||||
$definition
|
||||
->setClass(\Chill\MainBundle\CRUD\Routing\CRUDRoutesLoader::class)
|
||||
->addArgument('%chill_main_crud_route_loader_config%')
|
||||
;
|
||||
|
||||
$container->setDefinition('chill_main_crud_route_loader', $definition);
|
||||
|
||||
$alreadyExistingNames = [];
|
||||
|
||||
foreach ($config as $crudEntry) {
|
||||
$controller = $crudEntry['controller'];
|
||||
$controllerServiceName = 'cscrud_'.$crudEntry['name'].'_controller';
|
||||
$name = $crudEntry['name'];
|
||||
|
||||
// check for existing crud names
|
||||
if (\in_array($name, $alreadyExistingNames)) {
|
||||
throw new LogicException(sprintf("the name %s is defined twice in CRUD", $name));
|
||||
}
|
||||
|
||||
if (!$container->has($controllerServiceName)) {
|
||||
$controllerDefinition = new Definition($controller);
|
||||
$controllerDefinition->addTag('controller.service_arguments');
|
||||
$controllerDefinition->setAutoconfigured(true);
|
||||
$controllerDefinition->setClass($crudEntry['controller']);
|
||||
$container->setDefinition($controllerServiceName, $controllerDefinition);
|
||||
}
|
||||
|
||||
$container->setParameter('chill_main_crud_config_'.$name, $crudEntry);
|
||||
$container->getDefinition($controllerServiceName)
|
||||
->addMethodCall('setCrudConfig', ['%chill_main_crud_config_'.$name.'%']);
|
||||
}
|
||||
// Note: the controller are loaded inside compiler pass
|
||||
}
|
||||
}
|
||||
|
@@ -8,6 +8,7 @@ use Chill\MainBundle\DependencyInjection\Widget\Factory\WidgetFactoryInterface;
|
||||
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
|
||||
use Chill\MainBundle\DependencyInjection\Widget\AddWidgetConfigurationTrait;
|
||||
use Symfony\Component\DependencyInjection\ContainerBuilder;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
|
||||
|
||||
/**
|
||||
@@ -140,7 +141,7 @@ class Configuration implements ConfigurationInterface
|
||||
->scalarNode('controller_action')
|
||||
->defaultNull()
|
||||
->info('the method name to call in the route. Will be set to the action name if left empty.')
|
||||
->example("'action'")
|
||||
->example("action")
|
||||
->end()
|
||||
->scalarNode('path')
|
||||
->defaultNull()
|
||||
@@ -168,6 +169,78 @@ class Configuration implements ConfigurationInterface
|
||||
->end()
|
||||
|
||||
->end()
|
||||
|
||||
|
||||
->arrayNode('apis')
|
||||
->defaultValue([])
|
||||
->arrayPrototype()
|
||||
->children()
|
||||
->scalarNode('class')->cannotBeEmpty()->isRequired()->end()
|
||||
->scalarNode('controller')
|
||||
->cannotBeEmpty()
|
||||
->defaultValue(\Chill\MainBundle\CRUD\Controller\ApiController::class)
|
||||
->end()
|
||||
->scalarNode('name')->cannotBeEmpty()->isRequired()->end()
|
||||
->scalarNode('base_path')->cannotBeEmpty()->isRequired()->end()
|
||||
->scalarNode('base_role')->defaultNull()->end()
|
||||
->arrayNode('actions')
|
||||
->useAttributeAsKey('name')
|
||||
->arrayPrototype()
|
||||
->children()
|
||||
->scalarNode('controller_action')
|
||||
->defaultNull()
|
||||
->info('the method name to call in the controller. Will be set to the concatenation '.
|
||||
'of action name + \'Api\' if left empty.')
|
||||
->example("showApi")
|
||||
->end()
|
||||
->scalarNode('path')
|
||||
->defaultNull()
|
||||
->info('the path that will be **appended** after the base path. Do not forget to add ' .
|
||||
'arguments for the method. By default, will set to the action name, including an `{id}` '.
|
||||
'parameter. A suffix of action name will be appended, except if the action name '.
|
||||
'is "_entity".')
|
||||
->example('/{id}/my-action')
|
||||
->end()
|
||||
->arrayNode('requirements')
|
||||
->ignoreExtraKeys(false)
|
||||
->info('the requirements for the route. Will be set to `[ \'id\' => \'\d+\' ]` if left empty.')
|
||||
->end()
|
||||
->enumNode('single-collection')
|
||||
->values(['single', 'collection'])
|
||||
->defaultValue('single')
|
||||
->info('indicates if the returned object is a single element or a collection. '.
|
||||
'If the action name is `_index`, this value will always be considered as '.
|
||||
'`collection`')
|
||||
->end()
|
||||
->arrayNode('methods')
|
||||
->addDefaultsIfNotSet()
|
||||
->info('the allowed methods')
|
||||
->children()
|
||||
->booleanNode(Request::METHOD_GET)->defaultTrue()->end()
|
||||
->booleanNode(Request::METHOD_HEAD)->defaultTrue()->end()
|
||||
->booleanNode(Request::METHOD_POST)->defaultFalse()->end()
|
||||
->booleanNode(Request::METHOD_DELETE)->defaultFalse()->end()
|
||||
->booleanNode(Request::METHOD_PUT)->defaultFalse()->end()
|
||||
->end()
|
||||
->end()
|
||||
->arrayNode('roles')
|
||||
->addDefaultsIfNotSet()
|
||||
->info("The role require for each http method")
|
||||
->children()
|
||||
->scalarNode(Request::METHOD_GET)->defaultNull()->end()
|
||||
->scalarNode(Request::METHOD_HEAD)->defaultNull()->end()
|
||||
->scalarNode(Request::METHOD_POST)->defaultNull()->end()
|
||||
->scalarNode(Request::METHOD_DELETE)->defaultNull()->end()
|
||||
->scalarNode(Request::METHOD_PUT)->defaultNull()->end()
|
||||
->end()
|
||||
->end()
|
||||
->end()
|
||||
->end()
|
||||
->end()
|
||||
->end()
|
||||
->end()
|
||||
|
||||
->end()
|
||||
->end() // end of root/children
|
||||
->end() // end of root
|
||||
;
|
||||
|
103
src/Bundle/ChillMainBundle/Doctrine/Model/Point.php
Normal file
103
src/Bundle/ChillMainBundle/Doctrine/Model/Point.php
Normal file
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace Chill\MainBundle\Doctrine\Model;
|
||||
|
||||
use \JsonSerializable;
|
||||
|
||||
/**
|
||||
* Description of Point
|
||||
*
|
||||
*/
|
||||
class Point implements JsonSerializable {
|
||||
private float $lat;
|
||||
private float $lon;
|
||||
public static string $SRID = '4326';
|
||||
|
||||
private function __construct(float $lon, float $lat)
|
||||
{
|
||||
$this->lat = $lat;
|
||||
$this->lon = $lon;
|
||||
}
|
||||
|
||||
public function toGeoJson(): string
|
||||
{
|
||||
$array = $this->toArrayGeoJson();
|
||||
return \json_encode($array);
|
||||
}
|
||||
|
||||
public function jsonSerialize(): array
|
||||
{
|
||||
return $this->toArrayGeoJson();
|
||||
}
|
||||
|
||||
public function toArrayGeoJson(): array
|
||||
{
|
||||
return [
|
||||
"type" => "Point",
|
||||
"coordinates" => [ $this->lon, $this->lat ]
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function toWKT(): string
|
||||
{
|
||||
return 'SRID='.self::$SRID.';POINT('.$this->lon.' '.$this->lat.')';
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param type $geojson
|
||||
* @return Point
|
||||
*/
|
||||
public static function fromGeoJson(string $geojson): Point
|
||||
{
|
||||
$a = json_decode($geojson);
|
||||
//check if the geojson string is correct
|
||||
if (NULL === $a or !isset($a->type) or !isset($a->coordinates)){
|
||||
throw PointException::badJsonString($geojson);
|
||||
}
|
||||
|
||||
if ($a->type != 'Point'){
|
||||
throw PointException::badGeoType();
|
||||
}
|
||||
|
||||
$lat = $a->coordinates[1];
|
||||
$lon = $a->coordinates[0];
|
||||
|
||||
return Point::fromLonLat($lon, $lat);
|
||||
}
|
||||
|
||||
public static function fromLonLat(float $lon, float $lat): Point
|
||||
{
|
||||
if (($lon > -180 && $lon < 180) && ($lat > -90 && $lat < 90))
|
||||
{
|
||||
return new Point($lon, $lat);
|
||||
} else {
|
||||
throw PointException::badCoordinates($lon, $lat);
|
||||
}
|
||||
}
|
||||
|
||||
public static function fromArrayGeoJson(array $array): Point
|
||||
{
|
||||
if ($array['type'] == 'Point' &&
|
||||
isset($array['coordinates']))
|
||||
{
|
||||
return self::fromLonLat($array['coordinates'][0], $array['coordinates'][1]);
|
||||
}
|
||||
}
|
||||
|
||||
public function getLat(): float
|
||||
{
|
||||
return $this->lat;
|
||||
}
|
||||
|
||||
public function getLon(): float
|
||||
{
|
||||
return $this->lon;
|
||||
}
|
||||
}
|
||||
|
||||
|
27
src/Bundle/ChillMainBundle/Doctrine/Model/PointException.php
Normal file
27
src/Bundle/ChillMainBundle/Doctrine/Model/PointException.php
Normal file
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace Chill\MainBundle\Doctrine\Model;
|
||||
|
||||
use \Exception;
|
||||
|
||||
/**
|
||||
* Description of PointException
|
||||
*
|
||||
*/
|
||||
class PointException extends Exception {
|
||||
|
||||
public static function badCoordinates($lon, $lat): self
|
||||
{
|
||||
return new self("Input coordinates are not valid in the used coordinate system (longitude = $lon , latitude = $lat)");
|
||||
}
|
||||
|
||||
public static function badJsonString($str): self
|
||||
{
|
||||
return new self("The JSON string is not valid: $str");
|
||||
}
|
||||
|
||||
public static function badGeoType(): self
|
||||
{
|
||||
return new self("The geoJSON object type is not valid");
|
||||
}
|
||||
}
|
75
src/Bundle/ChillMainBundle/Doctrine/Type/PointType.php
Normal file
75
src/Bundle/ChillMainBundle/Doctrine/Type/PointType.php
Normal file
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace Chill\MainBundle\Doctrine\Type;
|
||||
|
||||
use Chill\MainBundle\Doctrine\Model\Point;
|
||||
use Doctrine\DBAL\Types\Type;
|
||||
use Doctrine\DBAL\Platforms\AbstractPlatform;
|
||||
use Chill\MainBundle\Doctrine\Model\PointException;
|
||||
|
||||
|
||||
/**
|
||||
* A Type for Doctrine to implement the Geography Point type
|
||||
* implemented by Postgis on postgis+postgresql databases
|
||||
*
|
||||
*/
|
||||
class PointType extends Type {
|
||||
|
||||
const POINT = 'point';
|
||||
|
||||
/**
|
||||
*
|
||||
* @param array $fieldDeclaration
|
||||
* @param AbstractPlatform $platform
|
||||
* @return type
|
||||
*/
|
||||
public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
|
||||
{
|
||||
return 'geometry(POINT,'.Point::$SRID.')';
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param type $value
|
||||
* @param AbstractPlatform $platform
|
||||
* @return Point
|
||||
*/
|
||||
public function convertToPHPValue($value, AbstractPlatform $platform)
|
||||
{
|
||||
if ($value === NULL){
|
||||
return NULL;
|
||||
} else {
|
||||
return Point::fromGeoJson($value);
|
||||
}
|
||||
}
|
||||
|
||||
public function getName()
|
||||
{
|
||||
return self::POINT;
|
||||
}
|
||||
|
||||
public function convertToDatabaseValue($value, AbstractPlatform $platform)
|
||||
{
|
||||
if ($value === NULL){
|
||||
return NULL;
|
||||
} else {
|
||||
return $value->toWKT();
|
||||
}
|
||||
}
|
||||
|
||||
public function canRequireSQLConversion()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function convertToPHPValueSQL($sqlExpr, $platform)
|
||||
{
|
||||
return 'ST_AsGeoJSON('.$sqlExpr.') ';
|
||||
}
|
||||
|
||||
public function convertToDatabaseValueSQL($sqlExpr, AbstractPlatform $platform)
|
||||
{
|
||||
return $sqlExpr;
|
||||
}
|
||||
}
|
||||
|
@@ -4,6 +4,8 @@ namespace Chill\MainBundle\Entity;
|
||||
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
||||
use Chill\MainBundle\Doctrine\Model\Point;
|
||||
use Chill\ThirdPartyBundle\Entity\ThirdParty;
|
||||
|
||||
/**
|
||||
* Address
|
||||
@@ -28,14 +30,14 @@ class Address
|
||||
*
|
||||
* @ORM\Column(type="string", length=255)
|
||||
*/
|
||||
private $streetAddress1 = '';
|
||||
private $street = '';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*
|
||||
* @ORM\Column(type="string", length=255)
|
||||
*/
|
||||
private $streetAddress2 = '';
|
||||
private $streetNumber = '';
|
||||
|
||||
/**
|
||||
* @var PostalCode
|
||||
@@ -43,7 +45,56 @@ class Address
|
||||
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\PostalCode")
|
||||
*/
|
||||
private $postcode;
|
||||
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*
|
||||
* @ORM\Column(type="string", length=16, nullable=true)
|
||||
*/
|
||||
private $floor;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*
|
||||
* @ORM\Column(type="string", length=16, nullable=true)
|
||||
*/
|
||||
private $corridor;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*
|
||||
* @ORM\Column(type="string", length=16, nullable=true)
|
||||
*/
|
||||
private $steps;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*
|
||||
* @ORM\Column(type="string", length=255, nullable=true)
|
||||
*/
|
||||
private $buildingName;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*
|
||||
* @ORM\Column(type="string", length=16, nullable=true)
|
||||
*/
|
||||
private $flat;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*
|
||||
* @ORM\Column(type="string", length=255, nullable=true)
|
||||
*/
|
||||
private $distribution;
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
*
|
||||
* @ORM\Column(type="string", length=255, nullable=true)
|
||||
*/
|
||||
private $extra;
|
||||
|
||||
/**
|
||||
* Indicates when the address starts validation. Used to build an history
|
||||
* of address. By default, the current date.
|
||||
@@ -53,27 +104,55 @@ class Address
|
||||
* @ORM\Column(type="date")
|
||||
*/
|
||||
private $validFrom;
|
||||
|
||||
|
||||
/**
|
||||
* Indicates when the address ends. Used to build an history
|
||||
* of address.
|
||||
*
|
||||
* @var \DateTime|null
|
||||
*
|
||||
* @ORM\Column(type="date", nullable=true)
|
||||
*/
|
||||
private $validTo;
|
||||
|
||||
/**
|
||||
* True if the address is a "no address", aka homeless person, ...
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private $isNoAddress = false;
|
||||
|
||||
|
||||
/**
|
||||
* A geospatial field storing the coordinates of the Address
|
||||
*
|
||||
* @var Point|null
|
||||
*
|
||||
* @ORM\Column(type="point", nullable=true)
|
||||
*/
|
||||
private $point;
|
||||
|
||||
/**
|
||||
* A ThirdParty reference for person's addresses that are linked to a third party
|
||||
*
|
||||
* @var ThirdParty|null
|
||||
*
|
||||
* @ORM\ManyToOne(targetEntity="Chill\ThirdPartyBundle\Entity\ThirdParty")
|
||||
* @ORM\JoinColumn(nullable=true)
|
||||
*/
|
||||
private $linkedToThirdParty;
|
||||
|
||||
/**
|
||||
* A list of metadata, added by customizable fields
|
||||
*
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $customs = [];
|
||||
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->validFrom = new \DateTime();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get id
|
||||
*
|
||||
@@ -85,7 +164,7 @@ class Address
|
||||
}
|
||||
|
||||
/**
|
||||
* Set streetAddress1
|
||||
* Set streetAddress1 (legacy function)
|
||||
*
|
||||
* @param string $streetAddress1
|
||||
*
|
||||
@@ -93,23 +172,23 @@ class Address
|
||||
*/
|
||||
public function setStreetAddress1($streetAddress1)
|
||||
{
|
||||
$this->streetAddress1 = $streetAddress1 === NULL ? '' : $streetAddress1;
|
||||
$this->street = $streetAddress1 === NULL ? '' : $streetAddress1;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get streetAddress1
|
||||
* Get streetAddress1 (legacy function)
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getStreetAddress1()
|
||||
{
|
||||
return $this->streetAddress1;
|
||||
return $this->street;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set streetAddress2
|
||||
* Set streetAddress2 (legacy function)
|
||||
*
|
||||
* @param string $streetAddress2
|
||||
*
|
||||
@@ -117,19 +196,19 @@ class Address
|
||||
*/
|
||||
public function setStreetAddress2($streetAddress2)
|
||||
{
|
||||
$this->streetAddress2 = $streetAddress2 === NULL ? '' : $streetAddress2;
|
||||
$this->streetNumber = $streetAddress2 === NULL ? '' : $streetAddress2;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get streetAddress2
|
||||
* Get streetAddress2 (legacy function)
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getStreetAddress2()
|
||||
{
|
||||
return $this->streetAddress2;
|
||||
return $this->streetNumber;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -155,7 +234,7 @@ class Address
|
||||
{
|
||||
return $this->postcode;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return \DateTime
|
||||
*/
|
||||
@@ -173,19 +252,19 @@ class Address
|
||||
$this->validFrom = $validFrom;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get IsNoAddress
|
||||
*
|
||||
*
|
||||
* Indicate true if the address is a fake address (homeless, ...)
|
||||
*
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function getIsNoAddress(): bool
|
||||
{
|
||||
return $this->isNoAddress;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
@@ -196,9 +275,9 @@ class Address
|
||||
|
||||
/**
|
||||
* Set IsNoAddress
|
||||
*
|
||||
*
|
||||
* Indicate true if the address is a fake address (homeless, ...)
|
||||
*
|
||||
*
|
||||
* @param bool $isNoAddress
|
||||
* @return $this
|
||||
*/
|
||||
@@ -207,10 +286,10 @@ class Address
|
||||
$this->isNoAddress = $isNoAddress;
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get customs informations in the address
|
||||
*
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function getCustoms(): array
|
||||
@@ -220,27 +299,27 @@ class Address
|
||||
|
||||
/**
|
||||
* Store custom informations in the address
|
||||
*
|
||||
*
|
||||
* @param array $customs
|
||||
* @return $this
|
||||
*/
|
||||
public function setCustoms(array $customs): self
|
||||
{
|
||||
$this->customs = $customs;
|
||||
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Validate the address.
|
||||
*
|
||||
*
|
||||
* Check that:
|
||||
*
|
||||
*
|
||||
* * if the address is not home address:
|
||||
* * the postal code is present
|
||||
* * the valid from is not null
|
||||
* * the address street 1 is greater than 2
|
||||
*
|
||||
*
|
||||
* @param ExecutionContextInterface $context
|
||||
* @param array $payload
|
||||
*/
|
||||
@@ -252,18 +331,18 @@ class Address
|
||||
->atPath('validFrom')
|
||||
->addViolation();
|
||||
}
|
||||
|
||||
|
||||
if ($this->isNoAddress()) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (empty($this->getStreetAddress1())) {
|
||||
$context
|
||||
->buildViolation("address.street1-should-be-set")
|
||||
->atPath('streetAddress1')
|
||||
->addViolation();
|
||||
}
|
||||
|
||||
|
||||
if (!$this->getPostcode() instanceof PostalCode) {
|
||||
$context
|
||||
->buildViolation("address.postcode-should-be-set")
|
||||
@@ -271,7 +350,7 @@ class Address
|
||||
->addViolation();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param Address $original
|
||||
* @return Address
|
||||
@@ -286,5 +365,149 @@ class Address
|
||||
;
|
||||
}
|
||||
|
||||
public function getStreet(): ?string
|
||||
{
|
||||
return $this->street;
|
||||
}
|
||||
|
||||
public function setStreet(string $street): self
|
||||
{
|
||||
$this->street = $street;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getStreetNumber(): ?string
|
||||
{
|
||||
return $this->streetNumber;
|
||||
}
|
||||
|
||||
public function setStreetNumber(string $streetNumber): self
|
||||
{
|
||||
$this->streetNumber = $streetNumber;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getFloor(): ?string
|
||||
{
|
||||
return $this->floor;
|
||||
}
|
||||
|
||||
public function setFloor(?string $floor): self
|
||||
{
|
||||
$this->floor = $floor;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getCorridor(): ?string
|
||||
{
|
||||
return $this->corridor;
|
||||
}
|
||||
|
||||
public function setCorridor(?string $corridor): self
|
||||
{
|
||||
$this->corridor = $corridor;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getSteps(): ?string
|
||||
{
|
||||
return $this->steps;
|
||||
}
|
||||
|
||||
public function setSteps(?string $steps): self
|
||||
{
|
||||
$this->steps = $steps;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getBuildingName(): ?string
|
||||
{
|
||||
return $this->buildingName;
|
||||
}
|
||||
|
||||
public function setBuildingName(?string $buildingName): self
|
||||
{
|
||||
$this->buildingName = $buildingName;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getFlat(): ?string
|
||||
{
|
||||
return $this->flat;
|
||||
}
|
||||
|
||||
public function setFlat(?string $flat): self
|
||||
{
|
||||
$this->flat = $flat;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getDistribution(): ?string
|
||||
{
|
||||
return $this->distribution;
|
||||
}
|
||||
|
||||
public function setDistribution(?string $distribution): self
|
||||
{
|
||||
$this->distribution = $distribution;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getExtra(): ?string
|
||||
{
|
||||
return $this->extra;
|
||||
}
|
||||
|
||||
public function setExtra(?string $extra): self
|
||||
{
|
||||
$this->extra = $extra;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getValidTo(): ?\DateTimeInterface
|
||||
{
|
||||
return $this->validTo;
|
||||
}
|
||||
|
||||
public function setValidTo(\DateTimeInterface $validTo): self
|
||||
{
|
||||
$this->validTo = $validTo;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPoint(): ?Point
|
||||
{
|
||||
return $this->point;
|
||||
}
|
||||
|
||||
public function setPoint(?Point $point): self
|
||||
{
|
||||
$this->point = $point;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getLinkedToThirdParty()
|
||||
{
|
||||
return $this->linkedToThirdParty;
|
||||
}
|
||||
|
||||
public function setLinkedToThirdParty($linkedToThirdParty): self
|
||||
{
|
||||
$this->linkedToThirdParty = $linkedToThirdParty;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
165
src/Bundle/ChillMainBundle/Entity/AddressReference.php
Normal file
165
src/Bundle/ChillMainBundle/Entity/AddressReference.php
Normal file
@@ -0,0 +1,165 @@
|
||||
<?php
|
||||
|
||||
namespace Chill\MainBundle\Entity;
|
||||
|
||||
use Chill\MainBundle\Entity\AddressReferenceRepository;
|
||||
use Doctrine\ORM\Mapping as ORM;
|
||||
use Chill\MainBundle\Doctrine\Model\Point;
|
||||
|
||||
/**
|
||||
* @ORM\Entity(repositoryClass=AddressReferenceRepository::class)
|
||||
* @ORM\Table(name="chill_main_address_reference")
|
||||
* @ORM\HasLifecycleCallbacks()
|
||||
*/
|
||||
class AddressReference
|
||||
{
|
||||
/**
|
||||
* @ORM\Id
|
||||
* @ORM\GeneratedValue
|
||||
* @ORM\Column(type="integer")
|
||||
*/
|
||||
private $id;
|
||||
|
||||
/**
|
||||
* @ORM\Column(type="string", length=255)
|
||||
*/
|
||||
private $refId;
|
||||
|
||||
/**
|
||||
* @ORM\Column(type="string", length=255, nullable=true)
|
||||
*/
|
||||
private $street;
|
||||
|
||||
/**
|
||||
* @ORM\Column(type="string", length=255, nullable=true)
|
||||
*/
|
||||
private $streetNumber;
|
||||
|
||||
/**
|
||||
* @var PostalCode
|
||||
*
|
||||
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\PostalCode")
|
||||
*/
|
||||
private $postcode;
|
||||
|
||||
/**
|
||||
* @ORM\Column(type="string", length=255, nullable=true)
|
||||
*/
|
||||
private $municipalityCode;
|
||||
|
||||
/**
|
||||
* @ORM\Column(type="string", length=255, nullable=true)
|
||||
*/
|
||||
private $source;
|
||||
|
||||
/**
|
||||
* A geospatial field storing the coordinates of the Address
|
||||
*
|
||||
* @var Point
|
||||
*
|
||||
* @ORM\Column(type="point")
|
||||
*/
|
||||
private $point;
|
||||
|
||||
|
||||
public function getId(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function getRefId(): ?string
|
||||
{
|
||||
return $this->refId;
|
||||
}
|
||||
|
||||
public function setRefId(string $refId): self
|
||||
{
|
||||
$this->refId = $refId;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getStreet(): ?string
|
||||
{
|
||||
return $this->street;
|
||||
}
|
||||
|
||||
public function setStreet(?string $street): self
|
||||
{
|
||||
$this->street = $street;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getStreetNumber(): ?string
|
||||
{
|
||||
return $this->streetNumber;
|
||||
}
|
||||
|
||||
public function setStreetNumber(?string $streetNumber): self
|
||||
{
|
||||
$this->streetNumber = $streetNumber;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set postcode
|
||||
*
|
||||
* @param PostalCode $postcode
|
||||
*
|
||||
* @return Address
|
||||
*/
|
||||
public function setPostcode(PostalCode $postcode = null)
|
||||
{
|
||||
$this->postcode = $postcode;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get postcode
|
||||
*
|
||||
* @return PostalCode
|
||||
*/
|
||||
public function getPostcode()
|
||||
{
|
||||
return $this->postcode;
|
||||
}
|
||||
|
||||
public function getMunicipalityCode(): ?string
|
||||
{
|
||||
return $this->municipalityCode;
|
||||
}
|
||||
|
||||
public function setMunicipalityCode(?string $municipalityCode): self
|
||||
{
|
||||
$this->municipalityCode = $municipalityCode;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getSource(): ?string
|
||||
{
|
||||
return $this->source;
|
||||
}
|
||||
|
||||
public function setSource(?string $source): self
|
||||
{
|
||||
$this->source = $source;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function getPoint(): ?Point
|
||||
{
|
||||
return $this->point;
|
||||
}
|
||||
|
||||
public function setPoint(?Point $point): self
|
||||
{
|
||||
$this->point = $point;
|
||||
|
||||
return $this;
|
||||
}
|
||||
}
|
@@ -33,8 +33,8 @@ use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
|
||||
* A type to create/update Address entity
|
||||
*
|
||||
* Options:
|
||||
*
|
||||
* - `has_valid_from` (boolean): show if an entry "has valid from" must be
|
||||
*
|
||||
* - `has_valid_from` (boolean): show if an entry "has valid from" must be
|
||||
* shown.
|
||||
* - `null_if_empty` (boolean): replace the address type by null if the street
|
||||
* or the postCode is empty. This is useful when the address is not required and
|
||||
@@ -45,10 +45,10 @@ class AddressType extends AbstractType
|
||||
public function buildForm(FormBuilderInterface $builder, array $options)
|
||||
{
|
||||
$builder
|
||||
->add('streetAddress1', TextType::class, array(
|
||||
->add('street', TextType::class, array(
|
||||
'required' => !$options['has_no_address'] // true if has no address is false
|
||||
))
|
||||
->add('streetAddress2', TextType::class, array(
|
||||
->add('streetNumber', TextType::class, array(
|
||||
'required' => false
|
||||
))
|
||||
->add('postCode', PostalCodeType::class, array(
|
||||
@@ -57,7 +57,7 @@ class AddressType extends AbstractType
|
||||
'required' => !$options['has_no_address'] // true if has no address is false
|
||||
))
|
||||
;
|
||||
|
||||
|
||||
if ($options['has_valid_from']) {
|
||||
$builder
|
||||
->add('validFrom', DateType::class, array(
|
||||
@@ -67,7 +67,7 @@ class AddressType extends AbstractType
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
if ($options['has_no_address']) {
|
||||
$builder
|
||||
->add('isNoAddress', ChoiceType::class, [
|
||||
@@ -79,12 +79,12 @@ class AddressType extends AbstractType
|
||||
'label' => 'address.address_homeless'
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
if ($options['null_if_empty'] === TRUE) {
|
||||
$builder->setDataMapper(new AddressDataMapper());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public function configureOptions(OptionsResolver $resolver)
|
||||
{
|
||||
$resolver
|
||||
|
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace Chill\MainBundle\Repository;
|
||||
|
||||
use Chill\MainBundle\Entity\AddressReference;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
/**
|
||||
* @method AddressReference|null find($id, $lockMode = null, $lockVersion = null)
|
||||
* @method AddressReference|null findOneBy(array $criteria, array $orderBy = null)
|
||||
* @method AddressReference[] findAll()
|
||||
* @method AddressReference[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
|
||||
*/
|
||||
class AddressReferenceRepository extends ServiceEntityRepository
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, AddressReference::class);
|
||||
}
|
||||
|
||||
// /**
|
||||
// * @return AddressReference[] Returns an array of AddressReference objects
|
||||
// */
|
||||
/*
|
||||
public function findByExampleField($value)
|
||||
{
|
||||
return $this->createQueryBuilder('a')
|
||||
->andWhere('a.exampleField = :val')
|
||||
->setParameter('val', $value)
|
||||
->orderBy('a.id', 'ASC')
|
||||
->setMaxResults(10)
|
||||
->getQuery()
|
||||
->getResult()
|
||||
;
|
||||
}
|
||||
*/
|
||||
|
||||
/*
|
||||
public function findOneBySomeField($value): ?AddressReference
|
||||
{
|
||||
return $this->createQueryBuilder('a')
|
||||
->andWhere('a.exampleField = :val')
|
||||
->setParameter('val', $value)
|
||||
->getQuery()
|
||||
->getOneOrNullResult()
|
||||
;
|
||||
}
|
||||
*/
|
||||
}
|
@@ -6,8 +6,8 @@
|
||||
<div class="chill_address_is_noaddress">{{ 'address.consider homeless'|trans }}</div>
|
||||
{% endif %}
|
||||
<div class="chill_address_address">
|
||||
{% if address.streetAddress1 is not empty %}<p class="street street1">{{ address.streetAddress1 }}</p>{% endif %}
|
||||
{% if address.streetAddress2 is not empty %}<p class="street street2">{{ address.streetAddress2 }}</p>{% endif %}
|
||||
{% if address.street is not empty %}<p class="street street1">{{ address.street }}</p>{% endif %}
|
||||
{% if address.streetNumber is not empty %}<p class="street street2">{{ address.streetNumber }}</p>{% endif %}
|
||||
{% if address.postCode is not empty %}
|
||||
<p class="postalCode"><span class="code">{{ address.postCode.code }}</span> <span class="name">{{ address.postCode.name }}</span></p>
|
||||
<p class="country">{{ address.postCode.country.name|localize_translatable_string }}</p>
|
||||
|
28
src/Bundle/ChillMainBundle/Serializer/Model/Collection.php
Normal file
28
src/Bundle/ChillMainBundle/Serializer/Model/Collection.php
Normal file
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace Chill\MainBundle\Serializer\Model;
|
||||
|
||||
use Chill\MainBundle\Pagination\PaginatorInterface;
|
||||
|
||||
class Collection
|
||||
{
|
||||
private PaginatorInterface $paginator;
|
||||
|
||||
private $items;
|
||||
|
||||
public function __construct($items, PaginatorInterface $paginator)
|
||||
{
|
||||
$this->items = $items;
|
||||
$this->paginator = $paginator;
|
||||
}
|
||||
|
||||
public function getPaginator(): PaginatorInterface
|
||||
{
|
||||
return $this->paginator;
|
||||
}
|
||||
|
||||
public function getItems()
|
||||
{
|
||||
return $this->items;
|
||||
}
|
||||
}
|
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace Chill\MainBundle\Serializer\Normalizer;
|
||||
|
||||
use Chill\MainBundle\Serializer\Model\Collection;
|
||||
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
|
||||
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
|
||||
use Symfony\Component\Serializer\Normalizer\NormalizerAwareTrait;
|
||||
|
||||
class CollectionNormalizer implements NormalizerInterface, NormalizerAwareInterface
|
||||
{
|
||||
use NormalizerAwareTrait;
|
||||
|
||||
public function supportsNormalization($data, string $format = null): bool
|
||||
{
|
||||
return $data instanceof Collection;
|
||||
}
|
||||
|
||||
public function normalize($collection, string $format = null, array $context = [])
|
||||
{
|
||||
/** @var $collection Collection */
|
||||
/** @var $collection Chill\MainBundle\Pagination\PaginatorInterface */
|
||||
$paginator = $collection->getPaginator();
|
||||
|
||||
$data['count'] = $paginator->getTotalItems();
|
||||
$pagination['first'] = $paginator->getCurrentPageFirstItemNumber();
|
||||
$pagination['items_per_page'] = $paginator->getItemsPerPage();
|
||||
$pagination['next'] = $paginator->hasNextPage() ?
|
||||
$paginator->getNextPage()->generateUrl() : null;
|
||||
$pagination['previous'] = $paginator->hasPreviousPage() ?
|
||||
$paginator->getPreviousPage()->generateUrl() : null;
|
||||
$pagination['more'] = $paginator->hasNextPage();
|
||||
$data['pagination'] = $pagination;
|
||||
|
||||
// normalize results
|
||||
$data['results'] = $this->normalizer->normalize($collection->getItems(),
|
||||
$format, $context);
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
119
src/Bundle/ChillMainBundle/Tests/Doctrine/Model/PointTest.php
Normal file
119
src/Bundle/ChillMainBundle/Tests/Doctrine/Model/PointTest.php
Normal file
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace Chill\MainBundle\Tests\Doctrine\Model;
|
||||
|
||||
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
|
||||
use Chill\MainBundle\Doctrine\Model\Point;
|
||||
|
||||
/**
|
||||
* Test the point model methods
|
||||
*
|
||||
* @author Julien Minet <julien.minet@champs-libres.coop>
|
||||
*/
|
||||
class ExportControllerTest extends KernelTestCase
|
||||
{
|
||||
|
||||
public function testToWKT()
|
||||
{
|
||||
$lon = 4.8634;
|
||||
$lat = 50.47382;
|
||||
$point = $this->preparePoint($lon, $lat);
|
||||
|
||||
$this->assertEquals($point->toWKT(),'SRID=4326;POINT(4.8634 50.47382)');
|
||||
}
|
||||
|
||||
public function testToGeojson()
|
||||
{
|
||||
$lon = 4.8634;
|
||||
$lat = 50.47382;
|
||||
$point = $this->preparePoint($lon, $lat);
|
||||
|
||||
$this->assertEquals($point->toGeoJson(),'{"type":"Point","coordinates":[4.8634,50.47382]}');
|
||||
}
|
||||
|
||||
public function testToArrayGeoJson()
|
||||
{
|
||||
$lon = 4.8634;
|
||||
$lat = 50.47382;
|
||||
$point = $this->preparePoint($lon, $lat);
|
||||
|
||||
$this->assertEquals(
|
||||
$point->toArrayGeoJson(),
|
||||
[
|
||||
'type' => 'Point',
|
||||
'coordinates' => [4.8634, 50.47382]
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
public function testJsonSerialize()
|
||||
{
|
||||
$lon = 4.8634;
|
||||
$lat = 50.47382;
|
||||
$point = $this->preparePoint($lon, $lat);
|
||||
|
||||
$this->assertEquals(
|
||||
$point->jsonSerialize(),
|
||||
[
|
||||
'type' => 'Point',
|
||||
'coordinates' => [4.8634, 50.47382]
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
public function testFromGeoJson()
|
||||
{
|
||||
$geojson = '{"type":"Point","coordinates":[4.8634,50.47382]}';
|
||||
$lon = 4.8634;
|
||||
$lat = 50.47382;
|
||||
$point = $this->preparePoint($lon, $lat);;
|
||||
|
||||
$this->assertEquals($point, Point::fromGeoJson($geojson));
|
||||
}
|
||||
|
||||
public function testFromLonLat()
|
||||
{
|
||||
$lon = 4.8634;
|
||||
$lat = 50.47382;
|
||||
$point = $this->preparePoint($lon, $lat);;
|
||||
|
||||
$this->assertEquals($point, Point::fromLonLat($lon, $lat));
|
||||
}
|
||||
|
||||
public function testFromArrayGeoJson()
|
||||
{
|
||||
$array = [
|
||||
'type' => 'Point',
|
||||
'coordinates' => [4.8634, 50.47382]
|
||||
];
|
||||
$lon = 4.8634;
|
||||
$lat = 50.47382;
|
||||
$point = $this->preparePoint($lon, $lat);;
|
||||
|
||||
$this->assertEquals($point, Point::fromArrayGeoJson($array));
|
||||
}
|
||||
|
||||
public function testGetLat()
|
||||
{
|
||||
$lon = 4.8634;
|
||||
$lat = 50.47382;
|
||||
$point = $this->preparePoint($lon, $lat);;
|
||||
|
||||
$this->assertEquals($lat, $point->getLat());
|
||||
}
|
||||
|
||||
public function testGetLon()
|
||||
{
|
||||
$lon = 4.8634;
|
||||
$lat = 50.47382;
|
||||
$point = $this->preparePoint($lon, $lat);;
|
||||
|
||||
$this->assertEquals($lon, $point->getLon());
|
||||
}
|
||||
|
||||
private function preparePoint($lon, $lat)
|
||||
{
|
||||
return Point::fromLonLat($lon, $lat);
|
||||
}
|
||||
|
||||
}
|
@@ -1,7 +1,8 @@
|
||||
services:
|
||||
Chill\MainBundle\CRUD\Routing\CRUDRoutesLoader:
|
||||
arguments:
|
||||
$config: '%chill_main_crud_route_loader_config%'
|
||||
$crudConfig: '%chill_main_crud_route_loader_config%'
|
||||
$apiConfig: '%chill_main_api_route_loader_config%'
|
||||
tags: [ routing.loader ]
|
||||
|
||||
Chill\MainBundle\CRUD\Resolver\Resolver:
|
||||
@@ -13,4 +14,4 @@ services:
|
||||
arguments:
|
||||
$resolver: '@Chill\MainBundle\CRUD\Resolver\Resolver'
|
||||
tags:
|
||||
- { name: twig.extension }
|
||||
- { name: twig.extension }
|
||||
|
@@ -6,6 +6,7 @@ services:
|
||||
- "@request_stack"
|
||||
- "@router"
|
||||
- "%chill_main.pagination.item_per_page%"
|
||||
|
||||
Chill\MainBundle\Pagination\PaginatorFactory: '@chill_main.paginator_factory'
|
||||
|
||||
chill_main.paginator.twig_extensions:
|
||||
|
@@ -11,3 +11,7 @@ services:
|
||||
Chill\MainBundle\Serializer\Normalizer\UserNormalizer:
|
||||
tags:
|
||||
- { name: 'serializer.normalizer', priority: 64 }
|
||||
|
||||
Chill\MainBundle\Serializer\Normalizer\CollectionNormalizer:
|
||||
tags:
|
||||
- { name: 'serializer.normalizer', priority: 64 }
|
||||
|
@@ -0,0 +1,32 @@
|
||||
<?php declare(strict_types=1);
|
||||
|
||||
namespace Chill\Migrations\Main;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* Create the postgis extension
|
||||
*/
|
||||
final class Version20210414091001 extends AbstractMigration
|
||||
{
|
||||
public function up(Schema $schema) : void
|
||||
{
|
||||
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
|
||||
|
||||
$this->addSql('CREATE EXTENSION IF NOT EXISTS postgis;');
|
||||
|
||||
}
|
||||
|
||||
public function down(Schema $schema) : void
|
||||
{
|
||||
$this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');
|
||||
|
||||
$this->addSql('DROP EXTENSION IF NOT EXISTS postgis;');
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return "Enable the postgis extension in public schema";
|
||||
}
|
||||
}
|
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Chill\Migrations\Main;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* Add new fields to address, including a Point geometry field.
|
||||
*/
|
||||
final class Version20210420115006 extends AbstractMigration
|
||||
{
|
||||
public function getDescription() : string
|
||||
{
|
||||
return 'Add a Point data type and modify the Address entity';
|
||||
}
|
||||
|
||||
public function up(Schema $schema) : void
|
||||
{
|
||||
$this->addSql('ALTER TABLE chill_main_address RENAME COLUMN streetaddress1 TO street;');
|
||||
$this->addSql('ALTER TABLE chill_main_address RENAME COLUMN streetaddress2 TO streetNumber;');
|
||||
$this->addSql('ALTER TABLE chill_main_address ADD floor VARCHAR(16) DEFAULT NULL');
|
||||
$this->addSql('ALTER TABLE chill_main_address ADD corridor VARCHAR(16) DEFAULT NULL');
|
||||
$this->addSql('ALTER TABLE chill_main_address ADD steps VARCHAR(16) DEFAULT NULL');
|
||||
$this->addSql('ALTER TABLE chill_main_address ADD buildingName VARCHAR(255) DEFAULT NULL');
|
||||
$this->addSql('ALTER TABLE chill_main_address ADD flat VARCHAR(16) DEFAULT NULL');
|
||||
$this->addSql('ALTER TABLE chill_main_address ADD distribution VARCHAR(255) DEFAULT NULL');
|
||||
$this->addSql('ALTER TABLE chill_main_address ADD extra VARCHAR(255) DEFAULT NULL');
|
||||
$this->addSql('ALTER TABLE chill_main_address ADD validTo DATE DEFAULT NULL');
|
||||
$this->addSql('ALTER TABLE chill_main_address ADD point geometry(POINT,4326) DEFAULT NULL');
|
||||
}
|
||||
|
||||
|
||||
public function down(Schema $schema) : void
|
||||
{
|
||||
$this->addSql('ALTER TABLE chill_main_address RENAME COLUMN street TO streetaddress1;');
|
||||
$this->addSql('ALTER TABLE chill_main_address RENAME COLUMN streetNumber TO streetaddress2;');
|
||||
$this->addSql('ALTER TABLE chill_main_address DROP floor');
|
||||
$this->addSql('ALTER TABLE chill_main_address DROP corridor');
|
||||
$this->addSql('ALTER TABLE chill_main_address DROP steps');
|
||||
$this->addSql('ALTER TABLE chill_main_address DROP buildingName');
|
||||
$this->addSql('ALTER TABLE chill_main_address DROP flat');
|
||||
$this->addSql('ALTER TABLE chill_main_address DROP distribution');
|
||||
$this->addSql('ALTER TABLE chill_main_address DROP extra');
|
||||
$this->addSql('ALTER TABLE chill_main_address DROP validTo');
|
||||
$this->addSql('ALTER TABLE chill_main_address DROP point');
|
||||
}
|
||||
}
|
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Chill\Migrations\Main;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* Add a AddressReference table for storing authoritative address data
|
||||
*/
|
||||
final class Version20210503085107 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Add a AddressReference table for storing authoritative address data';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql('CREATE SEQUENCE chill_main_address_reference_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE TABLE chill_main_address_reference (id INT NOT NULL, postcode_id INT DEFAULT NULL, refId VARCHAR(255) NOT NULL, street VARCHAR(255) DEFAULT NULL, streetNumber VARCHAR(255) DEFAULT NULL, municipalityCode VARCHAR(255) DEFAULT NULL, source VARCHAR(255) DEFAULT NULL, point geometry(POINT,4326) NOT NULL, PRIMARY KEY(id))');
|
||||
$this->addSql('CREATE INDEX IDX_CA6C1BD7EECBFDF1 ON chill_main_address_reference (postcode_id)');
|
||||
$this->addSql('ALTER TABLE chill_main_address_reference ADD CONSTRAINT FK_CA6C1BD7EECBFDF1 FOREIGN KEY (postcode_id) REFERENCES chill_main_postal_code (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('DROP SEQUENCE chill_main_address_reference_id_seq CASCADE');
|
||||
$this->addSql('DROP TABLE chill_main_address_reference');
|
||||
}
|
||||
}
|
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Chill\Migrations\Main;
|
||||
|
||||
use Doctrine\DBAL\Schema\Schema;
|
||||
use Doctrine\Migrations\AbstractMigration;
|
||||
|
||||
/**
|
||||
* Add linkedToThirdParty field to Address
|
||||
*/
|
||||
final class Version20210505153727 extends AbstractMigration
|
||||
{
|
||||
public function getDescription(): string
|
||||
{
|
||||
return 'Add linkedToThirdParty field to Address';
|
||||
}
|
||||
|
||||
public function up(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE chill_main_address ADD linkedToThirdParty_id INT DEFAULT NULL');
|
||||
$this->addSql('ALTER TABLE chill_main_address ADD CONSTRAINT FK_165051F6114B8DD9 FOREIGN KEY (linkedToThirdParty_id) REFERENCES chill_3party.third_party (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
|
||||
$this->addSql('CREATE INDEX IDX_165051F6114B8DD9 ON chill_main_address (linkedToThirdParty_id)');
|
||||
$this->addSql('
|
||||
CREATE TABLE chill_main_address_legacy AS
|
||||
TABLE chill_main_address;
|
||||
');
|
||||
$this->addSql('
|
||||
WITH hydrated_addresses AS (
|
||||
SELECT *, rank() OVER (PARTITION BY pa_a.person_id ORDER BY validfrom)
|
||||
FROM chill_main_address AS aa JOIN chill_person_persons_to_addresses AS pa_a ON aa.id = pa_a.address_id
|
||||
)
|
||||
UPDATE chill_main_address AS b
|
||||
SET validto = (
|
||||
SELECT validfrom - INTERVAL \'1 DAY\'
|
||||
FROM hydrated_addresses
|
||||
WHERE hydrated_addresses.id = (
|
||||
SELECT a1.id
|
||||
FROM hydrated_addresses AS a1 JOIN hydrated_addresses AS a2 ON a2.person_id = a1.person_id AND a2.rank = (a1.rank-1)
|
||||
WHERE a2.id = b.id
|
||||
)
|
||||
);
|
||||
');
|
||||
}
|
||||
|
||||
public function down(Schema $schema): void
|
||||
{
|
||||
$this->addSql('ALTER TABLE chill_main_address DROP CONSTRAINT FK_165051F6114B8DD9');
|
||||
$this->addSql('DROP INDEX IDX_165051F6114B8DD9');
|
||||
$this->addSql('ALTER TABLE chill_main_address DROP linkedToThirdParty_id');
|
||||
$this->addSql('DROP TABLE IF EXISTS chill_main_address_legacy');
|
||||
$this->addSql('
|
||||
UPDATE chill_main_address
|
||||
SET validto = null;
|
||||
');
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user