Compare commits

..

101 Commits

Author SHA1 Message Date
Pol Dellaiera
8364518282 Rename ChillPersonBundle:AccompanyingPeriod to ChillPersonBundle:AccompanyingPeriodParticipation. 2021-05-14 08:48:40 +02:00
Marc Ducobu
4e50d0ace9 Merge branch 'fix-style-stuff2' into 'master'
Fix style stuff2

See merge request Chill-Projet/chill-bundles!47
2021-05-12 14:06:46 +00:00
Marc Ducobu
0b54adeb59 Removing spaces at the end of line 2021-05-12 16:04:42 +02:00
Marc Ducobu
5d23de4862 Removing spaces at the end of line 2021-05-12 16:04:27 +02:00
a63c38b6aa Merge branch '37_modal_add-persons' 2021-05-07 15:46:38 +02:00
8915c42008 endpoint DELETE participation works ! 2021-05-07 15:44:08 +02:00
503293a359 Merge branch 'master' into '37_modal_add-persons'
# Conflicts:
#   src/Bundle/ChillPersonBundle/Entity/AccompanyingPeriod.php
#   src/Bundle/ChillPersonBundle/chill.webpack.config.js
2021-05-07 13:35:48 +00:00
7bdf71315a move Modal component in ChillMainAssets 2021-05-07 15:28:50 +02:00
6f5d457122 renaming store state dict name 2021-05-07 15:16:27 +02:00
b4274264a7 create addPersons store module, move state/getters/mutations/actions in module 2021-05-07 15:04:36 +02:00
8002725c87 fix doc for api 2021-05-07 12:42:49 +02:00
2c9edf3741 Set Collection normalization to fit into specs from https://gitlab.com/champs-libres/departement-de-la-vendee/chill/-/issues/136 2021-05-07 12:13:24 +02:00
3f562449e1 Merge branch 'issue23_addresses' into 'master'
Issue23 addresses

See merge request Chill-Projet/chill-bundles!12
2021-05-07 09:27:56 +00:00
1cce39bcb5 Merge branch 'bootstrap-api' into 'master'
Bootstrap api

See merge request Chill-Projet/chill-bundles!35
2021-05-07 09:14:11 +00:00
ad690db886 display reset link + minor changes 2021-05-07 10:36:50 +02:00
nobohan
1b8462b40d update validto field in chill_main_address for legacy 2021-05-07 10:27:11 +02:00
Pol Dellaiera
8c98f2cf6e Update .gitignore file. 2021-05-07 09:04:29 +02:00
f3260f57a4 fix display elements order
selectAndSuggested method in store getter, is callable in all components,
and make union of two arrays: suggested and selected

* we need to have selected in last position (required for isChecked method to work well)
* but we want to display selected in first position (for better ux)

then, we use double inversion to obtain good behaviour
2021-05-06 19:23:28 +02:00
b4ad0128e4 manage selected and suggested arrays: fix duplicate 2021-05-06 19:15:25 +02:00
33457d3cbc Merge branch 'fix-accompanying-period-opening' into bootstrap-api 2021-05-06 16:02:13 +02:00
e919b4322e fix accompanying period/remove person 2021-05-06 15:49:38 +02:00
b6131379f9 Merge remote-tracking branch 'origin/master' into bootstrap-api 2021-05-06 13:20:12 +02:00
e1fcc41ace avoiding duplicates between selected and suggested (wip)
see comments in store/index.js
2021-05-06 13:16:26 +02:00
f2a04cebe6 configure origin route into chillMainExtension 2021-05-06 13:12:18 +02:00
c693002ddb documentation for api - prepend config 2021-05-06 13:11:59 +02:00
ee77c8540a fix typos 2021-05-06 13:00:59 +02:00
a536d2780e fix state mutation for closeParticipation 2021-05-06 12:57:53 +02:00
f880598052 documentation for api 2021-05-06 12:56:19 +02:00
e7985ea52f customize controller for origin 2021-05-06 12:55:40 +02:00
f56dc65021 fix argument order 2021-05-06 12:55:12 +02:00
nobohan
4770758aee add migrations for addresse on household + add linkedtothirdparty on address 2021-05-06 12:36:58 +02:00
90fe484d81 fix api for rendering a single item 2021-05-06 12:18:47 +02:00
2b8bbe019d first impl for index action 2021-05-06 12:08:45 +02:00
9e1c151402 réinitialize suggested, avoiding double with selected (wip) 2021-05-06 10:57:04 +02:00
088e522292 Merge branch 'master' into _31_interface_creation_parcours 2021-05-06 10:55:22 +02:00
b8e6e98a74 fix payload error with add participation 2021-05-06 10:44:15 +02:00
07e0692783 bootstrap api and apply on accompanying period 2021-05-06 00:14:36 +02:00
e78d53064b closeParticipation fetch DELETE request 2021-05-05 21:48:00 +02:00
e6fcb5ff22 Merge branch '_test_closePerson' into _31_interface_creation_parcours 2021-05-05 20:47:39 +02:00
f02e33fda7 first impl for api 2021-05-05 20:33:34 +02:00
1bbec9efae improve addpersons store cycle: init query, selections and suggestions 2021-05-05 19:25:28 +02:00
3b53c4451c fix modal ux counter position 2021-05-05 18:45:51 +02:00
30f490959b for each selected, loop for post participation, then get response and commit state 2021-05-05 18:44:26 +02:00
nobohan
0a894b0db1 add new fields on Address and Household 2021-05-05 18:24:58 +02:00
c20e9507d5 prepare close participation button (wip) 2021-05-05 15:03:58 +02:00
f89c690f1b add scratch fontawesome 'remove' button 2021-05-05 13:36:45 +02:00
nobohan
f61af9d02a add household and householdmembers entities + migration 2021-05-05 11:44:55 +02:00
120e7cade5 simplify store suggested array 2021-05-05 11:11:13 +02:00
ac550e05e8 improve addPersons modal ux 2021-05-05 09:29:57 +02:00
nobohan
86c177bbbb remove vuejs address component 2021-05-04 17:26:47 +02:00
cc8de353d4 moving selected counter + cleaning code 2021-05-04 10:48:58 +02:00
4495a5d33b Union suggested and selected results 2021-05-03 23:15:38 +02:00
9dffe30aad Merge branch '_31_interface_creation_parcours' of gitlab.com:Chill-Projet/chill-bundles into _31_interface_creation_parcours 2021-05-03 22:53:47 +02:00
d393e74896 save checkboxes state in store 2021-05-03 22:44:28 +02:00
daf083dc88 save checkboxes state in store 2021-05-03 21:02:15 +02:00
nobohan
ce859697b5 Use json endpoint for showing address with Vuejs Components (WIP) 2021-05-03 17:16:45 +02:00
nobohan
1587c762f8 better fixture for AddressReference 2021-05-03 14:34:23 +02:00
nobohan
17c01d9b46 fix fixture for address reference 2021-05-03 12:18:21 +02:00
a1bb9ea352 modal addPerson design, search field: focus and position fixed 2021-05-03 11:52:06 +02:00
nobohan
a1895ec65f fixture for addressReference - WIP 2021-05-03 11:18:31 +02:00
nobohan
c5faa0b99d update the address fixture by adding some points 2021-05-03 09:28:05 +02:00
nobohan
e9d142f3e8 define legacy functions for Address 2021-05-03 09:28:05 +02:00
nobohan
91860afd80 check if point value is null for 2 methods in PointType 2021-05-03 09:28:05 +02:00
nobohan
bec0700d39 Point model: better handling of exception 2021-05-03 09:28:05 +02:00
nobohan
05d3d7f5c7 update twig template and AddressType following the changes in Address entity 2021-05-03 09:28:05 +02:00
nobohan
ebff36d257 add unit test for class Point 2021-05-03 09:28:05 +02:00
nobohan
a709b3afb6 add addressReference in Chill Main + migration 2021-05-03 09:28:05 +02:00
nobohan
69a3c6a9b2 refine the migration comment 2021-05-03 09:28:05 +02:00
juminet
8c33d876e8 code formatting in PointType 2021-05-03 09:28:05 +02:00
nobohan
1ec2fbcc16 translated exception messages in English 2021-05-03 09:28:05 +02:00
juminet
bc4e29141b syntax (null -> NULL and == -> ===) 2021-05-03 09:28:05 +02:00
nobohan
e90ea31683 add type hinting in Point and PointException 2021-05-03 09:28:05 +02:00
juminet
7c99f0b3e0 array synatx: array() -> [] 2021-05-03 09:28:05 +02:00
nobohan
c089960707 add type hinting in Point and PointException 2021-05-03 09:28:05 +02:00
nobohan
0b2f29f1e8 add migration for address 2021-05-03 09:28:05 +02:00
nobohan
9a4f50472a add point type + Address: add Point field : fix dependency injection of the Point type 2021-05-03 09:28:05 +02:00
nobohan
7d1a1c4004 #32 add point type + Address: add Point field + add null on nullable fields 2021-05-03 09:28:05 +02:00
nobohan
ebd58d4229 add more fields to Address entity + rename streetAddress1 and streetAddress2 2021-05-03 09:25:41 +02:00
nobohan
dd48795f64 #23 enable postgis in a chil main migration 2021-05-03 09:25:41 +02:00
3d45b6687f adding addPersons component with modal, search field and basic suggestions 2021-04-30 23:18:57 +02:00
35e6d36ce0 fetch postParticipation request, catch fetch error, store mutation+action 2021-04-30 16:33:49 +02:00
4900c81c11 improve inheritance with translations i18n.js files
vue-i18n --> chill main i18n ---( )---> app index
chill bundle i18n --> app i18n --^
2021-04-30 16:32:06 +02:00
ec68e6f761 make inheritance for vue translations i18n.js files
By importing only the app i18n file,
we benefit from the whole inherited chain:

app i18n < chill bundle i18n < chill main bundle i18n
2021-04-29 18:32:22 +02:00
25bd170f6b improve modal system, test when a modal call next modal 2021-04-29 15:49:25 +02:00
6939b4a313 Merge branch 'master' into _31_interface_creation_parcours 2021-04-29 14:19:02 +02:00
d18922ed98 permit multiple modals in same component 2021-04-29 14:04:40 +02:00
e8bf242c42 Merge branch '_31_interface_creation_parcours' of gitlab.com:Chill-Projet/chill-bundles into _31_interface_creation_parcours 2021-04-29 12:44:29 +02:00
2050460bb3 add modal system, added/removed managed by vue, appearence managed by bootstrap
Modal component is an hybrid solution between :
- Vue3 modal implementation
  => with 'v-if:showModal' directive:parameter, html scope is added/removed not just shown/hidden
  => with slot we can pass content from parent component
  => some classes are passed from parent component
- Bootstrap 4.4 _modal.scss module
  => using bootstrap css classes, the modal have a responsive behaviour,
  => modal design can be configured using css classes (size, scroll)

See
* https://v3.vuejs.org/examples/modal.html#modal-component
* https://github.com/bootstrap-vue/bootstrap-vue/issues/5196
2021-04-29 12:40:28 +02:00
nobohan
4add30e895 add fixture for parcours: replace createQuery by createQueryBuilder 2021-04-29 12:23:41 +02:00
e1dbfdafd7 test modals with vue and modals with bootstrap 2021-04-28 22:01:05 +02:00
75becb2294 Merge branch '_31_interface_creation_parcours' of gitlab.com:Chill-Projet/chill-bundles into _31_interface_creation_parcours 2021-04-28 21:58:52 +02:00
94e494361f adding show/edit links (prepare modal) + save button 2021-04-28 18:00:46 +02:00
nobohan
d27bdf68fb Merge branch '_31_interface_creation_parcours' of https://gitlab.com/Chill-Projet/chill-bundles into _31_interface_creation_parcours
merge..
2021-04-28 12:24:29 +02:00
nobohan
82b82920e1 add 2 fixtures for parcours 2021-04-28 12:24:25 +02:00
4bb3eadf91 renaming vuejs root dir 2021-04-28 11:41:15 +02:00
3a0c25c871 fix addPerson feature with vue3+store+i18n 2021-04-28 10:10:16 +02:00
083338da8d Merge branch 'master' into _31_interface_creation_parcours 2021-04-28 08:54:20 +02:00
37e5c9ceaa Merge branch '_31_interface_creation_parcours' of gitlab.com:Chill-Projet/chill-bundles into _31_interface_creation_parcours 2021-04-28 08:49:32 +02:00
4cf77a9b0e adapt multi components to new store and new api endpoints
* base of i18n (yarn add new deps)
2021-04-27 22:03:39 +02:00
nobohan
c2a4a95eba add a fixture for accompanying period - wip 2021-04-27 18:52:37 +02:00
01f9d03b14 init vuex store 2021-04-27 15:11:13 +02:00
478 changed files with 33302 additions and 1707 deletions

3
.gitignore vendored
View File

@@ -1,8 +1,8 @@
.composer/* .composer/*
composer.phar composer.phar
composer.lock composer.lock
docs/build/ docs/build/
.php_cs.cache
###> symfony/framework-bundle ### ###> symfony/framework-bundle ###
/.env.local /.env.local
@@ -19,3 +19,4 @@ docs/build/
/phpunit.xml /phpunit.xml
.phpunit.result.cache .phpunit.result.cache
###< phpunit/phpunit ### ###< phpunit/phpunit ###

View File

@@ -13,7 +13,7 @@
"Chill\\EventBundle\\": "src/Bundle/ChillEventBundle", "Chill\\EventBundle\\": "src/Bundle/ChillEventBundle",
"Chill\\FamilyMemberBundle\\": "src/Bundle/ChillFamilyMemberBundle", "Chill\\FamilyMemberBundle\\": "src/Bundle/ChillFamilyMemberBundle",
"Chill\\MainBundle\\": "src/Bundle/ChillMainBundle", "Chill\\MainBundle\\": "src/Bundle/ChillMainBundle",
"Chill\\PersonBundle\\": "src/Bundle/ChillPersonBundle/src", "Chill\\PersonBundle\\": "src/Bundle/ChillPersonBundle",
"Chill\\ReportBundle\\": "src/Bundle/ChillReportBundle", "Chill\\ReportBundle\\": "src/Bundle/ChillReportBundle",
"Chill\\TaskBundle\\": "src/Bundle/ChillTaskBundle", "Chill\\TaskBundle\\": "src/Bundle/ChillTaskBundle",
"Chill\\ThirdPartyBundle\\": "src/Bundle/ChillThirdPartyBundle" "Chill\\ThirdPartyBundle\\": "src/Bundle/ChillThirdPartyBundle"

View File

@@ -0,0 +1,453 @@
.. Copyright (C) 2014 Champs Libres Cooperative SCRLFS
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
A copy of the license is included in the section entitled "GNU
Free Documentation License".
.. _api:
API
###
Chill provides a basic framework to build REST api.
Configure a route
=================
Follow those steps to build a REST api:
1. Create your model;
2. Configure the API;
You can also:
* hook into the controller to customize some steps;
* add more route and steps
.. note::
Useful links:
* `How to use annotation to configure serialization <https://symfony.com/doc/current/serializer.html>`_
* `How to create your custom normalizer <https://symfony.com/doc/current/serializer/custom_normalizer.html>`_
Auto-loading the routes
***********************
Ensure that those lines are present in your file `app/config/routing.yml`:
.. code-block:: yaml
chill_cruds:
resource: 'chill_main_crud_route_loader:load'
type: service
Create your model
*****************
Create your model on the usual way:
.. code-block:: php
namespace Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\AccompanyingPeriod\OriginRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=OriginRepository::class)
* @ORM\Table(name="chill_person_accompanying_period_origin")
*/
class Origin
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="json")
*/
private $label;
/**
* @ORM\Column(type="date_immutable", nullable=true)
*/
private $noActiveAfter;
// .. getters and setters
}
Configure api
*************
Configure the api using Yaml (see the full configuration: :ref:`api_full_configuration`):
.. code-block:: yaml
# config/packages/chill_main.yaml
chill_main:
apis:
accompanying_period_origin:
base_path: '/api/1.0/person/accompanying-period/origin'
class: 'Chill\PersonBundle\Entity\AccompanyingPeriod\Origin'
name: accompanying_period_origin
base_role: 'ROLE_USER'
actions:
_index:
methods:
GET: true
HEAD: true
_entity:
methods:
GET: true
HEAD: true
.. note::
If you are working on a shared bundle (aka "The chill bundles"), you should define your configuration inside the class :code:`ChillXXXXBundleExtension`, using the "prependConfig" feature:
.. code-block:: php
namespace Chill\PersonBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Class ChillPersonExtension
* Loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
* @package Chill\PersonBundle\DependencyInjection
*/
class ChillPersonExtension extends Extension implements PrependExtensionInterface
{
public function prepend(ContainerBuilder $container)
{
$this->prependCruds($container);
}
/**
* @param ContainerBuilder $container
*/
protected function prependCruds(ContainerBuilder $container)
{
$container->prependExtensionConfig('chill_main', [
'apis' => [
[
'class' => \Chill\PersonBundle\Entity\AccompanyingPeriod\Origin::class,
'name' => 'accompanying_period_origin',
'base_path' => '/api/1.0/person/accompanying-period/origin',
'controller' => \Chill\PersonBundle\Controller\OpeningApiController::class,
'base_role' => 'ROLE_USER',
'actions' => [
'_index' => [
'methods' => [
Request::METHOD_GET => true,
Request::METHOD_HEAD => true
],
],
'_entity' => [
'methods' => [
Request::METHOD_GET => true,
Request::METHOD_HEAD => true
]
],
]
]
]
]);
}
}
The :code:`_index` and :code:`_entity` action
=============================================
The :code:`_index` and :code:`_entity` action are default actions:
* they will call a specific method in the default controller;
* they will generate defined routes:
Index:
Name: :code:`chill_api_single_accompanying_period_origin__index`
Path: :code:`/api/1.0/person/accompanying-period/origin.{_format}`
Entity:
Name: :code:`chill_api_single_accompanying_period_origin__entity`
Path: :code:`/api/1.0/person/accompanying-period/origin/{id}.{_format}`
Role
====
By default, the key `base_role` is used to check ACL. Take care of creating the :code:`Voter` required to take that into account.
For index action, the role will be called with :code:`NULL` as :code:`$subject`. The retrieved entity will be the subject for single queries.
You can also define a role for each method. In this case, this role is used for the given method, and, if any, the base role is taken into account.
.. code-block:: yaml
# config/packages/chill_main.yaml
chill_main:
apis:
accompanying_period_origin:
base_path: '/api/1.0/person/bla/bla'
class: 'Chill\PersonBundle\Entity\Blah'
name: bla
actions:
_entity:
methods:
GET: true
HEAD: true
roles:
GET: MY_ROLE_SEE
HEAD: MY ROLE_SEE
Customize the controller
========================
You can customize the controller by hooking into the default actions. Take care of extending :code:`Chill\MainBundle\CRUD\Controller\ApiController`.
.. code-block:: php
namespace Chill\PersonBundle\Controller;
use Chill\MainBundle\CRUD\Controller\ApiController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class OpeningApiController extends ApiController
{
protected function customizeQuery(string $action, Request $request, $qb): void
{
$qb->where($qb->expr()->gt('e.noActiveAfter', ':now'))
->orWhere($qb->expr()->isNull('e.noActiveAfter'));
$qb->setParameter('now', new \DateTime('now'));
}
}
And set your controller in configuration:
.. code-block:: yaml
chill_main:
apis:
accompanying_period_origin:
base_path: '/api/1.0/person/accompanying-period/origin'
class: 'Chill\PersonBundle\Entity\AccompanyingPeriod\Origin'
name: accompanying_period_origin
# add a controller
controller: 'Chill\PersonBundle\Controller\OpeningApiController'
base_role: 'ROLE_USER'
actions:
_index:
methods:
GET: true
HEAD: true
_entity:
methods:
GET: true
HEAD: true
Create your own actions
=======================
You can add your own actions:
.. code-block:: yaml
chill_main:
apis:
-
class: Chill\PersonBundle\Entity\AccompanyingPeriod
name: accompanying_course
base_path: /api/1.0/person/accompanying-course
controller: Chill\PersonBundle\Controller\AccompanyingCourseApiController
actions:
# add a custom participation:
participation:
methods:
POST: true
DELETE: true
GET: false
HEAD: false
PUT: false
roles:
POST: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE
DELETE: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE
GET: null
HEAD: null
PUT: null
single-collection: single
The key :code:`single-collection` with value :code:`single` will add a :code:`/{id}/ + "action name"` (in this example, :code:`/{id}/participation`) into the path, after the base path. If the value is :code:`collection`, no id will be set, but the action name will be append to the path.
Then, create the corresponding action into your controller:
.. code-block:: php
namespace Chill\PersonBundle\Controller;
use Chill\MainBundle\CRUD\Controller\ApiController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Chill\PersonBundle\Privacy\AccompanyingPeriodPrivacyEvent;
use Chill\PersonBundle\Entity\Person;
class AccompanyingCourseApiController extends ApiController
{
protected EventDispatcherInterface $eventDispatcher;
protected ValidatorInterface $validator;
public function __construct(EventDispatcherInterface $eventDispatcher, $validator)
{
$this->eventDispatcher = $eventDispatcher;
$this->validator = $validator;
}
public function participationApi($id, Request $request, $_format)
{
/** @var AccompanyingPeriod $accompanyingPeriod */
$accompanyingPeriod = $this->getEntity('participation', $id, $request);
$person = $this->getSerializer()
->deserialize($request->getContent(), Person::class, $_format, []);
if (NULL === $person) {
throw new BadRequestException('person id not found');
}
$this->onPostCheckACL('participation', $request, $accompanyingPeriod, $_format);
switch ($request->getMethod()) {
case Request::METHOD_POST:
$participation = $accompanyingPeriod->addPerson($person);
break;
case Request::METHOD_DELETE:
$participation = $accompanyingPeriod->removePerson($person);
break;
default:
throw new BadRequestException("This method is not supported");
}
$errors = $this->validator->validate($accompanyingPeriod);
if ($errors->count() > 0) {
// only format accepted
return $this->json($errors);
}
$this->getDoctrine()->getManager()->flush();
return $this->json($participation);
}
}
Serialization for collection
============================
A specific model has been defined for returning collection:
.. code-block:: json
{
"count": 49,
"results": [
],
"pagination": {
"more": true,
"next": "/api/1.0/search.json&q=xxxx......&page=2",
"previous": null,
"first": 0,
"items_per_page": 1
}
}
This can be achieved quickly by assembling results into a :code:`Chill\MainBundle\Serializer\Model\Collection`. The pagination information is given by using :code:`Paginator` (see :ref:`Pagination <pagination-ref>`).
.. code-block:: php
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Chill\MainBundle\Pagination\PaginatorInterface;
class MyController extends AbstractController
{
protected function serializeCollection(PaginatorInterface $paginator, $entities): Response
{
$model = new Collection($entities, $paginator);
return $this->json($model, Response::HTTP_OK, [], $context);
}
}
.. _api_full_configuration:
Full configuration example
==========================
.. code-block:: yaml
apis:
-
class: Chill\PersonBundle\Entity\AccompanyingPeriod
name: accompanying_course
base_path: /api/1.0/person/accompanying-course
controller: Chill\PersonBundle\Controller\AccompanyingCourseApiController
actions:
_entity:
roles:
GET: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE
HEAD: null
POST: null
DELETE: null
PUT: null
controller_action: null
path: null
single-collection: single
methods:
GET: true
HEAD: true
POST: false
DELETE: false
PUT: false
participation:
methods:
POST: true
DELETE: true
GET: false
HEAD: false
PUT: false
roles:
POST: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE
DELETE: CHILL_PERSON_ACCOMPANYING_PERIOD_SEE
GET: null
HEAD: null
PUT: null
controller_action: null
# the requirements for the route. Will be set to `[ 'id' => '\d+' ]` if left empty.
requirements: []
path: null
single-collection: single
base_role: null

View File

@@ -16,6 +16,7 @@ As Chill rely on the `symfony <http://symfony.com>`_ framework, reading the fram
Instructions to create a new bundle <create-a-new-bundle.rst> Instructions to create a new bundle <create-a-new-bundle.rst>
CRUD (Create - Update - Delete) for one entity <crud.rst> CRUD (Create - Update - Delete) for one entity <crud.rst>
Helpers for building a REST API <api.rst>
Routing <routing.rst> Routing <routing.rst>
Menus <menus.rst> Menus <menus.rst>
Forms <forms.rst> Forms <forms.rst>

View File

@@ -7,6 +7,8 @@
Free Documentation License". Free Documentation License".
.. _pagination-ref:
Pagination Pagination
########## ##########
@@ -15,7 +17,7 @@ The Bundle :code:`Chill\MainBundle` provides a **Pagination** api which allow yo
A simple example A simple example
**************** ****************
In the controller, get the :class:`Chill\Main\Pagination\PaginatorFactory` from the `Container` and use this :code:`PaginatorFactory` to create a :code:`Paginator` instance. In the controller, get the :code:`Chill\Main\Pagination\PaginatorFactory` from the `Container` and use this :code:`PaginatorFactory` to create a :code:`Paginator` instance.
.. literalinclude:: pagination/example.php .. literalinclude:: pagination/example.php

View File

@@ -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);
}
}

View File

@@ -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');
}
}

View 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');
}
}

View File

@@ -34,6 +34,7 @@ use Chill\MainBundle\CRUD\Form\CRUDDeleteEntityForm;
use Chill\MainBundle\Pagination\PaginatorFactory; use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Pagination\PaginatorInterface; use Chill\MainBundle\Pagination\PaginatorInterface;
use Chill\MainBundle\Security\Authorization\AuthorizationHelper; use Chill\MainBundle\Security\Authorization\AuthorizationHelper;
use Symfony\Component\Serializer\SerializerInterface;
/** /**
* Class CRUDController * Class CRUDController
@@ -484,7 +485,7 @@ class CRUDController extends AbstractController
* @param mixed $id * @param mixed $id
* @return Response * @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); $entity = $this->getEntity($action, $id, $request);
@@ -496,7 +497,7 @@ class CRUDController extends AbstractController
if (NULL === $entity) { if (NULL === $entity) {
throw $this->createNotFoundException(sprintf("The %s with id %s " 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); $response = $this->checkACL($action, $entity);
@@ -508,17 +509,36 @@ class CRUDController extends AbstractController
if ($response instanceof Response) { if ($response instanceof Response) {
return $response; return $response;
} }
$defaultTemplateParameters = [ if ($_format === 'html') {
'entity' => $entity, $defaultTemplateParameters = [
'crud_name' => $this->getCrudName() 'entity' => $entity,
]; 'crud_name' => $this->getCrudName()
];
return $this->render(
$this->getTemplateFor($action, $entity, $request), return $this->render(
$this->generateTemplateParameter($action, $entity, $request, $defaultTemplateParameters) $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. * The edit action.
@@ -799,7 +819,7 @@ class CRUDController extends AbstractController
*/ */
protected function getRoleFor($action) protected function getRoleFor($action)
{ {
if (NULL !== ($this->getActionConfig($action)['role'])) { if (\array_key_exists('role', $this->getActionConfig($action))) {
return $this->getActionConfig($action)['role']; return $this->getActionConfig($action)['role'];
} }
@@ -1181,6 +1201,7 @@ class CRUDController extends AbstractController
AuthorizationHelper::class => AuthorizationHelper::class, AuthorizationHelper::class => AuthorizationHelper::class,
EventDispatcherInterface::class => EventDispatcherInterface::class, EventDispatcherInterface::class => EventDispatcherInterface::class,
Resolver::class => Resolver::class, Resolver::class => Resolver::class,
SerializerInterface::class => SerializerInterface::class,
] ]
); );
} }

View File

@@ -23,6 +23,9 @@ namespace Chill\MainBundle\CRUD\Routing;
use Symfony\Component\Config\Loader\Loader; use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\Routing\Route; use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\HttpFoundation\Request;
use Chill\MainBundle\CRUD\Controller\ApiController;
use Chill\MainBundle\CRUD\Controller\CRUDController;
/** /**
* Class CRUDRoutesLoader * Class CRUDRoutesLoader
@@ -32,24 +35,34 @@ use Symfony\Component\Routing\RouteCollection;
*/ */
class CRUDRoutesLoader extends Loader class CRUDRoutesLoader extends Loader
{ {
/** protected array $crudConfig = [];
* @var array
*/ protected array $apiCrudConfig = [];
protected $config = [];
/** /**
* @var bool * @var bool
*/ */
private $isLoaded = false; 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. * 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) { if (true === $this->isLoaded) {
throw new \RuntimeException('Do not add the "CRUD" loader twice'); throw new \RuntimeException('Do not add the "CRUD" loader twice');
} }
$collection = new RouteCollection(); $collection = new RouteCollection();
foreach ($this->config as $config) { foreach ($this->crudConfig as $crudConfig) {
$collection->addCollection($this->loadConfig($config)); $collection->addCollection($this->loadCrudConfig($crudConfig));
} }
foreach ($this->apiConfig as $crudConfig) {
$collection->addCollection($this->loadApi($crudConfig));
}
return $collection; return $collection;
} }
/** /**
* @param $config * Load routes for CRUD (without api)
*
* @param $crudConfig
* @return RouteCollection * @return RouteCollection
*/ */
protected function loadConfig($config): RouteCollection protected function loadCrudConfig($crudConfig): RouteCollection
{ {
$collection = new 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 = [ $defaults = [
'_controller' => 'cscrud_'.$config['name'].'_controller'.':'.($action['controller_action'] ?? $name) '_controller' => $controller.':'.($action['controller_action'] ?? $name)
]; ];
if ($name === 'index') { if ($name === 'index') {
$path = "{_locale}".$config['base_path']; $path = "{_locale}".$crudConfig['base_path'];
$route = new Route($path, $defaults); $route = new Route($path, $defaults);
} elseif ($name === 'new') { } elseif ($name === 'new') {
$path = "{_locale}".$config['base_path'].'/'.$name; $path = "{_locale}".$crudConfig['base_path'].'/'.$name;
$route = new Route($path, $defaults); $route = new Route($path, $defaults);
} else { } else {
$path = "{_locale}".$config['base_path'].($action['path'] ?? '/{id}/'.$name); $path = "{_locale}".$crudConfig['base_path'].($action['path'] ?? '/{id}/'.$name);
$requirements = $action['requirements'] ?? [ $requirements = $action['requirements'] ?? [
'{id}' => '\d+' '{id}' => '\d+'
]; ];
$route = new Route($path, $defaults, $requirements); $route = new Route($path, $defaults, $requirements);
} }
$collection->add('chill_crud_'.$config['name'].'_'.$name, $route); $collection->add('chill_crud_'.$crudConfig['name'].'_'.$name, $route);
} }
return $collection; 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;
}
} }

View File

@@ -14,6 +14,7 @@ use Chill\MainBundle\DependencyInjection\CompilerPass\NotificationCounterCompile
use Chill\MainBundle\DependencyInjection\CompilerPass\MenuCompilerPass; use Chill\MainBundle\DependencyInjection\CompilerPass\MenuCompilerPass;
use Chill\MainBundle\DependencyInjection\CompilerPass\ACLFlagsCompilerPass; use Chill\MainBundle\DependencyInjection\CompilerPass\ACLFlagsCompilerPass;
use Chill\MainBundle\DependencyInjection\CompilerPass\GroupingCenterCompilerPass; use Chill\MainBundle\DependencyInjection\CompilerPass\GroupingCenterCompilerPass;
use Chill\MainBundle\CRUD\CompilerPass\CRUDControllerCompilerPass;
use Chill\MainBundle\Templating\Entity\CompilerPass as RenderEntityCompilerPass; use Chill\MainBundle\Templating\Entity\CompilerPass as RenderEntityCompilerPass;
@@ -33,5 +34,6 @@ class ChillMainBundle extends Bundle
$container->addCompilerPass(new ACLFlagsCompilerPass()); $container->addCompilerPass(new ACLFlagsCompilerPass());
$container->addCompilerPass(new GroupingCenterCompilerPass()); $container->addCompilerPass(new GroupingCenterCompilerPass());
$container->addCompilerPass(new RenderEntityCompilerPass()); $container->addCompilerPass(new RenderEntityCompilerPass());
$container->addCompilerPass(new CRUDControllerCompilerPass());
} }
} }

View 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');
}
}
}

View File

@@ -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();
}
}

View File

@@ -133,7 +133,7 @@ class ChillMainExtension extends Extension implements PrependExtensionInterface,
$loader->load('services/search.yaml'); $loader->load('services/search.yaml');
$loader->load('services/serializer.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( $container->prependExtensionConfig('doctrine', array(
'dbal' => [ 'dbal' => [
'types' => [ '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 * Load parameter for configuration and set parameters for api
* @param array $config the config under 'cruds' key
* @return null
*/ */
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; return;
} }
$loader->load('services/crud.yaml'); $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(); // Note: the controller are loaded inside compiler pass
$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.'%']);
}
} }
} }

View File

@@ -8,6 +8,7 @@ use Chill\MainBundle\DependencyInjection\Widget\Factory\WidgetFactoryInterface;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Chill\MainBundle\DependencyInjection\Widget\AddWidgetConfigurationTrait; use Chill\MainBundle\DependencyInjection\Widget\AddWidgetConfigurationTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpFoundation\Request;
/** /**
@@ -140,7 +141,7 @@ class Configuration implements ConfigurationInterface
->scalarNode('controller_action') ->scalarNode('controller_action')
->defaultNull() ->defaultNull()
->info('the method name to call in the route. Will be set to the action name if left empty.') ->info('the method name to call in the route. Will be set to the action name if left empty.')
->example("'action'") ->example("action")
->end() ->end()
->scalarNode('path') ->scalarNode('path')
->defaultNull() ->defaultNull()
@@ -168,6 +169,78 @@ class Configuration implements ConfigurationInterface
->end() ->end()
->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/children
->end() // end of root ->end() // end of root
; ;

View 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;
}
}

View 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");
}
}

View 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;
}
}

View File

@@ -4,6 +4,8 @@ namespace Chill\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Context\ExecutionContextInterface; use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Chill\MainBundle\Doctrine\Model\Point;
use Chill\ThirdPartyBundle\Entity\ThirdParty;
/** /**
* Address * Address
@@ -28,14 +30,14 @@ class Address
* *
* @ORM\Column(type="string", length=255) * @ORM\Column(type="string", length=255)
*/ */
private $streetAddress1 = ''; private $street = '';
/** /**
* @var string * @var string
* *
* @ORM\Column(type="string", length=255) * @ORM\Column(type="string", length=255)
*/ */
private $streetAddress2 = ''; private $streetNumber = '';
/** /**
* @var PostalCode * @var PostalCode
@@ -43,7 +45,56 @@ class Address
* @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\PostalCode") * @ORM\ManyToOne(targetEntity="Chill\MainBundle\Entity\PostalCode")
*/ */
private $postcode; 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 * Indicates when the address starts validation. Used to build an history
* of address. By default, the current date. * of address. By default, the current date.
@@ -53,27 +104,55 @@ class Address
* @ORM\Column(type="date") * @ORM\Column(type="date")
*/ */
private $validFrom; 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, ... * True if the address is a "no address", aka homeless person, ...
* *
* @var bool * @var bool
*/ */
private $isNoAddress = false; 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 * A list of metadata, added by customizable fields
* *
* @var array * @var array
*/ */
private $customs = []; private $customs = [];
public function __construct() public function __construct()
{ {
$this->validFrom = new \DateTime(); $this->validFrom = new \DateTime();
} }
/** /**
* Get id * Get id
* *
@@ -85,7 +164,7 @@ class Address
} }
/** /**
* Set streetAddress1 * Set streetAddress1 (legacy function)
* *
* @param string $streetAddress1 * @param string $streetAddress1
* *
@@ -93,23 +172,23 @@ class Address
*/ */
public function setStreetAddress1($streetAddress1) public function setStreetAddress1($streetAddress1)
{ {
$this->streetAddress1 = $streetAddress1 === NULL ? '' : $streetAddress1; $this->street = $streetAddress1 === NULL ? '' : $streetAddress1;
return $this; return $this;
} }
/** /**
* Get streetAddress1 * Get streetAddress1 (legacy function)
* *
* @return string * @return string
*/ */
public function getStreetAddress1() public function getStreetAddress1()
{ {
return $this->streetAddress1; return $this->street;
} }
/** /**
* Set streetAddress2 * Set streetAddress2 (legacy function)
* *
* @param string $streetAddress2 * @param string $streetAddress2
* *
@@ -117,19 +196,19 @@ class Address
*/ */
public function setStreetAddress2($streetAddress2) public function setStreetAddress2($streetAddress2)
{ {
$this->streetAddress2 = $streetAddress2 === NULL ? '' : $streetAddress2; $this->streetNumber = $streetAddress2 === NULL ? '' : $streetAddress2;
return $this; return $this;
} }
/** /**
* Get streetAddress2 * Get streetAddress2 (legacy function)
* *
* @return string * @return string
*/ */
public function getStreetAddress2() public function getStreetAddress2()
{ {
return $this->streetAddress2; return $this->streetNumber;
} }
/** /**
@@ -155,7 +234,7 @@ class Address
{ {
return $this->postcode; return $this->postcode;
} }
/** /**
* @return \DateTime * @return \DateTime
*/ */
@@ -173,19 +252,19 @@ class Address
$this->validFrom = $validFrom; $this->validFrom = $validFrom;
return $this; return $this;
} }
/** /**
* Get IsNoAddress * Get IsNoAddress
* *
* Indicate true if the address is a fake address (homeless, ...) * Indicate true if the address is a fake address (homeless, ...)
* *
* @return bool * @return bool
*/ */
public function getIsNoAddress(): bool public function getIsNoAddress(): bool
{ {
return $this->isNoAddress; return $this->isNoAddress;
} }
/** /**
* @return bool * @return bool
*/ */
@@ -196,9 +275,9 @@ class Address
/** /**
* Set IsNoAddress * Set IsNoAddress
* *
* Indicate true if the address is a fake address (homeless, ...) * Indicate true if the address is a fake address (homeless, ...)
* *
* @param bool $isNoAddress * @param bool $isNoAddress
* @return $this * @return $this
*/ */
@@ -207,10 +286,10 @@ class Address
$this->isNoAddress = $isNoAddress; $this->isNoAddress = $isNoAddress;
return $this; return $this;
} }
/** /**
* Get customs informations in the address * Get customs informations in the address
* *
* @return array * @return array
*/ */
public function getCustoms(): array public function getCustoms(): array
@@ -220,27 +299,27 @@ class Address
/** /**
* Store custom informations in the address * Store custom informations in the address
* *
* @param array $customs * @param array $customs
* @return $this * @return $this
*/ */
public function setCustoms(array $customs): self public function setCustoms(array $customs): self
{ {
$this->customs = $customs; $this->customs = $customs;
return $this; return $this;
} }
/** /**
* Validate the address. * Validate the address.
* *
* Check that: * Check that:
* *
* * if the address is not home address: * * if the address is not home address:
* * the postal code is present * * the postal code is present
* * the valid from is not null * * the valid from is not null
* * the address street 1 is greater than 2 * * the address street 1 is greater than 2
* *
* @param ExecutionContextInterface $context * @param ExecutionContextInterface $context
* @param array $payload * @param array $payload
*/ */
@@ -252,18 +331,18 @@ class Address
->atPath('validFrom') ->atPath('validFrom')
->addViolation(); ->addViolation();
} }
if ($this->isNoAddress()) { if ($this->isNoAddress()) {
return; return;
} }
if (empty($this->getStreetAddress1())) { if (empty($this->getStreetAddress1())) {
$context $context
->buildViolation("address.street1-should-be-set") ->buildViolation("address.street1-should-be-set")
->atPath('streetAddress1') ->atPath('streetAddress1')
->addViolation(); ->addViolation();
} }
if (!$this->getPostcode() instanceof PostalCode) { if (!$this->getPostcode() instanceof PostalCode) {
$context $context
->buildViolation("address.postcode-should-be-set") ->buildViolation("address.postcode-should-be-set")
@@ -271,7 +350,7 @@ class Address
->addViolation(); ->addViolation();
} }
} }
/** /**
* @param Address $original * @param Address $original
* @return Address * @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;
}
} }

View 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;
}
}

View File

@@ -33,8 +33,8 @@ use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
* A type to create/update Address entity * A type to create/update Address entity
* *
* Options: * 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. * shown.
* - `null_if_empty` (boolean): replace the address type by null if the street * - `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 * 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) public function buildForm(FormBuilderInterface $builder, array $options)
{ {
$builder $builder
->add('streetAddress1', TextType::class, array( ->add('street', TextType::class, array(
'required' => !$options['has_no_address'] // true if has no address is false 'required' => !$options['has_no_address'] // true if has no address is false
)) ))
->add('streetAddress2', TextType::class, array( ->add('streetNumber', TextType::class, array(
'required' => false 'required' => false
)) ))
->add('postCode', PostalCodeType::class, array( ->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 'required' => !$options['has_no_address'] // true if has no address is false
)) ))
; ;
if ($options['has_valid_from']) { if ($options['has_valid_from']) {
$builder $builder
->add('validFrom', DateType::class, array( ->add('validFrom', DateType::class, array(
@@ -67,7 +67,7 @@ class AddressType extends AbstractType
) )
); );
} }
if ($options['has_no_address']) { if ($options['has_no_address']) {
$builder $builder
->add('isNoAddress', ChoiceType::class, [ ->add('isNoAddress', ChoiceType::class, [
@@ -79,12 +79,12 @@ class AddressType extends AbstractType
'label' => 'address.address_homeless' 'label' => 'address.address_homeless'
]); ]);
} }
if ($options['null_if_empty'] === TRUE) { if ($options['null_if_empty'] === TRUE) {
$builder->setDataMapper(new AddressDataMapper()); $builder->setDataMapper(new AddressDataMapper());
} }
} }
public function configureOptions(OptionsResolver $resolver) public function configureOptions(OptionsResolver $resolver)
{ {
$resolver $resolver

View File

@@ -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()
;
}
*/
}

View File

@@ -28,7 +28,7 @@
// @import "bootstrap/scss/card"; // @import "bootstrap/scss/card";
// @import "bootstrap/scss/breadcrumb"; // @import "bootstrap/scss/breadcrumb";
// @import "bootstrap/scss/pagination"; // @import "bootstrap/scss/pagination";
// @import "bootstrap/scss/badge"; @import "bootstrap/scss/badge";
// @import "bootstrap/scss/jumbotron"; // @import "bootstrap/scss/jumbotron";
// @import "bootstrap/scss/alert"; // @import "bootstrap/scss/alert";
// @import "bootstrap/scss/progress"; // @import "bootstrap/scss/progress";
@@ -41,7 +41,7 @@
// @import "bootstrap/scss/popover"; // @import "bootstrap/scss/popover";
// @import "bootstrap/scss/carousel"; // @import "bootstrap/scss/carousel";
// @import "bootstrap/scss/spinners"; // @import "bootstrap/scss/spinners";
// @import "bootstrap/scss/utilities"; @import "bootstrap/scss/utilities";
// @import "bootstrap/scss/print"; // @import "bootstrap/scss/print";
@import "custom"; @import "custom";

View File

@@ -5,7 +5,7 @@
@include button($green, $white); @include button($green, $white);
} }
&.bt-reset, &.bt-delete { &.bt-reset, &.bt-delete, &.bt-remove {
@include button($red, $white); @include button($red, $white);
} }
@@ -24,6 +24,7 @@
&.bt-save::before, &.bt-save::before,
&.bt-new::before, &.bt-new::before,
&.bt-delete::before, &.bt-delete::before,
&.bt-remove::before,
&.bt-update::before, &.bt-update::before,
&.bt-edit::before, &.bt-edit::before,
&.bt-cancel::before, &.bt-cancel::before,
@@ -56,7 +57,12 @@
// add a trash // add a trash
content: ""; content: "";
} }
&.bt-remove::before {
// add a times
content: "";
}
&.bt-edit::before, &.bt-update::before { &.bt-edit::before, &.bt-update::before {
// add a pencil // add a pencil
content: ""; content: "";
@@ -94,6 +100,7 @@
&.bt-save::before, &.bt-save::before,
&.bt-new::before, &.bt-new::before,
&.bt-delete::before, &.bt-delete::before,
&.bt-remove::before,
&.bt-update::before, &.bt-update::before,
&.bt-edit::before, &.bt-edit::before,
&.bt-cancel::before, &.bt-cancel::before,
@@ -123,6 +130,7 @@
&.bt-save::before, &.bt-save::before,
&.bt-new::before, &.bt-new::before,
&.bt-delete::before, &.bt-delete::before,
&.bt-remove::before,
&.bt-update::before, &.bt-update::before,
&.bt-edit::before, &.bt-edit::before,
&.bt-cancel::before, &.bt-cancel::before,

View File

@@ -39,6 +39,8 @@ div.subheader {
height: 130px; height: 130px;
} }
//// VUEJS ////
div.vue-component { div.vue-component {
padding: 1.5em; padding: 1.5em;
margin: 2em 0; margin: 2em 0;
@@ -55,3 +57,97 @@ div.vue-component {
} }
dd { margin-left: 1em; } dd { margin-left: 1em; }
} }
//// MODAL ////
.modal-mask {
position: fixed;
z-index: 9998;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.75);
display: table;
transition: opacity 0.3s ease;
}
.modal-header .close { // bootstrap classes, override sc-button 0 radius
border-top-right-radius: 0.3rem;
}
/*
* The following styles are auto-applied to elements with
* transition="modal" when their visibility is toggled
* by Vue.js.
*
* You can easily play with the modal transition by editing
* these styles.
*/
.modal-enter {
opacity: 0;
}
.modal-leave-active {
opacity: 0;
}
.modal-enter .modal-container,
.modal-leave-active .modal-container {
-webkit-transform: scale(1.1);
transform: scale(1.1);
}
//// AddPersons modal
div.modal-body.up {
margin: auto 4em;
div.search {
position: relative;
input {
padding: 1.2em 1.5em 1.2em 2.5em;
margin: 1em 0;
}
i {
position: absolute;
top: 50%;
left: 0.5em;
padding: 0.65em 0;
opacity: 0.5;
}
}
}
div.results {
div.count {
margin: -0.5em 0 0.7em;
display: flex;
justify-content: space-between;
}
div.list-item {
line-height: 26pt;
padding: 0.3em 0.8em;
display: flex;
flex-direction: row;
&.checked {
background-color: #ececec;
border-bottom: 1px dotted #8b8b8b;
}
div.container {
& > input {
margin-right: 0.8em;
}
}
div.right_actions {
margin: 0 0 0 auto;
& > * {
margin-left: 0.5em;
}
a.sc-button {
border: 1px solid lightgrey;
font-size: 70%;
padding: 4px;
}
}
}
}
.discret {
color: grey;
margin-right: 1em;
}

View File

@@ -0,0 +1,45 @@
<template>
<transition name="modal">
<div class="modal-mask">
<!-- :: styles bootstrap :: -->
<div class="modal-dialog" :class="modalDialogClass">
<div class="modal-content">
<div class="modal-header">
<slot name="header"></slot>
<button class="close sc-button grey" @click="$emit('close')">
<i class="fa fa-times" aria-hidden="true"></i></button>
</div>
<div class="modal-body up" style="overflow-y: unset;">
<slot name="body-fixed"></slot>
</div>
<div class="modal-body">
<slot name="body"></slot>
</div>
<div class="modal-footer">
<button class="sc-button cancel" @click="$emit('close')">{{ $t('action.close') }}</button>
<slot name="footer"></slot>
</div>
</div>
</div>
<!-- :: end styles bootstrap :: -->
</div>
</transition>
</template>
<script>
/*
* This Modal component is a mix between :
* - Vue3 modal implementation
* => with 'v-if:showModal' directive:parameter, html scope is added/removed not just shown/hidden
* => with slot we can pass content from parent component
* => some classes are passed from parent component
* - Bootstrap 4.6 _modal.scss module
* => using bootstrap css classes, the modal have a responsive behaviour,
* => modal design can be configured using css classes (size, scroll)
*/
export default {
name: 'Modal',
props: ['modalDialogClass'],
emits: ['close']
}
</script>

View File

@@ -0,0 +1,55 @@
import { createI18n } from 'vue-i18n'
const datetimeFormats = {
fr: {
short: {
year: "numeric",
month: "numeric",
day: "numeric"
},
long: {
year: "numeric",
month: "short",
day: "numeric",
weekday: "short",
hour: "numeric",
minute: "numeric",
hour12: false
}
}
};
const messages = {
fr: {
action: {
actions: "Actions",
show: "Voir",
edit: "Modifier",
create: "Créer",
remove: "Enlever",
delete: "Supprimer",
save: "Enregistrer",
add: "Ajouter",
show_modal: "Ouvrir une modale",
ok: "OK",
cancel: "Annuler",
close: "Fermer",
next: "Suivant",
previous: "Précédent",
back: "Retour",
check_all: "cocher tout",
reset: "réinitialiser"
},
}
};
const _createI18n = (appMessages) => {
Object.assign(messages.fr, appMessages.fr);
return createI18n({
locale: 'fr',
fallbackLocale: 'fr',
datetimeFormats,
messages,
})
};
export { _createI18n }

View File

@@ -6,8 +6,8 @@
<div class="chill_address_is_noaddress">{{ 'address.consider homeless'|trans }}</div> <div class="chill_address_is_noaddress">{{ 'address.consider homeless'|trans }}</div>
{% endif %} {% endif %}
<div class="chill_address_address"> <div class="chill_address_address">
{% if address.streetAddress1 is not empty %}<p class="street street1">{{ address.streetAddress1 }}</p>{% endif %} {% if address.street is not empty %}<p class="street street1">{{ address.street }}</p>{% endif %}
{% if address.streetAddress2 is not empty %}<p class="street street2">{{ address.streetAddress2 }}</p>{% endif %} {% if address.streetNumber is not empty %}<p class="street street2">{{ address.streetNumber }}</p>{% endif %}
{% if address.postCode is not empty %} {% 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="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> <p class="country">{{ address.postCode.country.name|localize_translatable_string }}</p>

View File

@@ -32,34 +32,34 @@ use Chill\MainBundle\Entity\GroupCenter;
use Chill\MainBundle\Entity\RoleScope; use Chill\MainBundle\Entity\RoleScope;
/** /**
* Helper for authorizations. * Helper for authorizations.
* *
* Provides methods for user and entities information. * Provides methods for user and entities information.
* *
* @author Julien Fastré <julien.fastre@champs-libres.coop> * @author Julien Fastré <julien.fastre@champs-libres.coop>
*/ */
class AuthorizationHelper implements AuthorizationHelperInterface class AuthorizationHelper
{ {
/** /**
* *
* @var RoleHierarchyInterface * @var RoleHierarchyInterface
*/ */
protected $roleHierarchy; protected $roleHierarchy;
/** /**
* The role in a hierarchy, given by the parameter * The role in a hierarchy, given by the parameter
* `security.role_hierarchy.roles` from the container. * `security.role_hierarchy.roles` from the container.
* *
* @var string[] * @var string[]
*/ */
protected $hierarchy; protected $hierarchy;
/** /**
* *
* @var EntityManagerInterface * @var EntityManagerInterface
*/ */
protected $em; protected $em;
public function __construct( public function __construct(
RoleHierarchyInterface $roleHierarchy, RoleHierarchyInterface $roleHierarchy,
$hierarchy, $hierarchy,
@@ -69,10 +69,10 @@ class AuthorizationHelper implements AuthorizationHelperInterface
$this->hierarchy = $hierarchy; $this->hierarchy = $hierarchy;
$this->em = $em; $this->em = $em;
} }
/** /**
* Determines if a user is active on this center * Determines if a user is active on this center
* *
* @param User $user * @param User $user
* @param Center $center * @param Center $center
* @return bool * @return bool
@@ -81,21 +81,21 @@ class AuthorizationHelper implements AuthorizationHelperInterface
{ {
foreach ($user->getGroupCenters() as $groupCenter) { foreach ($user->getGroupCenters() as $groupCenter) {
if ($center->getId() === $groupCenter->getCenter()->getId()) { if ($center->getId() === $groupCenter->getCenter()->getId()) {
return true; return true;
} }
} }
return false; return false;
} }
/** /**
* *
* Determines if the user has access to the given entity. * Determines if the user has access to the given entity.
* *
* if the entity implements Chill\MainBundle\Entity\HasScopeInterface, * if the entity implements Chill\MainBundle\Entity\HasScopeInterface,
* the scope is taken into account. * the scope is taken into account.
* *
* @param User $user * @param User $user
* @param HasCenterInterface $entity the entity may also implement HasScopeInterface * @param HasCenterInterface $entity the entity may also implement HasScopeInterface
* @param string|Role $attribute * @param string|Role $attribute
@@ -103,15 +103,15 @@ class AuthorizationHelper implements AuthorizationHelperInterface
*/ */
public function userHasAccess(User $user, HasCenterInterface $entity, $attribute) public function userHasAccess(User $user, HasCenterInterface $entity, $attribute)
{ {
$center = $entity->getCenter(); $center = $entity->getCenter();
if (!$this->userCanReachCenter($user, $center)) { if (!$this->userCanReachCenter($user, $center)) {
return false; return false;
} }
$role = ($attribute instanceof Role) ? $attribute : new Role($attribute); $role = ($attribute instanceof Role) ? $attribute : new Role($attribute);
foreach ($user->getGroupCenters() as $groupCenter){ foreach ($user->getGroupCenters() as $groupCenter){
//filter on center //filter on center
if ($groupCenter->getCenter()->getId() === $entity->getCenter()->getId()) { if ($groupCenter->getCenter()->getId() === $entity->getCenter()->getId()) {
@@ -119,7 +119,7 @@ class AuthorizationHelper implements AuthorizationHelperInterface
//iterate on roleScopes //iterate on roleScopes
foreach($permissionGroup->getRoleScopes() as $roleScope) { foreach($permissionGroup->getRoleScopes() as $roleScope) {
//check that the role allow to reach the required role //check that the role allow to reach the required role
if ($this->isRoleReached($role, if ($this->isRoleReached($role,
new Role($roleScope->getRole()))){ new Role($roleScope->getRole()))){
//if yes, we have a right on something... //if yes, we have a right on something...
// perform check on scope if necessary // perform check on scope if necessary
@@ -137,17 +137,17 @@ class AuthorizationHelper implements AuthorizationHelperInterface
} }
} }
} }
} }
} }
return false; return false;
} }
/** /**
* Get reachable Centers for the given user, role, * Get reachable Centers for the given user, role,
* and optionnaly Scope * and optionnaly Scope
* *
* @param User $user * @param User $user
* @param Role $role * @param Role $role
* @param null|Scope $scope * @param null|Scope $scope
@@ -156,13 +156,13 @@ class AuthorizationHelper implements AuthorizationHelperInterface
public function getReachableCenters(User $user, Role $role, Scope $scope = null) public function getReachableCenters(User $user, Role $role, Scope $scope = null)
{ {
$centers = array(); $centers = array();
foreach ($user->getGroupCenters() as $groupCenter){ foreach ($user->getGroupCenters() as $groupCenter){
$permissionGroup = $groupCenter->getPermissionsGroup(); $permissionGroup = $groupCenter->getPermissionsGroup();
//iterate on roleScopes //iterate on roleScopes
foreach($permissionGroup->getRoleScopes() as $roleScope) { foreach($permissionGroup->getRoleScopes() as $roleScope) {
//check that the role is in the reachable roles //check that the role is in the reachable roles
if ($this->isRoleReached($role, if ($this->isRoleReached($role,
new Role($roleScope->getRole()))) { new Role($roleScope->getRole()))) {
if ($scope === null) { if ($scope === null) {
$centers[] = $groupCenter->getCenter(); $centers[] = $groupCenter->getCenter();
@@ -171,19 +171,19 @@ class AuthorizationHelper implements AuthorizationHelperInterface
if ($scope->getId() == $roleScope->getScope()->getId()){ if ($scope->getId() == $roleScope->getScope()->getId()){
$centers[] = $groupCenter->getCenter(); $centers[] = $groupCenter->getCenter();
break 1; break 1;
} }
} }
} }
} }
} }
return $centers; return $centers;
} }
/** /**
* Return all reachable scope for a given user, center and role * Return all reachable scope for a given user, center and role
* *
* @deprecated Use getReachableCircles * @deprecated Use getReachableCircles
* *
* @param User $user * @param User $user
@@ -195,10 +195,10 @@ class AuthorizationHelper implements AuthorizationHelperInterface
{ {
return $this->getReachableCircles($user, $role, $center); return $this->getReachableCircles($user, $role, $center);
} }
/** /**
* Return all reachable circle for a given user, center and role * Return all reachable circle for a given user, center and role
* *
* @param User $user * @param User $user
* @param Role $role * @param Role $role
* @param Center $center * @param Center $center
@@ -207,7 +207,7 @@ class AuthorizationHelper implements AuthorizationHelperInterface
public function getReachableCircles(User $user, Role $role, Center $center) public function getReachableCircles(User $user, Role $role, Center $center)
{ {
$scopes = array(); $scopes = array();
foreach ($user->getGroupCenters() as $groupCenter){ foreach ($user->getGroupCenters() as $groupCenter){
if ($center->getId() === $groupCenter->getCenter()->getId()) { if ($center->getId() === $groupCenter->getCenter()->getId()) {
//iterate on permissionGroup //iterate on permissionGroup
@@ -215,7 +215,7 @@ class AuthorizationHelper implements AuthorizationHelperInterface
//iterate on roleScopes //iterate on roleScopes
foreach($permissionGroup->getRoleScopes() as $roleScope) { foreach($permissionGroup->getRoleScopes() as $roleScope) {
//check that the role is in the reachable roles //check that the role is in the reachable roles
if ($this->isRoleReached($role, if ($this->isRoleReached($role,
new Role($roleScope->getRole()))) { new Role($roleScope->getRole()))) {
$scopes[] = $roleScope->getScope(); $scopes[] = $roleScope->getScope();
@@ -223,12 +223,12 @@ class AuthorizationHelper implements AuthorizationHelperInterface
} }
} }
} }
return $scopes; return $scopes;
} }
/** /**
* *
* @param Role $role * @param Role $role
* @param Center $center * @param Center $center
* @param Scope $circle * @param Scope $circle
@@ -239,7 +239,7 @@ class AuthorizationHelper implements AuthorizationHelperInterface
$parents = $this->getParentRoles($role); $parents = $this->getParentRoles($role);
$parents[] = $role; $parents[] = $role;
$parentRolesString = \array_map(function(Role $r) { return $r->getRole(); }, $parents); $parentRolesString = \array_map(function(Role $r) { return $r->getRole(); }, $parents);
$qb = $this->em->createQueryBuilder(); $qb = $this->em->createQueryBuilder();
$qb $qb
->select('u') ->select('u')
@@ -250,21 +250,21 @@ class AuthorizationHelper implements AuthorizationHelperInterface
->where('gc.center = :center') ->where('gc.center = :center')
->andWhere($qb->expr()->in('rs.role', $parentRolesString)) ->andWhere($qb->expr()->in('rs.role', $parentRolesString))
; ;
$qb->setParameter('center', $center); $qb->setParameter('center', $center);
if ($circle !== null) { if ($circle !== null) {
$qb->andWhere('rs.scope = :circle') $qb->andWhere('rs.scope = :circle')
->setParameter('circle', $circle) ->setParameter('circle', $circle)
; ;
} }
return $qb->getQuery()->getResult(); return $qb->getQuery()->getResult();
} }
/** /**
* Test if a parent role may give access to a given child role * Test if a parent role may give access to a given child role
* *
* @param Role $childRole The role we want to test if he is reachable * @param Role $childRole The role we want to test if he is reachable
* @param Role $parentRole The role which should give access to $childRole * @param Role $parentRole The role which should give access to $childRole
* @return boolean true if the child role is granted by parent role * @return boolean true if the child role is granted by parent role
@@ -273,14 +273,14 @@ class AuthorizationHelper implements AuthorizationHelperInterface
{ {
$reachableRoles = $this->roleHierarchy $reachableRoles = $this->roleHierarchy
->getReachableRoles([$parentRole]); ->getReachableRoles([$parentRole]);
return in_array($childRole, $reachableRoles); return in_array($childRole, $reachableRoles);
} }
/** /**
* Return all the role which give access to the given role. Only the role * Return all the role which give access to the given role. Only the role
* which are registered into Chill are taken into account. * which are registered into Chill are taken into account.
* *
* @param Role $role * @param Role $role
* @return Role[] the role which give access to the given $role * @return Role[] the role which give access to the given $role
*/ */
@@ -291,18 +291,18 @@ class AuthorizationHelper implements AuthorizationHelperInterface
$roles = \array_map( $roles = \array_map(
function($string) { function($string) {
return new Role($string); return new Role($string);
}, },
\array_keys($this->hierarchy) \array_keys($this->hierarchy)
); );
foreach ($roles as $r) { foreach ($roles as $r) {
$childRoles = $this->roleHierarchy->getReachableRoleNames([$r->getRole()]); $childRoles = $this->roleHierarchy->getReachableRoleNames([$r->getRole()]);
if (\in_array($role, $childRoles)) { if (\in_array($role, $childRoles)) {
$parentRoles[] = $r; $parentRoles[] = $r;
} }
} }
return $parentRoles; return $parentRoles;
} }
} }

View File

@@ -1,87 +0,0 @@
<?php
namespace Chill\MainBundle\Security\Authorization;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Entity\Center;
use Chill\MainBundle\Entity\HasCenterInterface;
use Symfony\Component\Security\Core\Role\Role;
use Chill\MainBundle\Entity\Scope;
interface AuthorizationHelperInterface
{
/**
* Determines if a user is active on this center
*
* @param User $user
* @param Center $center
* @return bool
*/
public function userCanReachCenter(User $user, Center $center);
/**
*
* Determines if the user has access to the given entity.
*
* if the entity implements Chill\MainBundle\Entity\HasScopeInterface,
* the scope is taken into account.
*
* @param User $user
* @param HasCenterInterface $entity the entity may also implement HasScopeInterface
* @param string|Role $attribute
* @return boolean true if the user has access
*/
public function userHasAccess(User $user, HasCenterInterface $entity, $attribute);
/**
* Get reachable Centers for the given user, role,
* and optionnaly Scope
*
* @param User $user
* @param Role $role
* @param null|Scope $scope
* @return Center[]
*/
public function getReachableCenters(User $user, Role $role, Scope $scope = null);
/**
* Return all reachable scope for a given user, center and role
*
* @deprecated Use getReachableCircles
*
* @param User $user
* @param Role $role
* @param Center $center
* @return Scope[]
*/
public function getReachableScopes(User $user, Role $role, Center $center);
/**
* Return all reachable circle for a given user, center and role
*
* @param User $user
* @param Role $role
* @param Center $center
* @return Scope[]
*/
public function getReachableCircles(User $user, Role $role, Center $center);
/**
*
* @param Role $role
* @param Center $center
* @param Scope $circle
* @return Users
*/
public function findUsersReaching(Role $role, Center $center, Scope $circle = null);
/**
* Return all the role which give access to the given role. Only the role
* which are registered into Chill are taken into account.
*
* @param Role $role
* @return Role[] the role which give access to the given $role
*/
public function getParentRoles(Role $role);
}

View 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;
}
}

View File

@@ -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;
}
}

View File

@@ -2,7 +2,7 @@
/* /*
* Chill is a software for social workers * Chill is a software for social workers
* *
* Copyright (C) 2014-2019, Champs Libres Cooperative SCRLFS, * Copyright (C) 2014-2019, Champs Libres Cooperative SCRLFS,
* <http://www.champs-libres.coop> * <http://www.champs-libres.coop>
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
@@ -28,18 +28,18 @@ use Twig\TwigFilter;
* *
* @package Chill\MainBundle\Templating\Entity * @package Chill\MainBundle\Templating\Entity
*/ */
class ChillEntityRenderExtension extends AbstractExtension implements ChillEntityRenderExtensionInterface class ChillEntityRenderExtension extends AbstractExtension
{ {
/** /**
* @var ChillEntityRenderInterface * @var ChillEntityRenderInterface
*/ */
protected $renders = []; protected $renders = [];
/** /**
* @var ChillEntityRender * @var ChillEntityRender
*/ */
protected $defaultRender; protected $defaultRender;
/** /**
* ChillEntityRenderExtension constructor. * ChillEntityRenderExtension constructor.
*/ */
@@ -47,7 +47,7 @@ class ChillEntityRenderExtension extends AbstractExtension implements ChillEntit
{ {
$this->defaultRender = new ChillEntityRender(); $this->defaultRender = new ChillEntityRender();
} }
/** /**
* @return array|TwigFilter[] * @return array|TwigFilter[]
*/ */
@@ -62,7 +62,7 @@ class ChillEntityRenderExtension extends AbstractExtension implements ChillEntit
]) ])
]; ];
} }
/** /**
* @param $entity * @param $entity
* @param array $options * @param array $options
@@ -76,7 +76,7 @@ class ChillEntityRenderExtension extends AbstractExtension implements ChillEntit
return $this->getRender($entity, $options) return $this->getRender($entity, $options)
->renderString($entity, $options); ->renderString($entity, $options);
} }
/** /**
* @param $entity * @param $entity
* @param array $options * @param array $options
@@ -90,7 +90,7 @@ class ChillEntityRenderExtension extends AbstractExtension implements ChillEntit
return $this->getRender($entity, $options) return $this->getRender($entity, $options)
->renderBox($entity, $options); ->renderBox($entity, $options);
} }
/** /**
* @param ChillEntityRenderInterface $render * @param ChillEntityRenderInterface $render
*/ */
@@ -98,7 +98,7 @@ class ChillEntityRenderExtension extends AbstractExtension implements ChillEntit
{ {
$this->renders[] = $render; $this->renders[] = $render;
} }
/** /**
* @param $entity * @param $entity
* @param $options * @param $options

View File

@@ -1,33 +0,0 @@
<?php
namespace Chill\MainBundle\Templating\Entity;
use Twig\Extension\ExtensionInterface;
use Twig\TwigFilter;
interface ChillEntityRenderExtensionInterface extends ExtensionInterface
{
/**
* @return array|TwigFilter[]
*/
public function getFilters();
/**
* @param $entity
* @param array $options
* @return string
*/
public function renderString($entity, array $options = []): string;
/**
* @param $entity
* @param array $options
* @return string
*/
public function renderBox($entity, array $options = []): string;
/**
* @param ChillEntityRenderInterface $render
*/
public function addRender(ChillEntityRenderInterface $render);
}

View File

@@ -23,36 +23,36 @@ use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Translation\Translator; use Symfony\Component\Translation\Translator;
/** /**
* *
* This helper helps to find the string in current locale from translatable_strings * This helper helps to find the string in current locale from translatable_strings
* *
* @author Julien Fastré <julien.fastre@champs-libres.coop> * @author Julien Fastré <julien.fastre@champs-libres.coop>
* *
*/ */
class TranslatableStringHelper implements TranslatableStringHelperInterface class TranslatableStringHelper
{ {
/** /**
* *
* @var RequestStack * @var RequestStack
*/ */
private $requestStack; private $requestStack;
private $fallbackLocales; private $fallbackLocales;
public function __construct(RequestStack $requestStack, Translator $translator) public function __construct(RequestStack $requestStack, Translator $translator)
{ {
$this->requestStack = $requestStack; $this->requestStack = $requestStack;
$this->fallbackLocales = $translator->getFallbackLocales(); $this->fallbackLocales = $translator->getFallbackLocales();
} }
/** /**
* return the string in current locale if it exists. * return the string in current locale if it exists.
* *
* If it does not exists; return the name in the first language available. * If it does not exists; return the name in the first language available.
* *
* Return a blank string if any strings are available. * Return a blank string if any strings are available.
* Return NULL if $translatableString is NULL * Return NULL if $translatableString is NULL
* *
* @param array $translatableStrings * @param array $translatableStrings
* @return string * @return string
*/ */
@@ -61,32 +61,32 @@ class TranslatableStringHelper implements TranslatableStringHelperInterface
if (NULL === $translatableStrings) { if (NULL === $translatableStrings) {
return NULL; return NULL;
} }
$language = $this->requestStack->getCurrentRequest()->getLocale(); $language = $this->requestStack->getCurrentRequest()->getLocale();
if (isset($translatableStrings[$language])) { if (isset($translatableStrings[$language])) {
return $translatableStrings[$language]; return $translatableStrings[$language];
} else { } else {
foreach ($this->fallbackLocales as $locale) { foreach ($this->fallbackLocales as $locale) {
if (array_key_exists($locale, $translatableStrings)) { if (array_key_exists($locale, $translatableStrings)) {
return $translatableStrings[$locale]; return $translatableStrings[$locale];
} }
} }
} }
// no fallback translation... trying the first available // no fallback translation... trying the first available
$langs = array_keys($translatableStrings); $langs = array_keys($translatableStrings);
if (count($langs) === 0) { if (count($langs) === 0) {
return ''; return '';
} }
return $translatableStrings[$langs[0]]; return $translatableStrings[$langs[0]];
} }
} }

View File

@@ -1,19 +0,0 @@
<?php
namespace Chill\MainBundle\Templating;
interface TranslatableStringHelperInterface
{
/**
* return the string in current locale if it exists.
*
* If it does not exists; return the name in the first language available.
*
* Return a blank string if any strings are available.
* Return NULL if $translatableString is NULL
*
* @param array $translatableStrings
* @return string
*/
public function localize(array $translatableStrings);
}

View 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);
}
}

View File

@@ -29,40 +29,40 @@ use Symfony\Component\DependencyInjection\ContainerAwareInterface;
* *
* @author Julien Fastré <julien.fastre@champs-libres.coop> * @author Julien Fastré <julien.fastre@champs-libres.coop>
*/ */
class TimelineBuilder implements ContainerAwareInterface, TimelineBuilderInterface class TimelineBuilder implements ContainerAwareInterface
{ {
use \Symfony\Component\DependencyInjection\ContainerAwareTrait; use \Symfony\Component\DependencyInjection\ContainerAwareTrait;
/** /**
* *
* @var \Doctrine\ORM\EntityManagerInterface * @var \Doctrine\ORM\EntityManagerInterface
*/ */
private $em; private $em;
/** /**
* Record provider * Record provider
* *
* This array has the structure `[ 'service id' => $service ]` * This array has the structure `[ 'service id' => $service ]`
* *
* @var TimelineProviderInterface[] * @var TimelineProviderInterface[]
*/ */
private $providers = []; private $providers = [];
/** /**
* Record provider and their context * Record provider and their context
* *
* This array has the structure `[ 'context' => [ 'service id' ] ]` * This array has the structure `[ 'context' => [ 'service id' ] ]`
* *
* @var array * @var array
*/ */
private $providersByContext = []; private $providersByContext = [];
public function __construct(EntityManagerInterface $em) public function __construct(EntityManagerInterface $em)
{ {
$this->em = $em; $this->em = $em;
} }
/** /**
* return an HTML string with timeline * return an HTML string with timeline
* *
@@ -79,18 +79,18 @@ class TimelineBuilder implements ContainerAwareInterface, TimelineBuilderInterfa
public function getTimelineHTML($context, array $args, $firstItem = 0, $number = 20) public function getTimelineHTML($context, array $args, $firstItem = 0, $number = 20)
{ {
$union = $this->buildUnionQuery($context, $args); $union = $this->buildUnionQuery($context, $args);
//add ORDER BY clause and LIMIT //add ORDER BY clause and LIMIT
$query = $union . sprintf(' ORDER BY date DESC LIMIT %d OFFSET %d', $query = $union . sprintf(' ORDER BY date DESC LIMIT %d OFFSET %d',
$number, $firstItem); $number, $firstItem);
// run query and handle results // run query and handle results
$fetched = $this->runUnionQuery($query); $fetched = $this->runUnionQuery($query);
$entitiesByKey = $this->getEntities($fetched, $context); $entitiesByKey = $this->getEntities($fetched, $context);
return $this->render($fetched, $entitiesByKey, $context, $args); return $this->render($fetched, $entitiesByKey, $context, $args);
} }
/** /**
* Return the number of items for the given context and args * Return the number of items for the given context and args
* *
@@ -101,17 +101,17 @@ class TimelineBuilder implements ContainerAwareInterface, TimelineBuilderInterfa
public function countItems($context, array $args) public function countItems($context, array $args)
{ {
$union = $this->buildUnionQuery($context, $args); $union = $this->buildUnionQuery($context, $args);
// embed the union query inside a count query // embed the union query inside a count query
$count = sprintf('SELECT COUNT(sq.id) AS total FROM (%s) as sq', $union); $count = sprintf('SELECT COUNT(sq.id) AS total FROM (%s) as sq', $union);
$rsm = (new ResultSetMapping()) $rsm = (new ResultSetMapping())
->addScalarResult('total', 'total', Type::INTEGER); ->addScalarResult('total', 'total', Type::INTEGER);
return $this->em->createNativeQuery($count, $rsm) return $this->em->createNativeQuery($count, $rsm)
->getSingleScalarResult(); ->getSingleScalarResult();
} }
/** /**
* add a provider id * add a provider id
* *
@@ -125,7 +125,7 @@ class TimelineBuilder implements ContainerAwareInterface, TimelineBuilderInterfa
$this->providersByContext[$context][] = $id; $this->providersByContext[$context][] = $id;
$this->providers[$id] = $provider; $this->providers[$id] = $provider;
} }
/** /**
* Get providers by context * Get providers by context
* *
@@ -139,16 +139,16 @@ class TimelineBuilder implements ContainerAwareInterface, TimelineBuilderInterfa
throw new \LogicException(sprintf('No builders have been defined for "%s"' throw new \LogicException(sprintf('No builders have been defined for "%s"'
. ' context', $context)); . ' context', $context));
} }
$providers = []; $providers = [];
foreach($this->providersByContext[$context] as $providerId) { foreach($this->providersByContext[$context] as $providerId) {
$providers[] = $this->providers[$providerId]; $providers[] = $this->providers[$providerId];
} }
return $providers; return $providers;
} }
/** /**
* build the UNION query with all providers * build the UNION query with all providers
* *
@@ -170,10 +170,10 @@ class TimelineBuilder implements ContainerAwareInterface, TimelineBuilderInterfa
$append = ($union === '') ? $select : ' UNION '.$select; $append = ($union === '') ? $select : ' UNION '.$select;
$union .= $append; $union .= $append;
} }
return $union; return $union;
} }
/** /**
* return the SQL SELECT query as a string, * return the SQL SELECT query as a string,
* *
@@ -186,7 +186,7 @@ class TimelineBuilder implements ContainerAwareInterface, TimelineBuilderInterfa
private function buildSelectQuery(TimelineProviderInterface $provider, $context, array $args) private function buildSelectQuery(TimelineProviderInterface $provider, $context, array $args)
{ {
$data = $provider->fetchQuery($context, $args); $data = $provider->fetchQuery($context, $args);
return sprintf( return sprintf(
'SELECT %s AS id, ' 'SELECT %s AS id, '
. '%s AS "date", ' . '%s AS "date", '
@@ -199,7 +199,7 @@ class TimelineBuilder implements ContainerAwareInterface, TimelineBuilderInterfa
$data['FROM'], $data['FROM'],
$data['WHERE']); $data['WHERE']);
} }
/** /**
* run the UNION query and return result as an array * run the UNION query and return result as an array
* *
@@ -212,11 +212,11 @@ class TimelineBuilder implements ContainerAwareInterface, TimelineBuilderInterfa
->addScalarResult('id', 'id') ->addScalarResult('id', 'id')
->addScalarResult('type', 'type') ->addScalarResult('type', 'type')
->addScalarResult('date', 'date'); ->addScalarResult('date', 'date');
return $this->em->createNativeQuery($query, $resultSetMapping) return $this->em->createNativeQuery($query, $resultSetMapping)
->getArrayResult(); ->getArrayResult();
} }
/** /**
* *
* @param array $queriedIds * @param array $queriedIds
@@ -227,11 +227,11 @@ class TimelineBuilder implements ContainerAwareInterface, TimelineBuilderInterfa
{ {
//gather entities by type to pass all id with same type to the TimelineProvider. //gather entities by type to pass all id with same type to the TimelineProvider.
$idsByType = array(); $idsByType = array();
foreach($queriedIds as $result) { foreach($queriedIds as $result) {
$idsByType[$result['type']][] = $result['id']; $idsByType[$result['type']][] = $result['id'];
} }
//fetch entities from providers //fetch entities from providers
$entitiesByType = array(); $entitiesByType = array();
foreach ($idsByType as $type => $ids) { foreach ($idsByType as $type => $ids) {
@@ -243,10 +243,10 @@ class TimelineBuilder implements ContainerAwareInterface, TimelineBuilderInterfa
} }
} }
} }
return $entitiesByType; return $entitiesByType;
} }
/** /**
* render the timeline as HTML * render the timeline as HTML
* *
@@ -269,17 +269,17 @@ class TimelineBuilder implements ContainerAwareInterface, TimelineBuilderInterfa
$timelineEntry['date'] = new \DateTime($result['date']); $timelineEntry['date'] = new \DateTime($result['date']);
$timelineEntry['template'] = $data['template']; $timelineEntry['template'] = $data['template'];
$timelineEntry['template_data'] = $data['template_data']; $timelineEntry['template_data'] = $data['template_data'];
$timelineEntries[] = $timelineEntry; $timelineEntries[] = $timelineEntry;
} }
return $this->container->get('templating') return $this->container->get('templating')
->render('@ChillMain/Timeline/index.html.twig', array( ->render('@ChillMain/Timeline/index.html.twig', array(
'results' => $timelineEntries 'results' => $timelineEntries
)); ));
} }
/** /**
* get the template data from the provider for the given entity, by type. * get the template data from the provider for the given entity, by type.
* *

View File

@@ -1,24 +0,0 @@
<?php
/*
* Copyright (C) 2015 Champs-Libres Coopérative <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\Timeline;
interface TimelineBuilderInterface
{
}

View File

@@ -10,7 +10,6 @@ services:
- "@translator.default" - "@translator.default"
Chill\MainBundle\Templating\TranslatableStringHelper: '@chill.main.helper.translatable_string' Chill\MainBundle\Templating\TranslatableStringHelper: '@chill.main.helper.translatable_string'
Chill\MainBundle\Templating\TranslatableStringHelperInterface: Chill\MainBundle\Templating\TranslatableStringHelper
chill.main.twig.translatable_string: chill.main.twig.translatable_string:
class: Chill\MainBundle\Templating\TranslatableStringTwig class: Chill\MainBundle\Templating\TranslatableStringTwig
@@ -20,14 +19,14 @@ services:
- [ setContainer, ["@service_container"]] - [ setContainer, ["@service_container"]]
tags: tags:
- { name: twig.extension } - { name: twig.extension }
chill.main.twig.widget: chill.main.twig.widget:
class: Chill\MainBundle\Templating\Widget\WidgetRenderingTwig class: Chill\MainBundle\Templating\Widget\WidgetRenderingTwig
arguments: arguments:
- "@event_dispatcher" - "@event_dispatcher"
tags: tags:
- { name: twig.extension } - { name: twig.extension }
chill.main.twig.csv_cell: chill.main.twig.csv_cell:
class: Chill\MainBundle\Templating\CSVCellTwig class: Chill\MainBundle\Templating\CSVCellTwig
tags: tags:

View File

@@ -1,7 +1,8 @@
services: services:
Chill\MainBundle\CRUD\Routing\CRUDRoutesLoader: Chill\MainBundle\CRUD\Routing\CRUDRoutesLoader:
arguments: 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 ] tags: [ routing.loader ]
Chill\MainBundle\CRUD\Resolver\Resolver: Chill\MainBundle\CRUD\Resolver\Resolver:
@@ -13,4 +14,4 @@ services:
arguments: arguments:
$resolver: '@Chill\MainBundle\CRUD\Resolver\Resolver' $resolver: '@Chill\MainBundle\CRUD\Resolver\Resolver'
tags: tags:
- { name: twig.extension } - { name: twig.extension }

View File

@@ -6,6 +6,7 @@ services:
- "@request_stack" - "@request_stack"
- "@router" - "@router"
- "%chill_main.pagination.item_per_page%" - "%chill_main.pagination.item_per_page%"
Chill\MainBundle\Pagination\PaginatorFactory: '@chill_main.paginator_factory' Chill\MainBundle\Pagination\PaginatorFactory: '@chill_main.paginator_factory'
chill_main.paginator.twig_extensions: chill_main.paginator.twig_extensions:

View File

@@ -1,4 +1,4 @@
services: services:
chill.main.security.authorization.helper: chill.main.security.authorization.helper:
class: Chill\MainBundle\Security\Authorization\AuthorizationHelper class: Chill\MainBundle\Security\Authorization\AuthorizationHelper
arguments: arguments:
@@ -6,48 +6,47 @@ services:
$hierarchy: "%security.role_hierarchy.roles%" $hierarchy: "%security.role_hierarchy.roles%"
$em: '@Doctrine\ORM\EntityManagerInterface' $em: '@Doctrine\ORM\EntityManagerInterface'
Chill\MainBundle\Security\Authorization\AuthorizationHelper: '@chill.main.security.authorization.helper' Chill\MainBundle\Security\Authorization\AuthorizationHelper: '@chill.main.security.authorization.helper'
Chill\MainBundle\Security\Authorization\AuthorizationHelperInterface: Chill\MainBundle\Security\Authorization\AuthorizationHelper
chill.main.role_provider: chill.main.role_provider:
class: Chill\MainBundle\Security\RoleProvider class: Chill\MainBundle\Security\RoleProvider
chill.main.user_provider: chill.main.user_provider:
class: Chill\MainBundle\Security\UserProvider\UserProvider class: Chill\MainBundle\Security\UserProvider\UserProvider
arguments: arguments:
$em: '@Doctrine\ORM\EntityManagerInterface' $em: '@Doctrine\ORM\EntityManagerInterface'
Chill\MainBundle\Security\Authorization\ChillExportVoter: Chill\MainBundle\Security\Authorization\ChillExportVoter:
arguments: arguments:
$authorizationHelper: '@Chill\MainBundle\Security\Authorization\AuthorizationHelper' $authorizationHelper: '@Chill\MainBundle\Security\Authorization\AuthorizationHelper'
tags: tags:
- { name: security.voter } - { name: security.voter }
Chill\MainBundle\Security\PasswordRecover\TokenManager: Chill\MainBundle\Security\PasswordRecover\TokenManager:
arguments: arguments:
$secret: '%kernel.secret%' $secret: '%kernel.secret%'
$logger: '@Psr\Log\LoggerInterface' $logger: '@Psr\Log\LoggerInterface'
Chill\MainBundle\Security\PasswordRecover\RecoverPasswordHelper: Chill\MainBundle\Security\PasswordRecover\RecoverPasswordHelper:
arguments: arguments:
$tokenManager: '@Chill\MainBundle\Security\PasswordRecover\TokenManager' $tokenManager: '@Chill\MainBundle\Security\PasswordRecover\TokenManager'
$urlGenerator: '@Symfony\Component\Routing\Generator\UrlGeneratorInterface' $urlGenerator: '@Symfony\Component\Routing\Generator\UrlGeneratorInterface'
$mailer: '@Chill\MainBundle\Notification\Mailer' $mailer: '@Chill\MainBundle\Notification\Mailer'
$routeParameters: "%chill_main.notifications%" $routeParameters: "%chill_main.notifications%"
Chill\MainBundle\Security\PasswordRecover\PasswordRecoverEventSubscriber: Chill\MainBundle\Security\PasswordRecover\PasswordRecoverEventSubscriber:
arguments: arguments:
$locker: '@Chill\MainBundle\Security\PasswordRecover\PasswordRecoverLocker' $locker: '@Chill\MainBundle\Security\PasswordRecover\PasswordRecoverLocker'
tags: tags:
- { name: kernel.event_subscriber } - { name: kernel.event_subscriber }
Chill\MainBundle\Security\PasswordRecover\PasswordRecoverLocker: Chill\MainBundle\Security\PasswordRecover\PasswordRecoverLocker:
arguments: arguments:
$chillRedis: '@Chill\MainBundle\Redis\ChillRedis' $chillRedis: '@Chill\MainBundle\Redis\ChillRedis'
$logger: '@Psr\Log\LoggerInterface' $logger: '@Psr\Log\LoggerInterface'
Chill\MainBundle\Security\PasswordRecover\PasswordRecoverVoter: Chill\MainBundle\Security\PasswordRecover\PasswordRecoverVoter:
arguments: arguments:
$locker: '@Chill\MainBundle\Security\PasswordRecover\PasswordRecoverLocker' $locker: '@Chill\MainBundle\Security\PasswordRecover\PasswordRecoverLocker'
$requestStack: '@Symfony\Component\HttpFoundation\RequestStack' $requestStack: '@Symfony\Component\HttpFoundation\RequestStack'
tags: tags:
- { name: security.voter } - { name: security.voter }

View File

@@ -11,3 +11,7 @@ services:
Chill\MainBundle\Serializer\Normalizer\UserNormalizer: Chill\MainBundle\Serializer\Normalizer\UserNormalizer:
tags: tags:
- { name: 'serializer.normalizer', priority: 64 } - { name: 'serializer.normalizer', priority: 64 }
Chill\MainBundle\Serializer\Normalizer\CollectionNormalizer:
tags:
- { name: 'serializer.normalizer', priority: 64 }

View File

@@ -30,7 +30,6 @@ services:
Chill\MainBundle\Templating\Entity\ChillEntityRenderExtension: Chill\MainBundle\Templating\Entity\ChillEntityRenderExtension:
tags: tags:
- { name: twig.extension } - { name: twig.extension }
Chill\MainBundle\Templating\Entity\ChillEntityRenderExtensionInterface: Chill\MainBundle\Templating\Entity\ChillEntityRenderExtension
Chill\MainBundle\Templating\Entity\CommentRender: Chill\MainBundle\Templating\Entity\CommentRender:
arguments: arguments:
@@ -38,7 +37,7 @@ services:
- '@Symfony\Component\Templating\EngineInterface' - '@Symfony\Component\Templating\EngineInterface'
tags: tags:
- { name: 'chill.render_entity' } - { name: 'chill.render_entity' }
Chill\MainBundle\Templating\ChillMarkdownRenderExtension: Chill\MainBundle\Templating\ChillMarkdownRenderExtension:
tags: tags:
- { name: twig.extension } - { name: twig.extension }

View File

@@ -4,6 +4,4 @@ services:
arguments: arguments:
- "@doctrine.orm.entity_manager" - "@doctrine.orm.entity_manager"
calls: calls:
- [ setContainer, ["@service_container"]] - [ setContainer, ["@service_container"]]
Chill\MainBundle\Timeline\TimelineBuilderInterface: "@chill_main.timeline_builder"

View File

@@ -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";
}
}

View File

@@ -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');
}
}

View File

@@ -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');
}
}

View File

@@ -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;
');
}
}

View File

@@ -17,57 +17,57 @@
*/ */
namespace Chill\PersonBundle\Actions; namespace Chill\PersonBundle\Actions;
use Symfony\Contracts\EventDispatcher\Event; use Symfony\Component\EventDispatcher\Event;
/** /**
* Event triggered when an entity attached to a person is removed. * Event triggered when an entity attached to a person is removed.
* *
* *
*/ */
class ActionEvent implements Event class ActionEvent extends Event
{ {
const DELETE = 'CHILL_PERSON.DELETE_ASSOCIATED_ENTITY'; const DELETE = 'CHILL_PERSON.DELETE_ASSOCIATED_ENTITY';
const MOVE = 'CHILL_PERSON.MOVE_ASSOCIATED_ENTITY'; const MOVE = 'CHILL_PERSON.MOVE_ASSOCIATED_ENTITY';
/** /**
* *
* @var int * @var int
*/ */
protected $personId; protected $personId;
/** /**
* the FQDN class name as recorded in doctrine * the FQDN class name as recorded in doctrine
* *
* @var string * @var string
*/ */
protected $entity; protected $entity;
/** /**
* an array of key value data to describe the movement * an array of key value data to describe the movement
* *
* @var array * @var array
*/ */
protected $metadata; protected $metadata;
/** /**
* the sql statement * the sql statement
* *
* @var string * @var string
*/ */
protected $sqlStatement; protected $sqlStatement;
/** /**
* *
* @var string[] * @var string[]
*/ */
protected $preSql = []; protected $preSql = [];
/** /**
* *
* @var string[] * @var string[]
*/ */
protected $postSql = []; protected $postSql = [];
public function __construct($personId, $entity, $sqlStatement, $metadata = []) public function __construct($personId, $entity, $sqlStatement, $metadata = [])
{ {
$this->personId = $personId; $this->personId = $personId;
@@ -77,7 +77,7 @@ class ActionEvent implements Event
} }
/** /**
* *
* @return string[] * @return string[]
*/ */
public function getPreSql(): array public function getPreSql(): array
@@ -86,7 +86,7 @@ class ActionEvent implements Event
} }
/** /**
* *
* @return string[] * @return string[]
*/ */
public function getPostSql(): array public function getPostSql(): array
@@ -105,7 +105,7 @@ class ActionEvent implements Event
/** /**
* Add Sql which will be executed **after** the delete statement * Add Sql which will be executed **after** the delete statement
* *
* @param type $postSql * @param type $postSql
* @return $this * @return $this
*/ */
@@ -122,22 +122,22 @@ class ActionEvent implements Event
/** /**
* get the entity name, as recorded in doctrine * get the entity name, as recorded in doctrine
* *
* @return string * @return string
*/ */
public function getEntity(): string public function getEntity(): string
{ {
return $this->entity; return $this->entity;
} }
public function getSqlStatement() public function getSqlStatement()
{ {
return $this->sqlStatement; return $this->sqlStatement;
} }
public function getMetadata() public function getMetadata()
{ {
return $this->metadata; return $this->metadata;
} }
} }

View File

@@ -5,10 +5,10 @@ namespace Chill\PersonBundle\Config;
/** /**
* Give help to interact with the config for alt names * Give help to interact with the config for alt names
* *
* *
*/ */
class ConfigPersonAltNamesHelper implements ConfigPersonAltNamesHelperInterface class ConfigPersonAltNamesHelper
{ {
/** /**
* the raw config, directly from the container parameter * the raw config, directly from the container parameter
@@ -16,32 +16,32 @@ class ConfigPersonAltNamesHelper implements ConfigPersonAltNamesHelperInterface
* @var array * @var array
*/ */
private $config = []; private $config = [];
public function __construct($config) public function __construct($config)
{ {
$this->config = $config; $this->config = $config;
} }
/** /**
* Return true if at least one alt name is configured * Return true if at least one alt name is configured
* *
* @return bool * @return bool
*/ */
public function hasAltNames(): bool public function hasAltNames(): bool
{ {
return count($this->config) > 0; return count($this->config) > 0;
} }
/** /**
* get the choices as key => values * get the choices as key => values
* *
* @return array * @return array
*/ */
public function getChoices(): array public function getChoices(): array
{ {
$choices = []; $choices = [];
foreach ($this->config as $entry) { foreach ($this->config as $entry) {
$labels = $entry['labels']; $labels = $entry['labels'];
$lang = false; $lang = false;
$label = false; $label = false;
@@ -50,11 +50,11 @@ class ConfigPersonAltNamesHelper implements ConfigPersonAltNamesHelperInterface
if (key($labels) === 'lang') { if (key($labels) === 'lang') {
$lang = current($labels); $lang = current($labels);
} }
if (key($labels) === 'label') { if (key($labels) === 'label') {
$label = current($labels); $label = current($labels);
} }
if ($lang !== FALSE && $label !== FALSE) { if ($lang !== FALSE && $label !== FALSE) {
$choices[$entry['key']][$lang] = $label; $choices[$entry['key']][$lang] = $label;
$lang = false; $lang = false;
@@ -63,7 +63,7 @@ class ConfigPersonAltNamesHelper implements ConfigPersonAltNamesHelperInterface
$cur = next($labels); $cur = next($labels);
} }
} }
return $choices; return $choices;
} }

View File

@@ -0,0 +1,79 @@
<?php
namespace Chill\PersonBundle\Controller;
use Chill\MainBundle\CRUD\Controller\ApiController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Symfony\Component\HttpFoundation\Exception\BadRequestException;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Chill\PersonBundle\Privacy\AccompanyingPeriodPrivacyEvent;
use Chill\PersonBundle\Entity\Person;
class AccompanyingCourseApiController extends ApiController
{
protected EventDispatcherInterface $eventDispatcher;
protected ValidatorInterface $validator;
public function __construct(EventDispatcherInterface $eventDispatcher, $validator)
{
$this->eventDispatcher = $eventDispatcher;
$this->validator = $validator;
}
public function participationApi($id, Request $request, $_format)
{
/** @var AccompanyingPeriod $accompanyingPeriod */
$accompanyingPeriod = $this->getEntity('participation', $id, $request);
$person = $this->getSerializer()
->deserialize($request->getContent(), Person::class, $_format, []);
if (NULL === $person) {
throw new BadRequestException('person id not found');
}
// TODO add acl
//
$this->onPostCheckACL('participation', $request, $_format, $accompanyingPeriod);
switch ($request->getMethod()) {
case Request::METHOD_POST:
$participation = $accompanyingPeriod->addPerson($person);
break;
case Request::METHOD_DELETE:
$participation = $accompanyingPeriod->removePerson($person);
$participation->setEndDate(new \DateTimeImmutable('now'));
break;
default:
throw new BadRequestException("This method is not supported");
}
$errors = $this->validator->validate($accompanyingPeriod);
if ($errors->count() > 0) {
// only format accepted
return $this->json($errors);
}
$this->getDoctrine()->getManager()->flush();
return $this->json($participation);
}
protected function onPostCheckACL(string $action, Request $request, string $_format, $entity): ?Response
{
$this->eventDispatcher->dispatch(
AccompanyingPeriodPrivacyEvent::ACCOMPANYING_PERIOD_PRIVACY_EVENT,
new AccompanyingPeriodPrivacyEvent($entity, [
'action' => $action,
'request' => $request->getMethod()
])
);
return null;
}
}

View File

@@ -121,7 +121,7 @@ class AccompanyingCourseController extends Controller
* @Route( * @Route(
* "/{_locale}/person/api/1.0/accompanying-course/{accompanying_period_id}/participation.{_format}", * "/{_locale}/person/api/1.0/accompanying-course/{accompanying_period_id}/participation.{_format}",
* name="chill_person_accompanying_course_api_add_participation", * name="chill_person_accompanying_course_api_add_participation",
* methods={"POST"}, * methods={"POST","DELETE"},
* format="json", * format="json",
* requirements={ * requirements={
* "_format": "json", * "_format": "json",
@@ -129,7 +129,7 @@ class AccompanyingCourseController extends Controller
* ) * )
* @ParamConverter("accompanyingCourse", options={"id": "accompanying_period_id"}) * @ParamConverter("accompanyingCourse", options={"id": "accompanying_period_id"})
*/ */
public function addParticipationAPI(Request $request, AccompanyingPeriod $accompanyingCourse, $_format): Response public function participationAPI(Request $request, AccompanyingPeriod $accompanyingCourse, $_format): Response
{ {
switch ($_format) { switch ($_format) {
case 'json': case 'json':
@@ -146,7 +146,9 @@ class AccompanyingCourseController extends Controller
} }
// TODO add acl // TODO add acl
$accompanyingCourse->addPerson($person); $participation = ($request->getMethod() === 'POST') ?
$accompanyingCourse->addPerson($person) : $accompanyingCourse->removePerson($person);
$errors = $this->validator->validate($accompanyingCourse); $errors = $this->validator->validate($accompanyingCourse);
if ($errors->count() > 0) { if ($errors->count() > 0) {
@@ -156,6 +158,6 @@ class AccompanyingCourseController extends Controller
$this->getDoctrine()->getManager()->flush(); $this->getDoctrine()->getManager()->flush();
return new JsonResponse(); return $this->json($participation);
} }
} }

View File

@@ -26,7 +26,7 @@ use Chill\PersonBundle\Privacy\PrivacyEvent;
use Doctrine\DBAL\Exception; use Doctrine\DBAL\Exception;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Chill\PersonBundle\Entity\Person; use Chill\PersonBundle\Entity\Person;
use Chill\PersonBundle\Form\Type\AccompanyingPeriodType; use Chill\PersonBundle\Form\AccompanyingPeriodType;
use Chill\PersonBundle\Entity\AccompanyingPeriod; use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Doctrine\Common\Collections\Criteria; use Doctrine\Common\Collections\Criteria;
use Chill\PersonBundle\Security\Authorization\PersonVoter; use Chill\PersonBundle\Security\Authorization\PersonVoter;
@@ -47,12 +47,12 @@ class AccompanyingPeriodController extends AbstractController
* @var EventDispatcherInterface * @var EventDispatcherInterface
*/ */
protected $eventDispatcher; protected $eventDispatcher;
/** /**
* @var ValidatorInterface * @var ValidatorInterface
*/ */
protected $validator; protected $validator;
/** /**
* AccompanyingPeriodController constructor. * AccompanyingPeriodController constructor.
* *
@@ -64,17 +64,11 @@ class AccompanyingPeriodController extends AbstractController
$this->eventDispatcher = $eventDispatcher; $this->eventDispatcher = $eventDispatcher;
$this->validator = $validator; $this->validator = $validator;
} }
/**
* @Route(
* name="chill_person_accompanying_period_list",
* path="/{_locale}/person/{person_id}/accompanying-period"
* )
*/
public function listAction(int $person_id): Response public function listAction(int $person_id): Response
{ {
$person = $this->_getPerson($person_id); $person = $this->_getPerson($person_id);
$event = new PrivacyEvent($person, [ $event = new PrivacyEvent($person, [
'element_class' => AccompanyingPeriod::class, 'element_class' => AccompanyingPeriod::class,
'action' => 'list' 'action' => 'list'
@@ -86,13 +80,7 @@ class AccompanyingPeriodController extends AbstractController
'person' => $person 'person' => $person
]); ]);
} }
/**
* @Route(
* name="chill_person_accompanying_period_create",
* path="/{_locale}/person/{person_id}/accompanying-period/create"
* )
*/
public function createAction(int $person_id, Request $request): Response public function createAction(int $person_id, Request $request): Response
{ {
$person = $this->_getPerson($person_id); $person = $this->_getPerson($person_id);
@@ -102,17 +90,17 @@ class AccompanyingPeriodController extends AbstractController
$accompanyingPeriod = new AccompanyingPeriod(new \DateTime('now')); $accompanyingPeriod = new AccompanyingPeriod(new \DateTime('now'));
$accompanyingPeriod->setClosingDate(new \DateTime('now')); $accompanyingPeriod->setClosingDate(new \DateTime('now'));
$accompanyingPeriod->addPerson($person); $accompanyingPeriod->addPerson($person);
//or $person->addAccompanyingPeriod($accompanyingPeriod); //or $person->addAccompanyingPeriod($accompanyingPeriod);
$form = $this->createForm( $form = $this->createForm(
AccompanyingPeriodType::class, AccompanyingPeriodType::class,
$accompanyingPeriod, [ $accompanyingPeriod, [
'period_action' => 'create', 'period_action' => 'create',
'center' => $person->getCenter() 'center' => $person->getCenter()
]); ]);
if ($request->getMethod() === 'POST') { if ($request->getMethod() === 'POST') {
$form->handleRequest($request); $form->handleRequest($request);
$errors = $this->_validatePerson($person); $errors = $this->_validatePerson($person);
@@ -132,7 +120,7 @@ class AccompanyingPeriodController extends AbstractController
$this->generateUrl('chill_person_accompanying_period_list', [ $this->generateUrl('chill_person_accompanying_period_list', [
'person_id' => $person->getId() 'person_id' => $person->getId()
])); ]));
} else { } else {
$flashBag->add('error', $this->get('translator') $flashBag->add('error', $this->get('translator')
->trans('Error! Period not created!')); ->trans('Error! Period not created!'));
@@ -149,12 +137,9 @@ class AccompanyingPeriodController extends AbstractController
'accompanying_period' => $accompanyingPeriod 'accompanying_period' => $accompanyingPeriod
]); ]);
} }
/** /**
* @Route( * @throws Exception
* name="chill_person_accompanying_period_update",
* path="/{_locale}/person/{person_id}/accompanying-period/{period_id}/update"
* )
*/ */
public function updateAction(int $person_id, int $period_id, Request $request): Response public function updateAction(int $person_id, int $period_id, Request $request): Response
{ {
@@ -169,7 +154,7 @@ class AccompanyingPeriodController extends AbstractController
/** @var Person $person */ /** @var Person $person */
$person = $this->_getPerson($person_id); $person = $this->_getPerson($person_id);
// CHECK // CHECK
if (! $accompanyingPeriod->containsPerson($person)) { if (! $accompanyingPeriod->containsPerson($person)) {
throw new Exception("Accompanying period " . $period_id . " does not contain person " . $person_id); throw new Exception("Accompanying period " . $period_id . " does not contain person " . $person_id);
@@ -191,7 +176,7 @@ class AccompanyingPeriodController extends AbstractController
if ($form->isValid(['Default', 'closed']) if ($form->isValid(['Default', 'closed'])
&& count($errors) === 0) { && count($errors) === 0) {
$em->flush(); $em->flush();
$flashBag->add('success', $flashBag->add('success',
@@ -201,9 +186,9 @@ class AccompanyingPeriodController extends AbstractController
$this->generateUrl('chill_person_accompanying_period_list', [ $this->generateUrl('chill_person_accompanying_period_list', [
'person_id' => $person->getId() 'person_id' => $person->getId()
])); ]));
} else { } else {
$flashBag->add('error', $this->get('translator') $flashBag->add('error', $this->get('translator')
->trans('Error when updating the period')); ->trans('Error when updating the period'));
@@ -219,22 +204,19 @@ class AccompanyingPeriodController extends AbstractController
'accompanying_period' => $accompanyingPeriod 'accompanying_period' => $accompanyingPeriod
]); ]);
} }
/** /**
* @Route( * @throws \Exception
* name="chill_person_accompanying_period_close",
* path="/{_locale}/person/{person_id}/accompanying-period/close"
* )
*/ */
public function closeAction(int $person_id, Request $request): Response public function closeAction(int $person_id, Request $request): Response
{ {
$person = $this->_getPerson($person_id); $person = $this->_getPerson($person_id);
$this->denyAccessUnlessGranted(PersonVoter::UPDATE, $person, 'You are not allowed to update this person'); $this->denyAccessUnlessGranted(PersonVoter::UPDATE, $person, 'You are not allowed to update this person');
if ($person->isOpen() === false) { if ($person->isOpen() === false) {
$this->get('session')->getFlashBag() $this->get('session')->getFlashBag()
->add('error', $this->get('translator') ->add('error', $this->get('translator')
->trans('Beware period is closed', ['%name%' => $person->__toString()] ->trans('Beware period is closed', ['%name%' => $person->__toString()]
@@ -247,7 +229,7 @@ class AccompanyingPeriodController extends AbstractController
} }
$current = $person->getCurrentAccompanyingPeriod(); $current = $person->getCurrentAccompanyingPeriod();
$form = $this->createForm(AccompanyingPeriodType::class, $current, [ $form = $this->createForm(AccompanyingPeriodType::class, $current, [
'period_action' => 'close', 'period_action' => 'close',
'center' => $person->getCenter() 'center' => $person->getCenter()
@@ -274,7 +256,7 @@ class AccompanyingPeriodController extends AbstractController
'person_id' => $person->getId() 'person_id' => $person->getId()
]) ])
); );
} else { } else {
$this->get('session')->getFlashBag() $this->get('session')->getFlashBag()
->add('error', $this->get('translator') ->add('error', $this->get('translator')
@@ -285,7 +267,7 @@ class AccompanyingPeriodController extends AbstractController
->add('info', $error->getMessage()); ->add('info', $error->getMessage());
} }
} }
} else { //if form is not valid } else { //if form is not valid
$this->get('session')->getFlashBag() $this->get('session')->getFlashBag()
->add('error', ->add('error',
@@ -306,7 +288,7 @@ class AccompanyingPeriodController extends AbstractController
'accompanying_period' => $current 'accompanying_period' => $current
]); ]);
} }
private function _validatePerson(Person $person): ConstraintViolationListInterface private function _validatePerson(Person $person): ConstraintViolationListInterface
{ {
$errors = $this->validator->validate($person, null, $errors = $this->validator->validate($person, null,
@@ -314,10 +296,10 @@ class AccompanyingPeriodController extends AbstractController
// Can be disabled with config // Can be disabled with config
if (false === $this->container->getParameter('chill_person.allow_multiple_simultaneous_accompanying_periods')) { if (false === $this->container->getParameter('chill_person.allow_multiple_simultaneous_accompanying_periods')) {
$errors_accompanying_period = $this->validator->validate($person, null, $errors_accompanying_period = $this->validator->validate($person, null,
['accompanying_period_consistent']); ['accompanying_period_consistent']);
foreach($errors_accompanying_period as $error ) { foreach($errors_accompanying_period as $error ) {
$errors->add($error); $errors->add($error);
} }
@@ -325,13 +307,7 @@ class AccompanyingPeriodController extends AbstractController
return $errors; return $errors;
} }
/**
* @Route(
* name="chill_person_accompanying_period_open",
* path="/{_locale}/person/{person_id}/accompanying-period/open"
* )
*/
public function openAction(int $person_id, Request $request): Response public function openAction(int $person_id, Request $request): Response
{ {
$person = $this->_getPerson($person_id); $person = $this->_getPerson($person_id);
@@ -408,13 +384,7 @@ class AccompanyingPeriodController extends AbstractController
'accompanying_period' => $accompanyingPeriod 'accompanying_period' => $accompanyingPeriod
]); ]);
} }
/**
* @Route(
* name="chill_person_accompanying_period_re_open",
* path="/{_locale}/person/{person_id}/accompanying-period/re-open"
* )
*/
public function reOpenAction(int $person_id, int $period_id, Request $request): Response public function reOpenAction(int $person_id, int $period_id, Request $request): Response
{ {
/** @var Person $person */ /** @var Person $person */
@@ -447,13 +417,13 @@ class AccompanyingPeriodController extends AbstractController
return $this->redirectToRoute('chill_person_accompanying_period_list', [ return $this->redirectToRoute('chill_person_accompanying_period_list', [
'person_id' => $person->getId() 'person_id' => $person->getId()
]); ]);
} elseif ($confirm === false && $period->canBeReOpened($person)) { } elseif ($confirm === false && $period->canBeReOpened($person)) {
return $this->render('ChillPersonBundle:AccompanyingPeriod:re_open.html.twig', [ return $this->render('ChillPersonBundle:AccompanyingPeriod:re_open.html.twig', [
'period' => $period, 'period' => $period,
'person' => $person 'person' => $person
]); ]);
} else { } else {
return (new Response()) return (new Response())
->setStatusCode(Response::HTTP_BAD_REQUEST) ->setStatusCode(Response::HTTP_BAD_REQUEST)

View File

@@ -13,29 +13,16 @@ use Symfony\Component\Routing\Annotation\Route;
class AdminController extends AbstractController class AdminController extends AbstractController
{ {
/** /**
* @Route( * @param $_locale
* name="chill_person_admin", * @return \Symfony\Component\HttpFoundation\Response
* path="/{_locale}/admin/person"
* )
*/ */
public function indexAction($_locale) public function indexAction($_locale)
{ {
return $this->render('ChillPersonBundle:Admin:layout.html.twig', []); return $this->render('ChillPersonBundle:Admin:layout.html.twig', []);
} }
/** /**
* @Route( * @return \Symfony\Component\HttpFoundation\RedirectResponse
* name="chill_person_admin_redirect_to_admin_index",
* path="/{_locale}/admin/person_redirect_to_main",
* options={
* menus={
* admin_person={
* order="0",
* label="Main admin menu"
* }
* }
* }
* )
*/ */
public function redirectToAdminIndexAction() public function redirectToAdminIndexAction()
{ {

View File

@@ -0,0 +1,17 @@
<?php
namespace Chill\PersonBundle\Controller;
use Chill\MainBundle\CRUD\Controller\ApiController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class OpeningApiController extends ApiController
{
protected function customizeQuery(string $action, Request $request, $qb): void
{
$qb->where($qb->expr()->gt('e.noActiveAfter', ':now'))
->orWhere($qb->expr()->isNull('e.noActiveAfter'));
$qb->setParameter('now', new \DateTime('now'));
}
}

View File

@@ -30,7 +30,6 @@ use Chill\MainBundle\Entity\Address;
use Doctrine\Common\Collections\Criteria; use Doctrine\Common\Collections\Criteria;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Validator\ValidatorInterface; use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\Routing\Annotation\Route;
/** /**
* Class PersonAddressController * Class PersonAddressController
@@ -46,7 +45,7 @@ class PersonAddressController extends AbstractController
* @var ValidatorInterface * @var ValidatorInterface
*/ */
protected $validator; protected $validator;
/** /**
* PersonAddressController constructor. * PersonAddressController constructor.
* *
@@ -56,13 +55,7 @@ class PersonAddressController extends AbstractController
{ {
$this->validator = $validator; $this->validator = $validator;
} }
/**
* @Route(
* name="chill_person_address_list",
* path="/{_locale}/person/{person_id}/address/list"
* )
*/
public function listAction($person_id) public function listAction($person_id)
{ {
$person = $this->getDoctrine()->getManager() $person = $this->getDoctrine()->getManager()
@@ -85,13 +78,6 @@ class PersonAddressController extends AbstractController
)); ));
} }
/**
* @Route(
* name="chill_person_address_create",
* path="/{_locale}/person/{person_id}/address/create",
* methods={"POST"}
* )
*/
public function newAction($person_id) public function newAction($person_id)
{ {
$person = $this->getDoctrine()->getManager() $person = $this->getDoctrine()->getManager()
@@ -119,12 +105,6 @@ class PersonAddressController extends AbstractController
)); ));
} }
/**
* @Route(
* name="chill_person_address_new",
* path="/{_locale}/person/{person_id}/address/new"
* )
*/
public function createAction($person_id, Request $request) public function createAction($person_id, Request $request)
{ {
$person = $this->getDoctrine()->getManager() $person = $this->getDoctrine()->getManager()
@@ -181,12 +161,6 @@ class PersonAddressController extends AbstractController
)); ));
} }
/**
* @Route(
* name="chill_person_address_edit",
* path="/{_locale}/person/{person_id}/address/{address_id}/edit"
* )
*/
public function editAction($person_id, $address_id) public function editAction($person_id, $address_id)
{ {
$person = $this->getDoctrine()->getManager() $person = $this->getDoctrine()->getManager()
@@ -215,12 +189,6 @@ class PersonAddressController extends AbstractController
)); ));
} }
/**
* @Route(
* name="chill_person_address_update",
* path="/{_locale}/person/{person_id}/address/{address_id}/update"
* )
*/
public function updateAction($person_id, $address_id, Request $request) public function updateAction($person_id, $address_id, Request $request)
{ {
$person = $this->getDoctrine()->getManager() $person = $this->getDoctrine()->getManager()

View File

@@ -34,14 +34,12 @@ use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Role\Role; use Symfony\Component\Security\Core\Role\Role;
use Chill\PersonBundle\Security\Authorization\PersonVoter; use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Chill\PersonBundle\Search\SimilarPersonMatcher; use Chill\PersonBundle\Search\SimilarPersonMatcher;
use Symfony\Component\Translation\TranslatorInterface;
use Chill\MainBundle\Search\SearchProvider; use Chill\MainBundle\Search\SearchProvider;
use Chill\PersonBundle\Repository\PersonRepository; use Chill\PersonBundle\Repository\PersonRepository;
use Chill\PersonBundle\Config\ConfigPersonAltNamesHelper; use Chill\PersonBundle\Config\ConfigPersonAltNamesHelper;
use Chill\PersonBundle\Repository\PersonNotDuplicateRepository;
use Symfony\Component\Validator\Validator\ValidatorInterface; use Symfony\Component\Validator\Validator\ValidatorInterface;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;
final class PersonController extends AbstractController final class PersonController extends AbstractController
{ {
@@ -119,12 +117,6 @@ final class PersonController extends AbstractController
return $cFGroup; return $cFGroup;
} }
/**
* @Route(
* name="chill_person_view",
* path="/{_locale}/person/{person_id}/general"
* )
*/
public function viewAction($person_id) public function viewAction($person_id)
{ {
$person = $this->_getPerson($person_id); $person = $this->_getPerson($person_id);
@@ -148,12 +140,6 @@ final class PersonController extends AbstractController
)); ));
} }
/**
* @Route(
* name="chill_person_general_edit",
* path="/{_locale}/person/{person_id}/general/edit"
* )
*/
public function editAction($person_id) public function editAction($person_id)
{ {
$person = $this->_getPerson($person_id); $person = $this->_getPerson($person_id);
@@ -177,13 +163,7 @@ final class PersonController extends AbstractController
array('person' => $person, 'form' => $form->createView())); array('person' => $person, 'form' => $form->createView()));
} }
/** public function updateAction($person_id, Request $request)
* @Route(
* name="chill_person_general_update",
* path="/{_locale}/person/{person_id}/general/update"
* )
*/
public function updateAction($person_id, Request $request, TranslatorInterface $translator)
{ {
$person = $this->_getPerson($person_id); $person = $this->_getPerson($person_id);
@@ -212,7 +192,7 @@ final class PersonController extends AbstractController
$this->get('session')->getFlashBag() $this->get('session')->getFlashBag()
->add('success', ->add('success',
$translator $this->get('translator')
->trans('The person data has been updated') ->trans('The person data has been updated')
); );
@@ -226,12 +206,6 @@ final class PersonController extends AbstractController
} }
} }
/**
* @Route(
* name="chill_person_new",
* path="/{_locale}/person/new"
* )
*/
public function newAction() public function newAction()
{ {
// this is a dummy default center. // this is a dummy default center.
@@ -316,13 +290,7 @@ final class PersonController extends AbstractController
return $errors; return $errors;
} }
/** public function reviewAction(Request $request)
* @Route(
* name="chill_person_review",
* path="/{_locale}/person/review"
* )
*/
public function reviewAction(Request $request, PersonNotDuplicateRepository $personNotDuplicateRepository)
{ {
if ($request->getMethod() !== 'POST') { if ($request->getMethod() !== 'POST') {
$r = new Response("You must send something to review the creation of a new Person"); $r = new Response("You must send something to review the creation of a new Person");
@@ -374,7 +342,8 @@ final class PersonController extends AbstractController
$this->em->persist($person); $this->em->persist($person);
$alternatePersons = $this->similarPersonMatcher->matchPerson($person, $personNotDuplicateRepository); $alternatePersons = $this->similarPersonMatcher
->matchPerson($person);
if (count($alternatePersons) === 0) { if (count($alternatePersons) === 0) {
return $this->forward('ChillPersonBundle:Person:create'); return $this->forward('ChillPersonBundle:Person:create');
@@ -398,12 +367,6 @@ final class PersonController extends AbstractController
'form' => $form->createView())); 'form' => $form->createView()));
} }
/**
* @Route(
* name="chill_person_create",
* path="/{_locale}/person/create"
* )
*/
public function createAction(Request $request) public function createAction(Request $request)
{ {

View File

@@ -12,17 +12,16 @@ use Chill\PersonBundle\Privacy\PrivacyEvent;
use Chill\PersonBundle\Repository\PersonRepository; use Chill\PersonBundle\Repository\PersonRepository;
use Chill\PersonBundle\Search\SimilarPersonMatcher; use Chill\PersonBundle\Search\SimilarPersonMatcher;
use http\Exception\InvalidArgumentException; use http\Exception\InvalidArgumentException;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Translation\TranslatorInterface; use Symfony\Component\Translation\TranslatorInterface;
use Chill\ActivityBundle\Entity\Activity; use Chill\ActivityBundle\Entity\Activity;
use Chill\DocStoreBundle\Entity\PersonDocument; use Chill\DocStoreBundle\Entity\PersonDocument;
use Chill\EventBundle\Entity\Participation; use Chill\EventBundle\Entity\Participation;
use Chill\PersonBundle\Repository\PersonNotDuplicateRepository;
use Chill\TaskBundle\Entity\SingleTask; use Chill\TaskBundle\Entity\SingleTask;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class PersonDuplicateController extends AbstractController class PersonDuplicateController extends Controller
{ {
/** /**
* @var \Chill\PersonBundle\Search\SimilarPersonMatcher * @var \Chill\PersonBundle\Search\SimilarPersonMatcher
@@ -63,13 +62,7 @@ class PersonDuplicateController extends AbstractController
$this->eventDispatcher = $eventDispatcher; $this->eventDispatcher = $eventDispatcher;
} }
/** public function viewAction($person_id)
* @Route(
* name="chill_person_duplicate_view",
* path="/{_locale}/person/{person_id}/duplicate/view"
* )
*/
public function viewAction($person_id, PersonNotDuplicateRepository $personNotDuplicateRepository)
{ {
$person = $this->_getPerson($person_id); $person = $this->_getPerson($person_id);
if ($person === null) { if ($person === null) {
@@ -83,7 +76,8 @@ class PersonDuplicateController extends AbstractController
$duplicatePersons = $this->similarPersonMatcher-> $duplicatePersons = $this->similarPersonMatcher->
matchPerson($person, 0.5, SimilarPersonMatcher::SIMILAR_SEARCH_ORDER_BY_ALPHABETICAL); matchPerson($person, 0.5, SimilarPersonMatcher::SIMILAR_SEARCH_ORDER_BY_ALPHABETICAL);
$notDuplicatePersons = $personNotDuplicateRepository->findNotDuplicatePerson($person); $notDuplicatePersons = $this->getDoctrine()->getRepository(PersonNotDuplicate::class)
->findNotDuplicatePerson($person);
return $this->render('ChillPersonBundle:PersonDuplicate:view.html.twig', [ return $this->render('ChillPersonBundle:PersonDuplicate:view.html.twig', [
'person' => $person, 'person' => $person,
@@ -92,12 +86,6 @@ class PersonDuplicateController extends AbstractController
]); ]);
} }
/**
* @Route(
* name="chill_person_duplicate_confirm",
* path="/{_locale}/person/{person1_id}/duplicate/{person2_id}/confirm"
* )
*/
public function confirmAction($person1_id, $person2_id, Request $request) public function confirmAction($person1_id, $person2_id, Request $request)
{ {
if ($person1_id === $person2_id) { if ($person1_id === $person2_id) {
@@ -109,7 +97,7 @@ class PersonDuplicateController extends AbstractController
$person1->counters = $this->_getCounters($person1_id); $person1->counters = $this->_getCounters($person1_id);
$person2->counters = $this->_getCounters($person2_id); $person2->counters = $this->_getCounters($person2_id);
if ($person1 === null) { if ($person1 === null) {
throw $this->createNotFoundException("Person with id $person1_id not" throw $this->createNotFoundException("Person with id $person1_id not"
. " found on this server"); . " found on this server");
@@ -155,12 +143,6 @@ class PersonDuplicateController extends AbstractController
]); ]);
} }
/**
* @Route(
* name="chill_person_duplicate_not_duplicate",
* path="/{_locale}/person/{person1_id}/duplicate/{person2_id}/not-duplicate"
* )
*/
public function notDuplicateAction($person1_id, $person2_id) public function notDuplicateAction($person1_id, $person2_id)
{ {
[$person1, $person2] = $this->_getPersonsByPriority($person1_id, $person2_id); [$person1, $person2] = $this->_getPersonsByPriority($person1_id, $person2_id);
@@ -184,12 +166,6 @@ class PersonDuplicateController extends AbstractController
return $this->redirectToRoute('chill_person_duplicate_view', ['person_id' => $person1->getId()]); return $this->redirectToRoute('chill_person_duplicate_view', ['person_id' => $person1->getId()]);
} }
/**
* @Route(
* name="chill_person_remove_duplicate_not_duplicate",
* path="/{_locale}/person/{person1_id}/duplicate/{person2_id}/remove-not-duplicate"
* )
*/
public function removeNotDuplicateAction($person1_id, $person2_id) public function removeNotDuplicateAction($person1_id, $person2_id)
{ {
[$person1, $person2] = $this->_getPersonsByPriority($person1_id, $person2_id); [$person1, $person2] = $this->_getPersonsByPriority($person1_id, $person2_id);
@@ -208,12 +184,6 @@ class PersonDuplicateController extends AbstractController
return $this->redirectToRoute('chill_person_duplicate_view', ['person_id' => $person1->getId()]); return $this->redirectToRoute('chill_person_duplicate_view', ['person_id' => $person1->getId()]);
} }
/**
* @Route(
* name="chill_person_find_manually_duplicate",
* path="/{_locale}/person/{person_id}/find-manually"
* )
*/
public function findManuallyDuplicateAction($person_id, Request $request) public function findManuallyDuplicateAction($person_id, Request $request)
{ {
$person = $this->_getPerson($person_id); $person = $this->_getPerson($person_id);
@@ -294,17 +264,17 @@ class PersonDuplicateController extends AbstractController
return [$person1, $person2]; return [$person1, $person2];
} }
private function _getCounters($id): ?array private function _getCounters($id): ?array
{ {
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
$nb_activity = $em->getRepository(Activity::class)->findBy(['person'=>$id]); $nb_activity = $em->getRepository(Activity::class)->findBy(['person'=>$id]);
$nb_document = $em->getRepository(PersonDocument::class)->findBy(['person'=>$id]); $nb_document = $em->getRepository(PersonDocument::class)->findBy(['person'=>$id]);
$nb_event = $em->getRepository(Participation::class)->findBy(['person'=>$id]); $nb_event = $em->getRepository(Participation::class)->findBy(['person'=>$id]);
$nb_task = $em->getRepository(SingleTask::class)->countByParameters(['person'=>$id]); $nb_task = $em->getRepository(SingleTask::class)->countByParameters(['person'=>$id]);
$person = $em->getRepository(Person::class)->findOneBy(['id'=>$id]); $person = $em->getRepository(Person::class)->findOneBy(['id'=>$id]);
return [ return [
'nb_activity' => count($nb_activity), 'nb_activity' => count($nb_activity),
'nb_document' => count($nb_document), 'nb_document' => count($nb_document),

View File

@@ -26,9 +26,7 @@ use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Chill\MainBundle\Timeline\TimelineBuilder; use Chill\MainBundle\Timeline\TimelineBuilder;
use Chill\MainBundle\Pagination\PaginatorFactory; use Chill\MainBundle\Pagination\PaginatorFactory;
use Chill\MainBundle\Timeline\TimelineBuilderInterface;
use Chill\PersonBundle\Security\Authorization\PersonVoter; use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Symfony\Component\Routing\Annotation\Route;
/** /**
* Class TimelinePersonController * Class TimelinePersonController
@@ -38,24 +36,24 @@ use Symfony\Component\Routing\Annotation\Route;
*/ */
class TimelinePersonController extends AbstractController class TimelinePersonController extends AbstractController
{ {
/** /**
* @var EventDispatcherInterface * @var EventDispatcherInterface
*/ */
protected $eventDispatcher; protected $eventDispatcher;
/** /**
* *
* @var TimelineBuilderInterface * @var TimelineBuilder
*/ */
protected $timelineBuilder; protected $timelineBuilder;
/** /**
* *
* @var PaginatorFactory * @var PaginatorFactory
*/ */
protected $paginatorFactory; protected $paginatorFactory;
/** /**
* TimelinePersonController constructor. * TimelinePersonController constructor.
* *
@@ -63,28 +61,15 @@ class TimelinePersonController extends AbstractController
*/ */
public function __construct( public function __construct(
EventDispatcherInterface $eventDispatcher, EventDispatcherInterface $eventDispatcher,
TimelineBuilderInterface $timelineBuilder, TimelineBuilder $timelineBuilder,
PaginatorFactory $paginatorFactory PaginatorFactory $paginatorFactory
) { ) {
$this->eventDispatcher = $eventDispatcher; $this->eventDispatcher = $eventDispatcher;
$this->timelineBuilder = $timelineBuilder; $this->timelineBuilder = $timelineBuilder;
$this->paginatorFactory = $paginatorFactory; $this->paginatorFactory = $paginatorFactory;
} }
/**
* @Route(
* name="chill_person_timeline",
* path="/{_locale}/person/{person_id}/timeline",
* options={
* menus={
* person={
* order="60",
* label="Timeline"
* }
* }
* }
* )
*/
public function personAction(Request $request, $person_id) public function personAction(Request $request, $person_id)
{ {
$person = $this->getDoctrine() $person = $this->getDoctrine()
@@ -94,22 +79,22 @@ class TimelinePersonController extends AbstractController
if ($person === NULL) { if ($person === NULL) {
throw $this->createNotFoundException(); throw $this->createNotFoundException();
} }
$this->denyAccessUnlessGranted(PersonVoter::SEE, $person); $this->denyAccessUnlessGranted(PersonVoter::SEE, $person);
$nbItems = $this->timelineBuilder->countItems('person', $nbItems = $this->timelineBuilder->countItems('person',
[ 'person' => $person ] [ 'person' => $person ]
); );
$paginator = $this->paginatorFactory->create($nbItems); $paginator = $this->paginatorFactory->create($nbItems);
$event = new PrivacyEvent($person, array('action' => 'timeline')); $event = new PrivacyEvent($person, array('action' => 'timeline'));
$this->eventDispatcher->dispatch(PrivacyEvent::PERSON_PRIVACY_EVENT, $event); $this->eventDispatcher->dispatch(PrivacyEvent::PERSON_PRIVACY_EVENT, $event);
return $this->render('ChillPersonBundle:Timeline:index.html.twig', array return $this->render('ChillPersonBundle:Timeline:index.html.twig', array
( (
'timeline' => $this->timelineBuilder->getTimelineHTML( 'timeline' => $this->timelineBuilder->getTimelineHTML(
'person', 'person',
array('person' => $person), array('person' => $person),
$paginator->getCurrentPage()->getFirstItemNumber(), $paginator->getCurrentPage()->getFirstItemNumber(),
$paginator->getItemsPerPage() $paginator->getItemsPerPage()

View File

@@ -0,0 +1,88 @@
<?php
/*
* Chill is a software for social workers
*
* Copyright (C) 2014-2015, Champs Libres Cooperative SCRLFS,
* <http://www.champs-libres.coop>, <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\PersonBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person;
/**
* Description of LoadAccompanyingPeriod
*
* @author Champs-Libres Coop
*/
class LoadAccompanyingPeriod extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{
use \Symfony\Component\DependencyInjection\ContainerAwareTrait;
public const ACCOMPANYING_PERIOD = 'parcours 1';
public function getOrder()
{
return 10004;
}
public static $references = array();
public function load(ObjectManager $manager)
{
$centerA = $this->getReference('centerA');
$centerAId = $centerA->getId();
$personIds = $this->container->get('doctrine.orm.entity_manager')
->createQueryBuilder()
->select('p.id')
->from('ChillPersonBundle:Person', 'p')
->where('p.center = :centerAId')
->orderBy('p.id', 'ASC')
->setParameter('centerAId', $centerAId)
->getQuery()
->getScalarResult();
$openingDate = new \DateTime('2020-04-01');
$person1 = $manager->getRepository(Person::class)->find($personIds[0]);
$person2 = $manager->getRepository(Person::class)->find($personIds[1]);
$socialScope = $this->getReference('scope_social');
$a = new AccompanyingPeriod($openingDate);
$a->addPerson($person1);
$a->addPerson($person2);
$a->addScope($socialScope);
$a->setStep(AccompanyingPeriod::STEP_CONFIRMED);
$manager->persist($a);
$this->addReference(self::ACCOMPANYING_PERIOD, $a);
echo "Adding one AccompanyingPeriod\n";
$manager->flush();
}
}

View File

@@ -0,0 +1,62 @@
<?php
/*
* Chill is a software for social workers
*
* Copyright (C) 2014-2015, Champs Libres Cooperative SCRLFS,
* <http://www.champs-libres.coop>, <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\PersonBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use Chill\PersonBundle\Entity\AccompanyingPeriod\Origin;
/**
* Description of LoadAccompanyingPeriodOrigin
*
* @author Champs-Libres Coop
*/
class LoadAccompanyingPeriodOrigin extends AbstractFixture implements OrderedFixtureInterface
{
public const ACCOMPANYING_PERIOD_ORIGIN = 'accompanying_period_origin';
public function getOrder()
{
return 10005;
}
private $phoneCall = ['en' => 'phone call', 'fr' => 'appel téléphonique'];
public static $references = array();
public function load(ObjectManager $manager)
{
$o = new Origin();
$o->setLabel(json_encode($this->phoneCall));
$manager->persist($o);
$this->addReference(self::ACCOMPANYING_PERIOD_ORIGIN, $o);
echo "Adding one AccompanyingPeriod Origin\n";
$manager->flush();
}
}

View File

@@ -29,6 +29,7 @@ use Chill\PersonBundle\Entity\Person;
use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Chill\MainBundle\DataFixtures\ORM\LoadPostalCodes; use Chill\MainBundle\DataFixtures\ORM\LoadPostalCodes;
use Chill\MainBundle\Entity\Address; use Chill\MainBundle\Entity\Address;
use Chill\MainBundle\Doctrine\Model\Point;
/** /**
* Load people into database * Load people into database
@@ -37,17 +38,17 @@ use Chill\MainBundle\Entity\Address;
* @author Marc Ducobu <marc@champs-libres.coop> * @author Marc Ducobu <marc@champs-libres.coop>
*/ */
class LoadPeople extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface class LoadPeople extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{ {
use \Symfony\Component\DependencyInjection\ContainerAwareTrait; use \Symfony\Component\DependencyInjection\ContainerAwareTrait;
protected $faker; protected $faker;
public function __construct() public function __construct()
{ {
$this->faker = \Faker\Factory::create('fr_FR'); $this->faker = \Faker\Factory::create('fr_FR');
} }
public function prepare() public function prepare()
{ {
//prepare days, month, years //prepare days, month, years
@@ -56,57 +57,57 @@ class LoadPeople extends AbstractFixture implements OrderedFixtureInterface, Con
$this->years[] = $y; $this->years[] = $y;
$y = $y +1; $y = $y +1;
} while ($y >= 1990); } while ($y >= 1990);
$m = 1; $m = 1;
do { do {
$this->month[] = $m; $this->month[] = $m;
$m = $m +1; $m = $m +1;
} while ($m >= 12); } while ($m >= 12);
$d = 1; $d = 1;
do { do {
$this->day[] = $d; $this->day[] = $d;
$d = $d + 1; $d = $d + 1;
} while ($d <= 28); } while ($d <= 28);
} }
public function getOrder() public function getOrder()
{ {
return 10000; return 10000;
} }
public function load(ObjectManager $manager) public function load(ObjectManager $manager)
{ {
$this->loadRandPeople($manager); $this->loadRandPeople($manager);
$this->loadExpectedPeople($manager); $this->loadExpectedPeople($manager);
$manager->flush(); $manager->flush();
} }
public function loadExpectedPeople(ObjectManager $manager) public function loadExpectedPeople(ObjectManager $manager)
{ {
echo "loading expected people...\n"; echo "loading expected people...\n";
foreach ($this->peoples as $person) { foreach ($this->peoples as $person) {
$this->addAPerson($this->fillWithDefault($person), $manager); $this->addAPerson($this->fillWithDefault($person), $manager);
} }
} }
public function loadRandPeople(ObjectManager $manager) public function loadRandPeople(ObjectManager $manager)
{ {
echo "loading rand people...\n"; echo "loading rand people...\n";
$this->prepare(); $this->prepare();
$chooseLastNameOrTri = array('tri', 'tri', 'name', 'tri'); $chooseLastNameOrTri = array('tri', 'tri', 'name', 'tri');
$i = 0; $i = 0;
do { do {
$i++; $i++;
$sex = $this->genders[array_rand($this->genders)]; $sex = $this->genders[array_rand($this->genders)];
if ($chooseLastNameOrTri[array_rand($chooseLastNameOrTri)] === 'tri' ) { if ($chooseLastNameOrTri[array_rand($chooseLastNameOrTri)] === 'tri' ) {
$length = rand(2, 3); $length = rand(2, 3);
$lastName = ''; $lastName = '';
@@ -117,13 +118,13 @@ class LoadPeople extends AbstractFixture implements OrderedFixtureInterface, Con
} else { } else {
$lastName = $this->lastNames[array_rand($this->lastNames)]; $lastName = $this->lastNames[array_rand($this->lastNames)];
} }
if ($sex === Person::MALE_GENDER) { if ($sex === Person::MALE_GENDER) {
$firstName = $this->firstNamesMale[array_rand($this->firstNamesMale)]; $firstName = $this->firstNamesMale[array_rand($this->firstNamesMale)];
} else { } else {
$firstName = $this->firstNamesFemale[array_rand($this->firstNamesFemale)]; $firstName = $this->firstNamesFemale[array_rand($this->firstNamesFemale)];
} }
// add an address on 80% of the created people // add an address on 80% of the created people
if (rand(0,100) < 80) { if (rand(0,100) < 80) {
$address = $this->getRandomAddress(); $address = $this->getRandomAddress();
@@ -137,7 +138,7 @@ class LoadPeople extends AbstractFixture implements OrderedFixtureInterface, Con
} else { } else {
$address = null; $address = null;
} }
$person = array( $person = array(
'FirstName' => $firstName, 'FirstName' => $firstName,
'LastName' => $lastName, 'LastName' => $lastName,
@@ -147,15 +148,15 @@ class LoadPeople extends AbstractFixture implements OrderedFixtureInterface, Con
'Address' => $address, 'Address' => $address,
'maritalStatus' => $this->maritalStatusRef[array_rand($this->maritalStatusRef)] 'maritalStatus' => $this->maritalStatusRef[array_rand($this->maritalStatusRef)]
); );
$this->addAPerson($this->fillWithDefault($person), $manager); $this->addAPerson($this->fillWithDefault($person), $manager);
} while ($i <= 100); } while ($i <= 100);
} }
/** /**
* fill a person array with default value * fill a person array with default value
* *
* @param string[] $specific * @param string[] $specific
*/ */
private function fillWithDefault(array $specific) private function fillWithDefault(array $specific)
@@ -171,10 +172,10 @@ class LoadPeople extends AbstractFixture implements OrderedFixtureInterface, Con
'Address' => null 'Address' => null
), $specific); ), $specific);
} }
/** /**
* create a new person from array data * create a new person from array data
* *
* @param array $person * @param array $person
* @param ObjectManager $manager * @param ObjectManager $manager
* @throws \Exception * @throws \Exception
@@ -200,35 +201,51 @@ class LoadPeople extends AbstractFixture implements OrderedFixtureInterface, Con
$this->addAccompanyingPeriods($p, $value, $manager); $this->addAccompanyingPeriods($p, $value, $manager);
break; break;
} }
//try to add the data using the setSomething function, //try to add the data using the setSomething function,
// if not possible, fallback to addSomething function // if not possible, fallback to addSomething function
if (method_exists($p, 'set'.$key)) { if (method_exists($p, 'set'.$key)) {
call_user_func(array($p, 'set'.$key), $value); call_user_func(array($p, 'set'.$key), $value);
} elseif (method_exists($p, 'add'.$key)) { } elseif (method_exists($p, 'add'.$key)) {
// if we have a "addSomething", we may have multiple items to add // if we have a "addSomething", we may have multiple items to add
// so, we set the value in an array if it is not an array, and // so, we set the value in an array if it is not an array, and
// will call the function addSomething multiple times // will call the function addSomething multiple times
if (!is_array($value)) { if (!is_array($value)) {
$value = array($value); $value = array($value);
} }
foreach($value as $v) { foreach($value as $v) {
if ($v !== NULL) { if ($v !== NULL) {
call_user_func(array($p, 'add'.$key), $v); call_user_func(array($p, 'add'.$key), $v);
} }
} }
} }
} }
$manager->persist($p); $manager->persist($p);
echo "add person'".$p->__toString()."'\n"; echo "add person'".$p->__toString()."'\n";
} }
/** /**
* Creata a random address * 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 address
*
* @return Address * @return Address
*/ */
private function getRandomAddress() private function getRandomAddress()
@@ -238,13 +255,16 @@ class LoadPeople extends AbstractFixture implements OrderedFixtureInterface, Con
->setStreetAddress2( ->setStreetAddress2(
rand(0,9) > 5 ? $this->faker->streetAddress : '' rand(0,9) > 5 ? $this->faker->streetAddress : ''
) )
->setPoint(
rand(0,9) > 5 ? $this->getRandomPoint() : NULL
)
->setPostcode($this->getReference( ->setPostcode($this->getReference(
LoadPostalCodes::$refs[array_rand(LoadPostalCodes::$refs)] LoadPostalCodes::$refs[array_rand(LoadPostalCodes::$refs)]
)) ))
->setValidFrom($this->faker->dateTimeBetween('-5 years')) ->setValidFrom($this->faker->dateTimeBetween('-5 years'))
; ;
} }
private function getCountry($countryCode) private function getCountry($countryCode)
{ {
if ($countryCode === NULL) { if ($countryCode === NULL) {
@@ -257,30 +277,30 @@ class LoadPeople extends AbstractFixture implements OrderedFixtureInterface, Con
private $maritalStatusRef = ['ms_single', 'ms_married', 'ms_widow', 'ms_separat', private $maritalStatusRef = ['ms_single', 'ms_married', 'ms_widow', 'ms_separat',
'ms_divorce', 'ms_legalco', 'ms_unknown']; 'ms_divorce', 'ms_legalco', 'ms_unknown'];
private $firstNamesMale = array("Jean", "Mohamed", "Alfred", "Robert", "Justin", "Brian", private $firstNamesMale = array("Jean", "Mohamed", "Alfred", "Robert", "Justin", "Brian",
"Compère", "Jean-de-Dieu", "Charles", "Pierre", "Luc", "Mathieu", "Alain", "Etienne", "Eric", "Compère", "Jean-de-Dieu", "Charles", "Pierre", "Luc", "Mathieu", "Alain", "Etienne", "Eric",
"Corentin", "Gaston", "Spirou", "Fantasio", "Mahmadou", "Mohamidou", "Vursuv", "Youssef" ); "Corentin", "Gaston", "Spirou", "Fantasio", "Mahmadou", "Mohamidou", "Vursuv", "Youssef" );
private $firstNamesFemale = array("Svedana", "Sevlatina", "Irène", "Marcelle", private $firstNamesFemale = array("Svedana", "Sevlatina", "Irène", "Marcelle",
"Corentine", "Alfonsine", "Caroline", "Solange", "Gostine", "Fatoumata", "Nicole", "Corentine", "Alfonsine", "Caroline", "Solange", "Gostine", "Fatoumata", "Nicole",
"Groseille", "Chana", "Oxana", "Ivana", "Julie", "Tina", "Adèle" ); "Groseille", "Chana", "Oxana", "Ivana", "Julie", "Tina", "Adèle" );
private $lastNames = array("Diallo", "Bah", "Gaillot", "Martin"); private $lastNames = array("Diallo", "Bah", "Gaillot", "Martin");
private $lastNamesTrigrams = array("fas", "tré", "hu", 'blart', 'van', 'der', 'lin', 'den', private $lastNamesTrigrams = array("fas", "tré", "hu", 'blart', 'van', 'der', 'lin', 'den',
'ta', 'mi', 'net', 'gna', 'bol', 'sac', 'ré', 'jo', 'du', 'pont', 'cas', 'tor', 'rob', 'al', 'ta', 'mi', 'net', 'gna', 'bol', 'sac', 'ré', 'jo', 'du', 'pont', 'cas', 'tor', 'rob', 'al',
'ma', 'gone', 'car',"fu", "ka", "lot", "no", "va", "du", "bu", "su", "jau", "tte", 'sir', 'ma', 'gone', 'car',"fu", "ka", "lot", "no", "va", "du", "bu", "su", "jau", "tte", 'sir',
"lo", 'to', "cho", "car", 'mo','zu', 'qi', 'mu'); "lo", 'to', "cho", "car", 'mo','zu', 'qi', 'mu');
private $genders = array(Person::MALE_GENDER, Person::FEMALE_GENDER); private $genders = array(Person::MALE_GENDER, Person::FEMALE_GENDER);
private $years = array(); private $years = array();
private $month = array(); private $month = array();
private $day = array(); private $day = array();
private $peoples = array( private $peoples = array(
array( array(
'LastName' => "Depardieu", 'LastName' => "Depardieu",
@@ -362,21 +382,21 @@ class LoadPeople extends AbstractFixture implements OrderedFixtureInterface, Con
'maritalStatus' => 'ms_legalco' 'maritalStatus' => 'ms_legalco'
), ),
); );
private function addAccompanyingPeriods(Person $person, array $periods, ObjectManager $manager) private function addAccompanyingPeriods(Person $person, array $periods, ObjectManager $manager)
{ {
foreach ($periods as $period) { foreach ($periods as $period) {
echo "adding new past Accompanying Period..\n"; echo "adding new past Accompanying Period..\n";
/** @var AccompanyingPeriod $accompanyingPeriod */ /** @var AccompanyingPeriod $accompanyingPeriod */
$accompanyingPeriod = new AccompanyingPeriod(new \DateTime($period['from'])); $accompanyingPeriod = new AccompanyingPeriod(new \DateTime($period['from']));
$accompanyingPeriod $accompanyingPeriod
->setClosingDate(new \DateTime($period['to'])) ->setClosingDate(new \DateTime($period['to']))
->setRemark($period['remark']) ->setRemark($period['remark'])
; ;
$person->addAccompanyingPeriod($accompanyingPeriod); $person->addAccompanyingPeriod($accompanyingPeriod);
} }
} }

View File

@@ -25,6 +25,7 @@ use Doctrine\Persistence\ObjectManager;
use Chill\MainBundle\DataFixtures\ORM\LoadPermissionsGroup; use Chill\MainBundle\DataFixtures\ORM\LoadPermissionsGroup;
use Chill\MainBundle\Entity\RoleScope; use Chill\MainBundle\Entity\RoleScope;
use Chill\PersonBundle\Security\Authorization\PersonVoter; use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter;
/** /**
* Add a role CHILL_PERSON_UPDATE & CHILL_PERSON_CREATE for all groups except administrative, * Add a role CHILL_PERSON_UPDATE & CHILL_PERSON_CREATE for all groups except administrative,
@@ -44,6 +45,7 @@ class LoadPersonACL extends AbstractFixture implements OrderedFixtureInterface
{ {
foreach (LoadPermissionsGroup::$refs as $permissionsGroupRef) { foreach (LoadPermissionsGroup::$refs as $permissionsGroupRef) {
$permissionsGroup = $this->getReference($permissionsGroupRef); $permissionsGroup = $this->getReference($permissionsGroupRef);
$scopeSocial = $this->getReference('scope_social');
//create permission group //create permission group
switch ($permissionsGroup->getName()) { switch ($permissionsGroup->getName()) {
@@ -51,6 +53,12 @@ class LoadPersonACL extends AbstractFixture implements OrderedFixtureInterface
case 'direction': case 'direction':
printf("Adding CHILL_PERSON_UPDATE & CHILL_PERSON_CREATE to %s permission group \n", $permissionsGroup->getName()); printf("Adding CHILL_PERSON_UPDATE & CHILL_PERSON_CREATE to %s permission group \n", $permissionsGroup->getName());
$permissionsGroup->addRoleScope(
(new RoleScope())
->setRole(AccompanyingPeriodVoter::SEE)
->setScope($scopeSocial)
);
$roleScopeUpdate = (new RoleScope()) $roleScopeUpdate = (new RoleScope())
->setRole('CHILL_PERSON_UPDATE') ->setRole('CHILL_PERSON_UPDATE')
->setScope(null); ->setScope(null);

View File

@@ -28,6 +28,7 @@ use Chill\MainBundle\DependencyInjection\MissingBundleException;
use Chill\PersonBundle\Security\Authorization\PersonVoter; use Chill\PersonBundle\Security\Authorization\PersonVoter;
use Chill\MainBundle\Security\Authorization\ChillExportVoter; use Chill\MainBundle\Security\Authorization\ChillExportVoter;
use Chill\PersonBundle\Doctrine\DQL\AddressPart; use Chill\PersonBundle\Doctrine\DQL\AddressPart;
use Symfony\Component\HttpFoundation\Request;
/** /**
* Class ChillPersonExtension * Class ChillPersonExtension
@@ -60,16 +61,23 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
$container->setParameter('chill_person.allow_multiple_simultaneous_accompanying_periods', $container->setParameter('chill_person.allow_multiple_simultaneous_accompanying_periods',
$config['allow_multiple_simultaneous_accompanying_periods']); $config['allow_multiple_simultaneous_accompanying_periods']);
$loader = new Loader\YamlFileLoader($container, new FileLocator(dirname(__DIR__, 2).'/config')); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../config'));
$loader->load('services.yaml'); $loader->load('services.yaml');
$loader->load('services/widgets.yaml'); $loader->load('services/widgets.yaml');
$loader->load('services/exports.yaml'); $loader->load('services/exports.yaml');
$loader->load('services/fixtures.yaml'); $loader->load('services/fixtures.yaml');
$loader->load('services/controller.yaml');
$loader->load('services/search.yaml'); $loader->load('services/search.yaml');
$loader->load('services/menu.yaml');
$loader->load('services/privacyEvent.yaml');
$loader->load('services/command.yaml'); $loader->load('services/command.yaml');
$loader->load('services/actions.yaml');
$loader->load('services/form.yaml'); $loader->load('services/form.yaml');
$loader->load('services/repository.yaml');
$loader->load('services/templating.yaml');
$loader->load('services/alt_names.yaml'); $loader->load('services/alt_names.yaml');
$loader->load('services/serializer.yaml'); $loader->load('services/serializer.yaml');
$loader->load('services/security.yaml');
// load service advanced search only if configure // load service advanced search only if configure
if ($config['search']['search_by_phone'] != 'never') { if ($config['search']['search_by_phone'] != 'never') {
@@ -179,7 +187,7 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
$container->prependExtensionConfig('chill_main', array( $container->prependExtensionConfig('chill_main', array(
'routing' => array( 'routing' => array(
'resources' => array( 'resources' => array(
dirname(__DIR__, 2) . '/config/routes.yaml' '@ChillPersonBundle/config/routes.yaml'
) )
) )
)); ));
@@ -301,6 +309,55 @@ class ChillPersonExtension extends Extension implements PrependExtensionInterfac
'template' => '@ChillPerson/MaritalStatus/edit.html.twig', 'template' => '@ChillPerson/MaritalStatus/edit.html.twig',
] ]
] ]
],
],
'apis' => [
[
'class' => \Chill\PersonBundle\Entity\AccompanyingPeriod::class,
'name' => 'accompanying_course',
'base_path' => '/api/1.0/person/accompanying-course',
'controller' => \Chill\PersonBundle\Controller\AccompanyingCourseApiController::class,
'actions' => [
'_entity' => [
'roles' => [
Request::METHOD_GET => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE
]
],
'participation' => [
'methods' => [
Request::METHOD_POST => true,
Request::METHOD_DELETE => true,
Request::METHOD_GET => false,
Request::METHOD_HEAD => false,
],
'roles' => [
Request::METHOD_POST => \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE,
Request::METHOD_DELETE=> \Chill\PersonBundle\Security\Authorization\AccompanyingPeriodVoter::SEE
]
]
]
],
[
'class' => \Chill\PersonBundle\Entity\AccompanyingPeriod\Origin::class,
'name' => 'accompanying_period_origin',
'base_path' => '/api/1.0/person/accompanying-period/origin',
'controller' => \Chill\PersonBundle\Controller\OpeningApiController::class,
'base_role' => 'ROLE_USER',
'actions' => [
'_index' => [
'methods' => [
Request::METHOD_GET => true,
Request::METHOD_HEAD => true
],
],
'_entity' => [
'methods' => [
Request::METHOD_GET => true,
Request::METHOD_HEAD => true
]
],
]
] ]
] ]
]); ]);

View File

@@ -37,43 +37,43 @@ use Chill\MainBundle\Entity\User;
/** /**
* AccompanyingPeriod Class * AccompanyingPeriod Class
* *
* @ORM\Entity * @ORM\Entity(repositoryClass="Chill\PersonBundle\Repository\AccompanyingPeriodRepository")
* @ORM\Table(name="chill_person_accompanying_period") * @ORM\Table(name="chill_person_accompanying_period")
*/ */
class AccompanyingPeriod class AccompanyingPeriod
{ {
/** /**
* Mark an accompanying period as "occasional" * Mark an accompanying period as "occasional"
* *
* used in INTENSITY * used in INTENSITY
*/ */
public const INTENSITY_OCCASIONAL = 'occasional'; public const INTENSITY_OCCASIONAL = 'occasional';
/** /**
* Mark an accompanying period as "regular" * Mark an accompanying period as "regular"
* *
* used in INTENSITY * used in INTENSITY
*/ */
public const INTENSITY_REGULAR = 'regular'; public const INTENSITY_REGULAR = 'regular';
public const INTENSITIES = [self::INTENSITY_OCCASIONAL, self::INTENSITY_REGULAR]; public const INTENSITIES = [self::INTENSITY_OCCASIONAL, self::INTENSITY_REGULAR];
/** /**
* Mark an accompanying period as "draft". * Mark an accompanying period as "draft".
* *
* This means that the accompanying period is not yet * This means that the accompanying period is not yet
* confirmed by the creator * confirmed by the creator
*/ */
public const STEP_DRAFT = 'DRAFT'; public const STEP_DRAFT = 'DRAFT';
/** /**
* Mark an accompanying period as "confirmed". * Mark an accompanying period as "confirmed".
* *
* This means that the accompanying period **is** * This means that the accompanying period **is**
* confirmed by the creator * confirmed by the creator
*/ */
public const STEP_CONFIRMED = 'CONFIRMED'; public const STEP_CONFIRMED = 'CONFIRMED';
/** /**
* @var integer * @var integer
* *
@@ -118,7 +118,7 @@ class AccompanyingPeriod
* *
* @ORM\OneToMany(targetEntity=AccompanyingPeriodParticipation::class, * @ORM\OneToMany(targetEntity=AccompanyingPeriodParticipation::class,
* mappedBy="accompanyingPeriod", * mappedBy="accompanyingPeriod",
* cascade={"persist", "remove", "merge", "detach"}) * cascade={"persist", "refresh", "remove", "merge", "detach"})
*/ */
private $participations; private $participations;
@@ -148,7 +148,7 @@ class AccompanyingPeriod
* @ORM\Column(type="string", length=32, nullable=true) * @ORM\Column(type="string", length=32, nullable=true)
*/ */
private $step = self::STEP_DRAFT; private $step = self::STEP_DRAFT;
/** /**
* @ORM\ManyToOne(targetEntity=Origin::class) * @ORM\ManyToOne(targetEntity=Origin::class)
* @ORM\JoinColumn(nullable=true) * @ORM\JoinColumn(nullable=true)
@@ -344,50 +344,68 @@ class AccompanyingPeriod
} }
/** /**
* This private function scan Participations Collection, * Get the participation containing a person
* searching for a given Person
*/ */
private function participationsContainsPerson(Person $person): ?AccompanyingPeriodParticipation public function getParticipationsContainsPerson(Person $person): Collection
{ {
foreach ($this->participations as $participation) { return $this->getParticipations($person)->filter(
/** @var AccompanyingPeriodParticipation $participation */ function(AccompanyingPeriodParticipation $participation) use ($person) {
if ($person === $participation->getPerson()) { if ($person === $participation->getPerson()) {
return $participation; return $participation;
}} }
});
return null;
} }
/** /**
* This public function is the same but return only true or false * Get the opened participation containing a person
*
* "Open" means that the closed date is NULL
*/
public function getOpenParticipationContainsPerson(Person $person): ?AccompanyingPeriodParticipation
{
$collection = $this->getParticipationsContainsPerson($person)->filter(
function(AccompanyingPeriodParticipation $participation) use ($person) {
if (NULL === $participation->getEndDate()) {
return $participation;
}
});
return $collection->count() > 0 ? $collection->first() : NULL;
}
/**
* Return true if the accompanying period contains a person.
*
* **Note**: this participation can be opened or not.
*/ */
public function containsPerson(Person $person): bool public function containsPerson(Person $person): bool
{ {
return ($this->participationsContainsPerson($person) === null) ? false : true; return $this->getParticipationsContainsPerson($person)->count() > 0;
} }
/** /**
* Add Person * Add Person
*/ */
public function addPerson(Person $person = null): self public function addPerson(Person $person = null): AccompanyingPeriodParticipation
{ {
$participation = new AccompanyingPeriodParticipation($this, $person); $participation = new AccompanyingPeriodParticipation($this, $person);
$this->participations[] = $participation; $this->participations[] = $participation;
return $this; return $participation;
} }
/** /**
* Remove Person * Remove Person
*/ */
public function removePerson(Person $person): void public function removePerson(Person $person): ?AccompanyingPeriodParticipation
{ {
$participation = $this->participationsContainsPerson($person); $participation = $this->getOpenParticipationContainsPerson($person);
if (! null === $participation) { if ($participation instanceof AccompanyingPeriodParticipation) {
$participation->setEndDate(new \DateTimeImmutable('now')); $participation->setEndDate(new \DateTimeImmutable('now'));
$this->participations->removeElement($participation);
} }
return $participation;
} }

View File

@@ -4,6 +4,7 @@ namespace Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\SocialWork\Result; use Chill\PersonBundle\Entity\SocialWork\Result;
use Chill\PersonBundle\Entity\SocialWork\SocialAction; use Chill\PersonBundle\Entity\SocialWork\SocialAction;
use Chill\PersonBundle\Repository\AccompanyingPeriod\AccompanyingPeriodWorkRepository;
use Chill\MainBundle\Entity\User; use Chill\MainBundle\Entity\User;
use Chill\PersonBundle\Entity\AccompanyingPeriod; use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\ThirdPartyBundle\Entity\ThirdParty; use Chill\ThirdPartyBundle\Entity\ThirdParty;
@@ -12,7 +13,7 @@ use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
/** /**
* @ORM\Entity * @ORM\Entity(repositoryClass=AccompanyingPeriodWorkRepository::class)
* @ORM\Table(name="chill_person_accompanying_period_work") * @ORM\Table(name="chill_person_accompanying_period_work")
*/ */
class AccompanyingPeriodWork class AccompanyingPeriodWork

View File

@@ -4,12 +4,13 @@ namespace Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\SocialWork\Goal; use Chill\PersonBundle\Entity\SocialWork\Goal;
use Chill\PersonBundle\Entity\SocialWork\Result; use Chill\PersonBundle\Entity\SocialWork\Result;
use Chill\PersonBundle\Repository\AccompanyingPeriod\AccompanyingPeriodWorkGoalRepository;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
/** /**
* @ORM\Entity * @ORM\Entity(repositoryClass=AccompanyingPeriodWorkGoalRepository::class)
* @ORM\Table(name="chill_person_accompanying_period_work_goal") * @ORM\Table(name="chill_person_accompanying_period_work_goal")
*/ */
class AccompanyingPeriodWorkGoal class AccompanyingPeriodWorkGoal

View File

@@ -29,7 +29,8 @@ use Doctrine\Common\Collections\ArrayCollection;
/** /**
* ClosingMotive give an explanation why we closed the Accompanying period * ClosingMotive give an explanation why we closed the Accompanying period
* *
* @ORM\Entity * @ORM\Entity(
* repositoryClass="Chill\PersonBundle\Repository\AccompanyingPeriod\ClosingMotiveRepository")
* @ORM\Table(name="chill_person_accompanying_period_closingmotive") * @ORM\Table(name="chill_person_accompanying_period_closingmotive")
*/ */
class ClosingMotive class ClosingMotive
@@ -49,14 +50,14 @@ class ClosingMotive
* @ORM\Column(type="json") * @ORM\Column(type="json")
*/ */
private $name; private $name;
/** /**
* @var boolean * @var boolean
* *
* @ORM\Column(type="boolean") * @ORM\Column(type="boolean")
*/ */
private $active = true; private $active = true;
/** /**
* @var self * @var self
* *
@@ -65,7 +66,7 @@ class ClosingMotive
* inversedBy="children") * inversedBy="children")
*/ */
private $parent = null; private $parent = null;
/** /**
* Child Accompanying periods * Child Accompanying periods
* @var Collection * @var Collection
@@ -75,15 +76,15 @@ class ClosingMotive
* mappedBy="parent") * mappedBy="parent")
*/ */
private $children; private $children;
/** /**
* @var float * @var float
* *
* @ORM\Column(type="float") * @ORM\Column(type="float")
*/ */
private $ordering = 0.0; private $ordering = 0.0;
/** /**
* ClosingMotive constructor. * ClosingMotive constructor.
*/ */
@@ -91,7 +92,7 @@ class ClosingMotive
{ {
$this->children = new ArrayCollection(); $this->children = new ArrayCollection();
} }
/** /**
* Get id * Get id
* *
@@ -125,7 +126,7 @@ class ClosingMotive
{ {
return $this->name; return $this->name;
} }
/** /**
* @return bool * @return bool
*/ */
@@ -133,7 +134,7 @@ class ClosingMotive
{ {
return $this->active; return $this->active;
} }
/** /**
* @param bool $active * @param bool $active
* @return $this * @return $this
@@ -141,16 +142,16 @@ class ClosingMotive
public function setActive(bool $active) public function setActive(bool $active)
{ {
$this->active = $active; $this->active = $active;
if ($this->active === FALSE) { if ($this->active === FALSE) {
foreach ($this->getChildren() as $child) { foreach ($this->getChildren() as $child) {
$child->setActive(FALSE); $child->setActive(FALSE);
} }
} }
return $this; return $this;
} }
/** /**
* @return ClosingMotive * @return ClosingMotive
*/ */
@@ -158,7 +159,7 @@ class ClosingMotive
{ {
return $this->parent; return $this->parent;
} }
/** /**
* @return Collection * @return Collection
*/ */
@@ -166,7 +167,7 @@ class ClosingMotive
{ {
return $this->children; return $this->children;
} }
/** /**
* @param ClosingMotive|null $parent * @param ClosingMotive|null $parent
* @return ClosingMotive * @return ClosingMotive
@@ -174,14 +175,14 @@ class ClosingMotive
public function setParent(?ClosingMotive $parent): ClosingMotive public function setParent(?ClosingMotive $parent): ClosingMotive
{ {
$this->parent = $parent; $this->parent = $parent;
if (NULL !== $parent) { if (NULL !== $parent) {
//$parent->addChildren($this); //$parent->addChildren($this);
} }
return $this; return $this;
} }
/** /**
* @param Collection $children * @param Collection $children
* @return ClosingMotive * @return ClosingMotive
@@ -189,10 +190,10 @@ class ClosingMotive
public function setChildren(Collection $children): ClosingMotive public function setChildren(Collection $children): ClosingMotive
{ {
$this->children = $children; $this->children = $children;
return $this; return $this;
} }
/** /**
* @param ClosingMotive $child * @param ClosingMotive $child
* @return ClosingMotive * @return ClosingMotive
@@ -202,13 +203,13 @@ class ClosingMotive
if ($this->children->contains($child)) { if ($this->children->contains($child)) {
return $this; return $this;
} }
$this->children->add($child); $this->children->add($child);
$child->setParent($this); $child->setParent($this);
return $this; return $this;
} }
/** /**
* @param ClosingMotive $child * @param ClosingMotive $child
* @return ClosingMotive * @return ClosingMotive
@@ -218,10 +219,10 @@ class ClosingMotive
if ($this->children->removeElement($child)) { if ($this->children->removeElement($child)) {
$child->setParent(null); $child->setParent(null);
} }
return $this; return $this;
} }
/** /**
* @return float * @return float
*/ */
@@ -229,7 +230,7 @@ class ClosingMotive
{ {
return $this->ordering; return $this->ordering;
} }
/** /**
* @param float $ordering * @param float $ordering
* @return $this * @return $this
@@ -237,10 +238,10 @@ class ClosingMotive
public function setOrdering(float $ordering) public function setOrdering(float $ordering)
{ {
$this->ordering = $ordering; $this->ordering = $ordering;
return $this; return $this;
} }
/** /**
* @return bool * @return bool
*/ */
@@ -248,7 +249,7 @@ class ClosingMotive
{ {
return $this->parent !== null; return $this->parent !== null;
} }
/** /**
* @return bool * @return bool
*/ */
@@ -256,7 +257,7 @@ class ClosingMotive
{ {
return $this->children->count() > 0; return $this->children->count() > 0;
} }
/** /**
* @return bool * @return bool
*/ */
@@ -264,7 +265,7 @@ class ClosingMotive
{ {
return $this->children->count() === 0; return $this->children->count() === 0;
} }
/** /**
* @return bool * @return bool
*/ */

View File

@@ -22,12 +22,13 @@
namespace Chill\PersonBundle\Entity\AccompanyingPeriod; namespace Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Repository\AccompanyingPeriod\CommentRepository;
use Chill\MainBundle\Entity\User; use Chill\MainBundle\Entity\User;
use Chill\PersonBundle\Entity\AccompanyingPeriod; use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
/** /**
* @ORM\Entity * @ORM\Entity(repositoryClass=CommentRepository::class)
* @ORM\Table(name="chill_person_accompanying_period_comment") * @ORM\Table(name="chill_person_accompanying_period_comment")
*/ */
class Comment class Comment

View File

@@ -22,10 +22,11 @@
namespace Chill\PersonBundle\Entity\AccompanyingPeriod; namespace Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Repository\AccompanyingPeriod\OriginRepository;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
/** /**
* @ORM\Entity * @ORM\Entity(repositoryClass=OriginRepository::class)
* @ORM\Table(name="chill_person_accompanying_period_origin") * @ORM\Table(name="chill_person_accompanying_period_origin")
*/ */
class Origin class Origin
@@ -52,7 +53,7 @@ class Origin
return $this->id; return $this->id;
} }
public function getLabel(): ?string public function getLabel()
{ {
return $this->label; return $this->label;
} }

View File

@@ -22,6 +22,7 @@
namespace Chill\PersonBundle\Entity\AccompanyingPeriod; namespace Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Repository\AccompanyingPeriod\ResourceRepository;
use Chill\PersonBundle\Entity\AccompanyingPeriod; use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\AccompanyingPeriod\Comment; use Chill\PersonBundle\Entity\AccompanyingPeriod\Comment;
use Chill\PersonBundle\Entity\Person; use Chill\PersonBundle\Entity\Person;
@@ -29,7 +30,7 @@ use Chill\ThirdPartyBundle\Entity\ThirdParty;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
/** /**
* @ORM\Entity * @ORM\Entity(repositoryClass=ResourceRepository::class)
* @ORM\Table(name="chill_person_accompanying_period_resource") * @ORM\Table(name="chill_person_accompanying_period_resource")
*/ */
class Resource class Resource
@@ -120,7 +121,7 @@ class Resource
return $this; return $this;
} }
/** /**
* @return Person|ThirdParty * @return Person|ThirdParty
*/ */

View File

@@ -22,6 +22,7 @@
namespace Chill\PersonBundle\Entity; namespace Chill\PersonBundle\Entity;
use Chill\PersonBundle\Repository\AccompanyingPeriodParticipationRepository;
use Chill\PersonBundle\Entity\AccompanyingPeriod; use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person; use Chill\PersonBundle\Entity\Person;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
@@ -30,7 +31,7 @@ use Doctrine\ORM\Mapping as ORM;
* AccompanyingPeriodParticipation Class * AccompanyingPeriodParticipation Class
* *
* @package Chill\PersonBundle\Entity * @package Chill\PersonBundle\Entity
* @ORM\Entity * @ORM\Entity(repositoryClass=AccompanyingPeriodParticipationRepository::class)
* @ORM\Table(name="chill_person_accompanying_period_participation") * @ORM\Table(name="chill_person_accompanying_period_participation")
*/ */
class AccompanyingPeriodParticipation class AccompanyingPeriodParticipation
@@ -41,83 +42,83 @@ class AccompanyingPeriodParticipation
* @ORM\Column(type="integer") * @ORM\Column(type="integer")
*/ */
private $id; private $id;
/** /**
* @ORM\ManyToOne(targetEntity=Person::class, inversedBy="accompanyingPeriodParticipations") * @ORM\ManyToOne(targetEntity=Person::class, inversedBy="accompanyingPeriodParticipations")
* @ORM\JoinColumn(name="person_id", referencedColumnName="id", nullable=false) * @ORM\JoinColumn(name="person_id", referencedColumnName="id", nullable=false)
*/ */
private $person; private $person;
/** /**
* @ORM\ManyToOne(targetEntity=AccompanyingPeriod::class, inversedBy="participations", cascade={"persist"}) * @ORM\ManyToOne(targetEntity=AccompanyingPeriod::class, inversedBy="participations", cascade={"persist"})
* @ORM\JoinColumn(name="accompanyingperiod_id", referencedColumnName="id", nullable=false) * @ORM\JoinColumn(name="accompanyingperiod_id", referencedColumnName="id", nullable=false)
*/ */
private $accompanyingPeriod; private $accompanyingPeriod;
/** /**
* @ORM\Column(type="date", nullable=false) * @ORM\Column(type="date", nullable=false)
*/ */
private $startDate; private $startDate;
/** /**
* @ORM\Column(type="date", nullable=true) * @ORM\Column(type="date", nullable=true)
*/ */
private $endDate = null; private $endDate = null;
public function __construct(AccompanyingPeriod $accompanyingPeriod, Person $person) public function __construct(AccompanyingPeriod $accompanyingPeriod, Person $person)
{ {
$this->startDate = new \DateTimeImmutable('now'); $this->startDate = new \DateTimeImmutable('now');
$this->accompanyingPeriod = $accompanyingPeriod; $this->accompanyingPeriod = $accompanyingPeriod;
$this->person = $person; $this->person = $person;
} }
public function getId(): ?int public function getId(): ?int
{ {
return $this->id; return $this->id;
} }
public function getPerson(): ?Person public function getPerson(): ?Person
{ {
return $this->person; return $this->person;
} }
public function setPerson(?Person $person): self public function setPerson(?Person $person): self
{ {
$this->person = $person; $this->person = $person;
return $this; return $this;
} }
public function getAccompanyingPeriod(): ?AccompanyingPeriod public function getAccompanyingPeriod(): ?AccompanyingPeriod
{ {
return $this->accompanyingPeriod; return $this->accompanyingPeriod;
} }
public function setAccompanyingPeriod(?AccompanyingPeriod $accompanyingPeriod): self public function setAccompanyingPeriod(?AccompanyingPeriod $accompanyingPeriod): self
{ {
$this->accompanyingPeriod = $accompanyingPeriod; $this->accompanyingPeriod = $accompanyingPeriod;
return $this; return $this;
} }
public function getStartDate(): ?\DateTimeInterface public function getStartDate(): ?\DateTimeInterface
{ {
return $this->startDate; return $this->startDate;
} }
/* /*
* public function setStartDate(\DateTimeInterface $startDate): self { $this->startDate = $startDate; return $this; } * public function setStartDate(\DateTimeInterface $startDate): self { $this->startDate = $startDate; return $this; }
*/ */
public function getEndDate(): ?\DateTimeInterface public function getEndDate(): ?\DateTimeInterface
{ {
return $this->endDate; return $this->endDate;
} }
public function setEndDate(?\DateTimeInterface $endDate): self public function setEndDate(?\DateTimeInterface $endDate): self
{ {
$this->endDate = $endDate; $this->endDate = $endDate;
return $this; return $this;
} }
} }

Some files were not shown because too many files have changed in this diff Show More